amplifier-agent-ts 0.6.2 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,8 +20,6 @@ export interface AssembleArgvInput {
20
20
  resume?: boolean;
21
21
  /** Working directory override; emits `--cwd <cwd>`. */
22
22
  cwd?: string;
23
- /** Provider override; emits `--provider <providerOverride>`. */
24
- providerOverride?: string;
25
23
  /**
26
24
  * Path to the engine's host config file (Issue #1). Emits
27
25
  * `--config <configPath>`. The engine's `single_turn` mode reads this
@@ -40,6 +38,47 @@ export interface AssembleArgvInput {
40
38
  * removed — the caller now owns this policy decision.
41
39
  */
42
40
  approvalMode?: "yes" | "no" | "prompt";
41
+ /**
42
+ * Stderr display mode forwarded to the engine via `--display <mode>`.
43
+ *
44
+ * - `"ndjson"` — engine emits one JSON-RPC notification per line on stderr,
45
+ * matching the `parseNdjsonStream` consumer this wrapper already wires
46
+ * onto `child.stderr`. Hosts that consume `display.onEvent` typed
47
+ * notifications (cost, model, cache tokens, llm duration, etc.) MUST set
48
+ * this; otherwise the engine emits human-readable `[type] summary` text
49
+ * that `parseNdjsonStream` cannot decode and the notification path
50
+ * stays silent.
51
+ * - `"text"` — engine emits human-readable text via CliDisplaySystem.
52
+ * Useful only for direct CLI use; the wrapper's NDJSON consumer can't
53
+ * decode it.
54
+ * - omitted — wrapper emits no `--display` flag; engine defaults to `text`.
55
+ * Preserved as the historical default so existing callers who haven't
56
+ * opted into structured consumption keep their old behavior.
57
+ *
58
+ * Requires engine support for the `--display` flag (added alongside
59
+ * JsonDisplaySystem). Older engines will fail with a click "no such option"
60
+ * error if this is set; coordinate the engine version with the wrapper
61
+ * version (link:/file:/published-pair) before opting in.
62
+ */
63
+ displayMode?: "text" | "ndjson";
64
+ /**
65
+ * Workspace name for isolating session state by project. Forwarded to the
66
+ * engine via `--workspace <name>`.
67
+ *
68
+ * When set, the engine writes session state to
69
+ * `~/.amplifier-agent/state/workspaces/<workspace>/sessions/<id>/`.
70
+ * When omitted, the engine auto-derives a slug from the cwd basename plus
71
+ * an 8-char sha256 of the resolved cwd path (e.g. `default-9e80f0e7`).
72
+ *
73
+ * Hosts that manage multiple agents per process (e.g. paperclip's
74
+ * amplifier-local adapter, which runs CEO + CTO + Coder + … per company)
75
+ * should set this so each agent's transcripts land in a separate
76
+ * directory. A typical scheme is `pc-<company-id-short>-<agent-id-short>`.
77
+ *
78
+ * Must satisfy the engine's slug grammar: `[a-z0-9][a-z0-9-]{0,63}`.
79
+ * The engine validates and rejects invalid slugs with `argv_workspace_invalid`.
80
+ */
81
+ workspace?: string;
43
82
  }
44
83
  /**
45
84
  * Build the argv array for `amplifier-agent run`.
@@ -57,5 +96,8 @@ export interface AssembleArgvInput {
57
96
  * in the subprocess env or pass `--config <path>` per turn.
58
97
  * - `--allow-protocol-skew` (engine PR #27): the unsafe override moved to
59
98
  * `host_config.allowProtocolSkew: true` in the JSON config file.
99
+ * - `--provider`, `--model`, `--effort` (engine PR #49): all provider
100
+ * configuration knobs now flow through `host_config.provider.{module,config}`.
101
+ * The TS wrapper passes `configPath`; the engine reads everything from there.
60
102
  */
61
103
  export declare function assembleArgv(input: AssembleArgvInput): string[];
@@ -25,6 +25,9 @@
25
25
  * in the subprocess env or pass `--config <path>` per turn.
