Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/exe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,24 @@ export function startAgentCommand(agentName: string, connection: ExeConnection,
`if [ -n \"$existing_status\" ]; then case \"$existing_status\" in idle|done) ${herdrBinary(connection)} agent prompt ${shellAtom(name)} ${shellAtom(resetPrompt)} ;; *) echo \"Factorize cannot reuse active Herdr agent ${name} (status: $existing_status)\" >&2; exit 1 ;; esac; else workspace=$(${herdrBinary(connection)} workspace create --cwd ${shellAtom(connection.cwd)} --label ${shellAtom(workspaceName)} --no-focus) && pane=$(printf '%s' \"$workspace\" | jq -r '.result.root_pane.pane_id // .pane_id // .paneId') && ${herdrBinary(connection)} agent start ${shellAtom(name)} --kind ${shellAtom(connection.agentKind)} --pane \"$pane\"${agentCommand(connection)}; fi`,
`prompt=$(printf '%s' ${shellAtom(encodedPrompt)} | base64 -d)`,
`${herdrBinary(connection)} agent prompt ${shellAtom(name)} \"$prompt\"`,
`${herdrBinary(connection)} agent get ${shellAtom(name)}`,
].join(" && ");
}

export function agentListCommand(connection: ExeConnection): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent list`; }
export function paneGetCommand(connection: ExeConnection, paneId: string): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} pane get ${shellAtom(paneId)}`; }
export function paneProcessInfoCommand(connection: ExeConnection, paneId: string): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} pane process-info ${shellAtom(paneId)}`; }
export function renameAgentCommand(connection: ExeConnection, currentName: string, expectedName: string): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent rename ${shellAtom(currentName)} ${shellAtom(expectedName)} && ${herdrBinary(connection)} agent get ${shellAtom(expectedName)}`; }
export function startAgentInPaneCommand(agentName: string, connection: ExeConnection, paneId: string): string { return `${herdrPrefix(connection)} && cd ${shellAtom(connection.cwd)} && ${herdrBinary(connection)} agent start ${shellAtom(agentName)} --kind ${shellAtom(connection.agentKind)} --pane ${shellAtom(paneId)}${agentCommand(connection)} && ${herdrBinary(connection)} agent get ${shellAtom(agentName)}`; }

/** Stop only the foreground process group observed in the exact persisted pane.
* Every signal is preceded by a fresh identity read, preventing stale-PID races. */
export function replaceForegroundCommand(agentName: string, connection: ExeConnection, paneId: string): string {
const herdr = herdrBinary(connection), pane = shellAtom(paneId);
const fields = `jq -er --arg pane ${pane} --arg cwd ${shellAtom(connection.cwd)} '[.result.pane_id // .pane_id // .result.pane.pane_id, .result.foreground.pid // .result.pid // .pid, .result.foreground.process_group // .result.foreground.pgid // .result.process_group // .result.pgid // .pgid, .result.foreground.cwd // .result.cwd // .cwd] | select(.[0] == $pane and .[1] > 1 and .[2] > 1 and .[3] == $cwd) | @tsv'`;
return [herdrPrefix(connection), `first=$(${herdr} pane process-info ${pane} | ${fields})`, `first_pid=$(printf '%s' "$first" | cut -f2)`, `first_pgid=$(printf '%s' "$first" | cut -f3)`, `kill -INT -- "-$first_pgid"`, `i=0; while [ "$i" -lt 10 ] && kill -0 -- "-$first_pgid" 2>/dev/null; do i=$((i+1)); sleep 1; done`, `if kill -0 -- "-$first_pgid" 2>/dev/null; then second=$(${herdr} pane process-info ${pane} | ${fields}) && second_pid=$(printf '%s' "$second" | cut -f2) && second_pgid=$(printf '%s' "$second" | cut -f3) && [ "$second_pid" = "$first_pid" ] && [ "$second_pgid" = "$first_pgid" ] && kill -TERM -- "-$first_pgid"; fi`, `i=0; while [ "$i" -lt 10 ] && kill -0 -- "-$first_pgid" 2>/dev/null; do i=$((i+1)); sleep 1; done`, `! kill -0 -- "-$first_pgid" 2>/dev/null`, `cd ${shellAtom(connection.cwd)}`, `${herdr} agent start ${shellAtom(agentName)} --kind ${shellAtom(connection.agentKind)} --pane ${pane}${agentCommand(connection)}`, `${herdr} agent get ${shellAtom(agentName)}`].join(" && ");
}

