amplifier-agent-ts 0.5.0 → 0.6.1

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.
@@ -14,7 +14,7 @@ export interface AssembleArgvInput {
14
14
  sessionId: string;
15
15
  /** Final user prompt — emitted last as a positional argument. */
16
16
  prompt: string;
17
- /** Protocol version the wrapper speaks (e.g. "0.2.0"). */
17
+ /** Protocol version the wrapper speaks (e.g. "0.3.0"). */
18
18
  protocolVersion: string;
19
19
  /** When true, emit `--resume` instead of `--fresh`. */
20
20
  resume?: boolean;
@@ -22,6 +22,24 @@ export interface AssembleArgvInput {
22
22
  cwd?: string;
23
23
  /** Provider override; emits `--provider <providerOverride>`. */
24
24
  providerOverride?: string;
25
+ /**
26
+ * Path to the engine's host config file (Issue #1). Emits
27
+ * `--config <configPath>`. The engine's `single_turn` mode reads this
28
+ * to compose the host_config layer (approval mode, MCP servers,
29
+ * provider defaults, allowProtocolSkew, etc.) — see
30
+ * `src/amplifier_agent_cli/modes/single_turn.py` (`--config` option).
31
+ */
32
+ configPath?: string;
33
+ /**
34
+ * Approval-mode override forwarded to the engine (Issue #10). When set,
35
+ * emits `-y` (always allow) or `-n` (always deny). `"prompt"` is left
36
+ * implicit so the engine falls back to its host_config approval.mode
37
+ * or its TTY-based default.
38
+ *
39
+ * The wrapper unconditionally emits `-y` from older revisions has been
40
+ * removed — the caller now owns this policy decision.
41
+ */
42
+ approvalMode?: "yes" | "no" | "prompt";
25
43
  }
26
44
  /**
27
45
  * Build the argv array for `amplifier-agent run`.
@@ -37,10 +37,30 @@ export function assembleArgv(input) {
37
37
  if (input.providerOverride !== undefined) {
38
38
  argv.push("--provider", input.providerOverride);
39
39
  }
40
+ // Issue #1: surface the engine's --config flag.
41
+ if (input.configPath !== undefined) {
42
+ argv.push("--config", input.configPath);
43
+ }
40
44
  argv.push("--output", "json");
41
45
  argv.push("--protocol-version", input.protocolVersion);
42
- // SC-C: wrapper enforces auto-allow at the bundle layer.
43
- argv.push("-y");
46
+ // Issue #10: approval policy is now caller-controlled.
47
+ // - "yes" -> -y (always allow)
48
+ // - "no" -> -n (always deny)
49
+ // - "prompt" -> emit nothing; engine falls back to host_config.approval.mode
50
+ // or the bundle's TTY-based default. This is the only way to
51
+ // defer to the engine's policy resolution.
52
+ // - undefined -> preserve historical default (-y) so existing callers
53
+ // who haven't opted into the approval API are unaffected.
54
+ const mode = input.approvalMode;
55
+ if (mode === "yes" || mode === undefined) {
56
+ argv.push("-y");
57
+ }
58
+ else if (mode === "no") {
59
+ argv.push("-n");
60
+ }
61
+ else {
62
+ // mode === "prompt": deliberately emit no flag.
63
+ }
44
64
  // Prompt is the final positional argument.
45
65
  argv.push(input.prompt);
46
66
  return argv;
package/dist/index.d.ts CHANGED
@@ -11,16 +11,49 @@ export { AaaError, SessionHandle } from "./session.js";
11
11
  export type { DisplayEvent, EngineInfo, SessionHandleParams, } from "./session.js";
12
12
  export type { ApprovalResponse } from "./approval.js";
13
13
  export type { EngineVersionPayload } from "./spawn.js";
14
+ /** @public */
15
+ export { assembleArgv } from "./argv-builder.js";
16
+ /** @public */
17
+ export type { AssembleArgvInput } from "./argv-builder.js";
18
+ /** @public */
19
+ export { resolveMcpConfigPath, cleanupSpillFile } from "./mcp-spill.js";
20
+ /** @public */
21
+ export type { McpSpillResult } from "./mcp-spill.js";
22
+ /** @public */
23
+ export { resolveBinaryPath, buildEnv, probeEngineVersion, DEFAULT_ALLOWLIST, BLOCKED_ENV_KEYS, } from "./spawn.js";
24
+ /** @public */
25
+ export type { ResolveBinaryPathOptions, BuildEnvOptions, } from "./spawn.js";
26
+ /** @public */
27
+ export { Transport, parseNdjsonStream } from "./transport.js";
28
+ /** @public */
29
+ export type { TransportOptions, ExitInfo, ParseNdjsonStreamOptions, } from "./transport.js";
30
+ /** @public */
31
+ export { checkProtocolVersion } from "./version.js";
32
+ /** @public */
33
+ export type { VersionCheckResult, VersionCheckOk, VersionCheckFail, CheckProtocolVersionOptions, } from "./version.js";
34
+ /** @public */
35
+ export { parseRunOutput, STDERR_TAIL_BYTES } from "./run-output-parser.js";
36
+ /** @public */
37
+ export type { SubprocessOutcome } from "./run-output-parser.js";
38
+ /** @public */
39
+ export { makeApprovalHandler } from "./approval.js";
40
+ /** @public */
41
+ export type { ApprovalAdapter, ApprovalRequest, ApprovalHandler, } from "./approval.js";
14
42
  import { SessionHandle } from "./session.js";
15
- import type { DisplayEvent } from "./session.js";
43
+ import type { DisplayEvent, ChildProcessFactory } from "./session.js";
16
44
  import type { ApprovalResponse } from "./approval.js";
17
45
  import type { McpServerConfig } from "./types.js";
18
46
  export type { McpServerConfig } from "./types.js";
47
+ /** @public */
48
+ export type { ChildProcessFactory } from "./session.js";
19
49
  /**
20
50
  * The protocol version that this TypeScript wrapper requires.
21
- * Forwarded to the engine via `--protocol-version` on every `submit()`.
51
+ * Forwarded to the engine via `--protocol-version` on every `submit()` and
52
+ * checked at `spawnAgent()` time against the engine's reported protocol
53
+ * version (see Issue #9 — `checkProtocolVersion()` is wired into the init
54
+ * path so skew fails fast wrapper-side before any subprocess spawn).
22
55
  */
23
- export declare const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.2.0";
56
+ export declare const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.3.0";
24
57
  /** Parameters for spawnAgent(). Signature is locked verbatim by design §8.2. */
25
58
  export interface SpawnAgentParams {
26
59
  /** 'burst' reserved; throws AaaError(lifecycle_unsupported) at runtime. */
@@ -34,15 +67,35 @@ export interface SpawnAgentParams {
34
67
  };
35
68
  providerOverride?: string;
36
69
  /**
37
- * Mid-turn approval callback.
70
+ * Approval policy (Issue #10).
38
71
  *
39
- * **NOT SUPPORTED IN v1.** Passing a non-null `onRequest` throws
40
- * `AaaError(approval_not_supported_in_v1)` at spawnAgent() time. The v1 wire
41
- * is Mode A (per-turn subprocess); there is no mid-turn host channel.
72
+ * Two shapes are accepted:
73
+ *
74
+ * 1. `{ mode: 'yes' | 'no' | 'prompt' }` — the static-policy shape.
75
+ * Maps to engine argv:
76
+ * - `'yes'` → `-y` (auto-allow every tool call)
77
+ * - `'no'` → `-n` (auto-deny every tool call)
78
+ * - `'prompt'` → emit no flag; the engine falls back to
79
+ * `host_config.approval.mode` or the bundle's
80
+ * TTY-based default. This is how a host hands
81
+ * policy resolution back to the engine.
82
+ *
83
+ * Engine compatibility: requires `amplifier-agent >= 0.4.0`
84
+ * (PR #34 added `host_config.approval.mode`).
85
+ *
86
+ * 2. `{ onRequest, timeoutMs }` — the legacy mid-turn callback shape.
87
+ * **NOT SUPPORTED IN v1.** Passing a non-null `onRequest` still
88
+ * throws `AaaError(approval_not_supported_in_v1)`. The v1 wire has
89
+ * no mid-turn host channel.
90
+ *
91
+ * When unset, the wrapper defaults to `mode: 'yes'` for backward
92
+ * compatibility with pre-0.6 behaviour (the wrapper unconditionally
93
+ * emitted `-y`).
42
94
  */
43
95
  approval?: {
44
- onRequest: (req: unknown) => Promise<ApprovalResponse>;
45
- timeoutMs: number;
96
+ mode?: "yes" | "no" | "prompt";
97
+ onRequest?: (req: unknown) => Promise<ApprovalResponse>;
98
+ timeoutMs?: number;
46
99
  };
47
100
  display?: {
48
101
  onEvent?: (event: DisplayEvent) => void;
@@ -58,8 +111,53 @@ export interface SpawnAgentParams {
58
111
  mcpServers?: Record<string, McpServerConfig>;
59
112
  /** Per-submit timeout in ms (default: 10 minutes). */
60
113
  timeoutMs?: number;
114
+ /**
115
+ * Path to a host config file (Issue #1). Forwarded to the engine via
116
+ * `--config <configPath>` so the engine's host_config layer
117
+ * (approval mode, MCP servers, provider defaults,
118
+ * `allowProtocolSkew`, etc.) is composed from the file the host
119
+ * already manages.
120
+ *
121
+ * Mirrors the engine's `single_turn --config` flag (engine PR #27 /
122
+ * v0.4.0). When unset, the engine's resolution order applies (env
123
+ * `AMPLIFIER_AGENT_CONFIG`, then `~/.config/amplifier-agent/host_config.json`).
124
+ *
125
+ * @public
126
+ */
127
+ configPath?: string;
128
+ /**
129
+ * Bypass the wrapper-side protocol-version check (Issue #9).
130
+ *
131
+ * Default `false`: `spawnAgent()` probes the engine's protocol version once
132
+ * during initialization and rejects with `AaaError(protocol_version_mismatch)`
133
+ * when it differs from `PROTOCOL_VERSION_REQUIRED_BY_WRAPPER`. Setting this to
134
+ * `true` skips the check and lets the engine run regardless — useful for
135
+ * exploratory work against pre-release engine versions, but unsafe by default.
136
+ *
137
+ * Mirrors the engine-side `host_config.allowProtocolSkew` knob.
138
+ */
139
+ allowProtocolSkew?: boolean;
61
140
  /** Replaces the real resolveBinaryPath() call. */
62
141
  _binaryResolver?: () => string;
142
+ /**
143
+ * Replaces the real probeEngineVersion() call (Issue #9 + #7). When set,
144
+ * `spawnAgent()` invokes this factory instead of spawning
145
+ * `<binaryPath> version --json`. Reserved for tests and host-side stubs.
146
+ */
147
+ _engineVersionProbe?: () => Promise<{
148
+ version: string;
149
+ protocolVersion: string;
150
+ bundleDigest?: string;
151
+ }>;
152
+ /**
153
+ * Override the subprocess factory used inside `SessionHandle.submit()`
154
+ * (Issue #3). When set, the wrapper invokes this factory in place of
155
+ * `child_process.spawn`. Useful for sandboxing, harness wrapping, or
156
+ * test doubles.
157
+ *
158
+ * @public
159
+ */
160
+ runChildProcess?: ChildProcessFactory;
63
161
  }
64
162
  /**
65
163
  * Compose all internal components into the single public entry point.
package/dist/index.js CHANGED
@@ -9,14 +9,49 @@
9
9
  */
10
10
  // Re-export public types and classes from sub-modules.
11
11
  export { AaaError, SessionHandle } from "./session.js";
12
+ // ---------------------------------------------------------------------------
13
+ // Public re-exports of wrapper internals (Issue #5).
14
+ //
15
+ // These helpers and their associated types are part of the wrapper's
16
+ // supported public surface. They are useful to host authors who want to:
17
+ // - Inspect the argv the wrapper would emit (`assembleArgv`)
18
+ // - Inject their own subprocess factory (`runChildProcess` + spawn helpers)
19
+ // - Probe the engine binary themselves (`resolveBinaryPath`,
20
+ // `probeEngineVersion`, `buildEnv`)
21
+ // - Drive the NDJSON event pipeline manually (`Transport`,
22
+ // `parseNdjsonStream`)
23
+ // - Reuse the same protocol-version comparison the wrapper uses
24
+ // (`checkProtocolVersion`)
25
+ // - Parse a captured run-output payload (`parseRunOutput`)
26
+ //
27
+ // All exports below are annotated `@public` in their defining module.
28
+ // ---------------------------------------------------------------------------
29
+ /** @public */
30
+ export { assembleArgv } from "./argv-builder.js";
31
+ /** @public */
32
+ export { resolveMcpConfigPath, cleanupSpillFile } from "./mcp-spill.js";
33
+ /** @public */
34
+ export { resolveBinaryPath, buildEnv, probeEngineVersion, DEFAULT_ALLOWLIST, BLOCKED_ENV_KEYS, } from "./spawn.js";
35
+ /** @public */
36
+ export { Transport, parseNdjsonStream } from "./transport.js";
37
+ /** @public */
38
+ export { checkProtocolVersion } from "./version.js";
39
+ /** @public */
40
+ export { parseRunOutput, STDERR_TAIL_BYTES } from "./run-output-parser.js";
41
+ /** @public */
42
+ export { makeApprovalHandler } from "./approval.js";
12
43
  // Internal imports used by spawnAgent().
13
44
  import { AaaError, SessionHandle } from "./session.js";
14
- import { resolveBinaryPath, buildEnv, DEFAULT_ALLOWLIST } from "./spawn.js";
45
+ import { resolveBinaryPath, buildEnv, probeEngineVersion, DEFAULT_ALLOWLIST, } from "./spawn.js";
46
+ import { checkProtocolVersion } from "./version.js";
15
47
  /**
16
48
  * The protocol version that this TypeScript wrapper requires.
17
- * Forwarded to the engine via `--protocol-version` on every `submit()`.
49
+ * Forwarded to the engine via `--protocol-version` on every `submit()` and
50
+ * checked at `spawnAgent()` time against the engine's reported protocol
51
+ * version (see Issue #9 — `checkProtocolVersion()` is wired into the init
52
+ * path so skew fails fast wrapper-side before any subprocess spawn).
18
53
  */
19
- export const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.2.0";
54
+ export const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.3.0";
20
55
  // ---------------------------------------------------------------------------
21
56
  // spawnAgent() — locked public entry point (Mode A v2)
22
57
  // ---------------------------------------------------------------------------
@@ -39,13 +74,23 @@ export async function spawnAgent(params) {
39
74
  // SC-C: reject mid-turn approval callback before any other work. The Mode A
40
75
  // wire has no mid-turn request channel; warning-only acceptance would ship
41
76
  // silent auto-allow to a host author who believed their callback was wired.
77
+ // Issue #10: `approval.mode` is the supported policy hook in v1; `onRequest`
78
+ // remains unsupported until a mid-turn channel returns (track WG-4).
42
79
  if (params.approval?.onRequest !== undefined) {
43
80
  throw new AaaError("approval_not_supported_in_v1", "Mid-turn approval callbacks (params.approval.onRequest) are not supported in v1. " +
44
- "The Mode A wire has no mid-turn request channel. The bundle's hooks-approval mount " +
45
- "is the v1 policy point — auto-approve by default, configurable per-tool via the " +
46
- "bundle's hooks-approval default-mode and gating settings. To customize approval " +
47
- "policy in v1, configure the bundle; do not pass an onRequest callback. " +
48
- "Mid-turn callbacks will return in v1.x — track WG-4 in amendment §6.", { classification: "protocol", severity: "error" });
81
+ "The Mode A wire has no mid-turn request channel. Use the static-policy shape " +
82
+ "`approval: { mode: 'yes' | 'no' | 'prompt' }` instead — it maps to engine argv " +
83
+ "(`-y` / `-n`) and to `host_config.approval.mode`. Mid-turn callbacks will return " +
84
+ "in v1.x — track WG-4 in amendment §6.", { classification: "protocol", severity: "error" });
85
+ }
86
+ // Issue #10: validate the static-policy shape if present.
87
+ let approvalModeArg;
88
+ if (params.approval?.mode !== undefined) {
89
+ const m = params.approval.mode;
90
+ if (m !== "yes" && m !== "no" && m !== "prompt") {
91
+ throw new AaaError("invalid_approval_mode", `params.approval.mode must be 'yes', 'no', or 'prompt' (got ${JSON.stringify(m)})`, { classification: "protocol", severity: "error" });
92
+ }
93
+ approvalModeArg = m;
49
94
  }
50
95
  // 1. Lifecycle guard (D10).
51
96
  if (params.lifecycle !== "one-shot") {
@@ -76,7 +121,48 @@ export async function spawnAgent(params) {
76
121
  allowlist,
77
122
  extra,
78
123
  });
79
- // 4. Return a SessionHandle. NO subprocess spawned here — the engine is
124
+ // 4. Issue #9: probe the engine binary for its protocol version and run
125
+ // `checkProtocolVersion()` BEFORE constructing a SessionHandle. This is
126
+ // a single `amplifier-agent version --json` roundtrip during init — far
127
+ // cheaper than discovering a mismatch on the first `submit()` after the
128
+ // engine has done its full bundle-load dance. The probe result is also
129
+ // cached on the handle for `getEngineInfo()` (Issue #7).
130
+ //
131
+ // Callers can:
132
+ // - Inject a synthetic probe via `_engineVersionProbe` (tests).
133
+ // - Bypass the check entirely with `allowProtocolSkew: true`.
134
+ let engineVersionPayload;
135
+ try {
136
+ if (params._engineVersionProbe) {
137
+ engineVersionPayload = await params._engineVersionProbe();
138
+ }
139
+ else {
140
+ engineVersionPayload = await probeEngineVersion(binaryPath, subprocessEnv);
141
+ }
142
+ }
143
+ catch (e) {
144
+ // Probe failure is non-fatal when skew is allowed: fall back to empty
145
+ // metadata. Otherwise surface it as a typed error.
146
+ if (params.allowProtocolSkew === true) {
147
+ engineVersionPayload = { version: "", protocolVersion: "" };
148
+ }
149
+ else {
150
+ const msg = e.message ?? "engine version probe failed";
151
+ throw new AaaError("engine_probe_failed", `Could not probe engine binary at ${binaryPath} for protocol version: ${msg}`, { classification: "transport", severity: "error" });
152
+ }
153
+ }
154
+ const check = checkProtocolVersion({
155
+ wrapper: PROTOCOL_VERSION_REQUIRED_BY_WRAPPER,
156
+ engine: engineVersionPayload.protocolVersion,
157
+ allowSkew: params.allowProtocolSkew === true,
158
+ });
159
+ if (!check.ok) {
160
+ throw new AaaError(check.code, check.remediation, {
161
+ classification: "protocol",
162
+ severity: "error",
163
+ });
164
+ }
165
+ // 5. Return a SessionHandle. NO subprocess spawned here — the engine is
80
166
  // launched per submit() (amendment §5.2). Skew override now lives in
81
167
  // `host_config.allowProtocolSkew: true` in the host config file (engine
82
168
  // PR #27); the wrapper no longer forwards an argv flag for it.
@@ -92,5 +178,20 @@ export async function spawnAgent(params) {
92
178
  : {}),
93
179
  protocolVersion: PROTOCOL_VERSION_REQUIRED_BY_WRAPPER,
94
180
  ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),
181
+ ...(params.runChildProcess !== undefined
182
+ ? { runChildProcess: params.runChildProcess }
183
+ : {}),
184
+ // Issue #1: forward host config path so assembleArgv can emit
185
+ // --config <path>.
186
+ ...(params.configPath !== undefined ? { configPath: params.configPath } : {}),
187
+ // Issue #10: forward the validated approval mode so assembleArgv can
188
+ // emit -y / -n / nothing.
189
+ ...(approvalModeArg !== undefined ? { approvalMode: approvalModeArg } : {}),
190
+ // Issue #4: thread display.onEvent through so SessionHandle can
191
+ // dispatch parsed NDJSON wire events to it.
192
+ ...(params.display !== undefined ? { display: params.display } : {}),
193
+ // Issue #7: persist engine metadata resolved during the probe.
194
+ engineVersion: engineVersionPayload.version,
195
+ bundleDigest: engineVersionPayload.bundleDigest ?? "",
95
196
  });
