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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # amplifier-agent-ts
2
+
3
+ TypeScript SDK for the [Amplifier agent](https://github.com/microsoft/amplifier-agent). Spawns and drives the `amplifier-agent` Python CLI over a stdio protocol.
4
+
5
+ > **Two packages, related but distinct.** This is the npm package, named `amplifier-agent-ts`. The Python engine it spawns is a separate package on PyPI named `amplifier-agent`. You need **both** for the SDK to work:
6
+ > - `npm install amplifier-agent-ts` — this package, the TypeScript SDK
7
+ > - `uv tool install amplifier-agent` (or `pip install amplifier-agent`) — the Python engine
8
+
9
+ ## What this is
10
+
11
+ ```
12
+ ┌─────────────────────────────────────────┐
13
+ │ Your Node.js application │
14
+ │ import { spawnAgent } │
15
+ │ from 'amplifier-agent-ts' │
16
+ └─────────────────┬───────────────────────┘
17
+ │ child_process.spawn
18
+ │ + NDJSON over stdio
19
+ ▼
20
+ ┌─────────────────────────────────────────┐
21
+ │ amplifier-agent (Python CLI) │
22
+ │ - All AI inference │
23
+ │ - All tool execution │
24
+ │ - All session state │
25
+ └─────────────────────────────────────────┘
26
+ ```
27
+
28
+ This SDK is a thin process supervisor. It resolves the engine binary, builds a subprocess environment, validates parameters, and exposes a `SessionHandle` whose `submit()` method launches the engine per turn (Mode A). All inference, tool execution, and session state live in the Python engine — not here.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ npm install amplifier-agent-ts
34
+ ```
35
+
36
+ This SDK has **zero npm runtime dependencies**. You also need the Python engine on your system — see [Runtime requirements](#runtime-requirements).
37
+
38
+ ## Quick start
39
+
40
+ ```typescript
41
+ import { spawnAgent, AaaError } from 'amplifier-agent-ts';
42
+ import { randomUUID } from 'node:crypto';
43
+
44
+ const session = await spawnAgent({
45
+ lifecycle: 'one-shot',
46
+ sessionId: randomUUID(),
47
+ });
48
+
49
+ try {
50
+ // The engine is launched per submit() (Mode A v2).
51
+ // See SessionHandle in dist/index.d.ts for the full submit() signature.
52
+ const result = await session.submit({ prompt: 'Hello, agent.' });
53
+ console.log(result.reply);
54
+ } catch (err) {
55
+ if (err instanceof AaaError) {
56
+ console.error(`[${err.code}] ${err.message}`);
57
+ } else {
58
+ throw err;
59
+ }
60
+ }
61
+ ```
62
+
63
+ For the full public API, see the type definitions in `dist/index.d.ts` and the source at [`src/index.ts`](https://github.com/microsoft/amplifier-agent/blob/main/wrappers/typescript/src/index.ts).
64
+
65
+ ## Runtime requirements
66
+
67
+ | Requirement | Why |
68
+ |---|---|
69
+ | Node.js ≥20 | The SDK uses `node:child_process` and `node:readline` |
70
+ | `amplifier-agent` Python CLI on PATH | The SDK spawns this binary on every `submit()` |
71
+ | Network access to `github.com` | The engine resolves agent modules from `git+https://` URLs at first invocation and per-run for the active provider |
72
+ | `@types/node` (TypeScript consumers only) | Not declared as a peer dependency to avoid install warnings, but required to compile against this package's `.d.ts`. Most TypeScript projects already have it. |
73
+
74
+ ### Installing the Python engine
75
+
76
+ ```bash
77
+ # Recommended
78
+ uv tool install amplifier-agent
79
+
80
+ # Or pip
81
+ pip install amplifier-agent
82
+ ```
83
+
84
+ The engine is a Rust/Python hybrid built with PyO3 + maturin. On standard platforms (Linux x86_64, Linux aarch64, macOS arm64, Windows x64), pre-built wheels are downloaded automatically from PyPI — **no Rust toolchain required**. On platforms without a matching wheel (Alpine/musl, FreeBSD, exotic architectures), installation falls back to source and requires `rustc 1.70+` and `maturin`.
85
+
86
+ The SDK looks for the binary via `which amplifier-agent`, or you can set `AMPLIFIER_AGENT_BIN` to an absolute path.
87
+
88
+ ### Network access
89
+
90
+ The Amplifier engine resolves agent modules from git URLs in the bundle manifest. On first invocation it clones and installs ~11 modules; on every invocation it injects the active provider module (anthropic / openai / azure-openai / ollama) from a `git+https://` URL. **Fully air-gapped environments are not supported today.** Network access to `github.com` is required at least on first run and remains required for provider module resolution on subsequent runs.
91
+
92
+ ## Version coupling
93
+
94
+ This SDK speaks **Amplifier protocol version 0.1.0**, exported as `PROTOCOL_VERSION_REQUIRED_BY_WRAPPER` and forwarded to the engine via `--protocol-version` on every `submit()`. The engine rejects protocol mismatches unless you opt out with `allowProtocolSkew: true`.
95
+
96
+ The SDK is also coupled to the engine's argv surface and stdout envelope schema. **Treat the SDK and engine as a coupled pair**: a major engine update may require a major SDK update. Pin both in your application.
97
+
98
+ ## License
99
+
100
+ MIT. See `LICENSE`.
101
+
102
+ ## Repository, issues, contributing
103
+
104
+ - Repository: https://github.com/microsoft/amplifier-agent (monorepo; SDK source is in `wrappers/typescript/`)
105
+ - Issues: https://github.com/microsoft/amplifier-agent/issues
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Approval bridge — in-band, mid-turn JSON-RPC round-trip (§5.2).
3
+ *
4
+ * makeApprovalHandler(adapter) returns a JSON-RPC request handler for
5
+ * 'approval/request' server-initiated requests. Wire it into the
6
+ * JsonRpcClient via rpc.onRequest('approval/request', makeApprovalHandler(adapter)).
7
+ *
8
+ * Decision semantics:
9
+ * - 'allow' — adapter accepted the tool call
10
+ * - 'deny' — adapter rejected, adapter threw, or no adapter configured
11
+ * - 'timeout' — adapter did not resolve within timeoutMs
12
+ *
13
+ * Pattern reference: Design §5.2 — six-step round-trip.
14
+ */
15
+ /** Request sent by the engine when a tool call requires approval. */
16
+ export interface ApprovalRequest {
17
+ id: string;
18
+ tool: string;
19
+ args: unknown;
20
+ }
21
+ /** Response the wrapper sends back to the engine. */
22
+ export interface ApprovalResponse {
23
+ decision: "allow" | "deny" | "timeout";
24
+ reason?: string;
25
+ [key: string]: unknown;
26
+ }
27
+ /** Adapter supplied by the host to handle approval requests. */
28
+ export interface ApprovalAdapter {
29
+ onRequest: (req: unknown) => Promise<ApprovalResponse>;
30
+ timeoutMs: number;
31
+ }
32
+ /** Handler type matching JsonRpcClient.onRequest signature. */
33
+ export type ApprovalHandler = (params: unknown) => Promise<unknown>;
34
+ /**
35
+ * Create a JSON-RPC request handler for 'approval/request'.
36
+ *
37
+ * @param adapter - Host-supplied adapter, or undefined for default-deny.
38
+ * @returns An async function (params) => ApprovalResponse.
39
+ */
40
+ export declare function makeApprovalHandler(adapter: ApprovalAdapter | undefined): ApprovalHandler;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Approval bridge — in-band, mid-turn JSON-RPC round-trip (§5.2).
3
+ *
4
+ * makeApprovalHandler(adapter) returns a JSON-RPC request handler for
5
+ * 'approval/request' server-initiated requests. Wire it into the
6
+ * JsonRpcClient via rpc.onRequest('approval/request', makeApprovalHandler(adapter)).
7
+ *
8
+ * Decision semantics:
9
+ * - 'allow' — adapter accepted the tool call
10
+ * - 'deny' — adapter rejected, adapter threw, or no adapter configured
11
+ * - 'timeout' — adapter did not resolve within timeoutMs
12
+ *
13
+ * Pattern reference: Design §5.2 — six-step round-trip.
14
+ */
15
+ /**
16
+ * Create a JSON-RPC request handler for 'approval/request'.
17
+ *
18
+ * @param adapter - Host-supplied adapter, or undefined for default-deny.
19
+ * @returns An async function (params) => ApprovalResponse.
20
+ */
21
+ export function makeApprovalHandler(adapter) {
22
+ if (!adapter) {
23
+ return async (_params) => ({
24
+ decision: "deny",
25
+ reason: "no_adapter_configured",
26
+ });
27
+ }
28
+ const { onRequest, timeoutMs } = adapter;
29
+ return async (params) => {
30
+ let timerId;
31
+ const timeoutPromise = new Promise((resolve) => {
32
+ timerId = setTimeout(() => {
33
+ resolve({ decision: "timeout" });
34
+ }, timeoutMs);
35
+ });
36
+ try {
37
+ const result = await Promise.race([onRequest(params), timeoutPromise]);
38
+ // Clear the timeout timer if onRequest won the race.
39
+ if (timerId !== undefined)
40
+ clearTimeout(timerId);
41
+ return result;
42
+ }
43
+ catch {
44
+ if (timerId !== undefined)
45
+ clearTimeout(timerId);
46
+ return { decision: "deny", reason: "adapter_error" };
47
+ }
48
+ };
49
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * argv-builder.ts — pure argv assembly for `amplifier-agent run`.
3
+ *
4
+ * Mode A v2 (task-5 / A3'): given a fully-resolved AssembleArgvInput, produce
5
+ * the exact argv array the wrapper will pass to the engine binary. This
6
+ * function performs no I/O and reads no environment — all spilling, env
7
+ * resolution, and capability composition happen upstream.
8
+ *
9
+ * SC-C: the wrapper always passes `-y` to enforce auto-allow at the bundle
10
+ * layer; approvals are handled by the orchestrating host, not the engine.
11
+ */
12
+ export interface AssembleArgvInput {
13
+ /** Session identifier (provided by caller, never generated here). */
14
+ sessionId: string;
15
+ /** Final user prompt — emitted last as a positional argument. */
16
+ prompt: string;
17
+ /** Protocol version the wrapper speaks (e.g. "0.1.0"). */
18
+ protocolVersion: string;
19
+ /** When true, emit `--resume` instead of `--fresh`. */
20
+ resume?: boolean;
21
+ /** Working directory override; emits `--cwd <cwd>`. */
22
+ cwd?: string;
23
+ /** Provider override; emits `--provider <providerOverride>`. */
24
+ providerOverride?: string;
25
+ /**
26
+ * Pre-resolved value for `--mcp-servers`. Caller decides whether this is
27
+ * inline JSON or an `@/path/to/file.json` spill reference; argv-builder
28
+ * threads it through unchanged.
29
+ */
30
+ mcpServersFlag?: string;
31
+ /** Host capabilities object — emitted as `--host-capabilities <JSON>`. */
32
+ hostCapabilities?: unknown;
33
+ /** Allowlisted env variable names — emits `--env-allowlist <comma-joined>`. */
34
+ envAllowlist?: string[];
35
+ /** Extra env entries — emitted as `--env-extra <JSON>`. */
36
+ envExtra?: Record<string, string>;
37
+ /** When true, emit `--allow-protocol-skew`. */
38
+ allowProtocolSkew?: boolean;
39
+ }
40
+ /**
41
+ * Build the argv array for `amplifier-agent run`.
42
+ *
43
+ * Pure function: no I/O, no env reads, no globals. Order is canonical and
44
+ * stable so wrapper integration tests can pin against it.
45
+ */
46
+ export declare function assembleArgv(input: AssembleArgvInput): string[];
@@ -0,0 +1,51 @@
1
+ /**
2
+ * argv-builder.ts — pure argv assembly for `amplifier-agent run`.
3
+ *
4
+ * Mode A v2 (task-5 / A3'): given a fully-resolved AssembleArgvInput, produce
5
+ * the exact argv array the wrapper will pass to the engine binary. This
6
+ * function performs no I/O and reads no environment — all spilling, env
7
+ * resolution, and capability composition happen upstream.
8
+ *
9
+ * SC-C: the wrapper always passes `-y` to enforce auto-allow at the bundle
10
+ * layer; approvals are handled by the orchestrating host, not the engine.
11
+ */
12
+ /**
13
+ * Build the argv array for `amplifier-agent run`.
14
+ *
15
+ * Pure function: no I/O, no env reads, no globals. Order is canonical and
16
+ * stable so wrapper integration tests can pin against it.
17
+ */
18
+ export function assembleArgv(input) {
19
+ const argv = [];
20
+ argv.push("run");
21
+ argv.push("--session-id", input.sessionId);
22
+ argv.push(input.resume ? "--resume" : "--fresh");
23
+ if (input.cwd !== undefined) {
24
+ argv.push("--cwd", input.cwd);
25
+ }
26
+ if (input.providerOverride !== undefined) {
27
+ argv.push("--provider", input.providerOverride);
28
+ }
29
+ if (input.mcpServersFlag !== undefined) {
30
+ argv.push("--mcp-servers", input.mcpServersFlag);
31
+ }
32
+ if (input.hostCapabilities !== undefined) {
33
+ argv.push("--host-capabilities", JSON.stringify(input.hostCapabilities));
34
+ }
35
+ if (input.envAllowlist !== undefined && input.envAllowlist.length > 0) {
36
+ argv.push("--env-allowlist", input.envAllowlist.join(","));
37
+ }
38
+ if (input.envExtra !== undefined) {
39
+ argv.push("--env-extra", JSON.stringify(input.envExtra));
40
+ }
41
+ argv.push("--output", "json");
42
+ argv.push("--protocol-version", input.protocolVersion);
43
+ if (input.allowProtocolSkew === true) {
44
+ argv.push("--allow-protocol-skew");
45
+ }
46
+ // SC-C: wrapper enforces auto-allow at the bundle layer.
47
+ argv.push("-y");
48
+ // Prompt is the final positional argument.
49
+ argv.push(input.prompt);
50
+ return argv;
51
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * amplifier-agent-client-ts — public entry point.
3
+ *
4
+ * Exports the locked public API from design §8.2, narrowed to Mode A v2
5
+ * (amendment §5). `spawnAgent` is synchronous-in-spirit: it validates
6
+ * parameters, resolves the engine binary path, builds the subprocess
7
+ * environment, and constructs a `SessionHandle`. **No subprocess is spawned
8
+ * at spawn-time** — the engine is launched per `submit()` (amendment §5.2).
9
+ */
10
+ export { AaaError, SessionHandle } from "./session.js";
11
+ export type { DisplayEvent, EngineInfo, SessionHandleParams, } from "./session.js";
12
+ export type { ApprovalResponse } from "./approval.js";
13
+ export type { EngineVersionPayload } from "./spawn.js";
14
+ import { SessionHandle } from "./session.js";
15
+ import type { DisplayEvent } from "./session.js";
16
+ import type { ApprovalResponse } from "./approval.js";
17
+ import type { McpServerConfig, HostCapabilities } from "./types.js";
18
+ export type { McpServerConfig, HostCapabilities } from "./types.js";
19
+ /**
20
+ * The protocol version that this TypeScript wrapper requires.
21
+ * Forwarded to the engine via `--protocol-version` on every `submit()`.
22
+ */
23
+ export declare const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.1.0";
24
+ /** Parameters for spawnAgent(). Signature is locked verbatim by design §8.2. */
25
+ export interface SpawnAgentParams {
26
+ /** 'burst' reserved; throws AaaError(lifecycle_unsupported) at runtime. */
27
+ lifecycle: "one-shot";
28
+ sessionId: string;
29
+ resume?: boolean;
30
+ cwd?: string;
31
+ env?: {
32
+ allowlist: string[];
33
+ extra?: Record<string, string>;
34
+ };
35
+ providerOverride?: string;
36
+ /**
37
+ * Mid-turn approval callback.
38
+ *
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.
42
+ */
43
+ approval?: {
44
+ onRequest: (req: unknown) => Promise<ApprovalResponse>;
45
+ timeoutMs: number;
46
+ };
47
+ display?: {
48
+ onEvent?: (event: DisplayEvent) => void;
49
+ subagentEvents?: "all" | "none";
50
+ };
51
+ /** Default false; opt out of D6 strict-refuse version check. */
52
+ allowProtocolSkew?: boolean;
53
+ /** Optional MCP servers to forward via `--mcp-servers` (A1). */
54
+ mcpServers?: Record<string, McpServerConfig>;
55
+ /** Optional host envelope forwarded via `--host-capabilities` (A1). */
56
+ host?: {
57
+ capabilities?: HostCapabilities;
58
+ };
59
+ /** Per-submit timeout in ms (default: 10 minutes). */
60
+ timeoutMs?: number;
61
+ /** Replaces the real resolveBinaryPath() call. */
62
+ _binaryResolver?: () => string;
63
+ }
64
+ /**
65
+ * Compose all internal components into the single public entry point.
66
+ *
67
+ * Mode A v2 flow (amendment §5):
68
+ * 1. Guard: lifecycle must be 'one-shot' (D10).
69
+ * 2. Reject `approval.onRequest !== undefined` (SC-C — v1 has no mid-turn channel).
70
+ * 3. Resolve engine binary path (or inject via `_binaryResolver`).
71
+ * 4. Build subprocess environment via `buildEnv`.
72
+ * 5. Return `new SessionHandle(params)` — **NO subprocess is spawned here**.
73
+ *
74
+ * The engine is launched per `submit()` (amendment §5.2). `agent/initialize`
75
+ * is gone; protocol-version handshake moves to argv at submit-time. Engine
76
+ * metadata (`engineVersion`, `bundleDigest`) is populated lazily once the
77
+ * first envelope arrives (TODO: Task-9 wires this from `parseRunOutput`).
78
+ */
79
+ export declare function spawnAgent(params: SpawnAgentParams): Promise<SessionHandle>;
package/dist/index.js ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * amplifier-agent-client-ts — public entry point.
3
+ *
4
+ * Exports the locked public API from design §8.2, narrowed to Mode A v2
5
+ * (amendment §5). `spawnAgent` is synchronous-in-spirit: it validates
6
+ * parameters, resolves the engine binary path, builds the subprocess
7
+ * environment, and constructs a `SessionHandle`. **No subprocess is spawned
8
+ * at spawn-time** — the engine is launched per `submit()` (amendment §5.2).
9
+ */
10
+ // Re-export public types and classes from sub-modules.
11
+ export { AaaError, SessionHandle } from "./session.js";
12
+ // Internal imports used by spawnAgent().
13
+ import { AaaError, SessionHandle } from "./session.js";
14
+ import { resolveBinaryPath, buildEnv, DEFAULT_ALLOWLIST } from "./spawn.js";
15
+ /**
16
+ * The protocol version that this TypeScript wrapper requires.
17
+ * Forwarded to the engine via `--protocol-version` on every `submit()`.
18
+ */
19
+ export const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.1.0";
20
+ // ---------------------------------------------------------------------------
21
+ // spawnAgent() — locked public entry point (Mode A v2)
22
+ // ---------------------------------------------------------------------------
23
+ /**
24
+ * Compose all internal components into the single public entry point.
25
+ *
26
+ * Mode A v2 flow (amendment §5):
27
+ * 1. Guard: lifecycle must be 'one-shot' (D10).
28
+ * 2. Reject `approval.onRequest !== undefined` (SC-C — v1 has no mid-turn channel).
29
+ * 3. Resolve engine binary path (or inject via `_binaryResolver`).
30
+ * 4. Build subprocess environment via `buildEnv`.
31
+ * 5. Return `new SessionHandle(params)` — **NO subprocess is spawned here**.
32
+ *
33
+ * The engine is launched per `submit()` (amendment §5.2). `agent/initialize`
34
+ * is gone; protocol-version handshake moves to argv at submit-time. Engine
35
+ * metadata (`engineVersion`, `bundleDigest`) is populated lazily once the
36
+ * first envelope arrives (TODO: Task-9 wires this from `parseRunOutput`).
37
+ */
38
+ export async function spawnAgent(params) {
39
+ // SC-C: reject mid-turn approval callback before any other work. The Mode A
40
+ // wire has no mid-turn request channel; warning-only acceptance would ship
41
+ // silent auto-allow to a host author who believed their callback was wired.
42
+ if (params.approval?.onRequest !== undefined) {
43
+ 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" });
49
+ }
50
+ // 1. Lifecycle guard (D10).
51
+ if (params.lifecycle !== "one-shot") {
52
+ throw new AaaError("lifecycle_unsupported", `lifecycle '${String(params.lifecycle)}' is not supported in v1; ` +
53
+ `only 'one-shot' is supported. 'burst' is reserved for a future minor version.`);
54
+ }
55
+ // 2. Resolve binary path.
56
+ let binaryPath;
57
+ if (params._binaryResolver) {
58
+ binaryPath = params._binaryResolver();
59
+ }
60
+ else {
61
+ try {
62
+ binaryPath = resolveBinaryPath({
63
+ env: process.env,
64
+ });
65
+ }
66
+ catch (e) {
67
+ const msg = e.message ?? "binary not found";
68
+ throw new AaaError("binary_not_found", msg);
69
+ }
70
+ }
71
+ // 3. Build subprocess environment.
72
+ const allowlist = params.env?.allowlist ?? DEFAULT_ALLOWLIST;
73
+ const extra = params.env?.extra ?? {};
74
+ const subprocessEnv = buildEnv({
75
+ processEnv: process.env,
76
+ allowlist,
77
+ extra,
78
+ });
79
+ // 4. Return a SessionHandle. NO subprocess spawned here — the engine is
80
+ // launched per submit() (amendment §5.2). NOTE: `version.ts` /
81
+ // `checkProtocolVersion` are unused in Mode A v2 (skew is enforced via
82
+ // argv `--protocol-version` + `--allow-protocol-skew` at the engine
83
+ // side); flagged for Task-9 cleanup.
84
+ return new SessionHandle({
85
+ binaryPath,
86
+ sessionId: params.sessionId,
87
+ subprocessEnv,
88
+ ...(params.resume !== undefined ? { resume: params.resume } : {}),
89
+ ...(params.cwd !== undefined ? { cwd: params.cwd } : {}),
90
+ ...(params.mcpServers !== undefined ? { mcpServers: params.mcpServers } : {}),
91
+ ...(params.host?.capabilities !== undefined
92
+ ? { hostCapabilities: params.host.capabilities }
93
+ : {}),
94
+ envAllowlist: allowlist,
95
+ envExtra: extra,
96
+ ...(params.providerOverride !== undefined
97
+ ? { providerOverride: params.providerOverride }
98
+ : {}),
99
+ ...(params.allowProtocolSkew !== undefined
100
+ ? { allowProtocolSkew: params.allowProtocolSkew }
101
+ : {}),
102
+ protocolVersion: PROTOCOL_VERSION_REQUIRED_BY_WRAPPER,
103
+ ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),
104
+ });
105
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Result of resolving the `--mcp-servers` flag value.
3
+ *
4
+ * - When `mcpServers` is null/undefined/empty: both fields are `null`.
5
+ * - When no server has a non-empty env block: `flag` is inline JSON,
6
+ * `spillPath` is `null` (no cleanup needed).
7
+ * - When any server has a non-empty env block: `flag` is `@<spillPath>`,
8
+ * `spillPath` points at the 0600 tmpfile (caller must cleanup).
9
+ */
10
+ export interface McpSpillResult {
11
+ flag: string | null;
12
+ spillPath: string | null;
13
+ }
14
+ /**
15
+ * Loose shape for an MCP server entry. We only inspect `env` here; the rest
16
+ * is threaded through untouched into the spilled JSON or inline payload.
17
+ */
18
+ interface McpServerLike {
19
+ env?: Record<string, string> | undefined;
20
+ [k: string]: unknown;
21
+ }
22
+ type McpServersMap = Record<string, McpServerLike>;
23
+ /**
24
+ * Resolve the value to pass for `--mcp-servers`.
25
+ *
26
+ * @param mcpServers Map of server-id -> config, or null/undefined.
27
+ * @param sessionId Session identifier; used as the per-session subdirectory
28
+ * under the spill base so concurrent sessions never clash.
29
+ *
30
+ * @returns A `McpSpillResult` with the flag value and (if spilled) the
31
+ * on-disk path for later cleanup.
32
+ */
33
+ export declare function resolveMcpServersFlag(mcpServers: McpServersMap | null | undefined, sessionId: string): Promise<McpSpillResult>;
34
+ /**
35
+ * Idempotently remove a spill file. Safe to call with `null` (no-op) and
36
+ * safe to call when the file is already gone (ENOENT swallowed). Other
37
+ * I/O errors propagate.
38
+ */
39
+ export declare function cleanupSpillFile(spillPath: string | null | undefined): Promise<void>;
40
+ export {};
@@ -0,0 +1,88 @@
1
+ /**
2
+ * mcp-spill.ts — secret-aware MCP servers config resolution (CR-A).
3
+ *
4
+ * A3'/CR-A: When forwarding `--mcp-servers` to the engine binary, the wrapper
5
+ * must avoid placing secret-bearing env blocks on the command line. If any
6
+ * server in the config has a non-empty `env` block, the full JSON is spilled
7
+ * to a 0600 tmpfile under `${XDG_RUNTIME_DIR || os.tmpdir()}/amplifier-agent/<sessionId>/`
8
+ * and the flag value is `@<path>`. When no server has env, the JSON is inlined
9
+ * directly (no spill, no cleanup needed).
10
+ *
11
+ * `cleanupSpillFile` is the matching teardown — idempotent unlink that
12
+ * swallows ENOENT so callers can call it unconditionally on every exit path.
13
+ */
14
+ import { mkdir, writeFile, unlink } from "node:fs/promises";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ /**
18
+ * Return true when at least one server has a non-empty `env` block.
19
+ * An empty object (`{}`) does NOT trigger spilling — only env blocks with
20
+ * at least one key are considered secret-bearing.
21
+ */
22
+ function anyServerHasEnv(mcpServers) {
23
+ for (const key of Object.keys(mcpServers)) {
24
+ const server = mcpServers[key];
25
+ if (!server)
26
+ continue;
27
+ const env = server.env;
28
+ if (env && typeof env === "object" && Object.keys(env).length > 0) {
29
+ return true;
30
+ }
31
+ }
32
+ return false;
33
+ }
34
+ /**
35
+ * Compute the base directory for spill files. Prefers
36
+ * `$XDG_RUNTIME_DIR/amplifier-agent` (typically a tmpfs on Linux) and falls
37
+ * back to `os.tmpdir()/amplifier-agent` otherwise.
38
+ */
39
+ function spillBaseDir() {
40
+ const xdg = process.env["XDG_RUNTIME_DIR"];
41
+ if (xdg && xdg.length > 0) {
42
+ return join(xdg, "amplifier-agent");
43
+ }
44
+ return join(tmpdir(), "amplifier-agent");
45
+ }
46
+ /**
47
+ * Resolve the value to pass for `--mcp-servers`.
48
+ *
49
+ * @param mcpServers Map of server-id -> config, or null/undefined.
50
+ * @param sessionId Session identifier; used as the per-session subdirectory
51
+ * under the spill base so concurrent sessions never clash.
52
+ *
53
+ * @returns A `McpSpillResult` with the flag value and (if spilled) the
54
+ * on-disk path for later cleanup.
55
+ */
56
+ export async function resolveMcpServersFlag(mcpServers, sessionId) {
57
+ if (!mcpServers || Object.keys(mcpServers).length === 0) {
58
+ return { flag: null, spillPath: null };
59
+ }
60
+ if (!anyServerHasEnv(mcpServers)) {
61
+ // No secrets — safe to inline as a JSON string.
62
+ return { flag: JSON.stringify(mcpServers), spillPath: null };
63
+ }
64
+ // Secret-bearing: spill to a 0600 tmpfile under a 0700 per-session dir.
65
+ const dir = join(spillBaseDir(), sessionId);
66
+ await mkdir(dir, { recursive: true, mode: 0o700 });
67
+ const filePath = join(dir, "mcp.json");
68
+ await writeFile(filePath, JSON.stringify(mcpServers), { mode: 0o600 });
69
+ return { flag: `@${filePath}`, spillPath: filePath };
70
+ }
71
+ /**
72
+ * Idempotently remove a spill file. Safe to call with `null` (no-op) and
73
+ * safe to call when the file is already gone (ENOENT swallowed). Other
74
+ * I/O errors propagate.
75
+ */
76
+ export async function cleanupSpillFile(spillPath) {
77
+ if (!spillPath)
78
+ return;
79
+ try {
80
+ await unlink(spillPath);
81
+ }
82
+ catch (err) {
83
+ const code = err.code;
84
+ if (code === "ENOENT")
85
+ return;
86
+ throw err;
87
+ }
88
+ }
@@ -0,0 +1,33 @@
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
+ import type { DisplayEvent } from "./session.js";
20
+ /** Maximum stderrTail length retained on synthesized engine errors. */
21
+ export declare const STDERR_TAIL_BYTES = 4096;
22
+ /** Outcome of running the `amplifier-agent run --output json` subprocess. */
23
+ export interface SubprocessOutcome {
24
+ stdout: string;
25
+ stderr: string;
26
+ exitCode: number;
27
+ }
28
+ /**
29
+ * Parse a subprocess outcome into a single DisplayEvent.
30
+ *
31
+ * See module docstring for precedence rules.
32
+ */
33
+ export declare function parseRunOutput(outcome: SubprocessOutcome): DisplayEvent;