/** * Host-neutral subagent-result helpers: failure classification, transient-error * detection, error sanitization, and the NDJSON event accumulator/parser, PLUS * the shared `runSubagentProcess` that the codex/claude/opencode runners delegate * to for the identical spawn / idle-watchdog / abort / signal-kill / stderr-cap / * post-exit classification block. * * This is the pure, host-SDK-free half of the original runner. The pi spawn * machinery lives in the pi adapter (`pi-taskflow`); the codex/claude/opencode * spawn machinery in their adapters. All of them reuse everything here so * failure semantics, retry heuristics, and usage folding are identical across * hosts. */ import { type ChildProcess } from "node:child_process"; import { type UsageStats } from "./usage.ts"; import type { AgentConfig } from "./agents.ts"; import type { CoreMessage, LiveUpdate, RunResult } from "./host/runner-types.ts"; export type { CoreMessage, LiveUpdate, RunOptions, RunResult, SubagentRunner } from "./host/runner-types.ts"; export declare function isFailed(r: RunResult): boolean; export declare function isTransientError(r: RunResult): boolean; /** Wait for a retry backoff, but release immediately when the run is aborted. * Resolves (rather than rejects) on abort so callers can leave their retry loop * through the normal `signal.aborted` branch and preserve paused semantics. */ export declare function abortableDelay(ms: number, signal?: AbortSignal): Promise; /** Placeholder written to a failed phase's `output` so downstream interpolation * can detect "upstream failed" without mistaking transport chrome for an answer. */ export declare const TRANSPORT_ERROR_PLACEHOLDER = "(upstream error: subagent failed; see error)"; /** Whether a failed RunResult contains a genuine non-empty answer body. */ export declare function hasMeaningfulFailedOutput(r: Pick): boolean; /** Preserve a real failed answer body while keeping transport placeholders out * of downstream contexts. Content type alone is not evidence of transport * garbage: an agent may legitimately be generating HTML/SVG/JSON. */ export declare function failedResultDisplayOutput(r: Pick): string; /** Hard cap on the errorMessage field stored in PhaseState (≈ 4 KB). */ export declare const ERROR_MESSAGE_MAX_LEN = 4096; /** Cheap HTML/JSON detector so we can summarize upstream garbage. */ export declare function looksLikeHtmlOrJson(s: string): boolean; /** * Truncate and (when obviously HTML) summarize an errorMessage before it is * persisted. Returns the cleaned string. Empty input returns empty. */ export declare function sanitizeErrorMessage(raw: string | undefined): string; export declare function getFinalOutput(messages: CoreMessage[]): string; /** Accumulated state folded from a subagent's NDJSON event stream. */ export interface EventAccumulator { messages: CoreMessage[]; usage: UsageStats; model?: string; /** Last non-empty assistant text, mirrored for the shared process supervisor. */ finalText: string; stopReason?: string; errorMessage?: string; lastActivity: string; /** Shared-supervisor aliases populated from Pi's message lifecycle. */ fatalError?: string; terminalSeen?: boolean; /** Set when message cap was hit — output gets a truncation notice. */ truncated?: boolean; } export declare function newAccumulator(model?: string): EventAccumulator; /** * Fold one NDJSON line into the accumulator. Returns a LiveUpdate when an * assistant message ended (for streaming), else null. Empty, malformed, and * non-`message_end` lines are ignored — making the parser robust to partial * buffers/noise and unit-testable without spawning a process. */ export declare function foldEventLine(acc: EventAccumulator, line: string): LiveUpdate | null; /** Run an array of items through `fn` with a bounded concurrency pool. */ export declare function mapWithConcurrencyLimit(items: TIn[], concurrency: number, fn: (item: TIn, index: number) => Promise): Promise; /** Coerce a JSON-sourced numeric field to a finite number, defaulting to 0. * Provider event streams are parsed off `any`; a version drift could ship a * numeric STRING (e.g. "1234"), and `number += string` silently corrupts to * string concatenation / NaN. This guard keeps usage accounting honest. */ export declare function num(v: unknown): number; /** Register a detached process group with the host-wide supervisor. Script * phases and agent runners share this registry so external host termination * cannot leave either kind of child mutating the workspace. */ export declare function registerProcessTree(pid: number): void; /** Remove a process group after its stdio has closed and all descendants have * been synchronously reaped. */ export declare function unregisterProcessTree(pid: number): void; /** Signal the whole process tree rooted at a spawned subagent. POSIX children * are process-group leaders (`detached:true` at spawn), so a negative pid * reaches every descendant in the group. Windows has no equivalent signal; * taskkill /T /F is the platform-supported tree termination primitive. */ export declare function killProcessTree(pid: number, signal: NodeJS.Signals, direct?: ChildProcess): void; declare const EXTERNAL_SIGNALS: readonly ["SIGTERM", "SIGINT", "SIGHUP"]; declare let gracefulSignalOwner: ((signal: (typeof EXTERNAL_SIGNALS)[number]) => void) | undefined; /** A process-owning launcher may persist cancellation before reaping its children. * Only one trusted in-process owner can claim this bounded shutdown window. */ export declare function registerGracefulSignalOwner(owner: NonNullable): () => void; /** Same idle window every host runner uses: a child silent this long is wedged. */ export declare const DEFAULT_IDLE_TIMEOUT_MS: number; /** After a phase timeout aborts its runner, allow process-backed hosts enough * time to execute their SIGTERM to SIGKILL escalation. A custom runner that * ignores AbortSignal entirely is still bounded by this grace window. */ export declare const PHASE_TIMEOUT_ABORT_GRACE_MS = 5500; /** Maximum NDJSON line size retained while waiting for a newline. A hostile or * broken host can otherwise stream an unterminated line until the orchestrator * runs out of memory. Host events are expected to be compact; 1 MiB still * leaves ample room for a large final answer while providing a hard bound. */ export declare const MAX_STDOUT_LINE_BYTES: number; /** The base accumulator contract the shared process runner reads/writes. Each * host's accumulator (Codex/Claude/OpenCode) satisfies this structurally and * may carry extra fields (e.g. claude's `sawResult`) its own foldLine uses. */ export interface SubagentAccumulator { usage: UsageStats; model?: string; /** Final answer text (the host's foldLine sets this from its event stream). */ finalText: string; lastActivity: string; /** Set by the host foldLine when the stream reported a fatal error event. */ fatalError?: string; /** Set by hosts whose protocol has an authoritative terminal event. */ terminalSeen?: boolean; /** Optional host-native terminal reason, used by completion policies. */ stopReason?: string; } export type CompletionEventClassification = "ignore" | "activity" | "terminal-candidate" | "fatal"; /** Optional host protocol layered over ordinary process exit. A terminal event * is only a candidate: the shared supervisor waits a grace period, revokes the * candidate on later activity, and commits only after canCommitTerminal passes. */ export interface CompletionPolicy { terminalGraceMs: number; classifyEvent(acc: TAcc, event: unknown): CompletionEventClassification; canCommitTerminal(acc: TAcc): boolean; } /** Standard "unknown agent" RunResult — identical across every host runner. */ export declare function unknownAgentResult(agentName: string, task: string, agents: AgentConfig[]): RunResult; export interface RunSubagentProcessOptions { /** Identity fields written verbatim onto the RunResult. */ agent: string; task: string; model?: string; /** Spawn spec. `env` defaults to the parent process env; a host may override * (e.g. opencode injects OPENCODE_CONFIG_CONTENT for read-only phases). */ bin: string; args: string[]; env?: NodeJS.ProcessEnv; cwd: string; /** Execution knobs (forwarded from the phase's RunOptions). */ idleTimeoutMs?: number; /** @internal SIGTERM-to-SIGKILL grace. Defaults to 5s; injectable for * deterministic supervisor tests. */ terminationGraceMs?: number; signal?: AbortSignal; onLive?: (live: LiveUpdate) => void; /** Bounded host-specific metadata observer. Receives raw stderr chunks before * the shared 64KB retained-diagnostic cap; exceptions are ignored. */ observeStderr?: (data: Buffer) => void; /** Per-host event folding: the host's accumulator + its line parser. */ acc: TAcc; foldLine: (acc: TAcc, line: string) => LiveUpdate | null; completionPolicy?: CompletionPolicy; /** Host-specific escape hatch for a known redundant record that can grow * without bound. The callback receives only a bounded prefix and must return * true only when the accumulator already contains the authoritative data. * Accepted records are discarded through their newline and never count as a * terminal event; the host must still emit its compact terminal record. */ canDiscardOversizedLine?: (acc: TAcc, prefix: string) => boolean; /** Synchronous notification at the terminal-reap linearization point. */ onTerminalCommit?: () => void; /** Fail closed when the CLI exits zero before its authoritative terminal event. */ requireTerminalEvent?: boolean; terminalEventLabel?: string; /** * How stdout lines are framed. * - `"json"` (default): every non-empty line must parse as JSON (NDJSON hosts). * - `"text"`: plain-text lines are passed straight to `foldLine` (e.g. Hermes * quiet mode). Malformed-JSON protocol failure is disabled. */ stdoutFormat?: "json" | "text"; } /** Spawn an isolated subagent process, fold its event stream, and classify the * outcome into a RunResult. The whole tail (fatalError, signal-kill remap, * idle-timeout, abort, isFailed + placeholder + sanitize) is the single source * of truth — every host runner that delegates here gets identical semantics. */ export declare function runSubagentProcess(opts: RunSubagentProcessOptions): Promise; //# sourceMappingURL=runner-core.d.ts.map