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
50 changes: 26 additions & 24 deletions src/exe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,50 +19,51 @@ export interface ExeResponse {

/** Calls exe.dev's documented HTTPS SSH-command API. */
export async function exec(connection: ExeConnection, remoteCommand: string): Promise<ExeResponse> {
const requestBody = `ssh ${shellAtom(connection.vmName)} ${shellAtom(remoteCommand)}`;
const marker = `__factorize_exit_${crypto.randomUUID().replaceAll("-", "")}__`;
const wrappedCommand = `( ${remoteCommand} ); factorize_exit=$?; printf '\\n${marker}:%s\\n' "$factorize_exit"; exit "$factorize_exit"`;
const requestBody = `ssh ${shellAtom(connection.vmName)} ${shellAtom(wrappedCommand)}`;
const response = await fetch("https://exe.dev/exec", {
method: "POST",
headers: { Authorization: `Bearer ${connection.apiToken}`, "Content-Type": "text/plain" },
body: requestBody,
});
const body = await response.text();
const exit = response.headers.get("X-Exe-Exit");
return { ok: response.ok, status: response.status, exitCode: exit && /^\d+$/.test(exit) ? Number(exit) : null, body, requestBody };
const rawBody = await response.text();
const sentinel = new RegExp(`(?:\\r?\\n)?${marker}:(\\d+)(?:\\r?\\n)?$`);
const captured = rawBody.match(sentinel);
const headerExit = response.headers.get("X-Exe-Exit");
const exitCode = captured ? Number(captured[1]) : headerExit && /^\d+$/.test(headerExit) ? Number(headerExit) : null;
const body = captured ? rawBody.replace(sentinel, "") : rawBody;
return { ok: response.ok && exitCode === 0, status: response.status, exitCode, body, requestBody };
}

/** Single shell atom; prevents ticket content from becoming syntax in either SSH parser. */
export function shellAtom(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}

export function startAgentCommand(agentName: string, connection: ExeConnection, prompt: string, workspaceName: string, worktreePath: string, lease: string): string {
export function startAgentCommand(agentName: string, connection: ExeConnection, prompt: string, workspaceName: string, runPath: string, lease: string): string {
const encodedPrompt = base64(prompt);
const name = agentName;
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)}`,
`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"`,
`mkdir -p ${shellAtom(`${connection.cwd.replace(/\/$/, "")}/.factorize-runs`)}`,
`if [ ! -e ${shellAtom(runPath)} ]; then mkdir ${shellAtom(runPath)}; fi`,
`test -d ${shellAtom(runPath)}`,
`if [ -e ${shellAtom(`${runPath}/.factorize-lease`)} ]; then test "$(cat ${shellAtom(`${runPath}/.factorize-lease`)})" = ${shellAtom(lease)}; else printf '%s' ${shellAtom(lease)} > ${shellAtom(`${runPath}/.factorize-lease`)}; fi`,
`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)}`,
`if [ -z "$workspace_id" ]; then created=$(${herdr} workspace create --cwd ${shellAtom(runPath)} --label ${shellAtom(workspaceName)} --no-focus) && workspace_id=$(printf '%s' "$created" | jq -er '.result.workspace.workspace_id') && tab_id=$(printf '%s' "$created" | jq -er '.result.tab.tab_id') && pane=$(printf '%s' "$created" | jq -er '.result.root_pane.pane_id') && ${herdr} tab rename "$tab_id" ${shellAtom(name)} >/dev/null; else tabs=$(${herdr} tab list --workspace "$workspace_id") && tab_id=$(printf '%s' "$tabs" | jq -r --arg label ${shellAtom(name)} '.result.tabs[]? | select(.label == $label) | .tab_id' | head -n1); if [ -z "$tab_id" ]; then created=$(${herdr} tab create --workspace "$workspace_id" --cwd ${shellAtom(runPath)} --label ${shellAtom(name)} --no-focus) && tab_id=$(printf '%s' "$created" | jq -er '.result.tab.tab_id') && pane=$(printf '%s' "$created" | jq -er '.result.root_pane.pane_id'); else panes=$(${herdr} pane list --workspace "$workspace_id") && pane=$(printf '%s' "$panes" | jq -r --arg tab "$tab_id" '.result.panes[]? | select(.tab_id == $tab) | .pane_id' | head -n1); test -n "$pane"; extras=$(printf '%s' "$panes" | jq -r --arg tab "$tab_id" --arg keep "$pane" '.result.panes[]? | select(.tab_id == $tab and .pane_id != $keep) | .pane_id'); for extra in $extras; do ${herdr} pane close "$extra" >/dev/null; done; fi; fi`,
`existing=$(${herdr} agent get ${shellAtom(name)} 2>/dev/null || true)`,
`if [ -n "$existing" ]; then printf '%s\\n' "$existing"; else ${herdr} agent start ${shellAtom(name)} --kind ${shellAtom(connection.agentKind)} --pane "$pane"${agentCommand(connection)} && prompt=$(printf '%s' ${shellAtom(encodedPrompt)} | base64 -d) && ${herdr} agent prompt ${shellAtom(name)} "$prompt" && ${herdr} agent get ${shellAtom(name)}; fi`,
].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 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 paneProcessInfoCommand(connection: ExeConnection, paneId: string): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} pane process-info --pane ${shellAtom(paneId)}`; }
export function validateWorktreeLeaseCommand(connection: ExeConnection, runPath: string, lease: string): string { return `${herdrPrefix(connection)} && test -d ${shellAtom(runPath)} && test "$(cat ${shellAtom(`${runPath}/.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, 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)}`; }

