amplifier-agent-ts 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ /**
2
+ * run-output-parser.ts — parse the Mode A v2 subprocess outcome into a DisplayEvent.
3
+ *
4
+ * Implements §4.1 envelope schema and §4.4 (SC-D) precedence rules from
5
+ * `docs/designs/2026-05-24-aaa-v2-mode-a-pivot-amendment.md`:
6
+ *
7
+ * Rule 1 — envelope parseable per §4.1 → envelope is authoritative.
8
+ * The `error` field (null or populated) drives the wrapper's outcome.
9
+ * The exit code is informational and does NOT override the envelope.
10
+ *
11
+ * Rule 2 — envelope absent / unparseable / partial → synthesize an error
12
+ * event from exit code and stderr tail. Partial JSON is NOT
13
+ * half-parsed (belt-and-suspenders): if any required §4.1 field
14
+ * is missing, the envelope is treated as unparseable.
15
+ *
16
+ * stderrTail is truncated to STDERR_TAIL_BYTES (4096) on synthesized paths;
17
+ * on the envelope path it is taken verbatim from the engine.
18
+ */
19
+ /** Maximum stderrTail length retained on synthesized engine errors. */
20
+ export const STDERR_TAIL_BYTES = 4096;
21
+ /** Maximum stdout snippet included in `envelope_missing` messages. */
22
+ const STDOUT_PREVIEW_BYTES = 512;
23
+ /**
24
+ * Keep the last `STDERR_TAIL_BYTES` chars of `stderr`.
25
+ * Returns `undefined` for an empty string so callers can omit the field
26
+ * cleanly when there is nothing to surface.
27
+ */
28
+ function tailStderr(stderr) {
29
+ if (!stderr)
30
+ return undefined;
31
+ if (stderr.length <= STDERR_TAIL_BYTES)
32
+ return stderr;
33
+ return stderr.slice(stderr.length - STDERR_TAIL_BYTES);
34
+ }
35
+ const VALID_CLASSIFICATIONS = new Set([
36
+ "transport",
37
+ "protocol",
38
+ "engine",
39
+ "approval",
40
+ "unknown",
41
+ ]);
42
+ /**
43
+ * Validate that `parsed` conforms to the §4.1 envelope shape.
44
+ *
45
+ * Required:
46
+ * - protocolVersion, sessionId, turnId, reply: string
47
+ * - error: null | object with `code: string`
48
+ * - metadata: object
49
+ *
50
+ * Partial / type-wrong envelopes return `false` so the caller falls to Rule 2.
51
+ */
52
+ function isShapeValid(parsed) {
53
+ if (parsed === null || typeof parsed !== "object")
54
+ return false;
55
+ const o = parsed;
56
+ if (typeof o.protocolVersion !== "string")
57
+ return false;
58
+ if (typeof o.sessionId !== "string")
59
+ return false;
60
+ if (typeof o.turnId !== "string")
61
+ return false;
62
+ if (typeof o.reply !== "string")
63
+ return false;
64
+ if (typeof o.metadata !== "object" || o.metadata === null)
65
+ return false;
66
+ if (o.error === null)
67
+ return true;
68
+ if (typeof o.error !== "object")
69
+ return false;
70
+ const err = o.error;
71
+ if (typeof err.code !== "string")
72
+ return false;
73
+ return true;
74
+ }
75
+ /**
76
+ * Parse a subprocess outcome into a single DisplayEvent.
77
+ *
78
+ * See module docstring for precedence rules.
79
+ */
80
+ export function parseRunOutput(outcome) {
81
+ const trimmed = outcome.stdout.trim();
82
+ // Attempt to parse stdout as JSON. Failures (empty, partial, non-JSON) are
83
+ // captured silently; the caller falls to Rule 2.
84
+ let parsed = null;
85
+ if (trimmed.length > 0) {
86
+ try {
87
+ parsed = JSON.parse(trimmed);
88
+ }
89
+ catch {
90
+ parsed = null;
91
+ }
92
+ }
93
+ // Rule 1 — envelope parseable per §4.1 → envelope wins.
94
+ if (parsed !== null && isShapeValid(parsed)) {
95
+ const env = parsed;
96
+ if (env.error === null) {
97
+ // Success path — exit code is informational only.
98
+ return { type: "result", text: env.reply };
99
+ }
100
+ // Failure path — populate from the envelope's error fields.
101
+ const err = env.error;
102
+ const classification = err.classification !== undefined &&
103
+ VALID_CLASSIFICATIONS.has(err.classification)
104
+ ? err.classification
105
+ : "unknown";
106
+ const severity = err.severity === "warning" ? "warning" : "error";
107
+ const correlationId = typeof err.correlationId === "string" ? err.correlationId : "";
108
+ const message = typeof err.message === "string" ? err.message : err.code;
109
+ const stderrTail = typeof err.stderrTail === "string" ? err.stderrTail : tailStderr(outcome.stderr);
110
+ return {
111
+ type: "error",
112
+ code: err.code,
113
+ classification,
114
+ severity,
115
+ correlationId,
116
+ message,
117
+ ...(stderrTail !== undefined ? { stderrTail } : {}),
118
+ retryable: false,
119
+ };
120
+ }
121
+ // Rule 2 — envelope absent or unparseable → synthesize from exit + stderr.
122
+ const stderrTail = tailStderr(outcome.stderr);
123
+ if (outcome.exitCode === 0) {
124
+ // Engine protocol violation: exit 0 without a parseable envelope.
125
+ const preview = outcome.stdout.slice(0, STDOUT_PREVIEW_BYTES);
126
+ const previewSuffix = outcome.stdout.length > STDOUT_PREVIEW_BYTES ? "...(truncated)" : "";
127
+ return {
128
+ type: "error",
129
+ code: "envelope_missing",
130
+ classification: "protocol",
131
+ severity: "error",
132
+ correlationId: "",
133
+ message: `Engine exited 0 without emitting a parseable §4.1 envelope. Stdout was: ${JSON.stringify(preview)}${previewSuffix}`,
134
+ ...(stderrTail !== undefined ? { stderrTail } : {}),
135
+ retryable: false,
136
+ };
137
+ }
138
+ // Non-zero exit, envelope absent or partial — engine-class failure.
139
+ return {
140
+ type: "error",
141
+ code: `engine_exit_${outcome.exitCode}`,
142
+ classification: "engine",
143
+ severity: "error",
144
+ correlationId: "",
145
+ message: `Engine exited ${outcome.exitCode} without emitting a parseable §4.1 envelope.`,
146
+ ...(stderrTail !== undefined ? { stderrTail } : {}),
147
+ retryable: false,
148
+ };
149
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * SessionHandle — subprocess driver for Mode A v2 (A3').
3
+ *
4
+ * Per the 2026-05-24 Mode A pivot amendment §5.2: each `submit()` call spawns a
5
+ * fresh `amplifier-agent run` subprocess with the assembled argv. The async
6
+ * iterable yields:
7
+ *
8
+ * 1. `{type:'init', sessionId}` — yielded SYNCHRONOUSLY before the
9
+ * subprocess is spawned (SC-1: no race window with the activity ticker).
10
+ * 2. `{type:'activity'}` — yielded every 2 seconds while the subprocess is
11
+ * alive (preserves NC's stuck-detection signal without engine-side
12
+ * cooperation).
13
+ * 3. `{type:'result', text}` or `{type:'error', ...}` — yielded once when
14
+ * the subprocess exits (`parseRunOutput` applied to stdout/stderr/exit)
15
+ * OR when the configured `timeoutMs` elapses (synthesized `engine_hung`).
16
+ *
17
+ * Lifecycle:
18
+ * - `submit()` is one-shot per session (D10). A second call throws
19
+ * `AaaError(lifecycle_unsupported)`.
20
+ * - `cancel()` SIGTERMs the whole process group (SC-B), waits up to 5s, then
21
+ * SIGKILLs if the engine has not exited. It also unlinks any MCP spill
22
+ * file created on this turn (CR-A cleanup).
23
+ * - `dispose()` is a synonym for `cancel()`.
24
+ */
25
+ import type { ChildProcess } from "node:child_process";
26
+ import type { McpServerConfig, HostCapabilities } from "./types.js";
27
+ /**
28
+ * A display event yielded by `SessionHandle.submit()`.
29
+ *
30
+ * Mode A v2 (CR-C, amendment §5.2): a discriminated union narrow enough that
31
+ * every variant's payload is exhaustively typed. The fields removed from the
32
+ * pre-amendment shape (`turnId`, `parentTurnId`, `synthesized`, `payload`)
33
+ * cannot be meaningfully populated on the Mode A wire.
34
+ */
35
+ export type DisplayEvent = {
36
+ type: "init";
37
+ sessionId: string;
38
+ } | {
39
+ type: "activity";
40
+ } | {
41
+ type: "result";
42
+ text: string;
43
+ } | {
44
+ type: "error";
45
+ code: string;
46
+ classification: "transport" | "protocol" | "engine" | "approval" | "unknown";
47
+ severity: "error" | "warning";
48
+ correlationId: string;
49
+ message: string;
50
+ stderrTail?: string;
51
+ retryable: boolean;
52
+ };
53
+ /** Typed error for AaA wrapper lifecycle and protocol violations. */
54
+ export declare class AaaError extends Error {
55
+ code: string;
56
+ remediation?: string;
57
+ classification?: "transport" | "protocol" | "engine" | "approval" | "unknown";
58
+ severity?: "error" | "warning";
59
+ correlationId?: string;
60
+ stderrTail?: string;
61
+ constructor(code: string, remediation?: string, opts?: {
62
+ classification?: AaaError["classification"];
63
+ severity?: AaaError["severity"];
64
+ correlationId?: string;
65
+ stderrTail?: string;
66
+ });
67
+ }
68
+ /** Info returned by SessionHandle.getEngineInfo() (D5). */
69
+ export interface EngineInfo {
70
+ binaryPath: string;
71
+ protocolVersion: string;
72
+ engineVersion: string;
73
+ bundleDigest: string;
74
+ }
75
+ /**
76
+ * Parameters for constructing a `SessionHandle` (amendment §5.2).
77
+ *
78
+ * All session config is captured up-front and stored as instance state. The
79
+ * subprocess is not spawned until `submit()` is called.
80
+ */
81
+ export interface SessionHandleParams {
82
+ /** Resolved absolute path to the amplifier-agent binary. */
83
+ binaryPath: string;
84
+ /** Session identifier (caller-supplied or minted by spawnAgent). */
85
+ sessionId: string;
86
+ /** Subprocess environment (already filtered by `buildEnv`). */
87
+ subprocessEnv: Record<string, string>;
88
+ /** When true, emit `--resume`; otherwise emit `--fresh`. */
89
+ resume?: boolean;
90
+ /** Working directory for the subprocess. */
91
+ cwd?: string;
92
+ /** MCP servers to forward via `--mcp-servers` (CR-A spill applies). */
93
+ mcpServers?: Record<string, McpServerConfig>;
94
+ /** Host capabilities forwarded via `--host-capabilities`. */
95
+ hostCapabilities?: HostCapabilities;
96
+ /** Allowlisted env variable names forwarded via `--env-allowlist`. */
97
+ envAllowlist?: string[];
98
+ /** Extra env entries forwarded via `--env-extra`. */
99
+ envExtra?: Record<string, string>;
100
+ /** Provider override forwarded via `--provider`. */
101
+ providerOverride?: string;
102
+ /** When true, append `--allow-protocol-skew` to argv. */
103
+ allowProtocolSkew?: boolean;
104
+ /** Protocol version the wrapper speaks (e.g. "0.1.0"). */
105
+ protocolVersion: string;
106
+ /** Per-submit timeout in milliseconds. Defaults to 10 minutes. */
107
+ timeoutMs?: number;
108
+ }
109
+ /**
110
+ * Wait for `child` to fire `exit`, or `ms` to elapse — whichever first.
111
+ *
112
+ * Resolves either way (the caller inspects `child.exitCode` / `signalCode` to
113
+ * determine which path was taken). Idempotent: if the child has already
114
+ * exited, resolves immediately.
115
+ */
116
+ export declare function waitForExitOrTimeout(child: ChildProcess, ms: number): Promise<void>;
117
+ /** One-shot session handle that drives the engine subprocess. */
118
+ export declare class SessionHandle {
119
+ private readonly params;
120
+ private submitted;
121
+ private subprocess;
122
+ private mcpSpillPath;
123
+ private readonly engineInfo;
124
+ constructor(params: SessionHandleParams);
125
+ /** Return resolved engine metadata (D5). */
126
+ getEngineInfo(): EngineInfo;
127
+ /**
128
+ * Submit a prompt and return an AsyncIterable of DisplayEvents.
129
+ *
130
+ * One-shot per session (D10): throws AaaError on second call.
131
+ */
132
+ submit(prompt: string): AsyncIterable<DisplayEvent>;
133
+ /**
134
+ * Async generator implementing the §5.2 iterable behavior:
135
+ * (i) yield `{type:'init', sessionId}` synchronously (SC-1);
136
+ * (ii) CR-A: resolve `--mcp-servers` flag (spill if env-bearing);
137
+ * (iii) build argv via `assembleArgv`;
138
+ * (iv) SC-B: spawn with `detached:true` so PID == PGID for group signals;
139
+ * (v) accumulate stdout/stderr from chunks;
140
+ * (vi) start a 2s activity ticker → queue;
141
+ * (vii) race `exitPromise` vs `timeoutPromise`;
142
+ * on timeout: cancel(), synthesize `engine_hung`;
143
+ * on exit: parseRunOutput({stdout, stderr, exitCode});
144
+ * (viii) cleanup spill file after exit;
145
+ * (ix) drain queue until the final event is yielded.
146
+ */
147
+ private makeIterable;
148
+ /**
149
+ * Cancel the running subprocess via SIGTERM-then-SIGKILL on the whole
150
+ * process group (SC-B), then unlink any MCP spill file (CR-A).
151
+ *
152
+ * Idempotent: safe to call when the subprocess has already exited and safe
153
+ * to call when no spill file was created. Errors from `process.kill` are
154
+ * swallowed (`ESRCH` means the group is already gone).
155
+ */
156
+ cancel(): Promise<void>;
157
+ /** Graceful shutdown — alias for `cancel()` (D3). */
158
+ dispose(): Promise<void>;
159
+ }
@@ -0,0 +1,317 @@
1
+ /**
2
+ * SessionHandle — subprocess driver for Mode A v2 (A3').
3
+ *
4
+ * Per the 2026-05-24 Mode A pivot amendment §5.2: each `submit()` call spawns a
5
+ * fresh `amplifier-agent run` subprocess with the assembled argv. The async
6
+ * iterable yields:
7
+ *
8
+ * 1. `{type:'init', sessionId}` — yielded SYNCHRONOUSLY before the
9
+ * subprocess is spawned (SC-1: no race window with the activity ticker).
10
+ * 2. `{type:'activity'}` — yielded every 2 seconds while the subprocess is
11
+ * alive (preserves NC's stuck-detection signal without engine-side
12
+ * cooperation).
13
+ * 3. `{type:'result', text}` or `{type:'error', ...}` — yielded once when
14
+ * the subprocess exits (`parseRunOutput` applied to stdout/stderr/exit)
15
+ * OR when the configured `timeoutMs` elapses (synthesized `engine_hung`).
16
+ *
17
+ * Lifecycle:
18
+ * - `submit()` is one-shot per session (D10). A second call throws
19
+ * `AaaError(lifecycle_unsupported)`.
20
+ * - `cancel()` SIGTERMs the whole process group (SC-B), waits up to 5s, then
21
+ * SIGKILLs if the engine has not exited. It also unlinks any MCP spill
22
+ * file created on this turn (CR-A cleanup).
23
+ * - `dispose()` is a synonym for `cancel()`.
24
+ */
25
+ import { spawn as childSpawn } from "node:child_process";
26
+ import { assembleArgv } from "./argv-builder.js";
27
+ import { resolveMcpServersFlag, cleanupSpillFile } from "./mcp-spill.js";
28
+ import { parseRunOutput, STDERR_TAIL_BYTES } from "./run-output-parser.js";
29
+ /** Typed error for AaA wrapper lifecycle and protocol violations. */
30
+ export class AaaError extends Error {
31
+ code;
32
+ remediation;
33
+ classification;
34
+ severity;
35
+ correlationId;
36
+ stderrTail;
37
+ constructor(code, remediation, opts) {
38
+ super(remediation ?? code);
39
+ this.code = code;
40
+ this.remediation = remediation;
41
+ this.name = "AaaError";
42
+ if (opts) {
43
+ this.classification = opts.classification;
44
+ this.severity = opts.severity;
45
+ this.correlationId = opts.correlationId;
46
+ this.stderrTail = opts.stderrTail;
47
+ }
48
+ }
49
+ }
50
+ /** Default subprocess timeout: 10 minutes. */
51
+ const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
52
+ /** Activity ticker interval: 2 seconds (NC stuck-detection has 10s threshold). */
53
+ const ACTIVITY_TICK_MS = 2000;
54
+ /** Grace window between SIGTERM and SIGKILL in `cancel()`. */
55
+ const SIGKILL_GRACE_MS = 5000;
56
+ /**
57
+ * Wait for `child` to fire `exit`, or `ms` to elapse — whichever first.
58
+ *
59
+ * Resolves either way (the caller inspects `child.exitCode` / `signalCode` to
60
+ * determine which path was taken). Idempotent: if the child has already
61
+ * exited, resolves immediately.
62
+ */
63
+ export function waitForExitOrTimeout(child, ms) {
64
+ return new Promise((resolve) => {
65
+ if (child.exitCode !== null || child.signalCode !== null) {
66
+ resolve();
67
+ return;
68
+ }
69
+ const timer = setTimeout(() => {
70
+ resolve();
71
+ }, ms);
72
+ child.once("exit", () => {
73
+ clearTimeout(timer);
74
+ resolve();
75
+ });
76
+ });
77
+ }
78
+ /** Last `STDERR_TAIL_BYTES` chars of `stderr`, or undefined if empty. */
79
+ function stderrTailOf(stderr) {
80
+ if (!stderr)
81
+ return undefined;
82
+ if (stderr.length <= STDERR_TAIL_BYTES)
83
+ return stderr;
84
+ return stderr.slice(stderr.length - STDERR_TAIL_BYTES);
85
+ }
86
+ /** One-shot session handle that drives the engine subprocess. */
87
+ export class SessionHandle {
88
+ params;
89
+ submitted = false;
90
+ subprocess = null;
91
+ mcpSpillPath = null;
92
+ engineInfo;
93
+ constructor(params) {
94
+ this.params = params;
95
+ this.engineInfo = {
96
+ binaryPath: params.binaryPath,
97
+ protocolVersion: params.protocolVersion,
98
+ // engineVersion / bundleDigest are no longer probed up-front under Mode
99
+ // A v2 — they will be populated from the JSON envelope's `metadata`
100
+ // field once it arrives (TODO: Task-9 wires this from parseRunOutput).
101
+ engineVersion: "",
102
+ bundleDigest: "",
103
+ };
104
+ }
105
+ /** Return resolved engine metadata (D5). */
106
+ getEngineInfo() {
107
+ return this.engineInfo;
108
+ }
109
+ /**
110
+ * Submit a prompt and return an AsyncIterable of DisplayEvents.
111
+ *
112
+ * One-shot per session (D10): throws AaaError on second call.
113
+ */
114
+ submit(prompt) {
115
+ if (this.submitted) {
116
+ throw new AaaError("lifecycle_unsupported", "SessionHandle.submit() is one-shot per session (D10); already submitted");
117
+ }
118
+ this.submitted = true;
119
+ return this.makeIterable(prompt);
120
+ }
121
+ /**
122
+ * Async generator implementing the §5.2 iterable behavior:
123
+ * (i) yield `{type:'init', sessionId}` synchronously (SC-1);
124
+ * (ii) CR-A: resolve `--mcp-servers` flag (spill if env-bearing);
125
+ * (iii) build argv via `assembleArgv`;
126
+ * (iv) SC-B: spawn with `detached:true` so PID == PGID for group signals;
127
+ * (v) accumulate stdout/stderr from chunks;
128
+ * (vi) start a 2s activity ticker → queue;
129
+ * (vii) race `exitPromise` vs `timeoutPromise`;
130
+ * on timeout: cancel(), synthesize `engine_hung`;
131
+ * on exit: parseRunOutput({stdout, stderr, exitCode});
132
+ * (viii) cleanup spill file after exit;
133
+ * (ix) drain queue until the final event is yielded.
134
+ */
135
+ async *makeIterable(prompt) {
136
+ // (i) SC-1: yield init synchronously, BEFORE any async work.
137
+ yield { type: "init", sessionId: this.params.sessionId };
138
+ // (ii) CR-A: resolve --mcp-servers (inline JSON OR spill to 0600 tmpfile).
139
+ // Cast through `unknown`: McpServerConfig is the schema-validated wire type
140
+ // (no index signature), while resolveMcpServersFlag's McpServerLike has an
141
+ // open index signature. The two are runtime-compatible — only `env` is
142
+ // inspected — but TS rightly rejects assignability without the cast.
143
+ const spill = await resolveMcpServersFlag((this.params.mcpServers ?? null), this.params.sessionId);
144
+ this.mcpSpillPath = spill.spillPath;
145
+ // (iii) build argv (pure function — no I/O).
146
+ const argv = assembleArgv({
147
+ sessionId: this.params.sessionId,
148
+ prompt,
149
+ protocolVersion: this.params.protocolVersion,
150
+ resume: this.params.resume,
151
+ cwd: this.params.cwd,
152
+ providerOverride: this.params.providerOverride,
153
+ mcpServersFlag: spill.flag ?? undefined,
154
+ hostCapabilities: this.params.hostCapabilities,
155
+ envAllowlist: this.params.envAllowlist,
156
+ envExtra: this.params.envExtra,
157
+ allowProtocolSkew: this.params.allowProtocolSkew,
158
+ });
159
+ // (iv) SC-B: spawn detached → new session group → PID == PGID.
160
+ const child = childSpawn(this.params.binaryPath, argv, {
161
+ detached: true,
162
+ stdio: ["ignore", "pipe", "pipe"],
163
+ env: this.params.subprocessEnv,
164
+ ...(this.params.cwd !== undefined ? { cwd: this.params.cwd } : {}),
165
+ });
166
+ this.subprocess = child;
167
+ // (v) accumulate stdout/stderr from chunks.
168
+ let stdoutBuf = "";
169
+ let stderrBuf = "";
170
+ child.stdout?.on("data", (chunk) => {
171
+ stdoutBuf += typeof chunk === "string" ? chunk : chunk.toString("utf-8");
172
+ });
173
+ child.stderr?.on("data", (chunk) => {
174
+ stderrBuf += typeof chunk === "string" ? chunk : chunk.toString("utf-8");
175
+ });
176
+ const queue = [];
177
+ let wake = null;
178
+ const push = (item) => {
179
+ queue.push(item);
180
+ if (wake !== null) {
181
+ const w = wake;
182
+ wake = null;
183
+ w();
184
+ }
185
+ };
186
+ // Single-shot finalize: whichever of {timeout, exit, spawn error} wins
187
+ // pushes the terminal event + done sentinel; later events are ignored.
188
+ let finalized = false;
189
+ const finalize = (ev) => {
190
+ if (finalized)
191
+ return;
192
+ finalized = true;
193
+ push(ev);
194
+ push({ _done: true });
195
+ };
196
+ // (vi) 2s activity ticker.
197
+ const ticker = setInterval(() => {
198
+ if (!finalized)
199
+ push({ type: "activity" });
200
+ }, ACTIVITY_TICK_MS);
201
+ // (vii) race exit vs timeout.
202
+ const timeoutMs = this.params.timeoutMs ?? DEFAULT_TIMEOUT_MS;
203
+ const timeoutHandle = setTimeout(() => {
204
+ // Synthesize engine_hung before invoking cancel(), so the iterator
205
+ // yields a terminal error even if SIGTERM/SIGKILL hangs.
206
+ const tail = stderrTailOf(stderrBuf);
207
+ finalize({
208
+ type: "error",
209
+ code: "engine_hung",
210
+ classification: "engine",
211
+ severity: "error",
212
+ correlationId: "",
213
+ message: `Engine subprocess hung past ${timeoutMs}ms timeout; SIGTERM/SIGKILL escalation invoked.`,
214
+ ...(tail !== undefined ? { stderrTail: tail } : {}),
215
+ retryable: false,
216
+ });
217
+ // Fire-and-forget: cancel races the next event-loop turn.
218
+ void this.cancel();
219
+ }, timeoutMs);
220
+ child.once("exit", (code, _signal) => {
221
+ clearTimeout(timeoutHandle);
222
+ if (finalized)
223
+ return;
224
+ const ev = parseRunOutput({
225
+ stdout: stdoutBuf,
226
+ stderr: stderrBuf,
227
+ exitCode: code ?? -1,
228
+ });
229
+ finalize(ev);
230
+ });
231
+ // Spawn failures (ENOENT, EACCES) emit 'error' before 'exit'. Treat them
232
+ // as transport-class failures; the test suite covers spawn-rejection at
233
+ // this seam (binary missing → typed AaaError-shaped DisplayEvent).
234
+ child.once("error", (err) => {
235
+ clearTimeout(timeoutHandle);
236
+ if (finalized)
237
+ return;
238
+ const tail = stderrTailOf(stderrBuf);
239
+ finalize({
240
+ type: "error",
241
+ code: "spawn_failed",
242
+ classification: "transport",
243
+ severity: "error",
244
+ correlationId: "",
245
+ message: `Failed to spawn engine subprocess (${err.code ?? "unknown"}): ${err.message}`,
246
+ ...(tail !== undefined ? { stderrTail: tail } : {}),
247
+ retryable: false,
248
+ });
249
+ });
250
+ // (ix) drain loop — yield activity events then the final event.
251
+ try {
252
+ // eslint-disable-next-line no-constant-condition
253
+ while (true) {
254
+ while (queue.length > 0) {
255
+ const item = queue.shift();
256
+ if ("_done" in item) {
257
+ return;
258
+ }
259
+ yield item;
260
+ }
261
+ await new Promise((resolve) => {
262
+ wake = resolve;
263
+ });
264
+ }
265
+ }
266
+ finally {
267
+ // (viii) cleanup ticker + spill file on every exit path.
268
+ clearInterval(ticker);
269
+ clearTimeout(timeoutHandle);
270
+ await cleanupSpillFile(this.mcpSpillPath);
271
+ this.mcpSpillPath = null;
272
+ }
273
+ }
274
+ /**
275
+ * Cancel the running subprocess via SIGTERM-then-SIGKILL on the whole
276
+ * process group (SC-B), then unlink any MCP spill file (CR-A).
277
+ *
278
+ * Idempotent: safe to call when the subprocess has already exited and safe
279
+ * to call when no spill file was created. Errors from `process.kill` are
280
+ * swallowed (`ESRCH` means the group is already gone).
281
+ */
282
+ async cancel() {
283
+ const child = this.subprocess;
284
+ if (child !== null &&
285
+ child.exitCode === null &&
286
+ child.signalCode === null &&
287
+ child.pid !== undefined) {
288
+ // detached:true on POSIX makes PID == PGID. Signal the negative pgid
289
+ // so every MCP child the engine launched receives the same signal.
290
+ const pgid = child.pid;
291
+ try {
292
+ process.kill(-pgid, "SIGTERM");
293
+ }
294
+ catch {
295
+ // ESRCH: group already dead — ignore.
296
+ }
297
+ await waitForExitOrTimeout(child, SIGKILL_GRACE_MS);
298
+ if (child.exitCode === null && child.signalCode === null) {
299
+ try {
300
+ process.kill(-pgid, "SIGKILL");
301
+ }
302
+ catch {
303
+ // ESRCH — ignore.
304
+ }
305
+ }
306
+ }
307
+ if (this.mcpSpillPath !== null) {
308
+ const path = this.mcpSpillPath;
309
+ this.mcpSpillPath = null;
310
+ await cleanupSpillFile(path);
311
+ }
312
+ }
313
+ /** Graceful shutdown — alias for `cancel()` (D3). */
314
+ async dispose() {
315
+ await this.cancel();
316
+ }
317
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Binary discovery, environment allowlist, and engine version probe.
3
+ *
4
+ * resolveBinaryPath() — find the amplifier-agent binary
5
+ * buildEnv() — filter subprocess env to a safe allowlist
6
+ * probeEngineVersion() — run `amplifier-agent version --json` and parse result
7
+ */
8
+ /** Variables always passed through to subprocess (exact name match). */
9
+ export declare const DEFAULT_ALLOWLIST: string[];
10
+ /**
11
+ * Environment variable names that are NEVER allowed in env.extra
12
+ * regardless of allowlist (design §4.12.1). These can be used to inject
13
+ * code into the subprocess (e.g. via shared-library preloading or Python
14
+ * import-path manipulation).
15
+ */
16
+ export declare const BLOCKED_ENV_KEYS: ReadonlySet<string>;
17
+ export interface ResolveBinaryPathOptions {
18
+ /** Environment to look up AMPLIFIER_AGENT_BIN from. Defaults to process.env. */
19
+ env?: Record<string, string | undefined>;
20
+ }
21
+ /**
22
+ * Resolve the path to the amplifier-agent binary.
23
+ *
24
+ * Resolution order:
25
+ * 1. AMPLIFIER_AGENT_BIN env var (if set and the path exists on disk)
26
+ * 2. `which amplifier-agent` via PATH lookup
27
+ *
28
+ * @throws Error with code 'binary_not_found' if neither path resolves.
29
+ */
30
+ export declare function resolveBinaryPath(opts?: ResolveBinaryPathOptions): string;
31
+ export interface BuildEnvOptions {
32
+ /** The caller's process environment (e.g. process.env). */
33
+ processEnv: Record<string, string | undefined>;
34
+ /**
35
+ * List of exact variable names that are allowed through.
36
+ * Variables with AMPLIFIER_ or LC_ prefixes are always included.
37
+ */
38
+ allowlist: string[];
39
+ /** Additional variables merged on top (override any allowlisted value). */
40
+ extra?: Record<string, string>;
41
+ }
42
+ /**
43
+ * Build the subprocess environment from the caller's process environment.
44
+ *
45
+ * Only variables whose name is in `allowlist`, starts with `AMPLIFIER_`,
46
+ * or starts with `LC_` are included. `extra` entries are merged last.
47
+ */
48
+ export declare function buildEnv(opts: BuildEnvOptions): Record<string, string>;
49
+ export interface EngineVersionPayload {
50
+ version: string;
51
+ protocolVersion: string;
52
+ bundleDigest?: string;
53
+ }
54
+ /**
55
+ * Run `<binPath> version --json` and parse the JSON response.
56
+ *
57
+ * @param binPath Absolute path to the amplifier-agent binary.
58
+ * @param env Environment to pass to the subprocess.
59
+ * @param timeoutMs Timeout in milliseconds (default: 5000).
60
+ */
61
+ export declare function probeEngineVersion(binPath: string, env: Record<string, string>, timeoutMs?: number): Promise<EngineVersionPayload>;