@agentproto/driver-agent-cli 0.1.0 → 0.2.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.
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  import { Writable, Readable } from 'stream';
3
3
  import { createAcpClient } from '@agentproto/acp/client';
4
4
  import { spawn } from 'child_process';
5
+ import { createInterface } from 'readline';
5
6
  import { randomUUID } from 'crypto';
6
7
  import { createDoctype } from '@agentproto/define-doctype';
7
8
 
@@ -155,7 +156,11 @@ var sessionSchema = z.object({
155
156
  var modelsSchema = z.object({
156
157
  default: z.string().optional(),
157
158
  allowed: z.array(z.string()).optional(),
158
- env: z.record(z.string(), z.string()).optional()
159
+ env: z.record(z.string(), z.string()).optional(),
160
+ // How a model is selected at session start: "config" (ACP
161
+ // set_config_option, default) | "command" (a `/model <id>` control turn,
162
+ // for agents like hermes that ignore the ACP session model config).
163
+ apply: z.enum(["config", "command"]).optional()
159
164
  }).strict();
160
165
  var capabilitiesSchema = z.object({
161
166
  streaming: z.boolean().optional(),
@@ -233,7 +238,7 @@ var agentCliFrontmatterSchema = z.object({
233
238
  auth: authSchema.optional(),
234
239
  sandbox: z.union([z.string(), z.record(z.string(), z.unknown())]),
235
240
  runner: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
236
- protocol: z.enum(["acp", "mcp", "proprietary"]),
241
+ protocol: z.enum(["acp", "mcp", "proprietary", "print"]),
237
242
  acp: z.string().optional(),
238
243
  mcp: mcpBlockSchema.optional(),
239
244
  adapter: z.string().regex(ADAPTER_PATTERN).optional(),
@@ -357,10 +362,16 @@ function createAcpProtocolArm(options) {
357
362
  if (opts.resumeSessionId) {
358
363
  session = await client.loadSession({
359
364
  sessionId: opts.resumeSessionId,
360
- cwd
365
+ cwd,
366
+ mcpServers: opts.mcpServers
361
367
  });
362
368
  } else {
363
- session = await client.newSession({ cwd });
369
+ session = await client.newSession({
370
+ cwd,
371
+ mcpServers: opts.mcpServers,
372
+ ...opts.model ? { model: opts.model } : {},
373
+ ...opts.effort ? { effort: opts.effort } : {}
374
+ });
364
375
  }
365
376
  },
366
377
  async send(turnId, message) {
@@ -384,6 +395,145 @@ function createAcpProtocolArm(options) {
384
395
  }
385
396
  };
386
397
  }
398
+ function createPrintSession(opts) {
399
+ let sessionId = opts.resumeSessionId ?? "";
400
+ let activeChild = null;
401
+ return {
402
+ get sessionId() {
403
+ return sessionId;
404
+ },
405
+ async *send(message) {
406
+ const prompt = extractPromptText(message);
407
+ const args = [
408
+ ...opts.baseArgs,
409
+ "--print",
410
+ "--output-format",
411
+ "stream-json",
412
+ "--no-interactive",
413
+ ...sessionId ? ["--resume", sessionId] : [],
414
+ prompt
415
+ ];
416
+ const child = spawn(opts.bin, args, {
417
+ cwd: opts.cwd,
418
+ env: opts.env,
419
+ stdio: ["ignore", "pipe", "pipe"]
420
+ });
421
+ activeChild = child;
422
+ const stderrLines = [];
423
+ const STDERR_KEEP = 80;
424
+ child.stderr?.setEncoding("utf8");
425
+ child.stderr?.on("data", (chunk) => {
426
+ for (const line of chunk.split(/\r?\n/)) {
427
+ if (!line) continue;
428
+ stderrLines.push(line);
429
+ if (stderrLines.length > STDERR_KEEP) stderrLines.shift();
430
+ }
431
+ });
432
+ try {
433
+ if (!child.stdout) throw new Error("print-arm: child has no stdout pipe");
434
+ const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
435
+ let capturedSessionId = "";
436
+ for await (const line of rl) {
437
+ if (!line.trim()) continue;
438
+ let evt;
439
+ try {
440
+ evt = JSON.parse(line);
441
+ } catch {
442
+ continue;
443
+ }
444
+ if (evt.type === "result" && typeof evt.session_id === "string" && evt.session_id) {
445
+ capturedSessionId = evt.session_id;
446
+ }
447
+ const sid = capturedSessionId || sessionId || "";
448
+ const mapped = mapEvent(evt, sid, stderrLines);
449
+ if (!mapped) continue;
450
+ yield mapped;
451
+ }
452
+ const exitCode = await waitForExit(child);
453
+ if (capturedSessionId) sessionId = capturedSessionId;
454
+ if (exitCode !== 0 && exitCode !== null) {
455
+ const errEvt = {
456
+ kind: "error",
457
+ error: {
458
+ message: `claude exited with code ${exitCode}`,
459
+ ...stderrLines.length ? { data: { stderr: stderrLines.join("\n") } } : {}
460
+ }
461
+ };
462
+ yield errEvt;
463
+ }
464
+ } finally {
465
+ activeChild = null;
466
+ }
467
+ },
468
+ async cancel() {
469
+ activeChild?.kill("SIGTERM");
470
+ },
471
+ async close() {
472
+ activeChild?.kill("SIGTERM");
473
+ }
474
+ };
475
+ }
476
+ function extractPromptText(message) {
477
+ if (typeof message === "string") return message;
478
+ if (message !== null && typeof message === "object") {
479
+ const m = message;
480
+ if (typeof m.text === "string") return m.text;
481
+ if (Array.isArray(message)) {
482
+ return message.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
483
+ }
484
+ }
485
+ return JSON.stringify(message);
486
+ }
487
+ function mapEvent(evt, sessionId, stderrLines) {
488
+ switch (evt.type) {
489
+ case "text":
490
+ return typeof evt.text === "string" ? { kind: "text-delta", sessionId, text: evt.text } : null;
491
+ case "thinking":
492
+ return typeof evt.thinking === "string" ? { kind: "thought", sessionId, text: evt.thinking } : null;
493
+ case "tool_use":
494
+ return {
495
+ kind: "tool-call",
496
+ sessionId,
497
+ toolCallId: typeof evt.id === "string" ? evt.id : "",
498
+ toolName: typeof evt.name === "string" ? evt.name : "?",
499
+ arguments: evt.input ?? {}
500
+ };
501
+ case "tool_result":
502
+ return {
503
+ kind: "tool-result",
504
+ sessionId,
505
+ toolCallId: typeof evt.tool_use_id === "string" ? evt.tool_use_id : "",
506
+ result: evt.content ?? null,
507
+ isError: evt.is_error === true
508
+ };
509
+ case "result":
510
+ if (evt.subtype === "error_during_execution" || evt.is_error === true) {
511
+ return {
512
+ kind: "error",
513
+ sessionId,
514
+ error: {
515
+ message: typeof evt.error === "string" ? evt.error : "Unknown error",
516
+ ...stderrLines.length ? { data: { stderr: stderrLines.join("\n") } } : {}
517
+ }
518
+ };
519
+ }
520
+ if (evt.subtype === "success") {
521
+ return { kind: "turn-end", sessionId, reason: "completed" };
522
+ }
523
+ return null;
524
+ case "system":
525
+ case "assistant":
526
+ return null;
527
+ default:
528
+ return null;
529
+ }
530
+ }
531
+ function waitForExit(child) {
532
+ return new Promise((resolve) => {
533
+ child.once("exit", (code) => resolve(code));
534
+ child.once("error", () => resolve(null));
535
+ });
536
+ }
387
537
 
388
538
  // src/manifest/compose.ts
389
539
  var RuntimeConfigError = class extends Error {
@@ -585,6 +735,15 @@ function createAgentCliRuntime(definition) {
585
735
  ...composed.env,
586
736
  ...opts?.env ?? {}
587
737
  };
738
+ if (definition.protocol === "print") {
739
+ return createPrintSession({
740
+ bin: definition.bin,
741
+ baseArgs: composed.binArgs,
742
+ cwd,
743
+ env,
744
+ ...opts?.resumeSessionId ? { resumeSessionId: opts.resumeSessionId } : {}
745
+ });
746
+ }
588
747
  const child = spawn(definition.bin, composed.binArgs, {
589
748
  cwd,
590
749
  env,
@@ -609,12 +768,22 @@ function createAgentCliRuntime(definition) {
609
768
  once: true
610
769
  });
611
770
  }
771
+ const optModel = opts?.config?.options?.model;
772
+ const optEffort = opts?.config?.options?.effort;
773
+ const modelApply = definition.models?.apply ?? "config";
774
+ const configModel = optModel && modelApply === "config" ? String(optModel) : void 0;
612
775
  await arm.connect({
613
776
  cwd,
614
777
  env,
615
778
  abortSignal: abortController.signal,
616
- ...opts?.resumeSessionId ? { resumeSessionId: opts.resumeSessionId } : {}
779
+ ...opts?.resumeSessionId ? { resumeSessionId: opts.resumeSessionId } : {},
780
+ ...opts?.mcpServers ? { mcpServers: opts.mcpServers } : {},
781
+ ...configModel ? { model: configModel } : {},
782
+ ...optEffort ? { effort: String(optEffort) } : {}
617
783
  });
784
+ if (optModel && modelApply === "command") {
785
+ await applyModelCommand(arm, String(optModel));
786
+ }
618
787
  const sessionId = arm.sessionId ?? randomUUID();
619
788
  return {
620
789
  sessionId,
@@ -633,6 +802,29 @@ function createAgentCliRuntime(definition) {
633
802
  }
634
803
  };
635
804
  }
805
+ async function applyModelCommand(arm, modelId) {
806
+ const turnId = randomUUID();
807
+ let acked = false;
808
+ try {
809
+ for await (const evt of promptTurn(arm, turnId, {
810
+ type: "text",
811
+ text: `/model ${modelId}`
812
+ })) {
813
+ if (/switch|model\s+set|now using/i.test(JSON.stringify(evt))) acked = true;
814
+ }
815
+ } catch (err) {
816
+ console.warn(
817
+ `[agent-cli] /model ${modelId} control turn failed (continuing on default):`,
818
+ err instanceof Error ? err.message : err
819
+ );
820
+ return;
821
+ }
822
+ if (!acked) {
823
+ console.warn(
824
+ `[agent-cli] /model ${modelId}: no switch acknowledgement \u2014 agent may be on its default model`
825
+ );
826
+ }
827
+ }
636
828
  async function* promptTurn(arm, turnId, message) {
637
829
  await arm.send(turnId, message);
638
830
  const stderrTail = arm._stderrTail;
@@ -661,6 +853,8 @@ function buildProtocolArm(def, child, cwd) {
661
853
  throw new Error(
662
854
  "createAgentCliRuntime: proprietary protocol arm not yet implemented"
663
855
  );
856
+ case "print":
857
+ throw new Error("createAgentCliRuntime: print arm bypasses buildProtocolArm");
664
858
  }
665
859
  }
666
860
  function filterStringEnv(env) {
@@ -671,6 +865,6 @@ function filterStringEnv(env) {
671
865
  return out;
672
866
  }
673
867
 
674
- export { RuntimeConfigError, agentCliFrontmatterSchema, autoAllowPermissionHandler, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, resolveContinuationStrategy, runtimeConfigSchema };
675
- //# sourceMappingURL=chunk-VIYTAHJJ.mjs.map
676
- //# sourceMappingURL=chunk-VIYTAHJJ.mjs.map
868
+ export { RuntimeConfigError, agentCliFrontmatterSchema, autoAllowPermissionHandler, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, createPrintSession, defineAgentCli, resolveContinuationStrategy, runtimeConfigSchema };
869
+ //# sourceMappingURL=chunk-YQHVLX6O.mjs.map
870
+ //# sourceMappingURL=chunk-YQHVLX6O.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":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A,QACA,GAAA;AAAA,QACA,YAAY,EAAE,IAAA,EAAM,IAAI,EAAA,EAAI,OAAA,EAAS,IAAI,OAAA;AAAQ,OAClD,CAAA;AAAA,IACH,KAAK,KAAA;AACH,MAAA,MAAM,IAAI,MAAM,6DAA6D,CAAA;AAAA,IAC/E,KAAK,aAAA;AACH,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF,KAAK,OAAA;AAEH,MAAA,MAAM,IAAI,MAAM,4DAA4D,CAAA;AAAA;AAElF;AAEA,SAAS,gBAAgB,GAAA,EAAgD;AACvE,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG;AACxC,IAAA,IAAI,OAAO,CAAA,KAAM,QAAA,EAAU,GAAA,CAAI,CAAC,CAAA,GAAI,CAAA;AAAA,EACtC;AACA,EAAA,OAAO,GAAA;AACT","file":"chunk-YQHVLX6O.mjs","sourcesContent":["/**\n * AIP-45 AGENT-CLI.md frontmatter zod schema.\n *\n * Mirrors `resources/aip-45/draft/AGENT-CLI.schema.json`. AIP-45 is a\n * sibling of AIP-29 (CLI.md, tool CLIs) covering interactive\n * agent-as-process binaries. The `protocol` discriminator (acp / mcp\n * / proprietary) selects the wire arm; cross-field rules ensure the\n * matching arm-specific block is present.\n *\n * Both authoring paths (`define-agent-cli.ts` and\n * `manifest/index.ts`) validate against this schema, so every\n * field-level constraint runs in both paths from a single source of\n * truth.\n */\n\nimport { z } from \"zod\"\n\nconst ID_PATTERN = /^[a-z0-9][a-z0-9-]{1,63}$/\nconst SEMVER_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/\nconst TAG_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/\nconst SEMVER_RANGE_PATTERN = /^[><=^~ \\d.\\-+\\w*xX|, ]+$/\nconst ADAPTER_PATTERN = /^@?[a-z0-9][a-z0-9-./]*$/\nconst BIN_PATTERN = /^[A-Za-z0-9._\\-/]+$/\nconst MODE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/\nconst OPTION_ID_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/\n\nconst CONTINUATION_STRATEGY_IDS = [\n \"none\",\n \"pinned-session\",\n \"transcript\",\n \"native-resume\",\n] as const\n\nconst CONTINUATION_KEY_SCOPES = [\n \"conversation\",\n \"operator\",\n \"user\",\n \"guild\",\n \"workspace\",\n] as const\n\n// AIP-29 install methods, mirrored locally to avoid a runtime cross-package import.\n// Schema-level $ref to AIP-29 is preserved on the JSON Schema side\n// (resources/aip-45/draft/AGENT-CLI.schema.json); this zod copy is the\n// TS-side mirror used by `defineAgentCli`. When AIP-29 grows new\n// install methods, both sides update together via scaffold-aip.\n\nconst installMethodSchema = z.discriminatedUnion(\"method\", [\n z.object({ method: z.literal(\"brew\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"apt\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"dnf\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"pacman\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"choco\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"scoop\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"npm\"), package: z.string(), global: z.boolean().optional(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"pip\"), package: z.string(), user: z.boolean().optional(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"cargo\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"go\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({\n method: z.literal(\"curl\"),\n url: z.string().url(),\n verify_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),\n experimental: z.boolean().optional(),\n }).strict(),\n z.object({\n method: z.literal(\"download\"),\n url: z.string().url(),\n extract_bin: z.string(),\n verify_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),\n experimental: z.boolean().optional(),\n }).strict(),\n z.object({ method: z.literal(\"vendored\"), path: z.string(), experimental: z.boolean().optional() }).strict(),\n])\n\nconst versionCheckSchema = z.object({\n cmd: z.string(),\n parse: z.string().describe(\"ECMAScript regex with at least one capture group.\"),\n range: z.string().regex(SEMVER_RANGE_PATTERN).describe(\"npm-style semver range.\"),\n timeout_ms: z.number().int().min(100).default(5000),\n}).strict()\n\nconst SETUP_STEP_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/\nconst SECRET_SLUG_PATTERN = /^([a-z][a-z0-9-]*[a-z0-9]\\/)?[a-z][a-z0-9-]*[a-z0-9]$/\n\n// `skip_if`: re-runnable health check that, when matching, skips the\n// enclosing setup step. Lets `agentproto setup <slug>` re-runs be\n// idempotent without external completion-ledger state.\nconst skipIfSchema = z\n .object({\n cmd: z.string(),\n exit_code: z.number().int().default(0),\n timeout_ms: z.number().int().min(100).default(5_000),\n })\n .strict()\n\n// `persist`: where the captured value lands so the runner can reuse\n// it on every spawn. Exactly one of env / secret_slug / cmd, enforced\n// via discriminated union.\nconst persistEnvSchema = z\n .object({ env: z.string().regex(/^[A-Z][A-Z0-9_]*$/) })\n .strict()\nconst persistSecretSchema = z\n .object({ secret_slug: z.string().regex(SECRET_SLUG_PATTERN).min(2).max(80) })\n .strict()\nconst persistCmdSchema = z.object({ cmd: z.string() }).strict()\nconst setupPersistSchema = z.union([\n persistEnvSchema,\n persistSecretSchema,\n persistCmdSchema,\n])\n\n// AIP-29 § Setup. Mirrors `resources/aip-29/draft/CLI.schema.json#/$defs/setupStep`.\n// The runner runs steps in declared order, persists completion per\n// (bundle.id, workspace.id, user.id), and surfaces `setup_required`\n// to headless callers when steps remain pending.\nconst setupStepSchema = z.discriminatedUnion(\"kind\", [\n z\n .object({\n id: z.string().regex(SETUP_STEP_ID_PATTERN),\n kind: z.literal(\"cmd\"),\n cmd: z.string(),\n description: z.string().max(2000).optional(),\n skip_if: skipIfSchema.optional(),\n timeout_ms: z.number().int().min(100).default(60_000),\n interactive: z.boolean().default(false),\n persist: setupPersistSchema.optional(),\n })\n .strict(),\n z\n .object({\n id: z.string().regex(SETUP_STEP_ID_PATTERN),\n kind: z.literal(\"prompt\"),\n prompt: z.string().min(1),\n description: z.string().max(2000).optional(),\n type: z.enum([\"text\", \"select\", \"boolean\", \"secret\"]).default(\"text\"),\n default: z.string().optional(),\n options: z\n .union([\n z.array(z.string().min(1)).min(1),\n z\n .object({\n cmd: z.string(),\n timeout_ms: z.number().int().min(100).default(30_000),\n })\n .strict(),\n ])\n .optional(),\n skip_if: skipIfSchema.optional(),\n persist: setupPersistSchema.optional(),\n })\n .strict(),\n z\n .object({\n id: z.string().regex(SETUP_STEP_ID_PATTERN),\n kind: z.literal(\"oauth\"),\n secret_slug: z.string().regex(SECRET_SLUG_PATTERN).min(2).max(80),\n description: z.string().max(2000).optional(),\n skip_if: skipIfSchema.optional(),\n })\n .strict(),\n z\n .object({\n id: z.string().regex(SETUP_STEP_ID_PATTERN),\n kind: z.literal(\"external\"),\n url: z.string().url(),\n description: z.string().max(2000).optional(),\n callback: z\n .object({\n param: z.string().min(1).optional(),\n timeout_ms: z.number().int().min(1_000).default(600_000),\n })\n .strict()\n .optional(),\n skip_if: skipIfSchema.optional(),\n persist: setupPersistSchema.optional(),\n })\n .strict(),\n])\n\nconst authSchema = z.object({\n ref: z.string().optional(),\n state: z.object({\n paths: z.array(z.string()).optional(),\n env: z.array(z.string()).optional(),\n }).strict().optional(),\n login: z.object({\n cmd: z.string(),\n interactive: z.boolean().optional(),\n requires_callback_url: z.boolean().optional(),\n }).strict().optional(),\n refresh: z.object({\n cmd: z.string(),\n interval_s: z.number().int().positive().optional(),\n }).strict().optional(),\n expiry: z.object({\n parse: z.string().optional(),\n grace_s: z.number().int().nonnegative().optional(),\n }).strict().optional(),\n}).strict()\n\nconst sessionSchema = z.object({\n mode: z.enum([\"ephemeral\", \"persistent\", \"resumable\"]).default(\"ephemeral\"),\n idle_timeout_ms: z.number().int().min(1000).default(600_000),\n max_turns: z.number().int().positive().optional(),\n context_carryover: z.boolean().default(true),\n}).strict()\n\nconst modelsSchema = z.object({\n default: z.string().optional(),\n allowed: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n // How a model is selected at session start: \"config\" (ACP\n // set_config_option, default) | \"command\" (a `/model <id>` control turn,\n // for agents like hermes that ignore the ACP session model config).\n apply: z.enum([\"config\", \"command\"]).optional(),\n}).strict()\n\nconst capabilitiesSchema = z.object({\n streaming: z.boolean().optional(),\n tool_calls: z.boolean().optional(),\n sub_agents: z.boolean().optional(),\n file_io: z.boolean().optional(),\n multimodal: z.boolean().optional(),\n resumable: z.boolean().optional(),\n bidirectional: z.boolean().optional(),\n /**\n * Adapter can ingest a filesystem path that the host UI just placed\n * on disk (host-side drag-drop into a terminal pastes the path\n * here). Implies the adapter has a Read-file tool wired so the\n * dropped path actually does something. Hosts gate drag-drop UI on\n * this flag — defaults to false (conservative).\n */\n file_attach: z.boolean().optional(),\n}).strict()\n\nconst modeSchema = z.object({\n id: z.string().regex(MODE_ID_PATTERN),\n description: z.string().optional(),\n bin_args_append: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict()\n\nconst optionSchema = z.object({\n id: z.string().regex(OPTION_ID_PATTERN),\n type: z.enum([\"boolean\", \"integer\", \"string\", \"enum\"]),\n description: z.string().optional(),\n enum: z.array(z.string()).min(1).optional(),\n default: z.union([z.boolean(), z.number(), z.string()]).optional(),\n min: z.number().int().optional(),\n max: z.number().int().optional(),\n bin_args_template: z.array(z.string()).optional(),\n bin_args_append_when_true: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict().refine(\n // type === \"enum\" REQUIRES an `enum` array. The JSON Schema enforces\n // this via `if/then`; the zod side mirrors with a refine so both\n // validation paths reject the same shapes.\n o => o.type !== \"enum\" || (Array.isArray(o.enum) && o.enum.length > 0),\n { message: \"option.type === 'enum' requires a non-empty `enum` array\" }\n)\n\nconst continuationStrategyIdSchema = z.enum(CONTINUATION_STRATEGY_IDS)\n\nconst continuationSchema = z.object({\n default: continuationStrategyIdSchema,\n supported: z.array(continuationStrategyIdSchema).min(1),\n pinned_session: z.object({\n idle_timeout_ms: z.number().int().min(1000).default(1_800_000),\n key_scope: z\n .array(z.enum(CONTINUATION_KEY_SCOPES))\n .min(1)\n .default([\"conversation\", \"operator\"]),\n }).strict().optional(),\n}).strict().refine(\n // The chosen `default` must appear in `supported` — otherwise the\n // host has no valid strategy to fall back to.\n c => c.supported.includes(c.default),\n {\n message: \"continuation.default must be a member of continuation.supported\",\n }\n)\n\nconst mcpBlockSchema = z.object({\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n transport: z.enum([\"stdio\", \"http\", \"sse\"]),\n url: z.string().url().optional(),\n}).strict()\n\nexport const agentCliFrontmatterSchema = z\n .object({\n name: z.string().min(1).max(80),\n id: z.string().regex(ID_PATTERN),\n description: z.string().min(1).max(2000),\n version: z.string().regex(SEMVER_PATTERN),\n bin: z.string().regex(BIN_PATTERN),\n bin_args: z.array(z.string()).optional(),\n install: z.array(installMethodSchema).min(1),\n version_check: versionCheckSchema,\n setup: z.array(setupStepSchema).optional(),\n auth: authSchema.optional(),\n sandbox: z.union([z.string(), z.record(z.string(), z.unknown())]),\n runner: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),\n protocol: z.enum([\"acp\", \"mcp\", \"proprietary\", \"print\"]),\n acp: z.string().optional(),\n mcp: mcpBlockSchema.optional(),\n adapter: z.string().regex(ADAPTER_PATTERN).optional(),\n session: sessionSchema.optional(),\n models: modelsSchema.optional(),\n capabilities: capabilitiesSchema.optional(),\n modes: z.array(modeSchema).optional(),\n options: z.array(optionSchema).optional(),\n continuation: continuationSchema.optional(),\n requires: z.object({\n os: z.array(z.enum([\"darwin\", \"linux\", \"windows\"])).optional(),\n arch: z.array(z.enum([\"x64\", \"arm64\", \"x86\", \"arm\"])).optional(),\n min_disk_mb: z.number().int().nonnegative().optional(),\n min_memory_mb: z.number().int().nonnegative().optional(),\n }).strict().optional(),\n examples: z.array(z.object({\n goal: z.string(),\n prompt: z.string(),\n note: z.string().optional(),\n }).strict()).optional(),\n tags: z.array(z.string().regex(TAG_PATTERN)).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .strict()\n .superRefine((m, ctx) => {\n // Unique mode ids — duplicates would silently shadow.\n if (m.modes) {\n const seen = new Set<string>()\n for (const mode of m.modes) {\n if (seen.has(mode.id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"modes\"],\n message: `Duplicate mode id '${mode.id}' — mode ids must be unique within a manifest.`,\n })\n }\n seen.add(mode.id)\n }\n }\n // Unique setup step ids — duplicates would silently shadow each\n // other in the host's completion ledger, leading to one step\n // never re-prompting and another always re-prompting.\n if (m.setup) {\n const seen = new Set<string>()\n for (const step of m.setup) {\n if (seen.has(step.id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"setup\"],\n message: `Duplicate setup step id '${step.id}' — step ids must be unique within a manifest.`,\n })\n }\n seen.add(step.id)\n }\n }\n // Unique option ids — same reasoning as modes.\n if (m.options) {\n const seen = new Set<string>()\n for (const opt of m.options) {\n if (seen.has(opt.id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"options\"],\n message: `Duplicate option id '${opt.id}' — option ids must be unique within a manifest.`,\n })\n }\n seen.add(opt.id)\n }\n }\n // continuation.default === \"native-resume\" requires capabilities.resumable: true.\n // Mirrors the JSON Schema's allOf rule so both validation paths\n // reject the same shape.\n if (\n m.continuation?.default === \"native-resume\" &&\n !m.capabilities?.resumable\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"continuation\", \"default\"],\n message:\n \"continuation.default === 'native-resume' requires capabilities.resumable: true.\",\n })\n }\n })\n .describe(\n \"Validates the YAML frontmatter portion of an AIP-45 AGENT-CLI.md manifest.\",\n )\n\nexport type AgentCliFrontmatter = z.infer<typeof agentCliFrontmatterSchema>\n\n// Re-export the per-call config schema for hosts that want to validate\n// `OPERATOR.runtime.config` against a manifest at load time. Validation\n// against the manifest's modes/options/continuation lives in\n// `manifest/compose.ts` (the spawn-arg composer) — this schema covers\n// only the SHAPE checks (types, enum values).\nexport const runtimeConfigSchema = z.object({\n mode: z.string().optional(),\n options: z.record(z.string(), z.union([z.boolean(), z.number(), z.string()]))\n .optional(),\n continuation: continuationStrategyIdSchema.optional(),\n}).strict()\n\nexport type RuntimeConfigInput = z.infer<typeof runtimeConfigSchema>\n","/**\n * AIP-45 protocol arm: `protocol: \"acp\"`.\n *\n * Wraps a subprocess's stdio in an `@agentproto/acp` client and\n * exposes the `AgentCliClient` shape the runner consumes. Each\n * `send()` call delegates to a single AcpClientSession.prompt() and\n * forwards the resulting StreamEvent stream.\n */\n\nimport type { ChildProcess } from \"node:child_process\"\nimport { Readable, Writable } from \"node:stream\"\nimport {\n createAcpClient,\n type AcpClient,\n type AcpClientSession,\n} from \"@agentproto/acp/client\"\nimport type {\n AgentCliClient,\n AgentCliConnectOptions,\n StreamEvent,\n} from \"../types.js\"\n\n/**\n * Outcome the host returns to the agent on a permission request.\n *\n * Mirrors the upstream ACP `RequestPermissionResponse` shape EXACTLY —\n * note the doubly-nested `outcome` field: the outer is the response\n * envelope, the inner is the discriminator (string literal, not a\n * `{ type: ... }` object). Get this wrong and the agent silently\n * interprets the response as a refusal (\"User refused permission to\n * run tool\"), so we type it strictly here.\n *\n * { outcome: { outcome: \"selected\", optionId: \"...\" } }\n * { outcome: { outcome: \"cancelled\" } }\n */\nexport type AcpPermissionOutcome =\n | { outcome: { outcome: \"selected\"; optionId: string } }\n | { outcome: { outcome: \"cancelled\" } }\n\nexport interface AcpPermissionRequestParams {\n sessionId?: string\n toolCall?: {\n toolCallId?: string\n title?: string\n kind?: string\n rawInput?: unknown\n }\n options?: Array<{ optionId: string; name?: string; kind?: string }>\n}\n\nexport type AcpPermissionHandler = (\n params: AcpPermissionRequestParams\n) => Promise<AcpPermissionOutcome> | AcpPermissionOutcome\n\n/**\n * Default handler: pick the first option whose `kind` starts with\n * `allow_` (Claude Code offers `allow_once` and `allow_always`).\n * Falls back to the first option if none match — keeps the agent\n * unblocked rather than throwing on an unfamiliar option set.\n *\n * Mirrors the trust model of in-process Mastra agents: the user\n * approved the operator binding once; subsequent tool calls don't\n * re-prompt by default. Hosts that want explicit per-call gating\n * pass their own `onPermissionRequest`.\n */\nexport const autoAllowPermissionHandler: AcpPermissionHandler = ({\n options,\n}) => {\n if (!options || options.length === 0) {\n // No options offered — return cancelled so the agent gets a\n // deterministic answer instead of hanging on a dropped request.\n return { outcome: { outcome: \"cancelled\" } }\n }\n const allow =\n options.find(o => typeof o.kind === \"string\" && o.kind.startsWith(\"allow_\")) ??\n options[0]\n return { outcome: { outcome: \"selected\", optionId: allow!.optionId } }\n}\n\nexport interface AcpProtocolOptions {\n child: ChildProcess\n cwd: string\n clientInfo?: { name: string; title?: string; version?: string }\n /** Called when the agent asks for permission to run a tool (Write,\n * Bash, ...). Defaults to `autoAllowPermissionHandler`. Pass a\n * custom handler to plumb requests through a UI / governance\n * policy. Throwing or returning a rejected promise bubbles to the\n * agent as an internal error. */\n onPermissionRequest?: AcpPermissionHandler\n}\n\nexport function createAcpProtocolArm(\n options: AcpProtocolOptions,\n): AgentCliClient {\n const { child, cwd } = options\n\n if (!child.stdin || !child.stdout) {\n throw new Error(\n \"AcpProtocolArm: subprocess must be spawned with piped stdin + stdout\",\n )\n }\n\n const output = Writable.toWeb(child.stdin) as WritableStream<Uint8Array>\n const input = Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>\n\n let client: AcpClient | null = null\n let session: AcpClientSession | null = null\n const pendingByTurn = new Map<string, AsyncIterable<StreamEvent>>()\n\n return {\n get sessionId(): string | undefined {\n return session?.sessionId\n },\n async connect(opts: AgentCliConnectOptions) {\n const permissionHandler =\n options.onPermissionRequest ?? autoAllowPermissionHandler\n client = await createAcpClient({\n output,\n input,\n clientInfo: options.clientInfo,\n capabilities: {\n fs: { readTextFile: true, writeTextFile: true },\n },\n // Wire the permission handler so the agent's `session/request_permission`\n // callbacks get a real answer instead of bubbling up as\n // \"AcpClient.requestPermission: no handler configured\" → which\n // surfaces in the chat as an opaque \"Internal error\" when the\n // agent tries to Write / Bash anything gated.\n handlers: {\n requestPermission: async (params: unknown) =>\n permissionHandler(params as AcpPermissionRequestParams),\n } as never,\n })\n // When the host hands us a `resumeSessionId`, reattach to the\n // agent's existing session via `loadSession` so the conversation\n // (model context, tool history, working files) carries over a\n // cold start. We trust the host to only send ids it persisted\n // from a prior turn; if the agent's `loadSession: true` capability\n // wasn't advertised the SDK call surfaces the per-protocol error.\n //\n // No silent fallback to `newSession` on resume failure — that\n // would create a new session quietly and lose continuity, which\n // is the bug we're trying to prevent. Let the error propagate.\n if (opts.resumeSessionId) {\n session = await client.loadSession({\n sessionId: opts.resumeSessionId,\n cwd,\n mcpServers: opts.mcpServers,\n })\n } else {\n session = await client.newSession({\n cwd,\n mcpServers: opts.mcpServers,\n ...(opts.model ? { model: opts.model } : {}),\n ...(opts.effort ? { effort: opts.effort } : {}),\n })\n }\n },\n async send(turnId, message) {\n if (!session) throw new Error(\"AcpProtocolArm.send: not connected\")\n // ACP's `prompt` field is `ContentBlock[]` — multiple blocks\n // together form the user's turn (text + image + resource_link\n // + ...). Callers MAY pass either:\n // - a single block (`{type:\"text\",text:\"...\"}`) — wrapped\n // into a one-element array for the wire\n // - an array of blocks — forwarded verbatim, supporting\n // multimodal turns without callers re-shaping per-arm\n const messages = Array.isArray(message) ? message : [message]\n const stream = session.prompt({ messages })\n pendingByTurn.set(turnId, stream)\n },\n async *events(): AsyncIterable<StreamEvent> {\n const last = Array.from(pendingByTurn.values()).at(-1)\n if (!last) return\n for await (const evt of last) yield evt\n },\n async cancel(_turnId) {\n if (!session) return\n await session.cancel()\n },\n async close() {\n if (session) await session.close()\n if (client) await client.close()\n },\n }\n}\n","/**\n * AIP-45 protocol arm: `protocol: \"print\"`.\n *\n * Drives `claude -p --output-format stream-json [--resume <id>]` — one\n * fresh subprocess per turn, no long-lived ACP connection. Simpler than\n * the ACP arm and immune to the stale-proxy race condition: the session\n * object itself never dies between turns; only the per-turn child does.\n *\n * The `sessionId` property starts empty (or pre-seeded with a\n * `resumeSessionId`) and is updated after the first successful turn from\n * the `result` event's `session_id` field. Subsequent turns pass\n * `--resume <sessionId>` so Claude Code rehydrates the conversation from\n * its JSONL store.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { createInterface } from \"node:readline\"\nimport type { AgentCliRuntimeSession, StreamEvent } from \"../types.js\"\n\nexport interface PrintArmOptions {\n bin: string\n /** Base argv passed to the binary BEFORE print flags and prompt.\n * Typically permission-mode and model overrides from `composeSpawn`. */\n baseArgs: string[]\n cwd: string\n env: Record<string, string>\n /** Pre-seed from `resumeSessionId` so the first turn reattaches. */\n resumeSessionId?: string\n}\n\nexport function createPrintSession(opts: PrintArmOptions): AgentCliRuntimeSession {\n let sessionId = opts.resumeSessionId ?? \"\"\n let activeChild: ReturnType<typeof spawn> | null = null\n\n return {\n get sessionId(): string {\n return sessionId\n },\n\n async *send(message: unknown): AsyncIterable<StreamEvent> {\n const prompt = extractPromptText(message)\n\n const args: string[] = [\n ...opts.baseArgs,\n \"--print\",\n \"--output-format\",\n \"stream-json\",\n \"--no-interactive\",\n ...(sessionId ? [\"--resume\", sessionId] : []),\n prompt,\n ]\n\n const child = spawn(opts.bin, args, {\n cwd: opts.cwd,\n env: opts.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n activeChild = child\n\n const stderrLines: string[] = []\n const STDERR_KEEP = 80\n child.stderr?.setEncoding(\"utf8\")\n child.stderr?.on(\"data\", (chunk: string) => {\n for (const line of chunk.split(/\\r?\\n/)) {\n if (!line) continue\n stderrLines.push(line)\n if (stderrLines.length > STDERR_KEEP) stderrLines.shift()\n }\n })\n\n try {\n if (!child.stdout) throw new Error(\"print-arm: child has no stdout pipe\")\n const rl = createInterface({ input: child.stdout, crlfDelay: Infinity })\n\n let capturedSessionId = \"\"\n for await (const line of rl) {\n if (!line.trim()) continue\n let evt: Record<string, unknown>\n try {\n evt = JSON.parse(line) as Record<string, unknown>\n } catch {\n continue\n }\n\n if (\n evt.type === \"result\" &&\n typeof evt.session_id === \"string\" &&\n evt.session_id\n ) {\n capturedSessionId = evt.session_id\n }\n\n const sid = capturedSessionId || sessionId || \"\"\n const mapped = mapEvent(evt, sid, stderrLines)\n if (!mapped) continue\n\n yield mapped\n }\n\n const exitCode = await waitForExit(child)\n if (capturedSessionId) sessionId = capturedSessionId\n\n if (exitCode !== 0 && exitCode !== null) {\n const errEvt: StreamEvent = {\n kind: \"error\",\n error: {\n message: `claude exited with code ${exitCode}`,\n ...(stderrLines.length\n ? { data: { stderr: stderrLines.join(\"\\n\") } }\n : {}),\n },\n }\n yield errEvt\n }\n } finally {\n activeChild = null\n }\n },\n\n async cancel(): Promise<void> {\n activeChild?.kill(\"SIGTERM\")\n },\n\n async close(): Promise<void> {\n activeChild?.kill(\"SIGTERM\")\n },\n }\n}\n\nfunction extractPromptText(message: unknown): string {\n if (typeof message === \"string\") return message\n if (message !== null && typeof message === \"object\") {\n const m = message as Record<string, unknown>\n if (typeof m.text === \"string\") return m.text\n if (Array.isArray(message)) {\n return (message as Array<Record<string, unknown>>)\n .filter(b => b.type === \"text\" && typeof b.text === \"string\")\n .map(b => b.text as string)\n .join(\"\\n\")\n }\n }\n return JSON.stringify(message)\n}\n\nfunction mapEvent(\n evt: Record<string, unknown>,\n sessionId: string,\n stderrLines: string[],\n): StreamEvent | null {\n switch (evt.type) {\n case \"text\":\n return typeof evt.text === \"string\"\n ? { kind: \"text-delta\", sessionId, text: evt.text }\n : null\n\n case \"thinking\":\n return typeof evt.thinking === \"string\"\n ? { kind: \"thought\", sessionId, text: evt.thinking }\n : null\n\n case \"tool_use\":\n return {\n kind: \"tool-call\",\n sessionId,\n toolCallId: typeof evt.id === \"string\" ? evt.id : \"\",\n toolName: typeof evt.name === \"string\" ? evt.name : \"?\",\n arguments: evt.input ?? {},\n }\n\n case \"tool_result\":\n return {\n kind: \"tool-result\",\n sessionId,\n toolCallId:\n typeof evt.tool_use_id === \"string\" ? evt.tool_use_id : \"\",\n result: evt.content ?? null,\n isError: evt.is_error === true,\n }\n\n case \"result\":\n if (\n evt.subtype === \"error_during_execution\" ||\n evt.is_error === true\n ) {\n return {\n kind: \"error\",\n sessionId,\n error: {\n message:\n typeof evt.error === \"string\" ? evt.error : \"Unknown error\",\n ...(stderrLines.length\n ? { data: { stderr: stderrLines.join(\"\\n\") } }\n : {}),\n },\n }\n }\n if (evt.subtype === \"success\") {\n return { kind: \"turn-end\", sessionId, reason: \"completed\" }\n }\n return null\n\n case \"system\":\n case \"assistant\":\n // skip: init metadata and full message recap (streaming text-delta covers it)\n return null\n\n default:\n return null\n }\n}\n\nfunction waitForExit(child: ReturnType<typeof spawn>): Promise<number | null> {\n return new Promise(resolve => {\n child.once(\"exit\", code => resolve(code))\n child.once(\"error\", () => resolve(null))\n })\n}\n","/**\n * Spawn-argument composer.\n *\n * Pure function: given an `AgentCliHandle` and a per-call\n * `RuntimeConfig`, produces the final `binArgs + env` to pass to the\n * runtime's `start()`. Validates the config against the manifest's\n * declared `modes` / `options` / `continuation.supported`; unknown ids\n * throw `RuntimeConfigError` (the host should NOT spawn — the user\n * configured something the manifest doesn't accept).\n *\n * Composition order (matches AIP-45 spec):\n * 1. Manifest's default `bin_args` (from `handle.bin_args`).\n * 2. Mode patch (`bin_args_append`, `env`) when `config.mode` set.\n * 3. Option patches in DECLARATION order (`bin_args_template` /\n * `bin_args_append_when_true` / `env`) for each option present\n * in `config.options`.\n *\n * Mode is applied before options because modes are coarse profile\n * switches (claude-code's `--permission-mode`) — options refine them.\n * Within options, declaration order is honoured so adapter authors\n * can express \"this flag must come after that one\" without the host\n * needing to know the rule.\n */\n\nimport type {\n AgentCliHandle,\n AgentCliOption,\n RuntimeConfig,\n} from \"../types.js\"\n\n/**\n * Thrown when `RuntimeConfig` references manifest entries that don't\n * exist or violates a declared constraint (type / enum / bounds). The\n * `code` field lets callers map to friendly UI messages without\n * inspecting the message string.\n */\nexport class RuntimeConfigError extends Error {\n readonly code:\n | \"unknown_mode\"\n | \"unknown_option\"\n | \"option_type_mismatch\"\n | \"option_enum_violation\"\n | \"option_bounds_violation\"\n | \"unsupported_continuation\"\n readonly path: string\n constructor(\n code: RuntimeConfigError[\"code\"],\n path: string,\n message: string\n ) {\n super(`[${code} at ${path}] ${message}`)\n this.code = code\n this.path = path\n this.name = \"RuntimeConfigError\"\n }\n}\n\n/**\n * Resolved spawn args + env. The runtime's `start()` impl merges\n * `env` into the host process env / sandbox env before exec.\n */\nexport interface ComposedSpawn {\n binArgs: string[]\n env: Record<string, string>\n}\n\n/**\n * Compose the final spawn args from a manifest + per-call config.\n * Pure — no I/O, no sandbox access, no global state. Safe to call\n * repeatedly with the same input.\n *\n * `config` may be undefined or an empty object — both fall back to\n * the manifest's defaults verbatim (manifest `bin_args`, no mode\n * patch, no option patches). Continuation is not applied here — the\n * `ContinuationStrategy` registry handles that — but we DO validate\n * `config.continuation` against `manifest.continuation.supported` so\n * a misconfigured operator fails fast at compose time, not at the\n * point the strategy tries to acquire a session.\n */\nexport function composeSpawn(\n handle: AgentCliHandle,\n config?: RuntimeConfig\n): ComposedSpawn {\n const binArgs: string[] = [...(handle.bin_args ?? [])]\n const env: Record<string, string> = {}\n\n if (!config) return { binArgs, env }\n\n // ── Mode patch ──────────────────────────────────────────────────\n if (config.mode !== undefined) {\n const mode = (handle.modes ?? []).find(m => m.id === config.mode)\n if (!mode) {\n const known = (handle.modes ?? []).map(m => m.id).join(\", \") || \"(none)\"\n throw new RuntimeConfigError(\n \"unknown_mode\",\n \"config.mode\",\n `Mode '${config.mode}' is not declared by manifest '${handle.id}'. Known modes: ${known}`\n )\n }\n if (mode.bin_args_append) binArgs.push(...mode.bin_args_append)\n if (mode.env) Object.assign(env, mode.env)\n }\n\n // ── Option patches (declaration order) ──────────────────────────\n if (config.options && Object.keys(config.options).length > 0) {\n const declared = handle.options ?? []\n const declaredById = new Map(declared.map(o => [o.id, o]))\n // Reject unknown ids first so the operator sees ALL the typos\n // (not just the one we hit first when iterating declared).\n for (const id of Object.keys(config.options)) {\n if (!declaredById.has(id)) {\n const known = declared.map(o => o.id).join(\", \") || \"(none)\"\n throw new RuntimeConfigError(\n \"unknown_option\",\n `config.options.${id}`,\n `Option '${id}' is not declared by manifest '${handle.id}'. Known options: ${known}`\n )\n }\n }\n // Then apply patches in declaration order so adapter-author intent\n // wins over operator-config key order.\n for (const option of declared) {\n if (!(option.id in config.options)) continue\n const value = config.options[option.id] as boolean | number | string\n validateOptionValue(option, value)\n const patch = renderOptionPatch(option, value)\n binArgs.push(...patch.binArgs)\n Object.assign(env, patch.env)\n }\n }\n\n // ── Continuation validation (no patch — strategy registry owns) ─\n if (config.continuation !== undefined && handle.continuation) {\n if (!handle.continuation.supported.includes(config.continuation)) {\n throw new RuntimeConfigError(\n \"unsupported_continuation\",\n \"config.continuation\",\n `Continuation strategy '${config.continuation}' is not in manifest '${handle.id}'.continuation.supported (${handle.continuation.supported.join(\", \")}).`\n )\n }\n }\n\n return { binArgs, env }\n}\n\n/**\n * Resolve the continuation strategy id to use for this call. Operator\n * config wins; manifest default is the fallback; \"none\" if neither\n * declares anything (preserves pre-AIP-45-extension behaviour).\n */\nexport function resolveContinuationStrategy(\n handle: AgentCliHandle,\n config?: RuntimeConfig\n): import(\"../types.js\").ContinuationStrategyId {\n if (config?.continuation) return config.continuation\n return handle.continuation?.default ?? \"none\"\n}\n\nfunction validateOptionValue(\n option: AgentCliOption,\n value: boolean | number | string\n): void {\n const path = `config.options.${option.id}`\n switch (option.type) {\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected boolean, got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n return\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected integer, got ${typeof value === \"number\" ? \"non-integer number\" : typeof value} (${JSON.stringify(value)}).`\n )\n }\n if (option.min !== undefined && value < option.min) {\n throw new RuntimeConfigError(\n \"option_bounds_violation\",\n path,\n `Value ${value} is below the declared minimum ${option.min}.`\n )\n }\n if (option.max !== undefined && value > option.max) {\n throw new RuntimeConfigError(\n \"option_bounds_violation\",\n path,\n `Value ${value} is above the declared maximum ${option.max}.`\n )\n }\n return\n case \"string\":\n if (typeof value !== \"string\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected string, got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n return\n case \"enum\":\n if (typeof value !== \"string\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected string (enum value), got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n if (!(option.enum ?? []).includes(value)) {\n throw new RuntimeConfigError(\n \"option_enum_violation\",\n path,\n `Value '${value}' is not in the declared enum (${(option.enum ?? []).join(\", \")}).`\n )\n }\n return\n }\n}\n\nfunction renderOptionPatch(\n option: AgentCliOption,\n value: boolean | number | string\n): { binArgs: string[]; env: Record<string, string> } {\n const stringValue = String(value)\n\n // boolean type: only emit the bare flag when value === true and the\n // option declared `bin_args_append_when_true`. Honor `env` too —\n // adapter authors might want to surface the bool via env.\n if (option.type === \"boolean\") {\n if (value !== true) return { binArgs: [], env: {} }\n return {\n binArgs: option.bin_args_append_when_true\n ? [...option.bin_args_append_when_true]\n : [],\n env: option.env ? interpolateEnv(option.env, stringValue) : {},\n }\n }\n\n // value-bearing types — apply `bin_args_template` (with `{value}`\n // interpolation) and merge `env`.\n return {\n binArgs: option.bin_args_template\n ? option.bin_args_template.map(token =>\n token.replace(/\\{value\\}/g, stringValue)\n )\n : [],\n env: option.env ? interpolateEnv(option.env, stringValue) : {},\n }\n}\n\nfunction interpolateEnv(\n env: Record<string, string>,\n value: string\n): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(env)) {\n out[k] = v.replace(/\\{value\\}/g, value)\n }\n return out\n}\n","import { spawn, type ChildProcess } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport { createDoctype } from \"@agentproto/define-doctype\"\nimport { agentCliFrontmatterSchema } from \"./schema.js\"\nimport { createAcpProtocolArm } from \"./protocol/acp-client.js\"\nimport { createPrintSession } from \"./protocol/print-arm.js\"\nimport { composeSpawn } from \"./manifest/compose.js\"\nimport type {\n AgentCliClient,\n AgentCliDefinition,\n AgentCliHandle,\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n StreamEvent,\n} from \"./types.js\"\n\nexport const defineAgentCli = createDoctype<AgentCliDefinition, AgentCliHandle>(\n {\n aip: 45,\n name: \"agent-cli\",\n readIdentity: (def) => def.id,\n validate(def) {\n const result = agentCliFrontmatterSchema.safeParse(def)\n if (!result.success) {\n throw new Error(\n `defineAgentCli (AIP-45): ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n\n const data = result.data\n\n if (data.protocol === \"acp\" && !data.acp) {\n throw new Error(\n \"defineAgentCli (AIP-45): `acp` ref is required when protocol=acp\",\n )\n }\n if (data.protocol === \"mcp\" && !data.mcp) {\n throw new Error(\n \"defineAgentCli (AIP-45): `mcp` block is required when protocol=mcp\",\n )\n }\n if (data.protocol === \"proprietary\" && !data.adapter) {\n throw new Error(\n \"defineAgentCli (AIP-45): `adapter` package is required when protocol=proprietary\",\n )\n }\n\n if (\n data.session?.mode === \"resumable\" &&\n data.capabilities?.resumable !== true\n ) {\n throw new Error(\n \"defineAgentCli (AIP-45): session.mode=resumable requires capabilities.resumable: true\",\n )\n }\n },\n build(def) {\n return { ...def } as AgentCliHandle\n },\n },\n)\n\nexport function createAgentCliRuntime(\n definition: AgentCliHandle,\n): AgentCliRuntime {\n return {\n definition,\n async start(opts?: AgentCliStartOptions): Promise<AgentCliRuntimeSession> {\n const cwd = opts?.cwd ?? process.cwd()\n // Compose final argv + env from the manifest + per-call config.\n // Mode patches and option patches land BEFORE the host-provided\n // env so an operator-set option can be observed by the CLI even\n // when the manifest also touches the same env key (operator\n // intent wins). Validation runs here too — a misconfigured\n // operator throws RuntimeConfigError before we exec anything.\n const composed = composeSpawn(definition, opts?.config)\n const env: Record<string, string> = {\n ...filterStringEnv(process.env),\n ...composed.env,\n ...(opts?.env ?? {}),\n }\n\n // The print arm spawns a fresh subprocess per turn — no\n // long-lived child, no AgentCliClient connect/events cycle.\n // Short-circuit here so buildProtocolArm is never called for it.\n if (definition.protocol === \"print\") {\n return createPrintSession({\n bin: definition.bin,\n baseArgs: composed.binArgs,\n cwd,\n env,\n ...(opts?.resumeSessionId\n ? { resumeSessionId: opts.resumeSessionId }\n : {}),\n })\n }\n\n const child = spawn(definition.bin, composed.binArgs, {\n cwd,\n env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n signal: opts?.signal,\n })\n\n // Drain child.stderr — without this the kernel pipe buffer\n // (~64 KB on macOS / Linux) eventually fills up and blocks the\n // child mid-write, hanging the entire ACP exchange. Buffer the\n // last few KB so a downstream error event can attach the tail\n // for debugging — adapters like claude-agent-acp print useful\n // context here (\"not authenticated\", \"model gated\") that the\n // JSON-RPC reply would otherwise reduce to \"Invalid params\".\n const stderrBuf: string[] = []\n const STDERR_KEEP_LINES = 80\n child.stderr?.setEncoding(\"utf8\")\n child.stderr?.on(\"data\", (chunk: string) => {\n for (const line of chunk.split(/\\r?\\n/)) {\n if (!line) continue\n stderrBuf.push(line)\n if (stderrBuf.length > STDERR_KEEP_LINES) stderrBuf.shift()\n }\n })\n\n const arm = buildProtocolArm(definition, child, cwd)\n arm._stderrTail = () => stderrBuf.join(\"\\n\")\n\n const abortController = new AbortController()\n if (opts?.signal) {\n opts.signal.addEventListener(\"abort\", () => abortController.abort(), {\n once: true,\n })\n }\n // Extract model + effort from the config options so the protocol\n // arm can apply them via ACP session/set_config_option — the ACP\n // wrapper (claude-agent-acp) does not read its own CLI args and\n // forward them to claude, so bin_args_template alone is not\n // sufficient. The compose step still adds them to binArgs as a\n // best-effort fallback for non-ACP arms.\n const optModel = opts?.config?.options?.model\n const optEffort = opts?.config?.options?.effort\n // Model-selection strategy (AgentCliModels.apply, default \"config\"):\n // \"config\" → apply via ACP session config (set_config_option) at\n // connect — works for claude-code.\n // \"command\" → the ACP session config is a no-op on this agent\n // (e.g. hermes silently keeps its own default), so we\n // DON'T pass model to connect; instead we send a\n // `/model <id>` control turn after newSession (below).\n const modelApply = definition.models?.apply ?? \"config\"\n const configModel =\n optModel && modelApply === \"config\" ? String(optModel) : undefined\n await arm.connect({\n cwd,\n env,\n abortSignal: abortController.signal,\n ...(opts?.resumeSessionId\n ? { resumeSessionId: opts.resumeSessionId }\n : {}),\n ...(opts?.mcpServers ? { mcpServers: opts.mcpServers } : {}),\n ...(configModel ? { model: configModel } : {}),\n ...(optEffort ? { effort: String(optEffort) } : {}),\n })\n\n // \"command\" model strategy: switch the model via a drained `/model\n // <id>` control turn. Best-effort — a failure is warned, never fatal,\n // so the session still starts (on the agent's default model).\n if (optModel && modelApply === \"command\") {\n await applyModelCommand(arm, String(optModel))\n }\n\n // Prefer the protocol-layer session id (ACP, etc.) so the host\n // can persist it for a future native-resume. Fall back to a\n // random UUID for protocols that don't model sessions — keeps\n // the field always-populated for downstream loggers.\n const sessionId = arm.sessionId ?? randomUUID()\n\n return {\n sessionId,\n send(message): AsyncIterable<StreamEvent> {\n const turnId = randomUUID()\n return promptTurn(arm, turnId, message)\n },\n async cancel() {\n abortController.abort()\n },\n async close() {\n await arm.close()\n if (!child.killed) child.kill(\"SIGTERM\")\n },\n }\n },\n }\n}\n\n/**\n * Switch the active model via a `/model <id>` control turn, for adapters\n * whose ACP session config doesn't select the model (`models.apply:\n * \"command\"`, e.g. hermes). The turn is fully drained so the switch\n * completes before the caller's first real turn. Best-effort: a transport\n * failure or a missing acknowledgement is warned, never thrown — the\n * session simply continues on the agent's default model.\n */\nasync function applyModelCommand(\n arm: AgentCliClient,\n modelId: string,\n): Promise<void> {\n const turnId = randomUUID()\n let acked = false\n try {\n for await (const evt of promptTurn(arm, turnId, {\n type: \"text\",\n text: `/model ${modelId}`,\n })) {\n // Loose check across the serialised event — hermes replies\n // \"Model switched to: <id> · Provider: …\". We don't couple to a\n // specific StreamEvent shape; any \"switch\" mention = acknowledged.\n if (/switch|model\\s+set|now using/i.test(JSON.stringify(evt))) acked = true\n }\n } catch (err) {\n console.warn(\n `[agent-cli] /model ${modelId} control turn failed (continuing on default):`,\n err instanceof Error ? err.message : err,\n )\n return\n }\n if (!acked) {\n console.warn(\n `[agent-cli] /model ${modelId}: no switch acknowledgement — agent may be on its default model`,\n )\n }\n}\n\nasync function* promptTurn(\n arm: AgentCliClient,\n turnId: string,\n message: unknown,\n): AsyncIterable<StreamEvent> {\n await arm.send(turnId, message)\n // Re-attach the recent stderr tail to error events. The ACP layer\n // surfaces a terse `{message: \"Invalid params\"}`; the child's\n // stderr almost always has a more useful line (\"npx claude-agent-acp:\n // not authenticated, run `claude login`\"). Hosts read `error.data`\n // when present, falling back to `message` for older payloads.\n const stderrTail = arm._stderrTail\n for await (const evt of arm.events()) {\n if (evt.kind === \"error\" && typeof stderrTail === \"function\") {\n const tail = stderrTail()\n if (tail) {\n const existing = (evt.error.data ?? {}) as Record<string, unknown>\n evt.error.data = { ...existing, stderr: tail }\n }\n }\n yield evt\n }\n}\n\nfunction buildProtocolArm(\n def: AgentCliHandle,\n child: ChildProcess,\n cwd: string,\n): AgentCliClient {\n switch (def.protocol) {\n case \"acp\":\n return createAcpProtocolArm({\n child,\n cwd,\n clientInfo: { name: def.id, version: def.version },\n })\n case \"mcp\":\n throw new Error(\"createAgentCliRuntime: mcp protocol arm not yet implemented\")\n case \"proprietary\":\n throw new Error(\n \"createAgentCliRuntime: proprietary protocol arm not yet implemented\",\n )\n case \"print\":\n // Unreachable: print is handled by the early-return in start() above.\n throw new Error(\"createAgentCliRuntime: print arm bypasses buildProtocolArm\")\n }\n}\n\nfunction filterStringEnv(env: NodeJS.ProcessEnv): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(env)) {\n if (typeof v === \"string\") out[k] = v\n }\n return out\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AgentCliHandle, a as AgentCliRuntime, b as AgentCliDefinition, c as AgentCliClient, R as RuntimeConfig, C as ContinuationStrategyId, d as AgentCliStartOptions, T as TurnContext, e as AgentCliRuntimeSession, f as ContinuationKeyScope } from './schema-Cq4w3654.js';
2
- export { g as AgentCliAuth, h as AgentCliCapabilities, i as AgentCliConnectOptions, j as AgentCliContinuation, k as AgentCliFrontmatter, l as AgentCliInstallMethod, m as AgentCliMcpBlock, n as AgentCliMode, o as AgentCliModels, p as AgentCliOption, q as AgentCliOptionType, r as AgentCliPinnedSessionTuning, s as AgentCliProtocol, t as AgentCliSession, u as AgentCliSessionMode, v as AgentCliSetupPersist, w as AgentCliSetupSkipIf, x as AgentCliSetupStep, y as AgentCliVersionCheck, z as RuntimeConfigInput, B as agentCliFrontmatterSchema, D as runtimeConfigSchema } from './schema-Cq4w3654.js';
1
+ import { A as AgentCliHandle, a as AgentCliRuntime, b as AgentCliDefinition, c as AgentCliClient, d as AgentCliRuntimeSession, R as RuntimeConfig, C as ContinuationStrategyId, e as AgentCliStartOptions, T as TurnContext, f as ContinuationKeyScope } from './schema-CCSzIDMJ.js';
2
+ export { g as AgentCliAuth, h as AgentCliCapabilities, i as AgentCliConnectOptions, j as AgentCliContinuation, k as AgentCliFrontmatter, l as AgentCliInstallMethod, m as AgentCliMcpBlock, n as AgentCliMode, o as AgentCliModels, p as AgentCliOption, q as AgentCliOptionType, r as AgentCliPinnedSessionTuning, s as AgentCliProtocol, t as AgentCliSession, u as AgentCliSessionMode, v as AgentCliSetupPersist, w as AgentCliSetupSkipIf, x as AgentCliSetupStep, y as AgentCliVersionCheck, z as RuntimeConfigInput, B as agentCliFrontmatterSchema, D as runtimeConfigSchema } from './schema-CCSzIDMJ.js';
3
3
  import { ChildProcess } from 'node:child_process';
4
4
  export { StreamEvent } from '@agentproto/acp';
5
5
  import 'zod';
@@ -7,6 +7,76 @@ import 'zod';
7
7
  declare const defineAgentCli: (def: AgentCliDefinition) => Readonly<AgentCliDefinition>;
8
8
  declare function createAgentCliRuntime(definition: AgentCliHandle): AgentCliRuntime;
9
9
 
10
+ /**
11
+ * Agent CLI as a model port — turn ANY AIP-45 agent CLI runtime into a generic
12
+ * `complete({system?, prompt}) → {result}` executor. This is the one bridge that
13
+ * lets the SAME registry (hermes, claude-code, opencode, codex, openclaw, …)
14
+ * back any prompt→completion seam: a report's chapter writer, a corpus
15
+ * distiller, a Mastra tool's judgment step. The executor swaps, the prompts
16
+ * (built by each seam's engine) don't.
17
+ *
18
+ * It drives the CLI over **ACP**: per `complete()` it spawns a fresh session,
19
+ * sends one user turn, concatenates the `text-delta` stream until `turn-end`,
20
+ * then closes. Lives here (not in a product) so seams BELOW the products —
21
+ * `@agentproto/corpus` distill, the CLI — can consume it without importing
22
+ * upward. The runner is injectable so assembly is unit-tested without a binary.
23
+ */
24
+
25
+ /**
26
+ * The minimal structural model port every seam consumes. Anything with this
27
+ * `complete` shape satisfies the corpus `ReportModelPort` / `DistillPort`-backing
28
+ * model / an AIP `ModelPort` — duck-typed, no nominal coupling.
29
+ */
30
+ interface ModelLike {
31
+ complete(req: {
32
+ system?: string;
33
+ prompt: string;
34
+ [k: string]: unknown;
35
+ }): Promise<{
36
+ result: string;
37
+ }>;
38
+ }
39
+ /**
40
+ * The "file-reading sub-agent" tier — opt-in across every file-IO-capable
41
+ * executor. When `datasetDir` is set the executor is rooted there and granted
42
+ * its own read tools, so instead of being limited to the excerpts a seam quotes
43
+ * in the prompt it can open the primary sources directly and ground first-hand.
44
+ */
45
+ interface FileReadingOptions {
46
+ /** Absolute path to the dataset/source root the executor may read from. */
47
+ datasetDir?: string;
48
+ }
49
+ /** The instruction prepended to a completion when {@link FileReadingOptions.datasetDir} is set. */
50
+ declare function datasetPreamble(datasetDir: string): string;
51
+ /** Compose system + prompt with an optional source-access preamble (shared by every executor). */
52
+ declare function composePrompt(system: string | undefined, prompt: string, datasetDir?: string): string;
53
+ /** Provider keys an agent CLI may route through, forwarded from the parent env by default. */
54
+ declare const PROVIDER_KEY_ENV: readonly ["OPENROUTER_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY"];
55
+ interface AgentCliModelOptions extends FileReadingOptions {
56
+ /**
57
+ * Env handed to the spawned CLI process — the provider key it routes through.
58
+ * Defaults to forwarding {@link PROVIDER_KEY_ENV} from the parent process env.
59
+ */
60
+ env?: Record<string, string>;
61
+ /** Working directory for the CLI process. Defaults to `datasetDir` when set. */
62
+ cwd?: string;
63
+ /** Timeout per completion (ms). Default 5 min. */
64
+ timeoutMs?: number;
65
+ /**
66
+ * Injectable runner (composed prompt → completion text). Defaults to driving
67
+ * the runtime over ACP. Override in tests to avoid the CLI.
68
+ */
69
+ run?: (prompt: string) => Promise<string>;
70
+ }
71
+ /** Build the env for the spawned CLI: explicit override, else forwarded provider keys. */
72
+ declare function resolveCliEnv(opts: Pick<AgentCliModelOptions, "env">): Record<string, string>;
73
+ /**
74
+ * Build a {@link ModelLike} backed by an AIP-45 agent-CLI runtime. Hand it any
75
+ * `*Runtime()` from the registry (Hermes, claude-code, opencode, …); per-CLI
76
+ * presets are one-liners over this.
77
+ */
78
+ declare function makeAgentCliModel(runtime: AgentCliRuntime, opts?: AgentCliModelOptions): ModelLike;
79
+
10
80
  /**
11
81
  * AIP-45 protocol arm: `protocol: "acp"`.
12
82
  *
@@ -83,6 +153,33 @@ interface AcpProtocolOptions {
83
153
  }
84
154
  declare function createAcpProtocolArm(options: AcpProtocolOptions): AgentCliClient;
85
155
 
156
+ /**
157
+ * AIP-45 protocol arm: `protocol: "print"`.
158
+ *
159
+ * Drives `claude -p --output-format stream-json [--resume <id>]` — one
160
+ * fresh subprocess per turn, no long-lived ACP connection. Simpler than
161
+ * the ACP arm and immune to the stale-proxy race condition: the session
162
+ * object itself never dies between turns; only the per-turn child does.
163
+ *
164
+ * The `sessionId` property starts empty (or pre-seeded with a
165
+ * `resumeSessionId`) and is updated after the first successful turn from
166
+ * the `result` event's `session_id` field. Subsequent turns pass
167
+ * `--resume <sessionId>` so Claude Code rehydrates the conversation from
168
+ * its JSONL store.
169
+ */
170
+
171
+ interface PrintArmOptions {
172
+ bin: string;
173
+ /** Base argv passed to the binary BEFORE print flags and prompt.
174
+ * Typically permission-mode and model overrides from `composeSpawn`. */
175
+ baseArgs: string[];
176
+ cwd: string;
177
+ env: Record<string, string>;
178
+ /** Pre-seed from `resumeSessionId` so the first turn reattaches. */
179
+ resumeSessionId?: string;
180
+ }
181
+ declare function createPrintSession(opts: PrintArmOptions): AgentCliRuntimeSession;
182
+
86
183
  /**
87
184
  * Thrown when `RuntimeConfig` references manifest entries that don't
88
185
  * exist or violates a declared constraint (type / enum / bounds). The
@@ -287,4 +384,4 @@ declare function configureNativeResume(hooks: NativeResumeHooks): void;
287
384
  declare const SPEC_NAME: "agentcli-interactive/v1";
288
385
  declare const SPEC_VERSION: "0.1.0-alpha";
289
386
 
290
- export { type AcpPermissionHandler, type AcpPermissionOutcome, type AcpPermissionRequestParams, type AcquireContext, AgentCliClient, AgentCliDefinition, AgentCliHandle, AgentCliRuntime, AgentCliRuntimeSession, AgentCliStartOptions, type ComposedSpawn, ContinuationKeyScope, type ContinuationStrategy, ContinuationStrategyId, type NativeResumeHooks, type ReleaseContext, type ReleaseOutcome, RuntimeConfig, RuntimeConfigError, SPEC_NAME, SPEC_VERSION, TurnContext, autoAllowPermissionHandler, composeSpawn, configureNativeResume, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, deriveKeyFromScope, getContinuationStrategy, listContinuationStrategies, registerContinuationStrategy, resolveContinuationStrategy };
387
+ export { type AcpPermissionHandler, type AcpPermissionOutcome, type AcpPermissionRequestParams, type AcquireContext, AgentCliClient, AgentCliDefinition, AgentCliHandle, type AgentCliModelOptions, AgentCliRuntime, AgentCliRuntimeSession, AgentCliStartOptions, type ComposedSpawn, ContinuationKeyScope, type ContinuationStrategy, ContinuationStrategyId, type FileReadingOptions, type ModelLike, type NativeResumeHooks, PROVIDER_KEY_ENV, type PrintArmOptions, type ReleaseContext, type ReleaseOutcome, RuntimeConfig, RuntimeConfigError, SPEC_NAME, SPEC_VERSION, TurnContext, autoAllowPermissionHandler, composePrompt, composeSpawn, configureNativeResume, createAcpProtocolArm, createAgentCliRuntime, createPrintSession, datasetPreamble, defineAgentCli, deriveKeyFromScope, getContinuationStrategy, listContinuationStrategies, makeAgentCliModel, registerContinuationStrategy, resolveCliEnv, resolveContinuationStrategy };
package/dist/index.mjs CHANGED
@@ -1,10 +1,80 @@
1
- export { RuntimeConfigError, agentCliFrontmatterSchema, autoAllowPermissionHandler, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, resolveContinuationStrategy, runtimeConfigSchema } from './chunk-VIYTAHJJ.mjs';
1
+ export { RuntimeConfigError, agentCliFrontmatterSchema, autoAllowPermissionHandler, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, createPrintSession, defineAgentCli, resolveContinuationStrategy, runtimeConfigSchema } from './chunk-YQHVLX6O.mjs';
2
2
 
3
3
  /**
4
4
  * @agentproto/driver-agent-cli v0.1.0-alpha
5
5
  * AIP-45 AGENT-CLI.md `defineAgentCli` reference implementation.
6
6
  */
7
7
 
8
+ // src/model.ts
9
+ function datasetPreamble(datasetDir) {
10
+ return `You have direct read access to the source files under \`${datasetDir}\` (e.g. \`sources/\` raw captures, \`entries/\` refined notes). Use your file-reading tools to consult the primary sources directly when grounding claims \u2014 do not rely only on the excerpts quoted in this prompt.`;
11
+ }
12
+ function composePrompt(system, prompt, datasetDir) {
13
+ const head = datasetDir ? `${datasetPreamble(datasetDir)}
14
+
15
+ ` : "";
16
+ return system ? `${head}${system}
17
+
18
+ ${prompt}` : `${head}${prompt}`;
19
+ }
20
+ var PROVIDER_KEY_ENV = [
21
+ "OPENROUTER_API_KEY",
22
+ "ANTHROPIC_API_KEY",
23
+ "OPENAI_API_KEY"
24
+ ];
25
+ function resolveCliEnv(opts) {
26
+ if (opts.env) return opts.env;
27
+ const env = {};
28
+ for (const k of PROVIDER_KEY_ENV) {
29
+ const v = process.env[k];
30
+ if (v) env[k] = v;
31
+ }
32
+ return env;
33
+ }
34
+ async function driveTurn(runtime, prompt, opts) {
35
+ const controller = new AbortController();
36
+ const timer = setTimeout(
37
+ () => controller.abort(),
38
+ opts.timeoutMs ?? 5 * 60 * 1e3
39
+ );
40
+ const cwd = opts.cwd ?? opts.datasetDir;
41
+ const session = await runtime.start({
42
+ env: resolveCliEnv(opts),
43
+ signal: controller.signal,
44
+ ...cwd ? { cwd } : {}
45
+ });
46
+ try {
47
+ let text = "";
48
+ for await (const evt of session.send({ role: "user", content: prompt })) {
49
+ if (evt.kind === "text-delta") {
50
+ text += evt.text;
51
+ } else if (evt.kind === "error") {
52
+ throw new Error(`${runtime.definition.id} model: ${evt.error.message}`);
53
+ } else if (evt.kind === "turn-end") {
54
+ if (evt.reason !== "completed")
55
+ throw new Error(`${runtime.definition.id} model: turn ${evt.reason}`);
56
+ break;
57
+ }
58
+ }
59
+ if (controller.signal.aborted)
60
+ throw new Error(`${runtime.definition.id} model: timed out`);
61
+ return text.trim();
62
+ } finally {
63
+ clearTimeout(timer);
64
+ await session.close();
65
+ }
66
+ }
67
+ function makeAgentCliModel(runtime, opts = {}) {
68
+ const run = opts.run ?? ((prompt) => driveTurn(runtime, prompt, opts));
69
+ return {
70
+ async complete({ system, prompt }) {
71
+ return {
72
+ result: await run(composePrompt(system, prompt, opts.datasetDir))
73
+ };
74
+ }
75
+ };
76
+ }
77
+
8
78
  // src/continuation/strategies/none.ts
9
79
  var noneStrategy = {
10
80
  id: "none",
@@ -221,6 +291,6 @@ registerContinuationStrategy(nativeResumeStrategy);
221
291
  var SPEC_NAME = "agentcli-interactive/v1";
222
292
  var SPEC_VERSION = "0.1.0-alpha";
223
293
 
224
- export { SPEC_NAME, SPEC_VERSION, configureNativeResume, deriveKeyFromScope, getContinuationStrategy, listContinuationStrategies, registerContinuationStrategy };
294
+ export { PROVIDER_KEY_ENV, SPEC_NAME, SPEC_VERSION, composePrompt, configureNativeResume, datasetPreamble, deriveKeyFromScope, getContinuationStrategy, listContinuationStrategies, makeAgentCliModel, registerContinuationStrategy, resolveCliEnv };
225
295
  //# sourceMappingURL=index.mjs.map
226
296
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/continuation/strategies/none.ts","../src/continuation/types.ts","../src/continuation/strategies/pinned-session.ts","../src/continuation/strategies/transcript.ts","../src/continuation/strategies/native-resume.ts","../src/continuation/registry.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;AAUO,IAAM,YAAA,GAAqC;AAAA,EAChD,EAAA,EAAI,MAAA;AAAA,EACJ,MAAM,QAAQ,GAAA,EAAK;AACjB,IAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,KAAA,CAAM,GAAA,CAAI,YAAY,CAAA;AAAA,EAC3C,CAAA;AAAA,EACA,MAAM,QAAQ,GAAA,EAAK;AACjB,IAAA,MAAM,GAAA,CAAI,QAAQ,KAAA,EAAM;AAAA,EAC1B;AACF,CAAA;;;ACuEO,SAAS,kBAAA,CACd,OACA,OAAA,EACe;AACf,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,MAAM,CAAA,GAAI,QAAQ,CAAC,CAAA;AACnB,IAAA,IAAI,GAAG,KAAA,CAAM,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,EAAI,CAAC,CAAA,CAAE,CAAA;AAAA,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GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU;AAAA,SACvC;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AACA,IAAA,OAAO,OAAA;AAAA,EACT,CAAA;AAAA,EAEA,MAAM,QAAQ,GAAA,EAAK;AAIjB,IAAA,MAAM,GAAA,CAAI,QAAQ,KAAA,EAAM;AAAA,EAC1B;AACF,CAAA;;;AC5HA,IAAM,QAAA,uBAAe,GAAA,EAAkD;AAQhE,SAAS,6BACd,QAAA,EACM;AACN,EAAA,QAAA,CAAS,GAAA,CAAI,QAAA,CAAS,EAAA,EAAI,QAAQ,CAAA;AACpC;AAEO,SAAS,wBACd,EAAA,EACsB;AACtB,EAAA,MAAM,CAAA,GAAI,QAAA,CAAS,GAAA,CAAI,EAAE,CAAA;AACzB,EAAA,IAAI,CAAC,CAAA,EAAG;AACN,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,wDAAA,EAA2D,EAAE,CAAA,cAAA,EAAiB,KAAA,CAAM,IAAA,CAAK,QAAA,CAAS,IAAA,EAAM,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KACtH;AAAA,EACF;AACA,EAAA,OAAO,CAAA;AACT;AAEO,SAAS,0BAAA,GAAuD;AACrE,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,QAAA,CAAS,IAAA,EAAM,CAAA;AACnC;AAIA,4BAAA,CAA6B,YAAY,CAAA;AACzC,4BAAA,CAA6B,qBAAqB,CAAA;AAClD,4BAAA,CAA6B,kBAAkB,CAAA;AAC/C,4BAAA,CAA6B,oBAAoB,CAAA;;;ACrC1C,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * `none` strategy — pre-AIP-45-extension behaviour.\n *\n * Spawn a fresh session per acquire; close it on release. No state,\n * no reuse. The default when a manifest declares no `continuation`\n * block (back-compat for adapters that haven't been updated).\n */\n\nimport type { ContinuationStrategy } from \"../types.js\"\n\nexport const noneStrategy: ContinuationStrategy = {\n id: \"none\",\n async acquire(ctx) {\n return ctx.runtime.start(ctx.startOptions)\n },\n async release(ctx) {\n await ctx.session.close()\n },\n}\n","/**\n * AIP-45 ContinuationStrategy interface.\n *\n * A continuation strategy decides HOW prior conversation turns reach a\n * spawned CLI on subsequent invocations. Built-ins handle:\n *\n * - `none` — fresh session per call (current pre-AIP-45 behaviour)\n * - `pinned-session` — keep the spawned child alive, reuse across turns\n * - `transcript` — caller-supplied preamble prepended to each turn\n * - `native-resume` — pass a session id to the CLI's own `--resume` flag\n *\n * Adapter packages MAY register custom strategies via the registry —\n * for example, a Goose-specific strategy that uses MCP-side session\n * load semantics. Custom strategy ids require a follow-up AIP that\n * opens the `ContinuationStrategyId` enum (so the manifest schema can\n * validate them).\n *\n * The strategy owns the SESSION LIFECYCLE: `acquire` returns a session\n * the caller can `send()` against, and `release` decides whether the\n * session lives on (pinned-session) or closes immediately (none). The\n * runner / generation strategy MUST go through `acquire`/`release` —\n * it MUST NOT call `runtime.start()` / `session.close()` directly when\n * a strategy is active.\n */\n\nimport type {\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n ContinuationKeyScope,\n ContinuationStrategyId,\n RuntimeConfig,\n TurnContext,\n} from \"../types.js\"\n\n/**\n * Per-acquire context the strategy gets. The runner builds this from\n * the manifest, the operator config, and the current turn's identity.\n */\nexport interface AcquireContext {\n runtime: AgentCliRuntime\n /** Already-composed start options (cwd / env / signal / config /\n * turnCtx). Strategies MAY override individual fields when they\n * call `runtime.start(...)` themselves. */\n startOptions: AgentCliStartOptions\n /** Per-call config (already validated against the manifest). */\n config: RuntimeConfig\n /** Identity context for key derivation. */\n turnCtx: TurnContext\n}\n\n/**\n * Strategies can hint to the runner about how the turn played out so\n * the strategy can decide whether to keep the session alive (normal\n * end), reset its TTL but keep it (transient error), or evict it\n * (dead-process error).\n */\nexport type ReleaseOutcome =\n | { kind: \"completed\" }\n | { kind: \"cancelled\" }\n | { kind: \"error\"; reason: \"transient\" | \"fatal\"; message: string }\n\nexport interface ReleaseContext {\n session: AgentCliRuntimeSession\n outcome: ReleaseOutcome\n turnCtx: TurnContext\n}\n\n/**\n * The strategy contract. `acquire` returns a session ready for the\n * caller to `send()` against — fresh OR reused. `release` decides\n * the session's fate. Strategies MAY hold internal state (e.g.\n * the pinned-session map) keyed by `turnCtx`.\n */\nexport interface ContinuationStrategy {\n readonly id: ContinuationStrategyId\n acquire(ctx: AcquireContext): Promise<AgentCliRuntimeSession>\n release(ctx: ReleaseContext): Promise<void>\n}\n\n/**\n * Derive a stable pin key from `turnCtx` according to the manifest's\n * `pinned_session.key_scope`. Missing scope fields downgrade to a\n * less-specific key with a warning — pinning still works, it just\n * collides more.\n *\n * Returns `null` when EVERY scope field the manifest asked for is\n * missing (no key derivable; strategy falls back to per-spawn).\n */\nexport function deriveKeyFromScope(\n scope: ContinuationKeyScope[],\n turnCtx: TurnContext\n): string | null {\n const parts: string[] = []\n for (const s of scope) {\n const v = turnCtx[s]\n if (v) parts.push(`${s}=${v}`)\n }\n return parts.length === 0 ? null : parts.join(\"|\")\n}\n","/**\n * `pinned-session` strategy — keep the spawned child alive across\n * turns so the CLI's in-memory model context carries over.\n *\n * Suitable for manifests that declare `session.mode: persistent` AND\n * `context_carryover: true` (Claude Code, OpenCode, ...). Acquires\n * either reuse a live pinned session or spawn fresh and pin; releases\n * keep the session alive and reset its idle TTL. The strategy\n * auto-evicts after the manifest's `pinned_session.idle_timeout_ms`.\n *\n * The pin key is derived from `turnCtx` according to the manifest's\n * `pinned_session.key_scope` (default: `[conversation, operator]` —\n * different conversations and different operators each get their own\n * child process).\n *\n * Lost on process restart. DB-backed pin persistence is a follow-up\n * (track sessionId in `cli_sessions` table, then optionally fall back\n * to native-resume / transcript on restart).\n */\n\nimport type {\n AgentCliRuntimeSession,\n AgentCliRuntime,\n AgentCliStartOptions,\n} from \"../../types.js\"\nimport type { ContinuationStrategy } from \"../types.js\"\nimport { deriveKeyFromScope } from \"../types.js\"\n\ninterface PinnedEntry {\n session: AgentCliRuntimeSession\n /** Cached so retry-after-eviction can recreate without re-resolving\n * the runtime entry from outside. */\n runtime: AgentCliRuntime\n /** Cached so eviction-and-retry uses the same start options. */\n startOptions: AgentCliStartOptions\n idleTimer: ReturnType<typeof setTimeout> | null\n}\n\nconst DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000\n\nconst pins = new Map<string, PinnedEntry>()\n\nfunction clearIdleTimer(entry: PinnedEntry): void {\n if (entry.idleTimer) {\n clearTimeout(entry.idleTimer)\n entry.idleTimer = null\n }\n}\n\nfunction scheduleIdleEviction(\n key: string,\n entry: PinnedEntry,\n idleTimeoutMs: number\n): void {\n clearIdleTimer(entry)\n entry.idleTimer = setTimeout(() => {\n pins.delete(key)\n entry.session.close().catch(err => {\n console.warn(\n `[pinned-session] idle close failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n })\n console.log(\n `[pinned-session] ${key} idle ${idleTimeoutMs / 60_000}m → closed`\n )\n }, idleTimeoutMs)\n // Don't keep the event loop alive just for the idle close — the\n // child will be reaped on process exit anyway. Without `unref`\n // a stale pin would block graceful shutdown.\n entry.idleTimer.unref?.()\n}\n\nfunction evictPin(key: string): void {\n const entry = pins.get(key)\n if (!entry) return\n clearIdleTimer(entry)\n pins.delete(key)\n entry.session.close().catch(err => {\n console.warn(\n `[pinned-session] evict close failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n })\n}\n\nexport const pinnedSessionStrategy: ContinuationStrategy = {\n id: \"pinned-session\",\n\n async acquire(ctx) {\n const tuning = ctx.runtime.definition.continuation?.pinned_session\n const scope = tuning?.key_scope ?? [\"conversation\", \"operator\"]\n const key = deriveKeyFromScope(scope, ctx.turnCtx)\n const idleTimeoutMs = tuning?.idle_timeout_ms ?? DEFAULT_IDLE_TIMEOUT_MS\n\n if (key === null) {\n // No identity to pin against — fall back to per-spawn behaviour.\n // Warn so the host learns to populate turnCtx.\n console.warn(\n `[pinned-session] turnCtx has no fields matching key_scope ${JSON.stringify(scope)}; falling back to per-spawn (no pin).`\n )\n return ctx.runtime.start(ctx.startOptions)\n }\n\n const existing = pins.get(key)\n if (existing) {\n // Cancel the idle timer — this turn is reusing the pin.\n clearIdleTimer(existing)\n return existing.session\n }\n\n const session = await ctx.runtime.start(ctx.startOptions)\n const entry: PinnedEntry = {\n session,\n runtime: ctx.runtime,\n startOptions: ctx.startOptions,\n idleTimer: null,\n }\n pins.set(key, entry)\n scheduleIdleEviction(key, entry, idleTimeoutMs)\n return session\n },\n\n async release(ctx) {\n // Find the entry by identity — ReleaseContext doesn't carry `runtime`,\n // so we match by session reference. Acceptable since the pin map is small.\n let foundKey: string | null = null\n for (const [k, e] of pins) {\n if (e.session === ctx.session) {\n foundKey = k\n break\n }\n }\n\n if (!foundKey) {\n // Session wasn't pinned (per-spawn fallback path) — close it\n // like the `none` strategy would.\n await ctx.session.close()\n return\n }\n\n const entry = pins.get(foundKey)!\n const tuning = entry.runtime.definition.continuation?.pinned_session\n const idleTimeoutMs = tuning?.idle_timeout_ms ?? DEFAULT_IDLE_TIMEOUT_MS\n\n // Fatal errors → evict so the next turn re-spawns. Transient\n // errors and normal completion → reset the idle TTL and keep.\n // Cancelled (user aborted) is treated like normal completion —\n // the user wanted to stop this turn, not the whole session.\n if (ctx.outcome.kind === \"error\" && ctx.outcome.reason === \"fatal\") {\n evictPin(foundKey)\n return\n }\n\n scheduleIdleEviction(foundKey, entry, idleTimeoutMs)\n },\n}\n\n/**\n * Test helper — drop all pinned entries and clear timers. Not part\n * of the public API; exposed under `__test__` so tests can reset the\n * module's singleton state between runs.\n */\nexport const __test__ = {\n resetPins(): void {\n for (const [k] of pins) evictPin(k)\n },\n pinCount(): number {\n return pins.size\n },\n}\n","/**\n * `transcript` strategy — works for any CLI, including those with\n * `resumable: false` and ephemeral sessions.\n *\n * The driver doesn't know about Mastra memory or the host's\n * conversation log — that's the host's domain. The host supplies the\n * preamble at acquire-time via `startOptions.config.options` (the\n * convention is option id `__transcript`, see below) and the strategy\n * is otherwise identical to `none` — fresh session per acquire,\n * close on release.\n *\n * In practice the host does the prepending itself before calling\n * `runtime.start` (it controls the `message` text). This strategy\n * exists mostly as a NAMED policy choice in the manifest — declaring\n * it tells the host \"use the transcript-replay path for this CLI\"\n * without the host needing to inspect capabilities.\n *\n * Token-costly but stateless and survives API restarts.\n */\n\nimport type { ContinuationStrategy } from \"../types.js\"\n\nexport const transcriptStrategy: ContinuationStrategy = {\n id: \"transcript\",\n async acquire(ctx) {\n return ctx.runtime.start(ctx.startOptions)\n },\n async release(ctx) {\n await ctx.session.close()\n },\n}\n","/**\n * `native-resume` strategy — reattach to the agent's own session by id\n * (ACP `loadSession`, MCP equivalent, or argv-style `--resume`).\n *\n * Two-step lifecycle:\n * 1. **acquire**: look up a persisted sessionId for `turnCtx` via\n * `loadHook`. If found, pass it to `runtime.start` as\n * `resumeSessionId` so the protocol arm reattaches. If not, spawn\n * fresh — and after the session is up, capture the new id from\n * `session.sessionId` and persist it via `saveHook`.\n * 2. **release**: close the spawned process. The session lives in\n * the agent's storage layer (e.g. Claude Code's JSONL files);\n * cold-start resume on the next acquire reads from that store.\n *\n * Hooks are registered once per host process via\n * `configureNativeResume({ load, save })`. Without hooks the strategy\n * degrades to per-spawn behaviour with a one-line warning — it's not\n * fatal because the spawn still works, just without continuity.\n *\n * Requires the manifest to declare `capabilities.resumable: true`\n * AND the agent to advertise the matching protocol capability (e.g.\n * ACP `loadSession: true`). The schema enforces the manifest side at\n * validation; runtime capability mismatch surfaces from the protocol\n * arm as the agent's own error.\n */\n\nimport type { ContinuationStrategy, AcquireContext } from \"../types.js\"\nimport { deriveKeyFromScope } from \"../types.js\"\nimport type { TurnContext } from \"../../types.js\"\n\nexport interface NativeResumeHooks {\n /** Look up a persisted sessionId for the given identity scope. Return\n * undefined when no prior session exists — strategy spawns fresh. */\n load: (turnCtx: TurnContext) => Promise<string | undefined>\n /** Persist a freshly-established sessionId so the next cold start\n * can resume. Called once per \"fresh spawn\" acquire (not per turn).\n * Idempotent / upsert semantics expected on the host side. */\n save: (turnCtx: TurnContext, sessionId: string) => Promise<void>\n /** Optional: drop the persisted entry when a session is detected as\n * unresumable (agent rejected loadSession with a hard error). */\n forget?: (turnCtx: TurnContext) => Promise<void>\n}\n\nlet _hooks: NativeResumeHooks | null = null\n\n/**\n * Register the host's session-id load/save callbacks. Call once at\n * boot. Subsequent calls overwrite — useful in tests; in prod treat\n * the registration as exclusive.\n */\nexport function configureNativeResume(hooks: NativeResumeHooks): void {\n _hooks = hooks\n}\n\n/** Reset to no-hooks. Test helper; not part of public API. */\nexport function __resetNativeResumeForTests(): void {\n _hooks = null\n}\n\nexport const nativeResumeStrategy: ContinuationStrategy = {\n id: \"native-resume\",\n async acquire(ctx: AcquireContext) {\n if (!_hooks) {\n console.warn(\n \"[native-resume] no hooks registered (call configureNativeResume at boot); falling back to per-spawn — no continuity.\"\n )\n return ctx.runtime.start(ctx.startOptions)\n }\n // Use the same key-derivation as pinned-session so a host can\n // declare its scope ONCE in the manifest (`continuation.pinned_session.key_scope`)\n // and have both strategies key off the same identity. Native-resume\n // doesn't have its own key_scope today; it inherits.\n const scope =\n ctx.runtime.definition.continuation?.pinned_session?.key_scope ?? [\n \"conversation\",\n \"operator\",\n ]\n const key = deriveKeyFromScope(scope, ctx.turnCtx)\n if (key === null) {\n console.warn(\n `[native-resume] turnCtx has no fields matching key_scope ${JSON.stringify(scope)}; falling back to per-spawn (no resume).`\n )\n return ctx.runtime.start(ctx.startOptions)\n }\n\n const existingId = await _hooks.load(ctx.turnCtx).catch(err => {\n console.warn(\n `[native-resume] load hook failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n return undefined\n })\n\n let session\n let resumed = false\n if (existingId) {\n try {\n session = await ctx.runtime.start({\n ...ctx.startOptions,\n resumeSessionId: existingId,\n })\n resumed = true\n } catch (err) {\n // Most likely the agent rejected the id (session expired,\n // wiped, mismatched cwd). Drop the stale pin and spawn fresh\n // so the user gets continuity going forward instead of being\n // stuck on a dead reference.\n console.warn(\n `[native-resume] resume failed for ${key} (id=${existingId.slice(0, 12)}…), starting fresh:`,\n err instanceof Error ? err.message : err\n )\n if (_hooks.forget) {\n await _hooks.forget(ctx.turnCtx).catch(() => undefined)\n }\n session = await ctx.runtime.start(ctx.startOptions)\n }\n } else {\n session = await ctx.runtime.start(ctx.startOptions)\n }\n\n // Persist the established id when this is a NEW session (resume\n // path keeps the same id we already have, no need to re-save).\n // The runtime guarantees session.sessionId reflects the protocol\n // session id when the arm exposes it.\n if (!resumed && session.sessionId) {\n await _hooks.save(ctx.turnCtx, session.sessionId).catch(err => {\n console.warn(\n `[native-resume] save hook failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n })\n }\n return session\n },\n\n async release(ctx) {\n // The protocol session lives in the agent's own storage; closing\n // the spawned subprocess is fine — `loadSession` on the next\n // acquire reattaches via the persisted id.\n await ctx.session.close()\n },\n}\n","/**\n * Continuation strategy registry.\n *\n * Module-scoped singleton — all built-ins are registered at import\n * time, custom strategies (from adapter packages) register via\n * `registerContinuationStrategy`. The runner looks up by id;\n * unregistered ids throw at acquire-time so the caller fails fast\n * with a clear \"this strategy id isn't registered\" message.\n */\n\nimport type { ContinuationStrategyId } from \"../types.js\"\nimport type { ContinuationStrategy } from \"./types.js\"\nimport { noneStrategy } from \"./strategies/none.js\"\nimport { pinnedSessionStrategy } from \"./strategies/pinned-session.js\"\nimport { transcriptStrategy } from \"./strategies/transcript.js\"\nimport { nativeResumeStrategy } from \"./strategies/native-resume.js\"\n\nconst registry = new Map<ContinuationStrategyId, ContinuationStrategy>()\n\n/**\n * Register (or replace) a continuation strategy. Adapter packages\n * MAY register custom strategies on import — but they MUST first\n * land an AIP that opens the `ContinuationStrategyId` enum so the\n * manifest schema accepts the new id.\n */\nexport function registerContinuationStrategy(\n strategy: ContinuationStrategy\n): void {\n registry.set(strategy.id, strategy)\n}\n\nexport function getContinuationStrategy(\n id: ContinuationStrategyId\n): ContinuationStrategy {\n const s = registry.get(id)\n if (!s) {\n throw new Error(\n `[agent-cli] No continuation strategy registered for id '${id}'. Built-ins: ${Array.from(registry.keys()).join(\", \")}.`\n )\n }\n return s\n}\n\nexport function listContinuationStrategies(): ContinuationStrategyId[] {\n return Array.from(registry.keys())\n}\n\n// Register built-ins eagerly at module load so any importer of the\n// registry sees them. Custom strategies layer on top.\nregisterContinuationStrategy(noneStrategy)\nregisterContinuationStrategy(pinnedSessionStrategy)\nregisterContinuationStrategy(transcriptStrategy)\nregisterContinuationStrategy(nativeResumeStrategy)\n","/**\n * @agentproto/driver-agent-cli — AIP-45 AGENT-CLI.md `defineAgentCli`\n * reference impl.\n *\n * Spec: https://agentproto.sh/docs/aip-45\n *\n * Authoring paths:\n * - TS: `defineAgentCli({...})` → `AgentCliHandle`\n * - MD: `parseAgentCliManifest(src) → agentCliFromManifest({...})` → `AgentCliHandle`\n *\n * Runtime: `createAgentCliRuntime(handle)` → spawn binary, dispatch\n * turns through the protocol arm (acp / mcp / proprietary), normalise\n * events to {@link StreamEvent}.\n */\n\nexport const SPEC_NAME = \"agentcli-interactive/v1\" as const\nexport const SPEC_VERSION = \"0.1.0-alpha\" as const\n\nexport {\n defineAgentCli,\n createAgentCliRuntime,\n} from \"./define-agent-cli.js\"\n// Exposed so callers can build a sandbox-resident `AgentCliRuntime`\n// against the same protocol layer the host-spawn factory uses, by\n// passing a `ChildProcess`-shaped duck whose stdio is bridged to a\n// remote subprocess (e2b sandbox, ssh, etc.). See guilde's\n// `cli-session-spawn/sandbox-runtime.ts` for a worked example.\nexport {\n createAcpProtocolArm,\n autoAllowPermissionHandler,\n type AcpPermissionHandler,\n type AcpPermissionOutcome,\n type AcpPermissionRequestParams,\n} from \"./protocol/acp-client.js\"\nexport {\n agentCliFrontmatterSchema,\n runtimeConfigSchema,\n type AgentCliFrontmatter,\n type RuntimeConfigInput,\n} from \"./schema.js\"\nexport {\n composeSpawn,\n resolveContinuationStrategy,\n RuntimeConfigError,\n type ComposedSpawn,\n} from \"./manifest/compose.js\"\nexport {\n registerContinuationStrategy,\n getContinuationStrategy,\n listContinuationStrategies,\n} from \"./continuation/registry.js\"\nexport {\n configureNativeResume,\n type NativeResumeHooks,\n} from \"./continuation/strategies/native-resume.js\"\nexport {\n deriveKeyFromScope,\n type ContinuationStrategy,\n type AcquireContext,\n type ReleaseContext,\n type ReleaseOutcome,\n} from \"./continuation/types.js\"\nexport type {\n AgentCliDefinition,\n AgentCliHandle,\n AgentCliProtocol,\n AgentCliSessionMode,\n AgentCliClient,\n AgentCliConnectOptions,\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n AgentCliCapabilities,\n AgentCliInstallMethod,\n AgentCliVersionCheck,\n AgentCliAuth,\n AgentCliSetupStep,\n AgentCliSetupSkipIf,\n AgentCliSetupPersist,\n AgentCliSession,\n AgentCliModels,\n AgentCliMcpBlock,\n AgentCliMode,\n AgentCliOption,\n AgentCliOptionType,\n AgentCliContinuation,\n AgentCliPinnedSessionTuning,\n ContinuationStrategyId,\n ContinuationKeyScope,\n RuntimeConfig,\n TurnContext,\n StreamEvent,\n} from \"./types.js\"\n"]}
1
+ {"version":3,"sources":["../src/model.ts","../src/continuation/strategies/none.ts","../src/continuation/types.ts","../src/continuation/strategies/pinned-session.ts","../src/continuation/strategies/transcript.ts","../src/continuation/strategies/native-resume.ts","../src/continuation/registry.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;AA0CO,SAAS,gBAAgB,UAAA,EAA4B;AAC1D,EAAA,OACE,2DAA2D,UAAU,CAAA,yNAAA,CAAA;AAKzE;AAGO,SAAS,aAAA,CACd,MAAA,EACA,MAAA,EACA,UAAA,EACQ;AACR,EAAA,MAAM,IAAA,GAAO,UAAA,GAAa,CAAA,EAAG,eAAA,CAAgB,UAAU,CAAC;;AAAA,CAAA,GAAS,EAAA;AACjE,EAAA,OAAO,MAAA,GAAS,CAAA,EAAG,IAAI,CAAA,EAAG,MAAM;;AAAA,EAAO,MAA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S,IAAA,EAAM,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KACtH;AAAA,EACF;AACA,EAAA,OAAO,CAAA;AACT;AAEO,SAAS,0BAAA,GAAuD;AACrE,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,QAAA,CAAS,IAAA,EAAM,CAAA;AACnC;AAIA,4BAAA,CAA6B,YAAY,CAAA;AACzC,4BAAA,CAA6B,qBAAqB,CAAA;AAClD,4BAAA,CAA6B,kBAAkB,CAAA;AAC/C,4BAAA,CAA6B,oBAAoB,CAAA;;;ACrC1C,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * Agent CLI as a model port — turn ANY AIP-45 agent CLI runtime into a generic\n * `complete({system?, prompt}) → {result}` executor. This is the one bridge that\n * lets the SAME registry (hermes, claude-code, opencode, codex, openclaw, …)\n * back any prompt→completion seam: a report's chapter writer, a corpus\n * distiller, a Mastra tool's judgment step. The executor swaps, the prompts\n * (built by each seam's engine) don't.\n *\n * It drives the CLI over **ACP**: per `complete()` it spawns a fresh session,\n * sends one user turn, concatenates the `text-delta` stream until `turn-end`,\n * then closes. Lives here (not in a product) so seams BELOW the products —\n * `@agentproto/corpus` distill, the CLI — can consume it without importing\n * upward. The runner is injectable so assembly is unit-tested without a binary.\n */\n\nimport type { AgentCliRuntime } from \"./types.js\"\n\n/**\n * The minimal structural model port every seam consumes. Anything with this\n * `complete` shape satisfies the corpus `ReportModelPort` / `DistillPort`-backing\n * model / an AIP `ModelPort` — duck-typed, no nominal coupling.\n */\nexport interface ModelLike {\n complete(req: {\n system?: string\n prompt: string\n [k: string]: unknown\n }): Promise<{ result: string }>\n}\n\n/**\n * The \"file-reading sub-agent\" tier — opt-in across every file-IO-capable\n * executor. When `datasetDir` is set the executor is rooted there and granted\n * its own read tools, so instead of being limited to the excerpts a seam quotes\n * in the prompt it can open the primary sources directly and ground first-hand.\n */\nexport interface FileReadingOptions {\n /** Absolute path to the dataset/source root the executor may read from. */\n datasetDir?: string\n}\n\n/** The instruction prepended to a completion when {@link FileReadingOptions.datasetDir} is set. */\nexport function datasetPreamble(datasetDir: string): string {\n return (\n `You have direct read access to the source files under \\`${datasetDir}\\` ` +\n `(e.g. \\`sources/\\` raw captures, \\`entries/\\` refined notes). Use your ` +\n `file-reading tools to consult the primary sources directly when grounding ` +\n `claims — do not rely only on the excerpts quoted in this prompt.`\n )\n}\n\n/** Compose system + prompt with an optional source-access preamble (shared by every executor). */\nexport function composePrompt(\n system: string | undefined,\n prompt: string,\n datasetDir?: string\n): string {\n const head = datasetDir ? `${datasetPreamble(datasetDir)}\\n\\n` : \"\"\n return system ? `${head}${system}\\n\\n${prompt}` : `${head}${prompt}`\n}\n\n/** Provider keys an agent CLI may route through, forwarded from the parent env by default. */\nexport const PROVIDER_KEY_ENV = [\n \"OPENROUTER_API_KEY\",\n \"ANTHROPIC_API_KEY\",\n \"OPENAI_API_KEY\",\n] as const\n\nexport interface AgentCliModelOptions extends FileReadingOptions {\n /**\n * Env handed to the spawned CLI process — the provider key it routes through.\n * Defaults to forwarding {@link PROVIDER_KEY_ENV} from the parent process env.\n */\n env?: Record<string, string>\n /** Working directory for the CLI process. Defaults to `datasetDir` when set. */\n cwd?: string\n /** Timeout per completion (ms). Default 5 min. */\n timeoutMs?: number\n /**\n * Injectable runner (composed prompt → completion text). Defaults to driving\n * the runtime over ACP. Override in tests to avoid the CLI.\n */\n run?: (prompt: string) => Promise<string>\n}\n\n/** Build the env for the spawned CLI: explicit override, else forwarded provider keys. */\nexport function resolveCliEnv(\n opts: Pick<AgentCliModelOptions, \"env\">\n): Record<string, string> {\n if (opts.env) return opts.env\n const env: Record<string, string> = {}\n for (const k of PROVIDER_KEY_ENV) {\n const v = process.env[k]\n if (v) env[k] = v\n }\n return env\n}\n\n/** Drive one ACP turn on `runtime`, concatenating the text deltas. */\nasync function driveTurn(\n runtime: AgentCliRuntime,\n prompt: string,\n opts: AgentCliModelOptions\n): Promise<string> {\n const controller = new AbortController()\n const timer = setTimeout(\n () => controller.abort(),\n opts.timeoutMs ?? 5 * 60 * 1000\n )\n\n const cwd = opts.cwd ?? opts.datasetDir\n const session = await runtime.start({\n env: resolveCliEnv(opts),\n signal: controller.signal,\n ...(cwd ? { cwd } : {}),\n })\n\n try {\n let text = \"\"\n for await (const evt of session.send({ role: \"user\", content: prompt })) {\n if (evt.kind === \"text-delta\") {\n text += evt.text\n } else if (evt.kind === \"error\") {\n throw new Error(`${runtime.definition.id} model: ${evt.error.message}`)\n } else if (evt.kind === \"turn-end\") {\n if (evt.reason !== \"completed\")\n throw new Error(`${runtime.definition.id} model: turn ${evt.reason}`)\n break\n }\n }\n if (controller.signal.aborted)\n throw new Error(`${runtime.definition.id} model: timed out`)\n return text.trim()\n } finally {\n clearTimeout(timer)\n await session.close()\n }\n}\n\n/**\n * Build a {@link ModelLike} backed by an AIP-45 agent-CLI runtime. Hand it any\n * `*Runtime()` from the registry (Hermes, claude-code, opencode, …); per-CLI\n * presets are one-liners over this.\n */\nexport function makeAgentCliModel(\n runtime: AgentCliRuntime,\n opts: AgentCliModelOptions = {}\n): ModelLike {\n const run = opts.run ?? ((prompt: string) => driveTurn(runtime, prompt, opts))\n return {\n async complete({ system, prompt }) {\n return {\n result: await run(composePrompt(system, prompt, opts.datasetDir)),\n }\n },\n }\n}\n","/**\n * `none` strategy — pre-AIP-45-extension behaviour.\n *\n * Spawn a fresh session per acquire; close it on release. No state,\n * no reuse. The default when a manifest declares no `continuation`\n * block (back-compat for adapters that haven't been updated).\n */\n\nimport type { ContinuationStrategy } from \"../types.js\"\n\nexport const noneStrategy: ContinuationStrategy = {\n id: \"none\",\n async acquire(ctx) {\n return ctx.runtime.start(ctx.startOptions)\n },\n async release(ctx) {\n await ctx.session.close()\n },\n}\n","/**\n * AIP-45 ContinuationStrategy interface.\n *\n * A continuation strategy decides HOW prior conversation turns reach a\n * spawned CLI on subsequent invocations. Built-ins handle:\n *\n * - `none` — fresh session per call (current pre-AIP-45 behaviour)\n * - `pinned-session` — keep the spawned child alive, reuse across turns\n * - `transcript` — caller-supplied preamble prepended to each turn\n * - `native-resume` — pass a session id to the CLI's own `--resume` flag\n *\n * Adapter packages MAY register custom strategies via the registry —\n * for example, a Goose-specific strategy that uses MCP-side session\n * load semantics. Custom strategy ids require a follow-up AIP that\n * opens the `ContinuationStrategyId` enum (so the manifest schema can\n * validate them).\n *\n * The strategy owns the SESSION LIFECYCLE: `acquire` returns a session\n * the caller can `send()` against, and `release` decides whether the\n * session lives on (pinned-session) or closes immediately (none). The\n * runner / generation strategy MUST go through `acquire`/`release` —\n * it MUST NOT call `runtime.start()` / `session.close()` directly when\n * a strategy is active.\n */\n\nimport type {\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n ContinuationKeyScope,\n ContinuationStrategyId,\n RuntimeConfig,\n TurnContext,\n} from \"../types.js\"\n\n/**\n * Per-acquire context the strategy gets. The runner builds this from\n * the manifest, the operator config, and the current turn's identity.\n */\nexport interface AcquireContext {\n runtime: AgentCliRuntime\n /** Already-composed start options (cwd / env / signal / config /\n * turnCtx). Strategies MAY override individual fields when they\n * call `runtime.start(...)` themselves. */\n startOptions: AgentCliStartOptions\n /** Per-call config (already validated against the manifest). */\n config: RuntimeConfig\n /** Identity context for key derivation. */\n turnCtx: TurnContext\n}\n\n/**\n * Strategies can hint to the runner about how the turn played out so\n * the strategy can decide whether to keep the session alive (normal\n * end), reset its TTL but keep it (transient error), or evict it\n * (dead-process error).\n */\nexport type ReleaseOutcome =\n | { kind: \"completed\" }\n | { kind: \"cancelled\" }\n | { kind: \"error\"; reason: \"transient\" | \"fatal\"; message: string }\n\nexport interface ReleaseContext {\n session: AgentCliRuntimeSession\n outcome: ReleaseOutcome\n turnCtx: TurnContext\n}\n\n/**\n * The strategy contract. `acquire` returns a session ready for the\n * caller to `send()` against — fresh OR reused. `release` decides\n * the session's fate. Strategies MAY hold internal state (e.g.\n * the pinned-session map) keyed by `turnCtx`.\n */\nexport interface ContinuationStrategy {\n readonly id: ContinuationStrategyId\n acquire(ctx: AcquireContext): Promise<AgentCliRuntimeSession>\n release(ctx: ReleaseContext): Promise<void>\n}\n\n/**\n * Derive a stable pin key from `turnCtx` according to the manifest's\n * `pinned_session.key_scope`. Missing scope fields downgrade to a\n * less-specific key with a warning — pinning still works, it just\n * collides more.\n *\n * Returns `null` when EVERY scope field the manifest asked for is\n * missing (no key derivable; strategy falls back to per-spawn).\n */\nexport function deriveKeyFromScope(\n scope: ContinuationKeyScope[],\n turnCtx: TurnContext\n): string | null {\n const parts: string[] = []\n for (const s of scope) {\n const v = turnCtx[s]\n if (v) parts.push(`${s}=${v}`)\n }\n return parts.length === 0 ? null : parts.join(\"|\")\n}\n","/**\n * `pinned-session` strategy — keep the spawned child alive across\n * turns so the CLI's in-memory model context carries over.\n *\n * Suitable for manifests that declare `session.mode: persistent` AND\n * `context_carryover: true` (Claude Code, OpenCode, ...). Acquires\n * either reuse a live pinned session or spawn fresh and pin; releases\n * keep the session alive and reset its idle TTL. The strategy\n * auto-evicts after the manifest's `pinned_session.idle_timeout_ms`.\n *\n * The pin key is derived from `turnCtx` according to the manifest's\n * `pinned_session.key_scope` (default: `[conversation, operator]` —\n * different conversations and different operators each get their own\n * child process).\n *\n * Lost on process restart. DB-backed pin persistence is a follow-up\n * (track sessionId in `cli_sessions` table, then optionally fall back\n * to native-resume / transcript on restart).\n */\n\nimport type {\n AgentCliRuntimeSession,\n AgentCliRuntime,\n AgentCliStartOptions,\n} from \"../../types.js\"\nimport type { ContinuationStrategy } from \"../types.js\"\nimport { deriveKeyFromScope } from \"../types.js\"\n\ninterface PinnedEntry {\n session: AgentCliRuntimeSession\n /** Cached so retry-after-eviction can recreate without re-resolving\n * the runtime entry from outside. */\n runtime: AgentCliRuntime\n /** Cached so eviction-and-retry uses the same start options. */\n startOptions: AgentCliStartOptions\n idleTimer: ReturnType<typeof setTimeout> | null\n}\n\nconst DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000\n\nconst pins = new Map<string, PinnedEntry>()\n\nfunction clearIdleTimer(entry: PinnedEntry): void {\n if (entry.idleTimer) {\n clearTimeout(entry.idleTimer)\n entry.idleTimer = null\n }\n}\n\nfunction scheduleIdleEviction(\n key: string,\n entry: PinnedEntry,\n idleTimeoutMs: number\n): void {\n clearIdleTimer(entry)\n entry.idleTimer = setTimeout(() => {\n pins.delete(key)\n entry.session.close().catch(err => {\n console.warn(\n `[pinned-session] idle close failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n })\n console.log(\n `[pinned-session] ${key} idle ${idleTimeoutMs / 60_000}m → closed`\n )\n }, idleTimeoutMs)\n // Don't keep the event loop alive just for the idle close — the\n // child will be reaped on process exit anyway. Without `unref`\n // a stale pin would block graceful shutdown.\n entry.idleTimer.unref?.()\n}\n\nfunction evictPin(key: string): void {\n const entry = pins.get(key)\n if (!entry) return\n clearIdleTimer(entry)\n pins.delete(key)\n entry.session.close().catch(err => {\n console.warn(\n `[pinned-session] evict close failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n })\n}\n\nexport const pinnedSessionStrategy: ContinuationStrategy = {\n id: \"pinned-session\",\n\n async acquire(ctx) {\n const tuning = ctx.runtime.definition.continuation?.pinned_session\n const scope = tuning?.key_scope ?? [\"conversation\", \"operator\"]\n const key = deriveKeyFromScope(scope, ctx.turnCtx)\n const idleTimeoutMs = tuning?.idle_timeout_ms ?? DEFAULT_IDLE_TIMEOUT_MS\n\n if (key === null) {\n // No identity to pin against — fall back to per-spawn behaviour.\n // Warn so the host learns to populate turnCtx.\n console.warn(\n `[pinned-session] turnCtx has no fields matching key_scope ${JSON.stringify(scope)}; falling back to per-spawn (no pin).`\n )\n return ctx.runtime.start(ctx.startOptions)\n }\n\n const existing = pins.get(key)\n if (existing) {\n // Cancel the idle timer — this turn is reusing the pin.\n clearIdleTimer(existing)\n return existing.session\n }\n\n const session = await ctx.runtime.start(ctx.startOptions)\n const entry: PinnedEntry = {\n session,\n runtime: ctx.runtime,\n startOptions: ctx.startOptions,\n idleTimer: null,\n }\n pins.set(key, entry)\n scheduleIdleEviction(key, entry, idleTimeoutMs)\n return session\n },\n\n async release(ctx) {\n // Find the entry by identity — ReleaseContext doesn't carry `runtime`,\n // so we match by session reference. Acceptable since the pin map is small.\n let foundKey: string | null = null\n for (const [k, e] of pins) {\n if (e.session === ctx.session) {\n foundKey = k\n break\n }\n }\n\n if (!foundKey) {\n // Session wasn't pinned (per-spawn fallback path) — close it\n // like the `none` strategy would.\n await ctx.session.close()\n return\n }\n\n const entry = pins.get(foundKey)!\n const tuning = entry.runtime.definition.continuation?.pinned_session\n const idleTimeoutMs = tuning?.idle_timeout_ms ?? DEFAULT_IDLE_TIMEOUT_MS\n\n // Fatal errors → evict so the next turn re-spawns. Transient\n // errors and normal completion → reset the idle TTL and keep.\n // Cancelled (user aborted) is treated like normal completion —\n // the user wanted to stop this turn, not the whole session.\n if (ctx.outcome.kind === \"error\" && ctx.outcome.reason === \"fatal\") {\n evictPin(foundKey)\n return\n }\n\n scheduleIdleEviction(foundKey, entry, idleTimeoutMs)\n },\n}\n\n/**\n * Test helper — drop all pinned entries and clear timers. Not part\n * of the public API; exposed under `__test__` so tests can reset the\n * module's singleton state between runs.\n */\nexport const __test__ = {\n resetPins(): void {\n for (const [k] of pins) evictPin(k)\n },\n pinCount(): number {\n return pins.size\n },\n}\n","/**\n * `transcript` strategy — works for any CLI, including those with\n * `resumable: false` and ephemeral sessions.\n *\n * The driver doesn't know about Mastra memory or the host's\n * conversation log — that's the host's domain. The host supplies the\n * preamble at acquire-time via `startOptions.config.options` (the\n * convention is option id `__transcript`, see below) and the strategy\n * is otherwise identical to `none` — fresh session per acquire,\n * close on release.\n *\n * In practice the host does the prepending itself before calling\n * `runtime.start` (it controls the `message` text). This strategy\n * exists mostly as a NAMED policy choice in the manifest — declaring\n * it tells the host \"use the transcript-replay path for this CLI\"\n * without the host needing to inspect capabilities.\n *\n * Token-costly but stateless and survives API restarts.\n */\n\nimport type { ContinuationStrategy } from \"../types.js\"\n\nexport const transcriptStrategy: ContinuationStrategy = {\n id: \"transcript\",\n async acquire(ctx) {\n return ctx.runtime.start(ctx.startOptions)\n },\n async release(ctx) {\n await ctx.session.close()\n },\n}\n","/**\n * `native-resume` strategy — reattach to the agent's own session by id\n * (ACP `loadSession`, MCP equivalent, or argv-style `--resume`).\n *\n * Two-step lifecycle:\n * 1. **acquire**: look up a persisted sessionId for `turnCtx` via\n * `loadHook`. If found, pass it to `runtime.start` as\n * `resumeSessionId` so the protocol arm reattaches. If not, spawn\n * fresh — and after the session is up, capture the new id from\n * `session.sessionId` and persist it via `saveHook`.\n * 2. **release**: close the spawned process. The session lives in\n * the agent's storage layer (e.g. Claude Code's JSONL files);\n * cold-start resume on the next acquire reads from that store.\n *\n * Hooks are registered once per host process via\n * `configureNativeResume({ load, save })`. Without hooks the strategy\n * degrades to per-spawn behaviour with a one-line warning — it's not\n * fatal because the spawn still works, just without continuity.\n *\n * Requires the manifest to declare `capabilities.resumable: true`\n * AND the agent to advertise the matching protocol capability (e.g.\n * ACP `loadSession: true`). The schema enforces the manifest side at\n * validation; runtime capability mismatch surfaces from the protocol\n * arm as the agent's own error.\n */\n\nimport type { ContinuationStrategy, AcquireContext } from \"../types.js\"\nimport { deriveKeyFromScope } from \"../types.js\"\nimport type { TurnContext } from \"../../types.js\"\n\nexport interface NativeResumeHooks {\n /** Look up a persisted sessionId for the given identity scope. Return\n * undefined when no prior session exists — strategy spawns fresh. */\n load: (turnCtx: TurnContext) => Promise<string | undefined>\n /** Persist a freshly-established sessionId so the next cold start\n * can resume. Called once per \"fresh spawn\" acquire (not per turn).\n * Idempotent / upsert semantics expected on the host side. */\n save: (turnCtx: TurnContext, sessionId: string) => Promise<void>\n /** Optional: drop the persisted entry when a session is detected as\n * unresumable (agent rejected loadSession with a hard error). */\n forget?: (turnCtx: TurnContext) => Promise<void>\n}\n\nlet _hooks: NativeResumeHooks | null = null\n\n/**\n * Register the host's session-id load/save callbacks. Call once at\n * boot. Subsequent calls overwrite — useful in tests; in prod treat\n * the registration as exclusive.\n */\nexport function configureNativeResume(hooks: NativeResumeHooks): void {\n _hooks = hooks\n}\n\n/** Reset to no-hooks. Test helper; not part of public API. */\nexport function __resetNativeResumeForTests(): void {\n _hooks = null\n}\n\nexport const nativeResumeStrategy: ContinuationStrategy = {\n id: \"native-resume\",\n async acquire(ctx: AcquireContext) {\n if (!_hooks) {\n console.warn(\n \"[native-resume] no hooks registered (call configureNativeResume at boot); falling back to per-spawn — no continuity.\"\n )\n return ctx.runtime.start(ctx.startOptions)\n }\n // Use the same key-derivation as pinned-session so a host can\n // declare its scope ONCE in the manifest (`continuation.pinned_session.key_scope`)\n // and have both strategies key off the same identity. Native-resume\n // doesn't have its own key_scope today; it inherits.\n const scope =\n ctx.runtime.definition.continuation?.pinned_session?.key_scope ?? [\n \"conversation\",\n \"operator\",\n ]\n const key = deriveKeyFromScope(scope, ctx.turnCtx)\n if (key === null) {\n console.warn(\n `[native-resume] turnCtx has no fields matching key_scope ${JSON.stringify(scope)}; falling back to per-spawn (no resume).`\n )\n return ctx.runtime.start(ctx.startOptions)\n }\n\n const existingId = await _hooks.load(ctx.turnCtx).catch(err => {\n console.warn(\n `[native-resume] load hook failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n return undefined\n })\n\n let session\n let resumed = false\n if (existingId) {\n try {\n session = await ctx.runtime.start({\n ...ctx.startOptions,\n resumeSessionId: existingId,\n })\n resumed = true\n } catch (err) {\n // Most likely the agent rejected the id (session expired,\n // wiped, mismatched cwd). Drop the stale pin and spawn fresh\n // so the user gets continuity going forward instead of being\n // stuck on a dead reference.\n console.warn(\n `[native-resume] resume failed for ${key} (id=${existingId.slice(0, 12)}…), starting fresh:`,\n err instanceof Error ? err.message : err\n )\n if (_hooks.forget) {\n await _hooks.forget(ctx.turnCtx).catch(() => undefined)\n }\n session = await ctx.runtime.start(ctx.startOptions)\n }\n } else {\n session = await ctx.runtime.start(ctx.startOptions)\n }\n\n // Persist the established id when this is a NEW session (resume\n // path keeps the same id we already have, no need to re-save).\n // The runtime guarantees session.sessionId reflects the protocol\n // session id when the arm exposes it.\n if (!resumed && session.sessionId) {\n await _hooks.save(ctx.turnCtx, session.sessionId).catch(err => {\n console.warn(\n `[native-resume] save hook failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n })\n }\n return session\n },\n\n async release(ctx) {\n // The protocol session lives in the agent's own storage; closing\n // the spawned subprocess is fine — `loadSession` on the next\n // acquire reattaches via the persisted id.\n await ctx.session.close()\n },\n}\n","/**\n * Continuation strategy registry.\n *\n * Module-scoped singleton — all built-ins are registered at import\n * time, custom strategies (from adapter packages) register via\n * `registerContinuationStrategy`. The runner looks up by id;\n * unregistered ids throw at acquire-time so the caller fails fast\n * with a clear \"this strategy id isn't registered\" message.\n */\n\nimport type { ContinuationStrategyId } from \"../types.js\"\nimport type { ContinuationStrategy } from \"./types.js\"\nimport { noneStrategy } from \"./strategies/none.js\"\nimport { pinnedSessionStrategy } from \"./strategies/pinned-session.js\"\nimport { transcriptStrategy } from \"./strategies/transcript.js\"\nimport { nativeResumeStrategy } from \"./strategies/native-resume.js\"\n\nconst registry = new Map<ContinuationStrategyId, ContinuationStrategy>()\n\n/**\n * Register (or replace) a continuation strategy. Adapter packages\n * MAY register custom strategies on import — but they MUST first\n * land an AIP that opens the `ContinuationStrategyId` enum so the\n * manifest schema accepts the new id.\n */\nexport function registerContinuationStrategy(\n strategy: ContinuationStrategy\n): void {\n registry.set(strategy.id, strategy)\n}\n\nexport function getContinuationStrategy(\n id: ContinuationStrategyId\n): ContinuationStrategy {\n const s = registry.get(id)\n if (!s) {\n throw new Error(\n `[agent-cli] No continuation strategy registered for id '${id}'. Built-ins: ${Array.from(registry.keys()).join(\", \")}.`\n )\n }\n return s\n}\n\nexport function listContinuationStrategies(): ContinuationStrategyId[] {\n return Array.from(registry.keys())\n}\n\n// Register built-ins eagerly at module load so any importer of the\n// registry sees them. Custom strategies layer on top.\nregisterContinuationStrategy(noneStrategy)\nregisterContinuationStrategy(pinnedSessionStrategy)\nregisterContinuationStrategy(transcriptStrategy)\nregisterContinuationStrategy(nativeResumeStrategy)\n","/**\n * @agentproto/driver-agent-cli — AIP-45 AGENT-CLI.md `defineAgentCli`\n * reference impl.\n *\n * Spec: https://agentproto.sh/docs/aip-45\n *\n * Authoring paths:\n * - TS: `defineAgentCli({...})` → `AgentCliHandle`\n * - MD: `parseAgentCliManifest(src) → agentCliFromManifest({...})` → `AgentCliHandle`\n *\n * Runtime: `createAgentCliRuntime(handle)` → spawn binary, dispatch\n * turns through the protocol arm (acp / mcp / proprietary), normalise\n * events to {@link StreamEvent}.\n */\n\nexport const SPEC_NAME = \"agentcli-interactive/v1\" as const\nexport const SPEC_VERSION = \"0.1.0-alpha\" as const\n\nexport {\n defineAgentCli,\n createAgentCliRuntime,\n} from \"./define-agent-cli.js\"\n// Agent CLI → generic model port: one executor backing every prompt→completion\n// seam (report writer, corpus distiller, Mastra judgment step) over any AIP-45 CLI.\nexport {\n makeAgentCliModel,\n resolveCliEnv,\n composePrompt,\n datasetPreamble,\n PROVIDER_KEY_ENV,\n} from \"./model.js\"\nexport type {\n ModelLike,\n FileReadingOptions,\n AgentCliModelOptions,\n} from \"./model.js\"\n// Exposed so callers can build a sandbox-resident `AgentCliRuntime`\n// against the same protocol layer the host-spawn factory uses, by\n// passing a `ChildProcess`-shaped duck whose stdio is bridged to a\n// remote subprocess (e2b sandbox, ssh, etc.). See guilde's\n// `cli-session-spawn/sandbox-runtime.ts` for a worked example.\nexport {\n createAcpProtocolArm,\n autoAllowPermissionHandler,\n type AcpPermissionHandler,\n type AcpPermissionOutcome,\n type AcpPermissionRequestParams,\n} from \"./protocol/acp-client.js\"\nexport {\n createPrintSession,\n type PrintArmOptions,\n} from \"./protocol/print-arm.js\"\nexport {\n agentCliFrontmatterSchema,\n runtimeConfigSchema,\n type AgentCliFrontmatter,\n type RuntimeConfigInput,\n} from \"./schema.js\"\nexport {\n composeSpawn,\n resolveContinuationStrategy,\n RuntimeConfigError,\n type ComposedSpawn,\n} from \"./manifest/compose.js\"\nexport {\n registerContinuationStrategy,\n getContinuationStrategy,\n listContinuationStrategies,\n} from \"./continuation/registry.js\"\nexport {\n configureNativeResume,\n type NativeResumeHooks,\n} from \"./continuation/strategies/native-resume.js\"\nexport {\n deriveKeyFromScope,\n type ContinuationStrategy,\n type AcquireContext,\n type ReleaseContext,\n type ReleaseOutcome,\n} from \"./continuation/types.js\"\nexport type {\n AgentCliDefinition,\n AgentCliHandle,\n AgentCliProtocol,\n AgentCliSessionMode,\n AgentCliClient,\n AgentCliConnectOptions,\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n AgentCliCapabilities,\n AgentCliInstallMethod,\n AgentCliVersionCheck,\n AgentCliAuth,\n AgentCliSetupStep,\n AgentCliSetupSkipIf,\n AgentCliSetupPersist,\n AgentCliSession,\n AgentCliModels,\n AgentCliMcpBlock,\n AgentCliMode,\n AgentCliOption,\n AgentCliOptionType,\n AgentCliContinuation,\n AgentCliPinnedSessionTuning,\n ContinuationStrategyId,\n ContinuationKeyScope,\n RuntimeConfig,\n TurnContext,\n StreamEvent,\n} from \"./types.js\"\n"]}
@@ -1,5 +1,5 @@
1
- import { k as AgentCliFrontmatter, A as AgentCliHandle } from '../schema-Cq4w3654.js';
2
- export { B as agentCliFrontmatterSchema } from '../schema-Cq4w3654.js';
1
+ import { k as AgentCliFrontmatter, A as AgentCliHandle } from '../schema-CCSzIDMJ.js';
2
+ export { B as agentCliFrontmatterSchema } from '../schema-CCSzIDMJ.js';
3
3
  import '@agentproto/acp';
4
4
  import 'zod';
5
5
 
@@ -1,5 +1,5 @@
1
- import { agentCliFrontmatterSchema, defineAgentCli } from '../chunk-VIYTAHJJ.mjs';
2
- export { agentCliFrontmatterSchema } from '../chunk-VIYTAHJJ.mjs';
1
+ import { agentCliFrontmatterSchema, defineAgentCli } from '../chunk-YQHVLX6O.mjs';
2
+ export { agentCliFrontmatterSchema } from '../chunk-YQHVLX6O.mjs';
3
3
  import matter from 'gray-matter';
4
4
 
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { StreamEvent } from '@agentproto/acp';
1
+ import { AcpMcpServer, StreamEvent } from '@agentproto/acp';
2
2
  import { z } from 'zod';
3
3
 
4
4
  /**
@@ -10,7 +10,7 @@ import { z } from 'zod';
10
10
  * proprietary adapter arms.
11
11
  */
12
12
 
13
- type AgentCliProtocol = "acp" | "mcp" | "proprietary";
13
+ type AgentCliProtocol = "acp" | "mcp" | "proprietary" | "print";
14
14
  type AgentCliSessionMode = "ephemeral" | "persistent" | "resumable";
15
15
  interface AgentCliInstallMethod {
16
16
  method: "brew" | "apt" | "dnf" | "pacman" | "choco" | "scoop" | "npm" | "pip" | "cargo" | "go" | "curl" | "download" | "vendored";
@@ -140,6 +140,18 @@ interface AgentCliModels {
140
140
  default?: string;
141
141
  allowed?: string[];
142
142
  env?: Record<string, string>;
143
+ /**
144
+ * How the host selects a model at session start:
145
+ * - "config" (default) — apply via ACP `session/set_config_option`
146
+ * with `configId:"model"` right after `newSession`. Works for ACP
147
+ * wrappers that expose model as a session config (e.g. claude-code).
148
+ * - "command" — `set_config_option` is a no-op / silently rejected on
149
+ * this agent (e.g. hermes), so instead send a `/model <id>` control
150
+ * turn after `newSession` and drain it. The agent's reply is checked
151
+ * for a "switched" acknowledgement; a failure is warned, not fatal.
152
+ * Omit → "config".
153
+ */
154
+ apply?: "config" | "command";
143
155
  }
144
156
  interface AgentCliCapabilities {
145
157
  streaming?: boolean;
@@ -311,6 +323,33 @@ interface AgentCliConnectOptions {
311
323
  * because per-protocol semantics aren't visible at this layer.
312
324
  */
313
325
  resumeSessionId?: string;
326
+ /**
327
+ * MCP servers to mount into the agent's session at spawn time. For
328
+ * the ACP arm these are forwarded verbatim into
329
+ * `session/new.mcpServers` (and `session/load.mcpServers` on resume),
330
+ * giving the child agent a scoped toolset the host chose — e.g. the
331
+ * daemon's own orchestration gateway so a spawned agent can itself
332
+ * spawn + supervise sub-agents. Arms that don't model MCP mounting
333
+ * ignore this field.
334
+ */
335
+ mcpServers?: AcpMcpServer[];
336
+ /**
337
+ * Model to activate at session start. For the ACP arm this is
338
+ * applied via `session/set_config_option` with `configId:"model"`
339
+ * immediately after `newSession` — the ACP wrapper (claude-agent-acp)
340
+ * does not forward CLI flags to the underlying claude process so
341
+ * bin_args_template alone cannot change the model.
342
+ */
343
+ model?: string;
344
+ /**
345
+ * Effort level to apply at session start. Effort is model-dependent:
346
+ * the same label ("high", "xhigh", …) maps to different underlying
347
+ * computation budgets per model, and the default differs by model
348
+ * (e.g. Sonnet 4.6 / Opus 4.8 default to "high"; Opus 4.7 to
349
+ * "xhigh"). Omit to keep the model's own default. Applied via
350
+ * `session/set_config_option` with `configId:"effort"` on ACP arms.
351
+ */
352
+ effort?: string;
314
353
  }
315
354
  /**
316
355
  * Per-turn dispatch shape. Implemented by every protocol arm
@@ -376,6 +415,13 @@ interface AgentCliStartOptions {
376
415
  * Forwarded verbatim to `protocolArm.connect({ resumeSessionId })`.
377
416
  */
378
417
  resumeSessionId?: string;
418
+ /**
419
+ * MCP servers to mount into the spawned agent's session. Threaded
420
+ * through to `protocolArm.connect({ mcpServers })` → the ACP arm's
421
+ * `session/new.mcpServers`. Lets the host inject a scoped toolset
422
+ * (e.g. the daemon's orchestration gateway) at spawn time.
423
+ */
424
+ mcpServers?: AcpMcpServer[];
379
425
  }
380
426
  /**
381
427
  * Operator-side runtime configuration. Mirrors the `runtime.config`
@@ -602,6 +648,7 @@ declare const agentCliFrontmatterSchema: z.ZodObject<{
602
648
  acp: "acp";
603
649
  mcp: "mcp";
604
650
  proprietary: "proprietary";
651
+ print: "print";
605
652
  }>;
606
653
  acp: z.ZodOptional<z.ZodString>;
607
654
  mcp: z.ZodOptional<z.ZodObject<{
@@ -629,6 +676,10 @@ declare const agentCliFrontmatterSchema: z.ZodObject<{
629
676
  default: z.ZodOptional<z.ZodString>;
630
677
  allowed: z.ZodOptional<z.ZodArray<z.ZodString>>;
631
678
  env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
679
+ apply: z.ZodOptional<z.ZodEnum<{
680
+ config: "config";
681
+ command: "command";
682
+ }>>;
632
683
  }, z.core.$strict>>;
633
684
  capabilities: z.ZodOptional<z.ZodObject<{
634
685
  streaming: z.ZodOptional<z.ZodBoolean>;
@@ -723,4 +774,4 @@ declare const runtimeConfigSchema: z.ZodObject<{
723
774
  }, z.core.$strict>;
724
775
  type RuntimeConfigInput = z.infer<typeof runtimeConfigSchema>;
725
776
 
726
- export { type AgentCliHandle as A, agentCliFrontmatterSchema as B, type ContinuationStrategyId as C, runtimeConfigSchema as D, type RuntimeConfig as R, type TurnContext as T, type AgentCliRuntime as a, type AgentCliDefinition as b, type AgentCliClient as c, type AgentCliStartOptions as d, type AgentCliRuntimeSession as e, type ContinuationKeyScope as f, type AgentCliAuth as g, type AgentCliCapabilities as h, type AgentCliConnectOptions as i, type AgentCliContinuation as j, type AgentCliFrontmatter as k, type AgentCliInstallMethod as l, type AgentCliMcpBlock as m, type AgentCliMode as n, type AgentCliModels as o, type AgentCliOption as p, type AgentCliOptionType as q, type AgentCliPinnedSessionTuning as r, type AgentCliProtocol as s, type AgentCliSession as t, type AgentCliSessionMode as u, type AgentCliSetupPersist as v, type AgentCliSetupSkipIf as w, type AgentCliSetupStep as x, type AgentCliVersionCheck as y, type RuntimeConfigInput as z };
777
+ export { type AgentCliHandle as A, agentCliFrontmatterSchema as B, type ContinuationStrategyId as C, runtimeConfigSchema as D, type RuntimeConfig as R, type TurnContext as T, type AgentCliRuntime as a, type AgentCliDefinition as b, type AgentCliClient as c, type AgentCliRuntimeSession as d, type AgentCliStartOptions as e, type ContinuationKeyScope as f, type AgentCliAuth as g, type AgentCliCapabilities as h, type AgentCliConnectOptions as i, type AgentCliContinuation as j, type AgentCliFrontmatter as k, type AgentCliInstallMethod as l, type AgentCliMcpBlock as m, type AgentCliMode as n, type AgentCliModels as o, type AgentCliOption as p, type AgentCliOptionType as q, type AgentCliPinnedSessionTuning as r, type AgentCliProtocol as s, type AgentCliSession as t, type AgentCliSessionMode as u, type AgentCliSetupPersist as v, type AgentCliSetupSkipIf as w, type AgentCliSetupStep as x, type AgentCliVersionCheck as y, type RuntimeConfigInput as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/driver-agent-cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "@agentproto/driver-agent-cli — AIP-45 AGENT-CLI.md reference implementation. Multi-protocol runner that loads an AGENT-CLI.md manifest, spawns the binary, and dispatches turns through an ACP / MCP / proprietary arm. ACP arm delegates to @agentproto/acp; emits the canonical StreamEvent taxonomy regardless of underlying protocol.",
5
5
  "keywords": [
6
6
  "agentproto",
@@ -53,8 +53,8 @@
53
53
  "dependencies": {
54
54
  "gray-matter": "^4.0.3",
55
55
  "zod": "^4.4.3",
56
- "@agentproto/define-doctype": "0.1.0",
57
- "@agentproto/acp": "0.1.0"
56
+ "@agentproto/acp": "0.2.0",
57
+ "@agentproto/define-doctype": "0.1.0"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/node": "^25.6.2",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/schema.ts","../src/protocol/acp-client.ts","../src/manifest/compose.ts","../src/define-agent-cli.ts"],"names":[],"mappings":";;;;;;;;;;;;AAiBA,IAAM,UAAA,GAAa,2BAAA;AACnB,IAAM,cAAA,GAAiB,iCAAA;AACvB,IAAM,WAAA,GAAc,2BAAA;AACpB,IAAM,oBAAA,GAAuB,2BAAA;AAC7B,IAAM,eAAA,GAAkB,0BAAA;AACxB,IAAM,WAAA,GAAc,qBAAA;AACpB,IAAM,eAAA,GAAkB,2BAAA;AACxB,IAAM,iBAAA,GAAoB,2BAAA;AAE1B,IAAM,yBAAA,GAA4B;AAAA,EAChC,MAAA;AAAA,EACA,gBAAA;AAAA,EACA,YAAA;AAAA,EACA;AACF,CAAA;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\n * sibling of AIP-29 (CLI.md, tool CLIs) covering interactive\n * agent-as-process binaries. The `protocol` discriminator (acp / mcp\n * / proprietary) selects the wire arm; cross-field rules ensure the\n * matching arm-specific block is present.\n *\n * Both authoring paths (`define-agent-cli.ts` and\n * `manifest/index.ts`) validate against this schema, so every\n * field-level constraint runs in both paths from a single source of\n * truth.\n */\n\nimport { z } from \"zod\"\n\nconst ID_PATTERN = /^[a-z0-9][a-z0-9-]{1,63}$/\nconst SEMVER_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/\nconst TAG_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/\nconst SEMVER_RANGE_PATTERN = /^[><=^~ \\d.\\-+\\w*xX|, ]+$/\nconst ADAPTER_PATTERN = /^@?[a-z0-9][a-z0-9-./]*$/\nconst BIN_PATTERN = /^[A-Za-z0-9._\\-/]+$/\nconst MODE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/\nconst OPTION_ID_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/\n\nconst CONTINUATION_STRATEGY_IDS = [\n \"none\",\n \"pinned-session\",\n \"transcript\",\n \"native-resume\",\n] as const\n\nconst CONTINUATION_KEY_SCOPES = [\n \"conversation\",\n \"operator\",\n \"user\",\n \"guild\",\n \"workspace\",\n] as const\n\n// AIP-29 install methods, mirrored locally to avoid a runtime cross-package import.\n// Schema-level $ref to AIP-29 is preserved on the JSON Schema side\n// (resources/aip-45/draft/AGENT-CLI.schema.json); this zod copy is the\n// TS-side mirror used by `defineAgentCli`. When AIP-29 grows new\n// install methods, both sides update together via scaffold-aip.\n\nconst installMethodSchema = z.discriminatedUnion(\"method\", [\n z.object({ method: z.literal(\"brew\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"apt\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"dnf\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"pacman\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"choco\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"scoop\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"npm\"), package: z.string(), global: z.boolean().optional(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"pip\"), package: z.string(), user: z.boolean().optional(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"cargo\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({ method: z.literal(\"go\"), package: z.string(), experimental: z.boolean().optional() }).strict(),\n z.object({\n method: z.literal(\"curl\"),\n url: z.string().url(),\n verify_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),\n experimental: z.boolean().optional(),\n }).strict(),\n z.object({\n method: z.literal(\"download\"),\n url: z.string().url(),\n extract_bin: z.string(),\n verify_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),\n experimental: z.boolean().optional(),\n }).strict(),\n z.object({ method: z.literal(\"vendored\"), path: z.string(), experimental: z.boolean().optional() }).strict(),\n])\n\nconst versionCheckSchema = z.object({\n cmd: z.string(),\n parse: z.string().describe(\"ECMAScript regex with at least one capture group.\"),\n range: z.string().regex(SEMVER_RANGE_PATTERN).describe(\"npm-style semver range.\"),\n timeout_ms: z.number().int().min(100).default(5000),\n}).strict()\n\nconst SETUP_STEP_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/\nconst SECRET_SLUG_PATTERN = /^([a-z][a-z0-9-]*[a-z0-9]\\/)?[a-z][a-z0-9-]*[a-z0-9]$/\n\n// `skip_if`: re-runnable health check that, when matching, skips the\n// enclosing setup step. Lets `agentproto setup <slug>` re-runs be\n// idempotent without external completion-ledger state.\nconst skipIfSchema = z\n .object({\n cmd: z.string(),\n exit_code: z.number().int().default(0),\n timeout_ms: z.number().int().min(100).default(5_000),\n })\n .strict()\n\n// `persist`: where the captured value lands so the runner can reuse\n// it on every spawn. Exactly one of env / secret_slug / cmd, enforced\n// via discriminated union.\nconst persistEnvSchema = z\n .object({ env: z.string().regex(/^[A-Z][A-Z0-9_]*$/) })\n .strict()\nconst persistSecretSchema = z\n .object({ secret_slug: z.string().regex(SECRET_SLUG_PATTERN).min(2).max(80) })\n .strict()\nconst persistCmdSchema = z.object({ cmd: z.string() }).strict()\nconst setupPersistSchema = z.union([\n persistEnvSchema,\n persistSecretSchema,\n persistCmdSchema,\n])\n\n// AIP-29 § Setup. Mirrors `resources/aip-29/draft/CLI.schema.json#/$defs/setupStep`.\n// The runner runs steps in declared order, persists completion per\n// (bundle.id, workspace.id, user.id), and surfaces `setup_required`\n// to headless callers when steps remain pending.\nconst setupStepSchema = z.discriminatedUnion(\"kind\", [\n z\n .object({\n id: z.string().regex(SETUP_STEP_ID_PATTERN),\n kind: z.literal(\"cmd\"),\n cmd: z.string(),\n description: z.string().max(2000).optional(),\n skip_if: skipIfSchema.optional(),\n timeout_ms: z.number().int().min(100).default(60_000),\n interactive: z.boolean().default(false),\n persist: setupPersistSchema.optional(),\n })\n .strict(),\n z\n .object({\n id: z.string().regex(SETUP_STEP_ID_PATTERN),\n kind: z.literal(\"prompt\"),\n prompt: z.string().min(1),\n description: z.string().max(2000).optional(),\n type: z.enum([\"text\", \"select\", \"boolean\", \"secret\"]).default(\"text\"),\n default: z.string().optional(),\n options: z\n .union([\n z.array(z.string().min(1)).min(1),\n z\n .object({\n cmd: z.string(),\n timeout_ms: z.number().int().min(100).default(30_000),\n })\n .strict(),\n ])\n .optional(),\n skip_if: skipIfSchema.optional(),\n persist: setupPersistSchema.optional(),\n })\n .strict(),\n z\n .object({\n id: z.string().regex(SETUP_STEP_ID_PATTERN),\n kind: z.literal(\"oauth\"),\n secret_slug: z.string().regex(SECRET_SLUG_PATTERN).min(2).max(80),\n description: z.string().max(2000).optional(),\n skip_if: skipIfSchema.optional(),\n })\n .strict(),\n z\n .object({\n id: z.string().regex(SETUP_STEP_ID_PATTERN),\n kind: z.literal(\"external\"),\n url: z.string().url(),\n description: z.string().max(2000).optional(),\n callback: z\n .object({\n param: z.string().min(1).optional(),\n timeout_ms: z.number().int().min(1_000).default(600_000),\n })\n .strict()\n .optional(),\n skip_if: skipIfSchema.optional(),\n persist: setupPersistSchema.optional(),\n })\n .strict(),\n])\n\nconst authSchema = z.object({\n ref: z.string().optional(),\n state: z.object({\n paths: z.array(z.string()).optional(),\n env: z.array(z.string()).optional(),\n }).strict().optional(),\n login: z.object({\n cmd: z.string(),\n interactive: z.boolean().optional(),\n requires_callback_url: z.boolean().optional(),\n }).strict().optional(),\n refresh: z.object({\n cmd: z.string(),\n interval_s: z.number().int().positive().optional(),\n }).strict().optional(),\n expiry: z.object({\n parse: z.string().optional(),\n grace_s: z.number().int().nonnegative().optional(),\n }).strict().optional(),\n}).strict()\n\nconst sessionSchema = z.object({\n mode: z.enum([\"ephemeral\", \"persistent\", \"resumable\"]).default(\"ephemeral\"),\n idle_timeout_ms: z.number().int().min(1000).default(600_000),\n max_turns: z.number().int().positive().optional(),\n context_carryover: z.boolean().default(true),\n}).strict()\n\nconst modelsSchema = z.object({\n default: z.string().optional(),\n allowed: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict()\n\nconst capabilitiesSchema = z.object({\n streaming: z.boolean().optional(),\n tool_calls: z.boolean().optional(),\n sub_agents: z.boolean().optional(),\n file_io: z.boolean().optional(),\n multimodal: z.boolean().optional(),\n resumable: z.boolean().optional(),\n bidirectional: z.boolean().optional(),\n /**\n * Adapter can ingest a filesystem path that the host UI just placed\n * on disk (host-side drag-drop into a terminal pastes the path\n * here). Implies the adapter has a Read-file tool wired so the\n * dropped path actually does something. Hosts gate drag-drop UI on\n * this flag — defaults to false (conservative).\n */\n file_attach: z.boolean().optional(),\n}).strict()\n\nconst modeSchema = z.object({\n id: z.string().regex(MODE_ID_PATTERN),\n description: z.string().optional(),\n bin_args_append: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict()\n\nconst optionSchema = z.object({\n id: z.string().regex(OPTION_ID_PATTERN),\n type: z.enum([\"boolean\", \"integer\", \"string\", \"enum\"]),\n description: z.string().optional(),\n enum: z.array(z.string()).min(1).optional(),\n default: z.union([z.boolean(), z.number(), z.string()]).optional(),\n min: z.number().int().optional(),\n max: z.number().int().optional(),\n bin_args_template: z.array(z.string()).optional(),\n bin_args_append_when_true: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict().refine(\n // type === \"enum\" REQUIRES an `enum` array. The JSON Schema enforces\n // this via `if/then`; the zod side mirrors with a refine so both\n // validation paths reject the same shapes.\n o => o.type !== \"enum\" || (Array.isArray(o.enum) && o.enum.length > 0),\n { message: \"option.type === 'enum' requires a non-empty `enum` array\" }\n)\n\nconst continuationStrategyIdSchema = z.enum(CONTINUATION_STRATEGY_IDS)\n\nconst continuationSchema = z.object({\n default: continuationStrategyIdSchema,\n supported: z.array(continuationStrategyIdSchema).min(1),\n pinned_session: z.object({\n idle_timeout_ms: z.number().int().min(1000).default(1_800_000),\n key_scope: z\n .array(z.enum(CONTINUATION_KEY_SCOPES))\n .min(1)\n .default([\"conversation\", \"operator\"]),\n }).strict().optional(),\n}).strict().refine(\n // The chosen `default` must appear in `supported` — otherwise the\n // host has no valid strategy to fall back to.\n c => c.supported.includes(c.default),\n {\n message: \"continuation.default must be a member of continuation.supported\",\n }\n)\n\nconst mcpBlockSchema = z.object({\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n transport: z.enum([\"stdio\", \"http\", \"sse\"]),\n url: z.string().url().optional(),\n}).strict()\n\nexport const agentCliFrontmatterSchema = z\n .object({\n name: z.string().min(1).max(80),\n id: z.string().regex(ID_PATTERN),\n description: z.string().min(1).max(2000),\n version: z.string().regex(SEMVER_PATTERN),\n bin: z.string().regex(BIN_PATTERN),\n bin_args: z.array(z.string()).optional(),\n install: z.array(installMethodSchema).min(1),\n version_check: versionCheckSchema,\n setup: z.array(setupStepSchema).optional(),\n auth: authSchema.optional(),\n sandbox: z.union([z.string(), z.record(z.string(), z.unknown())]),\n runner: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),\n protocol: z.enum([\"acp\", \"mcp\", \"proprietary\"]),\n acp: z.string().optional(),\n mcp: mcpBlockSchema.optional(),\n adapter: z.string().regex(ADAPTER_PATTERN).optional(),\n session: sessionSchema.optional(),\n models: modelsSchema.optional(),\n capabilities: capabilitiesSchema.optional(),\n modes: z.array(modeSchema).optional(),\n options: z.array(optionSchema).optional(),\n continuation: continuationSchema.optional(),\n requires: z.object({\n os: z.array(z.enum([\"darwin\", \"linux\", \"windows\"])).optional(),\n arch: z.array(z.enum([\"x64\", \"arm64\", \"x86\", \"arm\"])).optional(),\n min_disk_mb: z.number().int().nonnegative().optional(),\n min_memory_mb: z.number().int().nonnegative().optional(),\n }).strict().optional(),\n examples: z.array(z.object({\n goal: z.string(),\n prompt: z.string(),\n note: z.string().optional(),\n }).strict()).optional(),\n tags: z.array(z.string().regex(TAG_PATTERN)).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .strict()\n .superRefine((m, ctx) => {\n // Unique mode ids — duplicates would silently shadow.\n if (m.modes) {\n const seen = new Set<string>()\n for (const mode of m.modes) {\n if (seen.has(mode.id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"modes\"],\n message: `Duplicate mode id '${mode.id}' — mode ids must be unique within a manifest.`,\n })\n }\n seen.add(mode.id)\n }\n }\n // Unique setup step ids — duplicates would silently shadow each\n // other in the host's completion ledger, leading to one step\n // never re-prompting and another always re-prompting.\n if (m.setup) {\n const seen = new Set<string>()\n for (const step of m.setup) {\n if (seen.has(step.id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"setup\"],\n message: `Duplicate setup step id '${step.id}' — step ids must be unique within a manifest.`,\n })\n }\n seen.add(step.id)\n }\n }\n // Unique option ids — same reasoning as modes.\n if (m.options) {\n const seen = new Set<string>()\n for (const opt of m.options) {\n if (seen.has(opt.id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"options\"],\n message: `Duplicate option id '${opt.id}' — option ids must be unique within a manifest.`,\n })\n }\n seen.add(opt.id)\n }\n }\n // continuation.default === \"native-resume\" requires capabilities.resumable: true.\n // Mirrors the JSON Schema's allOf rule so both validation paths\n // reject the same shape.\n if (\n m.continuation?.default === \"native-resume\" &&\n !m.capabilities?.resumable\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"continuation\", \"default\"],\n message:\n \"continuation.default === 'native-resume' requires capabilities.resumable: true.\",\n })\n }\n })\n .describe(\n \"Validates the YAML frontmatter portion of an AIP-45 AGENT-CLI.md manifest.\",\n )\n\nexport type AgentCliFrontmatter = z.infer<typeof agentCliFrontmatterSchema>\n\n// Re-export the per-call config schema for hosts that want to validate\n// `OPERATOR.runtime.config` against a manifest at load time. Validation\n// against the manifest's modes/options/continuation lives in\n// `manifest/compose.ts` (the spawn-arg composer) — this schema covers\n// only the SHAPE checks (types, enum values).\nexport const runtimeConfigSchema = z.object({\n mode: z.string().optional(),\n options: z.record(z.string(), z.union([z.boolean(), z.number(), z.string()]))\n .optional(),\n continuation: continuationStrategyIdSchema.optional(),\n}).strict()\n\nexport type RuntimeConfigInput = z.infer<typeof runtimeConfigSchema>\n","/**\n * AIP-45 protocol arm: `protocol: \"acp\"`.\n *\n * Wraps a subprocess's stdio in an `@agentproto/acp` client and\n * exposes the `AgentCliClient` shape the runner consumes. Each\n * `send()` call delegates to a single AcpClientSession.prompt() and\n * forwards the resulting StreamEvent stream.\n */\n\nimport type { ChildProcess } from \"node:child_process\"\nimport { Readable, Writable } from \"node:stream\"\nimport {\n createAcpClient,\n type AcpClient,\n type AcpClientSession,\n} from \"@agentproto/acp/client\"\nimport type {\n AgentCliClient,\n AgentCliConnectOptions,\n StreamEvent,\n} from \"../types.js\"\n\n/**\n * Outcome the host returns to the agent on a permission request.\n *\n * Mirrors the upstream ACP `RequestPermissionResponse` shape EXACTLY —\n * note the doubly-nested `outcome` field: the outer is the response\n * envelope, the inner is the discriminator (string literal, not a\n * `{ type: ... }` object). Get this wrong and the agent silently\n * interprets the response as a refusal (\"User refused permission to\n * run tool\"), so we type it strictly here.\n *\n * { outcome: { outcome: \"selected\", optionId: \"...\" } }\n * { outcome: { outcome: \"cancelled\" } }\n */\nexport type AcpPermissionOutcome =\n | { outcome: { outcome: \"selected\"; optionId: string } }\n | { outcome: { outcome: \"cancelled\" } }\n\nexport interface AcpPermissionRequestParams {\n sessionId?: string\n toolCall?: {\n toolCallId?: string\n title?: string\n kind?: string\n rawInput?: unknown\n }\n options?: Array<{ optionId: string; name?: string; kind?: string }>\n}\n\nexport type AcpPermissionHandler = (\n params: AcpPermissionRequestParams\n) => Promise<AcpPermissionOutcome> | AcpPermissionOutcome\n\n/**\n * Default handler: pick the first option whose `kind` starts with\n * `allow_` (Claude Code offers `allow_once` and `allow_always`).\n * Falls back to the first option if none match — keeps the agent\n * unblocked rather than throwing on an unfamiliar option set.\n *\n * Mirrors the trust model of in-process Mastra agents: the user\n * approved the operator binding once; subsequent tool calls don't\n * re-prompt by default. Hosts that want explicit per-call gating\n * pass their own `onPermissionRequest`.\n */\nexport const autoAllowPermissionHandler: AcpPermissionHandler = ({\n options,\n}) => {\n if (!options || options.length === 0) {\n // No options offered — return cancelled so the agent gets a\n // deterministic answer instead of hanging on a dropped request.\n return { outcome: { outcome: \"cancelled\" } }\n }\n const allow =\n options.find(o => typeof o.kind === \"string\" && o.kind.startsWith(\"allow_\")) ??\n options[0]\n return { outcome: { outcome: \"selected\", optionId: allow!.optionId } }\n}\n\nexport interface AcpProtocolOptions {\n child: ChildProcess\n cwd: string\n clientInfo?: { name: string; title?: string; version?: string }\n /** Called when the agent asks for permission to run a tool (Write,\n * Bash, ...). Defaults to `autoAllowPermissionHandler`. Pass a\n * custom handler to plumb requests through a UI / governance\n * policy. Throwing or returning a rejected promise bubbles to the\n * agent as an internal error. */\n onPermissionRequest?: AcpPermissionHandler\n}\n\nexport function createAcpProtocolArm(\n options: AcpProtocolOptions,\n): AgentCliClient {\n const { child, cwd } = options\n\n if (!child.stdin || !child.stdout) {\n throw new Error(\n \"AcpProtocolArm: subprocess must be spawned with piped stdin + stdout\",\n )\n }\n\n const output = Writable.toWeb(child.stdin) as WritableStream<Uint8Array>\n const input = Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>\n\n let client: AcpClient | null = null\n let session: AcpClientSession | null = null\n const pendingByTurn = new Map<string, AsyncIterable<StreamEvent>>()\n\n return {\n get sessionId(): string | undefined {\n return session?.sessionId\n },\n async connect(opts: AgentCliConnectOptions) {\n const permissionHandler =\n options.onPermissionRequest ?? autoAllowPermissionHandler\n client = await createAcpClient({\n output,\n input,\n clientInfo: options.clientInfo,\n capabilities: {\n fs: { readTextFile: true, writeTextFile: true },\n },\n // Wire the permission handler so the agent's `session/request_permission`\n // callbacks get a real answer instead of bubbling up as\n // \"AcpClient.requestPermission: no handler configured\" → which\n // surfaces in the chat as an opaque \"Internal error\" when the\n // agent tries to Write / Bash anything gated.\n handlers: {\n requestPermission: async (params: unknown) =>\n permissionHandler(params as AcpPermissionRequestParams),\n } as never,\n })\n // When the host hands us a `resumeSessionId`, reattach to the\n // agent's existing session via `loadSession` so the conversation\n // (model context, tool history, working files) carries over a\n // cold start. We trust the host to only send ids it persisted\n // from a prior turn; if the agent's `loadSession: true` capability\n // wasn't advertised the SDK call surfaces the per-protocol error.\n //\n // No silent fallback to `newSession` on resume failure — that\n // would create a new session quietly and lose continuity, which\n // is the bug we're trying to prevent. Let the error propagate.\n if (opts.resumeSessionId) {\n session = await client.loadSession({\n sessionId: opts.resumeSessionId,\n cwd,\n })\n } else {\n session = await client.newSession({ cwd })\n }\n },\n async send(turnId, message) {\n if (!session) throw new Error(\"AcpProtocolArm.send: not connected\")\n // ACP's `prompt` field is `ContentBlock[]` — multiple blocks\n // together form the user's turn (text + image + resource_link\n // + ...). Callers MAY pass either:\n // - a single block (`{type:\"text\",text:\"...\"}`) — wrapped\n // into a one-element array for the wire\n // - an array of blocks — forwarded verbatim, supporting\n // multimodal turns without callers re-shaping per-arm\n const messages = Array.isArray(message) ? message : [message]\n const stream = session.prompt({ messages })\n pendingByTurn.set(turnId, stream)\n },\n async *events(): AsyncIterable<StreamEvent> {\n const last = Array.from(pendingByTurn.values()).at(-1)\n if (!last) return\n for await (const evt of last) yield evt\n },\n async cancel(_turnId) {\n if (!session) return\n await session.cancel()\n },\n async close() {\n if (session) await session.close()\n if (client) await client.close()\n },\n }\n}\n","/**\n * Spawn-argument composer.\n *\n * Pure function: given an `AgentCliHandle` and a per-call\n * `RuntimeConfig`, produces the final `binArgs + env` to pass to the\n * runtime's `start()`. Validates the config against the manifest's\n * declared `modes` / `options` / `continuation.supported`; unknown ids\n * throw `RuntimeConfigError` (the host should NOT spawn — the user\n * configured something the manifest doesn't accept).\n *\n * Composition order (matches AIP-45 spec):\n * 1. Manifest's default `bin_args` (from `handle.bin_args`).\n * 2. Mode patch (`bin_args_append`, `env`) when `config.mode` set.\n * 3. Option patches in DECLARATION order (`bin_args_template` /\n * `bin_args_append_when_true` / `env`) for each option present\n * in `config.options`.\n *\n * Mode is applied before options because modes are coarse profile\n * switches (claude-code's `--permission-mode`) — options refine them.\n * Within options, declaration order is honoured so adapter authors\n * can express \"this flag must come after that one\" without the host\n * needing to know the rule.\n */\n\nimport type {\n AgentCliHandle,\n AgentCliOption,\n RuntimeConfig,\n} from \"../types.js\"\n\n/**\n * Thrown when `RuntimeConfig` references manifest entries that don't\n * exist or violates a declared constraint (type / enum / bounds). The\n * `code` field lets callers map to friendly UI messages without\n * inspecting the message string.\n */\nexport class RuntimeConfigError extends Error {\n readonly code:\n | \"unknown_mode\"\n | \"unknown_option\"\n | \"option_type_mismatch\"\n | \"option_enum_violation\"\n | \"option_bounds_violation\"\n | \"unsupported_continuation\"\n readonly path: string\n constructor(\n code: RuntimeConfigError[\"code\"],\n path: string,\n message: string\n ) {\n super(`[${code} at ${path}] ${message}`)\n this.code = code\n this.path = path\n this.name = \"RuntimeConfigError\"\n }\n}\n\n/**\n * Resolved spawn args + env. The runtime's `start()` impl merges\n * `env` into the host process env / sandbox env before exec.\n */\nexport interface ComposedSpawn {\n binArgs: string[]\n env: Record<string, string>\n}\n\n/**\n * Compose the final spawn args from a manifest + per-call config.\n * Pure — no I/O, no sandbox access, no global state. Safe to call\n * repeatedly with the same input.\n *\n * `config` may be undefined or an empty object — both fall back to\n * the manifest's defaults verbatim (manifest `bin_args`, no mode\n * patch, no option patches). Continuation is not applied here — the\n * `ContinuationStrategy` registry handles that — but we DO validate\n * `config.continuation` against `manifest.continuation.supported` so\n * a misconfigured operator fails fast at compose time, not at the\n * point the strategy tries to acquire a session.\n */\nexport function composeSpawn(\n handle: AgentCliHandle,\n config?: RuntimeConfig\n): ComposedSpawn {\n const binArgs: string[] = [...(handle.bin_args ?? [])]\n const env: Record<string, string> = {}\n\n if (!config) return { binArgs, env }\n\n // ── Mode patch ──────────────────────────────────────────────────\n if (config.mode !== undefined) {\n const mode = (handle.modes ?? []).find(m => m.id === config.mode)\n if (!mode) {\n const known = (handle.modes ?? []).map(m => m.id).join(\", \") || \"(none)\"\n throw new RuntimeConfigError(\n \"unknown_mode\",\n \"config.mode\",\n `Mode '${config.mode}' is not declared by manifest '${handle.id}'. Known modes: ${known}`\n )\n }\n if (mode.bin_args_append) binArgs.push(...mode.bin_args_append)\n if (mode.env) Object.assign(env, mode.env)\n }\n\n // ── Option patches (declaration order) ──────────────────────────\n if (config.options && Object.keys(config.options).length > 0) {\n const declared = handle.options ?? []\n const declaredById = new Map(declared.map(o => [o.id, o]))\n // Reject unknown ids first so the operator sees ALL the typos\n // (not just the one we hit first when iterating declared).\n for (const id of Object.keys(config.options)) {\n if (!declaredById.has(id)) {\n const known = declared.map(o => o.id).join(\", \") || \"(none)\"\n throw new RuntimeConfigError(\n \"unknown_option\",\n `config.options.${id}`,\n `Option '${id}' is not declared by manifest '${handle.id}'. Known options: ${known}`\n )\n }\n }\n // Then apply patches in declaration order so adapter-author intent\n // wins over operator-config key order.\n for (const option of declared) {\n if (!(option.id in config.options)) continue\n const value = config.options[option.id] as boolean | number | string\n validateOptionValue(option, value)\n const patch = renderOptionPatch(option, value)\n binArgs.push(...patch.binArgs)\n Object.assign(env, patch.env)\n }\n }\n\n // ── Continuation validation (no patch — strategy registry owns) ─\n if (config.continuation !== undefined && handle.continuation) {\n if (!handle.continuation.supported.includes(config.continuation)) {\n throw new RuntimeConfigError(\n \"unsupported_continuation\",\n \"config.continuation\",\n `Continuation strategy '${config.continuation}' is not in manifest '${handle.id}'.continuation.supported (${handle.continuation.supported.join(\", \")}).`\n )\n }\n }\n\n return { binArgs, env }\n}\n\n/**\n * Resolve the continuation strategy id to use for this call. Operator\n * config wins; manifest default is the fallback; \"none\" if neither\n * declares anything (preserves pre-AIP-45-extension behaviour).\n */\nexport function resolveContinuationStrategy(\n handle: AgentCliHandle,\n config?: RuntimeConfig\n): import(\"../types.js\").ContinuationStrategyId {\n if (config?.continuation) return config.continuation\n return handle.continuation?.default ?? \"none\"\n}\n\nfunction validateOptionValue(\n option: AgentCliOption,\n value: boolean | number | string\n): void {\n const path = `config.options.${option.id}`\n switch (option.type) {\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected boolean, got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n return\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected integer, got ${typeof value === \"number\" ? \"non-integer number\" : typeof value} (${JSON.stringify(value)}).`\n )\n }\n if (option.min !== undefined && value < option.min) {\n throw new RuntimeConfigError(\n \"option_bounds_violation\",\n path,\n `Value ${value} is below the declared minimum ${option.min}.`\n )\n }\n if (option.max !== undefined && value > option.max) {\n throw new RuntimeConfigError(\n \"option_bounds_violation\",\n path,\n `Value ${value} is above the declared maximum ${option.max}.`\n )\n }\n return\n case \"string\":\n if (typeof value !== \"string\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected string, got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n return\n case \"enum\":\n if (typeof value !== \"string\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected string (enum value), got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n if (!(option.enum ?? []).includes(value)) {\n throw new RuntimeConfigError(\n \"option_enum_violation\",\n path,\n `Value '${value}' is not in the declared enum (${(option.enum ?? []).join(\", \")}).`\n )\n }\n return\n }\n}\n\nfunction renderOptionPatch(\n option: AgentCliOption,\n value: boolean | number | string\n): { binArgs: string[]; env: Record<string, string> } {\n const stringValue = String(value)\n\n // boolean type: only emit the bare flag when value === true and the\n // option declared `bin_args_append_when_true`. Honor `env` too —\n // adapter authors might want to surface the bool via env.\n if (option.type === \"boolean\") {\n if (value !== true) return { binArgs: [], env: {} }\n return {\n binArgs: option.bin_args_append_when_true\n ? [...option.bin_args_append_when_true]\n : [],\n env: option.env ? interpolateEnv(option.env, stringValue) : {},\n }\n }\n\n // value-bearing types — apply `bin_args_template` (with `{value}`\n // interpolation) and merge `env`.\n return {\n binArgs: option.bin_args_template\n ? option.bin_args_template.map(token =>\n token.replace(/\\{value\\}/g, stringValue)\n )\n : [],\n env: option.env ? interpolateEnv(option.env, stringValue) : {},\n }\n}\n\nfunction interpolateEnv(\n env: Record<string, string>,\n value: string\n): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(env)) {\n out[k] = v.replace(/\\{value\\}/g, value)\n }\n return out\n}\n","import { spawn, type ChildProcess } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport { createDoctype } from \"@agentproto/define-doctype\"\nimport { agentCliFrontmatterSchema } from \"./schema.js\"\nimport { createAcpProtocolArm } from \"./protocol/acp-client.js\"\nimport { composeSpawn } from \"./manifest/compose.js\"\nimport type {\n AgentCliClient,\n AgentCliDefinition,\n AgentCliHandle,\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n StreamEvent,\n} from \"./types.js\"\n\nexport const defineAgentCli = createDoctype<AgentCliDefinition, AgentCliHandle>(\n {\n aip: 45,\n name: \"agent-cli\",\n readIdentity: (def) => def.id,\n validate(def) {\n const result = agentCliFrontmatterSchema.safeParse(def)\n if (!result.success) {\n throw new Error(\n `defineAgentCli (AIP-45): ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n\n const data = result.data\n\n if (data.protocol === \"acp\" && !data.acp) {\n throw new Error(\n \"defineAgentCli (AIP-45): `acp` ref is required when protocol=acp\",\n )\n }\n if (data.protocol === \"mcp\" && !data.mcp) {\n throw new Error(\n \"defineAgentCli (AIP-45): `mcp` block is required when protocol=mcp\",\n )\n }\n if (data.protocol === \"proprietary\" && !data.adapter) {\n throw new Error(\n \"defineAgentCli (AIP-45): `adapter` package is required when protocol=proprietary\",\n )\n }\n\n if (\n data.session?.mode === \"resumable\" &&\n data.capabilities?.resumable !== true\n ) {\n throw new Error(\n \"defineAgentCli (AIP-45): session.mode=resumable requires capabilities.resumable: true\",\n )\n }\n },\n build(def) {\n return { ...def } as AgentCliHandle\n },\n },\n)\n\nexport function createAgentCliRuntime(\n definition: AgentCliHandle,\n): AgentCliRuntime {\n return {\n definition,\n async start(opts?: AgentCliStartOptions): Promise<AgentCliRuntimeSession> {\n const cwd = opts?.cwd ?? process.cwd()\n // Compose final argv + env from the manifest + per-call config.\n // Mode patches and option patches land BEFORE the host-provided\n // env so an operator-set option can be observed by the CLI even\n // when the manifest also touches the same env key (operator\n // intent wins). Validation runs here too — a misconfigured\n // operator throws RuntimeConfigError before we exec anything.\n const composed = composeSpawn(definition, opts?.config)\n const env: Record<string, string> = {\n ...filterStringEnv(process.env),\n ...composed.env,\n ...(opts?.env ?? {}),\n }\n\n const child = spawn(definition.bin, composed.binArgs, {\n cwd,\n env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n signal: opts?.signal,\n })\n\n // Drain child.stderr — without this the kernel pipe buffer\n // (~64 KB on macOS / Linux) eventually fills up and blocks the\n // child mid-write, hanging the entire ACP exchange. Buffer the\n // last few KB so a downstream error event can attach the tail\n // for debugging — adapters like claude-agent-acp print useful\n // context here (\"not authenticated\", \"model gated\") that the\n // JSON-RPC reply would otherwise reduce to \"Invalid params\".\n const stderrBuf: string[] = []\n const STDERR_KEEP_LINES = 80\n child.stderr?.setEncoding(\"utf8\")\n child.stderr?.on(\"data\", (chunk: string) => {\n for (const line of chunk.split(/\\r?\\n/)) {\n if (!line) continue\n stderrBuf.push(line)\n if (stderrBuf.length > STDERR_KEEP_LINES) stderrBuf.shift()\n }\n })\n\n const arm = buildProtocolArm(definition, child, cwd)\n arm._stderrTail = () => stderrBuf.join(\"\\n\")\n\n const abortController = new AbortController()\n if (opts?.signal) {\n opts.signal.addEventListener(\"abort\", () => abortController.abort(), {\n once: true,\n })\n }\n await arm.connect({\n cwd,\n env,\n abortSignal: abortController.signal,\n ...(opts?.resumeSessionId\n ? { resumeSessionId: opts.resumeSessionId }\n : {}),\n })\n\n // Prefer the protocol-layer session id (ACP, etc.) so the host\n // can persist it for a future native-resume. Fall back to a\n // random UUID for protocols that don't model sessions — keeps\n // the field always-populated for downstream loggers.\n const sessionId = arm.sessionId ?? randomUUID()\n\n return {\n sessionId,\n send(message): AsyncIterable<StreamEvent> {\n const turnId = randomUUID()\n return promptTurn(arm, turnId, message)\n },\n async cancel() {\n abortController.abort()\n },\n async close() {\n await arm.close()\n if (!child.killed) child.kill(\"SIGTERM\")\n },\n }\n },\n }\n}\n\nasync function* promptTurn(\n arm: AgentCliClient,\n turnId: string,\n message: unknown,\n): AsyncIterable<StreamEvent> {\n await arm.send(turnId, message)\n // Re-attach the recent stderr tail to error events. The ACP layer\n // surfaces a terse `{message: \"Invalid params\"}`; the child's\n // stderr almost always has a more useful line (\"npx claude-agent-acp:\n // not authenticated, run `claude login`\"). Hosts read `error.data`\n // when present, falling back to `message` for older payloads.\n const stderrTail = arm._stderrTail\n for await (const evt of arm.events()) {\n if (evt.kind === \"error\" && typeof stderrTail === \"function\") {\n const tail = stderrTail()\n if (tail) {\n const existing = (evt.error.data ?? {}) as Record<string, unknown>\n evt.error.data = { ...existing, stderr: tail }\n }\n }\n yield evt\n }\n}\n\nfunction buildProtocolArm(\n def: AgentCliHandle,\n child: ChildProcess,\n cwd: string,\n): AgentCliClient {\n switch (def.protocol) {\n case \"acp\":\n return createAcpProtocolArm({\n child,\n cwd,\n clientInfo: { name: def.id, version: def.version },\n })\n case \"mcp\":\n throw new Error(\"createAgentCliRuntime: mcp protocol arm not yet implemented\")\n case \"proprietary\":\n throw new Error(\n \"createAgentCliRuntime: proprietary protocol arm not yet implemented\",\n )\n }\n}\n\nfunction filterStringEnv(env: NodeJS.ProcessEnv): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(env)) {\n if (typeof v === \"string\") out[k] = v\n }\n return out\n}\n"]}