Expand All @@ -71,7 +72,7 @@ export function startAgentInPaneCommand(agentName: string, connection: ExeConnec
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(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(" && ");
return [herdrPrefix(connection), `first=$(${herdr} pane process-info --pane ${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 ${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 @@ -89,13 +90,14 @@ export function agentOutputCommand(connection: ExeConnection, agentName: string)
}

export function stopAgentCommand(connection: ExeConnection, agentName: string): string {
return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent stop ${shellAtom(agentName)}`;
const herdr = herdrBinary(connection);
return `${herdrPrefix(connection)} && agent=$(${herdr} agent get ${shellAtom(agentName)}) && pane=$(printf '%s' "$agent" | jq -er '.result.agent.pane_id') && ${herdr} pane close "$pane"`;
}

/** Revalidate terminal, worktree, and lease immediately before closing a pane. */
export function garbageCollectPaneCommand(connection: ExeConnection, paneId: string, terminalId: string, worktreePath: string, lease: string): string {
/** Revalidate terminal, run directory, and lease immediately before closing a pane. */
export function garbageCollectPaneCommand(connection: ExeConnection, paneId: string, terminalId: string, runPath: 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(" && ");
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 -d ${shellAtom(runPath)}`, `test "$(cat ${shellAtom(`${runPath}/.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`, `${herdr} pane close ${pane}`].join(" && ");
}

export function herdrCheckCommand(connection: ExeConnection): string {
Expand Down
2 changes: 1 addition & 1 deletion src/flow-schemas.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { z } from "zod";

export const scopeSchema = z.enum(["flows:read", "flows:write", "runs:read", "runs:write"]);
export const runStateSchema = z.enum(["queued", "starting", "running", "done", "blocked", "failed", "ignored"]);
export const runStateSchema = z.enum(["queued", "starting", "running", "recovering", "done", "blocked", "failed", "ignored"]);
export const matchRuleSchema = z.object({
type: z.enum(["owner", "creator", "status", "label", "assignee"]),
targetId: z.string().min(1),
Expand Down
9 changes: 5 additions & 4 deletions src/recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ export interface PaneProcess { paneId: string; pid: number; processGroup: number
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) };
const wrapper = obj(value), agent = wrapper.agent && typeof wrapper.agent === "object" ? 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, agent.agent), 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;
}
function jsonObjects(body: string): Record<string, any>[] {
Expand Down Expand Up @@ -36,7 +36,8 @@ export function safeToAdopt(saved: Partial<HerdrIdentity>, live: HerdrIdentity,
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 findOwnedAgent(saved: Partial<HerdrIdentity>, agents: HerdrIdentity[], worktreePath: string, expectedName: string, expectedKind: string): HerdrIdentity | undefined {
return agents.find((agent) => ownsPane(saved, agent, worktreePath)) ?? agents.find((agent) => agent.name === expectedName && agent.cwd === worktreePath && (!expectedKind || agent.kind === expectedKind));
export function findOwnedAgent(saved: Partial<HerdrIdentity>, agents: HerdrIdentity[], worktreePath: string, expectedName: string, expectedKind: string, runId: string): HerdrIdentity | undefined {
const runPath = (cwd: string) => cwd.includes(`/.factorize-runs/${runId}`) || cwd.includes(`/.factorize-worktrees/${runId}`);
return agents.find((agent) => ownsPane(saved, agent, worktreePath)) ?? agents.find((agent) => agent.name === expectedName && (!expectedKind || agent.kind === expectedKind) && (agent.cwd === worktreePath || runPath(agent.cwd)));
}
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