/** * Headless `claude -p` run lifecycle (T001 of the session-panel async-runs plan). * * Owns everything between "the web route decided to run a job" and a finished * run record: spawn, streaming stdout capture, timeout escalation, NDJSON event * parsing, exit mapping and per-write-target concurrency serialization. The * route supplies argv/cwd and this module never * decides what the child *does* — but it does own the child's OUTPUT CONTRACT: * every run is normalized onto `--output-format stream-json * --include-partial-messages --verbose` (see withStreamJsonArgv), so stdout is * always the newline-delimited event stream the reader below understands. When * the caller supplies an `eventLog` target, that stream is ALSO persisted * verbatim to the run's own event log before the reader parses a byte of it * (see run-event-log.ts) — the log is the durable record, parsing is a consumer. * The route's post-run write-back (transcript mirror + metadata.run finalization) * plugs in as the per-job `onSettled` callback, invoked after the child exits. * * Injectable `spawnImpl` + `binary` keep tests free of real children; the * default impl is plain node child_process `spawn` with `stdio: * ["ignore","pipe","pipe"]`. Every child-side failure resolves to an outcome * record — this module never throws on spawn/exit/timeout paths. */ import { type ChildProcess, type SpawnOptions } from "node:child_process"; import { type RunEventLogTarget } from "./run-event-log.js"; export type RunOutcome = "success" | "error" | "timeout"; export interface ClaudeRunRecord { pid: number | null; startedAt: number; endedAt?: number; outcome: RunOutcome; error?: string; replyText?: string; replyChars?: number; /** * Epoch ms (Date.now(), same unit as startedAt/endedAt — never an ISO string) * of the first assistant content seen on the event stream: time-to-first-token * is `firstTokenAt - startedAt`. Absent when the run produced no content * (spawn failure, refused overlap, a timeout before the model spoke). */ firstTokenAt?: number; /** * Count of stdout lines the NDJSON reader could not use — unparsable JSON, * non-object JSON, or an unknown event type. Omitted when zero. A nonzero * count on an otherwise successful run is the wire-format drift signal: the * run still settles normally, the number says the reader fell behind claude. */ skippedLines?: number; /** * Lines written to the run's durable event log — the count of stdout lines * that reached disk, which is >= what the reader could use (the log keeps the * ones it skipped too). Absent when the run had no log target. */ eventLogLines?: number; /** * The event log is INCOMPLETE — it hit RUN_EVENT_LOG_MAX_BYTES or lost bytes * to a short write, so what is on disk is no longer the whole stream. Omitted * (never `false`) when the log is complete. * * This has to travel with `eventLogLines` or the count lies by omission: a * capped log whose very first chunk was refused reports `eventLogLines: 0`, * which is exactly what a child that said nothing reports. Anything that * tails the file by offset must read this first. */ eventLogTruncated?: boolean; /** * Why the event log could not be written, when it failed. REPORTED, never * thrown: a run whose log is unwritable still runs, still settles and still * returns its reply — losing the audit trail is not a reason to lose the run. */ eventLogError?: string; } export interface ClaudeJobInput { /** * Argv for the child, e.g. ["-p", "…", "--resume", ""]. Any caller-supplied * output-format flags are rewritten by withStreamJsonArgv — the runner owns * that part of the contract because it owns the reader. */ argv: string[]; /** * Whether the runner rewrites `argv` onto its stream-json output contract * (withStreamJsonArgv). Defaults to true — every claude-code caller wants * it. A one-shot driver runtime whose wire format this reader does not speak * (opencode's `--format json` NDJSON) passes false, and its argv reaches the * child verbatim: rewriting it would append flags that runtime rejects. */ streamJsonArgv?: boolean; /** Working directory for the child; defaults to the server's cwd. */ cwd?: string; /** Timeout override; defaults to ARCS_CLAUDE_RUN_TIMEOUT_MS then 10 min. */ timeoutMs?: number; /** * Key serializing runs that write to the same target — a second live run for * the same key is refused (see beginRun). */ writeTargetKey: string; /** Base env for the child (defaults to process.env). */ env?: NodeJS.ProcessEnv; /** * Where to persist this run's stdout verbatim. When present, every stdout * chunk is written to `sessions/{sessionId}.run-{runId}.events.jsonl` BEFORE * the NDJSON reader below sees it, on every outcome — success, error and * timeout alike. The caller supplies the runId it already persisted as the * session's `currentRunId`, so the log's name and the session record cannot * disagree. Omit it and the run keeps no log (the runner stays usable without * a project dir). */ eventLog?: RunEventLogTarget; /** * Post-run write-back invoked with the settled record after the child has * fully exited (`close` fired, stdio drained) — on every path that yields a * record: success, error, timeout, even a refused overlap. The calling route * registers this to mirror the resumed session's transcript and finalize * metadata.run (mode-1 write-back); the runner itself stays argv-agnostic and * never decides what the callback does. Errors thrown by the callback are * swallowed — the write-back is best-effort and must never change the record * the runner returns. */ onSettled?: (record: ClaudeRunRecord) => void | Promise; } /** Minimal spawn surface so tests can inject a fake without a real child. */ export type SpawnImpl = (command: string, args: string[], options: SpawnOptions) => ChildProcess; export interface ClaudeRunnerOptions { /** Overrides `spawn` (tests). */ spawnImpl?: SpawnImpl; /** Binary name to spawn (tests); default "claude". */ binary?: string; /** SIGTERM → SIGKILL grace period; default 5s. */ killGraceMs?: number; } /** * Bound on the *raw* stdout tail kept as the last-resort reply for a child that * emits no usable events. It no longer truncates real replies — those are * assembled from whole event lines as they arrive. */ export declare const STDOUT_CAP: number; export declare const STDERR_CAP: number; /** * Ceiling on a single *unterminated* line the NDJSON reader will buffer — a * memory guard against a child that never emits a newline, not a reply cap. It * sits well above any single claude event (one message cannot approach 8 MB), so * a long reply split across chunks still reassembles whole. */ export declare const MAX_EVENT_LINE: number; /** * Rewrites caller argv onto the runner's output contract: drops any * `--output-format ` / `--output-format=` the caller chose (routes still * build plain `--output-format json`) plus any duplicate stream companions, then * appends STREAM_JSON_ARGV. Everything else — `-p`, the prompt, `--resume`, * `--session-id` — passes through untouched and in order. */ export declare function withStreamJsonArgv(argv: string[]): string[]; export type BeginRunResult = { ok: true; startedAt: number; } | { ok: false; reason: "ALREADY_RUNNING"; message: string; }; /** * Atomically claims the slot for a write-target key. Returns a typed refusal * when a live run already holds it. Synchronous and called immediately after * spawn (no await in between), so two overlapping requests cannot both win. */ export declare function beginRun(writeTargetKey: string, child: ChildProcess): BeginRunResult; /** Releases the slot for a write-target key (idempotent). */ export declare function endRun(writeTargetKey: string): void; /** Read-only liveness probe for the same slot (routes / UI status). */ export declare function isRunLive(writeTargetKey: string): boolean; /** * Pid of the child currently holding a write-target's slot. * * `undefined` means no live run (the spawn threw, or the slot was refused); * `null` means a live run whose child never reported a pid (an async spawn * failure — node reports ENOENT on the `error` event, not at spawn). * * Exists so the run route can persist the child's pid on the session's run * claim: `runClaudeJob` spawns synchronously (nothing is awaited before * `beginRun`), so a caller that reads this immediately after calling it — * before its own first await — sees the pid of the child it just started. * Read-only: it cannot start, stop or observe anything else about the run. */ export declare function liveRunPid(writeTargetKey: string): number | null | undefined; export declare function runClaudeJob(input: ClaudeJobInput, options?: ClaudeRunnerOptions): Promise; /** * The ceiling a run will actually be killed at: an explicit override first, * then ARCS_CLAUDE_RUN_TIMEOUT_MS, then the 10-minute default. * * Exported because the run route has to persist the resulting DEADLINE with the * session's run claim (a claim is only proof of life until the child is killed), * and a second copy of this precedence in the route would silently drift from * the one the timer here is armed with. */ export declare function resolveTimeoutMs(timeoutMs: number | undefined, env?: NodeJS.ProcessEnv): number; //# sourceMappingURL=claude-runner.d.ts.map