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
38 changes: 23 additions & 15 deletions src/exe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,24 @@ export function shellAtom(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}

export function startAgentCommand(agentName: string, connection: ExeConnection, prompt: string, workspaceName = agentName): string {
export function startAgentCommand(agentName: string, connection: ExeConnection, prompt: string, workspaceName: string, worktreePath: string, lease: string): string {
const encodedPrompt = base64(prompt);
const name = agentName;
const resetPrompt = newContextPrompt(connection.agentKind);
const herdr = herdrBinary(connection);
// Herdr commands are deliberately kept to a fixed allowlist. The sole dynamic payload is base64.
return [
herdrPrefix(connection),
`cd ${shellAtom(connection.cwd)}`,
// A named agent stays live after completing a turn. Reuse an idle/done
// slot instead of trying to start another agent with the same name.
`existing=$(${herdrBinary(connection)} agent get ${shellAtom(name)} 2>/dev/null || true)`,
"existing_status=$(printf '%s' \"$existing\" | jq -r '.result.agent.agent_status // .result.agent.state // empty' 2>/dev/null | tr '[:upper:]' '[:lower:]')",
`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`,
`mkdir -p ${shellAtom(`${connection.cwd.replace(/\/$/, "")}/.factorize-worktrees`)}`,
`test ! -e ${shellAtom(worktreePath)} && git worktree add --detach ${shellAtom(worktreePath)} HEAD`,
`gitdir=$(git -C ${shellAtom(worktreePath)} rev-parse --git-dir)`,
`printf '%s' ${shellAtom(lease)} > "$gitdir/factorize-lease"`,
`workspaces=$(${herdr} workspace list)`,
`workspace_id=$(printf '%s' "$workspaces" | jq -r --arg label ${shellAtom(workspaceName)} '.result.workspaces[]? | select(.label == $label) | .workspace_id' | head -n1)`,
`if [ -z "$workspace_id" ]; then workspace=$(${herdr} workspace create --cwd ${shellAtom(connection.cwd)} --label ${shellAtom(workspaceName)} --no-focus) && workspace_id=$(printf '%s' "$workspace" | jq -er '.result.workspace.workspace_id') && anchor=$(printf '%s' "$workspace" | jq -er '.result.root_pane.pane_id'); else anchor=$(${herdr} pane list --workspace "$workspace_id" | jq -er '.result.panes[0].pane_id'); fi`,
`created=$(${herdr} pane split "$anchor" --direction down --cwd ${shellAtom(worktreePath)} --no-focus)`,
`pane=$(printf '%s' "$created" | jq -er '.result.pane.pane_id')`,
`${herdr} agent start ${shellAtom(name)} --kind ${shellAtom(connection.agentKind)} --pane "$pane"${agentCommand(connection)}`,
`prompt=$(printf '%s' ${shellAtom(encodedPrompt)} | base64 -d)`,
`${herdrBinary(connection)} agent prompt ${shellAtom(name)} \"$prompt\"`,
`${herdrBinary(connection)} agent get ${shellAtom(name)}`,
Expand All @@ -57,15 +62,16 @@ export function startAgentCommand(agentName: string, connection: ExeConnection,
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 validateWorktreeLeaseCommand(connection: ExeConnection, worktreePath: string, lease: string): string { return `${herdrPrefix(connection)} && test "$(git -C ${shellAtom(worktreePath)} rev-parse --show-toplevel)" = ${shellAtom(worktreePath)} && gitdir=$(git -C ${shellAtom(worktreePath)} rev-parse --git-dir) && test "$(cat "$gitdir/factorize-lease")" = ${shellAtom(lease)}`; }
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)}`; }
export function startAgentInPaneCommand(agentName: string, connection: ExeConnection, paneId: string, cwd = connection.cwd): string { return `${herdrPrefix(connection)} && cd ${shellAtom(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 {
export function replaceForegroundCommand(agentName: string, connection: ExeConnection, paneId: string, cwd = connection.cwd): 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(" && ");
const fields = `jq -er --arg pane ${pane} --arg cwd ${shellAtom(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(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 {
Expand All @@ -86,6 +92,12 @@ export function stopAgentCommand(connection: ExeConnection, agentName: string):
return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent stop ${shellAtom(agentName)}`;
}

/** Revalidate terminal, worktree, and lease immediately before closing a pane. */
export function garbageCollectPaneCommand(connection: ExeConnection, paneId: string, terminalId: string, worktreePath: string, lease: string): string {
const herdr = herdrBinary(connection), pane = shellAtom(paneId);
return [herdrPrefix(connection), `pane_json=$(${herdr} pane get ${pane})`, `printf '%s' "$pane_json" | jq -e --arg pane ${pane} --arg terminal ${shellAtom(terminalId)} '(.result.pane // .result) | .pane_id == $pane and .terminal_id == $terminal' >/dev/null`, `test "$(git -C ${shellAtom(worktreePath)} rev-parse --show-toplevel)" = ${shellAtom(worktreePath)}`, `gitdir=$(git -C ${shellAtom(worktreePath)} rev-parse --git-dir)`, `test "$(cat "$gitdir/factorize-lease")" = ${shellAtom(lease)}`, `agent=$(${herdr} agent get ${pane} 2>/dev/null || true)`, `status=$(printf '%s' "$agent" | jq -r '.result.agent.agent_status // .result.agent.state // empty' | tr '[:upper:]' '[:lower:]')`, `case "$status" in ''|idle|done) ;; *) exit 1 ;; esac`, `[ -z "$status" ] || ${herdr} agent stop ${pane}`, `test -z "$(${herdr} agent get ${pane} 2>/dev/null || true)"`, `process=$(${herdr} pane process-info ${pane})`, `printf '%s' "$process" | jq -e '(.result.foreground.executable // .result.process.executable // "") | test("(^|/)(ba|z|fi)?sh$")' >/dev/null`, `${herdr} pane close ${pane}`].join(" && ");
}

export function herdrCheckCommand(connection: ExeConnection): string {
return `${herdrPrefix(connection)} && ${herdrBinary(connection)} --version && ${herdrBinary(connection)} workspace list`;
}
Expand All @@ -104,10 +116,6 @@ function herdrBinary(connection: ExeConnection): string {
return connection.herdrCommand?.trim() || "herdr";
}

function newContextPrompt(agentKind: string): string {
return agentKind === "claude" ? "/clear" : "/new";
}

/** Herdr owns the executable; it forwards these arguments after `--` to it. */
function agentCommand(connection: ExeConnection): string {
const command = connection.agentCommand?.trim() || defaultAgentCommand(connection.agentKind);
Expand Down
4 changes: 4 additions & 0 deletions src/recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ export function parseAgentList(body: string): HerdrIdentity[] { try { const pars
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); }
/** Native sessions and aliases may rotate; terminal + worktree own the pane. */
export function ownsPane(saved: Partial<HerdrIdentity>, live: HerdrIdentity, worktreePath: string): boolean {
return Boolean(saved.terminalId && saved.terminalId === live.terminalId && worktreePath && live.cwd === worktreePath && (!saved.paneId || saved.paneId === live.paneId));
}
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