amplifier-agent-ts 0.5.0 → 0.6.2
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/dist/argv-builder.d.ts +19 -1
- package/dist/argv-builder.js +22 -2
- package/dist/index.d.ts +113 -11
- package/dist/index.js +111 -10
- package/dist/session.d.ts +87 -7
- package/dist/session.js +89 -38
- package/dist/transport.d.ts +39 -0
- package/dist/transport.js +44 -0
- package/package.json +1 -1
package/dist/argv-builder.d.ts
CHANGED
|
@@ -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.
|
|
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`.
|
package/dist/argv-builder.js
CHANGED
|
@@ -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
|
-
//
|
|
43
|
-
|
|
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
|
@@ -7,20 +7,53 @@
|
|
|
7
7
|
* environment, and constructs a `SessionHandle`. **No subprocess is spawned
|
|
8
8
|
* at spawn-time** — the engine is launched per `submit()` (amendment §5.2).
|
|
9
9
|
*/
|
|
10
|
-
export { AaaError, SessionHandle } from "./session.js";
|
|
10
|
+
export { AaaError, SessionHandle, DEFAULT_TIMEOUT_MS } 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.
|
|
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
|
-
*
|
|
70
|
+
* Approval policy (Issue #10).
|
|
38
71
|
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
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
|
-
|
|
45
|
-
|
|
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;
|
|
@@ -56,10 +109,59 @@ export interface SpawnAgentParams {
|
|
|
56
109
|
* priority chain.
|
|
57
110
|
*/
|
|
58
111
|
mcpServers?: Record<string, McpServerConfig>;
|
|
59
|
-
/**
|
|
112
|
+
/**
|
|
113
|
+
* Per-submit timeout in ms. No timeout is applied unless a positive value
|
|
114
|
+
* is provided; `undefined` or `0` disables the wall-clock hang timer.
|
|
115
|
+
* Pass `DEFAULT_TIMEOUT_MS` to opt into the original 10-minute cap.
|
|
116
|
+
*/
|
|
60
117
|
timeoutMs?: number;
|
|
118
|
+
/**
|
|
119
|
+
* Path to a host config file (Issue #1). Forwarded to the engine via
|
|
120
|
+
* `--config <configPath>` so the engine's host_config layer
|
|
121
|
+
* (approval mode, MCP servers, provider defaults,
|
|
122
|
+
* `allowProtocolSkew`, etc.) is composed from the file the host
|
|
123
|
+
* already manages.
|
|
124
|
+
*
|
|
125
|
+
* Mirrors the engine's `single_turn --config` flag (engine PR #27 /
|
|
126
|
+
* v0.4.0). When unset, the engine's resolution order applies (env
|
|
127
|
+
* `AMPLIFIER_AGENT_CONFIG`, then `~/.config/amplifier-agent/host_config.json`).
|
|
128
|
+
*
|
|
129
|
+
* @public
|
|
130
|
+
*/
|
|
131
|
+
configPath?: string;
|
|
132
|
+
/**
|
|
133
|
+
* Bypass the wrapper-side protocol-version check (Issue #9).
|
|
134
|
+
*
|
|
135
|
+
* Default `false`: `spawnAgent()` probes the engine's protocol version once
|
|
136
|
+
* during initialization and rejects with `AaaError(protocol_version_mismatch)`
|
|
137
|
+
* when it differs from `PROTOCOL_VERSION_REQUIRED_BY_WRAPPER`. Setting this to
|
|
138
|
+
* `true` skips the check and lets the engine run regardless — useful for
|
|
139
|
+
* exploratory work against pre-release engine versions, but unsafe by default.
|
|
140
|
+
*
|
|
141
|
+
* Mirrors the engine-side `host_config.allowProtocolSkew` knob.
|
|
142
|
+
*/
|
|
143
|
+
allowProtocolSkew?: boolean;
|
|
61
144
|
/** Replaces the real resolveBinaryPath() call. */
|
|
62
145
|
_binaryResolver?: () => string;
|
|
146
|
+
/**
|
|
147
|
+
* Replaces the real probeEngineVersion() call (Issue #9 + #7). When set,
|
|
148
|
+
* `spawnAgent()` invokes this factory instead of spawning
|
|
149
|
+
* `<binaryPath> version --json`. Reserved for tests and host-side stubs.
|
|
150
|
+
*/
|
|
151
|
+
_engineVersionProbe?: () => Promise<{
|
|
152
|
+
version: string;
|
|
153
|
+
protocolVersion: string;
|
|
154
|
+
bundleDigest?: string;
|
|
155
|
+
}>;
|
|
156
|
+
/**
|
|
157
|
+
* Override the subprocess factory used inside `SessionHandle.submit()`
|
|
158
|
+
* (Issue #3). When set, the wrapper invokes this factory in place of
|
|
159
|
+
* `child_process.spawn`. Useful for sandboxing, harness wrapping, or
|
|
160
|
+
* test doubles.
|
|
161
|
+
*
|
|
162
|
+
* @public
|
|
163
|
+
*/
|
|
164
|
+
runChildProcess?: ChildProcessFactory;
|
|
63
165
|
}
|
|
64
166
|
/**
|
|
65
167
|
* Compose all internal components into the single public entry point.
|
package/dist/index.js
CHANGED
|
@@ -8,15 +8,50 @@
|
|
|
8
8
|
* at spawn-time** — the engine is launched per `submit()` (amendment §5.2).
|
|
9
9
|
*/
|
|
10
10
|
// Re-export public types and classes from sub-modules.
|
|
11
|
-
export { AaaError, SessionHandle } from "./session.js";
|
|
11
|
+
export { AaaError, SessionHandle, DEFAULT_TIMEOUT_MS } 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.
|
|
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.
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
|
|
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.
|
|
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
|
@@ -12,7 +12,9 @@
|
|
|
12
12
|
* cooperation).
|
|
13
13
|
* 3. `{type:'result', text}` or `{type:'error', ...}` — yielded once when
|
|
14
14
|
* the subprocess exits (`parseRunOutput` applied to stdout/stderr/exit)
|
|
15
|
-
* OR when the configured `timeoutMs`
|
|
15
|
+
* OR when the configured `timeoutMs` (if a positive number) elapses
|
|
16
|
+
* (synthesized `engine_hung`). No timeout is armed when `timeoutMs` is
|
|
17
|
+
* `undefined` or `<= 0`.
|
|
16
18
|
*
|
|
17
19
|
* Lifecycle:
|
|
18
20
|
* - `submit()` is one-shot per session (D10). A second call throws
|
|
@@ -22,8 +24,22 @@
|
|
|
22
24
|
* file created on this turn (CR-A cleanup).
|
|
23
25
|
* - `dispose()` is a synonym for `cancel()`.
|
|
24
26
|
*/
|
|
25
|
-
import type { ChildProcess } from "node:child_process";
|
|
27
|
+
import type { ChildProcess, SpawnOptions } from "node:child_process";
|
|
26
28
|
import type { McpServerConfig } from "./types.js";
|
|
29
|
+
/**
|
|
30
|
+
* Factory function compatible with the surface of `child_process.spawn`
|
|
31
|
+
* that `SessionHandle` calls. Hosts can supply this via
|
|
32
|
+
* `SpawnAgentParams.runChildProcess` (Issue #3) to substitute their own
|
|
33
|
+
* subprocess factory — useful for sandboxing, harness wrapping, or test
|
|
34
|
+
* doubles.
|
|
35
|
+
*
|
|
36
|
+
* The factory is invoked exactly once per `submit()` with the resolved
|
|
37
|
+
* binary path, the assembled argv array, and the spawn options the wrapper
|
|
38
|
+
* would have used (including `detached`, `stdio`, `env`, and optional `cwd`).
|
|
39
|
+
*
|
|
40
|
+
* @public
|
|
41
|
+
*/
|
|
42
|
+
export type ChildProcessFactory = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;
|
|
27
43
|
/**
|
|
28
44
|
* A display event yielded by `SessionHandle.submit()`.
|
|
29
45
|
*
|
|
@@ -49,6 +65,23 @@ export type DisplayEvent = {
|
|
|
49
65
|
message: string;
|
|
50
66
|
stderrTail?: string;
|
|
51
67
|
retryable: boolean;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Wire-protocol notification dispatched from the engine's stderr NDJSON
|
|
71
|
+
* stream (Issue #2 / #6). One of the 9 wire event types the engine
|
|
72
|
+
* emits: progress, result/delta, result/final, thinking/delta,
|
|
73
|
+
* thinking/final, tool/started, tool/completed, approval/request,
|
|
74
|
+
* approval/timeout, plus the wire-level error notification.
|
|
75
|
+
*
|
|
76
|
+
* `method` is the JSON-RPC method name verbatim from the wire envelope
|
|
77
|
+
* (e.g. `"progress"`, `"tool/started"`). `params` is the raw payload
|
|
78
|
+
* dictionary the engine emitted, unaltered. Callers may narrow on
|
|
79
|
+
* `method` and cast `params` to a typed shape from `./types.ts`.
|
|
80
|
+
*/
|
|
81
|
+
| {
|
|
82
|
+
type: "notification";
|
|
83
|
+
method: string;
|
|
84
|
+
params: unknown;
|
|
52
85
|
};
|
|
53
86
|
/** Typed error for AaA wrapper lifecycle and protocol violations. */
|
|
54
87
|
export declare class AaaError extends Error {
|
|
@@ -98,11 +131,58 @@ export interface SessionHandleParams {
|
|
|
98
131
|
mcpServers?: Record<string, McpServerConfig>;
|
|
99
132
|
/** Provider override forwarded via `--provider`. */
|
|
100
133
|
providerOverride?: string;
|
|
101
|
-
/**
|
|
134
|
+
/**
|
|
135
|
+
* Path to the engine's host config file (Issue #1). Forwarded to the
|
|
136
|
+
* engine via `--config <configPath>`. See the engine's
|
|
137
|
+
* `single_turn` mode for the resolved-precedence rules between argv
|
|
138
|
+
* flags, host_config, and the bundle's TTY-based default.
|
|
139
|
+
*/
|
|
140
|
+
configPath?: string;
|
|
141
|
+
/**
|
|
142
|
+
* Approval mode override (Issue #10). Maps to engine argv:
|
|
143
|
+
* `"yes" -> -y`, `"no" -> -n`, `"prompt" -> emit nothing` so the engine
|
|
144
|
+
* falls back to `host_config.approval.mode` or its bundle/TTY default.
|
|
145
|
+
* Undefined preserves the historical default (`-y`) for callers that
|
|
146
|
+
* have not opted into the approval API.
|
|
147
|
+
*/
|
|
148
|
+
approvalMode?: "yes" | "no" | "prompt";
|
|
149
|
+
/** Protocol version the wrapper speaks (e.g. "0.3.0"). */
|
|
102
150
|
protocolVersion: string;
|
|
103
|
-
/**
|
|
151
|
+
/**
|
|
152
|
+
* Per-submit timeout in milliseconds. No timeout is applied unless a
|
|
153
|
+
* positive value is provided. `undefined` or `<= 0` disables the
|
|
154
|
+
* wall-clock hang timer entirely. Pass `DEFAULT_TIMEOUT_MS` to opt into
|
|
155
|
+
* the original 10-minute cap.
|
|
156
|
+
*/
|
|
104
157
|
timeoutMs?: number;
|
|
158
|
+
/**
|
|
159
|
+
* Optional override for the subprocess factory (Issue #3). When set, the
|
|
160
|
+
* handle invokes this function instead of `child_process.spawn`.
|
|
161
|
+
*/
|
|
162
|
+
runChildProcess?: ChildProcessFactory;
|
|
163
|
+
/**
|
|
164
|
+
* Display sink (Issue #4). When set, every parsed NDJSON wire-event from
|
|
165
|
+
* the engine subprocess's stderr stream is dispatched here, in addition
|
|
166
|
+
* to whatever the iterator yields. Pass-through from
|
|
167
|
+
* `SpawnAgentParams.display`.
|
|
168
|
+
*/
|
|
169
|
+
display?: {
|
|
170
|
+
onEvent?: (event: DisplayEvent) => void;
|
|
171
|
+
};
|
|
172
|
+
/** Engine metadata resolved at spawnAgent() time (Issue #7). */
|
|
173
|
+
engineVersion?: string;
|
|
174
|
+
/** Bundle digest resolved at spawnAgent() time (Issue #7). */
|
|
175
|
+
bundleDigest?: string;
|
|
105
176
|
}
|
|
177
|
+
/**
|
|
178
|
+
* Default timeout value (10 minutes) exported for callers that want a
|
|
179
|
+
* wall-clock cap on individual turns. This constant is NOT applied
|
|
180
|
+
* automatically — pass it explicitly as `timeoutMs: DEFAULT_TIMEOUT_MS`
|
|
181
|
+
* to opt into the 10-minute limit.
|
|
182
|
+
*
|
|
183
|
+
* @public
|
|
184
|
+
*/
|
|
185
|
+
export declare const DEFAULT_TIMEOUT_MS: number;
|
|
106
186
|
/**
|
|
107
187
|
* Wait for `child` to fire `exit`, or `ms` to elapse — whichever first.
|
|
108
188
|
*
|
|
@@ -137,9 +217,9 @@ export declare class SessionHandle {
|
|
|
137
217
|
* (iv) SC-B: spawn with `detached:true` so PID == PGID for group signals;
|
|
138
218
|
* (v) accumulate stdout/stderr from chunks;
|
|
139
219
|
* (vi) start a 2s activity ticker → queue;
|
|
140
|
-
* (vii) race `exitPromise` vs `timeoutPromise
|
|
141
|
-
* on timeout: cancel(), synthesize `engine_hung`;
|
|
142
|
-
* on exit:
|
|
220
|
+
* (vii) race `exitPromise` vs `timeoutPromise` (timer only armed when
|
|
221
|
+
* `timeoutMs > 0`); on timeout: cancel(), synthesize `engine_hung`;
|
|
222
|
+
* on exit: parseRunOutput({stdout, stderr, exitCode});
|
|
143
223
|
* (viii) cleanup spill file after exit;
|
|
144
224
|
* (ix) drain queue until the final event is yielded.
|
|
145
225
|
*/
|
package/dist/session.js
CHANGED
|
@@ -12,7 +12,9 @@
|
|
|
12
12
|
* cooperation).
|
|
13
13
|
* 3. `{type:'result', text}` or `{type:'error', ...}` — yielded once when
|
|
14
14
|
* the subprocess exits (`parseRunOutput` applied to stdout/stderr/exit)
|
|
15
|
-
* OR when the configured `timeoutMs`
|
|
15
|
+
* OR when the configured `timeoutMs` (if a positive number) elapses
|
|
16
|
+
* (synthesized `engine_hung`). No timeout is armed when `timeoutMs` is
|
|
17
|
+
* `undefined` or `<= 0`.
|
|
16
18
|
*
|
|
17
19
|
* Lifecycle:
|
|
18
20
|
* - `submit()` is one-shot per session (D10). A second call throws
|
|
@@ -26,6 +28,7 @@ import { spawn as childSpawn } from "node:child_process";
|
|
|
26
28
|
import { assembleArgv } from "./argv-builder.js";
|
|
27
29
|
import { resolveMcpConfigPath, cleanupSpillFile } from "./mcp-spill.js";
|
|
28
30
|
import { parseRunOutput, STDERR_TAIL_BYTES } from "./run-output-parser.js";
|
|
31
|
+
import { parseNdjsonStream } from "./transport.js";
|
|
29
32
|
/** Typed error for AaA wrapper lifecycle and protocol violations. */
|
|
30
33
|
export class AaaError extends Error {
|
|
31
34
|
code;
|
|
@@ -47,8 +50,15 @@ export class AaaError extends Error {
|
|
|
47
50
|
}
|
|
48
51
|
}
|
|
49
52
|
}
|
|
50
|
-
/**
|
|
51
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Default timeout value (10 minutes) exported for callers that want a
|
|
55
|
+
* wall-clock cap on individual turns. This constant is NOT applied
|
|
56
|
+
* automatically — pass it explicitly as `timeoutMs: DEFAULT_TIMEOUT_MS`
|
|
57
|
+
* to opt into the 10-minute limit.
|
|
58
|
+
*
|
|
59
|
+
* @public
|
|
60
|
+
*/
|
|
61
|
+
export const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
|
|
52
62
|
/** Activity ticker interval: 2 seconds (NC stuck-detection has 10s threshold). */
|
|
53
63
|
const ACTIVITY_TICK_MS = 2000;
|
|
54
64
|
/** Grace window between SIGTERM and SIGKILL in `cancel()`. */
|
|
@@ -95,11 +105,13 @@ export class SessionHandle {
|
|
|
95
105
|
this.engineInfo = {
|
|
96
106
|
binaryPath: params.binaryPath,
|
|
97
107
|
protocolVersion: params.protocolVersion,
|
|
98
|
-
// engineVersion
|
|
99
|
-
//
|
|
100
|
-
//
|
|
101
|
-
|
|
102
|
-
|
|
108
|
+
// Issue #7: engineVersion + bundleDigest are populated from the engine
|
|
109
|
+
// version probe that spawnAgent() runs during initialization (Issue #9).
|
|
110
|
+
// Falls back to empty strings when the engine omits a field (e.g. the
|
|
111
|
+
// `version --json` payload does not include bundleDigest until a future
|
|
112
|
+
// engine release ships an admin endpoint exposing it).
|
|
113
|
+
engineVersion: params.engineVersion ?? "",
|
|
114
|
+
bundleDigest: params.bundleDigest ?? "",
|
|
103
115
|
};
|
|
104
116
|
}
|
|
105
117
|
/** Return resolved engine metadata (D5). */
|
|
@@ -128,9 +140,9 @@ export class SessionHandle {
|
|
|
128
140
|
* (iv) SC-B: spawn with `detached:true` so PID == PGID for group signals;
|
|
129
141
|
* (v) accumulate stdout/stderr from chunks;
|
|
130
142
|
* (vi) start a 2s activity ticker → queue;
|
|
131
|
-
* (vii) race `exitPromise` vs `timeoutPromise
|
|
132
|
-
* on timeout: cancel(), synthesize `engine_hung`;
|
|
133
|
-
* on exit:
|
|
143
|
+
* (vii) race `exitPromise` vs `timeoutPromise` (timer only armed when
|
|
144
|
+
* `timeoutMs > 0`); on timeout: cancel(), synthesize `engine_hung`;
|
|
145
|
+
* on exit: parseRunOutput({stdout, stderr, exitCode});
|
|
134
146
|
* (viii) cleanup spill file after exit;
|
|
135
147
|
* (ix) drain queue until the final event is yielded.
|
|
136
148
|
*/
|
|
@@ -147,7 +159,9 @@ export class SessionHandle {
|
|
|
147
159
|
this.mcpSpillPath = spill.configPath;
|
|
148
160
|
// (iii) build argv (pure function — no I/O). The MCP config path is
|
|
149
161
|
// forwarded to the engine via AMPLIFIER_MCP_CONFIG (subprocess env)
|
|
150
|
-
// rather than via an argv flag.
|
|
162
|
+
// rather than via an argv flag. `configPath` (Issue #1) and
|
|
163
|
+
// `approvalMode` (Issue #10) are forwarded via argv flags emitted
|
|
164
|
+
// by assembleArgv.
|
|
151
165
|
const argv = assembleArgv({
|
|
152
166
|
sessionId: this.params.sessionId,
|
|
153
167
|
prompt,
|
|
@@ -155,6 +169,8 @@ export class SessionHandle {
|
|
|
155
169
|
resume: this.params.resume,
|
|
156
170
|
cwd: this.params.cwd,
|
|
157
171
|
providerOverride: this.params.providerOverride,
|
|
172
|
+
configPath: this.params.configPath,
|
|
173
|
+
approvalMode: this.params.approvalMode,
|
|
158
174
|
});
|
|
159
175
|
// Build the subprocess env. When we spilled an MCP config, set
|
|
160
176
|
// AMPLIFIER_MCP_CONFIG so tool-mcp reads it natively via its
|
|
@@ -167,7 +183,12 @@ export class SessionHandle {
|
|
|
167
183
|
subprocessEnv.AMPLIFIER_MCP_CONFIG = spill.configPath;
|
|
168
184
|
}
|
|
169
185
|
// (iv) SC-B: spawn detached → new session group → PID == PGID.
|
|
170
|
-
|
|
186
|
+
// Issue #3: when the caller provided a `runChildProcess` factory, use it
|
|
187
|
+
// in place of `child_process.spawn`. The factory must satisfy the
|
|
188
|
+
// ChildProcessFactory contract (same signature surface SessionHandle
|
|
189
|
+
// requires).
|
|
190
|
+
const spawnFn = this.params.runChildProcess ?? childSpawn;
|
|
191
|
+
const child = spawnFn(this.params.binaryPath, argv, {
|
|
171
192
|
detached: true,
|
|
172
193
|
stdio: ["ignore", "pipe", "pipe"],
|
|
173
194
|
env: subprocessEnv,
|
|
@@ -180,9 +201,32 @@ export class SessionHandle {
|
|
|
180
201
|
child.stdout?.on("data", (chunk) => {
|
|
181
202
|
stdoutBuf += typeof chunk === "string" ? chunk : chunk.toString("utf-8");
|
|
182
203
|
});
|
|
183
|
-
child.
|
|
184
|
-
|
|
185
|
-
|
|
204
|
+
// Issue #2 / #6: wire `parseNdjsonStream` onto the child's stderr. The
|
|
205
|
+
// engine emits one JSON object per line for each wire-protocol
|
|
206
|
+
// notification (progress, result/delta, tool/started, etc.).
|
|
207
|
+
// - JSON lines are parsed into `notification` DisplayEvents and
|
|
208
|
+
// dispatched to `params.display?.onEvent` (Issue #4).
|
|
209
|
+
// - Non-JSON lines are accumulated into `stderrBuf` so the
|
|
210
|
+
// stderrTail surface on parseRunOutput stays useful for
|
|
211
|
+
// diagnostic snapshots.
|
|
212
|
+
// - JSON lines are also appended to `stderrBuf` verbatim, so a
|
|
213
|
+
// crash-time tail still contains the wire-event context.
|
|
214
|
+
const displayOnEvent = this.params.display?.onEvent;
|
|
215
|
+
if (child.stderr) {
|
|
216
|
+
void parseNdjsonStream(child.stderr, {
|
|
217
|
+
onJson: (obj) => {
|
|
218
|
+
stderrBuf += JSON.stringify(obj) + "\n";
|
|
219
|
+
if (displayOnEvent) {
|
|
220
|
+
const method = typeof obj.method === "string" ? obj.method : "unknown";
|
|
221
|
+
const params = "params" in obj ? obj.params : obj;
|
|
222
|
+
displayOnEvent({ type: "notification", method, params });
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
onNonJson: (line) => {
|
|
226
|
+
stderrBuf += line + "\n";
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
}
|
|
186
230
|
const queue = [];
|
|
187
231
|
let wake = null;
|
|
188
232
|
const push = (item) => {
|
|
@@ -208,27 +252,32 @@ export class SessionHandle {
|
|
|
208
252
|
if (!finalized)
|
|
209
253
|
push({ type: "activity" });
|
|
210
254
|
}, ACTIVITY_TICK_MS);
|
|
211
|
-
// (vii) race exit vs timeout
|
|
212
|
-
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
255
|
+
// (vii) race exit vs timeout (timer only armed when timeoutMs is a positive
|
|
256
|
+
// number; undefined/0/negative means no timeout is applied).
|
|
257
|
+
const timeoutMs = this.params.timeoutMs;
|
|
258
|
+
let timeoutHandle = null;
|
|
259
|
+
if (timeoutMs !== undefined && timeoutMs > 0) {
|
|
260
|
+
timeoutHandle = setTimeout(() => {
|
|
261
|
+
// Synthesize engine_hung before invoking cancel(), so the iterator
|
|
262
|
+
// yields a terminal error even if SIGTERM/SIGKILL hangs.
|
|
263
|
+
const tail = stderrTailOf(stderrBuf);
|
|
264
|
+
finalize({
|
|
265
|
+
type: "error",
|
|
266
|
+
code: "engine_hung",
|
|
267
|
+
classification: "engine",
|
|
268
|
+
severity: "error",
|
|
269
|
+
correlationId: "",
|
|
270
|
+
message: `Engine subprocess hung past ${timeoutMs}ms timeout; SIGTERM/SIGKILL escalation invoked.`,
|
|
271
|
+
...(tail !== undefined ? { stderrTail: tail } : {}),
|
|
272
|
+
retryable: false,
|
|
273
|
+
});
|
|
274
|
+
// Fire-and-forget: cancel races the next event-loop turn.
|
|
275
|
+
void this.cancel();
|
|
276
|
+
}, timeoutMs);
|
|
277
|
+
}
|
|
230
278
|
child.once("exit", (code, _signal) => {
|
|
231
|
-
|
|
279
|
+
if (timeoutHandle !== null)
|
|
280
|
+
clearTimeout(timeoutHandle);
|
|
232
281
|
if (finalized)
|
|
233
282
|
return;
|
|
234
283
|
const ev = parseRunOutput({
|
|
@@ -242,7 +291,8 @@ export class SessionHandle {
|
|
|
242
291
|
// as transport-class failures; the test suite covers spawn-rejection at
|
|
243
292
|
// this seam (binary missing → typed AaaError-shaped DisplayEvent).
|
|
244
293
|
child.once("error", (err) => {
|
|
245
|
-
|
|
294
|
+
if (timeoutHandle !== null)
|
|
295
|
+
clearTimeout(timeoutHandle);
|
|
246
296
|
if (finalized)
|
|
247
297
|
return;
|
|
248
298
|
const tail = stderrTailOf(stderrBuf);
|
|
@@ -276,7 +326,8 @@ export class SessionHandle {
|
|
|
276
326
|
finally {
|
|
277
327
|
// (viii) cleanup ticker + spill file on every exit path.
|
|
278
328
|
clearInterval(ticker);
|
|
279
|
-
|
|
329
|
+
if (timeoutHandle !== null)
|
|
330
|
+
clearTimeout(timeoutHandle);
|
|
280
331
|
await cleanupSpillFile(this.mcpSpillPath);
|
|
281
332
|
this.mcpSpillPath = null;
|
|
282
333
|
}
|
package/dist/transport.d.ts
CHANGED
|
@@ -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