UNPKG

@agentproto/driver-agent-cli

Version:

@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; e

1 lines • 301 kB
{"version":3,"sources":["../src/schema.ts","../src/protocol/acp-client.ts","../src/mcp-servers.ts","../src/process-tree.ts","../src/win32-spawn.ts","../src/command-sandbox-wrap.ts","../src/protocol/print-arm.ts","../src/protocol/proprietary.ts","../src/legacy-modes.ts","../src/manifest/compose.ts","../src/host-context.ts","../src/session-controls.ts","../src/npx-fast-path.ts","../src/define-agent-cli.ts"],"names":["resolve","join","basename","existsSync","dirname","readFileSync","homedir","mkdirSync","writeFileSync","spawn","randomUUID"],"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;AAEA,IAAM,uBAAA,GAA0B;AAAA,EAC9B,cAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA;AAQA,IAAM,mBAAA,GAAsB,CAAA,CAAE,kBAAA,CAAmB,QAAA,EAAU;AAAA,EACzD,CAAA,CAAE,OAAO,EAAE,MAAA,EAAQ,EAAE,OAAA,CAAQ,MAAM,GAAG,OAAA,EAAS,CAAA,CAAE,QAAO,EAAG,YAAA,EAAc,EAAE,OAAA,EAAQ,CAAE,UAAS,EAAG,EAAE,M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EA,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;AASA,SAAS,wBAAA,CACP,UAAA,EACA,SAAA,EACA,MAAA,EACO;AACP,EAAA,MAAM,KAAA,GAAQ,UAAA,CAAW,MAAA,EAAQ,OAAA,GAAU,CAAC,CAAA;AAC5C,EAAA,MAAM,WACH,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,OAAO,EAAA,KAC5C,wCAAA;AACF,EAAA,OAAO,IAAI,KAAA;AAAA,IACT,CAAA,EAAG,WAAW,GAAG,CAAA,qEAAA,EACX,SAAS,CAAA,mBAAA,EAAsB,MAAM,sMAGL,OAAO,CAAA,sCAAA;AAAA,GAC/C;AACF","file":"chunk-Y3FGLQ4R.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\n// Subscription (OAuth/bearer) billing declaration — see\n// AgentCliAuthSubscription. Presence = \"supports subscription mode\". Two\n// shapes:\n//   - bearer-injection (claude-code): `setEnv` is the var the runtime SETS to\n//     the resolved OAuth bearer.\n//   - external / file-based (codex, gemini): `external: true` and NO `setEnv` —\n//     the CLI reads its own local-login file (`~/.codex/auth.json`, …), so the\n//     runtime injects NOTHING and only scrubs the conflicting api-key vars.\n// `conflictEnv` are sibling credential vars scrubbed in every mode (except when\n// set); `unsetEnvAdd` is native-mode-only gateway hygiene.\nconst authSubscriptionEntrySchema = z.object({\n  setEnv: z.string().min(1).optional(),\n  external: z.boolean().optional(),\n  conflictEnv: z.array(z.string()).optional(),\n  unsetEnvAdd: z.array(z.string()).optional(),\n  // Provider scope for a multi-provider adapter's bearer surface (pi's\n  // ANTHROPIC_OAUTH_TOKEN is anthropic-only) — see AgentCliAuthSubscription.\n  provider: z.string().min(1).optional(),\n}).strict().superRefine((v, ctx) => {\n  if (v.external) {\n    if (v.setEnv !== undefined) {\n      ctx.addIssue({\n        code: z.ZodIssueCode.custom,\n        message:\n          \"authSubscription.external: true must NOT declare setEnv — an external \" +\n          \"(file-based) subscription injects no bearer; the CLI reads its own login file.\",\n        path: [\"setEnv\"],\n      })\n    }\n  } else if (v.setEnv === undefined) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      message:\n        \"authSubscription requires setEnv unless external: true (the bearer must be \" +\n        \"injected into some env var).\",\n      path: [\"setEnv\"],\n    })\n  }\n})\n\n// `authSubscription` accepts either ONE surface (today's shape, unscoped or\n// provider-scoped) or an ARRAY of surfaces — a multi-provider adapter that\n// ships more than one native OAuth login (mastracode: Claude AND ChatGPT)\n// declares one entry per provider. Two entries claiming the SAME provider\n// scope (or two unscoped entries) are ambiguous — the runtime's\n// `subscriptionSurfaceFor` has no tiebreak rule, so this is rejected at\n// validation time rather than resolved arbitrarily at spawn time.\nconst authSubscriptionSchema = z\n  .union([authSubscriptionEntrySchema, z.array(authSubscriptionEntrySchema).min(1)])\n  .superRefine((v, ctx) => {\n    if (!Array.isArray(v)) return\n    const seen = new Set<string>()\n    for (const entry of v) {\n      const key = entry.provider ?? \"\\0unscoped\"\n      if (seen.has(key)) {\n        ctx.addIssue({\n          code: z.ZodIssueCode.custom,\n          message: entry.provider\n            ? `authSubscription: duplicate provider scope \"${entry.provider}\" — two ` +\n              `entries claim the same provider, which is ambiguous at spawn time.`\n            : \"authSubscription: more than one unscoped entry (no `provider`) — \" +\n              \"ambiguous which one applies at spawn time.\",\n        })\n      }\n      seen.add(key)\n    }\n  })\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  // No default: undefined disables the per-turn watchdog entirely. Only\n  // adapters known to sometimes drop the final `prompt` response (e.g.\n  // hermes) should declare this — applying it broadly would risk\n  // false-positiving on another adapter's legitimately long turns.\n  turn_idle_timeout_ms: z.number().int().min(1000).optional(),\n  max_turns: z.number().int().positive().optional(),\n  context_carryover: z.boolean().default(true),\n}).strict()\n\n// A `models.allowed` entry: a bare id (provider unstated, adapter default)\n// or a { id, provider?, mode? } binding stating who serves it and which\n// adapter mode reaches it. See AgentCliModelEntry (types.ts).\nconst modelEntrySchema = z.union([\n  z.string(),\n  z.object({\n    id: z.string(),\n    provider: z.string().optional(),\n    mode: z.string().optional(),\n  }).strict(),\n])\n\nconst modelsSchema = z.object({\n  default: z.string().optional(),\n  allowed: z.array(modelEntrySchema).optional(),\n  // Model-id patterns the adapter must never route to (case-insensitive,\n  // trailing `*` = prefix match). Enforced at compose time — see\n  // AgentCliModels.deny. Reserves premium providers for dedicated adapters.\n  deny: 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  // \"arg\" (a CLI argument composed into bin_args at spawn).\n  apply: z.enum([\"config\", \"command\", \"arg\"]).optional(),\n  // Argv template for apply:\"arg\" — {model} interpolates the requested\n  // model id. See AgentCliModels.bin_args_template.\n  bin_args_template: z.array(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 has a verified native CLI resume into a real terminal/TUI\n   * session (e.g. `claude --resume <id>` or `hermes --resume <id> --tui`).\n   * When true, the host MAY restart this adapter via its native resume argv\n   * as a PTY session. Distinct from ACP-level `resumable`.\n   */\n  nativeTerminalResume: 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\nexport const modeSchema = z.object({\n  id: z.string().regex(MODE_ID_PATTERN),\n  description: z.string().optional(),\n  // Which orthogonal session-config axis this mode expresses (SPEC-tracked in\n  // @agentproto/runtime's session-config.ts). Narrowed to only \"context\" (SPEC\n  // §3.4a): route is derived from the model catalog (@route), not a manifest\n  // mode, and posture comes from the harness's own ACP mode registry\n  // (SessionModeState.availableModes) — neither is a `modes[]` entry anymore.\n  // The legacy \"posture\"/\"route\" classification still exists, but only inside\n  // the daemon's back-compat `decomposeMode` shim, not this manifest surface.\n  kind: z.enum([\"context\"]).optional(),\n  bin_args_prepend: z.array(z.string()).optional(),\n  bin_args_append: z.array(z.string()).optional(),\n  env: z.record(z.string(), z.string()).optional(),\n  // Env keys to DELETE from the spawn env (auth hygiene for gateway\n  // modes — see AgentCliMode.env_unset). Applied at the runtime merge\n  // point, not as a static set.\n  env_unset: z.array(z.string()).optional(),\n  // Honest support status surfaced to clients. Absent ⇒ \"active\".\n  status: z.enum([\"active\", \"noop\", \"planned\"]).optional(),\n  status_note: z.string().optional(),\n  // How the host activates this mode: \"bin_args\" (default, argv/env\n  // composed at spawn) | \"config\" (no CLI surface — forwarded to the ACP\n  // arm's connect({mode}) and applied via session/set_config_option\n  // configId:\"mode\", e.g. opencode).\n  apply: z.enum([\"bin_args\", \"config\"]).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_prepend: z.array(z.string()).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  // Env keys to DELETE from the spawn env when this option is active\n  // (auth hygiene for value-bearing gateway options — see\n  // AgentCliOption.env_unset). Symmetric with modeSchema.env_unset.\n  env_unset: z.array(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\n// AIP-45 gateway-preset declaration (see AgentCliPresetDeclaration). A\n// backend an Anthropic/OpenAI-compatible adapter can front, declared in\n// the manifest so the catalog can surface adapter-contributed presets\n// alongside the built-in registry. `scrubEnv` is optional here — an\n// adapter that scrubs in code may omit it.\nconst presetSchema = z.object({\n  id: z.string().min(1),\n  label: z.string().min(1),\n  description: z.string().optional(),\n  schemaFlavor: z.enum([\"anthropic\", \"openai\"]),\n  baseUrl: z.string().min(1),\n  keyEnv: z.string().min(1),\n  scrubEnv: z.array(z.string()).optional(),\n  defaultModel: z.string().optional(),\n  homepage: z.string().optional(),\n}).strict()\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\nconst printConfigSchema = z.object({\n  prompt_flag: z.string().optional(),\n  output_format: z.array(z.string()).optional(),\n  pre_prompt: z.array(z.string()).optional(),\n  resume: z.object({\n    flag: z.string(),\n    kind: z.enum([\"value\", \"boolean\"]),\n  }).strict().optional(),\n  event_schema: z.enum([\"claude-stream-json\", \"mastra-jsonl\", \"antigravity-stream-json\", \"jcode-ndjson\"]).optional(),\n}).strict().optional()\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    // Always-on spawn env (merged before mode/option env, which can\n    // override). See AgentCliDefinition.env — used by generic ACP agents.\n    env: z.record(z.string(), 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    // Billing-auth resolver inputs (DECISION 3). `provider` is a CatalogProvider\n    // id (validated against the catalog by the runtime resolver, not here, to\n    // keep this generic doctype decoupled from @agentproto/model-catalog).\n    provider: z.string().min(1).optional(),\n    authSubscription: authSubscriptionSchema.optional(),\n    // How this adapter receives a GATEWAY-routed bearer credential — see the\n    // doc on AgentCliDefinition.gatewayAuth. Distinct from a gateway preset's\n    // `keyEnv` (the providers-store lookup key) and from\n    // authSubscription.setEnv (this adapter's own native bearer).\n    gatewayAuth: z.object({\n      setEnv: z.string().min(1),\n    }).strict().optional(),\n    // Auth-derivation axis (DECISION 3): true when the adapter's api-key auth\n    // is derived from the requested model rather than a fixed `provider`\n    // (e.g. `pi`, `opencode`, `mastracode`). When set, the runtime resolver\n    // allows `\"api-key\"` mode on the model-derived direct endpoint and\n    // includes it in eligibility manifests for by-model routers. DISTINCT\n    // from `routeSelection` (the UI-facing route-choice axis).\n    modelDerivedApiKey: z.boolean().optional(),\n    // UI-facing route-choice axis (AIP-45 launch-menu drill-down, WP1).\n    // Absent ⇒ \"free\" (route is an independent choice); \"derived-from-model\"\n    // means the endpoint falls out of the model id's vendor prefix. DISTINCT\n    // from `modelDerivedApiKey` (the auth-derivation axis) — see the field\n    // doc on AgentCliDefinition.routeSelection.\n    routeSelection: z.enum([\"free\", \"derived-from-model\"]).optional(),\n    authEnforce: z.enum([\"always\", \"when-configured\"]).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    print: printConfigSchema,\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    // AIP-45 gateway presets this adapter can drive (merged into the\n    // provider-preset catalog; built-in wins on id collision).\n    presets: z.array(presetSchema).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  type AcpPermissionResolution,\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  // `title`/`kind` allow `null` (not just `undefined`) so the upstream ACP\n  // `RequestPermissionRequest` — whose `toolCall` is a `ToolCallUpdate` with\n  // `title: string | null` / `kind: ToolKind | null` — is structurally\n  // assignable to this shape. That lets the arm's handler take the SDK type\n  // directly, with no `as` cast at the `createAcpClient` call site.\n  toolCall?: {\n    toolCallId?: string\n    title?: string | null\n    kind?: string | null\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 *\n * NOT safe to use as-is for a `mode: \"plan\"` session — see\n * `planModePermissionHandler` below.\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\n/**\n * `toolCall.kind` Claude Code's ACP wrapper attaches to the \"ready to\n * code?\" permission request it raises when the agent wants to leave\n * plan mode (its internal `ExitPlanMode` tool, mapped by\n * `@agentclientprotocol/claude-agent-acp`'s `toolInfoFromToolUse`).\n * This is the ONLY reliable discriminator for that request — its\n * `options[].kind` values (`allow_always` / `allow_once` / `reject_once`)\n * are the same vocabulary an ordinary tool-permission request uses, so\n * `option.kind` alone can't tell the two apart.\n */\nconst PLAN_MODE_EXIT_TOOL_CALL_KIND = \"switch_mode\"\n\n/**\n * Permission handler for a session spawned with `mode: \"plan\"`.\n *\n * `autoAllowPermissionHandler` picks the first `allow_*` option, but for\n * the plan-mode-exit request that option is always an escalation away\n * from plan (`auto`, `acceptEdits`, or `bypassPermissions` depending on\n * what the wrapper offers) — auto-approving it silently defeats the\n * mode the caller asked for (see the regression this fixes: a `plan`\n * session that wrote a file when prompted to). Noted as a known gap in\n * a naive auto-allow handler when #143 shipped the `CLAUDE_CONFIG_DIR`\n * override that makes `mode: \"plan\"` take effect in the first place;\n * this closes it.\n *\n * Behaves exactly like `autoAllowPermissionHandler` for every other\n * request. For the plan-mode-exit request specifically, it selects the\n * offered `reject_once` option (\"No, keep planning\") so the wrapper\n * denies the exit with a clean, structured outcome — the tool call\n * fails, the agent stays in plan mode and can keep reasoning or tell\n * the user it's blocked, instead of the turn throwing on a `cancelled`\n * outcome. Falls back to `cancelled` if no `reject_once` option is\n * offered (shouldn't happen with the current wrapper, but a safe\n * default beats guessing an allow).\n *\n * This is a deliberate one-way gate: a plan-mode session driven by this\n * handler can never escalate itself out of plan mode. A caller that\n * wants a human (or a policy engine) to approve that escalation must\n * supply its own `onPermissionRequest` — this handler is only the\n * default for callers that don't.\n */\nexport const planModePermissionHandler: AcpPermissionHandler = params => {\n  const { options, toolCall } = params\n  if (!options || options.length === 0) {\n    return { outcome: { outcome: \"cancelled\" } }\n  }\n  if (toolCall?.kind === PLAN_MODE_EXIT_TOOL_CALL_KIND) {\n    const keepPlanning = options.find(o => o.kind === \"reject_once\")\n    return keepPlanning\n      ? { outcome: { outcome: \"selected\", optionId: keepPlanning.optionId } }\n      : { outcome: { outcome: \"cancelled\" } }\n  }\n  return autoAllowPermissionHandler(params)\n}\n\n/** Picks the safe default permission handler for a requested AIP-45\n *  mode when the caller didn't supply their own `onPermissionRequest`.\n *  Only `\"plan\"` gets special handling today — other modes (accept-edits,\n *  bypass-permissions) are already at-or-above the auto-allow handler's\n *  trust level, so there's no escalation for it to guard against. */\nfunction defaultPermissionHandlerForMode(\n  requestedMode: string | undefined,\n): AcpPermissionHandler {\n  return requestedMode === \"plan\"\n    ? planModePermissionHandler\n    : autoAllowPermissionHandler\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`, or\n   *  `planModePermissionHandler` when `requestedMode === \"plan\"`. 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   * AIP-45 mode requested at spawn (`opts.config.mode` in\n   * `define-agent-cli.ts`'s `start()`), if any. Used to pick the default\n   * permission handler when `onPermissionRequest` is omitted — see\n   * `defaultPermissionHandlerForMode`.\n   */\n  requestedMode?: string\n  /**\n   * When true, permission requests are surfaced as `agent-prompt` StreamEvents\n   * and HELD in the daemon's permission inbox rather than auto-answered —\n   * forwarded verbatim to `createAcpClient({ permissionHold })`. The\n   * `onPermissionRequest` / `requestedMode` handler is bypassed while this is\n   * set. Default false (unchanged: requests are auto-answered in-arm).\n   */\n  permissionHold?: boolean\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  // Disconnect subscribers registered BEFORE `connect()` created the client.\n  // Drained (and then unused) in `connect`; a later subscriber attaches\n  // straight to the live client instead.\n  const earlyDisconnectListeners: Array<(err: Error) => void> = []\n\n  return {\n    get sessionId(): string | undefined {\n      return session?.sessionId\n    },\n    get availableConfigOptions() {\n      return session?.availableConfigOptions ?? []\n    },\n    get modelApplyRejection() {\n      return session?.modelApplyRejection\n    },\n    get availableModes() {\n      return session?.availableModes ?? []\n    },\n    get currentModeId(): string | undefined {\n      return session?.currentModeId\n    },\n    isConnected(): boolean {\n      // Pre-connect (`client === null`) reports true: nothing has died yet,\n      // and a host that reads `false` here would tear down a session that was\n      // merely still starting. Post-connect this defers to the SDK\n      // connection's own abort signal — a live read, never a cached flag.\n      return client?.isConnected() ?? true\n    },\n    onDisconnect(listener) {\n      if (client) client.onDisconnect(listener)\n      else earlyDisconnectListeners.push(listener)\n    },\n    async connect(opts: AgentCliConnectOptions) {\n      const permissionHandler =\n        options.onPermissionRequest ??\n        defaultPermissionHandlerForMode(options.requestedMode)\n      client = await createAcpClient({\n        output,\n        input,\n        clientInfo: options.clientInfo,\n        capabilities: {\n          fs: { readTextFile: true, writeTextFile: true },\n        },\n        onActivity: opts.onActivity,\n        turnIdleTimeoutMs: opts.turnIdleTimeoutMs,\n        // Permission-hold mode: surface + park requests for the daemon inbox\n        // instead of auto-answering them in-arm (see AcpProtocolOptions).\n        ...(options.permissionHold ? { permissionHold: true } : {}),\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        // `params` is contextually typed as the SDK's `RequestPermissionRequest`\n        // (via `AcpClientOptions.handlers`), which is assignable to\n        // `AcpPermissionRequestParams` — so no cast is needed on either side.\n        handlers: {\n          requestPermission: async params => permissionHandler(params),\n        },\n      })\n      // Attach any disconnect subscriber that arrived before the client\n      // existed, BEFORE the first RPC below: `loadSession`/`newSession` are\n      // exactly where a wrapper that dies on startup takes the connection\n      // down with it, and a subscriber attached afterwards would still be\n      // told (the client reports an already-aborted signal synchronously) —\n      // attaching here just means it's told at the right moment.\n      for (const listener of earlyDisconnectListeners.splice(0)) {\n        client.onDisconnect(listener)\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          ...(opts.mode ? { mode: opts.mode } : {}),\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 setConfigOption(configId, value) {\n      // No connected session yet — nothing to apply against. Distinct from\n      // `not-supported` (a protocol-level absence): this arm DOES support\n      // it, there's just no live connection right now.\n      if (!session) return { applied: false, reason: \"not-connected\" }\n      return session.setConfigOption(configId, value)\n    },\n    async setSessionMode(modeId) {\n      // Same not-connected/not-supported split as setConfigOption above.\n      if (!session) return { applied: false, reason: \"not-connected\" }\n      return session.setSessionMode(modeId)\n    },\n    onOutOfTurnEvent(listener) {\n      // Subscribed after `connect()` resolved (the runtime binds it to the\n      // session it just started) — before that there is nothing to hear.\n      if (!session) return () => {}\n      return session.onOutOfTurnEvent(listener)\n    },\n    get steeringSupported() {\n      return session?.steeringSupported ?? false\n    },\n    async steer(content) {\n      // Nothing to steer before connect — same not-connected shape as the\n      // other session controls, reported as \"promptRequired\" (no turn).\n      if (!session) return \"promptRequired\"\n      return session.steer(content)\n    },\n    respondPermission(\n      requestId: string,\n      resolution: AcpPermissionResolution,\n    ): boolean {\n      // Resolve a permission request parked by permission-hold mode. Routed\n      // through the client (its pending map is keyed globally by request id).\n      return client?.respondPermission(requestId, resolution) ?? false\n    },\n    async close() {\n      if (session) await session.close()\n      if (client) await client.close()\n    },\n  }\n}\n","/**\n * Shared converter from this repo's generic `AcpMcpServer[]`\n * (`{ name, transport: \"stdio\"|\"http\"|\"sse\", ref? }`) to the\n * `Record<string, McpServerConfig>` shape mastracode expects — both\n * for the in-process SDK config (`MastraCodeConfig.mcpServers`) and\n * for the file-based `.mastracode/mcp.json` the print arm writes.\n *\n * The target type is structurally identical in both contexts:\n *   - stdio → `{ command, args?, env? }`\n *   - http  → `{ url, headers? }`\n *   - sse   → `{ url }` (mastracode's `McpHttpServerConfig` doc says\n *             it handles SSE through the same `url` field, no separate\n *             discriminator)\n *\n * Neither `McpServerConfig`/`McpStdioServerConfig`/`McpHttpServerConfig`\n * is exported from `mastracode`'s public surface (only `.`, `./tui`,\n * `./acp`, `./headless`, `./plugin` subpaths are exported — no `./mcp`),\n * so we define a local, structurally-matching type here. TS structural\n * typing means a plain object literal shaped correctly type-checks fine\n * against `MastraCodeConfig.mcpServers` without a named import.\n *\n * Mirrors EXACTLY the same transport→field semantics the ACP arm uses\n * in `toAcpMcpServer` (`@agentproto/acp/client`), just flattened to\n * mastracode's keyed-record shape instead of the ACP wire array.\n */\n\nimport type { AcpMcpServer } from \"./types.js\"\n\n/**\n * mastracode's per-server config entry (structural — not imported from\n * `mastracode`, which doesn't export these types from its public\n * surface). Detected structurally by mastracode: `command` present →\n * stdio, `url` present → http. Both keys present → entry is skipped\n * (mastracode's own validation).\n */\nexport type MastracodeMcpServerConfig =\n  | { command: string; args?: string[]; env?: Record<string, string> }\n  | { url: string; headers?: Record<string, string> }\n\n/**\n * Convert the repo's compact `AcpMcpServer[]` into mastracode's\n * `Record<string, McpServerConfig>` keyed by server name. Returns\n * `undefined` for an empty/missing input so callers can spread the\n * result conditionally (`...(cond ? { mcpServers } : {})`).\n *\n * On key collision the caller's entry simply overwrites — this matches\n * mastracode's own \"higher precedence overrides lower, by server name\"\n * merge semantics for both the SDK config field and the file-based\n * load-order.\n */\nexport function toFileBasedMcpServers(\n  servers: readonly AcpMcpServer[] | undefined,\n): Record<string, MastracodeMcpServerConfig> | undefined {\n  if (!servers || servers.length === 0) return undefined\n  const out: Record<string, MastracodeMcpServerConfig> = {}\n  for (const s of servers) {\n    out[s.name] =\n      s.transport === \"stdio\"\n        ? {\n            command: s.ref ?? \"\",\n            ...(s.args !== undefined ? { args: s.args } : {}),\n            ...(s.env !== undefined ? { env: s.env } : {}),\n          }\n        : { url: s.ref ?? \"\", ...(s.headers !== undefined ? { headers: s.headers } : {}) }\n  }\n  return out\n}\n","/**\n * Whole-tree teardown for a spawned adapter process.\n *\n * `child.kill(\"SIGTERM\")` alone signals only the direct child — for most\n * adapters that is an `npx`/`npm exec` wrapper, and the wrapper can ignore\n * SIGTERM (observed live) while the real adapter, its MCP servers, and any\n * headless Chrome they started keep running as its descendants. Worse, once\n * the wrapper does die those descendants reparent to init and are no longer\n * findable from the child's pid at all.\n *\n * So the tree is snapshotted (`ps -axo pid=,ppid=`) BEFORE anything is\n * signalled, every member gets SIGTERM, and whatever is still alive after a\n * grace period — plus anything it spawned meanwhile — gets SIGKILL.\n */\n\nimport { execFile, type ChildProcess } from \"node:child_process\"\n\nexport interface ProcessRow {\n  pid: number\n  ppid: number\n}\n\nexport interface TerminateTreeOptions {\n  /** How long SIGTERM gets before survivors are SIGKILLed. Default 3000ms. */\n  graceMs?: number\n  /** Liveness poll interval during the grace period. Default 100ms. */\n  pollMs?: number\n  /** Process table source — injectable for tests. Default `ps -axo pid=,ppid=`. */\n  listProcesses?: () => Promise<ProcessRow[]>\n}\n\nexport interface TerminateTreeResult {\n  /** Descendant pids found in the pre-signal snapshot (root excluded). */\n  descendants: number[]\n  /** Pids (root included) still alive after the grace period, SIGKILLed. */\n  killed: number[]\n}\n\nconst DEFAULT_GRACE_MS = 3000\nconst DEFAULT_POLL_MS = 100\n\n/** Every pid below `rootPid` in `rows` (breadth-first, root excluded). */\nexport function descendantsOf(rootPid: number, rows: readonly ProcessRow[]): number[] {\n  const byParent = new Map<number, number[]>()\n  for (const r of rows) {\n    const list = byParent.get(r.ppid)\n    if (list) list.push(r.pid)\n    else byParent.set(r.ppid, [r.pid])\n  }\n  const out: number[] = []\n  const seen = new Set<number>([rootPid])\n  const queue = [rootPid]\n  while (queue.length > 0) {\n    const pid = queue.shift() as number\n    for (const kid of byParent.get(pid) ?? []) {\n      if (seen.has(kid)) continue\n      seen.add(kid)\n      out.push(kid)\n      queue.push(kid)\n    }\n  }\n  return out\n}\n\n/**\n * SIGTERM `child` and its whole process tree, then SIGKILL whatever survives\n * `graceMs`. Resolves once the tree is gone or the SIGKILLs are sent.\n *\n * The root is signalled through `child.kill()` and its liveness read off\n * `exitCode`/`signalCode`, never a raw `process.kill(child.pid)` — a child\n * whose spawn failed has no pid to signal (see the runtime's\n * `killChildIfSpawned`), and a root that already exited is a no-op, so this\n * never touches a pid it didn't verifiably spawn and still own.\n */\nexport async function terminateChildTree(\n  child: ChildProcess,\n  opts: TerminateTreeOptions = {},\n): Promise<TerminateTreeResult> {\n  const graceMs = opts.graceMs ?? DEFAULT_GRACE_MS\n  const pollMs = opts.pollMs ?? DEFAULT_POLL_MS\n  const list = opts.listProcesses ?? listProcesses\n  const rootPid = child.pid\n  const rootAlive = (): boolean => child.exitCode === null && child.signalCode === null\n  if (typeof rootPid !== \"number\" || rootPid <= 0 || rootPid === process.pid || !rootAlive()) {\n    return { descendants: [], killed: [] }\n  }\n\n  // Snapshot first: after the root dies its descendants reparent to init.\n  const descendants = descendantsOf(rootPid, await list()).filter(p => p !== process.pid)\n  const tracked = new Set(descendants)\n\n  try {\n    child.kill(\"SIGTERM\")\n  } catch {\n    // already gone\n  }\n  for (const pid of tracked) signal(pid, \"SIGTERM\")\n\n  const anyAlive = (): boolean => rootAlive() || [...tracked].some(isAlive)\n  const deadline = Date.now() + graceMs\n  while (anyAlive() && Date.now() < deadline) {\n    await new Promise(r => setTimeout(r, pollMs))\n  }\n  if (!anyAlive()) return { descendants, killed: [] }\n\n  // Anything a survivor spawned during the grace period belongs to the tree\n  // too — re-walk from the root (if still alive) and from every survivor.\n  const rows = await list()\n  const survivors = [...tracked].filter(isAlive)\n  for (const from of rootAlive() ? [rootPid, ...survivors] : survivors) {\n    for (const pid of descendantsOf(from, rows)) {\n      if (pid !== process.pid) tracked.add(pid)\n    }\n  }\n\n  const killed: number[] = []\n  if (rootAlive()) {\n    try {\n      child.kill(\"SIGKILL\")\n      killed.push(rootPid)\n    } catch {\n      // already gone\n    }\n  }\n  for (const pid of tracked) {\n    if (isAlive(pid) && signal(pid, \"SIGKILL\")) killed.push(pid)\n  }\n  return { descendants, killed }\n}\n\nfunction signal(pid: number, sig: NodeJS.Signals): boolean {\n  try {\n    process.kill(pid, sig)\n    return true\n  } catch {\n    return false\n  }\n}\n\nfunction isAlive(pid: number): boolean {\n  try {\n    process.kill(pid, 0)\n    return true\n  } catch (err) {\n    // EPERM: exists, just not ours to signal-probe.\n    return (err as NodeJS.ErrnoException).code === \"EPERM\"\n  }\n}\n\n/** `ps` is absent on Windows — resolve empty, degrading to root-only. */\nfunction listProcesses(): Promise<ProcessRow[]> {\n  return new Promise(resolve => {\n    execFile(\"ps\", [\"-axo\", \"pid=,ppid=\"], { maxBuffer: 32 * 1024 * 1024 }, (err, stdout) => {\n      if (err) return resolve([])\n      const out: ProcessRow[] = []\n      for (const line of stdout.split(\"\\n\")) {\n        const m = line.match(/^\\s*(\\d+)\\s+(\\d+)\\s*$/)\n        if (m) out.push({ pid: Number(m[1]), ppid: Number(m[2]) })\n      }\n      resolve(out)\n    })\n  })\n}\n","/**\n * Win32 spawn argv resolution for AgentCli adapter launches — recap point 10\n * (WIN11 test 2026-09-29/30): a device-sandbox spawn onto a joined Windows\n * host reached its daemon and ran the inner `agent_start`, but the headless\n * adapter launch died with Node `spawn EINVAL`. e2b/Linux hosts had never\n * shown it because only Windows has npm `.cmd` shims.\n *\n * The mechanism (both file:line cited in the PR that ships this):\n *   - `resolveSpawnBin` (`define-agent-cli.ts:115-121`) rewrites the\n *     manifest `bin: \"npx\"` (opencode, claude-code, codex, …) to the\n *     ABSOLUTE `<execPath-dir>\\npx.cmd` on win32.\n *   - The ACP arm's spawn (`define-agent-cli.ts:527`) and the print arm's\n *     spawn (`print-arm.ts:188`) then pass that `.cmd` path to\n *     `child_process.spawn` WITHOUT the `shell` option.\n *   - Node ≥ 18.20.2 / 20.12.2 / 22.0 (CVE-2024-27980: `IsWindowsBatchFile`\n *     in `src/process_wrap.cc`) refuses every spawn whose file literal ends\n *     in `.bat`/`.cmd` without `shell: true` → the whole `agent_start`\n *     fails `spawn EINVAL`. Bare (extensionless) bins never hit that check\n *     — the spawn paths that work on Windows (the PTY/ConPTY launches,\n *     which cmd-resolve shims from a command-LINE string) pass either a\n *     bare name or a real `.exe` — which is exactly the divergence between\n *     the working local spawn and the device-bridge host spawn.\n *\n * Fix policy (two stages, keyed on the resolved bin's extension, win32 only):\n *   1. PREFERRED — rewrite a `.cmd`/`.bat` npm shim into the real node\n *      entry it wraps (`npx.cmd` → `node …/node_modules/npm/bin/npx-cli.js`):\n *      the spawn stays `shell:false` with clean argv, and no cmd.exe\n *      interpolation of our args. Every shipped adapter (bin `npx`/`npm`)\n *      takes this stage.\n *   2. FALLBACK — a `.cmd`/`.bat` bin we cannot rewrite (another global\n *      package's shim named directly in a manifest) spawns with\n *      `shell: true`, Node's documented escape hatch. Args reaching that\n *      stage come from adapter manifests plus operator `model`/`effort`\n *      values validated upstream — free-form shell input never goes here.\n */\n\nimport { existsSync } from \"node:fs\"\nimport { basename, dirname, join } from \"node:path\"\n\n/** True when `exe` is a batch file Node on Windows refuses to spawn\n *  directly without `shell: true` (see module doc — CVE-2024-27980). */\nexport function isWindowsBatchFile(\n  exe: string,\n  deps?: { platform?: NodeJS.Platform },\n): boolean {\n  if ((deps?.platform ?? process.platform) !== \"win32\") return false\n  return /\\.(?:bat|cmd)$/i.test(exe)\n}\n\n/** `spawn` options telling Node to run a batch-file bin through cmd.exe —\n *  empty (no options) on POSIX or for a non-batch bin. Spread verbatim\n *  into both arms' `spawn(execBin, execArgs, { … })` calls once the spawn\n *  args are final. */\nexport function windowsBatchShellOption(\n  exe: string,\n  deps?: { platform?: NodeJS.Platform },\n): { shell: true } | { shell?: never } {\n  if (isWindowsBatchFile(exe, deps)) return { shell: true }\n  return {}\n}\n\nexport interface WindowsBatchSpawnResolution {\n  bin: string\n  args: string[]\n}\n\n/** Stage 1: when `bin` is a `.cmd`/`.bat` npm shim whose real node entry\n *  sits beside it, swap the shim for\n *  `<execPath> <dirname(bin)/node_modules/npm/bin/<stem>-cli.js>`. npm's\n *  own `.cmd` shims (`npx.cmd`, `npm.cmd`) are exactly this: a two-line\n *  wrapper execing `node <…>/npm/bin/<npx|npm>-cli.js $*`, so the rewrite\n *  is behavior-identical while keeping the spawn `shell:false` (cmd.exe\n *  never sees our argv). `npx-cli.js`/`npm-cli.js` live next to their shim\n *  both in a Node install dir (`C:\\Program Files\\nodejs\\`) and in an npm\n *  global-prefix dir (`%APPDATA%\\npm\\`), so `dirname(bin)` is the right\n *  root in both layouts. A third-party global bin shim (e.g.\n *  `opencode.cmd`) has no such sibling JS — this returns `undefined` and\n *  the caller falls back to {@link windowsBatchShellOption}. */\nexport function resolveWindowsBatchSpawn(\n  bin: string,\n  args: readonly string[],\n  deps?: {\n    platform?: NodeJS.Platform\n    execPath?: string\n    exists?: (p: string) => boolean\n  },\n): WindowsBatchSpawnResolution | undefined {\n  if ((deps?.platform ?? process.platform) !== \"win32\") return undefined\n  if (!isWindowsBatchFile(bin, deps)) return undefined\n  const stem = basename(bin).replace(/\\.(?:bat|cmd)$/i, \"\")\n  if (stem !== \"npx\" && stem !== \"npm\") return undefined\n  const script = join(dirname(bin), \"node_modules\", \"npm\", \"bin\", `${stem}-cli.js`)\n  // Default to the fs-level check. The WIN11 field test (2026-09-30) shipped\n  // a dist where the production caller passed no deps at all, so this branch\n  // evaluated a placeholder `() => false` and the stage-1 rewrite silently\n  // never took — every spawn fell to the `shell: true` fallback and cmd.exe\n  // mangled the quoted `C:\\Program Files\\...` path (the \"ACP connection\n  // closed\" wall). Tests inject this via `deps`; production must hit the\n  // real filesystem.\n  if (!(deps?.exists ?? existsSync)(script)) return undefined\n  return { bin: deps?.execPath ?? process.execPath, args: [script, ...args] }\n}\n","/**\n * Wraps an agent-cli child's spawn argv through the shared OS-level\n * confinement backends (`@agentproto/command-sandbox` — macOS Seatbelt /\n * Linux bubblewrap), the same backends `@agentproto/runtime`'s\n * `command_execute` tool already wraps ALLOWLISTED commands through. This\n * confines the adapter's OWN process tree — the harness-agnostic\n * enforcement an ACP permission seam can never provide, since it only sees\n * tool calls the adapter chooses to report, not what an in-process Bash\n * actually touches.\n *\n * Used by both spawn sites in this package: the long-lived ACP/MCP arm\n * (`define-agent-cli.ts`) and the per-turn print-protocol arm\n * (`protocol/print-arm.ts`).\n */\n\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\nimport {\n  loadAdapterSpawnSandboxConfig,\n  resolveCommandSandbox,\n  type SandboxMode,\n  type SandboxPolicy,\n  type SandboxZones,\n} from \"@agentproto/command-sandbox\"\n\n/**\n * Directories OUTSIDE the workspace, under `$HOME`, that a confined adapter\n * child needs WRITE access to just to function — toolchain self-management\n * (pnpm/npm) plus the adapter's own runtime bookkeeping. Read access to\n * `~/.npmrc` etc. is covered by Seatbelt's `allow default` / bwrap's\n * ro-bind-try of system dirs already; these are specifically the\n * WRITE-needing paths, all empirically required (2026-07-22) running a REAL\n * `npx`-spawned `claude-agent-acp` child under `workspace` mode:\n *\n * - pnpm/npm toolchain: a pnpm self-update or global install fails\n *   otherwise — documented in `@agentproto/command-sandbox`'s own module\n *   doc for the `command_execute` use of these same backends.\n * - `~/.claude/session-env/<sessionId>`: Claude Code's own Bash-tool\n *   session bookkeeping directory (empty per-session dirs it creates\n *   itself) — without write access here every Bash tool call in the\n *   confined child fails with EPERM before the command even runs, since\n *   the tool can't create its own scratch dir. Narrowly scoped to\n *   `session-env` rather than all of `~/.claude` (which also holds\n *   settings/credentials this confinement should NOT grant write access\n *   to). Harmless to include for non-claude-code adapters — a directory\n *   that doesn't exist is simply not bound (bwrap `--bind-try`) / not\n *   matched (Seatbelt subpath allow on a nonexistent path is a no-op).\n */\nexport function defaultToolchainWritePaths(): string[] {\n  const home = homedir()\n  return [\n    join(home, \"Library\", \"pnpm\", \".tools\"), // macOS pnpm self-managed toolchain\n    join(home, \".local\", \"share\", \"pnpm\"), // Linux pnpm self-managed toolchain\n    join(home, \".npm\"), // npm cache — self-update / global installs\n    join(home, \".claude\", \"session-env\"), // claude-code's own Bash-tool session bookkeeping\n  ]\n}\n\n/**\n * pnpm/npm config files OUTSIDE the workspace that need READ access — without\n * these, pnpm still limps along on its built-in defaults but prints an EPERM\n * warning on every invocation (empirically observed 2026-07-22 running\n * `pnpm --version` / `pnpm store path` inside a real confined adapter child)\n * and silently ignores whatever the operator configured there (registry\n * mirrors, auth tokens for private registries, …). Same footgun\n * `@agentproto/command-sandbox`'s own module doc already documents for the\n * `command_execute` use of these backends.\n *\n * Also covers the git/gh keychain-backed credential gap flagged by PR 6a's\n * empirical verification: under `workspace` mode, a confined `git ls-remote`\n * failed with `unable to access '~/.gitconfig': Operation not permitted` and\n * a confined `gh auth status` failed with `open '~/.config/gh/config.yml':\n * operation not permitted` — BEFORE either tool ever reached the OS\n * keychain, because their own config files live under the denied `$HOME`\n * subtree and only metadata (stat/lstat), not content, is re-allowed there.\n * Re-verified 2026-07-23: re-allowing `~/.gitconfig` + `~/.config/git` +\n * `~/.config/gh` (content read) fixes both commands; `gh auth status` then\n * still failed one more level down — `git-credential-osxkeychain get`\n * silently returned nothing under confinement (vs. a full credential record\n * unconfined) even with `~/Library/Keychains` reachable via `allow default`'s\n * mach-lookup to securityd. Adding `~/Library/Keychains` here (content read,\n * not just the mach-IPC path `allow default` already permits) fixed it: the\n * client-side keychain lookup needs to read its own keychain database file,\n * not only talk to securityd over XPC. READ-ONLY is deliberate — an agent\n * should be able to RETRIEVE a stored credential to authenticate a push, but\n * granting WRITE would let a confined process tamper with the host's real\n * keychain (`git credential-osxkeychain store/erase`); that's out of scope\n * and not needed for the push/fetch flows this gap was blocking.\n *\n * Linux has no equivalent OS keychain this backend integrates with (`gh`/git\n * there typically use libsecret/gnome-keyring over D-Bus, or a plaintext\n * `.git-credentials` store) — see `command-sandbox-wrap.ts`'s module doc for\n * the documented workaround under bwrap.\n */\nexport function defaultToolchainReadPaths(): string[] {\n  const home = homedir()\n  return [\n    join(home, \".npmrc\"),\n    join(home, \"Library\", \"Preferences\", \"pnpm\", \"rc\"),\n    join(home, \".gitconfig\"), // git's own global config (credential.helper, user.*, …)\n    join(home, \".config\", \"git\"), // XDG git config fallback\n    join(home, \".config\", \"gh\"), // gh's config.yml + hosts.yml\n    join(home, \"Library\", \"Keychains\"), // macOS Keychain DB — git/gh credential retrieval (read-only; see doc above)\n  ]\n}\n\nexport interface WrapAgentCliSpawnOptions {\n  /**\n   * `undefined` ⇒ this call site didn't explicitly choose a mode — falls\n   * back to the workspace's `.agentproto/command-sandbox.json`\n   * `adapterSpawn.mode` (or `ADAPTER_COMMAND_SANDBOX_MODE_ENV`), and only\n   * stays unconfined if THAT also resolves to `undefined` (no file, no\n   * `adapterSpawn` key). An explicit mode here (from `agent_start`'s\n   * `commandSandbox` param) always wins over the config file — see the\n   * module's config-key doc in `@agentproto/command-sandbox` for why the\n   * two are independent.\n   */\n  mode: SandboxMode | undefined\n  /** The confinement boundary — normally the session's cwd. Also the\n   *  anchor `.agentproto/command-sandbox.json` is read from. */\n  cwd: string\n  /**\n   * Extra write-capable paths beyond the default toolchain set (e.g. the\n   * per-spawn `CLAUDE_CONFIG_DIR` temp dir mkdtemp'd BEFORE this spawn —\n   * bwrap's `--tmpfs /tmp` would otherwise hide it on Linux). Merged with\n   * (not a replacement for) the config file's own `adapterSpawn.extraWritePaths`.\n   */\n  extraWritePaths?: string[]\n  /** Merged with the config file's own `adapterSpawn.extraReadPaths`. */\n  extraReadPaths?: string[]\n  /**\n   * Host-declared filesystem zones (see `SandboxZones`). When present the\n   * confinement is ALWAYS engaged — `mode` defaults to `\"workspace\"`\n   * regardless of the workspace's config file, an explicit `\"off\"` is\n   * refused, and the cwd's own `.agentproto/command-sandbox.json` extra\n   * paths are ignored (the app being confined must not be able to widen its\n   * own boundary from a file the boundary is meant to make read-only).\n   */\n  zones?: SandboxZones\n  /** Adapter/arm identifier for the fail-closed error message. */\n  label: string\n}\n\n/**\n * Wrap `[bin, ...args]` for confined execution, or return it unchanged when\n * unconfined. FAIL-CLOSED when a mode IS configured but no backend exists\n * for this platform — mirrors `command_execute`'s own fail-closed contract\n * in `@agentproto/runtime`'s `command-tools.ts`: an operator who explicitly\n * opted into confinement believing it's active, silently getting an\n * unconfined agent-cli child that can read `~/.ssh`, is strictly worse than\n * a clear error.\n *\n * Mode resolution order: `opts.mode` (explicit `agent_start.commandSandbox`)\n * wins outright; otherwise `.agentproto/command-sandbox.json`'s\n * `adapterSpawn.mode` (itself overridable by `ADAPTER_COMMAND_SANDBOX_MODE_ENV`)\n * applies. If BOTH resolve to `undefined` (no explicit call, no config file /\n * no `adapterSpawn` key), this stays SILENT and unconfined — unlike\n * `command_execute`'s per-call warning, which fires because `off` is what\n * ITS config loader always resolves an untouched workspace TO. Here\n * `undefined` specifically means \"this axis was never engaged by anyone\",\n * so warning would print on every single session spawn across the whole\n * fleet by default — a real behavior change, not the \"default off,\n * unchanged behaviour\" this option promises. A resolved `mode: \"off\"`\n * (explicit call OR an `adapterSpawn` config block that opted in and picked\n * unconfined) still gets the loud warning, matching `command_execute`'s\n * reasoning that a live \"off\" state shouldn't fade into background noise.\n *\n * Extra read/write paths (both the caller's `opts.extraReadPaths`/\n * `extraWritePaths` and the config file's `adapterSpawn.extraReadPaths`/\n * `extraWritePaths`) always merge in on top of the built-in toolchain\n * defaults whenever confinement is active, regardless of which side chose\n * the mode — they're workspace-level exceptions, not mode-selection.\n */\nexport async function wrapAgentCliSpawn(\n  bin: string,\n  args: string[],\n  opts: WrapAgentCliSpawnOptions,\n): Promise<[string, string[]]> {\n  const cfg = await loadAdapterSpawnSandboxConfig(opts.cwd)\n  const mode = opts.zones ? (opts.mode ?? \"workspace\") : (opts.mode ?? cfg.mode)\n  if (mode === undefined) return [bin, args]\n  if (mode === \"off\" && opts.zones) {\n    throw new Error(\n      `agent-cli '${opts.label}': filesystem zones (an app boundary) cannot be ` +\n        `combined with commandSandbox \"off\" — the zones are only enforceable ` +\n        `through the OS sandbox. Refusing to spawn.`,\n    )\n  }\n  if (mode === \"off\") {\n    console.error(\n      `[agent-cli] ⚠ spawning '${opts.label}' UNCONFINED — no OS-level ` +\n        `sandbox is active (commandSandbox mode is \"off\").`,\n    )\n    return [bin, args]\n  }\n  const backend = resolveCommandSandbox()\n  if (!backend) {\n    throw new Error(\n      `agent-cli '${opts.label}': commandSandbox mode=\"${mode}\" is configured ` +\n        `but no sandbox backend is available on ${process.platform} (macOS ` +\n        `needs sandbox-exec, Linux needs bwrap installed). Refusing to spawn ` +\n        `unconfined — pass commandSandbox: \"off\" to explicitly accept ` +\n        `unconfined execution, or install the missing backend.`,\n    )\n  }\n  const fileCfg = opts.zones ? undefined : cfg\n  const policy: SandboxPolicy = {\n    workspace: opts.cwd,\n    extraReadPaths: [\n      ...defaultToolchainReadPaths(),\n      ...(fileCfg?.extraReadPaths ?? []),\n      ...(opts.extraReadPaths ?? []),\n    ],\n    extraWritePaths: [\n      ...defaultToolchainWritePaths(),\n      ...(fileCfg?.extraWritePaths ?? []),\n      ...(opts.extraWritePaths ?? []),\n    ],\n    ...(opts.zones ? { zones: opts.zones } : {}),\n    network: mode === \"strict\" || cfg.network === \"deny\" ? \"deny\" : \"allow\",\n  }\n  const wrapped = backend.wrap([bin, ...args], policy)\n  return [wrapped[0] ?? bin, wrapped.slice(1)]\n}\n","/**\n * AIP-45 protocol arm: `protocol: \"print\"`.\n *\n * Drives a headless CLI as one fresh subprocess per turn — no\n * long-lived ACP connection. Simpler than the ACP arm and immune to\n * the stale-proxy race condition: the session object itself never dies\n * between turns; only the per-turn child does.\n *\n * ## Configuration\n *\n * The adapter's `print` manifest block declares the CLI's one-shot\n * surface (flags, output format, event taxonomy). When the block is\n * absent, Claude Code defaults are applied for backward compatibility.\n *\n * ## Session tracking\n *\n * The `sessionId` property starts empty (or pre-seeded from\n * `resumeSessionId`) and is updated after the first successful turn\n * from the wire event that carries the session / thread identifier\n * (Claude: `result.session_id`; Mastra: `result.threadId`).\n * Subsequent turns pass the appropriate resume flag so the CLI\n * rehydrates the conversation.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { existsSync, mkdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from \"node:fs\"\nimport { createInterface } from \"node:readline\"\nimport { join } from \"node:path\"\nimport type { SandboxMode } from \"@agentproto/command-sandbox\"\nimport { toFileBasedMcpServers } from \"../mcp-servers.js\"\nimport { terminateChildTree } from \"../process-tree.js\"\nimport { windowsBatchShellOption } from \"../win32-spawn.js\"\nimport { wrapAgentCliSpawn } from \"../command-sandbox-wrap.js\"\nimport type {\n  AcpMcpServer,\n  AgentCliPrintConfig,\n  AgentCliRuntimeSession,\n  StreamEvent,\n} 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  /** Adapter-declared print surface config. Omit for Claude defaults. */\n  printConfig?: AgentCliPrintConfig\n  /**\n   * MCP servers to mount into the agent's session. For the `mastracode`\n   * print arm (`event_schema: \"mastra-jsonl\"`) these are written to\n   * `<cwd>/.mastracode/mcp.json` before the first turn's spawn (the\n   * mastracode CLI has no CLI flag / env var / config-dir override for\n   * MCP config — this was exhaustively verified against its source) and\n   * restored/removed on `close()`. Ignored for other print schemas\n   * (e.g. Claude Code), which don't load MCP config from this path.\n   */\n  mcpServers?: AcpMcpServer[]\n  /** OS-level confinement for the per-turn spawn — see\n   *  `AgentCliStartOptions.commandSandbox` in `../types.ts` and\n   *  `wrapAgentCliSpawn`'s doc for the fail-closed contract. */\n  commandSandbox?: SandboxMode\n  /** Extra write-capable paths beyond the default toolchain set, e.g. the\n   *  per-session `CLAUDE_CONFIG_DIR` temp dir set up by the caller. */\n  extraWritePaths?: string[]\n  /** Extra READ-only paths beyond the confinement boundary — the exact-file\n   *  AGENTS.md grant (`AgentCliStartOptions.additionalReadPaths`). READ\n   *  exceptions only; never widens writes. */\n  extraReadPaths?: string[]\n  /** See `AgentCliStartOptions.fsZones`. */\n  fsZones?: { readOnly: string[]; writable: string[]; hidden?: string[] }\n  /**\n   * The explicitly requested model id — when set, a wire event that\n   * truthfully reports which model the agent ACTUALLY started on (today:\n   * the jcode-ndjson `start` line's `model` field) is checked against it,\n   * and a mismatch aborts the turn loudly (child killed, error event)\n   * instead of letting the agent run on a model the operator didn't name.\n   * Set by `define-agent-cli.ts` only for `routeSelection:\n   * \"derived-from-model\"` adapters with an explicit `model` option — the\n   * print-protocol counterpart of its ACP-arm guard. The bug this closes:\n   * jcode's CLI silently falls back to its own default on an unknown\n   * `--model` id (observed live: `--model totally-bogus-xyz` →\n   * `{\"type\":\"start\",\"model\":\"gpt-5.6-sol\",\"provider\":\"OpenAI\"}`), which\n   * for a derived-from-model adapter is a different provider on a\n   * different bill. Schemas that never report the started model are\n   * unaffected. Compared via {@link printModelMismatch} (basename,\n   * `@suffix`/`provider/`-prefix tolerant).\n   */\n  expectedModel?: string\n}\n\n/**\n * Whether the agent's reported model contradicts the requested one.\n * Compares the model BASENAME (last `/` segment, `@route` suffix stripped,\n * case-insensitive) because the wire echoes a normalized form of the id:\n * jcode reports `deepseek/deepseek-v4-pro` for a requested\n * `deepseek/deepseek-v4-pro@openrouter` — same model, different spelling.\n * Basename equality keeps that a match while still catching a silent\n * default-model fallback (requested `gpt-5` vs reported `gpt-5.6-sol` IS a\n * mismatch — no substring leniency).\n */\nexport function printModelMismatch(requested: string, reported: string): boolean {\n  const basename = (id: string): string => {\n    const noSuffix = id.split(\"@\")[0] ?? id\n    const segs = noSuffix.split(\"/\")\n    return (segs[segs.length - 1] ?? noSuffix).trim().toLowerCase()\n  }\n  return basename(requested) !== basename(reported)\n}\n\n// ── Defaults (Claude Code backward-compatible) ──────────────────────\n\nconst DEFAULT_OUTPUT: string[] = [\"--output-format\", \"stream-json\"]\nconst DEFAULT_PRE_PROMPT: string[] = [\"--no-interactive\"]\nconst DEFAULT_RESUME = { flag: \"--resume\", kind: \"value\" as const }\n\n/** The event taxonomies the print arm knows how to map. Mirrors\n *  `AgentCliPrintConfig.event_schema` (minus the optional/undefined) so the\n *  mapper dispatch and the manifest stay in lockstep. */\ntype PrintEventSchema = NonNullable<AgentCliPrintConfig[\"event_schema\"]>\n\nexport function createPrintSession(\n  opts: PrintArmOptions,\n): AgentCliRuntimeSession {\n  const config = opts.printConfig\n  const outputFormat = config?.output_format ?? DEFAULT_OUTPUT\n  const prePrompt = config?.pre_prompt ?? DEFAULT_PRE_PROMPT\n  const promptFlag = config?.prompt_flag\n  const resumeCfg = config?.resume ?? DEFAULT_RESUME\n  const eventSchema = config?.event_schema ?? \"claude-stream-json\"\n\n  let sessionId = opts.resumeSessionId ?? \"\"\n  let activeChild: ReturnType<typeof spawn> | null = null\n\n  // ── MCP server injection (mastracode print arm only) ─────────────\n  // The mastracode CLI has no CLI flag, env var, or config-dir override\n  // for MCP config (exhaustively verified against its source). The only\n  // way to mount host-chosen MCP servers into a print-arm subprocess is\n  // to write them into `<cwd>/.mastracode/mcp.json`, which mastracode\n  // loads at process startup as its highest-precedence project-scope\n  // config. This is done once here (before the first turn's spawn) and\n  // restored on close(). Only applies when the adapter is mastracode\n  // (`event_schema: \"mastra-jsonl\"`) — other print adapters (Claude\n  // Code) don't read this path.\n  const mcpRestore = setupMcpConfigFile(opts, eventSchema)\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      // Build argv: baseArgs + output_format + pre_prompt +\n      //             resume_flag(+value) + prompt_flag(+text) | positional\n      const args: string[] = [\n        ...opts.baseArgs,\n        ...outputFormat,\n        ...prePrompt,\n      ]\n\n      // Resume flag\n      if (sessionId) {\n        args.push(resumeCfg.flag)\n        if (resumeCfg.kind === \"value\") args.push(sessionId)\n      }\n\n      // Prompt: flag or positional\n      if (promptFlag) {\n        args.push(promptFlag, prompt)\n      } else {\n        args.push(prompt)\n      }\n\n      // OS-level confinement — same fail-closed contract as the ACP arm's\n      // spawn in `define-agent-cli.ts`; see `wrapAgentCliSpawn`'s doc.\n      const [execBin, execArgs] = await wrapAgentCliSpawn(opts.bin, args, {\n        mode: opts.commandSandbox,\n        cwd: opts.cwd,\n        ...(opts.extraWritePaths ? { extraWritePaths: opts.extraWritePaths } : {}),\n        ...(opts.extraReadPaths ? { extraReadPaths: opts.extraReadPaths } : {}),\n        ...(opts.fsZones ? { zones: opts.fsZones } : {}),\n        label: \"print-arm\",\n      })\n      const child = spawn(execBin, execArgs, {\n        cwd: opts.cwd,\n        env: opts.env,\n        stdio: [\"ignore\", \"pipe\", \"pipe\"],\n        // Win32: only reached for a `.cmd`/`.bat` bin that\n        // `resolveWindowsBatchSpawn` couldn't rewrite to its node entry\n        // (see `win32-spawn.ts` — Node refuses direct batch spawning,\n        // CVE-2024-27980, the recap-10 `spawn EINVAL`). POSIX: `{}`.\n        ...windowsBatchShellOption(execBin),\n      })\n      activeChild = child\n\n      // Attached synchronously, before any `await`/generator suspension\n      // below, so a spawn failure (bad binary, PATH miss) is never left\n      // as an unhandled 'error' on the child — which would throw and\n      // crash the whole daemon process. See the matching guard + incident\n      // note in `define-agent-cli.ts`'s ACP spawn.\n      let spawnFailure: Error | undefined\n      await new Promise<void>(resolve => {\n        child.once(\"spawn\", () => resolve())\n        child.once(\"error\", err => {\n          spawnFailure = err\n          resolve()\n        })\n      })\n      if (spawnFailure) {\n        activeChild = null\n        yield {\n          kind: \"error\",\n          error: { message: `failed to spawn '${execBin} ${execArgs.join(\" \")}': ${spawnFailure.message}` },\n        }\n        return\n      }\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)\n          throw new Error(\"print-arm: child has no stdout pipe\")\n\n        let capturedSessionId = \"\"\n        const mastraState =\n          eventSchema === \"mastra-jsonl\"\n            ? createMastraMapperState()\n            : undefined\n        const jcodeState =\n          eventSchema === \"jcode-ndjson\"\n            ? createJcodeMapperState()\n            : undefined\n\n        // ── Decouple pipe draining from downstream consumption ────────\n        // A `for await (const line of rl)` loop backpressures onto\n        // `child.stdout`: when the loop suspends at a slow downstream\n        // consumer (e.g. an SSE write to the orchestrator client that has\n        // stopped reading), readline pauses the stream, the child's stdout\n        // OS pipe buffer fills, and the child's next `write()` fails with\n        // `ENOBUFS` and the process dies. High-volume producers (kimi via\n        // mastracode: 900+ tool results / 1200+ lines) hit this reliably.\n        //\n        // Instead, readline's `\"line\"` event (flowing mode) drains the\n        // pipe CONTINUOUSLY — parsing and mapping each line the instant it\n        // arrives — and pushes mapped events into an in-memory queue. The\n        // generator below yields from that queue at whatever pace\n        // downstream consumes. The child therefore never observes\n        // backpressure from a slow client.\n        const rl = createInterface({ input: child.stdout, crlfDelay: Infinity })\n        const queue = new EventQueue()\n        let modelMismatchAborted = false\n\n        rl.on(\"line\", (line: string) => {\n          if (!line.trim()) return\n          if (modelMismatchAborted) return\n          let evt: Record<string, unknown>\n          try {\n            evt = JSON.parse(line) as Record<string, unknown>\n          } catch {\n            return\n          }\n\n          // Derived-from-model guard (see PrintArmOptions.expectedModel):\n          // the jcode-ndjson `start` line truthfully names the model the\n          // agent actually chose — if that contradicts the explicitly\n          // requested one, the CLI silently fell back to its own default.\n          // Abort the turn NOW, before the model call completes, instead\n          // of running (and billing) a model the operator didn't name.\n          if (\n            opts.expectedModel &&\n            eventSchema === \"jcode-ndjson\" &&\n            evt.type === \"start\" &&\n            typeof evt.model === \"string\" &&\n            printModelMismatch(opts.expectedModel, evt.model)\n          ) {\n            modelMismatchAborted = true\n            const provider =\n              typeof evt.provider === \"string\" ? ` (provider ${evt.provider})` : \"\"\n            queue.push({\n              kind: \"error\",\n              error: {\n                message:\n                  `model mismatch: requested \"${opts.expectedModel}\" but the agent ` +\n                  `started on \"${evt.model}\"${provider} — its CLI silently fell back ` +\n                  `to a default it resolved itself. This adapter routes AND bills by ` +\n                  `the model id, so the turn was aborted instead of silently running ` +\n                  `(and billing) a model you didn't ask for. Check the id against ` +\n                  `the adapter's model menu.`,\n              },\n            })\n            queue.end()\n            child.kill(\"SIGTERM\")\n            return\n          }\n\n          // Capture the session/thread id from the wire event\n          const csid = captureSessionId(evt, eventSchema)\n          if (csid) capturedSessionId = csid\n\n          const sid = capturedSessionId || sessionId || \"\"\n          const mapped = mapEvent(evt, sid, stderrLines, eventSchema, mastraState, jcodeState)\n          // A single wire line can fan out to several StreamEvents — e.g. an\n          // Antigravity tool step carries both the call and its result, and its\n          // terminal `result` line carries usage + turn-end together.\n          if (Array.isArray(mapped)) {\n            for (const m of mapped) queue.push(m)\n          } else if (mapped) {\n            queue.push(mapped)\n          }\n        })\n        rl.once(\"close\", () => queue.end())\n\n        // Yield mapped events as downstream pulls them; the `\"line\"`\n        // handler above keeps draining the pipe regardless of how far\n        // behind this loop is.\n        for await (const mapped of queue) {\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 binLabel =\n            eventSchema === \"mastra-jsonl\"\n              ? \"mastracode\"\n              : eventSchema === \"antigravity-stream-json\"\n                ? \"agy\"\n                : eventSchema === \"jcode-ndjson\"\n                  ? \"jcode\"\n                  : \"claude\"\n          const errEvt: StreamEvent = {\n            kind: \"error\",\n            error: {\n              message: `${binLabel} 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    // The print arm spawns a fresh subprocess PER TURN from `baseArgs`,\n    // which already has the model baked in (composed once, before this\n    // session object was even constructed — see `bin_args_template`\n    // handling in define-agent-cli.ts/compose.ts). There is no live\n    // connection to apply a mid-session config change to, and rebuilding\n    // `baseArgs` would mean a fresh session, not a live switch — so this\n    // is honestly `requires-restart`, same as the `arg` model-apply\n    // strategy for ACP arms.\n    async setModel(): Promise<{ applied: false; reason: string }> {\n      return { applied: false, reason: \"requires-restart\" }\n    },\n\n    // No ACP session — no wrapper-advertised capability read-surface and\n    // no `session/set_mode` RPC to switch live. Mirrors the \"arm has no\n    // mid-session config surface\" case `define-agent-cli.ts` reports for\n    // `setModel` on other arms.\n    availableConfigOptions: [],\n    availableModes: [],\n    currentModeId: undefined,\n    async setSessionMode(): Promise<{ applied: false; reason: string }> {\n      return { applied: false, reason: \"not-supported\" }\n    },\n\n    // Same as `setSessionMode`: a print arm has no live ACP session to apply\n    // `set_config_option(configId:\"effort\")` against — effort is baked into\n    // the spawn argv/env, so a live change is honestly `not-supported`.\n    async setEffort(): Promise<{ applied: false; reason: string }> {\n      return { applied: false, reason: \"not-supported\" }\n    },\n\n    async close(): Promise<void> {\n      // Whole tree — the print CLI's own subprocesses (MCP servers, tools)\n      // must not outlive the session. Restore runs regardless.\n      const closing = activeChild ? terminateChildTree(activeChild) : undefined\n      mcpRestore?.()\n      await closing\n    },\n  }\n}\n\n// ── MCP config file injection (mastracode print arm) ────────────────\n\n/**\n * Before the first turn's spawn, shallow-merges our injected MCP servers\n * into `<cwd>/.mastracode/mcp.json` (the highest-precedence project-scope\n * config mastracode loads). Returns a restore function that reverts the\n * file to its pre-session state on `close()`, or `undefined` if no\n * injection was performed.\n *\n * Only activates when `eventSchema === \"mastra-jsonl\"` (mastracode) AND\n * `opts.mcpServers` is non-empty. Other print adapters (Claude Code)\n * don't read this path and are left untouched.\n *\n * Our injected servers win on key collision — this matches mastracode's\n * own \"higher precedence overrides lower, by server name\" merge\n * semantics, and the SDK's documented \"merged with, and overriding,\n * file-based configs\" behavior for the in-process arm, so both arms\n * behave consistently.\n *\n * KNOWN LIMITATION: two concurrent mastracode print sessions sharing\n * the SAME `cwd` will race on this read-merge-write (last writer wins\n * on the shared file). This is an upstream mastracode CLI limitation —\n * no config-dir isolation exists to route around it. This is a real but\n * narrow edge case (only matters for concurrent orchestrator children\n * spawned into the identical directory); no locking mechanism is built\n * here, by design.\n */\nfunction setupMcpConfigFile(\n  opts: PrintArmOptions,\n  eventSchema: PrintEventSchema,\n): (() => void) | undefined {\n  if (eventSchema !== \"mastra-jsonl\") {\n    // A credentialed mount that reaches an arm which cannot mount it at all\n    // must not fail silently: the caller believes the server will see the\n    // Authorization header, the server instead sees an anonymous caller.\n    // Warn with the mount names so the loss is attributable (the mcpServers\n    // feature itself is mastra-jsonl-only — see the doc block above).\n    const credentialed = (opts.mcpServers ?? [])\n      .filter(s => s.transport !== \"stdio\" && s.headers !== undefined && Object.keys(s.headers).length > 0)\n      .map(s => s.name)\n    if (credentialed.length > 0) {\n      console.error(\n        `[agentproto] WARNING: mcpServers ${credentialed.map(n => `\"${n}\"`).join(\", \")} declare ` +\n          `headers but the \"${eventSchema}\" print adapter has no MCP mounting path — ` +\n          \"the mounts (and their credentials) will NOT reach the agent.\",\n      )\n    }\n    return undefined\n  }\n  if (!opts.mcpServers || opts.mcpServers.length === 0) return undefined\n\n  const dir = join(opts.cwd, \".mastracode\")\n  const file = join(dir, \"mcp.json\")\n  const injected = toFileBasedMcpServers(opts.mcpServers)\n  if (!injected) return undefined\n\n  // Snapshot the pre-session state so close() can restore it.\n  const fileExisted = existsSync(file)\n  let originalContent: string | undefined\n  if (fileExisted) {\n    try {\n      originalContent = readFileSync(file, \"utf8\")\n    } catch {\n      originalContent = undefined\n    }\n  }\n  const dirExisted = existsSync(dir)\n\n  // Ensure `.mastracode/` exists, then read-merge-write.\n  if (!dirExisted) {\n    mkdirSync(dir, { recursive: true })\n  }\n\n  let existingServers: Record<string, unknown> = {}\n  if (originalContent !== undefined) {\n    try {\n      const parsed = JSON.parse(originalContent) as Record<string, unknown>\n      if (parsed && typeof parsed.mcpServers === \"object\" && parsed.mcpServers !== null) {\n        existingServers = parsed.mcpServers as Record<string, unknown>\n      }\n    } catch {\n      // Corrupt or unparseable file — start fresh with just our servers.\n      existingServers = {}\n    }\n  }\n\n  // Shallow-merge: our injected servers override on key collision.\n  const merged: Record<string, unknown> = { ...existingServers, ...injected }\n  const output = JSON.stringify({ mcpServers: merged }, null, 2)\n  writeFileSync(file, output, \"utf8\")\n\n  // Return the restore function.\n  return () => {\n    try {\n      if (!fileExisted) {\n        // We created the file — remove it. Also remove the `.mastracode/`\n        // dir only if we created that too AND it's now empty (don't\n        // rm -rf someone's existing directory).\n        rmSync(file, { force: true })\n        if (!dirExisted) {\n          try {\n            // `rmdirSync` (not `rmSync`) — only removes an EMPTY\n            // directory, throwing ENOTEMPTY otherwise. `rmSync` without\n            // `recursive: true` throws on any directory regardless of\n            // contents, which would always land in the catch below and\n            // silently leave the directory behind even when empty.\n            rmdirSync(dir)\n          } catch {\n            // Directory not empty (other files were added) — leave it.\n          }\n        }\n      } else if (originalContent !== undefined) {\n        // File existed before — restore its original content, but first\n        // remove only our injected keys from the merged object so any\n        // concurrent changes (if the file was modified externally) are\n        // preserved minus our entries. If that produces an empty\n        // mcpServers map, restore the original file verbatim.\n        let current: Record<string, unknown> = {}\n        try {\n          const parsed = JSON.parse(readFileSync(file, \"utf8\")) as Record<string, unknown>\n          if (parsed && typeof parsed.mcpServers === \"object\" && parsed.mcpServers !== null) {\n            current = parsed.mcpServers as Record<string, unknown>\n          }\n        } catch {\n          // Can't read current state — restore original verbatim.\n          writeFileSync(file, originalContent, \"utf8\")\n          return\n        }\n        for (const key of Object.keys(injected)) {\n          delete current[key]\n        }\n        if (Object.keys(current).length === 0) {\n          // All servers were ours — restore original file content.\n          writeFileSync(file, originalContent, \"utf8\")\n        } else {\n          writeFileSync(file, JSON.stringify({ mcpServers: current }, null, 2), \"utf8\")\n        }\n      }\n    } catch {\n      // Best-effort — never throw from close().\n    }\n  }\n}\n\n// ── Prompt extraction ───────────────────────────────────────────────\n\n/** Print-mode CLIs (mastracode, antigravity, jcode, …) declare\n *  `capabilities.multimodal: false` — this arm spawns a fresh subprocess\n *  per turn and hands it ONE plain-text argv value, with no wire-level\n *  content-block channel for an image/resource block to ride on. A\n *  non-text block therefore has nowhere to go: silently dropping it (the\n *  previous behavior — filtering an array down to just its text blocks)\n *  would send an incomplete prompt with no indication anything was lost.\n *  Throwing here instead surfaces a clear `[turn error]` in the session's\n *  event stream (same convention as an ACP adapter rejecting content its\n *  own `promptCapabilities` doesn't advertise) — the caller should upload\n *  the file via `POST /files/upload` and reference its path in the prompt\n *  text instead, which this adapter reads natively (see its `file_attach`\n *  capability). */\nfunction extractPromptText(message: unknown): string {\n  if (typeof message === \"string\") return message\n  const blocks = Array.isArray(message) ? message : [message]\n  const texts: string[] = []\n  for (const block of blocks) {\n    if (block !== null && typeof block === \"object\") {\n      const b = block as Record<string, unknown>\n      if (b.type === \"text\" && typeof b.text === \"string\") {\n        texts.push(b.text)\n        continue\n      }\n      if (b.type === undefined && typeof b.text === \"string\") {\n        // Not an ACP-shaped block at all — a caller-supplied `{text: \"...\"}`\n        // convenience shape rather than `{type:\"text\", text:\"...\"}`.\n        texts.push(b.text)\n        continue\n      }\n    }\n    const kind =\n      block !== null && typeof block === \"object\" && typeof (block as Record<string, unknown>).type === \"string\"\n        ? ((block as Record<string, unknown>).type as string)\n        : typeof block\n    throw new Error(\n      `this adapter has no multimodal input (capabilities.multimodal: false) — got a ` +\n        `\"${kind}\" content block it can't send. Upload the file via POST /files/upload ` +\n        `and reference its path in the prompt text instead.`\n    )\n  }\n  return texts.join(\"\\n\")\n}\n\n// ── Session id capture per event schema ─────────────────────────────\n\nfunction captureSessionId(\n  evt: Record<string, unknown>,\n  schema: PrintEventSchema,\n): string | null {\n  switch (schema) {\n    case \"claude-stream-json\":\n      if (\n        evt.type === \"result\" &&\n        typeof evt.session_id === \"string\" &&\n        evt.session_id\n      )\n        return evt.session_id\n      return null\n    case \"antigravity-stream-json\": {\n      // `agy` stamps `conversation_id` on every line, but at two different\n      // levels: top-level on the opening `init` event, and nested in the\n      // payload on `result`. Capture it from the `init` (available before\n      // the turn produces any text — so a mid-turn crash still resumes) and\n      // re-confirm it from the authoritative terminal `result`. A pre-flight\n      // failure (e.g. unknown --model) emits `result` with an empty\n      // conversation_id; the `&& id` guard drops that so we never clobber a\n      // good id with \"\". Verified against antigravity.google/docs/cli/headless.\n      if (evt.event === \"init\" && typeof evt.conversation_id === \"string\" && evt.conversation_id)\n        return evt.conversation_id\n      if (evt.event === \"result\") {\n        const r = evt.result as Record<string, unknown> | undefined\n        if (typeof r?.conversation_id === \"string\" && r.conversation_id)\n          return r.conversation_id\n      }\n      return null\n    }\n    case \"mastra-jsonl\":\n      // Mastra Code writes exactly one authoritative final line per run\n      // regardless of success/failure path: { type: \"result\", threadId,\n      // text, finishReason, exitCode, ... }. Reading it here (rather than\n      // the incidental om_status event, which only fires when\n      // Observational Memory is enabled) guarantees the thread id is\n      // captured on every turn.\n      if (\n        evt.type === \"result\" &&\n        typeof evt.threadId === \"string\" &&\n        evt.threadId\n      )\n        return evt.threadId\n      return null\n    case \"jcode-ndjson\":\n      // jcode stamps `session_id` on the opening `start` line (available\n      // before any text — so a mid-turn crash still resumes) and again on\n      // the terminal `done` line, which re-confirms it.\n      if (\n        (evt.type === \"start\" || evt.type === \"done\") &&\n        typeof evt.session_id === \"string\" &&\n        evt.session_id\n      )\n        return evt.session_id\n      return null\n  }\n}\n\n// ── Event mapping ───────────────────────────────────────────────────\n\nfunction mapEvent(\n  evt: Record<string, unknown>,\n  sessionId: string,\n  stderrLines: string[],\n  schema: PrintEventSchema,\n  mastraState?: MastraMapperState,\n  jcodeState?: JcodeMapperState,\n): StreamEvent | StreamEvent[] | null {\n  switch (schema) {\n    case \"claude-stream-json\":\n      return mapClaudeEvent(evt, sessionId, stderrLines)\n    case \"antigravity-stream-json\":\n      return mapAntigravityEvent(evt, sessionId, stderrLines)\n    case \"mastra-jsonl\": {\n      if (!mastraState) {\n        // Should never happen — mastra-jsonl schema always creates state\n        return mapClaudeEvent(evt, sessionId, stderrLines)\n      }\n      return mapMastraEvent(evt, sessionId, stderrLines, mastraState)\n    }\n    case \"jcode-ndjson\":\n      return mapJcodeEvent(evt, sessionId, jcodeState ?? createJcodeMapperState())\n    default:\n      return mapClaudeEvent(evt, sessionId, stderrLines)\n  }\n}\n\n// ── Claude Code stream-json mapper ──────────────────────────────────\n\nfunction mapClaudeEvent(\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\"\n                ? evt.error\n                : \"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      return null\n\n    default:\n      return null\n  }\n}\n\n// ── Google Antigravity stream-json mapper ──────────────────────────\n\n/**\n * Maps a single Google Antigravity (`agy --output-format stream-json`)\n * NDJSON line to this repo's {@link StreamEvent} taxonomy.\n *\n * The wire shape was verified against antigravity.google/docs/cli/headless.\n * Despite `agy` mirroring Claude Code's headless FLAGS (`-p`,\n * `--output-format stream-json`, `--continue`), its EVENTS are a different\n * taxonomy discriminated by an `event` field, not Claude's `type`:\n *\n *   {\"event\":\"init\",\"conversation_id\":\"…\",\"init\":{cwd,tools,permission_mode,…}}\n *   {\"event\":\"step_update\",\"step_update\":{conversation_id,step_index,state,\n *       step_type,text_delta?,tool_name?,tool_info?,usage?,…}}\n *   {\"event\":\"result\",\"result\":{conversation_id,status,response,error?,usage,…}}\n *\n * - Text streams as INCREMENTAL `step_update.text_delta` fragments on\n *   `agent_response` steps (the docs' own `jq -j … .text_delta` recipe\n *   concatenates them, so fragments never overlap — emit each verbatim, no\n *   accumulation state needed, unlike the Mastra mapper).\n * - A `tool` step's terminal `DONE` carries the call AND its result in one\n *   `tool_info` ({name, parameters, output, error?}). `agy` assigns no tool\n *   call id, so we synthesize one from `step_index` to correlate the pair.\n *   Returning a two-element array fans that single line out to a `tool-call`\n *   + `tool-result` (the print-arm line handler flattens arrays).\n * - The terminal `result` carries the run's total `usage` and its `status`;\n *   we emit a `usage_update` then the terminal `turn-end`/`error`.\n */\nfunction mapAntigravityEvent(\n  evt: Record<string, unknown>,\n  sessionId: string,\n  stderrLines: string[],\n): StreamEvent | StreamEvent[] | null {\n  switch (evt.event) {\n    case \"step_update\": {\n      const su = evt.step_update as Record<string, unknown> | undefined\n      if (!su) return null\n      const stepType = su.step_type\n\n      // Incremental assistant text.\n      if (\n        stepType === \"agent_response\" &&\n        typeof su.text_delta === \"string\" &&\n        su.text_delta\n      ) {\n        return { kind: \"text-delta\", sessionId, text: su.text_delta }\n      }\n\n      // A completed tool step carries the call and its result together.\n      // Emit the pair only on DONE; a preceding ACTIVE tool step (if any)\n      // is skipped so the call isn't announced twice.\n      if (stepType === \"tool\" && su.state === \"DONE\") {\n        const ti = su.tool_info as Record<string, unknown> | undefined\n        const toolName =\n          typeof su.tool_name === \"string\" && su.tool_name\n            ? su.tool_name\n            : typeof ti?.name === \"string\" && ti.name\n              ? (ti.name as string)\n              : \"?\"\n        const toolCallId =\n          typeof su.step_index === \"number\" ? `step-${su.step_index}` : \"\"\n        const err = ti?.error as Record<string, unknown> | undefined\n        const call: StreamEvent = {\n          kind: \"tool-call\",\n          sessionId,\n          toolCallId,\n          toolName,\n          arguments: ti?.parameters ?? {},\n        }\n        const result: StreamEvent = {\n          kind: \"tool-result\",\n          sessionId,\n          toolCallId,\n          result: err\n            ? typeof err.message === \"string\"\n              ? err.message\n              : err\n            : (ti?.output ?? null),\n          isError: !!err,\n        }\n        return [call, result]\n      }\n\n      // user_input / checkpoint / subagent steps carry no host-facing\n      // StreamEvent — skip them (subagents are surfaced by their own run).\n      return null\n    }\n\n    case \"result\": {\n      const r = evt.result as Record<string, unknown> | undefined\n      if (!r) return null\n      const status = typeof r.status === \"string\" ? r.status : \"\"\n      const out: StreamEvent[] = []\n\n      const usage = mapAntigravityUsage(r.usage, sessionId)\n      if (usage) out.push(usage)\n\n      if (status === \"ERROR\" || status === \"INVALID\") {\n        out.push({\n          kind: \"error\",\n          sessionId,\n          error: {\n            message:\n              typeof r.error === \"string\" && r.error\n                ? r.error\n                : `agy run ended with status ${status || \"ERROR\"}`,\n            ...(stderrLines.length\n              ? { data: { stderr: stderrLines.join(\"\\n\") } }\n              : {}),\n          },\n        })\n      } else {\n        out.push({\n          kind: \"turn-end\",\n          sessionId,\n          reason: mapAntigravityStatus(status),\n        })\n      }\n      return out.length ? out : null\n    }\n\n    // init and any unknown event carry no host-facing StreamEvent.\n    default:\n      return null\n  }\n}\n\n/**\n * Normalize `agy` terminal `result.status` to a StreamEvent turn-end reason.\n * ERROR / INVALID are handled as `error` events upstream, so only the\n * non-error terminal statuses land here.\n */\nfunction mapAntigravityStatus(\n  raw: string,\n): \"completed\" | \"cancelled\" | \"max_turns\" | \"error\" {\n  switch (raw) {\n    case \"CANCELED\":\n    case \"INTERRUPTED\":\n      return \"cancelled\"\n    // SUCCESS, WAITING, RUNNING (or anything else non-error): the turn ended.\n    default:\n      return \"completed\"\n  }\n}\n\n/**\n * Map `agy`'s `result.usage` ({input_tokens, output_tokens, thinking_tokens,\n * cache_read_tokens, total_tokens}) to a `usage_update` StreamEvent. `agy`\n * reports no context-window size/used or per-turn cost here, so those stay 0\n * / absent (the daemon's projector guards on >0 and never clobbers a real\n * size). Returns null when no token counts are present.\n */\nfunction mapAntigravityUsage(\n  usage: unknown,\n  sessionId: string,\n): StreamEvent | null {\n  if (usage === null || typeof usage !== \"object\") return null\n  const u = usage as Record<string, unknown>\n  const tokensIn = typeof u.input_tokens === \"number\" ? u.input_tokens : undefined\n  const tokensOut =\n    typeof u.output_tokens === \"number\" ? u.output_tokens : undefined\n  if (tokensIn === undefined && tokensOut === undefined) return null\n  return {\n    kind: \"usage_update\",\n    sessionId,\n    size: 0,\n    used: 0,\n    ...(tokensIn !== undefined ? { tokensIn } : {}),\n    ...(tokensOut !== undefined ? { tokensOut } : {}),\n  }\n}\n\n// ── jcode NDJSON mapper ─────────────────────────────────────────────\n\n/**\n * Mutable per-stream state for the jcode NDJSON mapper. Tool arguments\n * arrive as JSON-string `tool_input` deltas between `tool_start` and\n * `tool_exec`, so the pending call accumulates here until complete.\n */\nexport interface JcodeMapperState {\n  pending?: { id: string; name: string; input: string }\n}\n\nexport function createJcodeMapperState(): JcodeMapperState {\n  return {}\n}\n\n/**\n * Maps a single `jcode run --ndjson` line to this repo's\n * {@link StreamEvent} taxonomy. Wire shape verified against a live\n * `jcode run --ndjson` (2026-08-14):\n *\n *   {type:\"start\", session_id, model, provider}          → session capture\n *   {type:\"status_detail\"|\"connection_phase\"|\n *    \"connection_type\"|\"message_end\", …}                 → dropped (noise)\n *   {type:\"text_delta\", text}                            → text-delta\n *   {type:\"tool_start\", id, name}                        → open pending call\n *   {type:\"tool_input\", delta}                           → accumulate args\n *   {type:\"tool_exec\", id, name}                         → tool-call\n *   {type:\"tool_done\", id, name, output, error}          → tool-result\n *   {type:\"tokens\", input, output, cache_read_input, …}  → usage_update\n *   {type:\"done\", text, session_id, usage}               → turn-end\n *\n * `tokens` fires once per upstream API call (a tool round-trip produces\n * several), so usage arrives as successive updates, not one total.\n */\nexport function mapJcodeEvent(\n  evt: Record<string, unknown>,\n  sessionId: string,\n  state: JcodeMapperState,\n): StreamEvent | StreamEvent[] | null {\n  switch (evt.type) {\n    case \"text_delta\":\n      return typeof evt.text === \"string\"\n        ? { kind: \"text-delta\", sessionId, text: evt.text }\n        : null\n\n    case \"tool_start\":\n      state.pending = {\n        id: typeof evt.id === \"string\" ? evt.id : \"\",\n        name: typeof evt.name === \"string\" ? evt.name : \"?\",\n        input: \"\",\n      }\n      return null\n\n    case \"tool_input\":\n      if (state.pending && typeof evt.delta === \"string\")\n        state.pending.input += evt.delta\n      return null\n\n    case \"tool_exec\":\n      return flushPendingJcodeCall(state, sessionId)\n\n    case \"tool_done\": {\n      // Defensive: if `tool_exec` never arrived, flush the call here so\n      // the result is never orphaned from its call.\n      const call = flushPendingJcodeCall(state, sessionId)\n      const result: StreamEvent = {\n        kind: \"tool-result\",\n        sessionId,\n        toolCallId: typeof evt.id === \"string\" ? evt.id : \"\",\n        result: evt.output ?? null,\n        isError: evt.error !== null && evt.error !== undefined,\n      }\n      return call ? [call, result] : result\n    }\n\n    case \"tokens\": {\n      const tokensIn = typeof evt.input === \"number\" ? evt.input : undefined\n      const tokensOut = typeof evt.output === \"number\" ? evt.output : undefined\n      if (tokensIn === undefined && tokensOut === undefined) return null\n      // jcode reports no context-window size/used here, so those stay 0\n      // (the daemon's projector guards on >0 and never clobbers a real\n      // size) — same contract as the antigravity usage mapper.\n      return {\n        kind: \"usage_update\",\n        sessionId,\n        size: 0,\n        used: 0,\n        ...(tokensIn !== undefined ? { tokensIn } : {}),\n        ...(tokensOut !== undefined ? { tokensOut } : {}),\n      }\n    }\n\n    case \"done\":\n      return { kind: \"turn-end\", sessionId, reason: \"completed\" }\n\n    default:\n      return null\n  }\n}\n\nfunction flushPendingJcodeCall(\n  state: JcodeMapperState,\n  sessionId: string,\n): StreamEvent | null {\n  const pending = state.pending\n  state.pending = undefined\n  if (!pending) return null\n  let args: unknown\n  try {\n    args = JSON.parse(pending.input)\n  } catch {\n    args = { raw: pending.input }\n  }\n  return {\n    kind: \"tool-call\",\n    sessionId,\n    toolCallId: pending.id,\n    toolName: pending.name,\n    arguments: args,\n  }\n}\n\n// ── Mastra Code JSONL mapper ────────────────────────────────────────\n\n/**\n * Mutable per-stream state for the Mastra Code event mapper.\n * Mastra Code sends the FULL accumulated text on each `message_update`,\n * so we track the previous length to emit only the new portion.\n *\n * Exported so other Mastra Code protocol arms (e.g. the in-process\n * `proprietary` arm in `@agentproto/adapter-mastracode-inprocess`) can\n * reuse the same event mapper instead of reimplementing it — the wire\n * shape here is `AgentControllerEvent` regardless of whether it arrived\n * over a JSONL subprocess pipe or as a live in-process object.\n */\nexport interface MastraMapperState {\n  lastTextLength: number\n}\n\nexport function createMastraMapperState(): MastraMapperState {\n  return { lastTextLength: 0 }\n}\n\n/**\n * Extract text from Mastra Code content blocks.\n * Blocks are normally a `{ type: \"text\", text: \"...\" }` array directly on\n * `message.content`, but newer Mastra Code builds wrap them in an object —\n * `{ format: 2, parts: [...] }` — so unwrap that shape to the blocks array\n * first.\n */\nfunction extractTextFromBlocks(\n  content: unknown,\n): string {\n  let blocks = content\n  if (\n    blocks !== null &&\n    typeof blocks === \"object\" &&\n    !Array.isArray(blocks) &&\n    Array.isArray((blocks as Record<string, unknown>).parts)\n  ) {\n    blocks = (blocks as Record<string, unknown>).parts\n  }\n  if (!Array.isArray(blocks)) return \"\"\n  return (blocks as Array<Record<string, unknown>>)\n    .filter(c => c.type === \"text\" && typeof c.text === \"string\")\n    .map(c => c.text as string)\n    .join(\"\")\n}\n\n/**\n * Maps a single Mastra Code `AgentControllerEvent` (already a plain\n * object — JSON-parsed from a subprocess line, or handed over directly\n * by an in-process arm) to this repo's {@link StreamEvent} taxonomy.\n * `stderrLines` enriches `error` events for arms that have a real\n * subprocess to report on; pass `[]` when there is none (e.g. the\n * in-process arm).\n */\nexport function mapMastraEvent(\n  evt: Record<string, unknown>,\n  sessionId: string,\n  stderrLines: string[],\n  state: MastraMapperState,\n): StreamEvent | null {\n  switch (evt.type) {\n    // ── Text streaming ──────────────────────────────────────────\n    case \"message_update\": {\n      const content = (evt.message as Record<string, unknown>)?.content\n      const fullText = extractTextFromBlocks(content)\n      if (fullText.length > state.lastTextLength) {\n        const delta = fullText.slice(state.lastTextLength)\n        state.lastTextLength = fullText.length\n        return delta ? { kind: \"text-delta\", sessionId, text: delta } : null\n      }\n      return null\n    }\n\n    case \"message_end\": {\n      const msg = evt.message as Record<string, unknown> | undefined\n      if (msg?.role !== \"assistant\") return null\n      const fullText = extractTextFromBlocks(msg?.content)\n      // Emit any remaining text not covered by message_update deltas\n      if (fullText.length > state.lastTextLength) {\n        const delta = fullText.slice(state.lastTextLength)\n        state.lastTextLength = fullText.length\n        return delta ? { kind: \"text-delta\", sessionId, text: delta } : null\n      }\n      return null\n    }\n\n    // ── Tool calls ──────────────────────────────────────────────\n    case \"tool_start\":\n      return {\n        kind: \"tool-call\",\n        sessionId,\n        toolCallId:\n          typeof evt.toolCallId === \"string\" ? evt.toolCallId : \"\",\n        toolName:\n          typeof evt.toolName === \"string\" ? evt.toolName : \"?\",\n        // Mastra's controller event carries the tool call payload under\n        // `args`, not `input` (that's the Claude Code stream-json field\n        // name used by the sibling mapClaudeEvent tool_use case below).\n        arguments: evt.args ?? {},\n      }\n\n    case \"tool_end\":\n      return {\n        kind: \"tool-result\",\n        sessionId,\n        toolCallId:\n          typeof evt.toolCallId === \"string\" ? evt.toolCallId : \"\",\n        result: evt.result ?? null,\n        isError: evt.isError === true,\n      }\n\n    // ── Turn end ────────────────────────────────────────────────\n    case \"agent_end\": {\n      const rawReason =\n        typeof evt.reason === \"string\"\n          ? evt.reason\n          : \"complete\"\n      const reason = mapMastraFinishReason(rawReason)\n      return { kind: \"turn-end\", sessionId, reason }\n    }\n\n    // ── Final result line ────────────────────────────────────────\n    // Always written last, once, whether or not `agent_end` fired —\n    // pre-flight failures (bad model, unresolvable thread, missing API\n    // key) call straight into this without ever streaming an\n    // `agent_end` or `error` event. `turn-end` already came from\n    // `agent_end` on the success path, so this only needs to surface\n    // an error for the pre-flight-failure path.\n    case \"result\": {\n      const err = evt.error as Record<string, unknown> | undefined\n      if (!err) return null\n      return {\n        kind: \"error\",\n        sessionId,\n        error: {\n          message:\n            typeof err.message === \"string\" ? err.message : \"Unknown error\",\n          ...(stderrLines.length\n            ? { data: { stderr: stderrLines.join(\"\\n\") } }\n            : {}),\n        },\n      }\n    }\n\n    // ── Errors ─────────────────────────────────────────────────\n    case \"error\": {\n      const err = evt.error as Record<string, unknown> | undefined\n      return {\n        kind: \"error\",\n        sessionId,\n        error: {\n          message:\n            typeof err?.message === \"string\"\n              ? err.message\n              : \"Unknown error\",\n          ...(stderrLines.length\n            ? { data: { stderr: stderrLines.join(\"\\n\") } }\n            : {}),\n        },\n      }\n    }\n\n    // ── Token usage ─────────────────────────────────────────────\n    // Mastra Code DOES expose usage: its `AgentController` emits a native\n    // `usage_update` event ({ type: \"usage_update\", usage: TokenUsage })\n    // on every model step-finish — verified against @mastra/core 1.48.0's\n    // AgentControllerEvent union and its emit site\n    // (`this.#session.emit({ type: \"usage_update\", usage: stepUsage })`).\n    // `TokenUsage` carries `{ promptTokens, completionTokens, totalTokens }`.\n    // Map it to this repo's `usage_update` StreamEvent (the SAME shape\n    // claude-code emits over ACP) so mastracode sessions — both the print\n    // arm and the in-process arm, which share this mapper — carry token\n    // telemetry in the transcript. mastracode reports these cumulatively\n    // (its own headless `runMC` result-usage is last-write-wins over these\n    // events), and last-write-wins on the descriptor matches that. It\n    // carries no context-window size/used or per-turn cost here, so those\n    // stay 0 / absent (projectEvent guards on >0, never clobbering a real\n    // size).\n    case \"usage_update\": {\n      const usage = evt.usage as Record<string, unknown> | undefined\n      const promptTokens =\n        typeof usage?.promptTokens === \"number\" ? usage.promptTokens : undefined\n      const completionTokens =\n        typeof usage?.completionTokens === \"number\"\n          ? usage.completionTokens\n          : undefined\n      if (promptTokens === undefined && completionTokens === undefined)\n        return null\n      return {\n        kind: \"usage_update\",\n        sessionId,\n        size: 0,\n        used: 0,\n        ...(promptTokens !== undefined ? { tokensIn: promptTokens } : {}),\n        ...(completionTokens !== undefined\n          ? { tokensOut: completionTokens }\n          : {}),\n      }\n    }\n\n    // ── Shell output (tool-like) ────────────────────────────────\n    case \"shell_output\":\n      return typeof evt.output === \"string\"\n        ? {\n            kind: \"tool-result\",\n            sessionId,\n            toolCallId: \"\",\n            result: evt.output,\n            isError: false,\n          }\n        : null\n\n    // ── Skipped events ─────────────────────────────────────────\n    case \"agent_start\":\n    case \"subagent_start\":\n    case \"subagent_end\":\n    case \"tool_approval_required\":\n    case \"tool_suspended\":\n      return null\n\n    default:\n      return null\n  }\n}\n\n// ── Decoupling queue ────────────────────────────────────────────────\n\n/**\n * High-water mark (in buffered events) at which {@link EventQueue} logs a\n * single warning. This does NOT cap the buffer or drop events: the whole\n * point of this queue is to keep draining `child.stdout` so the subprocess\n * never hits `ENOBUFS`, and dropping mapped events would corrupt the\n * transcript / ring buffer this feeds. The mark exists purely to make a\n * genuinely stuck downstream consumer (one that has stopped pulling for an\n * extended period, letting the buffer grow toward a memory problem)\n * observable to operators instead of failing silently.\n *\n * Sized well above the worst incident seen in the wild (a mastracode run\n * emitting ~1200 lines / ~900 tool results): a transient burst is absorbed\n * without noise, while a persistently slow client trips the warning.\n */\nconst QUEUE_HIGH_WATER_MARK = 10_000\n\n/**\n * A bounded-signal async FIFO that decouples a fast push-side producer\n * (readline draining a subprocess pipe) from a slow pull-side consumer\n * (the daemon's event projector → transcript + ring buffer + SSE stream).\n *\n * `push()` never blocks and never rejects — the producer keeps draining\n * the OS pipe so the child never backpressures into `ENOBUFS`. The\n * consumer drives it as an async iterable; each `next()` resolves as soon\n * as an event is available (or immediately if one is already buffered),\n * and completes once {@link end} is called and the buffer is exhausted.\n *\n * Backpressure is applied to the CONSUMER, not the producer: the iterator\n * only advances when the caller pulls. If the caller stops pulling for a\n * long time the buffer grows; crossing {@link QUEUE_HIGH_WATER_MARK} emits\n * one warning so the condition is never silent (see the constant's doc for\n * why we favour bounded-visibility growth over dropping events).\n */\nclass EventQueue implements AsyncIterable<StreamEvent> {\n  private readonly buffer: StreamEvent[] = []\n  private resolveNext: (() => void) | null = null\n  private ended = false\n  private highWaterWarned = false\n\n  push(evt: StreamEvent): void {\n    this.buffer.push(evt)\n    if (\n      this.buffer.length > QUEUE_HIGH_WATER_MARK &&\n      !this.highWaterWarned\n    ) {\n      this.highWaterWarned = true\n      console.warn(\n        `print-arm: event backlog exceeded ${QUEUE_HIGH_WATER_MARK} ` +\n          `buffered events — downstream consumer is not keeping up. The ` +\n          `child's stdout is still being drained (no ENOBUFS), but memory ` +\n          `will grow until the consumer catches up.`,\n      )\n    }\n    // Wake a consumer parked in next().\n    const resolve = this.resolveNext\n    this.resolveNext = null\n    resolve?.()\n  }\n\n  /** Signal that no further events will be pushed. */\n  end(): void {\n    this.ended = true\n    const resolve = this.resolveNext\n    this.resolveNext = null\n    resolve?.()\n  }\n\n  async *[Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n    for (;;) {\n      const evt = this.buffer.shift()\n      if (evt !== undefined) {\n        yield evt\n        continue\n      }\n      if (this.ended) return\n      // Nothing buffered and not ended — park until push()/end() wakes us.\n      await new Promise<void>(resolve => {\n        this.resolveNext = resolve\n      })\n    }\n  }\n}\n\n// ── Process helpers ─────────────────────────────────────────────────\n\n/**\n * Normalize Mastra Code `agent_end.finishReason` to StreamEvent turn-end reason.\n * Mastra uses: \"complete\", \"aborted\", \"error\", \"suspended\"\n * StreamEvent expects: \"completed\", \"cancelled\", \"error\", \"max_turns\"\n */\nfunction mapMastraFinishReason(\n  raw: string,\n): \"completed\" | \"cancelled\" | \"max_turns\" | \"error\" {\n  switch (raw) {\n    case \"complete\":\n      return \"completed\"\n    case \"aborted\":\n    case \"suspended\":\n      return \"cancelled\"\n    case \"error\":\n      return \"error\"\n    default:\n      return \"completed\"\n  }\n}\n\nfunction waitForExit(\n  child: ReturnType<typeof spawn>,\n): 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 * AIP-45 protocol arm: `protocol: \"proprietary\"`.\n *\n * Loads an NPM adapter package (named in the manifest's `adapter`\n * field) implementing `AgentCliClient`. The package translates the\n * vendor's REPL/proprietary stream into the canonical StreamEvent\n * taxonomy.\n *\n * Unlike the `acp` / `print` arms (built into this package, driving a\n * spawned subprocess), a proprietary arm may not involve a subprocess\n * at all — e.g. an in-process SDK integration. `createAgentCliRuntime`\n * skips the subprocess spawn entirely for `protocol: \"proprietary\"`\n * (see `define-agent-cli.ts`); this loader has no opinion on whether\n * the loaded package owns a child process, a socket, or nothing.\n *\n * ## Adapter package contract\n *\n * The named package's default export path (its `main`/`exports[\".\"]`)\n * must export a factory:\n *\n *   export function createAgentCliClient(\n *     definition: AgentCliHandle,\n *   ): AgentCliClient | Promise<AgentCliClient>\n *\n * A default export function is accepted as a fallback for adapters\n * that only have one thing to export. The factory receives the full\n * manifest handle so adapter-specific config (models, capabilities,\n * metadata) is available without a second lookup — mirrors the ACP\n * arm receiving `clientInfo` derived from the manifest.\n */\n\nimport { isAbsolute } from \"node:path\"\nimport { pathToFileURL } from \"node:url\"\nimport type { AgentCliClient, AgentCliHandle } from \"../types.js\"\n\nexport interface ProprietaryProtocolOptions {\n  /** NPM package name to load — from manifest.adapter. */\n  adapter: string\n  /** Full manifest handle, forwarded verbatim to the loaded factory. */\n  definition: AgentCliHandle\n}\n\ntype AgentCliClientFactory = (\n  definition: AgentCliHandle,\n) => AgentCliClient | Promise<AgentCliClient>\n\nexport async function createProprietaryProtocolArm(\n  options: ProprietaryProtocolOptions,\n): Promise<AgentCliClient> {\n  let mod: Record<string, unknown>\n  try {\n    // `withResolvedProprietaryAdapter` (packages/cli/src/registry/resolve.ts)\n    // may hand us an ABSOLUTE filesystem path (adapter resolved to a real\n    // .js/.cjs/.mjs file). A dynamic `import()` of such a path works on\n    // POSIX (the loader resolves it against cwd) but fails on win32 with\n    // `ERR_UNSUPPORTED_ESM_URL_SCHEME` / `Received protocol 'c:'` — the\n    // WIN11 field test in issue #1637. Rewriting absolute paths to\n    // `file://` URLs is behavior-identical on POSIX and fixes win32; a\n    // bare package specifier (no absolute path) imports as-is.\n    const target = isAbsolute(options.adapter)\n      ? pathToFileURL(options.adapter).href\n      : options.adapter\n    mod = (await import(target)) as Record<string, unknown>\n  } catch (err) {\n    const cause = err instanceof Error ? err.message : String(err)\n    throw new Error(\n      `createProprietaryProtocolArm: could not load adapter package '${options.adapter}'. ` +\n        `Install it with: npm i ${options.adapter}\\n  cause: ${cause}`,\n    )\n  }\n\n  const candidate =\n    \"createAgentCliClient\" in mod ? mod.createAgentCliClient : mod.default\n  if (typeof candidate !== \"function\") {\n    throw new Error(\n      `createProprietaryProtocolArm: adapter package '${options.adapter}' does not export a ` +\n        `'createAgentCliClient' factory function (or a default export function). A ` +\n        `protocol=\"proprietary\" adapter must export ` +\n        `createAgentCliClient(definition: AgentCliHandle): AgentCliClient | Promise<AgentCliClient>.`,\n    )\n  }\n\n  return await (candidate as AgentCliClientFactory)(options.definition)\n}\n","/**\n * Legacy AIP-45 mode-id classification — the SINGLE SOURCE for recognizing the\n * gateway (route) and permission (posture) ids that used to be declared as\n * `modes[]` entries before the SPEC §3.4a route/posture extraction.\n *\n * Those entries are now deleted from the adapter manifests: route is derived\n * from the model catalog's `@route` route-identity and posture comes from the\n * harness's own ACP mode registry (`SessionModeState.availableModes`) plus the\n * canonical-posture layer (step 2c). But a caller may STILL pass one of the old\n * ids as `config.mode` — a persisted OPERATOR.md `runtime.config.mode`, a\n * `defaults.adapters.<slug>` binding, or an in-flight request written against\n * the pre-migration manifest. Both the compose path (`composeSpawn`) and the\n * daemon-boundary shim (`@agentproto/runtime`'s `decomposeMode`) therefore need\n * to recognize the legacy vocabulary. `@agentproto/runtime` imports this module\n * rather than re-hardcoding the list, so the id→axis classification stays\n * single-sourced across the driver/runtime boundary (runtime → driver only; the\n * driver stays lean, never depending back on the runtime).\n *\n * This module classifies onto the AXIS only (`route`/`posture`/`context`); the\n * canonical-posture value mapping (`bypass-permissions` → `bypass`, …) is a\n * daemon concept and lives in `@agentproto/runtime`, keyed by\n * {@link LEGACY_POSTURE_MODE_IDS}.\n */\n\n/** Gateway-preset ids that were declared as `kind:\"route\"` modes. */\nexport const LEGACY_GATEWAY_MODE_IDS: ReadonlySet<string> = new Set([\n  \"moonshot\",\n  \"openrouter\",\n  \"requesty\",\n  \"deepseek\",\n])\n\n/**\n * Permission-profile ids that were declared as `kind:\"posture\"` modes across\n * the claude-code / codex / opencode adapters (the superset over adapters —\n * some ids are another adapter's vocabulary: codex's `full-access`, opencode's\n * `build`).\n */\nexport const LEGACY_POSTURE_MODE_IDS: ReadonlySet<string> = new Set([\n  \"default\",\n  \"plan\",\n  \"accept-edits\",\n  \"bypass-permissions\",\n  \"read-only\",\n  \"full-access\",\n  \"build\",\n])\n\n/**\n * Classify a legacy mode id onto its orthogonal axis. Gateway ids ⇒ `\"route\"`,\n * known permission ids ⇒ `\"posture\"`, everything else ⇒ `\"context\"` — the\n * least-privilege default, so a truly-unknown id never silently grants a\n * posture or reroutes billing (SPEC R4).\n */\nexport function inferLegacyModeKind(\n  modeId: string,\n): \"posture\" | \"route\" | \"context\" {\n  if (LEGACY_GATEWAY_MODE_IDS.has(modeId)) return \"route\"\n  if (LEGACY_POSTURE_MODE_IDS.has(modeId)) return \"posture\"\n  return \"context\"\n}\n\n/**\n * True when `modeId` is a KNOWN legacy route-or-posture id that used to be a\n * `modes[]` entry but was extracted (SPEC §3.4a) — i.e. it classifies as\n * `route` or `posture`, not `context` and not a genuinely-unknown id.\n * `composeSpawn` degrades such an id to a soft no-op (no env/argv patch: route\n * now resolves from the catalog, posture from the ACP registry / canonical\n * layer) instead of throwing `unknown_mode`; a truly-unknown id — for which\n * this returns `false` — still throws.\n */\nexport function isLegacyExtractedModeId(modeId: string): boolean {\n  return (\n    LEGACY_GATEWAY_MODE_IDS.has(modeId) || LEGACY_POSTURE_MODE_IDS.has(modeId)\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. Every declared `bin_args_prepend` (mode's, then each present\n *      option's in declaration order) — argv that must precede a\n *      subcommand baked into `bin_args` (e.g. hermes'\n *      `--ignore-user-config` ahead of `acp`).\n *   2. Manifest's default `bin_args` (from `handle.bin_args`).\n *   3. Every declared `bin_args_append` / `bin_args_append_when_true`\n *      / `bin_args_template` (mode's, then each present option's in\n *      declaration order), then finally `models.bin_args_template`\n *      when `models.apply === \"arg\"` and a model was requested — a CLI arg,\n *      not an ACP session config.\n * Final argv is `[...prepend, ...bin_args, ...append]`.\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\"\nimport { isLegacyExtractedModeId } from \"../legacy-modes.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    | \"model_denied\"\n    | \"missing_auth_credential\"\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   * Env keys the active mode AND active options declared for deletion\n   * (AgentCliMode.env_unset / AgentCliOption.env_unset). Surfaced\n   * pure-side so the runtime's `start()` — which owns the process.env\n   * merge — can apply the deletions at the one point where the ambient\n   * env is actually present (compose starts from `{}` and can't delete\n   * what isn't there yet). Empty when nothing declares any.\n   */\n  envUnset: string[]\n}\n\n/**\n * Optional spawn-time hints that are outside the pure runtime config.\n * Today the only consumer is auth-aware codex model handling: the\n * composer can be told to skip `models.apply:\"arg\"` when the caller has\n * already determined that the current auth mode must preserve the CLI's\n * default model.\n */\nexport interface ComposeSpawnOptions {\n  skipModelArg?: boolean\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  opts?: ComposeSpawnOptions\n): ComposedSpawn {\n  if (!config)\n    return {\n      binArgs: [...(handle.bin_args ?? [])],\n      env: { ...(handle.env ?? {}) },\n      envUnset: [],\n    }\n\n  const prepend: string[] = []\n  const append: string[] = []\n  // Always-on manifest env goes in first so a selected mode/option can\n  // still override any key it also declares (mode/option intent wins).\n  const env: Record<string, string> = { ...(handle.env ?? {}) }\n  const envUnset: string[] = []\n\n  // ── Mode patch ──────────────────────────────────────────────────\n  if (config.mode !== undefined) {\n    const mode = (handle.modes ?? []).find(m => m.id === config.mode)\n    if (!mode) {\n      // Back-compat (SPEC §3.4a route/posture extraction): route and posture\n      // are no longer manifest `modes[]` entries — route resolves from the\n      // model catalog `@route`, posture from the harness ACP mode registry /\n      // canonical-posture layer. A caller can still pass one of those extracted\n      // legacy ids as `config.mode` (a persisted OPERATOR.md\n      // `runtime.config.mode`, a `defaults.adapters.<slug>` binding, an\n      // in-flight request written against the pre-migration manifest), so a\n      // KNOWN legacy route/posture id DEGRADES to a soft no-op here — its\n      // env/argv patch is gone, and the axis it targeted is applied elsewhere\n      // (or, until step 2c lands, dormant) — rather than hard-failing the spawn.\n      // Only a genuinely-unknown id (never a valid mode) still throws. The\n      // legacy-id set is single-sourced in `../legacy-modes`, shared with the\n      // daemon's `decomposeMode` shim so the two can't drift.\n      if (!isLegacyExtractedModeId(config.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      // Known legacy extracted id → soft no-op: fall through with no mode patch.\n    } else if ((mode.apply ?? \"bin_args\") === \"bin_args\") {\n      // \"config\" modes have no argv/env surface — the CLI doesn't accept a\n      // flag for this mode at all (e.g. opencode's plan/build). The mode id\n      // is instead forwarded to the ACP arm's connect({mode}) by\n      // define-agent-cli.ts and applied via session/set_config_option. Skip\n      // bin_args_prepend/bin_args_append/env here even if an author declared\n      // them alongside apply:\"config\" — config wins, argv is never composed,\n      // so a typo'd flag can't crash the spawn the way this whole bug did.\n      if (mode.bin_args_prepend) prepend.push(...mode.bin_args_prepend)\n      if (mode.bin_args_append) append.push(...mode.bin_args_append)\n      if (mode.env) Object.assign(env, mode.env)\n      if (mode.env_unset) envUnset.push(...mode.env_unset)\n    }\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      prepend.push(...patch.prepend)\n      append.push(...patch.append)\n      Object.assign(env, patch.env)\n      if (patch.envUnset.length) envUnset.push(...patch.envUnset)\n    }\n  }\n\n  // ── Model deny-list enforcement ─────────────────────────────────\n  // The `model` option is deliberately free-form (any provider id), so\n  // `models.allowed` is only a curated menu — it can't *prevent* a caller\n  // from passing an off-menu id. `models.deny` is the hard guardrail: a\n  // requested model matching any deny pattern is refused here, before we\n  // spawn anything, so a budget adapter can't be steered onto a provider it\n  // must never use (e.g. Anthropic models are reserved for claude-code).\n  const requestedModel = config.options?.model\n  if (typeof requestedModel === \"string\" && handle.models?.deny?.length) {\n    const denyHit = handle.models.deny.find(pattern =>\n      matchesModelPattern(pattern, requestedModel)\n    )\n    if (denyHit) {\n      throw new RuntimeConfigError(\n        \"model_denied\",\n        \"config.options.model\",\n        `Model '${requestedModel}' is denied by manifest '${handle.id}' (matches deny pattern '${denyHit}'). This adapter deliberately does not route to that provider — use a permitted model or a different adapter.`\n      )\n    }\n  }\n\n  // ── Model apply:\"arg\" — CLI-argument model selection ────────────\n  // For adapters whose wrapper takes its model as a CLI arg rather than\n  // an ACP session config, compose\n  // the manifest's `models.bin_args_template` here with `{model}`\n  // interpolated. define-agent-cli.ts reads `models.apply` and only\n  // forwards `model` into the ACP connect() call for \"config\" — \"arg\"\n  // never reaches the ACP layer at all, so this is the only place the\n  // requested model is actually applied.\n  if (\n    typeof requestedModel === \"string\" &&\n    handle.models?.apply === \"arg\" &&\n    handle.models.bin_args_template &&\n    !opts?.skipModelArg\n  ) {\n    append.push(\n      ...handle.models.bin_args_template.map(token =>\n        token.replace(\"{model}\", requestedModel)\n      )\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 {\n    binArgs: [...prepend, ...(handle.bin_args ?? []), ...append],\n    env,\n    envUnset,\n  }\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\n/**\n * Case-insensitive match of a model id against a deny/allow pattern.\n * Supports a single trailing `*` wildcard (prefix match); otherwise exact.\n */\nfunction matchesModelPattern(pattern: string, modelId: string): boolean {\n  const p = pattern.toLowerCase()\n  const m = modelId.toLowerCase()\n  return p.endsWith(\"*\") ? m.startsWith(p.slice(0, -1)) : m === p\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): { prepend: string[]; append: string[]; env: Record<string, string>; envUnset: 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. Booleans\n  // have no prepend counterpart — `bin_args_append_when_true` is for\n  // bare flags, which never need to precede a baked-in subcommand.\n  if (option.type === \"boolean\") {\n    if (value !== true) return { prepend: [], append: [], env: {}, envUnset: [] }\n    return {\n      prepend: [],\n      append: option.bin_args_append_when_true\n        ? [...option.bin_args_append_when_true]\n        : [],\n      env: option.env ? interpolateEnv(option.env, stringValue) : {},\n      envUnset: option.env_unset ? [...option.env_unset] : [],\n    }\n  }\n\n  // value-bearing types — apply `bin_args_prepend` / `bin_args_template`\n  // (with `{value}` interpolation) and merge `env`. `env_unset` applies\n  // whenever the option is active with a non-default value (the same\n  // condition under which `env` merges) — so a `base_url` option, e.g.,\n  // scrubs the ambient ANTHROPIC_API_KEY the moment it's set.\n  return {\n    prepend: option.bin_args_prepend\n      ? option.bin_args_prepend.map(token =>\n          token.replace(/\\{value\\}/g, stringValue)\n        )\n      : [],\n    append: 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    envUnset: option.env_unset ? [...option.env_unset] : [],\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 { realpathSync } from \"node:fs\"\nimport { dirname, resolve } from \"node:path\"\n\n/** Adapters with a verified switch for excluding host instruction files. */\nexport function agentCliSupportsHostContextIsolation(adapterId: string): boolean {\n  return adapterId === \"claude-code\"\n}\n\n// claudeMdExcludes entries are picomatch globs, so a literal path with glob\n// metacharacters must be escaped or it silently matches nothing.\nfunction escapeGlob(p: string): string {\n  return p.replace(/[\\\\*?[\\]{}()!+@]/g, \"\\\\$&\")\n}\n\nfunction ancestors(dir: string): string[] {\n  const out: string[] = []\n  let cur = dirname(dir)\n  for (;;) {\n    out.push(cur)\n    const parent = dirname(cur)\n    if (parent === cur) return out\n    cur = parent\n  }\n}\n\n/**\n * `claudeMdExcludes` entries covering every instruction file Claude Code\n * would load from a STRICT ancestor of `cwd` (the host monorepo around an\n * installed app). `cwd`'s own CLAUDE.md is deliberately left loadable — it\n * is the app's. Both the lexical and the symlink-resolved ancestor chains\n * are covered, since the SDK may walk either.\n */\nexport function hostContextExcludes(cwd: string): string[] {\n  const abs = resolve(cwd)\n  let real = abs\n  try {\n    real = realpathSync(abs)\n  } catch {\n    // cwd not created yet — the lexical chain is all there is\n  }\n  const dirs = new Set([...ancestors(abs), ...ancestors(real)])\n  const out: string[] = []\n  for (const d of dirs) {\n    const base = d === \"/\" ? \"\" : escapeGlob(d)\n    out.push(\n      `${base}/CLAUDE.md`,\n      `${base}/CLAUDE.local.md`,\n      `${base}/.claude/CLAUDE.md`,\n      `${base}/.claude/rules/**`,\n    )\n  }\n  return out\n}\n","/**\n * Live-session control surface, built once from a connected protocol arm.\n *\n * `AgentCliRuntimeSession` requires six members beyond\n * `send`/`cancel`/`close`: the three mid-session switches (`setModel`,\n * `setSessionMode`, `setEffort`, SPEC §3.9/§3.4a) and the three\n * read-surface snapshots (`availableConfigOptions`, `availableModes`,\n * `currentModeId`). All six are pure delegation to the arm — none of\n * them touch the child process, the spawn, or the transport.\n *\n * They used to live inline inside `createAgentCliRuntime`, which made\n * them unreachable for any host that builds its OWN session over a\n * different transport. Those hosts exist and are the whole point of\n * `createAcpProtocolArm` being exported: guilde runs one runtime whose\n * child lives in an e2b sandbox and another whose child lives on a\n * remote daemon behind a WS tunnel, both driving the same ACP arm. Every\n * such host had to hand-copy this block, and silently broke the day the\n * interface grew a seventh member.\n *\n * So it lives here, exported, and `createAgentCliRuntime` consumes it\n * like everyone else — one implementation, one place to extend.\n */\n\nimport { randomUUID } from \"node:crypto\"\nimport type {\n  AgentCliClient,\n  AgentCliHandle,\n  AgentCliRuntimeSession,\n  SetModelResult,\n  StreamEvent,\n} from \"./types.js\"\n\n/**\n * The slice of `AgentCliRuntimeSession` {@link createArmSessionControls}\n * supplies. Spread it into the session literal alongside the\n * transport-specific `sessionId`/`send`/`cancel`/`close`.\n */\nexport type ArmSessionControls = Pick<\n  AgentCliRuntimeSession,\n  | \"setModel\"\n  | \"setSessionMode\"\n  | \"setEffort\"\n  | \"availableConfigOptions\"\n  | \"availableModes\"\n  | \"currentModeId\"\n>\n\n/**\n * Build the control surface from a CONNECTED arm.\n *\n * Call this after `arm.connect()` has resolved: the read-surface fields\n * are snapshots, so an ACP arm's captured `newSession`/`loadSession`\n * response has to already be populated. Arms that don't model this\n * (print, proprietary) leave the getters undefined and are defaulted\n * here to the same empty/absent shape their `setModel`-style\n * counterparts use for \"not supported\".\n *\n * Every switch resolves — none throws, none tears down the session, even\n * when the underlying agent rejects the request. See\n * {@link SetModelResult} and friends for the reason vocabulary.\n */\nexport function createArmSessionControls(\n  arm: AgentCliClient,\n  definition: AgentCliHandle,\n): ArmSessionControls {\n  const modelApply = definition.models?.apply ?? \"config\"\n\n  return {\n    // Capability read-surface (SPEC §3.9/§3.4a) — snapshotted once\n    // `arm.connect()` has resolved. Not live-updated by a later\n    // `setModel`/`setSessionMode` call.\n    availableConfigOptions: arm.availableConfigOptions ?? [],\n    availableModes: arm.availableModes ?? [],\n    currentModeId: arm.currentModeId,\n\n    /**\n     * Mid-session model switch — the runtime counterpart to the\n     * spawn-time model apply. Dispatches on the same\n     * `definition.models.apply` strategy so a live switch behaves\n     * exactly like the spawn-time apply would have, just against an\n     * already-running session.\n     */\n    async setModel(modelId: string): Promise<SetModelResult> {\n      if (modelApply === \"arg\") {\n        // This CLI takes its model as a spawn-time argv token\n        // (bin_args_template, composed once before spawn) — there is\n        // no live surface to change it against a running session.\n        return { applied: false, reason: \"requires-restart\" }\n      }\n      if (modelApply === \"command\") {\n        return applyModelCommand(arm, modelId)\n      }\n      // \"config\" (default): apply via the arm's setConfigOption, which\n      // only the ACP arm implements — other arms (print, proprietary)\n      // simply don't have a mid-session config surface.\n      if (!arm.setConfigOption) {\n        return { applied: false, reason: \"not-supported\" }\n      }\n      const result = await arm.setConfigOption(\"model\", modelId)\n      return result.applied\n        ? { applied: true, model: modelId }\n        : { applied: false, ...(result.reason ? { reason: result.reason } : {}) }\n    },\n\n    /**\n     * Mid-session posture switch — the native-mode counterpart to\n     * `setModel`, wired directly to the arm's `setSessionMode` (only the\n     * ACP arm implements it).\n     */\n    async setSessionMode(modeId: string) {\n      if (!arm.setSessionMode) {\n        return { applied: false, reason: \"not-supported\" }\n      }\n      const result = await arm.setSessionMode(modeId)\n      return result.applied\n        ? { applied: true, modeId }\n        : { applied: false, ...(result.reason ? { reason: result.reason } : {}) }\n    },\n\n    /**\n     * Mid-session effort switch — the effort-axis counterpart to\n     * `setModel`'s `\"config\"` strategy, wired to the same\n     * `arm.setConfigOption` surface with `configId:\"effort\"`. Best-effort:\n     * an effort label the current model rejects resolves\n     * `{applied:false, reason}` (SPEC risk R7).\n     */\n    async setEffort(effort: string) {\n      if (!arm.setConfigOption) {\n        return { applied: false, reason: \"not-supported\" }\n      }\n      const result = await arm.setConfigOption(\"effort\", effort)\n      return result.applied\n        ? { applied: true, effort }\n        : { applied: false, ...(result.reason ? { reason: result.reason } : {}) }\n    },\n  }\n}\n\n/**\n * Loose acknowledgement match shared by `applyModelCommand`'s dedicated\n * control turn below AND the ordinary-prompt learn-path\n * (`@agentproto/runtime`'s `sessions.ts` `runAgentTurn`, which watches a\n * plain `/model <id>` typed as a normal conversational turn — the shape the\n * hermes spawn recipe's `/model` shortcut actually sends today, since it\n * never goes through this control turn). Hermes replies \"Model switched to:\n * <id> · Provider: …\"; other adapters phrase it differently, so this is\n * deliberately lax rather than coupled to one adapter's wording or a\n * specific `StreamEvent` shape.\n *\n * REPORTED BY THE ADAPTER, NOT INDEPENDENTLY VERIFIED — good enough as a\n * display hint (`SessionDescriptor.activeModel`), never as a source of\n * billing/cost truth. A caller that ever reads `activeModel` for cost\n * purposes must know it read a heuristic, not a fact.\n */\nexport const MODEL_SWITCH_ACK_RE = /switch|model\\s+set|now using/i\n\n/** See {@link MODEL_SWITCH_ACK_RE}. */\nexport function isModelSwitchAcknowledgement(evt: unknown): boolean {\n  return MODEL_SWITCH_ACK_RE.test(JSON.stringify(evt))\n}\n\n/**\n * Extract the target model id from a plain-text turn that opens with a\n * `/model <id>` control command — whether it arrives through\n * `applyModelCommand`'s dedicated control turn or as an ORDINARY\n * conversational prompt (see {@link MODEL_SWITCH_ACK_RE}'s doc for why the\n * latter matters: it's the case the hermes spawn recipe actually produces).\n */\nexport function parseModelSwitchCommand(text: string): string | undefined {\n  return /^\\s*\\/model\\s+(\\S+)/i.exec(text)?.[1]\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 next real turn. Best-effort: a transport\n * failure or a missing acknowledgement is warned and reported as\n * `{applied:false, reason}`, never thrown — the session simply continues\n * on whatever model it already had. Shared by the spawn-time apply\n * (return value ignored there) and the mid-session `setModel(\"command\")`\n * path (return value surfaced to the caller).\n */\nexport async function applyModelCommand(\n  arm: AgentCliClient,\n  modelId: string,\n): Promise<SetModelResult> {\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      if (isModelSwitchAcknowledgement(evt)) acked = true\n    }\n  } catch (err) {\n    const reason = err instanceof Error ? err.message : String(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 { applied: false, reason }\n  }\n  if (!acked) {\n    const reason = \"no switch acknowledgement — agent may be on its default model\"\n    console.warn(`[agent-cli] /model ${modelId}: ${reason}`)\n    return { applied: false, reason }\n  }\n  return { applied: true, model: modelId }\n}\n\n/**\n * Send a turn and yield the arm's events for it.\n *\n * Re-attaches the recent stderr tail to error events. The ACP layer\n * surfaces a terse `{message: \"Invalid params\"}`; the child's stderr\n * almost always has a more useful line (\"npx claude-agent-acp: not\n * authenticated, run `claude login`\"). Hosts read `error.data` when\n * present, falling back to `message` for older payloads.\n */\nexport async function* promptTurn(\n  arm: AgentCliClient,\n  turnId: string,\n  message: unknown,\n): AsyncIterable<StreamEvent> {\n  await arm.send(turnId, message)\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","import { createHash } from \"node:crypto\"\nimport { existsSync, readFileSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { basename, join } from \"node:path\"\n\n/**\n * Skip `npm exec` for an adapter launched as `npx -y <pkg>@<exact version>`\n * whose exact version already sits in npm's npx cache — exec the cached bin\n * directly instead.\n *\n * Why (F34b, measured live 2026-09-26): before `npx` runs anything it does a\n * full arborist `loadActual()` of the project tree around the CHILD's cwd\n * (~20s warm, ~2min cold for a large pnpm monorepo), then a second one of\n * the npx cache dir under a cross-process `concurrency.lock` keyed by the\n * package spec — i.e. one lock per adapter. Every step is filesystem-bound,\n * so a concurrent worktree provision (`pnpm install` + build in its setup\n * hooks) on the same disk stretched a plain claude-code spawn to minutes,\n * which looked exactly like spawns queuing behind provisioning. The\n * daemon never held a lock; npm did the waiting.\n *\n * Only EXACT versions qualify: an unpinned spec (`-y opencode-ai`) relies on\n * npx's registry check to pick up new releases, and bypassing it would\n * silently freeze the version. Anything that doesn't resolve cleanly (cache\n * miss, version mismatch, ambiguous bin, Windows `.cmd` shims) returns\n * `undefined` so the caller spawns `npx` exactly as before — the fast path\n * can only ever remove work, never change which version runs.\n */\nexport interface NpxFastPath {\n  /** Absolute path of the cached bin to exec in place of `npx`. */\n  bin: string\n  /** The argv after the package spec — what npx would have forwarded. */\n  args: string[]\n  /** `<cache>/_npx/<hash>/node_modules/.bin` — npx prepends it to the\n   *  child's PATH, so the fast path does too. */\n  binDir: string\n}\n\n/** Same key libnpmexec uses for `<cache>/_npx/<hash>`: sha512 over the\n *  sorted package specs, newline-joined, first 16 hex chars. */\nexport function npxCacheKey(packages: readonly string[]): string {\n  return createHash(\"sha512\")\n    .update([...packages].sort((a, b) => a.localeCompare(b, \"en\")).join(\"\\n\"))\n    .digest(\"hex\")\n    .slice(0, 16)\n}\n\n/** `name@1.2.3` (optionally scoped, optional prerelease/build) → parts;\n *  anything else (range, tag, bare name, url, path) → undefined. */\nfunction parseExactSpec(spec: string): { name: string; version: string } | undefined {\n  const m = /^((?:@[a-z0-9][\\w.-]*\\/)?[a-z0-9][\\w.-]*)@(\\d+\\.\\d+\\.\\d+(?:-[\\w.-]+)?(?:\\+[\\w.-]+)?)$/i.exec(spec)\n  return m ? { name: m[1]!, version: m[2]! } : undefined\n}\n\n/** npm's own rule (`get-bin-from-manifest`): a lone bin wins; otherwise the\n *  bin named after the unscoped package name; otherwise ambiguous. */\nfunction binNameFromManifest(name: string, bin: unknown): string | undefined {\n  const unscoped = name.replace(/^@[^/]+\\//, \"\")\n  if (typeof bin === \"string\") return unscoped\n  if (!bin || typeof bin !== \"object\") return undefined\n  const names = Object.keys(bin)\n  if (names.length === 1) return names[0]\n  return names.includes(unscoped) ? unscoped : undefined\n}\n\nexport function resolveNpxFastPath(\n  bin: string,\n  args: readonly string[],\n  env: Record<string, string | undefined>,\n  deps?: {\n    platform?: NodeJS.Platform\n    home?: string\n    exists?: (p: string) => boolean\n    readFile?: (p: string) => string\n  },\n): NpxFastPath | undefined {\n  if ((deps?.platform ?? process.platform) === \"win32\") return undefined\n  if (basename(bin) !== \"npx\") return undefined\n  const [yes, spec, ...rest] = args\n  if (yes !== \"-y\" && yes !== \"--yes\") return undefined\n  if (spec === undefined) return undefined\n  const parsed = parseExactSpec(spec)\n  if (!parsed) return undefined\n\n  const exists = deps?.exists ?? existsSync\n  const readFile = deps?.readFile ?? ((p: string) => readFileSync(p, \"utf8\"))\n  const cacheRoot =\n    env[\"npm_config_cache\"] ?? env[\"NPM_CONFIG_CACHE\"] ?? join(deps?.home ?? homedir(), \".npm\")\n  const installDir = join(cacheRoot, \"_npx\", npxCacheKey([spec]))\n  try {\n    const pkg = JSON.parse(readFile(join(installDir, \"node_modules\", parsed.name, \"package.json\"))) as {\n      version?: unknown\n      bin?: unknown\n    }\n    if (pkg.version !== parsed.version) return undefined\n    const binName = binNameFromManifest(parsed.name, pkg.bin)\n    if (!binName) return undefined\n    const binDir = join(installDir, \"node_modules\", \".bin\")\n    const binPath = join(binDir, binName)\n    if (!exists(binPath)) return undefined\n    return { bin: binPath, args: rest, binDir }\n  } catch {\n    return undefined\n  }\n}\n","import { spawn, type ChildProcess } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport { delimiter, dirname, join } from \"node:path\"\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 { createProprietaryProtocolArm } from \"./protocol/proprietary.js\"\nimport { composeSpawn, RuntimeConfigError } from \"./manifest/compose.js\"\nimport { wrapAgentCliSpawn } from \"./command-sandbox-wrap.js\"\nimport { hostContextExcludes } from \"./host-context.js\"\nimport { terminateChildTree } from \"./process-tree.js\"\nimport { resolveNpxFastPath } from \"./npx-fast-path.js\"\nimport { resolveWindowsBatchSpawn, windowsBatchShellOption } from \"./win32-spawn.js\"\nimport {\n  applyModelCommand,\n  createArmSessionControls,\n  promptTurn,\n} from \"./session-controls.js\"\nimport type {\n  AgentCliClient,\n  AgentCliDefinition,\n  AgentCliHandle,\n  AgentCliRuntime,\n  AgentCliRuntimeSession,\n  AgentCliStartOptions,\n  SetModelResult,\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: AgentCliDefinition) {\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      if (\n        data.models?.apply === \"arg\" &&\n        !data.models.bin_args_template?.length\n      ) {\n        throw new Error(\n          \"defineAgentCli (AIP-45): models.apply=\\\"arg\\\" requires models.bin_args_template\",\n        )\n      }\n    },\n    build(def: AgentCliDefinition) {\n      return { ...def } as AgentCliHandle\n    },\n  },\n)\n\n/**\n * A manifest `bin: \"node\"` means \"run with the node that's driving THIS\n * process\" (the daemon's own `process.execPath`), not \"look up `node` on\n * the child's PATH\". A bare `spawn(\"node\", ...)` depends on PATH containing\n * a `node` entry — true in an interactive shell (nvm etc.) but NOT\n * guaranteed under launchd, which starts the daemon with a minimal PATH.\n * Resolving to `process.execPath` sidesteps PATH entirely for the one bin\n * value that always means \"this runtime\".\n *\n * `npx` / `npm` get the same treatment when possible: every Node install\n * layout (nvm, fnm, homebrew, system, Volta) ships them as siblings of the\n * `node` binary, so a daemon whose PATH lacks that dir (launchd again —\n * observed live 2026-08-30 as `spawn npx ENOENT` on a codex `agent_start`)\n * can still resolve them relative to its own `process.execPath`. Falls back\n * to the bare name (PATH lookup, prior behavior) when no sibling exists —\n * e.g. a trimmed container image exposing npx elsewhere on PATH.\n *\n * Every other bin (hermes, gemini, …) is left untouched — those are meant\n * to be resolved off PATH.\n */\nexport function resolveSpawnBin(\n  bin: string,\n  deps?: { execPath?: string; exists?: (p: string) => boolean },\n): string {\n  const execPath = deps?.execPath ?? process.execPath\n  if (bin === \"node\") return execPath\n  if (bin === \"npx\" || bin === \"npm\") {\n    const exists = deps?.exists ?? existsSync\n    const sibling = join(\n      dirname(execPath),\n      process.platform === \"win32\" ? `${bin}.cmd` : bin,\n    )\n    if (exists(sibling)) return sibling\n  }\n  return bin\n}\n\n/**\n * Ensure the running node binary's directory is on the child env's PATH.\n * Resolving `npx` to an absolute sibling path (above) is necessary but not\n * sufficient: npx is a `#!/usr/bin/env node` script, so its shebang — and\n * the `node` its target package's own bin shim execs — still resolve off\n * the CHILD's PATH. Under a launchd daemon whose PATH lacks the nvm bin\n * dir, an absolute-path npx would otherwise die right after spawn.\n * APPENDED, not prepended, so an operator-supplied PATH (opts.env) keeps\n * picking its own toolchain first; this only adds a fallback.\n */\nfunction ensureExecDirOnPath(\n  env: Record<string, string>,\n  execPath: string = process.execPath,\n): void {\n  const execDir = dirname(execPath)\n  const parts = (env.PATH ?? \"\").split(delimiter).filter(Boolean)\n  if (parts.includes(execDir)) return\n  env.PATH = [...parts, execDir].join(delimiter)\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      const resolvedBin = resolveSpawnBin(definition.bin)\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      // `contextProfile` is the one decomposed axis that still has a\n      // manifest-level spawn projection.  Preserve an explicit legacy mode\n      // for backwards compatibility; otherwise select the declared context\n      // mode (for example claude-code's `lean`) without overloading posture\n      // or route into `config.mode` again.\n      const contextMode = opts?.contextProfile\n        ? (definition.modes ?? []).find(\n            mode => mode.id === opts.contextProfile && mode.kind === \"context\",\n          )\n        : undefined\n      const config =\n        opts?.config?.mode || !contextMode\n          ? opts?.config\n          : { ...opts?.config, mode: contextMode.id }\n      const composed = composeSpawn(definition, config)\n      const env: Record<string, string> = {\n        ...filterStringEnv(process.env),\n        ...composed.env,\n      }\n      // Mode-declared env scrub (AgentCliMode.env_unset): delete AFTER the\n      // ambient + mode/option env are merged but BEFORE the host-provided\n      // opts.env. A gateway mode (e.g. claude-code's `moonshot`) declares\n      // keys that must never reach a non-native Anthropic-compatible endpoint\n      // — scrubbing here is the only point where the real key is actually\n      // present (compose starts from `{}` and can't delete what isn't there).\n      // opts.env is applied after so an operator who explicitly forwards a\n      // scrubbed key takes responsibility for it (operator intent wins).\n      for (const k of composed.envUnset) delete env[k]\n\n      // Deterministic billing-auth (AgentCliStartOptions.auth). MECHANICAL:\n      // the runtime resolver already decided the provider, mode, env var to\n      // SET, and vars to SCRUB — this driver imports no catalog/registry and\n      // makes no policy choice, it just applies the resolved spec. EXPLICIT\n      // credential selection, not scrub-by-absence: the credential is SET from\n      // the resolver's named ref, never inferred from what's ambient.\n      //\n      // ENGAGE when the adapter enforces `always` (claude-code — every spawn,\n      // preserving #312 fail-fast) OR the operator explicitly configured auth\n      // (`explicit`). An unconfigured `when-configured` adapter (codex/hermes/\n      // claude-sdk with no auth) does NOT engage → runs ambient, unchanged.\n      const authSpec = opts?.auth\n      // A gateway mode (moonshot/openrouter) or an explicit `auth_token`\n      // option already injected ANTHROPIC_AUTH_TOKEN into composed.env for\n      // Bearer auth against a non-Anthropic endpoint. Billing-auth\n      // engagement must not run in that case: an `always`-enforcing adapter\n      // (claude-code) would otherwise SET CLAUDE_CODE_OAUTH_TOKEN for\n      // subscription mode alongside it — two credentials the claude binary\n      // can't reconcile with a gateway ANTHROPIC_BASE_URL, and the resolved\n      // spec's own conflictEnv scrub can't remove ANTHROPIC_AUTH_TOKEN\n      // either (composed.env's own keys are protected from the blanket\n      // scrub below, by design). The gateway's Bearer token wins outright —\n      // skip engagement rather than let two auth mechanisms collide.\n      //\n      // Symmetric case: a `base_url` option (or gateway mode) can also be\n      // set WITHOUT an `auth_token` — e.g. the caller forgot it, or it's\n      // supplied a different way. `hasGatewayAuthToken` alone doesn't catch\n      // this: `engageAuth` would still be true, and since the per-key scrub\n      // loop below only deletes keys NOT already in `composed.env` (this\n      // spawn's own base_url is protected there, by the same design as\n      // above), nothing stops `env[authSpec.setEnv] = authSpec.credential`\n      // from injecting a real Anthropic subscription credential\n      // (CLAUDE_CODE_OAUTH_TOKEN) into a spawn whose ANTHROPIC_BASE_URL\n      // points at a foreign host. An explicit gateway base_url must protect\n      // against native creds leaking IN, exactly as an explicit gateway auth\n      // token already protects against native creds leaking OUT — skip\n      // engagement in both directions.\n      const hasGatewayAuthToken = \"ANTHROPIC_AUTH_TOKEN\" in composed.env\n      const hasGatewayBaseUrl = \"ANTHROPIC_BASE_URL\" in composed.env\n      // A gateway route resolved BY THE RUNTIME couples its base_url with the\n      // matching api-key credential in ONE spec — `authSpec.baseUrl` is set\n      // ONLY on that path (resolveAuthSpec fills it exclusively in the gateway-\n      // route branch, which forces api-key; a native/subscription spec never\n      // carries a baseUrl). In that case the ANTHROPIC_BASE_URL now in\n      // composed.env came from THIS very resolution — routed into the base_url\n      // option alongside the credential — so engaging billing-auth is exactly\n      // right: it injects the gateway bearer (ANTHROPIC_AUTH_TOKEN) that pairs\n      // with it and scrubs the raw provider var. WITHOUT this the credential is\n      // silently dropped (the `hasGatewayBaseUrl` skip below swallows it) and\n      // the outbound request reaches the gateway UNAUTHENTICATED → the real\n      // upstream 401s → \"Authentication required\" (the P0 bug). The skip guard\n      // still fires for the DIFFERENT case it exists for: a base_url set\n      // MANUALLY via option paired with a NATIVE spec (no `authSpec.baseUrl`),\n      // where engaging would leak a native credential to a foreign host.\n      const resolverCoupledGateway = authSpec?.baseUrl !== undefined\n      const engageAuth =\n        !!authSpec &&\n        !hasGatewayAuthToken &&\n        (resolverCoupledGateway || !hasGatewayBaseUrl) &&\n        (authSpec.enforce === \"always\" || authSpec.explicit === true)\n      if (authSpec && engageAuth) {\n        // Scrub the conflicting credential(s)/toggles BEFORE setting this\n        // mode's own credential. A key this spawn's own mode/option patch\n        // explicitly SET (e.g. a gateway preset's ANTHROPIC_BASE_URL) wins\n        // over the blanket scrub — composed.env is the record of keys this\n        // spawn's own config explicitly assigned.\n        for (const key of authSpec.unsetEnv) {\n          if (!(key in composed.env)) delete env[key]\n        }\n        // File-based (external) subscription — codex/gemini: the CLI reads its\n        // OWN local-login file (`~/.codex/auth.json`, …), so there is no bearer\n        // to inject and no credential to fail-fast on. The scrub above (the\n        // api-key vars) is the whole job: it stops a leftover OPENAI_API_KEY /\n        // GEMINI_API_KEY from silently flipping the CLI to api-key billing under\n        // a \"subscription\" label. Money-safe by construction — NOTHING is set\n        // into any env var, so an OAuth bearer can never land in an api-key\n        // channel. The host already verified the login is present (fail-loud)\n        // before resolving this spec.\n        // An external subscription stops here: the scrub above is the entire\n        // effect. Only the inject-a-credential path continues below.\n        if (!authSpec.externalCredential) {\n        // Fail-fast: the credential is resolved by the HOST from a named\n        // config/store ref, never read ambiently — if it didn't resolve,\n        // refuse the spawn rather than silently falling back to another or an\n        // ambient credential. Checked against the RESOLVED credential, not the\n        // merged env, so an unrelated `opts.env` key can't paper over a\n        // genuinely missing one. Message NAMES the fix instead of reciting\n        // prose (kept short — the old wall-of-text overflowed the VS Code\n        // notification box): when `neitherConfigured` is set, `mode` above is\n        // an arbitrary fallback pick, not a real signal — a zero-credential\n        // user must see BOTH paths, not just the one preference[0] happened\n        // to land on (that was the bug: an api-key-only user told to buy a\n        // subscription).\n        if (!authSpec.credential) {\n          const slug = definition.id\n          const providerLabel = definition.provider ?? \"<provider>\"\n          const configBlock =\n            `{\"defaults\":{\"adapters\":{\"${slug}\":{\"auth\":{\"mode\":\"api-key\"}}}}}` +\n            ` in ~/.agentproto/config.json`\n          const storeHint = authSpec.ignoredApiKeyInStore\n            ? ` (providers.json already has a stored key for ${providerLabel} — ignored until that block exists)`\n            : \"\"\n          const supportsSub = !!definition.authSubscription\n          const message =\n            authSpec.neitherConfigured && supportsSub\n              ? `agent-cli '${slug}': no billing auth. Subscription → \\`claude setup-token\\`. ` +\n                `Api-key → \\`agentproto auth provider set ${providerLabel} sk-…\\`${storeHint}. ` +\n                `Add ${configBlock}. Never inherited from the shell.`\n              : authSpec.mode === \"subscription\"\n                ? `agent-cli '${slug}': run \\`claude setup-token\\` and configure the result — ` +\n                  `bills the Max/Pro subscription, not API credits. Never inherited from the shell.`\n                : `agent-cli '${slug}': run \\`agentproto auth provider set ${providerLabel} sk-…\\`` +\n                  `${storeHint}, then add ${configBlock}. Never inherited from the shell.`\n          throw new RuntimeConfigError(\"missing_auth_credential\", \"opts.auth.credential\", message)\n        }\n        env[authSpec.setEnv] = authSpec.credential\n        }\n      }\n\n      Object.assign(env, opts?.env ?? {})\n      // After ALL env layers (ambient, mode/option patches, billing-auth,\n      // opts.env) so the append lands on the final PATH — see the helper's\n      // doc for why even an absolute-path npx needs this.\n      ensureExecDirOnPath(env)\n      // Pinned `npx -y pkg@x.y.z` already in the npx cache ⇒ exec the cached\n      // bin directly; npm's own pre-run tree scans made spawns wait minutes\n      // behind unrelated disk load (see `resolveNpxFastPath`'s doc).\n      const npxFast = resolveNpxFastPath(resolvedBin, composed.binArgs, env)\n      if (npxFast) {\n        // Runs AFTER ensureExecDirOnPath, so this only adds to its append —\n        // matches what npx itself would have put first on the child's PATH.\n        env.PATH = [npxFast.binDir, ...(env.PATH ?? \"\").split(delimiter).filter(Boolean)].join(delimiter)\n      }\n      const spawnBin = npxFast?.bin ?? resolvedBin\n      const spawnArgs = npxFast?.args ?? composed.binArgs\n      // Win32 batch-file shims (see `win32-spawn.ts`'s module doc — recap\n      // point 10, the Windows-host device-sandbox `spawn EINVAL`): rewrite\n      // npm `.cmd` shims to their real node entry (preferred, stays\n      // shell:false) BEFORE the arms spawn, so both arms inherit a clean\n      // argv; whatever still ends in `.cmd`/`.bat` gets `shell: true`\n      // inside the arm via `windowsBatchShellOption`.\n      const batchRewrite = resolveWindowsBatchSpawn(spawnBin, spawnArgs)\n      const finalBin = batchRewrite?.bin ?? spawnBin\n      const finalArgs = batchRewrite?.args ?? spawnArgs\n\n      // Exact-file read grant (`AgentCliStartOptions.additionalReadPaths`):\n      // the runtime hands down the exact AGENTS.md path(s) an inherited\n      // pointer prompt names (see `session-spawn.ts`'s\n      // `additionalReadPathsForAgentsMd`). Derive the child env var adapters\n      // read (`AGENTPROTO_ADDITIONAL_READ_PATHS`, a JSON array) HERE, from\n      // this one option as the single authority, so BOTH arms — ACP and\n      // print — carry it. Read-only by contract; nothing here widens writes.\n      if (opts?.additionalReadPaths?.length) {\n        env.AGENTPROTO_ADDITIONAL_READ_PATHS = JSON.stringify(opts.additionalReadPaths)\n      }\n\n      // claude-code's ACP wrapper never reads `--permission-mode` from argv\n      // (the `bin_args_append` above is a no-op against it) — it resolves\n      // `permissions.defaultMode` exclusively via `CLAUDE_CONFIG_DIR`/\n      // `<cwd>/.claude/settings(.local).json`, merged through the SDK's\n      // `resolveSettings`. Point a per-session `CLAUDE_CONFIG_DIR` at a\n      // throwaway temp dir carrying just that one field, so a non-default\n      // requested mode (e.g. \"plan\") actually takes effect without ever\n      // touching the target repo's own `.claude` directory. A repo that\n      // commits its own escalated `permissions.defaultMode` can still\n      // defeat this (see resolveClaudeCodePermissionMode's doc) — that's a\n      // documented limitation, not a bug in this override.\n      const permissionMode = resolveClaudeCodePermissionMode(\n        definition,\n        opts?.posture,\n        config?.mode,\n      )\n      // Isolation from ambient config must NOT be conditional on a\n      // requested posture/mode — a caller that never passes `posture` (the\n      // common case: `agent_start` / `spawnAgentSession` with no opinion on\n      // permission posture) used to get NO `CLAUDE_CONFIG_DIR` override at\n      // all, so the child inherited the DAEMON's own `process.env` and,\n      // through it, the operator's real `~/.claude.json` — including every\n      // globally-registered MCP server (e.g. an `agentproto` MCP entry\n      // pointing right back at this same daemon's `agent_start`, letting an\n      // unscoped one-shot worker spawn further unscoped children on its\n      // own). Confirmed in production 2026-08-07: a batch worker\n      // (`pmlawhub/tools/fiches/run-lane.sh`) self-spawned dozens of\n      // uncontrolled child sessions this way. Verified by reading\n      // `@anthropic-ai/claude-agent-sdk`'s bundled `sdk.mjs` directly: the\n      // SDK resolves its GLOBAL config file (the one carrying `mcpServers`)\n      // as `$CLAUDE_CONFIG_DIR/.claude.json` (falling back to\n      // `$CLAUDE_CONFIG_DIR/.config.json` if present) — never the real\n      // `~/.claude.json` once `CLAUDE_CONFIG_DIR` is set to anything else.\n      // So isolating every claude-code spawn through this path, regardless\n      // of whether a posture/mode was requested, closes the leak; only the\n      // settings.json CONTENT (permissions.defaultMode) stays conditional\n      // on `permissionMode` actually resolving to something.\n      const isolateClaudeCodeConfig = definition.id === \"claude-code\"\n      // Hoisted out of the `if` below so it's visible to the commandSandbox\n      // wrap further down: bwrap's `--tmpfs /tmp` (`command-sandbox.ts`)\n      // would otherwise HIDE this dir on Linux since it's mkdtemp'd under\n      // `os.tmpdir()` BEFORE the confined spawn — it must ride along as an\n      // extraWritePaths entry, not rely on the workspace bind.\n      let claudeConfigDir: string | undefined\n      if (isolateClaudeCodeConfig) {\n        // `opts.configDir` (AgentCliStartOptions.configDir) makes the\n        // isolated dir PERSISTENT instead of throwaway: the caller picks a\n        // stable path (the daemon keys it per session lineage) so the SDK's\n        // own conversation store — `projects/<cwd-slug>/<uuid>.jsonl`, the\n        // thing `resumeSessionId` needs to find — survives adapter respawns.\n        // A fresh mkdtemp per spawn is why a reaped-then-resumed session\n        // used to lose native resume: the transcript sat in the previous\n        // process's temp dir, and the new one minted an empty dir. The\n        // isolation content below is written either way — the ISOLATION\n        // invariant lives in the files, not in the dir being temporary.\n        if (opts?.configDir) {\n          claudeConfigDir = opts.configDir\n          mkdirSync(claudeConfigDir, { recursive: true })\n        } else {\n          claudeConfigDir = mkdtempSync(\n            join(tmpdir(), \"agentproto-claude-config-\"),\n          )\n        }\n        // Explicit empty `mcpServers` rather than just leaving the global\n        // config file absent — an absent file falls back to whatever the\n        // SDK treats as \"fresh install\" defaults, which is unspecified and\n        // could change; writing it makes the isolation load-bearing on our\n        // own content, not on unverified fallback behavior. On a REUSED\n        // persistent dir, preserve the SDK's own accumulated state (project\n        // trust, onboarding flags — it rewrites this file itself) but\n        // RE-ASSERT `mcpServers: {}` every spawn: a session that ran\n        // `claude mcp add` mid-conversation must not smuggle that server\n        // back into its next respawn — same ambient-leak surface the\n        // temp-dir isolation closed (#824).\n        const globalConfigPath = join(claudeConfigDir, \".claude.json\")\n        let priorGlobalConfig: Record<string, unknown> = {}\n        try {\n          const parsed: unknown = JSON.parse(readFileSync(globalConfigPath, \"utf8\"))\n          if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n            priorGlobalConfig = parsed as Record<string, unknown>\n          }\n        } catch {\n          // absent or unparseable — start from the empty baseline\n        }\n        writeFileSync(\n          globalConfigPath,\n          JSON.stringify({ ...priorGlobalConfig, mcpServers: {} }),\n        )\n        // Isolating CLAUDE_CONFIG_DIR also shadows the operator's real\n        // `~/.claude/settings.json` — including `attribution`, the key an\n        // operator sets to suppress Claude Code's own default \"🤖 Generated\n        // with Claude Code\" PR-body footer / `Co-authored-by: Claude` commit\n        // trailer. A spawned session has no ambient settings.json to fall\n        // back to at all once isolated, so it reverts to those CLI defaults\n        // regardless of what's configured globally — confirmed on\n        // agentproto/ts PR #837, opened after this isolation went\n        // unconditional (#824), which carried the footer despite the\n        // spawning operator's global settings disabling it. Bake the\n        // suppression into every isolated settings.json unconditionally\n        // rather than reading the real file back in: that would reopen\n        // exactly the ambient-leak surface this isolation exists to close,\n        // and make spawn output depend on whatever happens to be in the\n        // runner's home dir.\n        const isolatedSettings: Record<string, unknown> = {\n          attribution: { commit: \"\", pr: \"\", sessionUrl: false },\n        }\n        const isolatedPermissions: Record<string, unknown> = {}\n        if (permissionMode) isolatedPermissions.defaultMode = permissionMode\n        if (opts?.fsZones?.writable.length) {\n          // The OS sandbox already allows these; registering them keeps the\n          // harness from prompting on (or refusing) a write it can't tell is\n          // in-bounds — the run workspace sits outside the app-dir cwd.\n          isolatedPermissions.additionalDirectories = opts.fsZones.writable\n        }\n        if (Object.keys(isolatedPermissions).length > 0) {\n          isolatedSettings.permissions = isolatedPermissions\n        }\n        if (opts?.isolateHostContext) {\n          isolatedSettings.claudeMdExcludes = hostContextExcludes(cwd)\n        }\n        writeFileSync(\n          join(claudeConfigDir, \"settings.json\"),\n          JSON.stringify(isolatedSettings),\n        )\n        env.CLAUDE_CONFIG_DIR = claudeConfigDir\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        // Derived-from-model guard, print flavor: hand the arm the\n        // explicitly requested model so it can abort a turn whose wire\n        // `start` event names a DIFFERENT model — jcode's CLI silently\n        // falls back to its own default on an unknown `--model` id, which\n        // for a derived-from-model adapter is a different provider on a\n        // different bill (same contract as the ACP-arm guard below; see\n        // PrintArmOptions.expectedModel).\n        const printModel = config?.options?.model\n        return createPrintSession({\n          bin: finalBin,\n          baseArgs: finalArgs,\n          cwd,\n          env,\n          ...(opts?.resumeSessionId\n            ? { resumeSessionId: opts.resumeSessionId }\n            : {}),\n          ...(opts?.mcpServers ? { mcpServers: opts.mcpServers } : {}),\n          printConfig: definition.print,\n          commandSandbox: opts?.commandSandbox,\n          ...(opts?.fsZones ? { fsZones: opts.fsZones } : {}),\n          ...(claudeConfigDir ? { extraWritePaths: [claudeConfigDir] } : {}),\n          // Exact-file read grant — see the ACP arm's wrapAgentCliSpawn call.\n          ...(opts?.additionalReadPaths?.length\n            ? { extraReadPaths: opts.additionalReadPaths }\n            : {}),\n          ...(definition.routeSelection === \"derived-from-model\" && printModel\n            ? { expectedModel: String(printModel) }\n            : {}),\n        })\n      }\n\n      // `proprietary` arms are not guaranteed to own a subprocess at all\n      // (e.g. an in-process SDK integration) — `buildProtocolArm` decides\n      // per-protocol whether `child` is required. Skip the spawn entirely\n      // for `proprietary` so an in-process arm pays no subprocess cost.\n      let child: ChildProcess | undefined\n      const stderrBuf: string[] = []\n      if (definition.protocol !== \"proprietary\") {\n        // OS-level confinement (`AgentCliStartOptions.commandSandbox`):\n        // wraps THIS spawn's argv through the same Seatbelt/bwrap backends\n        // `command_execute` already uses (`@agentproto/command-sandbox`),\n        // so the adapter's own process tree — not just its reported tool\n        // calls — is denied out-of-workspace reads/writes. Off by default;\n        // see `wrapAgentCliSpawn`'s doc for the fail-closed contract.\n        const [execBin, execArgs] = await wrapAgentCliSpawn(\n          finalBin,\n          finalArgs,\n          {\n            mode: opts?.commandSandbox,\n            cwd,\n            ...(opts?.fsZones ? { zones: opts.fsZones } : {}),\n            ...(claudeConfigDir ? { extraWritePaths: [claudeConfigDir] } : {}),\n            // Exact-file read grant (see additionalReadPaths above):\n            // READ-only exceptions to the confinement boundary, never writes.\n            ...(opts?.additionalReadPaths?.length\n              ? { extraReadPaths: opts.additionalReadPaths }\n              : {}),\n            label: definition.id,\n          },\n        )\n        const spawned = spawn(execBin, execArgs, {\n          cwd,\n          env,\n          stdio: [\"pipe\", \"pipe\", \"pipe\"],\n          signal: opts?.signal,\n          // Win32: a `.cmd`/`.bat` bin that `resolveWindowsBatchSpawn`\n          // couldn't rewrite to its node entry needs the shell — Node\n          // refuses to spawn batch files directly (CVE-2024-27980, the\n          // recap-10 `spawn EINVAL`). POSIX: `{}` — unchanged.\n          ...windowsBatchShellOption(execBin),\n        })\n        child = spawned\n\n        // Attached synchronously, before any `await` below, so a spawn\n        // failure (bad binary, PATH missing the target under a minimal\n        // launchd env, …) is always observed by a listener. Node throws\n        // an UNHANDLED exception — crashing this ENTIRE process, every\n        // session on the box, not just this spawn — when a ChildProcess\n        // emits 'error' with nobody listening. Confirmed live 2026-08-11:\n        // a launchd-started daemon (PATH without the interactive shell's\n        // nvm setup) hit `spawn('node') ENOENT` from an `app_run` →\n        // mastra-agent spawn with no 'error' listener anywhere on the\n        // chain, taking down every running session. Race 'spawn' vs\n        // 'error' and turn a failure into a normal rejection instead —\n        // the caller (`session-spawn.ts` / `app_run`) already turns a\n        // rejected `start()` into a clean `{ok:false, message}` result.\n        let spawnFailure: Error | undefined\n        await new Promise<void>(resolve => {\n          spawned.once(\"spawn\", () => resolve())\n          spawned.once(\"error\", err => {\n            spawnFailure = err\n            resolve()\n          })\n        })\n        if (spawnFailure) {\n          const isEnoent =\n            (spawnFailure as NodeJS.ErrnoException).code === \"ENOENT\"\n          // Node reports a nonexistent WORKING DIRECTORY as the byte-identical\n          // `spawn <bin> ENOENT` it uses for a missing binary — a stale\n          // workspace path masquerades as \"npx is not installed\" and sends\n          // whoever reads the error down the wrong trail. Disambiguate here,\n          // where the failure is in hand, rather than preflighting every\n          // start: the cwd probe only runs on the already-failed path.\n          const cwdMissing = isEnoent && !existsSync(cwd)\n          const enoentHint = !isEnoent\n            ? \"\"\n            : cwdMissing\n              ? `\\ncwd '${cwd}' does not exist — Node reports a missing working directory with this same ENOENT. Recreate the directory, or pass a valid cwd/workspace (is the workspace path stale, or its worktree removed?).`\n              : `\\n'${execBin}' was not found on the daemon's PATH. If it works in your own terminal, the daemon's environment may be stale — restart the daemon from a shell where \\`which ${definition.bin}\\` resolves (\\`agentproto daemon restart\\`).`\n          throw new Error(\n            `agent-cli '${definition.id}': failed to spawn '${execBin} ${execArgs.join(\" \")}': ${spawnFailure.message}${enoentHint}`,\n          )\n        }\n        // The spawn itself succeeded — keep a listener attached for the\n        // rest of the child's life so a LATER 'error' (e.g. a broken\n        // pipe) never goes unhandled either.\n        spawned.on(\"error\", err => {\n          stderrBuf.push(`[spawn error] ${err.message}`)\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 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\n      const arm = await buildProtocolArm(\n        definition,\n        child,\n        cwd,\n        config?.mode,\n        opts?.permissionHold ?? false,\n      )\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 = config?.options?.model\n      const optEffort = 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      //   \"arg\"     → this CLI takes its model as a CLI argument, already\n      //               composed into binArgs by compose.ts before spawn — we DON'T pass\n      //               model to connect() at all, same as \"command\".\n      const modelApply = definition.models?.apply ?? \"config\"\n      const configModel =\n        optModel && modelApply === \"config\" ? String(optModel) : undefined\n      // Mode-selection strategy (AgentCliMode.apply, default \"bin_args\"):\n      //   \"bin_args\" → the mode's argv/env patch (already composed above)\n      //               is how the CLI picks the mode — no ACP config to send.\n      //   \"config\"   → the CLI has no argv/env surface for this mode (e.g.\n      //               opencode's plan/build); compose.ts already skipped its\n      //               bin_args/env, so forward the mode id to the ACP arm's\n      //               connect({mode}) instead, applied via\n      //               session/set_config_option(configId:\"mode\").\n      const requestedModeId = config?.mode\n      const requestedModeDecl = requestedModeId\n        ? (definition.modes ?? []).find(m => m.id === requestedModeId)\n        : undefined\n      const configMode =\n        requestedModeDecl?.apply === \"config\" ? requestedModeId : undefined\n      // Caller-supplied override wins; otherwise fall back to the\n      // manifest's declared default (if any) so an adapter known to drop\n      // responses (e.g. hermes) gets watchdog protection without every\n      // host having to opt in per spawn.\n      const turnIdleTimeoutMs =\n        opts?.turnIdleTimeoutMs ?? definition.session?.turn_idle_timeout_ms\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        ...(configMode ? { mode: configMode } : {}),\n        ...(opts?.onActivity ? { onActivity: opts.onActivity } : {}),\n        ...(turnIdleTimeoutMs !== undefined ? { turnIdleTimeoutMs } : {}),\n        ...(opts?.permissionHold ? { permissionHold: true } : {}),\n      })\n\n      // Derived-from-model guard: when the ACP server REJECTED the\n      // connect-time model apply, the session is alive but on the agent's\n      // own default model. For a free/fixed-routing adapter that's a\n      // tolerable degradation (the route and bill don't change — keep\n      // agentproto#186's warn-and-continue). For a\n      // routeSelection:\"derived-from-model\" adapter (opencode, mastracode,\n      // hermes, jcode) the model id IS the route: \"kept the default\" means\n      // a DIFFERENT provider on a DIFFERENT bill than the operator named\n      // (observed live: opencode spawned with a claude-code-style\n      // `…@openrouter` id silently ran anthropic/claude-sonnet-4-5).\n      // That's a misroute, not a preference — refuse the spawn loudly,\n      // with the server's own reason and the id shape this adapter needs.\n      if (\n        configModel &&\n        definition.routeSelection === \"derived-from-model\" &&\n        arm.modelApplyRejection\n      ) {\n        const { requested, reason } = arm.modelApplyRejection\n        await arm.close().catch(() => {})\n        if (child && !child.killed) child.kill(\"SIGTERM\")\n        throw derivedModelRefusalError(definition, requested, reason)\n      }\n\n      // \"command\" model strategy: switch the model via a drained `/model\n      // <id>` control turn. Best-effort for free/fixed-routing adapters — a\n      // failure is warned, never fatal, so the session still starts (on the\n      // agent's default model). For a derived-from-model adapter (hermes is\n      // the command-apply case today) the SAME guard as the config path\n      // above applies: an unacknowledged/failed switch means the session is\n      // on a model — and a bill — the operator didn't name, so refuse the\n      // spawn instead of continuing silently.\n      if (optModel && modelApply === \"command\") {\n        const commandResult = await applyModelCommand(arm, String(optModel))\n        if (\n          !commandResult.applied &&\n          definition.routeSelection === \"derived-from-model\"\n        ) {\n          await arm.close().catch(() => {})\n          if (child && !child.killed) child.kill(\"SIGTERM\")\n          throw derivedModelRefusalError(\n            definition,\n            String(optModel),\n            commandResult.reason ?? \"model switch not acknowledged\",\n          )\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      // The turn `cancel()` acts on. `send()` mints a fresh id per turn and\n      // dropped it on the floor, which left `cancel()` with nothing to name —\n      // see its comment below.\n      let currentTurnId: string | undefined\n\n      return {\n        sessionId,\n        pid: child?.pid,\n        // Transport liveness, delegated to the arm (see the fields' docs on\n        // AgentCliRuntimeSession). An arm that models no long-lived\n        // connection reports nothing, which reads as \"connected\" — there is\n        // no stream for it to have lost, and nothing to subscribe to.\n        isConnected: () => arm.isConnected?.() ?? true,\n        ...(arm.onDisconnect\n          ? { onDisconnect: (listener: (err: Error) => void) => arm.onDisconnect!(listener) }\n          : {}),\n        // Live model/mode/effort switches + the capability read-surface,\n        // all pure arm delegation — shared with every host that builds\n        // its own session over another transport. See session-controls.ts.\n        // Snapshotted after `arm.connect()` above resolved.\n        ...createArmSessionControls(arm, definition),\n        send(message): AsyncIterable<StreamEvent> {\n          const turnId = randomUUID()\n          currentTurnId = turnId\n          return promptTurn(arm, turnId, message)\n        },\n        /**\n         * Cancel the in-flight turn — the wire equivalent of Ctrl-C at the\n         * agent's own TUI, and the primitive the host's interrupt path\n         * (`SessionsRegistry.interruptSession`, `{interrupt: true}`) is built\n         * on.\n         *\n         * This used to be `abortController.abort()` alone, which cancelled\n         * NOTHING: that controller is the CONNECTION-level signal, handed to\n         * `arm.connect({abortSignal})` at spawn, and no arm reads it. So the\n         * abort fired into the void while the agent kept working — a turn\n         * \"cancelled\" this way ran happily to completion, and the host's 60s\n         * settle-wait then timed out on a turn that was never asked to stop.\n         * It only ever LOOKED like it worked for turns that happened to end\n         * naturally inside that wait.\n         *\n         * Both arms have always implemented the real thing — the ACP arm\n         * sends `session/cancel`, the print arm SIGTERMs the child — it was\n         * simply never called. Call it.\n         *\n         * Connection-level abort deliberately stays out of this: aborting the\n         * connection would end the SESSION, and cancelling a turn must leave\n         * it alive and idle for the next prompt. That distinction is the whole\n         * point of interrupt-vs-kill.\n         */\n        async cancel() {\n          // No turn has been sent yet — nothing to cancel, and naming a turn\n          // that never existed would be a lie to the arm.\n          if (currentTurnId === undefined) return\n          // Deliberately NOT cleared afterwards: a second cancel re-sends the\n          // same id, and both arms are idempotent on it (ACP `session/cancel`\n          // for a settled turn is a no-op; SIGTERM to an already-dead child\n          // does nothing). Clearing it would instead make a cancel racing a\n          // turn-end silently skip the arm — the exact no-op this whole fix\n          // exists to remove.\n          await arm.cancel(currentTurnId)\n        },\n        ...(arm.respondPermission\n          ? {\n              respondPermission(requestId, resolution) {\n                return arm.respondPermission!(requestId, resolution)\n              },\n            }\n          : {}),\n        ...(arm.onOutOfTurnEvent\n          ? {\n              onOutOfTurnEvent(listener) {\n                return arm.onOutOfTurnEvent!(listener)\n              },\n            }\n          : {}),\n        ...(arm.steer\n          ? {\n              // Snapshotted after `arm.connect()` resolved, like the\n              // config/mode read surfaces above.\n              steeringSupported: arm.steeringSupported === true,\n              steer(content: unknown) {\n                return arm.steer!(content)\n              },\n            }\n          : {}),\n        async close() {\n          await arm.close()\n          // The whole tree, not just `child`: that is usually an npx/npm-exec\n          // wrapper that may ignore SIGTERM, with the real adapter (and its\n          // MCP servers / headless Chrome) running underneath it.\n          if (child) await terminateChildTree(child)\n        },\n      }\n    },\n  }\n}\n\nasync function buildProtocolArm(\n  def: AgentCliHandle,\n  child: ChildProcess | undefined,\n  cwd: string,\n  requestedMode?: string,\n  permissionHold?: boolean,\n): Promise<AgentCliClient> {\n  switch (def.protocol) {\n    case \"acp\":\n      if (!child) {\n        throw new Error(\"createAgentCliRuntime: acp protocol requires a spawned subprocess\")\n      }\n      return createAcpProtocolArm({\n        child,\n        cwd,\n        clientInfo: { name: def.id, version: def.version },\n        requestedMode,\n        ...(permissionHold ? { permissionHold: true } : {}),\n      })\n    case \"mcp\":\n      throw new Error(\"createAgentCliRuntime: mcp protocol arm not yet implemented\")\n    case \"proprietary\":\n      if (!def.adapter) {\n        // defineAgentCli's validate() already enforces this for manifests\n        // built through it — this guards a hand-built AgentCliHandle that\n        // bypassed that check.\n        throw new Error(\n          \"createAgentCliRuntime: proprietary protocol requires manifest.adapter\",\n        )\n      }\n      return createProprietaryProtocolArm({ adapter: def.adapter, definition: def })\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\n/**\n * Derives the `permissions.defaultMode` value claude-code's settings.json\n * expects for a requested AIP-45 mode, by reading the same\n * `[\"--permission-mode\", \"<value>\"]` pair already declared in the\n * adapter's `modes[].bin_args_append` (one vocabulary, one source of\n * truth — see `adapters/claude-code/src/index.ts`). Scoped to\n * `definition.id === \"claude-code\"` since this settings-file mechanism\n * is specific to that adapter's ACP wrapper; every other adapter's\n * `bin_args_append` is applied to argv as normal and this returns\n * `undefined` for them. Also `undefined` for an unrequested mode, or a\n * mode (like \"default\") that has no `--permission-mode` patch — the\n * caller (`start()` above) uses that to skip writing\n * `permissions.defaultMode` into the isolated `CLAUDE_CONFIG_DIR`'s\n * `settings.json`, NOT to skip the `CLAUDE_CONFIG_DIR` override itself:\n * that override is unconditional for every claude-code spawn (see\n * `isolateClaudeCodeConfig` in `start()`) so ambient global config\n * (`~/.claude.json`, including registered `mcpServers`) never leaks into a\n * spawn that never requested a posture.\n */\nfunction resolveClaudeCodePermissionMode(\n  definition: AgentCliHandle,\n  posture: string | undefined,\n  configMode: string | undefined,\n): string | undefined {\n  if (definition.id !== \"claude-code\") return undefined\n\n  // Canonical posture is a first-class axis. It deliberately does not depend\n  // on the retired claude-code posture entries in `modes[]`: context profiles\n  // can therefore select `lean` at the same time as a permission posture.\n  // `read-only` maps to Claude Code's plan permission boundary; Claude Code\n  // does not expose a stricter read-only native mode.\n  const canonicalPermissionMode: Record<string, string | undefined> = {\n    plan: \"plan\",\n    \"read-only\": \"plan\",\n    \"accept-edits\": \"acceptEdits\",\n    bypass: \"bypassPermissions\",\n  }\n  if (posture && canonicalPermissionMode[posture]) {\n    return canonicalPermissionMode[posture]\n  }\n\n  // Legacy callers that still send a single AIP-45 mode remain supported.\n  if (!configMode) return undefined\n  const mode = (definition.modes ?? []).find((m) => m.id === configMode)\n  const args = mode?.bin_args_append ?? []\n  const flagIndex = args.indexOf(\"--permission-mode\")\n  if (flagIndex === -1 || flagIndex + 1 >= args.length) return undefined\n  return args[flagIndex + 1]\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\n/**\n * The spawn-refusal error for a derived-from-model adapter whose explicitly\n * requested model did not take — shared by the \"config\" (ACP rejection) and\n * \"command\" (`/model` control turn, unacknowledged/failed) apply paths so\n * the two guards can never drift. Names the requested id, the concrete\n * reason, and the adapter's own expected id shape (first menu entry).\n */\nfunction derivedModelRefusalError(\n  definition: AgentCliDefinition,\n  requested: string,\n  reason: string,\n): Error {\n  const first = definition.models?.allowed?.[0]\n  const example =\n    (typeof first === \"string\" ? first : first?.id) ??\n    \"openrouter/anthropic/claude-sonnet-4-6\"\n  return new Error(\n    `${definition.bin}: refusing to start on the default model — the requested model ` +\n      `\"${requested}\" was not applied (${reason}). This adapter routes AND ` +\n      `bills by the model id's own provider prefix, so continuing would silently run ` +\n      `(and bill) a model you didn't ask for. Use the adapter's ` +\n      `\"<provider>/<model>\" form (e.g. \"${example}\"), or pick an id from its model menu.`,\n  )\n}\n"]}