26
26
  * - `--allow-protocol-skew` (engine PR #27): the unsafe override moved to
27
27
  * `host_config.allowProtocolSkew: true` in the JSON config file.
28
+ * - `--provider`, `--model`, `--effort` (engine PR #49): all provider
29
+ * configuration knobs now flow through `host_config.provider.{module,config}`.
30
+ * The TS wrapper passes `configPath`; the engine reads everything from there.
28
31
  */
29
32
  export function assembleArgv(input) {
30
33
  const argv = [];
@@ -34,15 +37,28 @@ export function assembleArgv(input) {
34
37
  if (input.cwd !== undefined) {
35
38
  argv.push("--cwd", input.cwd);
36
39
  }
37
- if (input.providerOverride !== undefined) {
38
- argv.push("--provider", input.providerOverride);
39
- }
40
40
  // Issue #1: surface the engine's --config flag.
41
41
  if (input.configPath !== undefined) {
42
42
  argv.push("--config", input.configPath);
43
43
  }
44
44
  argv.push("--output", "json");
45
45
  argv.push("--protocol-version", input.protocolVersion);
46
+ // Optional --display flag. Only emit when explicitly set so older engines
47
+ // (which don't accept --display) keep working with this wrapper. New hosts
48
+ // that consume the structured wire-event stream (paperclip's amplifier-local
49
+ // adapter, future SDK consumers) should set this to "ndjson" so the engine
50
+ // emits one JSON-RPC notification per line on stderr -- the shape
51
+ // `parseNdjsonStream` in `session.ts` expects.
52
+ if (input.displayMode !== undefined) {
53
+ argv.push("--display", input.displayMode);
54
+ }
55
+ // Optional --workspace flag. When set, the engine writes session state to
56
+ // `~/.amplifier-agent/state/workspaces/<workspace>/sessions/<id>/`
57
+ // instead of auto-deriving the slug from cwd. Hosts that manage multiple
58
+ // agents per process should set this so transcripts don't mingle.
59
+ if (input.workspace !== undefined && input.workspace.length > 0) {
60
+ argv.push("--workspace", input.workspace);
61
+ }
46
62
  // Issue #10: approval policy is now caller-controlled.
47
63
  // - "yes" -> -y (always allow)
48
64
  // - "no" -> -n (always deny)
package/dist/index.d.ts CHANGED
@@ -16,6 +16,10 @@ export { assembleArgv } from "./argv-builder.js";
16
16
  /** @public */
17
17
  export type { AssembleArgvInput } from "./argv-builder.js";
18
18
  /** @public */
19
+ export { listModels, listAllModels, ListModelsError } from "./list-models.js";
20
+ /** @public */
21
+ export type { ListModelsParams, ListAllModelsParams, ModelInfo, ModelsListEnvelope, ProviderListResult, ListAllModelsEnvelope, } from "./list-models.js";
22
+ /** @public */
19
23
  export { resolveMcpConfigPath, cleanupSpillFile } from "./mcp-spill.js";
20
24
  /** @public */
21
25
  export type { McpSpillResult } from "./mcp-spill.js";
@@ -65,7 +69,6 @@ export interface SpawnAgentParams {
65
69
  allowlist: string[];
66
70
  extra?: Record<string, string>;
67
71
  };
68
- providerOverride?: string;
69
72
  /**
70
73
  * Approval policy (Issue #10).
71
74
  *
@@ -101,6 +104,44 @@ export interface SpawnAgentParams {
101
104
  onEvent?: (event: DisplayEvent) => void;
102
105
  subagentEvents?: "all" | "none";
103
106
  };
107
+ /**
108
+ * Stderr display mode forwarded to the engine via `--display <mode>`.
109
+ *
110
+ * Required to be `"ndjson"` for hosts consuming structured wire events via
111
+ * `display.onEvent`. The engine's default (`text`) emits human-readable
112
+ * `[type] summary` lines that the wrapper's `parseNdjsonStream` consumer
113
+ * cannot decode — `display.onEvent` stays silent and structured fields
114
+ * (cost, model, cache token counts, llm duration, etc.) never reach the
115
+ * host.
116
+ *
117
+ * - `"ndjson"` — engine emits one JSON-RPC notification per line on stderr.
118
+ * Wrapper's `parseNdjsonStream.onJson` callback dispatches them as typed
119
+ * `display.onEvent({type: "notification", method, params})` events.
120
+ * - `"text"` — engine emits human-readable text. Only useful for direct
121
+ * CLI use.
122
+ * - omitted — wrapper emits no `--display` flag. Engine defaults to `text`,
123
+ * matching pre-existing behavior. Use this for compatibility with older
124
+ * engines that don't accept `--display`.
125
+ *
126
+ * Engine compatibility: requires `amplifier-agent` engine with the
127
+ * `--display` flag (added alongside `JsonDisplaySystem`). Older engines
128
+ * fail with a click "no such option" error if this is set.
129
+ */
130
+ displayMode?: "text" | "ndjson";
131
+ /**
132
+ * Workspace name for isolating session state by project. Forwarded to the
133
+ * engine via `--workspace <name>`. When unset, the engine auto-derives a
134
+ * slug from the cwd basename + 8-char sha256 of the resolved cwd path.
135
+ *
136
+ * Hosts that manage multiple agents per process (e.g. paperclip's
137
+ * amplifier-local adapter, running multiple agents per company) should
138
+ * set this so each agent's transcripts land in a separate directory
139
+ * under `~/.amplifier-agent/state/workspaces/<workspace>/sessions/<id>/`.
140
+ *
141
+ * Must satisfy the engine's slug grammar `[a-z0-9][a-z0-9-]{0,63}`. The
142
+ * engine validates and rejects invalid slugs with `argv_workspace_invalid`.
143
+ */
144
+ workspace?: string;
104
145
  /**
105
146
  * Optional MCP servers. Spilled to a 0600 tmpfile per submit and forwarded
106
147
  * to the engine via the `AMPLIFIER_MCP_CONFIG` env var injected into the
@@ -124,7 +165,7 @@ export interface SpawnAgentParams {
124
165
  *
125
166
  * Mirrors the engine's `single_turn --config` flag (engine PR #27 /
126
167
  * v0.4.0). When unset, the engine's resolution order applies (env
127
- * `AMPLIFIER_AGENT_CONFIG`, then `~/.config/amplifier-agent/host_config.json`).
168
+ * `AMPLIFIER_AGENT_CONFIG`, then `~/.amplifier-agent/config/host_config.json`).
128
169
  *
129
170
  * @public
130
171
  */
package/dist/index.js CHANGED
@@ -29,6 +29,8 @@ export { AaaError, SessionHandle, DEFAULT_TIMEOUT_MS } from "./session.js";
29
29
  /** @public */
30
30
  export { assembleArgv } from "./argv-builder.js";
31
31
  /** @public */
32
+ export { listModels, listAllModels, ListModelsError } from "./list-models.js";
33
+ /** @public */
32
34
  export { resolveMcpConfigPath, cleanupSpillFile } from "./mcp-spill.js";
33
35
  /** @public */
34
36
  export { resolveBinaryPath, buildEnv, probeEngineVersion, DEFAULT_ALLOWLIST, BLOCKED_ENV_KEYS, } from "./spawn.js";
@@ -173,9 +175,6 @@ export async function spawnAgent(params) {
173
175
  ...(params.resume !== undefined ? { resume: params.resume } : {}),
174
176
  ...(params.cwd !== undefined ? { cwd: params.cwd } : {}),
175
177
  ...(params.mcpServers !== undefined ? { mcpServers: params.mcpServers } : {}),
176
- ...(params.providerOverride !== undefined
177
- ? { providerOverride: params.providerOverride }
178
- : {}),
179
178
  protocolVersion: PROTOCOL_VERSION_REQUIRED_BY_WRAPPER,
180
179
  ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),
181
180
  ...(params.runChildProcess !== undefined
@@ -187,6 +186,18 @@ export async function spawnAgent(params) {
187
186
  // Issue #10: forward the validated approval mode so assembleArgv can
188
187
  // emit -y / -n / nothing.
189
188
  ...(approvalModeArg !== undefined ? { approvalMode: approvalModeArg } : {}),
189
+ // Forward displayMode so assembleArgv can emit `--display ndjson` (or
190
+ // text). Required for hosts consuming structured wire events via the
191
+ // wrapper's parseNdjsonStream → display.onEvent path; without ndjson
192
+ // the engine emits human-readable text that the NDJSON consumer
193
+ // cannot decode.
194
+ ...(params.displayMode !== undefined ? { displayMode: params.displayMode } : {}),
195
+ // Forward workspace so assembleArgv can emit `--workspace <slug>`.
196
+ // When omitted, the engine auto-derives a slug from cwd basename +
197
+ // sha256 — fine for single-agent hosts, but multi-agent hosts (like
198
+ // paperclip) should set this so each agent gets an isolated state dir
199
+ // instead of all sharing the same cwd-derived workspace.
200
+ ...(params.workspace !== undefined ? { workspace: params.workspace } : {}),
190
201
  // Issue #4: thread display.onEvent through so SessionHandle can
191
202
  // dispatch parsed NDJSON wire events to it.
192
203
  ...(params.display !== undefined ? { display: params.display } : {}),
@@ -0,0 +1,146 @@
1
+ /**
2
+ * list-models.ts — wrapper-side discovery of provider models.
3
+ *
4
+ * Spawns the Python `amplifier-agent models list … --output json` subcommand
5
+ * and returns the parsed JSON envelope. The Python implementation lives at
6
+ * `src/amplifier_agent_cli/admin/models.py`. This is the discovery half of
7
+ * the model-management story; the override half lives in
8
+ * host_config.provider.config (default_model, effort, temperature, …) which
9
+ * the engine consumes when the wrapper passes `configPath` to `assembleArgv`.
10
+ * The previous per-call `modelOverride` / `effortOverride` fields were
11
+ * removed when host_config became the single source of truth.
12
+ *
13
+ * Two functions are exported:
14
+ *
15
+ * listModels({ provider, … })
16
+ * Single-provider discovery (existing). Spawns `models list --provider <p>
17
+ * --output json`. Returns `ModelsListEnvelope`.
18
+ *
19
+ * listAllModels({ … })
20
+ * Aggregate discovery (new in this revision). Spawns `models list
21
+ * --output json` (no --provider). The engine enumerates every known
22
+ * provider in parallel and emits a per-provider results envelope so
23
+ * callers can see at a glance which providers are configured and what
24
+ * models each reports. Returns `ListAllModelsEnvelope`.
25
+ *
26
+ * Wire contract (kept in sync with the Python emitter):
27
+ * stdout (exit 0): JSON envelope with schema_version === 1
28
+ * exit 0 + empty models: legitimate (azure-openai always; ollama when down)
29
+ * exit 1: usage error (unknown provider) — message on stderr
30
+ * exit 2: provider error (auth, network, timeout) — message on stderr
31
+ */
32
+ /** Single model entry — mirrors amplifier-core ModelInfo.model_dump(). */
33
+ export interface ModelInfo {
34
+ id: string;
35
+ display_name: string;
36
+ context_window: number;
37
+ max_output_tokens: number;
38
+ capabilities: string[];
39
+ defaults: Record<string, unknown>;
40
+ }
41
+ /** JSON envelope returned by `amplifier-agent models list --provider <p> --output json`. */
42
+ export interface ModelsListEnvelope {
43
+ schema_version: 1;
44
+ provider: string;
45
+ fetched_at: string;
46
+ models: ModelInfo[];
47
+ }
48
+ /**
49
+ * Per-provider result inside the aggregate envelope.
50
+ *
51
+ * The `status` field is kept as a free-form string rather than a union so the
52
+ * wrapper stays forward-compatible with new statuses the engine may add.
53
+ * Current values emitted by the engine (see `admin/models.py`):
54
+ *
55
+ * - "ok" — provider returned a model list (possibly empty)
56
+ * - "credentials_missing" — provider module loaded but auth not configured
57
+ * - "module_not_installed" — provider module not present in the bundle
58
+ * - "error" — provider raised an error during discovery
59
+ *
60
+ * When `status !== "ok"`, `models` is `[]` and an `error` field carries the
61
+ * human-readable reason. Callers should compare against the literal "ok"
62
+ * rather than enumerating failure cases — that way new failure modes don't
63
+ * silently get treated as success.
64
+ */
65
+ export interface ProviderListResult {
66
+ provider: string;
67
+ status: string;
68
+ models: ModelInfo[];
69
+ error?: string;
70
+ }
71
+ /** JSON envelope returned by `amplifier-agent models list --output json` (aggregate mode). */
72
+ export interface ListAllModelsEnvelope {
73
+ schema_version: 1;
74
+ fetched_at: string;
75
+ results: ProviderListResult[];
76
+ }
77
+ export interface ListModelsParams {
78
+ /** Provider name (anthropic, openai, ollama, azure-openai). */
79
+ provider: string;
80
+ /** Subprocess timeout in milliseconds. Default: 15000. */
81
+ timeoutMs?: number;
82
+ /**
83
+ * Path to amplifier-agent binary or executable name on PATH.
84
+ * Default: "amplifier-agent".
85
+ */
86
+ binaryPath?: string;
87
+ /**
88
+ * Environment variables passed to the subprocess. If undefined, inherits
89
+ * process.env. Use this to forward provider API keys (ANTHROPIC_API_KEY etc.).
90
+ */
91
+ env?: NodeJS.ProcessEnv;
92
+ }
93
+ /**
94
+ * Parameters for {@link listAllModels}. Same shape as {@link ListModelsParams}
95
+ * minus the `provider` field — aggregate mode queries every known provider.
96
+ */
97
+ export interface ListAllModelsParams {
98
+ /** Subprocess timeout in milliseconds. Default: 15000. */
99
+ timeoutMs?: number;
100
+ /**
101
+ * Path to amplifier-agent binary or executable name on PATH.
102
+ * Default: "amplifier-agent".
103
+ */
104
+ binaryPath?: string;
105
+ /**
106
+ * Environment variables passed to the subprocess. If undefined, inherits
107
+ * process.env. Use this to forward provider API keys (ANTHROPIC_API_KEY,
108
+ * OPENAI_API_KEY, etc.) — providers without their keys will return
109
+ * `status: "credentials_missing"` in the aggregate envelope, not raise.
110
+ */
111
+ env?: NodeJS.ProcessEnv;
112
+ }
113
+ /**
114
+ * Error thrown when `listModels()` or `listAllModels()` fails. Carries exit
115
+ * code and stderr so callers can disambiguate auth vs network vs usage errors.
116
+ */
117
+ export declare class ListModelsError extends Error {
118
+ readonly exitCode: number | null;
119
+ readonly stderr: string;
120
+ constructor(message: string, exitCode: number | null, stderr: string);
121
+ }
122
+ /**
123
+ * Spawn `amplifier-agent models list --provider <p> --output json` and return
124
+ * the parsed envelope. See {@link ListModelsError} for failure modes.
125
+ *
126
+ * An empty `models: []` is NOT an error — azure-openai always returns this,
127
+ * ollama returns it when the daemon is down. Callers should treat it as a
128
+ * legitimate "no models discoverable" result, not a failure.
129
+ */
130
+ export declare function listModels(params: ListModelsParams): Promise<ModelsListEnvelope>;
131
+ /**
132
+ * Spawn `amplifier-agent models list --output json` (no --provider) and
133
+ * return the parsed aggregate envelope. The engine queries every known
134
+ * provider in parallel and returns one `ProviderListResult` per provider
135
+ * in {@link ListAllModelsEnvelope.results}.
136
+ *
137
+ * Per-provider failure modes (auth missing, module not installed, network
138
+ * error) are reported on individual `results` entries with `status !== "ok"`
139
+ * — this function only rejects on subprocess-level failures (spawn error,
140
+ * exit code 1 = usage, exit code 2 = engine-wide provider error, timeout).
141
+ *
142
+ * Recommended for hosts that want a single "all available models" dropdown
143
+ * without orchestrating four sequential single-provider calls. One spawn,
144
+ * engine-side parallelism, native per-provider auth status.
145
+ */
146
+ export declare function listAllModels(params?: ListAllModelsParams): Promise<ListAllModelsEnvelope>;
@@ -0,0 +1,295 @@
1
+ /**
2
+ * list-models.ts — wrapper-side discovery of provider models.
3
+ *
4
+ * Spawns the Python `amplifier-agent models list … --output json` subcommand
5
+ * and returns the parsed JSON envelope. The Python implementation lives at
6
+ * `src/amplifier_agent_cli/admin/models.py`. This is the discovery half of
7
+ * the model-management story; the override half lives in
8
+ * host_config.provider.config (default_model, effort, temperature, …) which
9
+ * the engine consumes when the wrapper passes `configPath` to `assembleArgv`.
10
+ * The previous per-call `modelOverride` / `effortOverride` fields were
11
+ * removed when host_config became the single source of truth.
12
+ *
13
+ * Two functions are exported:
14
+ *
15
+ * listModels({ provider, … })
16
+ * Single-provider discovery (existing). Spawns `models list --provider <p>
17
+ * --output json`. Returns `ModelsListEnvelope`.
18
+ *
19
+ * listAllModels({ … })
20
+ * Aggregate discovery (new in this revision). Spawns `models list
21
+ * --output json` (no --provider). The engine enumerates every known
22
+ * provider in parallel and emits a per-provider results envelope so
23
+ * callers can see at a glance which providers are configured and what
24
+ * models each reports. Returns `ListAllModelsEnvelope`.
25
+ *
26
+ * Wire contract (kept in sync with the Python emitter):
27
+ * stdout (exit 0): JSON envelope with schema_version === 1
28
+ * exit 0 + empty models: legitimate (azure-openai always; ollama when down)
29
+ * exit 1: usage error (unknown provider) — message on stderr
30
+ * exit 2: provider error (auth, network, timeout) — message on stderr
31
+ */
32
+ import { spawn } from "node:child_process";
33
+ /**
34
+ * Error thrown when `listModels()` or `listAllModels()` fails. Carries exit
35
+ * code and stderr so callers can disambiguate auth vs network vs usage errors.
36
+ */
37
+ export class ListModelsError extends Error {
38
+ exitCode;
39
+ stderr;
40
+ constructor(message, exitCode, stderr) {
41
+ super(message);
42
+ this.exitCode = exitCode;
43
+ this.stderr = stderr;
44
+ this.name = "ListModelsError";
45
+ }
46
+ }
47
+ const DEFAULT_TIMEOUT_MS = 15_000;
48
+ const DEFAULT_BINARY = "amplifier-agent";
49
+ /** Sanity cap on stdout/stderr collection — paranoia against runaway output. */
50
+ const MAX_BUFFER_BYTES = 10 * 1024 * 1024;
51
+ /**
52
+ * Shared subprocess driver for `models list` invocations.
53
+ *
54
+ * Handles spawn failures, the 15s default timeout, stdout/stderr accumulation
55
+ * with a 10MB sanity cap, and SIGTERM-on-hang. Returns the raw outcome so
56
+ * each public function can apply its own envelope validation and exit-code
57
+ * interpretation.
58
+ */
59
+ function runModelsListSubprocess(args, options) {
60
+ return new Promise((resolve, reject) => {
61
+ let stdoutBytes = 0;
62
+ let stderrBytes = 0;
63
+ let stdoutTruncated = false;
64
+ let stderrTruncated = false;
65
+ const stdoutChunks = [];
66
+ const stderrChunks = [];
67
+ let settled = false;
68
+ // Build spawn options — `env: undefined` makes child inherit process.env;
69
+ // an explicit env REPLACES (not merges) so callers stay in control.
70
+ const spawnOptions = {};
71
+ if (options.env !== undefined) {
72
+ spawnOptions.env = options.env;
73
+ }
74
+ else {
75
+ spawnOptions.env = process.env;
76
+ }
77
+ let child;
78
+ try {
79
+ child = spawn(options.binary, args, spawnOptions);
80
+ }
81
+ catch (err) {
82
+ // Synchronous spawn failures (extremely rare — most surface via "error").
83
+ reject(new ListModelsError(`failed to spawn ${options.binary}: ${err instanceof Error ? err.message : String(err)}`, null, ""));
84
+ return;
85
+ }
86
+ const settle = (fn) => {
87
+ if (settled)
88
+ return;
89
+ settled = true;
90
+ clearTimeout(timer);
91
+ fn();
92
+ };
93
+ const timer = setTimeout(() => {
94
+ // Subprocess wedged. Kill it and reject. The "exit" handler may still
95
+ // fire after kill — the `settled` flag suppresses the double-callback.
96
+ try {
97
+ child.kill("SIGTERM");
98
+ }
99
+ catch {
100
+ /* swallow — kill on dead pid throws on some platforms */
101
+ }
102
+ settle(() => reject(new ListModelsError(`listModels timed out after ${options.timeoutMs}ms`, null, decodeBuffer(stderrChunks))));
103
+ }, options.timeoutMs);
104
+ child.stdout?.on("data", (chunk) => {
105
+ if (stdoutTruncated)
106
+ return;
107
+ stdoutBytes += chunk.length;
108
+ if (stdoutBytes > MAX_BUFFER_BYTES) {
109
+ stdoutTruncated = true;
110
+ return;
111
+ }
112
+ stdoutChunks.push(chunk);
113
+ });
114
+ child.stderr?.on("data", (chunk) => {
115
+ if (stderrTruncated)
116
+ return;
117
+ stderrBytes += chunk.length;
118
+ if (stderrBytes > MAX_BUFFER_BYTES) {
119
+ stderrTruncated = true;
120
+ return;
121
+ }
122
+ stderrChunks.push(chunk);
123
+ });
124
+ child.on("error", (err) => {
125
+ // Spawn failure (ENOENT etc.) typically arrives here, not via throw.
126
+ settle(() => reject(new ListModelsError(`failed to spawn ${options.binary}: ${err.message}`, null, decodeBuffer(stderrChunks))));
127
+ });
128
+ child.on("exit", (code) => {
129
+ const stdout = decodeBuffer(stdoutChunks);
130
+ let stderr = decodeBuffer(stderrChunks);
131
+ if (stdoutTruncated)
132
+ stderr += "\n[listModels: stdout truncated at 10MB]";
133
+ if (stderrTruncated)
134
+ stderr += "\n[listModels: stderr truncated at 10MB]";
135
+ settle(() => resolve({ exitCode: code, stdout, stderr }));
136
+ });
137
+ });
138
+ }
139
+ /**
140
+ * Map a subprocess outcome into a typed envelope or a `ListModelsError`.
141
+ *
142
+ * Both `listModels` and `listAllModels` share the same exit-code contract
143
+ * (0 = ok + envelope on stdout; 1 = usage error; 2 = provider error). They
144
+ * differ only in their stdout shape, which `validate` handles.
145
+ */
146
+ function interpretOutcome(outcome, validate) {
147
+ const { exitCode, stdout, stderr } = outcome;
148
+ if (exitCode === 0) {
149
+ let parsed;
150
+ try {
151
+ parsed = JSON.parse(stdout);
152
+ }
153
+ catch (err) {
154
+ throw new ListModelsError(`invalid envelope: JSON parse failed (${err instanceof Error ? err.message : String(err)})`, exitCode, stderr);
155
+ }
156
+ const validation = validate(parsed);
157
+ if (validation.ok) {
158
+ return validation.value;
159
+ }
160
+ throw new ListModelsError(`invalid envelope: ${validation.reason}`, exitCode, stderr);
161
+ }
162
+ if (exitCode === 1) {
163
+ throw new ListModelsError(`usage error: ${stderr.trim()}`, exitCode, stderr);
164
+ }
165
+ if (exitCode === 2) {
166
+ throw new ListModelsError(`provider error: ${stderr.trim()}`, exitCode, stderr);
167
+ }
168
+ throw new ListModelsError(`subprocess exited with unexpected code`, exitCode, stderr);
169
+ }
170
+ /**
171
+ * Spawn `amplifier-agent models list --provider <p> --output json` and return
172
+ * the parsed envelope. See {@link ListModelsError} for failure modes.
173
+ *
174
+ * An empty `models: []` is NOT an error — azure-openai always returns this,
175
+ * ollama returns it when the daemon is down. Callers should treat it as a
176
+ * legitimate "no models discoverable" result, not a failure.
177
+ */
178
+ export async function listModels(params) {
179
+ const timeoutMs = params.timeoutMs ?? DEFAULT_TIMEOUT_MS;
180
+ const binary = params.binaryPath ?? DEFAULT_BINARY;
181
+ const args = ["models", "list", "--provider", params.provider, "--output", "json"];
182
+ const outcome = await runModelsListSubprocess(args, { timeoutMs, binary, env: params.env });
183
+ return interpretOutcome(outcome, validateSingleEnvelope);
184
+ }
185
+ /**
186
+ * Spawn `amplifier-agent models list --output json` (no --provider) and
187
+ * return the parsed aggregate envelope. The engine queries every known
188
+ * provider in parallel and returns one `ProviderListResult` per provider
189
+ * in {@link ListAllModelsEnvelope.results}.
190
+ *
191
+ * Per-provider failure modes (auth missing, module not installed, network
192
+ * error) are reported on individual `results` entries with `status !== "ok"`
193
+ * — this function only rejects on subprocess-level failures (spawn error,
194
+ * exit code 1 = usage, exit code 2 = engine-wide provider error, timeout).
195
+ *
196
+ * Recommended for hosts that want a single "all available models" dropdown
197
+ * without orchestrating four sequential single-provider calls. One spawn,
198
+ * engine-side parallelism, native per-provider auth status.
199
+ */
200
+ export async function listAllModels(params = {}) {
201
+ const timeoutMs = params.timeoutMs ?? DEFAULT_TIMEOUT_MS;
202
+ const binary = params.binaryPath ?? DEFAULT_BINARY;
203
+ const args = ["models", "list", "--output", "json"];
204
+ const outcome = await runModelsListSubprocess(args, { timeoutMs, binary, env: params.env });
205
+ return interpretOutcome(outcome, validateAggregateEnvelope);
206
+ }
207
+ function decodeBuffer(chunks) {
208
+ if (chunks.length === 0)
209
+ return "";
210
+ return Buffer.concat(chunks).toString("utf8");
211
+ }
212
+ /**
213
+ * Lenient single-provider envelope check: enough to catch malformed payloads,
214
+ * not a full pydantic-style schema validation. We accept extra fields and
215
+ * let the caller see them as `unknown` via TS structural typing.
216
+ */
217
+ function validateSingleEnvelope(value) {
218
+ if (value === null || typeof value !== "object") {
219
+ return { ok: false, reason: "envelope is not an object" };
220
+ }
221
+ const obj = value;
222
+ if (obj["schema_version"] !== 1) {
223
+ return {
224
+ ok: false,
225
+ reason: `unsupported schema_version (expected 1, got ${JSON.stringify(obj["schema_version"])})`,
226
+ };
227
+ }
228
+ if (typeof obj["provider"] !== "string") {
229
+ return { ok: false, reason: "provider must be a string" };
230
+ }
231
+ if (!Array.isArray(obj["models"])) {
232
+ return { ok: false, reason: "models must be an array" };
233
+ }
234
+ for (let i = 0; i < obj["models"].length; i++) {
235
+ const m = obj["models"][i];
236
+ if (m === null || typeof m !== "object") {
237
+ return { ok: false, reason: `models[${i}] is not an object` };
238
+ }
239
+ if (typeof m["id"] !== "string") {
240
+ return { ok: false, reason: `models[${i}].id must be a string` };
241
+ }
242
+ }
243
+ // fetched_at is documented as ISO 8601 but we don't enforce — the Python
244
+ // side guarantees it, and a stricter parse here would just be ceremony.
245
+ return { ok: true, value: obj };
246
+ }
247
+ /**
248
+ * Lenient aggregate envelope check. Same posture as `validateSingleEnvelope`:
249
+ * verify the structural skeleton, treat unknown fields as forward-compat
250
+ * extension points, and let pathological payloads surface as parse errors.
251
+ */
252
+ function validateAggregateEnvelope(value) {
253
+ if (value === null || typeof value !== "object") {
254
+ return { ok: false, reason: "envelope is not an object" };
255
+ }
256
+ const obj = value;
257
+ if (obj["schema_version"] !== 1) {
258
+ return {
259
+ ok: false,
260
+ reason: `unsupported schema_version (expected 1, got ${JSON.stringify(obj["schema_version"])})`,
261
+ };
262
+ }
263
+ if (!Array.isArray(obj["results"])) {
264
+ return { ok: false, reason: "results must be an array" };
265
+ }
266
+ for (let i = 0; i < obj["results"].length; i++) {
267
+ const r = obj["results"][i];
268
+ if (r === null || typeof r !== "object") {
269
+ return { ok: false, reason: `results[${i}] is not an object` };
270
+ }
271
+ const result = r;
272
+ if (typeof result["provider"] !== "string") {
273
+ return { ok: false, reason: `results[${i}].provider must be a string` };
274
+ }
275
+ if (typeof result["status"] !== "string") {
276
+ return { ok: false, reason: `results[${i}].status must be a string` };
277
+ }
278
+ if (!Array.isArray(result["models"])) {
279
+ return { ok: false, reason: `results[${i}].models must be an array` };
280
+ }
281
+ for (let j = 0; j < result["models"].length; j++) {
282
+ const m = result["models"][j];
283
+ if (m === null || typeof m !== "object") {
284
+ return { ok: false, reason: `results[${i}].models[${j}] is not an object` };
285
+ }
286
+ if (typeof m["id"] !== "string") {
287
+ return { ok: false, reason: `results[${i}].models[${j}].id must be a string` };
288
+ }
289
+ }
290
+ // `error` is optional and only meaningful when status !== "ok"; don't
291
+ // enforce its presence or shape here. Hosts that care can switch on
292
+ // status and read `error` lenient-string-style.
293
+ }
294
+ return { ok: true, value: obj };
295
+ }
package/dist/session.d.ts CHANGED
@@ -130,7 +130,6 @@ export interface SessionHandleParams {
130
130
  */
131
131
  mcpServers?: Record<string, McpServerConfig>;
132
132
  /** Provider override forwarded via `--provider`. */
133
- providerOverride?: string;
134
133
  /**
135
134
  * Path to the engine's host config file (Issue #1). Forwarded to the
136
135
  * engine via `--config <configPath>`. See the engine's
@@ -146,6 +145,40 @@ export interface SessionHandleParams {
146
145
  * have not opted into the approval API.
147
146
  */
148
147
  approvalMode?: "yes" | "no" | "prompt";
148
+ /**
149
+ * Stderr display mode forwarded to the engine via `--display <mode>`.
150
+ *
151
+ * - `"ndjson"` — required for hosts that consume structured wire events
152
+ * via the `display.onEvent` callback below. The engine emits one
153
+ * JSON-RPC notification per line on stderr, matching the
154
+ * `parseNdjsonStream` consumer this wrapper wires onto `child.stderr`.
155
+ * This is the only way to receive enriched `usage` fields (cost,
156
+ * model, provider, cache token counts, llm duration, etc.) the
157
+ * streaming hook produces.
158
+ * - `"text"` — engine emits human-readable text via CliDisplaySystem.
159
+ * The wrapper's NDJSON consumer cannot decode it, so `display.onEvent`
160
+ * stays silent. Useful only for direct CLI use, not wrapper consumers.
161
+ * - omitted — wrapper emits no `--display` flag. Engine defaults to
162
+ * `text`, preserving the historical pre-#45 behavior. Use this for
163
+ * compatibility with older engines that don't accept `--display`.
164
+ *
165
+ * Requires engine support for the `--display` flag. Older engines
166
+ * (pre-#45-followup) fail with `click` "no such option" if this is set.
167
+ */
168
+ displayMode?: "text" | "ndjson";
169
+ /**
170
+ * Workspace name for isolating session state by project. Forwarded to the
171
+ * engine via `--workspace <name>`. When unset, the engine auto-derives a
172
+ * slug from the cwd basename + 8-char sha256 of the resolved cwd path.
173
+ *
174
+ * Hosts that manage multiple agents per process should set this so each
175
+ * agent's transcripts land in a separate directory under
176
+ * `~/.amplifier-agent/state/workspaces/<workspace>/sessions/<id>/`.
177
+ *
178
+ * Must satisfy `[a-z0-9][a-z0-9-]{0,63}`. The engine validates and rejects
179
+ * invalid slugs with `argv_workspace_invalid`.
180
+ */
181
+ workspace?: string;
149
182
  /** Protocol version the wrapper speaks (e.g. "0.3.0"). */
150
183
  protocolVersion: string;
151
184
  /**
package/dist/session.js CHANGED
@@ -168,9 +168,10 @@ export class SessionHandle {
168
168
  protocolVersion: this.params.protocolVersion,
169
169
  resume: this.params.resume,
170
170
  cwd: this.params.cwd,
171
- providerOverride: this.params.providerOverride,
172
171
  configPath: this.params.configPath,
173
172
  approvalMode: this.params.approvalMode,
173
+ displayMode: this.params.displayMode,
174
+ workspace: this.params.workspace,
174
175
  });
175
176
  // Build the subprocess env. When we spilled an MCP config, set
176
177
  // AMPLIFIER_MCP_CONFIG so tool-mcp reads it natively via its
@@ -205,7 +206,16 @@ export class SessionHandle {
205
206
  // engine emits one JSON object per line for each wire-protocol
206
207
  // notification (progress, result/delta, tool/started, etc.).
207
208
  // - JSON lines are parsed into `notification` DisplayEvents and
208
- // dispatched to `params.display?.onEvent` (Issue #4).
209
+ // delivered via TWO paths so hosts can choose either consumption
210
+ // model:
211
+ // 1. Pushed onto the iterator queue so `for await (const ev of
212
+ // handle.submit(...))` yields them. Iterator consumers (e.g.
213
+ // paperclip's amplifier-local adapter, which switches on
214
+ // `event.type === "notification"`) need this path.
215
+ // 2. Dispatched to `params.display?.onEvent` (Issue #4) for hosts
216
+ // that prefer a push-based callback.
217
+ // Hosts that subscribe via BOTH paths will receive each
218
+ // notification twice -- acceptable; subscribe to one or the other.
209
219
  // - Non-JSON lines are accumulated into `stderrBuf` so the
210
220
  // stderrTail surface on parseRunOutput stays useful for
211
221
  // diagnostic snapshots.
@@ -216,10 +226,14 @@ export class SessionHandle {
216
226
  void parseNdjsonStream(child.stderr, {
217
227
  onJson: (obj) => {
218
228
  stderrBuf += JSON.stringify(obj) + "\n";
229
+ const method = typeof obj.method === "string" ? obj.method : "unknown";
230
+ const params = "params" in obj ? obj.params : obj;
231
+ const ev = { type: "notification", method, params };
232
+ // Path 1: iterator queue.
233
+ push(ev);
234
+ // Path 2: callback (legacy / push-only hosts).
219
235
  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 });
236
+ displayOnEvent(ev);
223
237
  }
224
238
  },
225
239
  onNonJson: (line) => {
package/dist/transport.js CHANGED
@@ -13,6 +13,12 @@
13
13
  */
14
14
  import { spawn } from "node:child_process";
15
15
  import { createInterface } from "node:readline";
16
+ /**
17
+ * How long terminate() keeps reading the child's stdio after the child itself
18
+ * has exited, before giving up on pipes that a surviving grandchild is holding
19
+ * open. See the comment in {@link Transport.spawn} for why this exists.
20
+ */
21
+ const ORPHANED_STDIO_DRAIN_MS = 250;
16
22
  /**
17
23
  * Consume an NDJSON stream line-by-line, dispatching each parseable JSON
18
24
  * line to `onJson` and each non-JSON line to `onNonJson` (or silently
@@ -79,12 +85,46 @@ export class Transport {
79
85
  cwd: this.opts.cwd,
80
86
  });
81
87
  this.proc = proc;
82
- // exitPromise resolves after the child process AND all its stdio streams
83
- // have closed. The 'close' event fires AFTER readline has processed all
84
- // buffered lines, so frames are guaranteed to be delivered before the
85
- // promise resolves.
88
+ // exitPromise normally resolves on 'close', which fires after the child
89
+ // process AND all its stdio streams have closed. 'close' comes AFTER
90
+ // readline has processed every buffered line, so frames are guaranteed to
91
+ // be delivered before the promise resolves.
92
+ //
93
+ // But 'close' waits for EOF on stdout/stderr, and those pipe write-ends are
94
+ // inherited by every grandchild the child spawned. A grandchild that
95
+ // outlives its parent keeps the write-end open, so EOF never arrives and
96
+ // 'close' never fires -- terminate() would hang for as long as the orphan
97
+ // lives, not for as long as the child lives. This is not hypothetical: a
98
+ // POSIX shell that forks rather than execs (`sh -c "sleep 60"` on dash)
99
+ // reproduces it exactly, and so does any engine tool subprocess that
100
+ // outlives the engine it was spawned from.
101
+ //
102
+ // So: 'exit' means the child itself is dead and everything it ever wrote is
103
+ // already in the pipe. Give the reader a short grace window to drain that
104
+ // buffer, then stop waiting on pipes that are being held open by somebody
105
+ // else, and detach from them so the handles are released.
86
106
  this.exitPromise = new Promise((resolve) => {
87
- proc.on("close", (code, signal) => resolve({ code, signal }));
107
+ let settled = false;
108
+ const settle = (info) => {
109
+ if (settled)
110
+ return;
111
+ settled = true;
112
+ resolve(info);
113
+ };
114
+ proc.on("close", (code, signal) => settle({ code, signal }));
115
+ proc.on("exit", (code, signal) => {
116
+ // Not a correctness deadline -- 'close' wins this race whenever the
117
+ // pipes are actually closable, which is every well-behaved child. This
118
+ // only bounds the pathological case, so it is deliberately generous.
119
+ const drain = setTimeout(() => {
120
+ proc.stdin?.destroy();
121
+ proc.stdout?.destroy();
122
+ proc.stderr?.destroy();
123
+ settle({ code, signal });
124
+ }, ORPHANED_STDIO_DRAIN_MS);
125
+ // Never let the grace timer itself hold the event loop open.
126
+ drain.unref();
127
+ });
88
128
  });
89
129
  // Read stdout line by line; parse JSON; dispatch to registered callbacks.
90
130
  const stdoutRl = createInterface({ input: proc.stdout });
package/dist/types.d.ts CHANGED
@@ -244,6 +244,7 @@ export interface ToolCompletedNotification {
244
244
  name: string;
245
245
  result: unknown;
246
246
  durationMs: number;
247
+ agentName?: string;
247
248
  }
248
249
  /**
249
250
  * Emitted when a tool call begins execution.
@@ -254,6 +255,7 @@ export interface ToolStartedNotification {
254
255
  toolCallId: string;
255
256
  name: string;
256
257
  args: unknown;
258
+ agentName?: string;
257
259
  }
258
260
  /**
259
261
  * Parameters for the ``turn/submit`` JSON-RPC method.
@@ -285,6 +287,13 @@ export interface UsageNotification {
285
287
  turnId: string;
286
288
  inputTokens: number;
287
289
  outputTokens: number;
288
- cost?: number;
290
+ cost?: string;
291
+ llmDurationMs?: number;
292
+ model?: string;
293
+ provider?: string;
294
+ cacheReadTokens?: number;
295
+ cacheWriteTokens?: number;
296
+ sessionCostTotal?: string;
297
+ agentName?: string;
289
298
  }
290
299
  export type ErrorCode = "agent_not_ready" | "approval_denied" | "approval_protocol_violation" | "approval_timeout" | "approval_translation_failed" | "bundle_load_failed" | "config_validation" | "env_injection_rejected" | "internal" | "invalid_session" | "prompt_required" | "protocol_version_mismatch" | "provider_init_failed" | "provider_not_configured" | "runtime" | "session_not_found" | "spawn_failed" | "stale_session" | "tool_execution_failed" | "wire_protocol_violation";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "amplifier-agent-ts",
3
- "version": "0.6.2",
3
+ "version": "0.7.1",
4
4
  "description": "TypeScript SDK for the Amplifier agent. Spawns and drives the amplifier-agent Python CLI over a stdio protocol.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -19,7 +19,8 @@
19
19
  "test": "vitest run",
20
20
  "typecheck": "tsc --noEmit",
21
21
  "lint": "tsc --noEmit",
22
- "gen:types": "tsx scripts/gen-types.ts"
22
+ "gen:types": "tsx scripts/gen-types.ts",
23
+ "prepare": "npm run build"
23
24
  },
24
25
  "engines": {
25
26
  "node": ">=20"