amplifier-agent-ts 0.7.1 → 0.8.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.
@@ -12,9 +12,22 @@
12
12
  export interface AssembleArgvInput {
13
13
  /** Session identifier (provided by caller, never generated here). */
14
14
  sessionId: string;
15
- /** Final user prompt — emitted last as a positional argument. */
15
+ /**
16
+ * Final user prompt — emitted last as a positional argument, behind a
17
+ * literal `--` separator. Ignored when `promptFile` is set.
18
+ */
16
19
  prompt: string;
17
- /** Protocol version the wrapper speaks (e.g. "0.3.0"). */
20
+ /**
21
+ * Path to a spill file holding the prompt, produced upstream by
22
+ * `resolvePromptFilePath` in `prompt-spill.ts`. When set, the prompt rides
23
+ * on `--prompt-file <path>` and NO positional prompt is emitted; the two
24
+ * transports are mutually exclusive and the engine rejects both at once
25
+ * with `argv_prompt_conflict`.
26
+ *
27
+ * Defaults to undefined, so callers that never spill are unaffected.
28
+ */
29
+ promptFile?: string;
30
+ /** Protocol version the wrapper speaks (e.g. "0.4.0"). */
18
31
  protocolVersion: string;
19
32
  /** When true, emit `--resume` instead of `--fresh`. */
20
33
  resume?: boolean;
@@ -77,7 +77,20 @@ export function assembleArgv(input) {
77
77
  else {
78
78
  // mode === "prompt": deliberately emit no flag.
79
79
  }
80
- // Prompt is the final positional argument.
80
+ // Prompt transport. When the prompt was spilled to a file upstream it rides
81
+ // on --prompt-file and NO positional is emitted; argv has hard size ceilings
82
+ // (131072 bytes per element on Linux, 32767 chars for the whole command line
83
+ // on Windows) that a large turn context blows straight past.
84
+ if (input.promptFile !== undefined) {
85
+ argv.push("--prompt-file", input.promptFile);
86
+ return argv;
87
+ }
88
+ // Otherwise the prompt is the final positional argument, always preceded by
89
+ // a literal "--". Unconditional, not conditional on a leading '-': a guard
90
+ // is a second thing to get wrong, and the engine already accepts "--" for
91
+ // every prompt. Without it, click parses a '-'-leading prompt as an option
92
+ // and the turn dies exit 2 with "No such option".
93
+ argv.push("--");
81
94
  argv.push(input.prompt);
82
95
  return argv;
83
96
  }
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * at spawn-time** — the engine is launched per `submit()` (amendment §5.2).
9
9
  */
10
10
  export { AaaError, SessionHandle, DEFAULT_TIMEOUT_MS } from "./session.js";
11
- export type { DisplayEvent, EngineInfo, SessionHandleParams, } from "./session.js";
11
+ export type { DisplayEvent, EngineInfo, SessionHandleParams, Usage, } from "./session.js";
12
12
  export type { ApprovalResponse } from "./approval.js";
13
13
  export type { EngineVersionPayload } from "./spawn.js";
14
14
  /** @public */
@@ -36,9 +36,9 @@ export { checkProtocolVersion } from "./version.js";
36
36
  /** @public */
37
37
  export type { VersionCheckResult, VersionCheckOk, VersionCheckFail, CheckProtocolVersionOptions, } from "./version.js";
38
38
  /** @public */
39
- export { parseRunOutput, STDERR_TAIL_BYTES } from "./run-output-parser.js";
39
+ export { parseRunOutput, tailStderrBytes, STDERR_TAIL_BYTES, } from "./run-output-parser.js";
40
40
  /** @public */
41
- export type { SubprocessOutcome } from "./run-output-parser.js";
41
+ export type { SubprocessOutcome, ParseRunOutputOptions, } from "./run-output-parser.js";
42
42
  /** @public */
43
43
  export { makeApprovalHandler } from "./approval.js";
44
44
  /** @public */
@@ -56,8 +56,12 @@ export type { ChildProcessFactory } from "./session.js";
56
56
  * checked at `spawnAgent()` time against the engine's reported protocol
57
57
  * version (see Issue #9 — `checkProtocolVersion()` is wired into the init
58
58
  * path so skew fails fast wrapper-side before any subprocess spawn).
59
+ *
60
+ * 0.4.0 added the envelope's per-turn usage block (`cacheReadTokens`,
61
+ * `cacheWriteTokens`, `costUsd`, and real `tokensIn`/`tokensOut`) that the
62
+ * `usage` field on the terminal `result` / `error` events surfaces.
59
63
  */
60
- export declare const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.3.0";
64
+ export declare const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.4.0";
61
65
  /** Parameters for spawnAgent(). Signature is locked verbatim by design §8.2. */