export function agentStatusCommand(connection: ExeConnection, agentName: string): string {
return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent get ${shellAtom(agentName)}`;
}
Expand Down
15 changes: 15 additions & 0 deletions src/recovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export interface HerdrIdentity { name: string; status: string; kind: string; workspaceId: string; paneId: string; terminalId: string; cwd: string; sessionSource: string; sessionKind: string; sessionValue: string; }
export interface PaneProcess { paneId: string; pid: number; processGroup: number; argv: string[]; executable: string; cwd: string; }
const obj = (value: unknown): Record<string, any> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, any> : {};
const str = (...values: unknown[]) => String(values.find((value) => typeof value === "string" || typeof value === "number") ?? "");
function identity(value: unknown): HerdrIdentity | null {
const wrapper = obj(value), agent = obj(wrapper.agent ?? wrapper), session = obj(agent.session_identity ?? agent.agent_session ?? agent.session), source = obj(session.source);
const result = { name: str(agent.name, agent.agent_name), status: str(agent.agent_status, agent.status, agent.state).toLowerCase(), kind: str(agent.agent_kind, agent.kind), workspaceId: str(agent.workspace_id, obj(agent.workspace).id), paneId: str(agent.pane_id, obj(agent.pane).id), terminalId: str(agent.terminal_id, obj(agent.terminal).id), cwd: str(agent.cwd), sessionSource: typeof session.source === "string" ? session.source : str(agent.session_source), sessionKind: str(session.kind, source.kind, agent.session_kind), sessionValue: str(session.value, session.id, source.value, agent.session_id, agent.session_value) };
return result.name || result.paneId || result.sessionValue ? result : null;
}
export function parseAgent(body: string): HerdrIdentity | null { for (const candidate of [body, ...body.trim().split(/\n/).reverse()]) { try { const parsed = obj(JSON.parse(candidate)); const found = identity(obj(parsed.result).agent ?? parsed.agent ?? parsed.result ?? parsed); if (found) return found; } catch {} } return null; }
export function parseAgentList(body: string): HerdrIdentity[] { try { const parsed = obj(JSON.parse(body)), result = obj(parsed.result); const values = Array.isArray(result.agents) ? result.agents : Array.isArray(parsed.agents) ? parsed.agents : Array.isArray(parsed.result) ? parsed.result : []; return values.map(identity).filter((value): value is HerdrIdentity => value !== null); } catch { return []; } }
export function sameStableSession(saved: Partial<HerdrIdentity>, live: HerdrIdentity): boolean { return Boolean(saved.sessionValue && live.sessionValue && saved.sessionValue === live.sessionValue && (!saved.sessionKind || !live.sessionKind || saved.sessionKind === live.sessionKind)); }
export function matchesLineage(saved: Partial<HerdrIdentity>, live: HerdrIdentity): boolean { return Boolean((saved.terminalId && saved.terminalId === live.terminalId) || (saved.paneId && saved.paneId === live.paneId && (!saved.workspaceId || !live.workspaceId || saved.workspaceId === live.workspaceId))); }
export function safeToAdopt(saved: Partial<HerdrIdentity>, live: HerdrIdentity, claimedSessions: Set<string>): boolean { return matchesLineage(saved, live) && (!saved.kind || saved.kind === live.kind) && (!saved.cwd || saved.cwd === live.cwd) && !claimedSessions.has(live.sessionValue); }
export function parsePaneProcess(body: string): PaneProcess | null { try { const parsed = obj(JSON.parse(body)), result = obj(parsed.result), foreground = obj(result.foreground ?? result.process ?? parsed.foreground ?? parsed); const pane = obj(result.pane); const pid = Number(foreground.pid ?? result.pid), processGroup = Number(foreground.process_group ?? foreground.pgid ?? result.process_group ?? result.pgid); if (!Number.isSafeInteger(pid) || pid <= 1 || !Number.isSafeInteger(processGroup) || processGroup <= 1) return null; return { paneId: str(result.pane_id, pane.pane_id, pane.id, parsed.pane_id), pid, processGroup, argv: Array.isArray(foreground.argv) ? foreground.argv.map(String) : [], executable: str(foreground.executable, foreground.exe), cwd: str(foreground.cwd, result.cwd) }; } catch { return null; } }
Loading