96
197
  }
package/dist/session.d.ts CHANGED
@@ -22,8 +22,22 @@
22
22
  * file created on this turn (CR-A cleanup).
23
23
  * - `dispose()` is a synonym for `cancel()`.
24
24
  */
25
- import type { ChildProcess } from "node:child_process";
25
+ import type { ChildProcess, SpawnOptions } from "node:child_process";
26
26
  import type { McpServerConfig } from "./types.js";
27
+ /**
28
+ * Factory function compatible with the surface of `child_process.spawn`
29
+ * that `SessionHandle` calls. Hosts can supply this via
30
+ * `SpawnAgentParams.runChildProcess` (Issue #3) to substitute their own
31
+ * subprocess factory — useful for sandboxing, harness wrapping, or test
32
+ * doubles.
33
+ *
34
+ * The factory is invoked exactly once per `submit()` with the resolved
35
+ * binary path, the assembled argv array, and the spawn options the wrapper
36
+ * would have used (including `detached`, `stdio`, `env`, and optional `cwd`).
37
+ *
38
+ * @public
39
+ */
40
+ export type ChildProcessFactory = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;
27
41
  /**
28
42
  * A display event yielded by `SessionHandle.submit()`.
29
43
  *
@@ -49,6 +63,23 @@ export type DisplayEvent = {
49
63
  message: string;
50
64
  stderrTail?: string;
51
65
  retryable: boolean;
66
+ }
67
+ /**
68
+ * Wire-protocol notification dispatched from the engine's stderr NDJSON
69
+ * stream (Issue #2 / #6). One of the 9 wire event types the engine
70
+ * emits: progress, result/delta, result/final, thinking/delta,
71
+ * thinking/final, tool/started, tool/completed, approval/request,
72
+ * approval/timeout, plus the wire-level error notification.
73
+ *
74
+ * `method` is the JSON-RPC method name verbatim from the wire envelope
75
+ * (e.g. `"progress"`, `"tool/started"`). `params` is the raw payload
76
+ * dictionary the engine emitted, unaltered. Callers may narrow on
77
+ * `method` and cast `params` to a typed shape from `./types.ts`.
78
+ */
79
+ | {
80
+ type: "notification";
81
+ method: string;
82
+ params: unknown;
52
83
  };