62
66
  export interface SpawnAgentParams {
63
67
  /** 'burst' reserved; throws AaaError(lifecycle_unsupported) at runtime. */
@@ -182,6 +186,24 @@ export interface SpawnAgentParams {
182
186
  * Mirrors the engine-side `host_config.allowProtocolSkew` knob.
183
187
  */
184
188
  allowProtocolSkew?: boolean;
189
+ /**
190
+ * Byte cap on `stderrTail` for the terminal `result` / `error` events.
191
+ *
192
+ * - a positive number — the last N UTF-8 BYTES of the engine's stderr,
193
+ * never split mid-codepoint. Trimming to a codepoint boundary can yield
194
+ * slightly fewer than N bytes; that is correct.
195
+ * - `null` — the ENTIRE stderr buffer, uncapped.
196
+ * - `0` — capture disabled; `stderrTail` is omitted.
197
+ * - omitted — `STDERR_TAIL_BYTES` (4096) applies, which preserves
198
+ * the historical `error`-event behaviour exactly.
199
+ *
200
+ * One knob governs both terminal events. The cap is in BYTES, not
201
+ * characters: a character count is meaningless for budgeting a payload the
202
+ * moment stderr contains non-ASCII.
203
+ *
204
+ * @public
205
+ */
206
+ stderrTailBytes?: number | null;
185
207
  /** Replaces the real resolveBinaryPath() call. */
186
208
  _binaryResolver?: () => string;
187
209
  /**
package/dist/index.js CHANGED
@@ -39,7 +39,7 @@ export { Transport, parseNdjsonStream } from "./transport.js";
39
39
  /** @public */
40
40
  export { checkProtocolVersion } from "./version.js";
41
41
  /** @public */
42
- export { parseRunOutput, STDERR_TAIL_BYTES } from "./run-output-parser.js";
42
+ export { parseRunOutput, tailStderrBytes, STDERR_TAIL_BYTES, } from "./run-output-parser.js";
43
43
  /** @public */
44
44
  export { makeApprovalHandler } from "./approval.js";
45
45
  // Internal imports used by spawnAgent().
@@ -52,8 +52,12 @@ import { checkProtocolVersion } from "./version.js";
52
52
  * checked at `spawnAgent()` time against the engine's reported protocol
53
53
  * version (see Issue #9 — `checkProtocolVersion()` is wired into the init
54
54
  * path so skew fails fast wrapper-side before any subprocess spawn).
55
+ *
56
+ * 0.4.0 added the envelope's per-turn usage block (`cacheReadTokens`,
57
+ * `cacheWriteTokens`, `costUsd`, and real `tokensIn`/`tokensOut`) that the
58
+ * `usage` field on the terminal `result` / `error` events surfaces.
55
59
  */
56
- export const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.3.0";
60
+ export const PROTOCOL_VERSION_REQUIRED_BY_WRAPPER = "0.4.0";
57
61
  // ---------------------------------------------------------------------------
58
62
  // spawnAgent() — locked public entry point (Mode A v2)
59
63
  // ---------------------------------------------------------------------------
@@ -201,6 +205,13 @@ export async function spawnAgent(params) {
201
205
  // Issue #4: thread display.onEvent through so SessionHandle can
202
206
  // dispatch parsed NDJSON wire events to it.
203
207
  ...(params.display !== undefined ? { display: params.display } : {}),
208
+ // Forward the stderr-tail byte cap so the terminal result/error events
209
+ // carry exactly as much stderr as the host asked for. `null` is a
210
+ // meaningful value (the whole buffer), so it must be forwarded rather
211
+ // than treated as "unset".
212
+ ...(params.stderrTailBytes !== undefined
213
+ ? { stderrTailBytes: params.stderrTailBytes }
214
+ : {}),
204
215
  // Issue #7: persist engine metadata resolved during the probe.
205
216
  engineVersion: engineVersionPayload.version,
206
217
  bundleDigest: engineVersionPayload.bundleDigest ?? "",
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Spill any prompt whose UTF-8 encoded length reaches this many bytes.
3
+ *
4
+ * The threshold must sit safely under the SMALLEST platform ceiling. That is
5
+ * NOT Linux's 131072-byte per-element cap — it is Windows' 32767-CHARACTER cap
6
+ * on the ENTIRE command line, which the prompt shares with the binary path and
7
+ * every other flag (`--session-id`, `--config`, `--cwd`, `--workspace`, ...).
8
+ * 16384 leaves roughly half of that budget as headroom for the rest of the
9
+ * argv, and still keeps ordinary prompts on the fast in-memory path.
10
+ *
11
+ * The comparison is made against the UTF-8 ENCODED byte length
12
+ * (`Buffer.byteLength(prompt, "utf8")`), never `prompt.length`: a multibyte
13
+ * prompt occupies more bytes on the wire than it has characters, and the OS
14
+ * limit is denominated in bytes.
15
+ */
16
+ export declare const PROMPT_SPILL_THRESHOLD_BYTES = 16384;
17
+ /**
18
+ * Result of deciding whether to spill the prompt to a tmpfile.
19
+ *
20
+ * - When the prompt fits on argv: `promptFile` is `null` and the caller passes
21
+ * the prompt positionally as before.
22
+ * - Otherwise: `promptFile` points at the 0600 spill file containing the
23
+ * prompt text verbatim, and the caller emits `--prompt-file <path>` with no
24
+ * positional prompt.
25
+ */
26
+ export interface PromptSpillResult {
27
+ promptFile: string | null;
28
+ }
29
+ /**
30
+ * Resolve the prompt file path to pass as `--prompt-file`.
31
+ *
32
+ * Spills to a 0600 tmpfile under a 0700 per-session dir when the prompt's
33
+ * UTF-8 byte length reaches `PROMPT_SPILL_THRESHOLD_BYTES`; otherwise does no
34
+ * I/O at all and reports `promptFile: null`.
35
+ *
36
+ * The write completes — and the file handle is closed — before this promise
37
+ * resolves, which matters on Windows, where a child process cannot open a file
38
+ * the parent still holds. The content is the prompt text verbatim: UTF-8, with
39
+ * no newline translation, because the engine reads the file as strict `utf-8`
40
+ * and any `\n` → `\r\n` rewrite would corrupt the caller's prompt in transit.
41
+ *
42
+ * @param prompt The caller's prompt text.
43
+ * @param sessionId Session identifier; used as the per-session subdirectory
44
+ * under the spill base so concurrent sessions never clash.
45
+ *
46
+ * @returns A `PromptSpillResult` with the on-disk prompt path (or null when
47
+ * the prompt is small enough to travel as a positional argv element).
48
+ */
49
+ export declare function resolvePromptFilePath(prompt: string, sessionId: string): Promise<PromptSpillResult>;
50
+ /**
51
+ * Idempotently remove a prompt spill file. Safe to call with `null` (no-op)
52
+ * and safe to call when the file is already gone (ENOENT swallowed). Other
53
+ * I/O errors propagate.
54
+ */
55
+ export declare function cleanupPromptSpillFile(promptFile: string | null | undefined): Promise<void>;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * prompt-spill.ts — oversized-prompt spill-to-file resolution.
3
+ *
4
+ * Companion to `mcp-spill.ts` and structured identically. A large prompt
5
+ * cannot ride on argv: it travels as the final positional element, and a
6
+ * single argv element is capped at `MAX_ARG_STRLEN` (131072 bytes) on Linux
7
+ * while the whole command line is capped at 32767 chars on Windows. Past
8
+ * those ceilings the spawn fails with `E2BIG` before the engine even boots.
9
+ * So the wrapper spills the prompt to a 0600 tmpfile under
10
+ * `${XDG_RUNTIME_DIR || os.tmpdir()}/amplifier-agent/<sessionId>/prompt.txt`
11
+ * and passes `--prompt-file <path>` instead of the positional argument.
12
+ *
13
+ * This mirrors the treatment the MCP server map already gets — see
14
+ * docs/spec/wrapper-contract.md, "Prompt spill".
15
+ *
16
+ * `cleanupPromptSpillFile` is the matching teardown — idempotent unlink that
17
+ * swallows ENOENT so callers can call it unconditionally on every exit path.
18
+ */
19
+ import { mkdir, writeFile, unlink } from "node:fs/promises";
20
+ import { tmpdir } from "node:os";
21
+ import { join } from "node:path";
22
+ /**
23
+ * Spill any prompt whose UTF-8 encoded length reaches this many bytes.
24
+ *
25
+ * The threshold must sit safely under the SMALLEST platform ceiling. That is
26
+ * NOT Linux's 131072-byte per-element cap — it is Windows' 32767-CHARACTER cap
27
+ * on the ENTIRE command line, which the prompt shares with the binary path and
28
+ * every other flag (`--session-id`, `--config`, `--cwd`, `--workspace`, ...).
29
+ * 16384 leaves roughly half of that budget as headroom for the rest of the
30
+ * argv, and still keeps ordinary prompts on the fast in-memory path.
31
+ *
32
+ * The comparison is made against the UTF-8 ENCODED byte length
33
+ * (`Buffer.byteLength(prompt, "utf8")`), never `prompt.length`: a multibyte
34
+ * prompt occupies more bytes on the wire than it has characters, and the OS
35
+ * limit is denominated in bytes.
36
+ */
37
+ export const PROMPT_SPILL_THRESHOLD_BYTES = 16384;
38
+ /**
39
+ * Compute the base directory for spill files. Prefers
40
+ * `$XDG_RUNTIME_DIR/amplifier-agent` (typically a tmpfs on Linux) and falls
41
+ * back to `os.tmpdir()/amplifier-agent` otherwise.
42
+ */
43
+ function spillBaseDir() {
44
+ const xdg = process.env["XDG_RUNTIME_DIR"];
45
+ if (xdg && xdg.length > 0) {
46
+ return join(xdg, "amplifier-agent");
47
+ }
48
+ return join(tmpdir(), "amplifier-agent");
49
+ }
50
+ /**
51
+ * Resolve the prompt file path to pass as `--prompt-file`.
52
+ *
53
+ * Spills to a 0600 tmpfile under a 0700 per-session dir when the prompt's
54
+ * UTF-8 byte length reaches `PROMPT_SPILL_THRESHOLD_BYTES`; otherwise does no
55
+ * I/O at all and reports `promptFile: null`.
56
+ *
57
+ * The write completes — and the file handle is closed — before this promise
58
+ * resolves, which matters on Windows, where a child process cannot open a file
59
+ * the parent still holds. The content is the prompt text verbatim: UTF-8, with
60
+ * no newline translation, because the engine reads the file as strict `utf-8`
61
+ * and any `\n` → `\r\n` rewrite would corrupt the caller's prompt in transit.
62
+ *
63
+ * @param prompt The caller's prompt text.
64
+ * @param sessionId Session identifier; used as the per-session subdirectory
65
+ * under the spill base so concurrent sessions never clash.
66
+ *
67
+ * @returns A `PromptSpillResult` with the on-disk prompt path (or null when
68
+ * the prompt is small enough to travel as a positional argv element).
69
+ */
70
+ export async function resolvePromptFilePath(prompt, sessionId) {
71
+ if (Buffer.byteLength(prompt, "utf8") < PROMPT_SPILL_THRESHOLD_BYTES) {
72
+ return { promptFile: null };
73
+ }
74
+ const dir = join(spillBaseDir(), sessionId);
75
+ await mkdir(dir, { recursive: true, mode: 0o700 });
76
+ const filePath = join(dir, "prompt.txt");
77
+ // The prompt is caller data and may carry secrets, so the file is created
78
+ // 0600. `writeFile` opens, writes and closes before the promise resolves.
79
+ await writeFile(filePath, prompt, { encoding: "utf8", mode: 0o600 });
80
+ return { promptFile: filePath };
81
+ }
82
+ /**
83
+ * Idempotently remove a prompt spill file. Safe to call with `null` (no-op)
84
+ * and safe to call when the file is already gone (ENOENT swallowed). Other
85
+ * I/O errors propagate.
86
+ */
87
+ export async function cleanupPromptSpillFile(promptFile) {
88
+ if (!promptFile)
89
+ return;
90
+ try {
91
+ await unlink(promptFile);
92
+ }
93
+ catch (err) {
94
+ const code = err.code;
95
+ if (code === "ENOENT")
96
+ return;
97
+ throw err;
98
+ }
99
+ }
@@ -11,13 +11,22 @@
11
11
  * Rule 2 — envelope absent / unparseable / partial → synthesize an error
12
12
  * event from exit code and stderr tail. Partial JSON is NOT
13
13
  * half-parsed (belt-and-suspenders): if any required §4.1 field
14
- * is missing, the envelope is treated as unparseable.
14
+ * is missing, the envelope is treated as unparseable. The turn id
15
+ * is unknowable here (the engine assigns it), but the SESSION id is
16
+ * the caller's own — pass it as `fallbackSessionId` and it is
17
+ * reported rather than dropped.
15
18
  *
16
- * stderrTail is truncated to STDERR_TAIL_BYTES (4096) on synthesized paths;
17
- * on the envelope path it is taken verbatim from the engine.
19
+ * On the Rule 1 path the envelope is now *read*, not merely shape-checked:
20
+ * `sessionId`, `turnId` and the `metadata` usage block are surfaced on the
21
+ * terminal event. The wrapper performs no arithmetic of its own — the engine's
22
+ * UsageAccumulator already summed the turn, so re-summing here would
23
+ * double-count.
24
+ *
25
+ * `stderrTail` is bounded by `stderrTailBytes` in real UTF-8 BYTES (see
26
+ * `tailStderrBytes`); `STDERR_TAIL_BYTES` (4096) is the default.
18
27
  */
19
28
  import type { DisplayEvent } from "./session.js";
20
- /** Maximum stderrTail length retained on synthesized engine errors. */
29
+ /** Default cap on `stderrTail`, in BYTES of UTF-8. */
21
30
  export declare const STDERR_TAIL_BYTES = 4096;
22
31
  /** Outcome of running the `amplifier-agent run --output json` subprocess. */
23
32
  export interface SubprocessOutcome {
@@ -25,9 +34,58 @@ export interface SubprocessOutcome {
25
34
  stderr: string;
26
35
  exitCode: number;
27
36
  }
37
+ /** Options for `parseRunOutput`. */
38
+ export interface ParseRunOutputOptions {
39
+ /**
40
+ * Byte cap for `stderrTail` on the returned event.
41
+ *
42
+ * - a positive number — at most that many UTF-8 BYTES, taken from the end.
43
+ * - `null` — the ENTIRE stderr buffer, uncapped.
44
+ * - `0` — capture disabled; `stderrTail` is omitted.
45
+ * - `undefined` — not supplied; `STDERR_TAIL_BYTES` (4096) applies.
46
+ *
47
+ * The cap applies to whatever ends up in `stderrTail`, including a tail the
48
+ * engine supplied inside the envelope, so `0` really does mean "do not give
49
+ * me stderr".
50
+ */
51
+ stderrTailBytes?: number | null;
52
+ /**
53
+ * The caller's own session id, reported on the SYNTHESIZED (Rule 2) events
54
+ * only. Never overrides the envelope: on the Rule 1 path the envelope's
55
+ * `sessionId` is authoritative and this option is ignored.
56
+ *
57
+ * `undefined` (the default) preserves the previous behaviour of omitting the
58
+ * field — a caller with no session id to offer, such as a host post-parsing
59
+ * a captured payload, is not made to invent one.
60
+ */
61
+ fallbackSessionId?: string;
62
+ }
63
+ /**
64
+ * Return the last `limit` BYTES of `text`, never splitting a codepoint.
65
+ *
66
+ * The cap is expressed in bytes because that is what a host budgeting a log
67
+ * line or a payload actually cares about; a character count is meaningless for
68
+ * that purpose the moment stderr contains non-ASCII. JavaScript strings are
69
+ * UTF-16 code units, so `String.prototype.slice` cannot express this — the
70
+ * work happens on a `Buffer`.
71
+ *
72
+ * `limit` semantics: a positive number caps to that many UTF-8 bytes, `null`
73
+ * means the whole buffer, `undefined` falls back to `STDERR_TAIL_BYTES`, and
74
+ * `0` (or negative) disables capture and returns `undefined`. An empty `text`
75
+ * always returns `undefined`: there is nothing to report.
76
+ *
77
+ * Boundary safety: after slicing the encoded buffer, leading UTF-8
78
+ * continuation bytes (`0b10xxxxxx`) are dropped so the slice begins on a lead
79
+ * byte. The result therefore decodes cleanly — no U+FFFD — at the cost of up
80
+ * to 3 bytes fewer than `limit`. Returning slightly less than the cap is
81
+ * correct; returning a broken character is not.
82
+ *
83
+ * @public
84
+ */
85
+ export declare function tailStderrBytes(text: string, limit?: number | null | undefined): string | undefined;
28
86
  /**
29
87
  * Parse a subprocess outcome into a single DisplayEvent.
30
88
  *
31
89
  * See module docstring for precedence rules.
32
90
  */
33
- export declare function parseRunOutput(outcome: SubprocessOutcome): DisplayEvent;
91
+ export declare function parseRunOutput(outcome: SubprocessOutcome, options?: ParseRunOutputOptions): DisplayEvent;
@@ -11,26 +11,65 @@
11
11
  * Rule 2 — envelope absent / unparseable / partial → synthesize an error
12
12
  * event from exit code and stderr tail. Partial JSON is NOT
13
13
  * half-parsed (belt-and-suspenders): if any required §4.1 field
14
- * is missing, the envelope is treated as unparseable.
14
+ * is missing, the envelope is treated as unparseable. The turn id
15
+ * is unknowable here (the engine assigns it), but the SESSION id is
16
+ * the caller's own — pass it as `fallbackSessionId` and it is
17
+ * reported rather than dropped.
15
18
  *
16
- * stderrTail is truncated to STDERR_TAIL_BYTES (4096) on synthesized paths;
17
- * on the envelope path it is taken verbatim from the engine.
19
+ * On the Rule 1 path the envelope is now *read*, not merely shape-checked:
20
+ * `sessionId`, `turnId` and the `metadata` usage block are surfaced on the
21
+ * terminal event. The wrapper performs no arithmetic of its own — the engine's
22
+ * UsageAccumulator already summed the turn, so re-summing here would
23
+ * double-count.
24
+ *
25
+ * `stderrTail` is bounded by `stderrTailBytes` in real UTF-8 BYTES (see
26
+ * `tailStderrBytes`); `STDERR_TAIL_BYTES` (4096) is the default.
18
27
  */
19
- /** Maximum stderrTail length retained on synthesized engine errors. */
28
+ /** Default cap on `stderrTail`, in BYTES of UTF-8. */
20
29
  export const STDERR_TAIL_BYTES = 4096;
21
30
  /** Maximum stdout snippet included in `envelope_missing` messages. */
22
31
  const STDOUT_PREVIEW_BYTES = 512;
23
32
  /**
24
- * Keep the last `STDERR_TAIL_BYTES` chars of `stderr`.
25
- * Returns `undefined` for an empty string so callers can omit the field
26
- * cleanly when there is nothing to surface.
33
+ * Return the last `limit` BYTES of `text`, never splitting a codepoint.
34
+ *
35
+ * The cap is expressed in bytes because that is what a host budgeting a log
36
+ * line or a payload actually cares about; a character count is meaningless for
37
+ * that purpose the moment stderr contains non-ASCII. JavaScript strings are
38
+ * UTF-16 code units, so `String.prototype.slice` cannot express this — the
39
+ * work happens on a `Buffer`.
40
+ *
41
+ * `limit` semantics: a positive number caps to that many UTF-8 bytes, `null`
42
+ * means the whole buffer, `undefined` falls back to `STDERR_TAIL_BYTES`, and
43
+ * `0` (or negative) disables capture and returns `undefined`. An empty `text`
44
+ * always returns `undefined`: there is nothing to report.
45
+ *
46
+ * Boundary safety: after slicing the encoded buffer, leading UTF-8
47
+ * continuation bytes (`0b10xxxxxx`) are dropped so the slice begins on a lead
48
+ * byte. The result therefore decodes cleanly — no U+FFFD — at the cost of up
49
+ * to 3 bytes fewer than `limit`. Returning slightly less than the cap is
50
+ * correct; returning a broken character is not.
51
+ *
52
+ * @public
27
53
  */
28
- function tailStderr(stderr) {
29
- if (!stderr)
54
+ export function tailStderrBytes(text, limit = STDERR_TAIL_BYTES) {
55
+ if (!text)
56
+ return undefined;
57
+ if (limit === null)
58
+ return text;
59
+ const cap = limit === undefined ? STDERR_TAIL_BYTES : limit;
60
+ if (cap <= 0)
30
61
  return undefined;
31
- if (stderr.length <= STDERR_TAIL_BYTES)
32
- return stderr;
33
- return stderr.slice(stderr.length - STDERR_TAIL_BYTES);
62
+ const raw = Buffer.from(text, "utf-8");
63
+ if (raw.length <= cap)
64
+ return text;
65
+ let start = raw.length - cap;
66
+ // A UTF-8 continuation byte matches 0b10xxxxxx; a lead byte never does. The
67
+ // source is a valid string, so at most 3 continuation bytes can precede the
68
+ // first lead byte in the window.
69
+ while (start < raw.length && (raw[start] & 0xc0) === 0x80) {
70
+ start += 1;
71
+ }
72
+ return raw.subarray(start).toString("utf-8");
34
73
  }
35
74
  const VALID_CLASSIFICATIONS = new Set([
36
75
  "transport",
@@ -39,6 +78,58 @@ const VALID_CLASSIFICATIONS = new Set([
39
78
  "approval",
40
79
  "unknown",
41
80
  ]);
81
+ /**
82
+ * The envelope `metadata` keys that make up a usage report. Presence of at
83
+ * least one of them is what distinguishes "the engine reported usage" from
84
+ * "this engine predates protocol 0.4.0 and reported none".
85
+ */
86
+ const USAGE_KEYS = [
87
+ "tokensIn",
88
+ "tokensOut",
89
+ "cacheReadTokens",
90
+ "cacheWriteTokens",
91
+ "costUsd",
92
+ ];
93
+ /**
94
+ * Coerce a wire token count to a number, defaulting to 0.
95
+ *
96
+ * Deliberately total: a malformed count must not be able to turn a completed
97
+ * turn into a throw on the host's side.
98
+ */
99
+ function toInt(value) {
100
+ if (typeof value === "number" && Number.isFinite(value))
101
+ return Math.trunc(value);
102
+ if (typeof value === "string") {
103
+ const parsed = Number(value);
104
+ if (Number.isFinite(parsed))
105
+ return Math.trunc(parsed);
106
+ }
107
+ return 0;
108
+ }
109
+ /**
110
+ * Read the envelope's `metadata` usage block into a `Usage`.
111
+ *
112
+ * Returns `undefined` when the metadata carries none of the usage keys at all
113
+ * — an engine older than protocol 0.4.0 never reported them, and claiming
114
+ * zeroes on its behalf would be a fabricated number rather than an absent one.
115
+ */
116
+ function usageFromMetadata(metadata) {
117
+ if (!USAGE_KEYS.some((key) => key in metadata))
118
+ return undefined;
119
+ // costUsd stays a STRING on the TS side. See the `Usage` doc comment in
120
+ // session.ts for why this is a deliberate parity exception.
121
+ const rawCost = metadata.costUsd;
122
+ const costUsd = typeof rawCost === "string" ? rawCost : rawCost == null ? null : String(rawCost);
123
+ return {
124
+ // Mirrors the envelope verbatim: tokensIn is the CHARGED total the engine
125
+ // already computed. No wrapper-side arithmetic.
126
+ inputTokens: toInt(metadata.tokensIn),
127
+ outputTokens: toInt(metadata.tokensOut),
128
+ cacheReadTokens: toInt(metadata.cacheReadTokens),
129
+ cacheWriteTokens: toInt(metadata.cacheWriteTokens),
130
+ costUsd,
131
+ };
132
+ }
42
133
  /**
43
134
  * Validate that `parsed` conforms to the §4.1 envelope shape.
44
135
  *
@@ -77,7 +168,9 @@ function isShapeValid(parsed) {
77
168
  *
78
169
  * See module docstring for precedence rules.
79
170
  */
80
- export function parseRunOutput(outcome) {
171
+ export function parseRunOutput(outcome, options = {}) {
172
+ const tailBytes = options.stderrTailBytes;
173
+ const fallbackSessionId = options.fallbackSessionId;
81
174
  const trimmed = outcome.stdout.trim();
82
175
  // Attempt to parse stdout as JSON. Failures (empty, partial, non-JSON) are
83
176
  // captured silently; the caller falls to Rule 2.
@@ -93,9 +186,21 @@ export function parseRunOutput(outcome) {
93
186
  // Rule 1 — envelope parseable per §4.1 → envelope wins.
94
187
  if (parsed !== null && isShapeValid(parsed)) {
95
188
  const env = parsed;
189
+ const usage = usageFromMetadata(env.metadata);
96
190
  if (env.error === null) {
97
- // Success path — exit code is informational only.
98
- return { type: "result", text: env.reply };
191
+ // Success path — exit code is informational only, but still reported as
192
+ // observed so a host can see a post-flush crash (a result event carrying
193
+ // a non-zero exitCode).
194
+ const stderrTail = tailStderrBytes(outcome.stderr, tailBytes);
195
+ return {
196
+ type: "result",
197
+ text: env.reply,
198
+ sessionId: env.sessionId,
199
+ turnId: env.turnId,
200
+ exitCode: outcome.exitCode,
201
+ ...(usage !== undefined ? { usage } : {}),
202
+ ...(stderrTail !== undefined ? { stderrTail } : {}),
203
+ };
99
204
  }
100
205
  // Failure path — populate from the envelope's error fields.
101
206
  const err = env.error;
@@ -106,7 +211,8 @@ export function parseRunOutput(outcome) {
106
211
  const severity = err.severity === "warning" ? "warning" : "error";
107
212
  const correlationId = typeof err.correlationId === "string" ? err.correlationId : "";
108
213
  const message = typeof err.message === "string" ? err.message : err.code;
109
- const stderrTail = typeof err.stderrTail === "string" ? err.stderrTail : tailStderr(outcome.stderr);
214
+ const sourceTail = typeof err.stderrTail === "string" ? err.stderrTail : outcome.stderr;
215
+ const stderrTail = tailStderrBytes(sourceTail, tailBytes);
110
216
  return {
111
217
  type: "error",
112
218
  code: err.code,
@@ -116,10 +222,21 @@ export function parseRunOutput(outcome) {
116
222
  message,
117
223
  ...(stderrTail !== undefined ? { stderrTail } : {}),
118
224
  retryable: false,
225
+ sessionId: env.sessionId,
226
+ turnId: env.turnId,
227
+ exitCode: outcome.exitCode,
228
+ ...(usage !== undefined ? { usage } : {}),
119
229
  };
120
230
  }
121
231
  // Rule 2 — envelope absent or unparseable → synthesize from exit + stderr.
122
- const stderrTail = tailStderr(outcome.stderr);
232
+ // No envelope means no turnId and no usage to report: the engine assigns the
233
+ // turn id and nothing came back, so inventing one would be a fabrication.
234
+ // The SESSION id is different — the caller minted it and passed it in as
235
+ // `fallbackSessionId`, so a host correlating this failure against its own
236
+ // records still gets the handle it already knows. The exit code remains
237
+ // load-bearing for the code/classification split below.
238
+ const stderrTail = tailStderrBytes(outcome.stderr, tailBytes);
239
+ const sessionIdField = fallbackSessionId !== undefined ? { sessionId: fallbackSessionId } : {};
123
240
  if (outcome.exitCode === 0) {
124
241
  // Engine protocol violation: exit 0 without a parseable envelope.
125
242
  const preview = outcome.stdout.slice(0, STDOUT_PREVIEW_BYTES);
@@ -133,6 +250,8 @@ export function parseRunOutput(outcome) {
133
250
  message: `Engine exited 0 without emitting a parseable §4.1 envelope. Stdout was: ${JSON.stringify(preview)}${previewSuffix}`,
134
251
  ...(stderrTail !== undefined ? { stderrTail } : {}),
135
252
  retryable: false,
253
+ ...sessionIdField,
254
+ exitCode: outcome.exitCode,
136
255
  };
137
256
  }
138
257
  // Non-zero exit, envelope absent or partial — engine-class failure.
@@ -145,5 +264,7 @@ export function parseRunOutput(outcome) {
145
264
  message: `Engine exited ${outcome.exitCode} without emitting a parseable §4.1 envelope.`,
146
265
  ...(stderrTail !== undefined ? { stderrTail } : {}),
147
266
  retryable: false,
267
+ ...sessionIdField,
268
+ exitCode: outcome.exitCode,
148
269
  };
149
270
  }
package/dist/session.d.ts CHANGED
@@ -40,23 +40,117 @@ import type { McpServerConfig } from "./types.js";
40
40
  * @public
41
41
  */
42
42
  export type ChildProcessFactory = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;
43
+ /**
44
+ * Per-turn token and cost accounting, as reported by the engine.
45
+ *
46
+ * Read straight off the §4.1 envelope's `metadata` block. The wrapper does NOT
47
+ * sum anything: the engine's `UsageAccumulator` already folded every `usage`
48
+ * display event of the turn (including sub-agent LLM calls) into these totals,
49
+ * so re-summing wrapper-side would double-count.
50
+ *
51
+ * PARITY NOTE — `costUsd` is the one field where the two wrappers deliberately
52
+ * differ. The Python wrapper parses it into a `Decimal`; TypeScript keeps the
53
+ * decimal STRING the engine put on the wire. JavaScript has no decimal type,
54
+ * and `number` is an IEEE-754 binary double: `0.1 + 0.2 !== 0.3`, so parsing a
55
+ * monetary value into one loses precision the moment a host sums a few turns.
56
+ * Handing back the exact string the engine emitted lets a host feed it to
57
+ * whichever decimal library it already uses. This asymmetry is a language
58
+ * constraint, not drift — see `Usage.cost_usd` in
59
+ * wrappers/python-py/src/amplifier_agent_py/types.py.
60
+ *
61
+ * @public
62
+ */
63
+ export interface Usage {
64
+ /**
65
+ * Input tokens **charged**, mirroring the envelope's `tokensIn`. This is the
66
+ * provider's gross input plus cache writes. Cache reads are already counted
67
+ * inside the gross input, so `cacheReadTokens` is a SUBSET of this value, not
68
+ * an addend. A host that wants the fresh-only figure derives it as
69
+ * `inputTokens - cacheReadTokens - cacheWriteTokens`.
70
+ */
71
+ inputTokens: number;
72
+ /** Output tokens (envelope `tokensOut`). */
73
+ outputTokens: number;
74
+ /**
75
+ * The portion of `inputTokens` the provider served from its prompt cache.
76
+ * Already included above; never add it on top.
77
+ */
78
+ cacheReadTokens: number;
79
+ /**
80
+ * Input tokens written into the provider's prompt cache. Billed on top of the
81
+ * gross input, so this IS a component of `inputTokens`.
82
+ */
83
+ cacheWriteTokens: number;
84
+ /**
85
+ * Turn cost as a decimal STRING (never a number — see the parity note on
86
+ * this interface). `null` when no provider reported a cost; that is not the
87
+ * same claim as `"0"`.
88
+ */
89
+ costUsd: string | null;
90
+ }
43
91
  /**
44
92
  * A display event yielded by `SessionHandle.submit()`.
45
93
  *
46
94
  * Mode A v2 (CR-C, amendment §5.2): a discriminated union narrow enough that
47
95
  * every variant's payload is exhaustively typed. The fields removed from the
48
- * pre-amendment shape (`turnId`, `parentTurnId`, `synthesized`, `payload`)
49
- * cannot be meaningfully populated on the Mode A wire.
96
+ * pre-amendment shape (`parentTurnId`, `synthesized`, `payload`) cannot be
97
+ * meaningfully populated on the Mode A wire.
50
98
  */
51
99
  export type DisplayEvent = {
52
100
  type: "init";
53
101
  sessionId: string;
54
102
  } | {
55
103
  type: "activity";
56
- } | {
104
+ }
105
+ /**
106
+ * Terminal success event. `sessionId` / `turnId` / `exitCode` are never
107
+ * optional: a `result` event exists only on the envelope path, so the
108
+ * identity fields the envelope carries are always known. (The `error`
109
+ * variant can be synthesized with no envelope at all, which is why its
110
+ * equivalents are optional there.)
111
+ *
112
+ * `usage` is absent only when the envelope's `metadata` carried no usage
113
+ * keys whatsoever — an engine older than protocol 0.4.0. Absent means "not
114
+ * reported", which is a different claim from a present `Usage` reading zero
115
+ * (a turn that made no LLM call really did spend nothing).
116
+ *
117
+ * `stderrTail` holds the last `stderrTailBytes` BYTES of the engine's
118
+ * stderr, or the whole buffer when that option is `null`, or is omitted when
119
+ * it is `0` or stderr was empty.
120
+ */
121
+ | {
57
122
  type: "result";
58
123
  text: string;
59
- } | {
124
+ sessionId: string;
125
+ turnId: string;
126
+ exitCode: number;
127
+ usage?: Usage;
128
+ stderrTail?: string;
129
+ }
130
+ /**
131
+ * Terminal failure event. `sessionId` / `turnId` / `exitCode` / `usage` are
132
+ * populated from the §4.1 envelope when one was parsed.
133
+ *
134
+ * On the synthesized (Rule 2) paths — envelope absent, unparseable, spawn
135
+ * failure, or hang — there is no envelope to read them from, and the fields
136
+ * split by who knows the answer:
137
+ *
138
+ * - `sessionId` IS present whenever the wrapper itself knows it, which is
139
+ * every failure raised through a `SessionHandle`: the handle was given the
140
+ * session id at construction time, so a host correlating the failure gets
141
+ * the same identifier it passed in. It is omitted only when
142
+ * `parseRunOutput` is called directly without a `fallbackSessionId`.
143
+ * - `turnId` is omitted. The engine assigns turn ids and no envelope came
144
+ * back, so the wrapper genuinely does not know it and will not invent one.
145
+ * - `exitCode` is present on the parser's Rule 2 paths (the process did
146
+ * exit) and omitted on spawn failure and hang, where it never did.
147
+ * - `usage` is omitted: only the envelope reports it.
148
+ *
149
+ * `usage` on the failure path is not a duplicate report: nothing else on the
150
+ * failure path carries usage, so a turn that burned tokens and then failed
151
+ * would otherwise spend them invisibly.
152
+ */
153
+ | {
60
154
  type: "error";
61
155
  code: string;
62
156
  classification: "transport" | "protocol" | "engine" | "approval" | "unknown";
@@ -65,6 +159,10 @@ export type DisplayEvent = {
65
159
  message: string;
66
160
  stderrTail?: string;
67
161
  retryable: boolean;
162
+ sessionId?: string;
163
+ turnId?: string;
164
+ exitCode?: number;
165
+ usage?: Usage;
68
166
  }
69
167
  /**
70
168
  * Wire-protocol notification dispatched from the engine's stderr NDJSON
@@ -179,8 +277,20 @@ export interface SessionHandleParams {
179
277
  * invalid slugs with `argv_workspace_invalid`.
180
278
  */
181
279
  workspace?: string;
182
- /** Protocol version the wrapper speaks (e.g. "0.3.0"). */
280
+ /** Protocol version the wrapper speaks (e.g. "0.4.0"). */
183
281
  protocolVersion: string;
282
+ /**
283
+ * Byte cap on `stderrTail` for BOTH the terminal `result` and `error`
284
+ * events.
285
+ *
286
+ * - a positive number — the last N UTF-8 BYTES, never split mid-codepoint.
287
+ * - `null` — the ENTIRE stderr buffer.
288
+ * - `0` — capture disabled; the field is omitted.
289
+ * - `undefined` — not supplied; `STDERR_TAIL_BYTES` (4096) applies,
290
+ * which preserves the historical `error`-event
291
+ * behaviour exactly.
292
+ */
293
+ stderrTailBytes?: number | null;
184
294
  /**
185
295
  * Per-submit timeout in milliseconds. No timeout is applied unless a
186
296
  * positive value is provided. `undefined` or `<= 0` disables the
@@ -230,6 +340,7 @@ export declare class SessionHandle {
230
340
  private submitted;
231
341
  private subprocess;
232
342
  private mcpSpillPath;
343
+ private promptSpillPath;
233
344
  private readonly engineInfo;
234
345
  constructor(params: SessionHandleParams);
235
346
  /** Return resolved engine metadata (D5). */
package/dist/session.js CHANGED
@@ -27,7 +27,8 @@
27
27
  import { spawn as childSpawn } from "node:child_process";
28
28
  import { assembleArgv } from "./argv-builder.js";
29
29
  import { resolveMcpConfigPath, cleanupSpillFile } from "./mcp-spill.js";
30
- import { parseRunOutput, STDERR_TAIL_BYTES } from "./run-output-parser.js";
30
+ import { resolvePromptFilePath, cleanupPromptSpillFile, } from "./prompt-spill.js";
31
+ import { parseRunOutput, tailStderrBytes } from "./run-output-parser.js";
31
32
  import { parseNdjsonStream } from "./transport.js";
32
33
  /** Typed error for AaA wrapper lifecycle and protocol violations. */
33
34
  export class AaaError extends Error {
@@ -85,20 +86,13 @@ export function waitForExitOrTimeout(child, ms) {
85
86
  });
86
87
  });
87
88
  }
88
- /** Last `STDERR_TAIL_BYTES` chars of `stderr`, or undefined if empty. */
89
- function stderrTailOf(stderr) {
90
- if (!stderr)
91
- return undefined;
92
- if (stderr.length <= STDERR_TAIL_BYTES)
93
- return stderr;
94
- return stderr.slice(stderr.length - STDERR_TAIL_BYTES);
95
- }
96
89
  /** One-shot session handle that drives the engine subprocess. */
97
90
  export class SessionHandle {
98
91
  params;
99
92
  submitted = false;
100
93
  subprocess = null;
101
94
  mcpSpillPath = null;
95
+ promptSpillPath = null;
102
96
  engineInfo;
103
97
  constructor(params) {
104
98
  this.params = params;
@@ -157,6 +151,15 @@ export class SessionHandle {
157
151
  // rejects assignability without the cast.
158
152
  const spill = await resolveMcpConfigPath((this.params.mcpServers ?? null), this.params.sessionId);
159
153
  this.mcpSpillPath = spill.configPath;
154
+ // (ii-b) Same treatment for an oversized prompt: spill it to a 0600
155
+ // tmpfile and pass --prompt-file, because argv is capped at 131072 bytes
156
+ // per element on Linux and 32767 chars for the whole command line on
157
+ // Windows. `promptFile` is null when the prompt is small enough to ride
158
+ // on argv positionally. This await also guarantees the file is fully
159
+ // written AND closed before the child is spawned — on Windows a child
160
+ // cannot open a file the parent still holds.
161
+ const promptSpill = await resolvePromptFilePath(prompt, this.params.sessionId);
162
+ this.promptSpillPath = promptSpill.promptFile;
160
163
  // (iii) build argv (pure function — no I/O). The MCP config path is
161
164
  // forwarded to the engine via AMPLIFIER_MCP_CONFIG (subprocess env)
162
165
  // rather than via an argv flag. `configPath` (Issue #1) and
@@ -165,6 +168,9 @@ export class SessionHandle {
165
168
  const argv = assembleArgv({
166
169
  sessionId: this.params.sessionId,
167
170
  prompt,
171
+ ...(promptSpill.promptFile !== null
172
+ ? { promptFile: promptSpill.promptFile }
173
+ : {}),
168
174
  protocolVersion: this.params.protocolVersion,
169
175
  resume: this.params.resume,
170
176
  cwd: this.params.cwd,
@@ -274,7 +280,7 @@ export class SessionHandle {
274
280
  timeoutHandle = setTimeout(() => {
275
281
  // Synthesize engine_hung before invoking cancel(), so the iterator
276
282
  // yields a terminal error even if SIGTERM/SIGKILL hangs.
277
- const tail = stderrTailOf(stderrBuf);
283
+ const tail = tailStderrBytes(stderrBuf, this.params.stderrTailBytes);
278
284
  finalize({
279
285
  type: "error",
280
286
  code: "engine_hung",
@@ -284,6 +290,9 @@ export class SessionHandle {
284
290
  message: `Engine subprocess hung past ${timeoutMs}ms timeout; SIGTERM/SIGKILL escalation invoked.`,
285
291
  ...(tail !== undefined ? { stderrTail: tail } : {}),
286
292
  retryable: false,
293
+ // The engine never reported a turn id, but the session id is ours —
294
+ // report it so a hung turn is still correlatable.
295
+ sessionId: this.params.sessionId,
287
296
  });
288
297
  // Fire-and-forget: cancel races the next event-loop turn.
289
298
  void this.cancel();
@@ -298,6 +307,13 @@ export class SessionHandle {
298
307
  stdout: stdoutBuf,
299
308
  stderr: stderrBuf,
300
309
  exitCode: code ?? -1,
310
+ }, {
311
+ stderrTailBytes: this.params.stderrTailBytes,
312
+ // Rule 2 synthesis has no envelope to read identity from; hand the
313
+ // parser the session id we already hold so the synthesized error
314
+ // still carries it. Ignored on the Rule 1 path, where the envelope
315
+ // is authoritative.
316
+ fallbackSessionId: this.params.sessionId,
301
317
  });
302
318
  finalize(ev);
303
319
  });
@@ -309,7 +325,7 @@ export class SessionHandle {
309
325
  clearTimeout(timeoutHandle);
310
326
  if (finalized)
311
327
  return;
312
- const tail = stderrTailOf(stderrBuf);
328
+ const tail = tailStderrBytes(stderrBuf, this.params.stderrTailBytes);
313
329
  finalize({
314
330
  type: "error",
315
331
  code: "spawn_failed",
@@ -319,6 +335,9 @@ export class SessionHandle {
319
335
  message: `Failed to spawn engine subprocess (${err.code ?? "unknown"}): ${err.message}`,
320
336
  ...(tail !== undefined ? { stderrTail: tail } : {}),
321
337
  retryable: false,
338
+ // No engine ran, so there is no turn id to report — but the session id
339
+ // is the handle's own, and a host correlating this failure needs it.
340
+ sessionId: this.params.sessionId,
322
341
  });
323
342
  });
324
343
  // (ix) drain loop — yield activity events then the final event.
@@ -344,6 +363,8 @@ export class SessionHandle {
344
363
  clearTimeout(timeoutHandle);
345
364
  await cleanupSpillFile(this.mcpSpillPath);
346
365
  this.mcpSpillPath = null;
366
+ await cleanupPromptSpillFile(this.promptSpillPath);
367
+ this.promptSpillPath = null;
347
368
  }
348
369
  }
349
370
  /**
@@ -384,6 +405,11 @@ export class SessionHandle {
384
405
  this.mcpSpillPath = null;
385
406
  await cleanupSpillFile(path);
386
407
  }
408
+ if (this.promptSpillPath !== null) {
409
+ const promptPath = this.promptSpillPath;
410
+ this.promptSpillPath = null;
411
+ await cleanupPromptSpillFile(promptPath);
412
+ }
387
413
  }
388
414
  /** Graceful shutdown — alias for `cancel()` (D3). */
389
415
  async dispose() {
package/dist/types.d.ts CHANGED
@@ -275,6 +275,11 @@ export interface TurnSubmitResult {
275
275
  reply: string | null;
276
276
  turnId: string;
277
277
  sessionId: string;
278
+ tokensIn: number;
279
+ tokensOut: number;
280
+ cacheReadTokens: number;
281
+ cacheWriteTokens: number;
282
+ costUsd: string | null;
278
283
  finalEvent?: {
279
284
  [k: string]: unknown;
280
285
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "amplifier-agent-ts",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
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": {