@agentproto/driver-agent-cli 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schema.ts","../src/protocol/acp-client.ts","../src/manifest/compose.ts","../src/define-agent-cli.ts"],"names":[],"mappings":";;;;;;;;;;;;AAiBA,IAAM,UAAA,GAAa,2BAAA;AACnB,IAAM,cAAA,GAAiB,iCAAA;AACvB,IAAM,WAAA,GAAc,2BAAA;AACpB,IAAM,oBAAA,GAAuB,2BAAA;AAC7B,IAAM,eAAA,GAAkB,0BAAA;AACxB,IAAM,WAAA,GAAc,qBAAA;AACpB,IAAM,eAAA,GAAkB,2BAAA;AACxB,IAAM,iBAAA,GAAoB,2BAAA;AAE1B,IAAM,yBAAA,GAA4B;AAAA,EAChC,MAAA;AAAA,EACA,gBAAA;AAAA,EACA,YAAA;AAAA,EACA;AACF,CAAA;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,MAAA,EAAO;AAAA,EAC1G,CAAA,CAAE,OAAO,EAAE,MAAA,EAAQ,EAAE,OAAA,CAAQ,KAAK,GAAG,OAAA,EAAS,CAAA,CAAE,QAAO,EAAG,YAAA,EAAc,EAAE,OAAA,EAAQ,CAAE,UAAS,EAAG,EAAE,MAAA,EAAO;AAAA,EACzG,CAAA,CAAE,OAAO,EAAE,MAAA,EAAQ,EAAE,OAAA,CAAQ,KAAK,GA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AI,EAAA,EAAI,OAAA,EAAS,IAAI,OAAA;AAAQ,OAClD,CAAA;AAAA,IACH,KAAK,KAAA;AACH,MAAA,MAAM,IAAI,MAAM,6DAA6D,CAAA;AAAA,IAC/E,KAAK,aAAA;AACH,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AAAA,OACF;AAAA;AAEN;AAEA,SAAS,gBAAgB,GAAA,EAAgD;AACvE,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG;AACxC,IAAA,IAAI,OAAO,CAAA,KAAM,QAAA,EAAU,GAAA,CAAI,CAAC,CAAA,GAAI,CAAA;AAAA,EACtC;AACA,EAAA,OAAO,GAAA;AACT","file":"chunk-EEIYDRIU.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 authSchema = z.object({\n ref: z.string().optional(),\n state: z.object({\n paths: z.array(z.string()).optional(),\n env: z.array(z.string()).optional(),\n }).strict().optional(),\n login: z.object({\n cmd: z.string(),\n interactive: z.boolean().optional(),\n requires_callback_url: z.boolean().optional(),\n }).strict().optional(),\n refresh: z.object({\n cmd: z.string(),\n interval_s: z.number().int().positive().optional(),\n }).strict().optional(),\n expiry: z.object({\n parse: z.string().optional(),\n grace_s: z.number().int().nonnegative().optional(),\n }).strict().optional(),\n}).strict()\n\nconst sessionSchema = z.object({\n mode: z.enum([\"ephemeral\", \"persistent\", \"resumable\"]).default(\"ephemeral\"),\n idle_timeout_ms: z.number().int().min(1000).default(600_000),\n max_turns: z.number().int().positive().optional(),\n context_carryover: z.boolean().default(true),\n}).strict()\n\nconst modelsSchema = z.object({\n default: z.string().optional(),\n allowed: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict()\n\nconst capabilitiesSchema = z.object({\n streaming: z.boolean().optional(),\n tool_calls: z.boolean().optional(),\n sub_agents: z.boolean().optional(),\n file_io: z.boolean().optional(),\n multimodal: z.boolean().optional(),\n resumable: z.boolean().optional(),\n bidirectional: z.boolean().optional(),\n}).strict()\n\nconst modeSchema = z.object({\n id: z.string().regex(MODE_ID_PATTERN),\n description: z.string().optional(),\n bin_args_append: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict()\n\nconst optionSchema = z.object({\n id: z.string().regex(OPTION_ID_PATTERN),\n type: z.enum([\"boolean\", \"integer\", \"string\", \"enum\"]),\n description: z.string().optional(),\n enum: z.array(z.string()).min(1).optional(),\n default: z.union([z.boolean(), z.number(), z.string()]).optional(),\n min: z.number().int().optional(),\n max: z.number().int().optional(),\n bin_args_template: z.array(z.string()).optional(),\n bin_args_append_when_true: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict().refine(\n // type === \"enum\" REQUIRES an `enum` array. The JSON Schema enforces\n // this via `if/then`; the zod side mirrors with a refine so both\n // validation paths reject the same shapes.\n o => o.type !== \"enum\" || (Array.isArray(o.enum) && o.enum.length > 0),\n { message: \"option.type === 'enum' requires a non-empty `enum` array\" }\n)\n\nconst continuationStrategyIdSchema = z.enum(CONTINUATION_STRATEGY_IDS)\n\nconst continuationSchema = z.object({\n default: continuationStrategyIdSchema,\n supported: z.array(continuationStrategyIdSchema).min(1),\n pinned_session: z.object({\n idle_timeout_ms: z.number().int().min(1000).default(1_800_000),\n key_scope: z\n .array(z.enum(CONTINUATION_KEY_SCOPES))\n .min(1)\n .default([\"conversation\", \"operator\"]),\n }).strict().optional(),\n}).strict().refine(\n // The chosen `default` must appear in `supported` — otherwise the\n // host has no valid strategy to fall back to.\n c => c.supported.includes(c.default),\n {\n message: \"continuation.default must be a member of continuation.supported\",\n }\n)\n\nconst mcpBlockSchema = z.object({\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n transport: z.enum([\"stdio\", \"http\", \"sse\"]),\n url: z.string().url().optional(),\n}).strict()\n\nexport const agentCliFrontmatterSchema = z\n .object({\n name: z.string().min(1).max(80),\n id: z.string().regex(ID_PATTERN),\n description: z.string().min(1).max(2000),\n version: z.string().regex(SEMVER_PATTERN),\n bin: z.string().regex(BIN_PATTERN),\n bin_args: z.array(z.string()).optional(),\n install: z.array(installMethodSchema).min(1),\n version_check: versionCheckSchema,\n auth: authSchema.optional(),\n sandbox: z.union([z.string(), z.record(z.string(), z.unknown())]),\n runner: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),\n protocol: z.enum([\"acp\", \"mcp\", \"proprietary\"]),\n acp: z.string().optional(),\n mcp: mcpBlockSchema.optional(),\n adapter: z.string().regex(ADAPTER_PATTERN).optional(),\n session: sessionSchema.optional(),\n models: modelsSchema.optional(),\n capabilities: capabilitiesSchema.optional(),\n modes: z.array(modeSchema).optional(),\n options: z.array(optionSchema).optional(),\n continuation: continuationSchema.optional(),\n requires: z.object({\n os: z.array(z.enum([\"darwin\", \"linux\", \"windows\"])).optional(),\n arch: z.array(z.enum([\"x64\", \"arm64\", \"x86\", \"arm\"])).optional(),\n min_disk_mb: z.number().int().nonnegative().optional(),\n min_memory_mb: z.number().int().nonnegative().optional(),\n }).strict().optional(),\n examples: z.array(z.object({\n goal: z.string(),\n prompt: z.string(),\n note: z.string().optional(),\n }).strict()).optional(),\n tags: z.array(z.string().regex(TAG_PATTERN)).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .strict()\n .superRefine((m, ctx) => {\n // Unique mode ids — duplicates would silently shadow.\n if (m.modes) {\n const seen = new Set<string>()\n for (const mode of m.modes) {\n if (seen.has(mode.id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"modes\"],\n message: `Duplicate mode id '${mode.id}' — mode ids must be unique within a manifest.`,\n })\n }\n seen.add(mode.id)\n }\n }\n // Unique option ids — same reasoning as modes.\n if (m.options) {\n const seen = new Set<string>()\n for (const opt of m.options) {\n if (seen.has(opt.id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"options\"],\n message: `Duplicate option id '${opt.id}' — option ids must be unique within a manifest.`,\n })\n }\n seen.add(opt.id)\n }\n }\n // continuation.default === \"native-resume\" requires capabilities.resumable: true.\n // Mirrors the JSON Schema's allOf rule so both validation paths\n // reject the same shape.\n if (\n m.continuation?.default === \"native-resume\" &&\n !m.capabilities?.resumable\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"continuation\", \"default\"],\n message:\n \"continuation.default === 'native-resume' requires capabilities.resumable: true.\",\n })\n }\n })\n .describe(\n \"Validates the YAML frontmatter portion of an AIP-45 AGENT-CLI.md manifest.\",\n )\n\nexport type AgentCliFrontmatter = z.infer<typeof agentCliFrontmatterSchema>\n\n// Re-export the per-call config schema for hosts that want to validate\n// `OPERATOR.runtime.config` against a manifest at load time. Validation\n// against the manifest's modes/options/continuation lives in\n// `manifest/compose.ts` (the spawn-arg composer) — this schema covers\n// only the SHAPE checks (types, enum values).\nexport const runtimeConfigSchema = z.object({\n mode: z.string().optional(),\n options: z.record(z.string(), z.union([z.boolean(), z.number(), z.string()]))\n .optional(),\n continuation: continuationStrategyIdSchema.optional(),\n}).strict()\n\nexport type RuntimeConfigInput = z.infer<typeof runtimeConfigSchema>\n","/**\n * AIP-45 protocol arm: `protocol: \"acp\"`.\n *\n * Wraps a subprocess's stdio in an `@agentproto/acp` client and\n * exposes the `AgentCliClient` shape the runner consumes. Each\n * `send()` call delegates to a single AcpClientSession.prompt() and\n * forwards the resulting StreamEvent stream.\n */\n\nimport type { ChildProcess } from \"node:child_process\"\nimport { Readable, Writable } from \"node:stream\"\nimport {\n createAcpClient,\n type AcpClient,\n type AcpClientSession,\n} from \"@agentproto/acp/client\"\nimport type {\n AgentCliClient,\n AgentCliConnectOptions,\n StreamEvent,\n} from \"../types.js\"\n\nexport interface AcpProtocolOptions {\n child: ChildProcess\n cwd: string\n clientInfo?: { name: string; title?: string; version?: string }\n}\n\nexport function createAcpProtocolArm(\n options: AcpProtocolOptions,\n): AgentCliClient {\n const { child, cwd } = options\n\n if (!child.stdin || !child.stdout) {\n throw new Error(\n \"AcpProtocolArm: subprocess must be spawned with piped stdin + stdout\",\n )\n }\n\n const output = Writable.toWeb(child.stdin) as WritableStream<Uint8Array>\n const input = Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>\n\n let client: AcpClient | null = null\n let session: AcpClientSession | null = null\n const pendingByTurn = new Map<string, AsyncIterable<StreamEvent>>()\n\n return {\n get sessionId(): string | undefined {\n return session?.sessionId\n },\n async connect(opts: AgentCliConnectOptions) {\n client = await createAcpClient({\n output,\n input,\n clientInfo: options.clientInfo,\n capabilities: {\n fs: { readTextFile: true, writeTextFile: true },\n },\n })\n // When the host hands us a `resumeSessionId`, reattach to the\n // agent's existing session via `loadSession` so the conversation\n // (model context, tool history, working files) carries over a\n // cold start. We trust the host to only send ids it persisted\n // from a prior turn; if the agent's `loadSession: true` capability\n // wasn't advertised the SDK call surfaces the per-protocol error.\n //\n // No silent fallback to `newSession` on resume failure — that\n // would create a new session quietly and lose continuity, which\n // is the bug we're trying to prevent. Let the error propagate.\n if (opts.resumeSessionId) {\n session = await client.loadSession({\n sessionId: opts.resumeSessionId,\n cwd,\n })\n } else {\n session = await client.newSession({ cwd })\n }\n },\n async send(turnId, message) {\n if (!session) throw new Error(\"AcpProtocolArm.send: not connected\")\n // ACP's `prompt` field is `ContentBlock[]` — multiple blocks\n // together form the user's turn (text + image + resource_link\n // + ...). Callers MAY pass either:\n // - a single block (`{type:\"text\",text:\"...\"}`) — wrapped\n // into a one-element array for the wire\n // - an array of blocks — forwarded verbatim, supporting\n // multimodal turns without callers re-shaping per-arm\n const messages = Array.isArray(message) ? message : [message]\n const stream = session.prompt({ messages })\n pendingByTurn.set(turnId, stream)\n },\n async *events(): AsyncIterable<StreamEvent> {\n const last = Array.from(pendingByTurn.values()).at(-1)\n if (!last) return\n for await (const evt of last) yield evt\n },\n async cancel(_turnId) {\n if (!session) return\n await session.cancel()\n },\n async close() {\n if (session) await session.close()\n if (client) await client.close()\n },\n }\n}\n","/**\n * Spawn-argument composer.\n *\n * Pure function: given an `AgentCliHandle` and a per-call\n * `RuntimeConfig`, produces the final `binArgs + env` to pass to the\n * runtime's `start()`. Validates the config against the manifest's\n * declared `modes` / `options` / `continuation.supported`; unknown ids\n * throw `RuntimeConfigError` (the host should NOT spawn — the user\n * configured something the manifest doesn't accept).\n *\n * Composition order (matches AIP-45 spec):\n * 1. Manifest's default `bin_args` (from `handle.bin_args`).\n * 2. Mode patch (`bin_args_append`, `env`) when `config.mode` set.\n * 3. Option patches in DECLARATION order (`bin_args_template` /\n * `bin_args_append_when_true` / `env`) for each option present\n * in `config.options`.\n *\n * Mode is applied before options because modes are coarse profile\n * switches (claude-code's `--permission-mode`) — options refine them.\n * Within options, declaration order is honoured so adapter authors\n * can express \"this flag must come after that one\" without the host\n * needing to know the rule.\n */\n\nimport type {\n AgentCliHandle,\n AgentCliOption,\n RuntimeConfig,\n} from \"../types.js\"\n\n/**\n * Thrown when `RuntimeConfig` references manifest entries that don't\n * exist or violates a declared constraint (type / enum / bounds). The\n * `code` field lets callers map to friendly UI messages without\n * inspecting the message string.\n */\nexport class RuntimeConfigError extends Error {\n readonly code:\n | \"unknown_mode\"\n | \"unknown_option\"\n | \"option_type_mismatch\"\n | \"option_enum_violation\"\n | \"option_bounds_violation\"\n | \"unsupported_continuation\"\n readonly path: string\n constructor(\n code: RuntimeConfigError[\"code\"],\n path: string,\n message: string\n ) {\n super(`[${code} at ${path}] ${message}`)\n this.code = code\n this.path = path\n this.name = \"RuntimeConfigError\"\n }\n}\n\n/**\n * Resolved spawn args + env. The runtime's `start()` impl merges\n * `env` into the host process env / sandbox env before exec.\n */\nexport interface ComposedSpawn {\n binArgs: string[]\n env: Record<string, string>\n}\n\n/**\n * Compose the final spawn args from a manifest + per-call config.\n * Pure — no I/O, no sandbox access, no global state. Safe to call\n * repeatedly with the same input.\n *\n * `config` may be undefined or an empty object — both fall back to\n * the manifest's defaults verbatim (manifest `bin_args`, no mode\n * patch, no option patches). Continuation is not applied here — the\n * `ContinuationStrategy` registry handles that — but we DO validate\n * `config.continuation` against `manifest.continuation.supported` so\n * a misconfigured operator fails fast at compose time, not at the\n * point the strategy tries to acquire a session.\n */\nexport function composeSpawn(\n handle: AgentCliHandle,\n config?: RuntimeConfig\n): ComposedSpawn {\n const binArgs: string[] = [...(handle.bin_args ?? [])]\n const env: Record<string, string> = {}\n\n if (!config) return { binArgs, env }\n\n // ── Mode patch ──────────────────────────────────────────────────\n if (config.mode !== undefined) {\n const mode = (handle.modes ?? []).find(m => m.id === config.mode)\n if (!mode) {\n const known = (handle.modes ?? []).map(m => m.id).join(\", \") || \"(none)\"\n throw new RuntimeConfigError(\n \"unknown_mode\",\n \"config.mode\",\n `Mode '${config.mode}' is not declared by manifest '${handle.id}'. Known modes: ${known}`\n )\n }\n if (mode.bin_args_append) binArgs.push(...mode.bin_args_append)\n if (mode.env) Object.assign(env, mode.env)\n }\n\n // ── Option patches (declaration order) ──────────────────────────\n if (config.options && Object.keys(config.options).length > 0) {\n const declared = handle.options ?? []\n const declaredById = new Map(declared.map(o => [o.id, o]))\n // Reject unknown ids first so the operator sees ALL the typos\n // (not just the one we hit first when iterating declared).\n for (const id of Object.keys(config.options)) {\n if (!declaredById.has(id)) {\n const known = declared.map(o => o.id).join(\", \") || \"(none)\"\n throw new RuntimeConfigError(\n \"unknown_option\",\n `config.options.${id}`,\n `Option '${id}' is not declared by manifest '${handle.id}'. Known options: ${known}`\n )\n }\n }\n // Then apply patches in declaration order so adapter-author intent\n // wins over operator-config key order.\n for (const option of declared) {\n if (!(option.id in config.options)) continue\n const value = config.options[option.id] as boolean | number | string\n validateOptionValue(option, value)\n const patch = renderOptionPatch(option, value)\n binArgs.push(...patch.binArgs)\n Object.assign(env, patch.env)\n }\n }\n\n // ── Continuation validation (no patch — strategy registry owns) ─\n if (config.continuation !== undefined && handle.continuation) {\n if (!handle.continuation.supported.includes(config.continuation)) {\n throw new RuntimeConfigError(\n \"unsupported_continuation\",\n \"config.continuation\",\n `Continuation strategy '${config.continuation}' is not in manifest '${handle.id}'.continuation.supported (${handle.continuation.supported.join(\", \")}).`\n )\n }\n }\n\n return { binArgs, env }\n}\n\n/**\n * Resolve the continuation strategy id to use for this call. Operator\n * config wins; manifest default is the fallback; \"none\" if neither\n * declares anything (preserves pre-AIP-45-extension behaviour).\n */\nexport function resolveContinuationStrategy(\n handle: AgentCliHandle,\n config?: RuntimeConfig\n): import(\"../types.js\").ContinuationStrategyId {\n if (config?.continuation) return config.continuation\n return handle.continuation?.default ?? \"none\"\n}\n\nfunction validateOptionValue(\n option: AgentCliOption,\n value: boolean | number | string\n): void {\n const path = `config.options.${option.id}`\n switch (option.type) {\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected boolean, got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n return\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected integer, got ${typeof value === \"number\" ? \"non-integer number\" : typeof value} (${JSON.stringify(value)}).`\n )\n }\n if (option.min !== undefined && value < option.min) {\n throw new RuntimeConfigError(\n \"option_bounds_violation\",\n path,\n `Value ${value} is below the declared minimum ${option.min}.`\n )\n }\n if (option.max !== undefined && value > option.max) {\n throw new RuntimeConfigError(\n \"option_bounds_violation\",\n path,\n `Value ${value} is above the declared maximum ${option.max}.`\n )\n }\n return\n case \"string\":\n if (typeof value !== \"string\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected string, got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n return\n case \"enum\":\n if (typeof value !== \"string\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected string (enum value), got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n if (!(option.enum ?? []).includes(value)) {\n throw new RuntimeConfigError(\n \"option_enum_violation\",\n path,\n `Value '${value}' is not in the declared enum (${(option.enum ?? []).join(\", \")}).`\n )\n }\n return\n }\n}\n\nfunction renderOptionPatch(\n option: AgentCliOption,\n value: boolean | number | string\n): { binArgs: string[]; env: Record<string, string> } {\n const stringValue = String(value)\n\n // boolean type: only emit the bare flag when value === true and the\n // option declared `bin_args_append_when_true`. Honor `env` too —\n // adapter authors might want to surface the bool via env.\n if (option.type === \"boolean\") {\n if (value !== true) return { binArgs: [], env: {} }\n return {\n binArgs: option.bin_args_append_when_true\n ? [...option.bin_args_append_when_true]\n : [],\n env: option.env ? interpolateEnv(option.env, stringValue) : {},\n }\n }\n\n // value-bearing types — apply `bin_args_template` (with `{value}`\n // interpolation) and merge `env`.\n return {\n binArgs: option.bin_args_template\n ? option.bin_args_template.map(token =>\n token.replace(/\\{value\\}/g, stringValue)\n )\n : [],\n env: option.env ? interpolateEnv(option.env, stringValue) : {},\n }\n}\n\nfunction interpolateEnv(\n env: Record<string, string>,\n value: string\n): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(env)) {\n out[k] = v.replace(/\\{value\\}/g, value)\n }\n return out\n}\n","import { spawn, type ChildProcess } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport { createDoctype } from \"@agentproto/define-doctype\"\nimport { agentCliFrontmatterSchema } from \"./schema.js\"\nimport { createAcpProtocolArm } from \"./protocol/acp-client.js\"\nimport { composeSpawn } from \"./manifest/compose.js\"\nimport type {\n AgentCliClient,\n AgentCliDefinition,\n AgentCliHandle,\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n StreamEvent,\n} from \"./types.js\"\n\nexport const defineAgentCli = createDoctype<AgentCliDefinition, AgentCliHandle>(\n {\n aip: 45,\n name: \"agent-cli\",\n readIdentity: (def) => def.id,\n validate(def) {\n const result = agentCliFrontmatterSchema.safeParse(def)\n if (!result.success) {\n throw new Error(\n `defineAgentCli (AIP-45): ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n\n const data = result.data\n\n if (data.protocol === \"acp\" && !data.acp) {\n throw new Error(\n \"defineAgentCli (AIP-45): `acp` ref is required when protocol=acp\",\n )\n }\n if (data.protocol === \"mcp\" && !data.mcp) {\n throw new Error(\n \"defineAgentCli (AIP-45): `mcp` block is required when protocol=mcp\",\n )\n }\n if (data.protocol === \"proprietary\" && !data.adapter) {\n throw new Error(\n \"defineAgentCli (AIP-45): `adapter` package is required when protocol=proprietary\",\n )\n }\n\n if (\n data.session?.mode === \"resumable\" &&\n data.capabilities?.resumable !== true\n ) {\n throw new Error(\n \"defineAgentCli (AIP-45): session.mode=resumable requires capabilities.resumable: true\",\n )\n }\n },\n build(def) {\n return { ...def } as AgentCliHandle\n },\n },\n)\n\nexport function createAgentCliRuntime(\n definition: AgentCliHandle,\n): AgentCliRuntime {\n return {\n definition,\n async start(opts?: AgentCliStartOptions): Promise<AgentCliRuntimeSession> {\n const cwd = opts?.cwd ?? process.cwd()\n // Compose final argv + env from the manifest + per-call config.\n // Mode patches and option patches land BEFORE the host-provided\n // env so an operator-set option can be observed by the CLI even\n // when the manifest also touches the same env key (operator\n // intent wins). Validation runs here too — a misconfigured\n // operator throws RuntimeConfigError before we exec anything.\n const composed = composeSpawn(definition, opts?.config)\n const env: Record<string, string> = {\n ...filterStringEnv(process.env),\n ...composed.env,\n ...(opts?.env ?? {}),\n }\n\n const child = spawn(definition.bin, composed.binArgs, {\n cwd,\n env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n signal: opts?.signal,\n })\n\n const arm = buildProtocolArm(definition, child, cwd)\n\n const abortController = new AbortController()\n if (opts?.signal) {\n opts.signal.addEventListener(\"abort\", () => abortController.abort(), {\n once: true,\n })\n }\n await arm.connect({\n cwd,\n env,\n abortSignal: abortController.signal,\n ...(opts?.resumeSessionId\n ? { resumeSessionId: opts.resumeSessionId }\n : {}),\n })\n\n // Prefer the protocol-layer session id (ACP, etc.) so the host\n // can persist it for a future native-resume. Fall back to a\n // random UUID for protocols that don't model sessions — keeps\n // the field always-populated for downstream loggers.\n const sessionId = arm.sessionId ?? randomUUID()\n\n return {\n sessionId,\n send(message): AsyncIterable<StreamEvent> {\n const turnId = randomUUID()\n return promptTurn(arm, turnId, message)\n },\n async cancel() {\n abortController.abort()\n },\n async close() {\n await arm.close()\n if (!child.killed) child.kill(\"SIGTERM\")\n },\n }\n },\n }\n}\n\nasync function* promptTurn(\n arm: AgentCliClient,\n turnId: string,\n message: unknown,\n): AsyncIterable<StreamEvent> {\n await arm.send(turnId, message)\n for await (const evt of arm.events()) yield evt\n}\n\nfunction buildProtocolArm(\n def: AgentCliHandle,\n child: ChildProcess,\n cwd: string,\n): AgentCliClient {\n switch (def.protocol) {\n case \"acp\":\n return createAcpProtocolArm({\n child,\n cwd,\n clientInfo: { name: def.id, version: def.version },\n })\n case \"mcp\":\n throw new Error(\"createAgentCliRuntime: mcp protocol arm not yet implemented\")\n case \"proprietary\":\n throw new Error(\n \"createAgentCliRuntime: proprietary protocol arm not yet implemented\",\n )\n }\n}\n\nfunction filterStringEnv(env: NodeJS.ProcessEnv): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(env)) {\n if (typeof v === \"string\") out[k] = v\n }\n return out\n}\n"]}
@@ -0,0 +1,234 @@
1
+ import { A as AgentCliHandle, a as AgentCliRuntime, b as AgentCliDefinition, c as AgentCliClient, R as RuntimeConfig, C as ContinuationStrategyId, d as AgentCliStartOptions, T as TurnContext, e as AgentCliRuntimeSession, f as ContinuationKeyScope } from './schema-CdCb4gW1.js';
2
+ export { g as AgentCliAuth, h as AgentCliCapabilities, i as AgentCliConnectOptions, j as AgentCliContinuation, k as AgentCliFrontmatter, l as AgentCliInstallMethod, m as AgentCliMcpBlock, n as AgentCliMode, o as AgentCliModels, p as AgentCliOption, q as AgentCliOptionType, r as AgentCliPinnedSessionTuning, s as AgentCliProtocol, t as AgentCliSession, u as AgentCliSessionMode, v as AgentCliVersionCheck, w as RuntimeConfigInput, x as agentCliFrontmatterSchema, y as runtimeConfigSchema } from './schema-CdCb4gW1.js';
3
+ import { ChildProcess } from 'node:child_process';
4
+ export { StreamEvent } from '@agentproto/acp';
5
+ import 'zod';
6
+
7
+ declare const defineAgentCli: (def: AgentCliDefinition) => Readonly<AgentCliDefinition>;
8
+ declare function createAgentCliRuntime(definition: AgentCliHandle): AgentCliRuntime;
9
+
10
+ /**
11
+ * AIP-45 protocol arm: `protocol: "acp"`.
12
+ *
13
+ * Wraps a subprocess's stdio in an `@agentproto/acp` client and
14
+ * exposes the `AgentCliClient` shape the runner consumes. Each
15
+ * `send()` call delegates to a single AcpClientSession.prompt() and
16
+ * forwards the resulting StreamEvent stream.
17
+ */
18
+
19
+ interface AcpProtocolOptions {
20
+ child: ChildProcess;
21
+ cwd: string;
22
+ clientInfo?: {
23
+ name: string;
24
+ title?: string;
25
+ version?: string;
26
+ };
27
+ }
28
+ declare function createAcpProtocolArm(options: AcpProtocolOptions): AgentCliClient;
29
+
30
+ /**
31
+ * Thrown when `RuntimeConfig` references manifest entries that don't
32
+ * exist or violates a declared constraint (type / enum / bounds). The
33
+ * `code` field lets callers map to friendly UI messages without
34
+ * inspecting the message string.
35
+ */
36
+ declare class RuntimeConfigError extends Error {
37
+ readonly code: "unknown_mode" | "unknown_option" | "option_type_mismatch" | "option_enum_violation" | "option_bounds_violation" | "unsupported_continuation";
38
+ readonly path: string;
39
+ constructor(code: RuntimeConfigError["code"], path: string, message: string);
40
+ }
41
+ /**
42
+ * Resolved spawn args + env. The runtime's `start()` impl merges
43
+ * `env` into the host process env / sandbox env before exec.
44
+ */
45
+ interface ComposedSpawn {
46
+ binArgs: string[];
47
+ env: Record<string, string>;
48
+ }
49
+ /**
50
+ * Compose the final spawn args from a manifest + per-call config.
51
+ * Pure — no I/O, no sandbox access, no global state. Safe to call
52
+ * repeatedly with the same input.
53
+ *
54
+ * `config` may be undefined or an empty object — both fall back to
55
+ * the manifest's defaults verbatim (manifest `bin_args`, no mode
56
+ * patch, no option patches). Continuation is not applied here — the
57
+ * `ContinuationStrategy` registry handles that — but we DO validate
58
+ * `config.continuation` against `manifest.continuation.supported` so
59
+ * a misconfigured operator fails fast at compose time, not at the
60
+ * point the strategy tries to acquire a session.
61
+ */
62
+ declare function composeSpawn(handle: AgentCliHandle, config?: RuntimeConfig): ComposedSpawn;
63
+ /**
64
+ * Resolve the continuation strategy id to use for this call. Operator
65
+ * config wins; manifest default is the fallback; "none" if neither
66
+ * declares anything (preserves pre-AIP-45-extension behaviour).
67
+ */
68
+ declare function resolveContinuationStrategy(handle: AgentCliHandle, config?: RuntimeConfig): ContinuationStrategyId;
69
+
70
+ /**
71
+ * AIP-45 ContinuationStrategy interface.
72
+ *
73
+ * A continuation strategy decides HOW prior conversation turns reach a
74
+ * spawned CLI on subsequent invocations. Built-ins handle:
75
+ *
76
+ * - `none` — fresh session per call (current pre-AIP-45 behaviour)
77
+ * - `pinned-session` — keep the spawned child alive, reuse across turns
78
+ * - `transcript` — caller-supplied preamble prepended to each turn
79
+ * - `native-resume` — pass a session id to the CLI's own `--resume` flag
80
+ *
81
+ * Adapter packages MAY register custom strategies via the registry —
82
+ * for example, a Goose-specific strategy that uses MCP-side session
83
+ * load semantics. Custom strategy ids require a follow-up AIP that
84
+ * opens the `ContinuationStrategyId` enum (so the manifest schema can
85
+ * validate them).
86
+ *
87
+ * The strategy owns the SESSION LIFECYCLE: `acquire` returns a session
88
+ * the caller can `send()` against, and `release` decides whether the
89
+ * session lives on (pinned-session) or closes immediately (none). The
90
+ * runner / generation strategy MUST go through `acquire`/`release` —
91
+ * it MUST NOT call `runtime.start()` / `session.close()` directly when
92
+ * a strategy is active.
93
+ */
94
+
95
+ /**
96
+ * Per-acquire context the strategy gets. The runner builds this from
97
+ * the manifest, the operator config, and the current turn's identity.
98
+ */
99
+ interface AcquireContext {
100
+ runtime: AgentCliRuntime;
101
+ /** Already-composed start options (cwd / env / signal / config /
102
+ * turnCtx). Strategies MAY override individual fields when they
103
+ * call `runtime.start(...)` themselves. */
104
+ startOptions: AgentCliStartOptions;
105
+ /** Per-call config (already validated against the manifest). */
106
+ config: RuntimeConfig;
107
+ /** Identity context for key derivation. */
108
+ turnCtx: TurnContext;
109
+ }
110
+ /**
111
+ * Strategies can hint to the runner about how the turn played out so
112
+ * the strategy can decide whether to keep the session alive (normal
113
+ * end), reset its TTL but keep it (transient error), or evict it
114
+ * (dead-process error).
115
+ */
116
+ type ReleaseOutcome = {
117
+ kind: "completed";
118
+ } | {
119
+ kind: "cancelled";
120
+ } | {
121
+ kind: "error";
122
+ reason: "transient" | "fatal";
123
+ message: string;
124
+ };
125
+ interface ReleaseContext {
126
+ session: AgentCliRuntimeSession;
127
+ outcome: ReleaseOutcome;
128
+ turnCtx: TurnContext;
129
+ }
130
+ /**
131
+ * The strategy contract. `acquire` returns a session ready for the
132
+ * caller to `send()` against — fresh OR reused. `release` decides
133
+ * the session's fate. Strategies MAY hold internal state (e.g.
134
+ * the pinned-session map) keyed by `turnCtx`.
135
+ */
136
+ interface ContinuationStrategy {
137
+ readonly id: ContinuationStrategyId;
138
+ acquire(ctx: AcquireContext): Promise<AgentCliRuntimeSession>;
139
+ release(ctx: ReleaseContext): Promise<void>;
140
+ }
141
+ /**
142
+ * Derive a stable pin key from `turnCtx` according to the manifest's
143
+ * `pinned_session.key_scope`. Missing scope fields downgrade to a
144
+ * less-specific key with a warning — pinning still works, it just
145
+ * collides more.
146
+ *
147
+ * Returns `null` when EVERY scope field the manifest asked for is
148
+ * missing (no key derivable; strategy falls back to per-spawn).
149
+ */
150
+ declare function deriveKeyFromScope(scope: ContinuationKeyScope[], turnCtx: TurnContext): string | null;
151
+
152
+ /**
153
+ * Continuation strategy registry.
154
+ *
155
+ * Module-scoped singleton — all built-ins are registered at import
156
+ * time, custom strategies (from adapter packages) register via
157
+ * `registerContinuationStrategy`. The runner looks up by id;
158
+ * unregistered ids throw at acquire-time so the caller fails fast
159
+ * with a clear "this strategy id isn't registered" message.
160
+ */
161
+
162
+ /**
163
+ * Register (or replace) a continuation strategy. Adapter packages
164
+ * MAY register custom strategies on import — but they MUST first
165
+ * land an AIP that opens the `ContinuationStrategyId` enum so the
166
+ * manifest schema accepts the new id.
167
+ */
168
+ declare function registerContinuationStrategy(strategy: ContinuationStrategy): void;
169
+ declare function getContinuationStrategy(id: ContinuationStrategyId): ContinuationStrategy;
170
+ declare function listContinuationStrategies(): ContinuationStrategyId[];
171
+
172
+ /**
173
+ * `native-resume` strategy — reattach to the agent's own session by id
174
+ * (ACP `loadSession`, MCP equivalent, or argv-style `--resume`).
175
+ *
176
+ * Two-step lifecycle:
177
+ * 1. **acquire**: look up a persisted sessionId for `turnCtx` via
178
+ * `loadHook`. If found, pass it to `runtime.start` as
179
+ * `resumeSessionId` so the protocol arm reattaches. If not, spawn
180
+ * fresh — and after the session is up, capture the new id from
181
+ * `session.sessionId` and persist it via `saveHook`.
182
+ * 2. **release**: close the spawned process. The session lives in
183
+ * the agent's storage layer (e.g. Claude Code's JSONL files);
184
+ * cold-start resume on the next acquire reads from that store.
185
+ *
186
+ * Hooks are registered once per host process via
187
+ * `configureNativeResume({ load, save })`. Without hooks the strategy
188
+ * degrades to per-spawn behaviour with a one-line warning — it's not
189
+ * fatal because the spawn still works, just without continuity.
190
+ *
191
+ * Requires the manifest to declare `capabilities.resumable: true`
192
+ * AND the agent to advertise the matching protocol capability (e.g.
193
+ * ACP `loadSession: true`). The schema enforces the manifest side at
194
+ * validation; runtime capability mismatch surfaces from the protocol
195
+ * arm as the agent's own error.
196
+ */
197
+
198
+ interface NativeResumeHooks {
199
+ /** Look up a persisted sessionId for the given identity scope. Return
200
+ * undefined when no prior session exists — strategy spawns fresh. */
201
+ load: (turnCtx: TurnContext) => Promise<string | undefined>;
202
+ /** Persist a freshly-established sessionId so the next cold start
203
+ * can resume. Called once per "fresh spawn" acquire (not per turn).
204
+ * Idempotent / upsert semantics expected on the host side. */
205
+ save: (turnCtx: TurnContext, sessionId: string) => Promise<void>;
206
+ /** Optional: drop the persisted entry when a session is detected as
207
+ * unresumable (agent rejected loadSession with a hard error). */
208
+ forget?: (turnCtx: TurnContext) => Promise<void>;
209
+ }
210
+ /**
211
+ * Register the host's session-id load/save callbacks. Call once at
212
+ * boot. Subsequent calls overwrite — useful in tests; in prod treat
213
+ * the registration as exclusive.
214
+ */
215
+ declare function configureNativeResume(hooks: NativeResumeHooks): void;
216
+
217
+ /**
218
+ * @agentproto/driver-agent-cli — AIP-45 AGENT-CLI.md `defineAgentCli`
219
+ * reference impl.
220
+ *
221
+ * Spec: https://agentproto.sh/docs/aip-45
222
+ *
223
+ * Authoring paths:
224
+ * - TS: `defineAgentCli({...})` → `AgentCliHandle`
225
+ * - MD: `parseAgentCliManifest(src) → agentCliFromManifest({...})` → `AgentCliHandle`
226
+ *
227
+ * Runtime: `createAgentCliRuntime(handle)` → spawn binary, dispatch
228
+ * turns through the protocol arm (acp / mcp / proprietary), normalise
229
+ * events to {@link StreamEvent}.
230
+ */
231
+ declare const SPEC_NAME: "agentcli-interactive/v1";
232
+ declare const SPEC_VERSION: "0.1.0-alpha";
233
+
234
+ export { type AcquireContext, AgentCliClient, AgentCliDefinition, AgentCliHandle, AgentCliRuntime, AgentCliRuntimeSession, AgentCliStartOptions, type ComposedSpawn, ContinuationKeyScope, type ContinuationStrategy, ContinuationStrategyId, type NativeResumeHooks, type ReleaseContext, type ReleaseOutcome, RuntimeConfig, RuntimeConfigError, SPEC_NAME, SPEC_VERSION, TurnContext, composeSpawn, configureNativeResume, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, deriveKeyFromScope, getContinuationStrategy, listContinuationStrategies, registerContinuationStrategy, resolveContinuationStrategy };
package/dist/index.mjs ADDED
@@ -0,0 +1,226 @@
1
+ export { RuntimeConfigError, agentCliFrontmatterSchema, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, resolveContinuationStrategy, runtimeConfigSchema } from './chunk-EEIYDRIU.mjs';
2
+
3
+ /**
4
+ * @agentproto/driver-agent-cli v0.1.0-alpha
5
+ * AIP-45 AGENT-CLI.md `defineAgentCli` reference implementation.
6
+ */
7
+
8
+ // src/continuation/strategies/none.ts
9
+ var noneStrategy = {
10
+ id: "none",
11
+ async acquire(ctx) {
12
+ return ctx.runtime.start(ctx.startOptions);
13
+ },
14
+ async release(ctx) {
15
+ await ctx.session.close();
16
+ }
17
+ };
18
+
19
+ // src/continuation/types.ts
20
+ function deriveKeyFromScope(scope, turnCtx) {
21
+ const parts = [];
22
+ for (const s of scope) {
23
+ const v = turnCtx[s];
24
+ if (v) parts.push(`${s}=${v}`);
25
+ }
26
+ return parts.length === 0 ? null : parts.join("|");
27
+ }
28
+
29
+ // src/continuation/strategies/pinned-session.ts
30
+ var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1e3;
31
+ var pins = /* @__PURE__ */ new Map();
32
+ function clearIdleTimer(entry) {
33
+ if (entry.idleTimer) {
34
+ clearTimeout(entry.idleTimer);
35
+ entry.idleTimer = null;
36
+ }
37
+ }
38
+ function scheduleIdleEviction(key, entry, idleTimeoutMs) {
39
+ clearIdleTimer(entry);
40
+ entry.idleTimer = setTimeout(() => {
41
+ pins.delete(key);
42
+ entry.session.close().catch((err) => {
43
+ console.warn(
44
+ `[pinned-session] idle close failed for ${key}:`,
45
+ err instanceof Error ? err.message : err
46
+ );
47
+ });
48
+ console.log(
49
+ `[pinned-session] ${key} idle ${idleTimeoutMs / 6e4}m \u2192 closed`
50
+ );
51
+ }, idleTimeoutMs);
52
+ entry.idleTimer.unref?.();
53
+ }
54
+ function evictPin(key) {
55
+ const entry = pins.get(key);
56
+ if (!entry) return;
57
+ clearIdleTimer(entry);
58
+ pins.delete(key);
59
+ entry.session.close().catch((err) => {
60
+ console.warn(
61
+ `[pinned-session] evict close failed for ${key}:`,
62
+ err instanceof Error ? err.message : err
63
+ );
64
+ });
65
+ }
66
+ var pinnedSessionStrategy = {
67
+ id: "pinned-session",
68
+ async acquire(ctx) {
69
+ const tuning = ctx.runtime.definition.continuation?.pinned_session;
70
+ const scope = tuning?.key_scope ?? ["conversation", "operator"];
71
+ const key = deriveKeyFromScope(scope, ctx.turnCtx);
72
+ const idleTimeoutMs = tuning?.idle_timeout_ms ?? DEFAULT_IDLE_TIMEOUT_MS;
73
+ if (key === null) {
74
+ console.warn(
75
+ `[pinned-session] turnCtx has no fields matching key_scope ${JSON.stringify(scope)}; falling back to per-spawn (no pin).`
76
+ );
77
+ return ctx.runtime.start(ctx.startOptions);
78
+ }
79
+ const existing = pins.get(key);
80
+ if (existing) {
81
+ clearIdleTimer(existing);
82
+ return existing.session;
83
+ }
84
+ const session = await ctx.runtime.start(ctx.startOptions);
85
+ const entry = {
86
+ session,
87
+ runtime: ctx.runtime,
88
+ startOptions: ctx.startOptions,
89
+ idleTimer: null
90
+ };
91
+ pins.set(key, entry);
92
+ scheduleIdleEviction(key, entry, idleTimeoutMs);
93
+ return session;
94
+ },
95
+ async release(ctx) {
96
+ ctx.session;
97
+ const idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS;
98
+ let foundKey = null;
99
+ for (const [k, e] of pins) {
100
+ if (e.session === ctx.session) {
101
+ foundKey = k;
102
+ break;
103
+ }
104
+ }
105
+ if (!foundKey) {
106
+ await ctx.session.close();
107
+ return;
108
+ }
109
+ const entry = pins.get(foundKey);
110
+ if (ctx.outcome.kind === "error" && ctx.outcome.reason === "fatal") {
111
+ evictPin(foundKey);
112
+ return;
113
+ }
114
+ scheduleIdleEviction(foundKey, entry, idleTimeoutMs);
115
+ }
116
+ };
117
+
118
+ // src/continuation/strategies/transcript.ts
119
+ var transcriptStrategy = {
120
+ id: "transcript",
121
+ async acquire(ctx) {
122
+ return ctx.runtime.start(ctx.startOptions);
123
+ },
124
+ async release(ctx) {
125
+ await ctx.session.close();
126
+ }
127
+ };
128
+
129
+ // src/continuation/strategies/native-resume.ts
130
+ var _hooks = null;
131
+ function configureNativeResume(hooks) {
132
+ _hooks = hooks;
133
+ }
134
+ var nativeResumeStrategy = {
135
+ id: "native-resume",
136
+ async acquire(ctx) {
137
+ if (!_hooks) {
138
+ console.warn(
139
+ "[native-resume] no hooks registered (call configureNativeResume at boot); falling back to per-spawn \u2014 no continuity."
140
+ );
141
+ return ctx.runtime.start(ctx.startOptions);
142
+ }
143
+ const scope = ctx.runtime.definition.continuation?.pinned_session?.key_scope ?? [
144
+ "conversation",
145
+ "operator"
146
+ ];
147
+ const key = deriveKeyFromScope(scope, ctx.turnCtx);
148
+ if (key === null) {
149
+ console.warn(
150
+ `[native-resume] turnCtx has no fields matching key_scope ${JSON.stringify(scope)}; falling back to per-spawn (no resume).`
151
+ );
152
+ return ctx.runtime.start(ctx.startOptions);
153
+ }
154
+ const existingId = await _hooks.load(ctx.turnCtx).catch((err) => {
155
+ console.warn(
156
+ `[native-resume] load hook failed for ${key}:`,
157
+ err instanceof Error ? err.message : err
158
+ );
159
+ return void 0;
160
+ });
161
+ let session;
162
+ let resumed = false;
163
+ if (existingId) {
164
+ try {
165
+ session = await ctx.runtime.start({
166
+ ...ctx.startOptions,
167
+ resumeSessionId: existingId
168
+ });
169
+ resumed = true;
170
+ } catch (err) {
171
+ console.warn(
172
+ `[native-resume] resume failed for ${key} (id=${existingId.slice(0, 12)}\u2026), starting fresh:`,
173
+ err instanceof Error ? err.message : err
174
+ );
175
+ if (_hooks.forget) {
176
+ await _hooks.forget(ctx.turnCtx).catch(() => void 0);
177
+ }
178
+ session = await ctx.runtime.start(ctx.startOptions);
179
+ }
180
+ } else {
181
+ session = await ctx.runtime.start(ctx.startOptions);
182
+ }
183
+ if (!resumed && session.sessionId) {
184
+ await _hooks.save(ctx.turnCtx, session.sessionId).catch((err) => {
185
+ console.warn(
186
+ `[native-resume] save hook failed for ${key}:`,
187
+ err instanceof Error ? err.message : err
188
+ );
189
+ });
190
+ }
191
+ return session;
192
+ },
193
+ async release(ctx) {
194
+ await ctx.session.close();
195
+ }
196
+ };
197
+
198
+ // src/continuation/registry.ts
199
+ var registry = /* @__PURE__ */ new Map();
200
+ function registerContinuationStrategy(strategy) {
201
+ registry.set(strategy.id, strategy);
202
+ }
203
+ function getContinuationStrategy(id) {
204
+ const s = registry.get(id);
205
+ if (!s) {
206
+ throw new Error(
207
+ `[agent-cli] No continuation strategy registered for id '${id}'. Built-ins: ${Array.from(registry.keys()).join(", ")}.`
208
+ );
209
+ }
210
+ return s;
211
+ }
212
+ function listContinuationStrategies() {
213
+ return Array.from(registry.keys());
214
+ }
215
+ registerContinuationStrategy(noneStrategy);
216
+ registerContinuationStrategy(pinnedSessionStrategy);
217
+ registerContinuationStrategy(transcriptStrategy);
218
+ registerContinuationStrategy(nativeResumeStrategy);
219
+
220
+ // src/index.ts
221
+ var SPEC_NAME = "agentcli-interactive/v1";
222
+ var SPEC_VERSION = "0.1.0-alpha";
223
+
224
+ export { SPEC_NAME, SPEC_VERSION, configureNativeResume, deriveKeyFromScope, getContinuationStrategy, listContinuationStrategies, registerContinuationStrategy };
225
+ //# sourceMappingURL=index.mjs.map
226
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/continuation/strategies/none.ts","../src/continuation/types.ts","../src/continuation/strategies/pinned-session.ts","../src/continuation/strategies/transcript.ts","../src/continuation/strategies/native-resume.ts","../src/continuation/registry.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;AAUO,IAAM,YAAA,GAAqC;AAAA,EAChD,EAAA,EAAI,MAAA;AAAA,EACJ,MAAM,QAAQ,GAAA,EAAK;AACjB,IAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,KAAA,CAAM,GAAA,CAAI,YAAY,CAAA;AAAA,EAC3C,CAAA;AAAA,EACA,MAAM,QAAQ,GAAA,EAAK;AACjB,IAAA,MAAM,GAAA,CAAI,QAAQ,KAAA,EAAM;AAAA,EAC1B;AACF,CAAA;;;ACuEO,SAAS,kBAAA,CACd,OACA,OAAA,EACe;AACf,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,MAAM,CAAA,GAAI,QAAQ,CAAC,CAAA;AACnB,IAAA,IAAI,GAAG,KAAA,CAAM,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,EAAI,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,MAAM,MAAA,KAAW,CAAA,GAAI,IAAA,GAAO,KAAA,CAAM,KAAK,GAAG,CAAA;AACnD;;;AC7DA,IAAM,uBAAA,GAA0B,KAAK,EAAA,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,EAC1B;AACF,CAAA;;;AC5HA,IAAM,QAAA,uBAAe,GAAA,EAAkD;AAQhE,SAAS,6BACd,QAAA,EACM;AACN,EAAA,QAAA,CAAS,GAAA,CAAI,QAAA,CAAS,EAAA,EAAI,QAAQ,CAAA;AACpC;AAEO,SAAS,wBACd,EAAA,EACsB;AACtB,EAAA,MAAM,CAAA,GAAI,QAAA,CAAS,GAAA,CAAI,EAAE,CAAA;AACzB,EAAA,IAAI,CAAC,CAAA,EAAG;AACN,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,wDAAA,EAA2D,EAAE,CAAA,cAAA,EAAiB,KAAA,CAAM,IAAA,CAAK,QAAA,CAAS,IAAA,EAAM,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KACtH;AAAA,EACF;AACA,EAAA,OAAO,CAAA;AACT;AAEO,SAAS,0BAAA,GAAuD;AACrE,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,QAAA,CAAS,IAAA,EAAM,CAAA;AACnC;AAIA,4BAAA,CAA6B,YAAY,CAAA;AACzC,4BAAA,CAA6B,qBAAqB,CAAA;AAClD,4BAAA,CAA6B,kBAAkB,CAAA;AAC/C,4BAAA,CAA6B,oBAAoB,CAAA;;;ACrC1C,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * `none` strategy — pre-AIP-45-extension behaviour.\n *\n * Spawn a fresh session per acquire; close it on release. No state,\n * no reuse. The default when a manifest declares no `continuation`\n * block (back-compat for adapters that haven't been updated).\n */\n\nimport type { ContinuationStrategy } from \"../types.js\"\n\nexport const noneStrategy: ContinuationStrategy = {\n id: \"none\",\n async acquire(ctx) {\n return ctx.runtime.start(ctx.startOptions)\n },\n async release(ctx) {\n await ctx.session.close()\n },\n}\n","/**\n * AIP-45 ContinuationStrategy interface.\n *\n * A continuation strategy decides HOW prior conversation turns reach a\n * spawned CLI on subsequent invocations. Built-ins handle:\n *\n * - `none` — fresh session per call (current pre-AIP-45 behaviour)\n * - `pinned-session` — keep the spawned child alive, reuse across turns\n * - `transcript` — caller-supplied preamble prepended to each turn\n * - `native-resume` — pass a session id to the CLI's own `--resume` flag\n *\n * Adapter packages MAY register custom strategies via the registry —\n * for example, a Goose-specific strategy that uses MCP-side session\n * load semantics. Custom strategy ids require a follow-up AIP that\n * opens the `ContinuationStrategyId` enum (so the manifest schema can\n * validate them).\n *\n * The strategy owns the SESSION LIFECYCLE: `acquire` returns a session\n * the caller can `send()` against, and `release` decides whether the\n * session lives on (pinned-session) or closes immediately (none). The\n * runner / generation strategy MUST go through `acquire`/`release` —\n * it MUST NOT call `runtime.start()` / `session.close()` directly when\n * a strategy is active.\n */\n\nimport type {\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n ContinuationKeyScope,\n ContinuationStrategyId,\n RuntimeConfig,\n TurnContext,\n} from \"../types.js\"\n\n/**\n * Per-acquire context the strategy gets. The runner builds this from\n * the manifest, the operator config, and the current turn's identity.\n */\nexport interface AcquireContext {\n runtime: AgentCliRuntime\n /** Already-composed start options (cwd / env / signal / config /\n * turnCtx). Strategies MAY override individual fields when they\n * call `runtime.start(...)` themselves. */\n startOptions: AgentCliStartOptions\n /** Per-call config (already validated against the manifest). */\n config: RuntimeConfig\n /** Identity context for key derivation. */\n turnCtx: TurnContext\n}\n\n/**\n * Strategies can hint to the runner about how the turn played out so\n * the strategy can decide whether to keep the session alive (normal\n * end), reset its TTL but keep it (transient error), or evict it\n * (dead-process error).\n */\nexport type ReleaseOutcome =\n | { kind: \"completed\" }\n | { kind: \"cancelled\" }\n | { kind: \"error\"; reason: \"transient\" | \"fatal\"; message: string }\n\nexport interface ReleaseContext {\n session: AgentCliRuntimeSession\n outcome: ReleaseOutcome\n turnCtx: TurnContext\n}\n\n/**\n * The strategy contract. `acquire` returns a session ready for the\n * caller to `send()` against — fresh OR reused. `release` decides\n * the session's fate. Strategies MAY hold internal state (e.g.\n * the pinned-session map) keyed by `turnCtx`.\n */\nexport interface ContinuationStrategy {\n readonly id: ContinuationStrategyId\n acquire(ctx: AcquireContext): Promise<AgentCliRuntimeSession>\n release(ctx: ReleaseContext): Promise<void>\n}\n\n/**\n * Derive a stable pin key from `turnCtx` according to the manifest's\n * `pinned_session.key_scope`. Missing scope fields downgrade to a\n * less-specific key with a warning — pinning still works, it just\n * collides more.\n *\n * Returns `null` when EVERY scope field the manifest asked for is\n * missing (no key derivable; strategy falls back to per-spawn).\n */\nexport function deriveKeyFromScope(\n scope: ContinuationKeyScope[],\n turnCtx: TurnContext\n): string | null {\n const parts: string[] = []\n for (const s of scope) {\n const v = turnCtx[s]\n if (v) parts.push(`${s}=${v}`)\n }\n return parts.length === 0 ? null : parts.join(\"|\")\n}\n","/**\n * `pinned-session` strategy — keep the spawned child alive across\n * turns so the CLI's in-memory model context carries over.\n *\n * Suitable for manifests that declare `session.mode: persistent` AND\n * `context_carryover: true` (Claude Code, OpenCode, ...). Acquires\n * either reuse a live pinned session or spawn fresh and pin; releases\n * keep the session alive and reset its idle TTL. The strategy\n * auto-evicts after the manifest's `pinned_session.idle_timeout_ms`.\n *\n * The pin key is derived from `turnCtx` according to the manifest's\n * `pinned_session.key_scope` (default: `[conversation, operator]` —\n * different conversations and different operators each get their own\n * child process).\n *\n * Lost on process restart. DB-backed pin persistence is a follow-up\n * (track sessionId in `cli_sessions` table, then optionally fall back\n * to native-resume / transcript on restart).\n */\n\nimport type {\n AgentCliRuntimeSession,\n AgentCliRuntime,\n AgentCliStartOptions,\n} from \"../../types.js\"\nimport type { ContinuationStrategy } from \"../types.js\"\nimport { deriveKeyFromScope } from \"../types.js\"\n\ninterface PinnedEntry {\n session: AgentCliRuntimeSession\n /** Cached so retry-after-eviction can recreate without re-resolving\n * the runtime entry from outside. */\n runtime: AgentCliRuntime\n /** Cached so eviction-and-retry uses the same start options. */\n startOptions: AgentCliStartOptions\n idleTimer: ReturnType<typeof setTimeout> | null\n}\n\nconst DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000\n\nconst pins = new Map<string, PinnedEntry>()\n\nfunction clearIdleTimer(entry: PinnedEntry): void {\n if (entry.idleTimer) {\n clearTimeout(entry.idleTimer)\n entry.idleTimer = null\n }\n}\n\nfunction scheduleIdleEviction(\n key: string,\n entry: PinnedEntry,\n idleTimeoutMs: number\n): void {\n clearIdleTimer(entry)\n entry.idleTimer = setTimeout(() => {\n pins.delete(key)\n entry.session.close().catch(err => {\n console.warn(\n `[pinned-session] idle close failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n })\n console.log(\n `[pinned-session] ${key} idle ${idleTimeoutMs / 60_000}m → closed`\n )\n }, idleTimeoutMs)\n // Don't keep the event loop alive just for the idle close — the\n // child will be reaped on process exit anyway. Without `unref`\n // a stale pin would block graceful shutdown.\n entry.idleTimer.unref?.()\n}\n\nfunction evictPin(key: string): void {\n const entry = pins.get(key)\n if (!entry) return\n clearIdleTimer(entry)\n pins.delete(key)\n entry.session.close().catch(err => {\n console.warn(\n `[pinned-session] evict close failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n })\n}\n\nexport const pinnedSessionStrategy: ContinuationStrategy = {\n id: \"pinned-session\",\n\n async acquire(ctx) {\n const tuning = ctx.runtime.definition.continuation?.pinned_session\n const scope = tuning?.key_scope ?? [\"conversation\", \"operator\"]\n const key = deriveKeyFromScope(scope, ctx.turnCtx)\n const idleTimeoutMs = tuning?.idle_timeout_ms ?? DEFAULT_IDLE_TIMEOUT_MS\n\n if (key === null) {\n // No identity to pin against — fall back to per-spawn behaviour.\n // Warn so the host learns to populate turnCtx.\n console.warn(\n `[pinned-session] turnCtx has no fields matching key_scope ${JSON.stringify(scope)}; falling back to per-spawn (no pin).`\n )\n return ctx.runtime.start(ctx.startOptions)\n }\n\n const existing = pins.get(key)\n if (existing) {\n // Cancel the idle timer — this turn is reusing the pin.\n clearIdleTimer(existing)\n return existing.session\n }\n\n const session = await ctx.runtime.start(ctx.startOptions)\n const entry: PinnedEntry = {\n session,\n runtime: ctx.runtime,\n startOptions: ctx.startOptions,\n idleTimer: null,\n }\n pins.set(key, entry)\n scheduleIdleEviction(key, entry, idleTimeoutMs)\n return session\n },\n\n async release(ctx) {\n const tuning = ctx.session as unknown as {\n // The session itself doesn't expose key info — find the entry\n // by identity match. Acceptable since the pin map is small.\n }\n void tuning\n const idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS\n let foundKey: string | null = null\n for (const [k, e] of pins) {\n if (e.session === ctx.session) {\n foundKey = k\n break\n }\n }\n\n if (!foundKey) {\n // Session wasn't pinned (per-spawn fallback path) — close it\n // like the `none` strategy would.\n await ctx.session.close()\n return\n }\n\n const entry = pins.get(foundKey)!\n\n // Fatal errors → evict so the next turn re-spawns. Transient\n // errors and normal completion → reset the idle TTL and keep.\n // Cancelled (user aborted) is treated like normal completion —\n // the user wanted to stop this turn, not the whole session.\n if (ctx.outcome.kind === \"error\" && ctx.outcome.reason === \"fatal\") {\n evictPin(foundKey)\n return\n }\n\n scheduleIdleEviction(foundKey, entry, idleTimeoutMs)\n },\n}\n\n/**\n * Test helper — drop all pinned entries and clear timers. Not part\n * of the public API; exposed under `__test__` so tests can reset the\n * module's singleton state between runs.\n */\nexport const __test__ = {\n resetPins(): void {\n for (const [k] of pins) evictPin(k)\n },\n pinCount(): number {\n return pins.size\n },\n}\n","/**\n * `transcript` strategy — works for any CLI, including those with\n * `resumable: false` and ephemeral sessions.\n *\n * The driver doesn't know about Mastra memory or the host's\n * conversation log — that's the host's domain. The host supplies the\n * preamble at acquire-time via `startOptions.config.options` (the\n * convention is option id `__transcript`, see below) and the strategy\n * is otherwise identical to `none` — fresh session per acquire,\n * close on release.\n *\n * In practice the host does the prepending itself before calling\n * `runtime.start` (it controls the `message` text). This strategy\n * exists mostly as a NAMED policy choice in the manifest — declaring\n * it tells the host \"use the transcript-replay path for this CLI\"\n * without the host needing to inspect capabilities.\n *\n * Token-costly but stateless and survives API restarts.\n */\n\nimport type { ContinuationStrategy } from \"../types.js\"\n\nexport const transcriptStrategy: ContinuationStrategy = {\n id: \"transcript\",\n async acquire(ctx) {\n return ctx.runtime.start(ctx.startOptions)\n },\n async release(ctx) {\n await ctx.session.close()\n },\n}\n","/**\n * `native-resume` strategy — reattach to the agent's own session by id\n * (ACP `loadSession`, MCP equivalent, or argv-style `--resume`).\n *\n * Two-step lifecycle:\n * 1. **acquire**: look up a persisted sessionId for `turnCtx` via\n * `loadHook`. If found, pass it to `runtime.start` as\n * `resumeSessionId` so the protocol arm reattaches. If not, spawn\n * fresh — and after the session is up, capture the new id from\n * `session.sessionId` and persist it via `saveHook`.\n * 2. **release**: close the spawned process. The session lives in\n * the agent's storage layer (e.g. Claude Code's JSONL files);\n * cold-start resume on the next acquire reads from that store.\n *\n * Hooks are registered once per host process via\n * `configureNativeResume({ load, save })`. Without hooks the strategy\n * degrades to per-spawn behaviour with a one-line warning — it's not\n * fatal because the spawn still works, just without continuity.\n *\n * Requires the manifest to declare `capabilities.resumable: true`\n * AND the agent to advertise the matching protocol capability (e.g.\n * ACP `loadSession: true`). The schema enforces the manifest side at\n * validation; runtime capability mismatch surfaces from the protocol\n * arm as the agent's own error.\n */\n\nimport type { ContinuationStrategy, AcquireContext } from \"../types.js\"\nimport { deriveKeyFromScope } from \"../types.js\"\nimport type { TurnContext } from \"../../types.js\"\n\nexport interface NativeResumeHooks {\n /** Look up a persisted sessionId for the given identity scope. Return\n * undefined when no prior session exists — strategy spawns fresh. */\n load: (turnCtx: TurnContext) => Promise<string | undefined>\n /** Persist a freshly-established sessionId so the next cold start\n * can resume. Called once per \"fresh spawn\" acquire (not per turn).\n * Idempotent / upsert semantics expected on the host side. */\n save: (turnCtx: TurnContext, sessionId: string) => Promise<void>\n /** Optional: drop the persisted entry when a session is detected as\n * unresumable (agent rejected loadSession with a hard error). */\n forget?: (turnCtx: TurnContext) => Promise<void>\n}\n\nlet _hooks: NativeResumeHooks | null = null\n\n/**\n * Register the host's session-id load/save callbacks. Call once at\n * boot. Subsequent calls overwrite — useful in tests; in prod treat\n * the registration as exclusive.\n */\nexport function configureNativeResume(hooks: NativeResumeHooks): void {\n _hooks = hooks\n}\n\n/** Reset to no-hooks. Test helper; not part of public API. */\nexport function __resetNativeResumeForTests(): void {\n _hooks = null\n}\n\nexport const nativeResumeStrategy: ContinuationStrategy = {\n id: \"native-resume\",\n async acquire(ctx: AcquireContext) {\n if (!_hooks) {\n console.warn(\n \"[native-resume] no hooks registered (call configureNativeResume at boot); falling back to per-spawn — no continuity.\"\n )\n return ctx.runtime.start(ctx.startOptions)\n }\n // Use the same key-derivation as pinned-session so a host can\n // declare its scope ONCE in the manifest (`continuation.pinned_session.key_scope`)\n // and have both strategies key off the same identity. Native-resume\n // doesn't have its own key_scope today; it inherits.\n const scope =\n ctx.runtime.definition.continuation?.pinned_session?.key_scope ?? [\n \"conversation\",\n \"operator\",\n ]\n const key = deriveKeyFromScope(scope, ctx.turnCtx)\n if (key === null) {\n console.warn(\n `[native-resume] turnCtx has no fields matching key_scope ${JSON.stringify(scope)}; falling back to per-spawn (no resume).`\n )\n return ctx.runtime.start(ctx.startOptions)\n }\n\n const existingId = await _hooks.load(ctx.turnCtx).catch(err => {\n console.warn(\n `[native-resume] load hook failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n return undefined\n })\n\n let session\n let resumed = false\n if (existingId) {\n try {\n session = await ctx.runtime.start({\n ...ctx.startOptions,\n resumeSessionId: existingId,\n })\n resumed = true\n } catch (err) {\n // Most likely the agent rejected the id (session expired,\n // wiped, mismatched cwd). Drop the stale pin and spawn fresh\n // so the user gets continuity going forward instead of being\n // stuck on a dead reference.\n console.warn(\n `[native-resume] resume failed for ${key} (id=${existingId.slice(0, 12)}…), starting fresh:`,\n err instanceof Error ? err.message : err\n )\n if (_hooks.forget) {\n await _hooks.forget(ctx.turnCtx).catch(() => undefined)\n }\n session = await ctx.runtime.start(ctx.startOptions)\n }\n } else {\n session = await ctx.runtime.start(ctx.startOptions)\n }\n\n // Persist the established id when this is a NEW session (resume\n // path keeps the same id we already have, no need to re-save).\n // The runtime guarantees session.sessionId reflects the protocol\n // session id when the arm exposes it.\n if (!resumed && session.sessionId) {\n await _hooks.save(ctx.turnCtx, session.sessionId).catch(err => {\n console.warn(\n `[native-resume] save hook failed for ${key}:`,\n err instanceof Error ? err.message : err\n )\n })\n }\n return session\n },\n\n async release(ctx) {\n // The protocol session lives in the agent's own storage; closing\n // the spawned subprocess is fine — `loadSession` on the next\n // acquire reattaches via the persisted id.\n await ctx.session.close()\n },\n}\n","/**\n * Continuation strategy registry.\n *\n * Module-scoped singleton — all built-ins are registered at import\n * time, custom strategies (from adapter packages) register via\n * `registerContinuationStrategy`. The runner looks up by id;\n * unregistered ids throw at acquire-time so the caller fails fast\n * with a clear \"this strategy id isn't registered\" message.\n */\n\nimport type { ContinuationStrategyId } from \"../types.js\"\nimport type { ContinuationStrategy } from \"./types.js\"\nimport { noneStrategy } from \"./strategies/none.js\"\nimport { pinnedSessionStrategy } from \"./strategies/pinned-session.js\"\nimport { transcriptStrategy } from \"./strategies/transcript.js\"\nimport { nativeResumeStrategy } from \"./strategies/native-resume.js\"\n\nconst registry = new Map<ContinuationStrategyId, ContinuationStrategy>()\n\n/**\n * Register (or replace) a continuation strategy. Adapter packages\n * MAY register custom strategies on import — but they MUST first\n * land an AIP that opens the `ContinuationStrategyId` enum so the\n * manifest schema accepts the new id.\n */\nexport function registerContinuationStrategy(\n strategy: ContinuationStrategy\n): void {\n registry.set(strategy.id, strategy)\n}\n\nexport function getContinuationStrategy(\n id: ContinuationStrategyId\n): ContinuationStrategy {\n const s = registry.get(id)\n if (!s) {\n throw new Error(\n `[agent-cli] No continuation strategy registered for id '${id}'. Built-ins: ${Array.from(registry.keys()).join(\", \")}.`\n )\n }\n return s\n}\n\nexport function listContinuationStrategies(): ContinuationStrategyId[] {\n return Array.from(registry.keys())\n}\n\n// Register built-ins eagerly at module load so any importer of the\n// registry sees them. Custom strategies layer on top.\nregisterContinuationStrategy(noneStrategy)\nregisterContinuationStrategy(pinnedSessionStrategy)\nregisterContinuationStrategy(transcriptStrategy)\nregisterContinuationStrategy(nativeResumeStrategy)\n","/**\n * @agentproto/driver-agent-cli — AIP-45 AGENT-CLI.md `defineAgentCli`\n * reference impl.\n *\n * Spec: https://agentproto.sh/docs/aip-45\n *\n * Authoring paths:\n * - TS: `defineAgentCli({...})` → `AgentCliHandle`\n * - MD: `parseAgentCliManifest(src) → agentCliFromManifest({...})` → `AgentCliHandle`\n *\n * Runtime: `createAgentCliRuntime(handle)` → spawn binary, dispatch\n * turns through the protocol arm (acp / mcp / proprietary), normalise\n * events to {@link StreamEvent}.\n */\n\nexport const SPEC_NAME = \"agentcli-interactive/v1\" as const\nexport const SPEC_VERSION = \"0.1.0-alpha\" as const\n\nexport {\n defineAgentCli,\n createAgentCliRuntime,\n} from \"./define-agent-cli.js\"\n// Exposed so callers can build a sandbox-resident `AgentCliRuntime`\n// against the same protocol layer the host-spawn factory uses, by\n// passing a `ChildProcess`-shaped duck whose stdio is bridged to a\n// remote subprocess (e2b sandbox, ssh, etc.). See guilde's\n// `cli-session-spawn/sandbox-runtime.ts` for a worked example.\nexport { createAcpProtocolArm } from \"./protocol/acp-client.js\"\nexport {\n agentCliFrontmatterSchema,\n runtimeConfigSchema,\n type AgentCliFrontmatter,\n type RuntimeConfigInput,\n} from \"./schema.js\"\nexport {\n composeSpawn,\n resolveContinuationStrategy,\n RuntimeConfigError,\n type ComposedSpawn,\n} from \"./manifest/compose.js\"\nexport {\n registerContinuationStrategy,\n getContinuationStrategy,\n listContinuationStrategies,\n} from \"./continuation/registry.js\"\nexport {\n configureNativeResume,\n type NativeResumeHooks,\n} from \"./continuation/strategies/native-resume.js\"\nexport {\n deriveKeyFromScope,\n type ContinuationStrategy,\n type AcquireContext,\n type ReleaseContext,\n type ReleaseOutcome,\n} from \"./continuation/types.js\"\nexport type {\n AgentCliDefinition,\n AgentCliHandle,\n AgentCliProtocol,\n AgentCliSessionMode,\n AgentCliClient,\n AgentCliConnectOptions,\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n AgentCliCapabilities,\n AgentCliInstallMethod,\n AgentCliVersionCheck,\n AgentCliAuth,\n AgentCliSession,\n AgentCliModels,\n AgentCliMcpBlock,\n AgentCliMode,\n AgentCliOption,\n AgentCliOptionType,\n AgentCliContinuation,\n AgentCliPinnedSessionTuning,\n ContinuationStrategyId,\n ContinuationKeyScope,\n RuntimeConfig,\n TurnContext,\n StreamEvent,\n} from \"./types.js\"\n"]}