53
84
  /** Typed error for AaA wrapper lifecycle and protocol violations. */
54
85
  export declare class AaaError extends Error {
@@ -98,10 +129,43 @@ export interface SessionHandleParams {
98
129
  mcpServers?: Record<string, McpServerConfig>;
99
130
  /** Provider override forwarded via `--provider`. */
100
131
  providerOverride?: string;
101
- /** Protocol version the wrapper speaks (e.g. "0.2.0"). */
132
+ /**
133
+ * Path to the engine's host config file (Issue #1). Forwarded to the
134
+ * engine via `--config <configPath>`. See the engine's
135
+ * `single_turn` mode for the resolved-precedence rules between argv
136
+ * flags, host_config, and the bundle's TTY-based default.
137
+ */
138
+ configPath?: string;
139
+ /**
140
+ * Approval mode override (Issue #10). Maps to engine argv:
141
+ * `"yes" -> -y`, `"no" -> -n`, `"prompt" -> emit nothing` so the engine
142
+ * falls back to `host_config.approval.mode` or its bundle/TTY default.
143
+ * Undefined preserves the historical default (`-y`) for callers that
144
+ * have not opted into the approval API.
145
+ */
146
+ approvalMode?: "yes" | "no" | "prompt";
147
+ /** Protocol version the wrapper speaks (e.g. "0.3.0"). */
102
148
  protocolVersion: string;
103
149
  /** Per-submit timeout in milliseconds. Defaults to 10 minutes. */
104
150
  timeoutMs?: number;
151
+ /**
152
+ * Optional override for the subprocess factory (Issue #3). When set, the
153
+ * handle invokes this function instead of `child_process.spawn`.
154
+ */
155
+ runChildProcess?: ChildProcessFactory;
156
+ /**
157
+ * Display sink (Issue #4). When set, every parsed NDJSON wire-event from
158
+ * the engine subprocess's stderr stream is dispatched here, in addition
159
+ * to whatever the iterator yields. Pass-through from
160
+ * `SpawnAgentParams.display`.
161
+ */
162
+ display?: {
163
+ onEvent?: (event: DisplayEvent) => void;
164
+ };
165
+ /** Engine metadata resolved at spawnAgent() time (Issue #7). */
166
+ engineVersion?: string;
167
+ /** Bundle digest resolved at spawnAgent() time (Issue #7). */
168
+ bundleDigest?: string;
105
169
  }
106
170
  /**
107
171
  * Wait for `child` to fire `exit`, or `ms` to elapse — whichever first.
package/dist/session.js CHANGED
@@ -26,6 +26,7 @@ import { spawn as childSpawn } from "node:child_process";
26
26
  import { assembleArgv } from "./argv-builder.js";
27
27
  import { resolveMcpConfigPath, cleanupSpillFile } from "./mcp-spill.js";
28
28
  import { parseRunOutput, STDERR_TAIL_BYTES } from "./run-output-parser.js";
29
+ import { parseNdjsonStream } from "./transport.js";
29
30
  /** Typed error for AaA wrapper lifecycle and protocol violations. */
30
31
  export class AaaError extends Error {
31
32
  code;
@@ -95,11 +96,13 @@ export class SessionHandle {
95
96
  this.engineInfo = {
96
97
  binaryPath: params.binaryPath,
97
98
  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: "",
99
+ // Issue #7: engineVersion + bundleDigest are populated from the engine
100
+ // version probe that spawnAgent() runs during initialization (Issue #9).
101
+ // Falls back to empty strings when the engine omits a field (e.g. the
102
+ // `version --json` payload does not include bundleDigest until a future
103
+ // engine release ships an admin endpoint exposing it).
104
+ engineVersion: params.engineVersion ?? "",
105
+ bundleDigest: params.bundleDigest ?? "",
103
106
  };
104
107
  }
105
108
  /** Return resolved engine metadata (D5). */
@@ -147,7 +150,9 @@ export class SessionHandle {
147
150
  this.mcpSpillPath = spill.configPath;
148
151
  // (iii) build argv (pure function — no I/O). The MCP config path is
149
152
  // forwarded to the engine via AMPLIFIER_MCP_CONFIG (subprocess env)
150
- // rather than via an argv flag.
153
+ // rather than via an argv flag. `configPath` (Issue #1) and
154
+ // `approvalMode` (Issue #10) are forwarded via argv flags emitted
155
+ // by assembleArgv.
151
156
  const argv = assembleArgv({
152
157
  sessionId: this.params.sessionId,
153
158
  prompt,
@@ -155,6 +160,8 @@ export class SessionHandle {
155
160
  resume: this.params.resume,
156
161
  cwd: this.params.cwd,
157
162
  providerOverride: this.params.providerOverride,
163
+ configPath: this.params.configPath,
164
+ approvalMode: this.params.approvalMode,
158
165
  });
159
166
  // Build the subprocess env. When we spilled an MCP config, set
160
167
  // AMPLIFIER_MCP_CONFIG so tool-mcp reads it natively via its
@@ -167,7 +174,12 @@ export class SessionHandle {
167
174
  subprocessEnv.AMPLIFIER_MCP_CONFIG = spill.configPath;
168
175
  }
169
176
  // (iv) SC-B: spawn detached → new session group → PID == PGID.
170
- const child = childSpawn(this.params.binaryPath, argv, {
177
+ // Issue #3: when the caller provided a `runChildProcess` factory, use it
178
+ // in place of `child_process.spawn`. The factory must satisfy the
179
+ // ChildProcessFactory contract (same signature surface SessionHandle
180
+ // requires).
181
+ const spawnFn = this.params.runChildProcess ?? childSpawn;
182
+ const child = spawnFn(this.params.binaryPath, argv, {
171
183
  detached: true,
172
184
  stdio: ["ignore", "pipe", "pipe"],
173
185
  env: subprocessEnv,
@@ -180,9 +192,32 @@ export class SessionHandle {
180
192
  child.stdout?.on("data", (chunk) => {
181
193
  stdoutBuf += typeof chunk === "string" ? chunk : chunk.toString("utf-8");
182
194
  });
183
- child.stderr?.on("data", (chunk) => {
184
- stderrBuf += typeof chunk === "string" ? chunk : chunk.toString("utf-8");
185
- });
195
+ // Issue #2 / #6: wire `parseNdjsonStream` onto the child's stderr. The
196
+ // engine emits one JSON object per line for each wire-protocol
197
+ // notification (progress, result/delta, tool/started, etc.).
198
+ // - JSON lines are parsed into `notification` DisplayEvents and
199
+ // dispatched to `params.display?.onEvent` (Issue #4).
200
+ // - Non-JSON lines are accumulated into `stderrBuf` so the
201
+ // stderrTail surface on parseRunOutput stays useful for
202
+ // diagnostic snapshots.
203
+ // - JSON lines are also appended to `stderrBuf` verbatim, so a
204
+ // crash-time tail still contains the wire-event context.
205
+ const displayOnEvent = this.params.display?.onEvent;
206
+ if (child.stderr) {
207
+ void parseNdjsonStream(child.stderr, {
208
+ onJson: (obj) => {
209
+ stderrBuf += JSON.stringify(obj) + "\n";
210
+ if (displayOnEvent) {
211
+ const method = typeof obj.method === "string" ? obj.method : "unknown";
212
+ const params = "params" in obj ? obj.params : obj;
213
+ displayOnEvent({ type: "notification", method, params });
214
+ }
215
+ },
216
+ onNonJson: (line) => {
217
+ stderrBuf += line + "\n";
218
+ },
219
+ });
220
+ }
186
221
  const queue = [];
187
222
  let wake = null;
188
223
  const push = (item) => {
@@ -11,6 +11,7 @@
11
11
  *
12
12
  * No JSON-RPC semantics here — that is Task 6.
13
13
  */
14
+ import type { Readable } from "node:stream";
14
15
  export interface TransportOptions {
15
16
  /** Command to spawn (e.g. "cat", "sh"). */
16
17
  command: string;
@@ -35,6 +36,44 @@ export interface ExitInfo {
35
36
  /** Signal name if the process was killed by a signal, otherwise null. */
36
37
  signal: string | null;
37
38
  }
39
+ /**
40
+ * Options for {@link parseNdjsonStream}.
41
+ *
42
+ * @public
43
+ */
44
+ export interface ParseNdjsonStreamOptions {
45
+ /**
46
+ * Invoked once per line that parses cleanly as JSON. Failures in the
47
+ * callback are NOT caught — the caller is responsible for not throwing
48
+ * inside the dispatcher.
49
+ */
50
+ onJson: (obj: Record<string, unknown>) => void;
51
+ /**
52
+ * Invoked once per line that does NOT parse as JSON (e.g. plain stderr
53
+ * text, partial frames). The line is delivered verbatim without the
54
+ * trailing newline. Default: silently drop the line.
55
+ */
56
+ onNonJson?: (line: string) => void;
57
+ }
58
+ /**
59
+ * Consume an NDJSON stream line-by-line, dispatching each parseable JSON
60
+ * line to `onJson` and each non-JSON line to `onNonJson` (or silently
61
+ * dropping it).
62
+ *
63
+ * Implements the same parsing model that {@link Transport} uses internally,
64
+ * but exposed as a standalone helper so SessionHandle can wire it onto
65
+ * the engine subprocess's stderr stream without owning the spawn.
66
+ *
67
+ * **Wire contract:** the engine emits one JSON object per line on stderr
68
+ * for each wire-protocol notification (Issue #2 / #6). Each parsed object
69
+ * is delivered verbatim to `onJson`; the caller decides how to interpret
70
+ * the `method`/`params` shape.
71
+ *
72
+ * Returns a Promise that resolves when the underlying stream emits `end`.
73
+ *
74
+ * @public
75
+ */
76
+ export declare function parseNdjsonStream(stream: Readable, options: ParseNdjsonStreamOptions): Promise<void>;
38
77
  export declare class Transport {
39
78
  private readonly opts;
40
79
  private proc;
package/dist/transport.js CHANGED
@@ -13,6 +13,50 @@
13
13
  */
14
14
  import { spawn } from "node:child_process";
15
15
  import { createInterface } from "node:readline";
16
+ /**
17
+ * Consume an NDJSON stream line-by-line, dispatching each parseable JSON
18
+ * line to `onJson` and each non-JSON line to `onNonJson` (or silently
19
+ * dropping it).
20
+ *
21
+ * Implements the same parsing model that {@link Transport} uses internally,
22
+ * but exposed as a standalone helper so SessionHandle can wire it onto
23
+ * the engine subprocess's stderr stream without owning the spawn.
24
+ *
25
+ * **Wire contract:** the engine emits one JSON object per line on stderr
26
+ * for each wire-protocol notification (Issue #2 / #6). Each parsed object
27
+ * is delivered verbatim to `onJson`; the caller decides how to interpret
28
+ * the `method`/`params` shape.
29
+ *
30
+ * Returns a Promise that resolves when the underlying stream emits `end`.
31
+ *
32
+ * @public
33
+ */
34
+ export function parseNdjsonStream(stream, options) {
35
+ return new Promise((resolve, reject) => {
36
+ const rl = createInterface({ input: stream });
37
+ rl.on("line", (line) => {
38
+ const trimmed = line.trim();
39
+ if (trimmed.length === 0)
40
+ return;
41
+ try {
42
+ const obj = JSON.parse(trimmed);
43
+ if (typeof obj === "object" && obj !== null) {
44
+ options.onJson(obj);
45
+ }
46
+ else if (options.onNonJson) {
47
+ // JSON-parseable but not an object (e.g. a bare number/string).
48
+ options.onNonJson(line);
49
+ }
50
+ }
51
+ catch {
52
+ if (options.onNonJson)
53
+ options.onNonJson(line);
54
+ }
55
+ });
56
+ rl.on("close", () => resolve());
57
+ stream.on("error", (err) => reject(err));
58
+ });
59
+ }
16
60
  export class Transport {
17
61
  opts;
18
62
  proc = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "amplifier-agent-ts",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "TypeScript SDK for the Amplifier agent. Spawns and drives the amplifier-agent Python CLI over a stdio protocol.",
5
5
  "type": "module",
6
6
  "exports": {