@agentproto/driver-agent-cli 0.1.0-alpha.0 → 0.1.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-EEIYDRIU.mjs → chunk-H76NLWVO.mjs} +21 -3
- package/dist/chunk-H76NLWVO.mjs.map +1 -0
- package/dist/index.d.ts +49 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/manifest/index.mjs +2 -2
- package/package.json +2 -2
- package/dist/chunk-EEIYDRIU.mjs.map +0 -1
|
@@ -226,6 +226,15 @@ var runtimeConfigSchema = z.object({
|
|
|
226
226
|
options: z.record(z.string(), z.union([z.boolean(), z.number(), z.string()])).optional(),
|
|
227
227
|
continuation: continuationStrategyIdSchema.optional()
|
|
228
228
|
}).strict();
|
|
229
|
+
var autoAllowPermissionHandler = ({
|
|
230
|
+
options
|
|
231
|
+
}) => {
|
|
232
|
+
if (!options || options.length === 0) {
|
|
233
|
+
return { outcome: { type: "cancelled" } };
|
|
234
|
+
}
|
|
235
|
+
const allow = options.find((o) => typeof o.kind === "string" && o.kind.startsWith("allow_")) ?? options[0];
|
|
236
|
+
return { outcome: { type: "selected", optionId: allow.optionId } };
|
|
237
|
+
};
|
|
229
238
|
function createAcpProtocolArm(options) {
|
|
230
239
|
const { child, cwd } = options;
|
|
231
240
|
if (!child.stdin || !child.stdout) {
|
|
@@ -243,12 +252,21 @@ function createAcpProtocolArm(options) {
|
|
|
243
252
|
return session?.sessionId;
|
|
244
253
|
},
|
|
245
254
|
async connect(opts) {
|
|
255
|
+
const permissionHandler = options.onPermissionRequest ?? autoAllowPermissionHandler;
|
|
246
256
|
client = await createAcpClient({
|
|
247
257
|
output,
|
|
248
258
|
input,
|
|
249
259
|
clientInfo: options.clientInfo,
|
|
250
260
|
capabilities: {
|
|
251
261
|
fs: { readTextFile: true, writeTextFile: true }
|
|
262
|
+
},
|
|
263
|
+
// Wire the permission handler so the agent's `session/request_permission`
|
|
264
|
+
// callbacks get a real answer instead of bubbling up as
|
|
265
|
+
// "AcpClient.requestPermission: no handler configured" → which
|
|
266
|
+
// surfaces in the chat as an opaque "Internal error" when the
|
|
267
|
+
// agent tries to Write / Bash anything gated.
|
|
268
|
+
handlers: {
|
|
269
|
+
requestPermission: async (params) => permissionHandler(params)
|
|
252
270
|
}
|
|
253
271
|
});
|
|
254
272
|
if (opts.resumeSessionId) {
|
|
@@ -547,6 +565,6 @@ function filterStringEnv(env) {
|
|
|
547
565
|
return out;
|
|
548
566
|
}
|
|
549
567
|
|
|
550
|
-
export { RuntimeConfigError, agentCliFrontmatterSchema, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, resolveContinuationStrategy, runtimeConfigSchema };
|
|
551
|
-
//# sourceMappingURL=chunk-
|
|
552
|
-
//# sourceMappingURL=chunk-
|
|
568
|
+
export { RuntimeConfigError, agentCliFrontmatterSchema, autoAllowPermissionHandler, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, resolveContinuationStrategy, runtimeConfigSchema };
|
|
569
|
+
//# sourceMappingURL=chunk-H76NLWVO.mjs.map
|
|
570
|
+
//# sourceMappingURL=chunk-H76NLWVO.mjs.map
|
|
@@ -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;AAA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pB,KAAK,KAAA;AACH,MAAA,OAAO,oBAAA,CAAqB;AAAA,QAC1B,KAAA;AAAA,QACA,GAAA;AAAA,QACA,YAAY,EAAE,IAAA,EAAM,IAAI,EAAA,EAAI,OAAA,EAAS,IAAI,OAAA;AAAQ,OAClD,CAAA;AAAA,IACH,KAAK,KAAA;AACH,MAAA,MAAM,IAAI,MAAM,6DAA6D,CAAA;AAAA,IAC/E,KAAK,aAAA;AACH,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AAAA,OACF;AAAA;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-H76NLWVO.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\n/**\n * Outcome the host returns to the agent on a permission request.\n * Mirrors the upstream ACP shape — `selected` picks one of the\n * agent-offered options by id, `cancelled` aborts the tool call.\n */\nexport type AcpPermissionOutcome =\n | { outcome: { type: \"selected\"; optionId: string } }\n | { outcome: { type: \"cancelled\" } }\n\nexport interface AcpPermissionRequestParams {\n sessionId?: string\n toolCall?: {\n toolCallId?: string\n title?: string\n kind?: string\n rawInput?: unknown\n }\n options?: Array<{ optionId: string; name?: string; kind?: string }>\n}\n\nexport type AcpPermissionHandler = (\n params: AcpPermissionRequestParams\n) => Promise<AcpPermissionOutcome> | AcpPermissionOutcome\n\n/**\n * Default handler: pick the first option whose `kind` starts with\n * `allow_` (Claude Code offers `allow_once` and `allow_always`).\n * Falls back to the first option if none match — keeps the agent\n * unblocked rather than throwing on an unfamiliar option set.\n *\n * Mirrors the trust model of in-process Mastra agents: the user\n * approved the operator binding once; subsequent tool calls don't\n * re-prompt by default. Hosts that want explicit per-call gating\n * pass their own `onPermissionRequest`.\n */\nexport const autoAllowPermissionHandler: AcpPermissionHandler = ({\n options,\n}) => {\n if (!options || options.length === 0) {\n // No options offered — return cancelled so the agent gets a\n // deterministic answer instead of hanging on a dropped request.\n return { outcome: { type: \"cancelled\" } }\n }\n const allow =\n options.find(o => typeof o.kind === \"string\" && o.kind.startsWith(\"allow_\")) ??\n options[0]\n return { outcome: { type: \"selected\", optionId: allow!.optionId } }\n}\n\nexport interface AcpProtocolOptions {\n child: ChildProcess\n cwd: string\n clientInfo?: { name: string; title?: string; version?: string }\n /** Called when the agent asks for permission to run a tool (Write,\n * Bash, ...). Defaults to `autoAllowPermissionHandler`. Pass a\n * custom handler to plumb requests through a UI / governance\n * policy. Throwing or returning a rejected promise bubbles to the\n * agent as an internal error. */\n onPermissionRequest?: AcpPermissionHandler\n}\n\nexport function createAcpProtocolArm(\n options: AcpProtocolOptions,\n): AgentCliClient {\n const { child, cwd } = options\n\n if (!child.stdin || !child.stdout) {\n throw new Error(\n \"AcpProtocolArm: subprocess must be spawned with piped stdin + stdout\",\n )\n }\n\n const output = Writable.toWeb(child.stdin) as WritableStream<Uint8Array>\n const input = Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>\n\n let client: AcpClient | null = null\n let session: AcpClientSession | null = null\n const pendingByTurn = new Map<string, AsyncIterable<StreamEvent>>()\n\n return {\n get sessionId(): string | undefined {\n return session?.sessionId\n },\n async connect(opts: AgentCliConnectOptions) {\n const permissionHandler =\n options.onPermissionRequest ?? autoAllowPermissionHandler\n client = await createAcpClient({\n output,\n input,\n clientInfo: options.clientInfo,\n capabilities: {\n fs: { readTextFile: true, writeTextFile: true },\n },\n // Wire the permission handler so the agent's `session/request_permission`\n // callbacks get a real answer instead of bubbling up as\n // \"AcpClient.requestPermission: no handler configured\" → which\n // surfaces in the chat as an opaque \"Internal error\" when the\n // agent tries to Write / Bash anything gated.\n handlers: {\n requestPermission: async (params: unknown) =>\n permissionHandler(params as AcpPermissionRequestParams),\n } as never,\n })\n // When the host hands us a `resumeSessionId`, reattach to the\n // agent's existing session via `loadSession` so the conversation\n // (model context, tool history, working files) carries over a\n // cold start. We trust the host to only send ids it persisted\n // from a prior turn; if the agent's `loadSession: true` capability\n // wasn't advertised the SDK call surfaces the per-protocol error.\n //\n // No silent fallback to `newSession` on resume failure — that\n // would create a new session quietly and lose continuity, which\n // is the bug we're trying to prevent. Let the error propagate.\n if (opts.resumeSessionId) {\n session = await client.loadSession({\n sessionId: opts.resumeSessionId,\n cwd,\n })\n } else {\n session = await client.newSession({ cwd })\n }\n },\n async send(turnId, message) {\n if (!session) throw new Error(\"AcpProtocolArm.send: not connected\")\n // ACP's `prompt` field is `ContentBlock[]` — multiple blocks\n // together form the user's turn (text + image + resource_link\n // + ...). Callers MAY pass either:\n // - a single block (`{type:\"text\",text:\"...\"}`) — wrapped\n // into a one-element array for the wire\n // - an array of blocks — forwarded verbatim, supporting\n // multimodal turns without callers re-shaping per-arm\n const messages = Array.isArray(message) ? message : [message]\n const stream = session.prompt({ messages })\n pendingByTurn.set(turnId, stream)\n },\n async *events(): AsyncIterable<StreamEvent> {\n const last = Array.from(pendingByTurn.values()).at(-1)\n if (!last) return\n for await (const evt of last) yield evt\n },\n async cancel(_turnId) {\n if (!session) return\n await session.cancel()\n },\n async close() {\n if (session) await session.close()\n if (client) await client.close()\n },\n }\n}\n","/**\n * Spawn-argument composer.\n *\n * Pure function: given an `AgentCliHandle` and a per-call\n * `RuntimeConfig`, produces the final `binArgs + env` to pass to the\n * runtime's `start()`. Validates the config against the manifest's\n * declared `modes` / `options` / `continuation.supported`; unknown ids\n * throw `RuntimeConfigError` (the host should NOT spawn — the user\n * configured something the manifest doesn't accept).\n *\n * Composition order (matches AIP-45 spec):\n * 1. Manifest's default `bin_args` (from `handle.bin_args`).\n * 2. Mode patch (`bin_args_append`, `env`) when `config.mode` set.\n * 3. Option patches in DECLARATION order (`bin_args_template` /\n * `bin_args_append_when_true` / `env`) for each option present\n * in `config.options`.\n *\n * Mode is applied before options because modes are coarse profile\n * switches (claude-code's `--permission-mode`) — options refine them.\n * Within options, declaration order is honoured so adapter authors\n * can express \"this flag must come after that one\" without the host\n * needing to know the rule.\n */\n\nimport type {\n AgentCliHandle,\n AgentCliOption,\n RuntimeConfig,\n} from \"../types.js\"\n\n/**\n * Thrown when `RuntimeConfig` references manifest entries that don't\n * exist or violates a declared constraint (type / enum / bounds). The\n * `code` field lets callers map to friendly UI messages without\n * inspecting the message string.\n */\nexport class RuntimeConfigError extends Error {\n readonly code:\n | \"unknown_mode\"\n | \"unknown_option\"\n | \"option_type_mismatch\"\n | \"option_enum_violation\"\n | \"option_bounds_violation\"\n | \"unsupported_continuation\"\n readonly path: string\n constructor(\n code: RuntimeConfigError[\"code\"],\n path: string,\n message: string\n ) {\n super(`[${code} at ${path}] ${message}`)\n this.code = code\n this.path = path\n this.name = \"RuntimeConfigError\"\n }\n}\n\n/**\n * Resolved spawn args + env. The runtime's `start()` impl merges\n * `env` into the host process env / sandbox env before exec.\n */\nexport interface ComposedSpawn {\n binArgs: string[]\n env: Record<string, string>\n}\n\n/**\n * Compose the final spawn args from a manifest + per-call config.\n * Pure — no I/O, no sandbox access, no global state. Safe to call\n * repeatedly with the same input.\n *\n * `config` may be undefined or an empty object — both fall back to\n * the manifest's defaults verbatim (manifest `bin_args`, no mode\n * patch, no option patches). Continuation is not applied here — the\n * `ContinuationStrategy` registry handles that — but we DO validate\n * `config.continuation` against `manifest.continuation.supported` so\n * a misconfigured operator fails fast at compose time, not at the\n * point the strategy tries to acquire a session.\n */\nexport function composeSpawn(\n handle: AgentCliHandle,\n config?: RuntimeConfig\n): ComposedSpawn {\n const binArgs: string[] = [...(handle.bin_args ?? [])]\n const env: Record<string, string> = {}\n\n if (!config) return { binArgs, env }\n\n // ── Mode patch ──────────────────────────────────────────────────\n if (config.mode !== undefined) {\n const mode = (handle.modes ?? []).find(m => m.id === config.mode)\n if (!mode) {\n const known = (handle.modes ?? []).map(m => m.id).join(\", \") || \"(none)\"\n throw new RuntimeConfigError(\n \"unknown_mode\",\n \"config.mode\",\n `Mode '${config.mode}' is not declared by manifest '${handle.id}'. Known modes: ${known}`\n )\n }\n if (mode.bin_args_append) binArgs.push(...mode.bin_args_append)\n if (mode.env) Object.assign(env, mode.env)\n }\n\n // ── Option patches (declaration order) ──────────────────────────\n if (config.options && Object.keys(config.options).length > 0) {\n const declared = handle.options ?? []\n const declaredById = new Map(declared.map(o => [o.id, o]))\n // Reject unknown ids first so the operator sees ALL the typos\n // (not just the one we hit first when iterating declared).\n for (const id of Object.keys(config.options)) {\n if (!declaredById.has(id)) {\n const known = declared.map(o => o.id).join(\", \") || \"(none)\"\n throw new RuntimeConfigError(\n \"unknown_option\",\n `config.options.${id}`,\n `Option '${id}' is not declared by manifest '${handle.id}'. Known options: ${known}`\n )\n }\n }\n // Then apply patches in declaration order so adapter-author intent\n // wins over operator-config key order.\n for (const option of declared) {\n if (!(option.id in config.options)) continue\n const value = config.options[option.id] as boolean | number | string\n validateOptionValue(option, value)\n const patch = renderOptionPatch(option, value)\n binArgs.push(...patch.binArgs)\n Object.assign(env, patch.env)\n }\n }\n\n // ── Continuation validation (no patch — strategy registry owns) ─\n if (config.continuation !== undefined && handle.continuation) {\n if (!handle.continuation.supported.includes(config.continuation)) {\n throw new RuntimeConfigError(\n \"unsupported_continuation\",\n \"config.continuation\",\n `Continuation strategy '${config.continuation}' is not in manifest '${handle.id}'.continuation.supported (${handle.continuation.supported.join(\", \")}).`\n )\n }\n }\n\n return { binArgs, env }\n}\n\n/**\n * Resolve the continuation strategy id to use for this call. Operator\n * config wins; manifest default is the fallback; \"none\" if neither\n * declares anything (preserves pre-AIP-45-extension behaviour).\n */\nexport function resolveContinuationStrategy(\n handle: AgentCliHandle,\n config?: RuntimeConfig\n): import(\"../types.js\").ContinuationStrategyId {\n if (config?.continuation) return config.continuation\n return handle.continuation?.default ?? \"none\"\n}\n\nfunction validateOptionValue(\n option: AgentCliOption,\n value: boolean | number | string\n): void {\n const path = `config.options.${option.id}`\n switch (option.type) {\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected boolean, got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n return\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected integer, got ${typeof value === \"number\" ? \"non-integer number\" : typeof value} (${JSON.stringify(value)}).`\n )\n }\n if (option.min !== undefined && value < option.min) {\n throw new RuntimeConfigError(\n \"option_bounds_violation\",\n path,\n `Value ${value} is below the declared minimum ${option.min}.`\n )\n }\n if (option.max !== undefined && value > option.max) {\n throw new RuntimeConfigError(\n \"option_bounds_violation\",\n path,\n `Value ${value} is above the declared maximum ${option.max}.`\n )\n }\n return\n case \"string\":\n if (typeof value !== \"string\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected string, got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n return\n case \"enum\":\n if (typeof value !== \"string\") {\n throw new RuntimeConfigError(\n \"option_type_mismatch\",\n path,\n `Expected string (enum value), got ${typeof value} (${JSON.stringify(value)}).`\n )\n }\n if (!(option.enum ?? []).includes(value)) {\n throw new RuntimeConfigError(\n \"option_enum_violation\",\n path,\n `Value '${value}' is not in the declared enum (${(option.enum ?? []).join(\", \")}).`\n )\n }\n return\n }\n}\n\nfunction renderOptionPatch(\n option: AgentCliOption,\n value: boolean | number | string\n): { binArgs: string[]; env: Record<string, string> } {\n const stringValue = String(value)\n\n // boolean type: only emit the bare flag when value === true and the\n // option declared `bin_args_append_when_true`. Honor `env` too —\n // adapter authors might want to surface the bool via env.\n if (option.type === \"boolean\") {\n if (value !== true) return { binArgs: [], env: {} }\n return {\n binArgs: option.bin_args_append_when_true\n ? [...option.bin_args_append_when_true]\n : [],\n env: option.env ? interpolateEnv(option.env, stringValue) : {},\n }\n }\n\n // value-bearing types — apply `bin_args_template` (with `{value}`\n // interpolation) and merge `env`.\n return {\n binArgs: option.bin_args_template\n ? option.bin_args_template.map(token =>\n token.replace(/\\{value\\}/g, stringValue)\n )\n : [],\n env: option.env ? interpolateEnv(option.env, stringValue) : {},\n }\n}\n\nfunction interpolateEnv(\n env: Record<string, string>,\n value: string\n): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(env)) {\n out[k] = v.replace(/\\{value\\}/g, value)\n }\n return out\n}\n","import { spawn, type ChildProcess } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport { createDoctype } from \"@agentproto/define-doctype\"\nimport { agentCliFrontmatterSchema } from \"./schema.js\"\nimport { createAcpProtocolArm } from \"./protocol/acp-client.js\"\nimport { composeSpawn } from \"./manifest/compose.js\"\nimport type {\n AgentCliClient,\n AgentCliDefinition,\n AgentCliHandle,\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n StreamEvent,\n} from \"./types.js\"\n\nexport const defineAgentCli = createDoctype<AgentCliDefinition, AgentCliHandle>(\n {\n aip: 45,\n name: \"agent-cli\",\n readIdentity: (def) => def.id,\n validate(def) {\n const result = agentCliFrontmatterSchema.safeParse(def)\n if (!result.success) {\n throw new Error(\n `defineAgentCli (AIP-45): ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n\n const data = result.data\n\n if (data.protocol === \"acp\" && !data.acp) {\n throw new Error(\n \"defineAgentCli (AIP-45): `acp` ref is required when protocol=acp\",\n )\n }\n if (data.protocol === \"mcp\" && !data.mcp) {\n throw new Error(\n \"defineAgentCli (AIP-45): `mcp` block is required when protocol=mcp\",\n )\n }\n if (data.protocol === \"proprietary\" && !data.adapter) {\n throw new Error(\n \"defineAgentCli (AIP-45): `adapter` package is required when protocol=proprietary\",\n )\n }\n\n if (\n data.session?.mode === \"resumable\" &&\n data.capabilities?.resumable !== true\n ) {\n throw new Error(\n \"defineAgentCli (AIP-45): session.mode=resumable requires capabilities.resumable: true\",\n )\n }\n },\n build(def) {\n return { ...def } as AgentCliHandle\n },\n },\n)\n\nexport function createAgentCliRuntime(\n definition: AgentCliHandle,\n): AgentCliRuntime {\n return {\n definition,\n async start(opts?: AgentCliStartOptions): Promise<AgentCliRuntimeSession> {\n const cwd = opts?.cwd ?? process.cwd()\n // Compose final argv + env from the manifest + per-call config.\n // Mode patches and option patches land BEFORE the host-provided\n // env so an operator-set option can be observed by the CLI even\n // when the manifest also touches the same env key (operator\n // intent wins). Validation runs here too — a misconfigured\n // operator throws RuntimeConfigError before we exec anything.\n const composed = composeSpawn(definition, opts?.config)\n const env: Record<string, string> = {\n ...filterStringEnv(process.env),\n ...composed.env,\n ...(opts?.env ?? {}),\n }\n\n const child = spawn(definition.bin, composed.binArgs, {\n cwd,\n env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n signal: opts?.signal,\n })\n\n 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"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -16,6 +16,48 @@ declare function createAgentCliRuntime(definition: AgentCliHandle): AgentCliRunt
|
|
|
16
16
|
* forwards the resulting StreamEvent stream.
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
+
/**
|
|
20
|
+
* Outcome the host returns to the agent on a permission request.
|
|
21
|
+
* Mirrors the upstream ACP shape — `selected` picks one of the
|
|
22
|
+
* agent-offered options by id, `cancelled` aborts the tool call.
|
|
23
|
+
*/
|
|
24
|
+
type AcpPermissionOutcome = {
|
|
25
|
+
outcome: {
|
|
26
|
+
type: "selected";
|
|
27
|
+
optionId: string;
|
|
28
|
+
};
|
|
29
|
+
} | {
|
|
30
|
+
outcome: {
|
|
31
|
+
type: "cancelled";
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
interface AcpPermissionRequestParams {
|
|
35
|
+
sessionId?: string;
|
|
36
|
+
toolCall?: {
|
|
37
|
+
toolCallId?: string;
|
|
38
|
+
title?: string;
|
|
39
|
+
kind?: string;
|
|
40
|
+
rawInput?: unknown;
|
|
41
|
+
};
|
|
42
|
+
options?: Array<{
|
|
43
|
+
optionId: string;
|
|
44
|
+
name?: string;
|
|
45
|
+
kind?: string;
|
|
46
|
+
}>;
|
|
47
|
+
}
|
|
48
|
+
type AcpPermissionHandler = (params: AcpPermissionRequestParams) => Promise<AcpPermissionOutcome> | AcpPermissionOutcome;
|
|
49
|
+
/**
|
|
50
|
+
* Default handler: pick the first option whose `kind` starts with
|
|
51
|
+
* `allow_` (Claude Code offers `allow_once` and `allow_always`).
|
|
52
|
+
* Falls back to the first option if none match — keeps the agent
|
|
53
|
+
* unblocked rather than throwing on an unfamiliar option set.
|
|
54
|
+
*
|
|
55
|
+
* Mirrors the trust model of in-process Mastra agents: the user
|
|
56
|
+
* approved the operator binding once; subsequent tool calls don't
|
|
57
|
+
* re-prompt by default. Hosts that want explicit per-call gating
|
|
58
|
+
* pass their own `onPermissionRequest`.
|
|
59
|
+
*/
|
|
60
|
+
declare const autoAllowPermissionHandler: AcpPermissionHandler;
|
|
19
61
|
interface AcpProtocolOptions {
|
|
20
62
|
child: ChildProcess;
|
|
21
63
|
cwd: string;
|
|
@@ -24,6 +66,12 @@ interface AcpProtocolOptions {
|
|
|
24
66
|
title?: string;
|
|
25
67
|
version?: string;
|
|
26
68
|
};
|
|
69
|
+
/** Called when the agent asks for permission to run a tool (Write,
|
|
70
|
+
* Bash, ...). Defaults to `autoAllowPermissionHandler`. Pass a
|
|
71
|
+
* custom handler to plumb requests through a UI / governance
|
|
72
|
+
* policy. Throwing or returning a rejected promise bubbles to the
|
|
73
|
+
* agent as an internal error. */
|
|
74
|
+
onPermissionRequest?: AcpPermissionHandler;
|
|
27
75
|
}
|
|
28
76
|
declare function createAcpProtocolArm(options: AcpProtocolOptions): AgentCliClient;
|
|
29
77
|
|
|
@@ -231,4 +279,4 @@ declare function configureNativeResume(hooks: NativeResumeHooks): void;
|
|
|
231
279
|
declare const SPEC_NAME: "agentcli-interactive/v1";
|
|
232
280
|
declare const SPEC_VERSION: "0.1.0-alpha";
|
|
233
281
|
|
|
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 };
|
|
282
|
+
export { type AcpPermissionHandler, type AcpPermissionOutcome, type AcpPermissionRequestParams, type AcquireContext, AgentCliClient, AgentCliDefinition, AgentCliHandle, AgentCliRuntime, AgentCliRuntimeSession, AgentCliStartOptions, type ComposedSpawn, ContinuationKeyScope, type ContinuationStrategy, ContinuationStrategyId, type NativeResumeHooks, type ReleaseContext, type ReleaseOutcome, RuntimeConfig, RuntimeConfigError, SPEC_NAME, SPEC_VERSION, TurnContext, autoAllowPermissionHandler, composeSpawn, configureNativeResume, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, deriveKeyFromScope, getContinuationStrategy, listContinuationStrategies, registerContinuationStrategy, resolveContinuationStrategy };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { RuntimeConfigError, agentCliFrontmatterSchema, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, resolveContinuationStrategy, runtimeConfigSchema } from './chunk-
|
|
1
|
+
export { RuntimeConfigError, agentCliFrontmatterSchema, autoAllowPermissionHandler, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, defineAgentCli, resolveContinuationStrategy, runtimeConfigSchema } from './chunk-H76NLWVO.mjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* @agentproto/driver-agent-cli v0.1.0-alpha
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/continuation/strategies/none.ts","../src/continuation/types.ts","../src/continuation/strategies/pinned-session.ts","../src/continuation/strategies/transcript.ts","../src/continuation/strategies/native-resume.ts","../src/continuation/registry.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;AAUO,IAAM,YAAA,GAAqC;AAAA,EAChD,EAAA,EAAI,MAAA;AAAA,EACJ,MAAM,QAAQ,GAAA,EAAK;AACjB,IAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,KAAA,CAAM,GAAA,CAAI,YAAY,CAAA;AAAA,EAC3C,CAAA;AAAA,EACA,MAAM,QAAQ,GAAA,EAAK;AACjB,IAAA,MAAM,GAAA,CAAI,QAAQ,KAAA,EAAM;AAAA,EAC1B;AACF,CAAA;;;ACuEO,SAAS,kBAAA,CACd,OACA,OAAA,EACe;AACf,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,MAAM,CAAA,GAAI,QAAQ,CAAC,CAAA;AACnB,IAAA,IAAI,GAAG,KAAA,CAAM,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,EAAI,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,MAAM,MAAA,KAAW,CAAA,GAAI,IAAA,GAAO,KAAA,CAAM,KAAK,GAAG,CAAA;AACnD;;;AC7DA,IAAM,uBAAA,GAA0B,KAAK,EAAA,GAAK,GAAA;AAE1C,IAAM,IAAA,uBAAW,GAAA,EAAyB;AAE1C,SAAS,eAAe,KAAA,EAA0B;AAChD,EAAA,IAAI,MAAM,SAAA,EAAW;AACnB,IAAA,YAAA,CAAa,MAAM,SAAS,CAAA;AAC5B,IAAA,KAAA,CAAM,SAAA,GAAY,IAAA;AAAA,EACpB;AACF;AAEA,SAAS,oBAAA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,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"]}
|
|
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,GAAK,GAAA;AAE1C,IAAM,IAAA,uBAAW,GAAA,EAAyB;AAE1C,SAAS,eAAe,KAAA,EAA0B;AAChD,EAAA,IAAI,MAAM,SAAA,EAAW;AACnB,IAAA,YAAA,CAAa,MAAM,SAAS,CAAA;AAC5B,IAAA,KAAA,CAAM,SAAA,GAAY,IAAA;AAAA,EACpB;AACF;AAEA,SAAS,oBAAA,CACP,GAAA,EACA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AE,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 {\n createAcpProtocolArm,\n autoAllowPermissionHandler,\n type AcpPermissionHandler,\n type AcpPermissionOutcome,\n type AcpPermissionRequestParams,\n} from \"./protocol/acp-client.js\"\nexport {\n agentCliFrontmatterSchema,\n runtimeConfigSchema,\n type AgentCliFrontmatter,\n type RuntimeConfigInput,\n} from \"./schema.js\"\nexport {\n composeSpawn,\n resolveContinuationStrategy,\n RuntimeConfigError,\n type ComposedSpawn,\n} from \"./manifest/compose.js\"\nexport {\n registerContinuationStrategy,\n getContinuationStrategy,\n listContinuationStrategies,\n} from \"./continuation/registry.js\"\nexport {\n configureNativeResume,\n type NativeResumeHooks,\n} from \"./continuation/strategies/native-resume.js\"\nexport {\n deriveKeyFromScope,\n type ContinuationStrategy,\n type AcquireContext,\n type ReleaseContext,\n type ReleaseOutcome,\n} from \"./continuation/types.js\"\nexport type {\n AgentCliDefinition,\n AgentCliHandle,\n AgentCliProtocol,\n AgentCliSessionMode,\n AgentCliClient,\n AgentCliConnectOptions,\n AgentCliRuntime,\n AgentCliRuntimeSession,\n AgentCliStartOptions,\n AgentCliCapabilities,\n AgentCliInstallMethod,\n AgentCliVersionCheck,\n AgentCliAuth,\n 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"]}
|
package/dist/manifest/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { agentCliFrontmatterSchema, defineAgentCli } from '../chunk-
|
|
2
|
-
export { agentCliFrontmatterSchema } from '../chunk-
|
|
1
|
+
import { agentCliFrontmatterSchema, defineAgentCli } from '../chunk-H76NLWVO.mjs';
|
|
2
|
+
export { agentCliFrontmatterSchema } from '../chunk-H76NLWVO.mjs';
|
|
3
3
|
import matter from 'gray-matter';
|
|
4
4
|
|
|
5
5
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentproto/driver-agent-cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1",
|
|
4
4
|
"description": "@agentproto/driver-agent-cli — AIP-45 AGENT-CLI.md reference implementation. Multi-protocol runner that loads an AGENT-CLI.md manifest, spawns the binary, and dispatches turns through an ACP / MCP / proprietary arm. ACP arm delegates to @agentproto/acp; emits the canonical StreamEvent taxonomy regardless of underlying protocol.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentproto",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"gray-matter": "^4.0.3",
|
|
55
55
|
"zod": "^4.3.6",
|
|
56
|
-
"@agentproto/acp": "0.1.0-alpha.
|
|
56
|
+
"@agentproto/acp": "0.1.0-alpha.1",
|
|
57
57
|
"@agentproto/define-doctype": "0.1.0-alpha.0"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema.ts","../src/protocol/acp-client.ts","../src/manifest/compose.ts","../src/define-agent-cli.ts"],"names":[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,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"]}
|