From 36313fc9083744a050bccc7c917208b2405146c2 Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 28 Sep 2026 11:38:44 -0500 Subject: [PATCH] Preserve Cursor child activity without flattening foreign sessions Co-Authored-By: Paperclip --- .../runner-cursor-capabilities.md | 14 +- .../drivers/acpx/cursor-extensions.test.ts | 15 ++ .../src/drivers/acpx/cursor-extensions.ts | 57 ++++- ...cursor-subagents-package-contract.test.mjs | 109 ++++++++++ patches/acpx@0.13.1.patch | 204 ++++++++++-------- 5 files changed, 306 insertions(+), 93 deletions(-) create mode 100644 packages/paperclip-runner/test/acpx-cursor-subagents-package-contract.test.mjs diff --git a/doc/architecture/runner-cursor-capabilities.md b/doc/architecture/runner-cursor-capabilities.md index ec582ddbcef..73a015465de 100644 --- a/doc/architecture/runner-cursor-capabilities.md +++ b/doc/architecture/runner-cursor-capabilities.md @@ -23,7 +23,7 @@ The reference is the runner's Codex app-server integration and its closed thread | Human questions | `cursor/ask_question`, native single/multiple selections | `normalizeCursorQuestionRequest`: all questions required; opaque UI IDs round-trip native IDs; forged/duplicate/missing selections rejected | Active-turn adapter maps canonical answers, decline to skipped, and cancellation; durable delivery still requires end-to-end evidence | | Proposed plans and decisions | `cursor/create_plan` with full Markdown, overview, todos, named phases and project flag | `normalizeCursorPlanRequest`: complete presentation; accept/reject/cancel; revision-derived question ID; rejection feedback | Foundation question descriptions allow 100,000 chars; this boundary also enforces the 196 KiB UTF-8 durable payload cap. Oversize rejects; it is never truncated. No generated `planUri`, since no uploaded plan artifact is fabricated | | Execution checklist | Standard ACP `plan` and `cursor/update_todos` (`merge`) | Per-turn reducer merges by native ID and emits complete snapshots with increasing revisions | Native cancelled status is visible as “Cancelled” with canonical blocked status, since canonical plan schema has no cancelled enum | -| Child activity | Optional `subagent_spawned`, `subagent_state_update`; metadata has tool-call/agent/model identity | Stateful child normalizer emits canonical delegation and retains role/task across state deltas; active-turn adapter validates parent, known child spawn, and immutable tool/agent origin | Requires client `_meta.subagents: true`. ACPX SDK 1.4.0 lacks these two update variants; a closed pre-parser intercept is required. Nested transcript routing and child authority need end-to-end evidence | +| Child activity | Optional `subagent_spawned`, `subagent_state_update`; metadata has tool-call/agent/model identity | Stateful child normalizer emits canonical delegation and retains role/task across state deltas; active-turn adapter validates parent, known child spawn, and immutable tool/agent origin | Requires client `_meta.subagents: true`. ACPX SDK 1.4.0 lacks these two update variants. A closed opt-in pre-parser intercept binds the parent and declared descendants; child text/reasoning/plan/tool summaries are attributed to their child, never flattened into the parent. Nested media and raw tool details remain partial | | Completed subagent tasks | `cursor/task`: description, prompt, subtype, model, ID, duration | Canonical delegation with role, model, task and duration in activity summary | Dedicated numeric duration field absent from canonical delegation schema | | Subagent questions | Pinned ACP subagent handler explicitly rejects interactive questions | No unsupported affordance advertised | Confirmed harness omission; requires upstream support | | Generated images | `cursor/generate_image`: description, path and reference-image paths | Canonical generated/viewed artifact events; description notice; realpath/regular-file containment checks; `registered:false` | Paths are references, not automatic uploads. Revalidate before artifact ingestion. No image bytes invented | @@ -61,7 +61,7 @@ Artifact paths are never automatically read or uploaded. References require a pr Passed in the provider worktree: -- 13 Cursor Vitest cases: questions, multi-selection, native ID round-trip, invalid answers, exact plan revisions, outcomes, todo delta merging, delegation metadata, path containment/symlink refusal, child identity retention, private launch defaults and project config gates; active-turn canonical response mapping and immediate acknowledgements; stale/foreign/unknown child identity rejection. +- 14 Cursor Vitest cases: questions, multi-selection, native ID round-trip, invalid answers, exact plan revisions, outcomes, todo delta merging, delegation metadata, path containment/symlink refusal, child identity retention, private launch defaults and project config gates; active-turn canonical response mapping and immediate acknowledgements; stale/foreign/unknown child identity rejection. - 5 materializer Node tests: platform pins, entire-tree tampering, linked paths, archive tampering before extraction, and overwrite refusal. - Targeted strict TypeScript compilation for both provider modules and their imported contracts. - Credential-free wire initialization and auth/method probes, plus real macOS ARM64 materialization and archive/closure inventories for the other two platforms. @@ -70,6 +70,14 @@ The generic native-distribution lease now snapshots the pinned closure, launches Priority follow-ups before advertising support: (1) shared hook integration with durable response/recovery tests; (2) authenticated native lifetime and cleanup proof; (3) explicit credentials plus exact available model and measured dollar budget; (4) local and Daytona semantic tools, permissions, steering distinction, files/artifacts, questions/plans and settlement proof; (5) field-by-field captured trace audit to identify any additional unconsumed native fields. -Remaining rich capabilities intentionally unused: session discovery, generic mode/config-option UI, provider session titles, command/skill picker metadata, nested child transcripts beyond delegation summaries, native numeric task duration, and optional planUri. They are listed above with reasons; neither “unsupported” nor “complete” should be inferred for unverified live behaviors. The final combined report must update this inventory with integration evidence and include any further events observed during authenticated qualification. +Remaining rich capabilities intentionally unused: session discovery, generic mode/config-option UI, provider session titles, command/skill picker metadata, full nested child transcripts beyond bounded delegation summaries, native numeric task duration, and optional planUri. They are listed above with reasons; neither “unsupported” nor “complete” should be inferred for unverified live behaviors. The final combined report must update this inventory with integration evidence and include any further events observed during authenticated qualification. Shared display-channel verification additionally covers exact rich-event schema validation, terminal/semantic/source injection rejection, active-turn fences, complete Unicode plan preservation through durable outbox persistence, secret redaction disclosure, and oversized UTF-8 rejection. The 4 KiB diagnostic preview cap remains active for diagnostics, never full approval documents. + +## Child transcript boundary and remaining fields + +Pinned source creates a separate session-update presenter for every child and can use another child as the immediate parent. Enabling `_meta.subagents` therefore requires handling both lifecycle and ordinary child session updates. The Cursor-specific ACPX compatibility path tracks declared descendants per stream and active prompt, forwards them only under the retained root parent authority, and suppresses unknown child sessions. It leaves the SDK's standard parent update schema closed. Known child updates never become parent assistant messages. Old-stream, foreign-parent, pre-turn, settled, aborted, oversized, unknown-child and duplicate-spawn cases are covered. + +Child assistant/reasoning text, plan steps and tool lifecycle are displayed in each child's activity summary. The 4,000-character activity surface retains a clearly marked tail when it fills; this is a summary, not a complete nested transcript. Child tool raw input/output, locations, diffs, media content and other child update fields are not rendered by this summary surface and produce explicit partial-detail notices. Adding canonical child transcript/tool surfaces is the next priority for these meaningful exposed fields. Native `capabilities:{}` currently carries no populated child capability fields; `_meta.cursor.agentId` and `toolCallId` are retained internally for immutable origin checks. Nested parent identity is represented in activity metadata because canonical delegation has no parent-child relation field. Native `disconnected` now yields a failed child with a visible explanation, never a successful completion. + +Three real ACP stream tests prove child lifecycle/transcript preservation before SDK parsing, nested parent attribution, standard parent parsing, and old-stream/turn/connection fences. Existing nine shared extension and Pi receipt package tests pass unchanged against the resulting patched package. Three native factory cases verify all platform pins, exact profiles, and rejection of unsupported distributions; native assets resolve only from the runner-owned package authority. diff --git a/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.test.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.test.ts index 2af0f6441d5..3aae9725bc4 100644 --- a/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.test.ts @@ -143,4 +143,19 @@ describe("Cursor active-turn extension adapter", () => { await expect(adapter.notification("cursor/subagent_update", { sessionId: "parent", update: spawned })).rejects.toThrow("duplicated"); await expect(createCursorProfileExtensionAdapter({ ...context, turnId: "next" }).notification("cursor/subagent_update", { sessionId: "parent", update: state })).rejects.toThrow("no spawn"); }); + + it("attributes nested child transcripts, reports partial tool detail, and settles disconnected children honestly", async () => { + const adapter = createCursorProfileExtensionAdapter({ workspacePath: await workspace(), sessionId: "parent", turnId: "turn" }); + const child = { sessionUpdate: "subagent_spawned", subagentSessionId: "child", name: "Explore", task: "", _meta: { cursor: { toolCallId: "task", agentId: "agent" } } }; + await adapter.notification("cursor/subagent_update", { sessionId: "parent", update: child }); + const grandchild = { ...child, subagentSessionId: "grandchild", _meta: { cursor: { toolCallId: "task-2", agentId: "agent-2" } } }; + expect(await adapter.notification("cursor/subagent_update", { sessionId: "parent", parentSessionId: "child", update: grandchild })).toMatchObject([{ payload: { children: [{ activitySummary: expect.stringContaining("Parent child:") }] } }]); + const text = await adapter.notification("cursor/subagent_update", { sessionId: "parent", childSessionId: "grandchild", parentSessionId: "child", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "漢".repeat(5_000) } } }); + expect(text[0]?.payload).toMatchObject({ children: [{ activitySummary: expect.stringContaining("Earlier child activity omitted") }] }); + const tool = await adapter.notification("cursor/subagent_update", { sessionId: "parent", childSessionId: "child", update: { sessionUpdate: "tool_call", toolCallId: "read", title: "Read src", status: "completed", rawInput: { path: "src/index.ts" } } }); + expect(tool).toMatchObject([{ eventType: "delegation.updated", payload: { children: [{ activitySummary: "Tool Read src: completed" }] } }, { eventType: "provider.notice.recorded", payload: { category: "cursor_child_detail_partial" } }]); + const disconnected = await adapter.notification("cursor/subagent_update", { sessionId: "parent", update: { ...child, sessionUpdate: "subagent_state_update", state: "disconnected" } }); + expect(disconnected).toMatchObject([{ payload: { status: "failed", children: [{ status: "failed", activitySummary: expect.stringContaining("disconnected before settling") }] } }]); + await expect(adapter.notification("cursor/subagent_update", { sessionId: "parent", childSessionId: "grandchild", parentSessionId: "wrong", update: {} })).rejects.toThrow("unknown parent"); + }); }); diff --git a/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.ts index b508ac71225..d28ad4168f2 100644 --- a/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.ts @@ -37,7 +37,7 @@ export function createCursorProfileExtensionAdapter(context: { }) { const normalizeNotification = createCursorNotificationNormalizer(context); const normalizeSubagent = createCursorSubagentNormalizer(); - const children = new Map(); + const children = new Map(); const assertSession = (params: Record) => { if (params.sessionId !== context.sessionId) throw new Error("Cursor extension has a stale parent session"); }; @@ -79,6 +79,22 @@ export function createCursorProfileExtensionAdapter(context: { // The transport synthesizes this method only from the two pinned native // session/update variants, after checking the active parent connection. const update = object(params.update); + const parentSessionId = optionalText(params.parentSessionId, "parentSessionId", 1_000) ?? context.sessionId; + if (parentSessionId !== context.sessionId && !children.has(parentSessionId)) throw new Error("Cursor child has an unknown parent"); + if (params.childSessionId !== undefined) { + const childId = requiredText(params.childSessionId, "childSessionId", 1_000); + const child = children.get(childId); + if (!child || child.parentSessionId !== parentSessionId) throw new Error("Cursor child activity has no matching spawn"); + const summary = cursorChildActivitySummary(update); + const combined = [child.activity, summary.text].filter(Boolean).join("\n"); + child.activity = boundedChildActivity(combined); + const event = structuredClone(child.event); + event.eventType = "delegation.updated"; + const nested = object((event.payload.children as unknown[])[0]); + nested.activitySummary = child.activity; + child.event = event; + return [event, ...(summary.gap ? [notice(`${childId}:${String(update.sessionUpdate)}`, "cursor_child_detail_partial", summary.gap)] : [])]; + } const id = requiredText(update.subagentSessionId, "subagentSessionId", 1_000); if (id === context.sessionId) throw new Error("Cursor child cannot impersonate its parent session"); const metadata = object(object(update._meta).cursor); @@ -90,10 +106,13 @@ export function createCursorProfileExtensionAdapter(context: { } else if (update.sessionUpdate !== "subagent_state_update" || !previous) { throw new Error("Cursor child update has no spawn in this active turn"); } - if (previous && (previous.toolCallId !== toolCallId || previous.agentId !== agentId)) throw new Error("Cursor child update changed its origin identity"); + if (previous && (previous.toolCallId !== toolCallId || previous.agentId !== agentId || previous.parentSessionId !== parentSessionId)) throw new Error("Cursor child update changed its origin identity"); const event = normalizeSubagent(update); if (!event) throw new Error("Unsupported Cursor child update"); - children.set(id, { toolCallId, agentId }); + const nested = object((event.payload.children as unknown[])[0]); + const activity = boundedChildActivity([parentSessionId === context.sessionId ? undefined : `Parent child: ${stableId(parentSessionId)}`, previous?.activity, nested.activitySummary].filter(Boolean).join("\n")); + nested.activitySummary = activity || null; + children.set(id, { toolCallId, agentId, parentSessionId, event, activity }); return [event]; }, }; @@ -316,16 +335,44 @@ export function normalizeCursorSubagentUpdate(value: unknown): CanonicalProvider const metadata = object(object(update._meta).cursor); const itemId = stableId(requiredText(metadata.toolCallId, "subagent toolCallId", 1_000)); const state = update.sessionUpdate === "subagent_spawned" ? "running" : update.state; - const status = state === "cancelled" ? "interrupted" : state; + const status = state === "cancelled" ? "interrupted" : state === "disconnected" ? "failed" : state; if (!["running", "completed", "failed", "interrupted"].includes(String(status))) throw new Error("Unknown Cursor subagent state"); return { eventType: status === "running" ? "delegation.started" : "delegation.completed", itemId, payload: { schema: "paperclip.delegation.v1", delegationId: itemId, action: "spawn", status, children: [{ childId: stableId(requiredText(update.subagentSessionId, "subagentSessionId", 1_000)), role: optionalText(update.name, "name", 160) ?? null, model: optionalText(metadata.model, "model", 240) ?? null, - status, summary: optionalText(update.task, "task", 4_000) ?? null, activitySummary: null }], + status, summary: update.task === "" ? null : optionalText(update.task, "task", 4_000) ?? null, + activitySummary: state === "disconnected" ? "Cursor child disconnected before settling." : null }], } }; } +function cursorChildActivitySummary(update: Record): { text: string; gap?: string } { + const kind = requiredText(update.sessionUpdate, "child update kind", 160); + if (["agent_message_chunk", "agent_thought_chunk", "user_message_chunk"].includes(kind)) { + const content = object(update.content); + if (content.type === "text" && typeof content.text === "string" && content.text.length <= 65_536) { + return { text: `${kind === "agent_thought_chunk" ? "Reasoning" : kind === "user_message_chunk" ? "Input" : "Output"}: ${content.text}` }; + } + return { text: `Child ${kind} contains non-text content.`, gap: "Cursor child media is reported as activity; nested transcript media rendering is not supported yet." }; + } + if (kind === "tool_call" || kind === "tool_call_update") { + const toolCallId = requiredText(update.toolCallId, "child toolCallId", 1_000); + const title = optionalText(update.title, "child tool title", 4_000) ?? toolCallId; + const status = optionalText(update.status, "child tool status", 160) ?? "running"; + return { text: `Tool ${title}: ${status}`, gap: "Cursor child tool lifecycle is attributed to the child; raw input, output, locations and diffs need a nested tool surface and are not rendered in this summary." }; + } + if (kind === "plan") { + const entries = array(update.entries, "child plan entries", 256); + return { text: `Child plan: ${entries.map(value => { const entry = object(value); return `[${requiredText(entry.status, "child plan status", 160)}] ${requiredText(entry.content, "child plan step", 4_000)}`; }).join("; ")}` }; + } + return { text: `Child activity: ${kind}`, gap: `Cursor child update ${kind} was retained as a kind notice; its fields need a nested transcript surface.` }; +} + +function boundedChildActivity(text: string): string { + const points = Array.from(text); + return points.length <= 4_000 ? text : `[Earlier child activity omitted]\n${points.slice(-3_960).join("")}`; +} + /** Preserve identity across delta state updates; use a fresh reducer per turn. */ export function createCursorSubagentNormalizer() { const children = new Map>(); diff --git a/packages/paperclip-runner/test/acpx-cursor-subagents-package-contract.test.mjs b/packages/paperclip-runner/test/acpx-cursor-subagents-package-contract.test.mjs new file mode 100644 index 00000000000..41ae321c280 --- /dev/null +++ b/packages/paperclip-runner/test/acpx-cursor-subagents-package-contract.test.mjs @@ -0,0 +1,109 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import test from "node:test"; + +const require = createRequire(import.meta.url); +const acpxRoot = process.env.PAPERCLIP_TEST_ACPX_PACKAGE_ROOT ?? dirname(require.resolve("acpx/package.json")); +const { k: AcpClient } = await import(pathToFileURL(join(acpxRoot, "dist/live-checkpoint-BSIrfgVo.js"))); +const fixture = String.raw` +const readline=require('node:readline'); +const send=value=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...value})+'\n'); +const child=(kind,sessionId='parent',extra={})=>({method:'session/update',params:{sessionId,update:{sessionUpdate:kind,subagentSessionId:'child',name:'Explore',task:'Read source',_meta:{cursor:{toolCallId:'task-1',agentId:'native-child',model:'small'}},...extra}}}); +readline.createInterface({input:process.stdin}).on('line',line=>{ + const message=JSON.parse(line); + if(message.method==='initialize')send({id:message.id,result:{protocolVersion:1,agentCapabilities:{},authMethods:[]}}); + else if(message.method==='session/new'){send(child('subagent_spawned'));send({id:message.id,result:{sessionId:'parent'}});} + else if(message.method==='session/prompt'){ + const mode=message.params.prompt[0].text; + if(mode==='valid'){ + send(child('subagent_spawned')); + send({method:'session/update',params:{sessionId:'child',update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:'child output'}}}}); + send(child('subagent_spawned','child',{subagentSessionId:'grandchild'})); + send(child('subagent_state_update','child',{subagentSessionId:'grandchild',state:'completed'})); + send(child('subagent_state_update','parent',{state:'completed'})); + }else if(mode==='foreign'){ + send(child('subagent_spawned','other-parent')); + const missing=child('subagent_spawned');delete missing.params.sessionId;send(missing); + send({method:'session/update',params:{sessionId:'unowned-child',update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:'must not become parent text'}}}}); + }else if(mode==='oversized')send(child('subagent_spawned','parent',{task:'x'.repeat(300000)})); + else if(mode==='unknown')send(child('subagent_deleted')); + send({method:'session/update',params:{sessionId:'parent',update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:'done'}}}}); + send({id:message.id,result:{stopReason:'end_turn'}}); + } +}); +`; + +async function withClient(options, run) { + const cwd = await mkdtemp(join(tmpdir(), "paperclip-cursor-child-")); + const client = new AcpClient({ + agentCommand: "paperclip-verified-cursor-fixture", cwd, + permissionMode: "approve-all", fs: false, terminal: false, authPolicy: "skip", + suppressSdkConsoleErrors: true, + extensionMethods: ["cursor/subagent_update"], clientCapabilities: { _meta: { subagents: true } }, + spawnAgent: () => spawn(process.execPath, ["-e", fixture], { cwd, stdio: ["pipe", "pipe", "pipe"] }), + ...options, + }); + try { await client.start(); await client.createSession(); await run(client); } + finally { await client.close(); await rm(cwd, { recursive: true, force: true }); } +} + +test("pinned Cursor children survive the SDK boundary while retaining parent and native metadata", { timeout: 10000 }, async () => { + const notifications = []; const standard = []; + await withClient({ onExtensionNotification: (method, params) => notifications.push({ method, params }), onSessionUpdate: value => standard.push(value) }, async client => { + assert.equal(notifications.length, 0, "pre-turn child event is not admitted"); + assert.equal((await client.prompt("parent", "valid")).stopReason, "end_turn"); + assert.deepEqual(notifications.map(value => value.method), Array(5).fill("cursor/subagent_update")); + assert.deepEqual(notifications.map(value => value.params.update.sessionUpdate), ["subagent_spawned", "agent_message_chunk", "subagent_spawned", "subagent_state_update", "subagent_state_update"]); + assert.equal(notifications[0].params.sessionId, "parent"); + assert.equal(notifications[0].params.update._meta.cursor.model, "small"); + assert.equal(notifications[1].params.childSessionId, "child"); + assert.equal(notifications[1].params.sessionId, "parent"); + assert.equal(notifications[2].params.parentSessionId, "child"); + assert.equal(notifications[2].params.sessionId, "parent"); + assert.equal(standard.length, 1, "standard output still follows SDK validation"); + }); +}); + +test("child interception refuses foreign/missing parent, oversized data and unknown variants", { timeout: 10000 }, async () => { + const notifications = []; const standard = []; + await withClient({ onExtensionNotification: (...args) => notifications.push(args), onSessionUpdate: value => standard.push(value) }, async client => { + for (const mode of ["foreign", "oversized", "unknown"]) await client.prompt("parent", mode); + assert.deepEqual(notifications, []); + assert.equal(standard.length, 3); + assert.ok(standard.every(value => value.sessionId === "parent")); + }); +}); + +test("subagent compatibility is opt-in and rejects old stream, settled turn and aborted connection authority", { timeout: 10000 }, async () => { + for (const options of [{ extensionMethods: [] }, { clientCapabilities: {} }]) { + const notifications = []; + await withClient({ ...options, onExtensionNotification: (...args) => notifications.push(args) }, async client => { + await client.prompt("parent", "valid"); + assert.deepEqual(notifications, []); + }); + } + const notifications = []; + const client = new AcpClient({ agentCommand: "fixture", cwd: tmpdir(), permissionMode: "approve-all", extensionMethods: ["cursor/subagent_update"], clientCapabilities: { _meta: { subagents: true } }, onExtensionNotification: (...args) => notifications.push(args) }); + const current = { active: null, children: new Map() }; const old = { active: null, children: new Map() }; + const turn = new AbortController(); const connection = new AbortController(); + client.cursorSubagentStreamOwner = current; + client.activePrompt = { sessionId: "parent", elicitationController: turn }; + client.connection = { signal: connection.signal }; + const message = { method: "session/update", params: { sessionId: "parent", update: { sessionUpdate: "subagent_spawned", subagentSessionId: "child" } } }; + assert.equal(client.handleCursorSubagentNotification(message, old), true); + assert.equal(notifications.length, 0); + client.handleCursorSubagentNotification(message, current); + assert.equal(notifications.length, 1); + turn.abort(); client.handleCursorSubagentNotification(message, current); + assert.equal(notifications.length, 1); + client.activePrompt = { sessionId: "parent", elicitationController: new AbortController() }; + connection.abort(); client.handleCursorSubagentNotification(message, current); + assert.equal(notifications.length, 1); + client.activePrompt = null; client.handleCursorSubagentNotification(message, current); + assert.equal(notifications.length, 1); +}); diff --git a/patches/acpx@0.13.1.patch b/patches/acpx@0.13.1.patch index 2d535d0b329..3f380457b61 100644 --- a/patches/acpx@0.13.1.patch +++ b/patches/acpx@0.13.1.patch @@ -1,8 +1,16 @@ diff --git a/dist/client-CxNllqui.d.ts b/dist/client-CxNllqui.d.ts -index 5e2113a..b7b5151 100644 --- a/dist/client-CxNllqui.d.ts +++ b/dist/client-CxNllqui.d.ts -@@ -135,6 +135,7 @@ declare class AcpClient { +@@ -120,6 +120,8 @@ + private initializeProtocolConnection; + private handleInitializeFailure; + private createTappedStream; ++ private cursorSubagentStreamOwner; ++ private handleCursorSubagentNotification; + createSession(cwd?: string): Promise; + loadSession(sessionId: string, cwd?: string): Promise; + loadSessionWithOptions(sessionId: string, cwd?: string, options?: LoadSessionOptions): Promise; +@@ -135,6 +137,7 @@ private throwPromptPermissionFailureIfPresent; setSessionMode(sessionId: string, modeId: string): Promise; setSessionConfigOption(sessionId: string, configId: string, value: string): Promise; @@ -11,10 +19,9 @@ index 5e2113a..b7b5151 100644 private setSessionModelThroughConfig; private setSessionModelThroughLegacyMethod; diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js -index d454fd7..4312cdd 100644 --- a/dist/live-checkpoint-BSIrfgVo.js +++ b/dist/live-checkpoint-BSIrfgVo.js -@@ -1068,6 +1068,7 @@ function serializeSessionRecordForDisk(record) { +@@ -1068,6 +1068,7 @@ last_agent_disconnect_reason: canonical.lastAgentDisconnectReason, protocol_version: canonical.protocolVersion, agent_capabilities: canonical.agentCapabilities, @@ -22,7 +29,7 @@ index d454fd7..4312cdd 100644 title: canonical.title, messages: canonical.messages, updated_at: canonical.updated_at, -@@ -1239,7 +1240,8 @@ function parseRequestTokenUsage(raw) { +@@ -1239,7 +1240,8 @@ for (const [key, value] of Object.entries(record)) { const parsed = parseTokenUsage(value); if (parsed == null) return null; @@ -32,7 +39,7 @@ index d454fd7..4312cdd 100644 } return usage; } -@@ -1541,6 +1543,7 @@ function parseSessionRecord(raw) { +@@ -1541,6 +1543,7 @@ lastAgentDisconnectReason: optionals.lastAgentDisconnectReason, protocolVersion: typeof record.protocol_version === "number" ? record.protocol_version : void 0, agentCapabilities: asRecord$4(record.agent_capabilities), @@ -40,7 +47,7 @@ index d454fd7..4312cdd 100644 title: conversation.title, messages: conversation.messages, updated_at: conversation.updated_at, -@@ -1661,7 +1664,7 @@ const ZED_TAG_KEYS = /* @__PURE__ */ new Set([ +@@ -1661,7 +1664,7 @@ "RedactedThinking", "ToolUse" ]); @@ -49,7 +56,7 @@ index d454fd7..4312cdd 100644 const OPAQUE_VALUE_PATHS = /* @__PURE__ */ new Set([ "agent_capabilities", "messages.Agent.content.ToolUse.input", -@@ -3104,10 +3107,10 @@ function authEnvKey(methodId) { +@@ -3104,10 +3107,10 @@ authEnvKeyCache.set(methodId, key); return key; } @@ -62,7 +69,7 @@ index d454fd7..4312cdd 100644 if (typeof value === "string" && value.trim().length > 0) return value; } function protectedEnvKey(key) { -@@ -3135,8 +3138,21 @@ function promotePrefixedAuthEnvironment(env) { +@@ -3135,8 +3138,21 @@ } return protectedKeys; } @@ -86,7 +93,7 @@ index d454fd7..4312cdd 100644 const protectedAuthEnvKeys = promotePrefixedAuthEnvironment(env); if (authCredentials) for (const [methodId, credential] of Object.entries(authCredentials)) { addAuthCredentialEnvKeys(protectedAuthEnvKeys, methodId, credential); -@@ -3178,10 +3194,10 @@ function resolveConfiguredAuthCredential(methodId, authCredentials) { +@@ -3178,10 +3194,10 @@ const configCredentials = authCredentials ?? {}; return configCredentials[methodId] ?? configCredentials[toEnvToken(methodId)]; } @@ -99,7 +106,7 @@ index d454fd7..4312cdd 100644 stdio: [ "pipe", "pipe", -@@ -3961,10 +3977,13 @@ function resolveClientCapabilities(params) { +@@ -3961,10 +3977,13 @@ ...params.elicitationModes.includes("url") ? { url: {} } : {} } } : {} }; @@ -115,7 +122,7 @@ index d454fd7..4312cdd 100644 }; } function hasResponseField(response, field) { -@@ -4067,6 +4086,27 @@ function createNdJsonMessageStream(agentCommand, output, input) { +@@ -4067,6 +4086,27 @@ } }) }; } @@ -143,7 +150,7 @@ index d454fd7..4312cdd 100644 var AcpClient = class { options; connection; -@@ -4105,7 +4145,9 @@ var AcpClient = class { +@@ -4105,7 +4145,9 @@ cwd: asAbsoluteCwd(options.cwd), authPolicy: options.authPolicy ?? "skip", permissionPolicy: snapshotPermissionPolicy(options.permissionPolicy), @@ -154,7 +161,7 @@ index d454fd7..4312cdd 100644 }; this.eventHandlers = { onAcpMessage: this.options.onAcpMessage, -@@ -4216,9 +4258,21 @@ var AcpClient = class { +@@ -4216,9 +4258,21 @@ this.lastAgentExit = void 0; this.lastKnownPid = child.pid ?? void 0; this.attachAgentLifecycleObservers(child); @@ -176,7 +183,7 @@ index d454fd7..4312cdd 100644 if (!this.options.verbose) return; process.stderr.write(chunk); }); -@@ -4226,6 +4280,7 @@ var AcpClient = class { +@@ -4226,6 +4280,7 @@ const output = Readable.toWeb(child.stdout); const stream = this.createTappedStream(createNdJsonMessageStream(this.options.agentCommand, input, output)); const connection = this.createConnection(stream, launch); @@ -184,7 +191,7 @@ index d454fd7..4312cdd 100644 connection.signal.addEventListener("abort", () => { this.recordAgentExit("connection_close", child.exitCode ?? null, child.signalCode ?? null); }, { once: true }); -@@ -4253,7 +4308,12 @@ var AcpClient = class { +@@ -4253,7 +4308,12 @@ geminiAcp: isGeminiAcpCommand(spawnCommand, args), copilotAcp: isCopilotAcpCommand(spawnCommand, args), claudeAcp: isClaudeAcpCommand(spawnCommand, args), @@ -198,7 +205,7 @@ index d454fd7..4312cdd 100644 }; } logAgentLaunch(plan) { -@@ -4279,10 +4339,17 @@ var AcpClient = class { +@@ -4279,10 +4339,17 @@ } async spawnAgentProcess(plan) { const spawnCommand = buildAgentSpawnCommand(plan.spawnCommand, plan.args, process.platform, plan.spawnOptions.env); @@ -218,7 +225,7 @@ index d454fd7..4312cdd 100644 try { await waitForSpawn$1(spawnedChild); } catch (error) { -@@ -4293,10 +4360,10 @@ var AcpClient = class { +@@ -4293,10 +4360,10 @@ createConnection(stream, launch) { const app = client({ name: "acpx" }).onNotification(methods.client.session.update, async ({ params }) => { await this.handleSessionUpdate(params); @@ -232,7 +239,7 @@ index d454fd7..4312cdd 100644 }).onRequest(methods.client.fs.readTextFile, async ({ params }) => { return await this.handleReadTextFile(params); }).onRequest(methods.client.fs.writeTextFile, async ({ params }) => { -@@ -4312,6 +4379,11 @@ var AcpClient = class { +@@ -4312,6 +4379,11 @@ }).onRequest(methods.client.terminal.release, async ({ params }) => { return await this.handleReleaseTerminal(params); }); @@ -244,7 +251,7 @@ index d454fd7..4312cdd 100644 if (launch.devinAcp) app.onRequest("_cognition.ai/request_diagnostics", (params) => { return params && typeof params === "object" && !Array.isArray(params) ? params : {}; }, async () => ({})); -@@ -4333,12 +4405,12 @@ var AcpClient = class { +@@ -4333,12 +4405,12 @@ async initializeProtocolConnection(connection, launch) { const initializePromise = connection.initialize({ protocolVersion: PROTOCOL_VERSION, @@ -259,7 +266,7 @@ index d454fd7..4312cdd 100644 clientInfo: resolveClientInfo(launch.devinAcp) }); const initialized = launch.geminiAcp ? await withTimeout(initializePromise, resolveGeminiAcpStartupTimeoutMs()) : await initializePromise; -@@ -4358,6 +4430,36 @@ var AcpClient = class { +@@ -4358,6 +4430,36 @@ throw normalizedError; } createTappedStream(base) { @@ -296,10 +303,13 @@ index d454fd7..4312cdd 100644 const onAcpMessage = () => this.eventHandlers.onAcpMessage; const onAcpOutputMessage = () => this.eventHandlers.onAcpOutputMessage; const elicitationRequestIds = /* @__PURE__ */ new Set(); -@@ -4367,8 +4469,9 @@ var AcpClient = class { +@@ -4367,8 +4469,12 @@ const shouldSuppressInboundReplaySessionUpdate = (message) => { return this.suppressReplaySessionUpdateMessages && isSessionUpdateNotification(message); }; ++ const cursorSubagentOwner = { active: null, children: new Map() }; ++ this.cursorSubagentStreamOwner = cursorSubagentOwner; ++ const onCursorSubagentNotification = (message) => this.handleCursorSubagentNotification(message, cursorSubagentOwner); + const onExtensionNotification = (message) => this.handleExtensionNotification(message); const observeInbound = (message) => { - const requestId = elicitationRequestId(message); @@ -307,7 +317,7 @@ index d454fd7..4312cdd 100644 if (requestId !== void 0) { elicitationRequestIds.add(requestId); return; -@@ -4379,6 +4482,7 @@ var AcpClient = class { +@@ -4379,6 +4485,7 @@ } }; return { @@ -315,11 +325,12 @@ index d454fd7..4312cdd 100644 readable: new ReadableStream({ async start(controller) { const reader = base.readable.getReader(); try { -@@ -4387,10 +4491,16 @@ var AcpClient = class { +@@ -4387,10 +4494,17 @@ if (done) break; if (!value) continue; observeInbound(value); - if (isExtensionNotification(value)) continue; ++ if (onCursorSubagentNotification(value)) continue; + if (isExtensionNotification(value)) { + onExtensionNotification(value); + continue; @@ -333,7 +344,7 @@ index d454fd7..4312cdd 100644 reader.releaseLock(); controller.close(); } -@@ -4403,10 +4513,20 @@ var AcpClient = class { +@@ -4403,10 +4517,20 @@ onAcpOutputMessage()?.("outbound", message); onAcpMessage()?.("outbound", message); } @@ -354,7 +365,7 @@ index d454fd7..4312cdd 100644 writer.releaseLock(); } } }) -@@ -4422,7 +4542,10 @@ var AcpClient = class { +@@ -4422,7 +4546,10 @@ const createPromise = this.runConnectionRequest(() => connection.newSession({ cwd: sessionCwd, mcpServers: this.options.mcpServers ?? [], @@ -366,7 +377,7 @@ index d454fd7..4312cdd 100644 })); result = claudeAcp ? await withTimeout(createPromise, resolveClaudeAcpSessionCreateTimeoutMs()) : await createPromise; } catch (error) { -@@ -4864,7 +4987,7 @@ var AcpClient = class { +@@ -4864,7 +4991,7 @@ } selectAuthMethod(methods) { for (const method of methods) { @@ -375,7 +386,7 @@ index d454fd7..4312cdd 100644 if (envCredential) return { methodId: method.id, credential: envCredential, -@@ -4890,7 +5013,7 @@ var AcpClient = class { +@@ -4890,7 +5017,7 @@ } readAgentSpecificEnvCredential(methodId) { if (!this.isGrokBuildAcpCommand() || methodId !== "xai.api_key") return; @@ -384,7 +395,7 @@ index d454fd7..4312cdd 100644 return typeof value === "string" && value.trim().length > 0 ? value : void 0; } selectAgentManagedAuthMethod(methodId) { -@@ -4915,9 +5038,9 @@ var AcpClient = class { +@@ -4915,9 +5042,9 @@ await connection.authenticate({ methodId: selected.methodId }); this.log(`authenticated with method ${selected.methodId} (${selected.source})`); } @@ -396,7 +407,7 @@ index d454fd7..4312cdd 100644 if (hostResponse) return hostResponse; const { response, recorded } = await this.resolvePermissionRequestFromMode(params); if (!recorded) { -@@ -4926,14 +5049,49 @@ var AcpClient = class { +@@ -4926,14 +5053,81 @@ } return response; } @@ -423,6 +434,38 @@ index d454fd7..4312cdd 100644 + signal.removeEventListener("abort", onAbort); + } + } ++ handleCursorSubagentNotification(message, owner) { ++ // Keep the SDK's standard union closed. Cursor child transcripts use ++ // their own session IDs and must never be flattened into the parent. ++ const method = "cursor/subagent_update"; ++ if (!this.options.extensionMethods.includes(method) || this.options.clientCapabilities?._meta?.subagents !== true) return false; ++ if (message?.method !== "session/update" || "id" in message) return false; ++ const lifecycle = ["subagent_spawned", "subagent_state_update"].includes(message?.params?.update?.sessionUpdate); ++ const active = this.activePrompt; ++ const connection = this.connection; ++ if (this.cursorSubagentStreamOwner !== owner || this.closing || connection?.signal.aborted) return true; ++ if (!active || !connection || active.elicitationController.signal.aborted) return lifecycle || owner.children.has(message?.params?.sessionId); ++ if (owner.active !== active) { owner.active = active; owner.children.clear(); } ++ if (!lifecycle && message?.params?.sessionId === active.sessionId) return false; ++ try { ++ const params = boundedExtensionRecord(message.params); ++ if (lifecycle) { ++ if (params.sessionId !== active.sessionId && !owner.children.has(params.sessionId)) return true; ++ const child = params.update?.subagentSessionId; ++ if (typeof child !== "string" || !child || child.length > 1000 || child === active.sessionId) return true; ++ if (params.update.sessionUpdate === "subagent_spawned") { ++ if (owner.children.has(child) || owner.children.size >= 256) return true; ++ owner.children.set(child, params.sessionId); ++ } else if (owner.children.get(child) !== params.sessionId) return true; ++ this.options.onExtensionNotification?.(method, { sessionId: active.sessionId, parentSessionId: params.sessionId, update: params.update }); ++ } else if (owner.children.has(params.sessionId)) { ++ this.options.onExtensionNotification?.(method, { sessionId: active.sessionId, parentSessionId: owner.children.get(params.sessionId), childSessionId: params.sessionId, update: params.update }); ++ } ++ } catch { ++ this.log("Cursor child activity notification was rejected"); ++ } ++ return true; ++ } + handleExtensionNotification(message) { + if (!this.options.extensionMethods.includes(message.method) || !this.options.onExtensionNotification || this.closing) return; + const active = this.activePrompt; @@ -448,7 +491,7 @@ index d454fd7..4312cdd 100644 })).then((response) => ({ kind: "response", response -@@ -4970,7 +5128,7 @@ var AcpClient = class { +@@ -4970,7 +5164,7 @@ isElicitationSessionCancelling(sessionId) { return this.closing || this.cancellingSessionIds.has(sessionId); } @@ -457,7 +500,7 @@ index d454fd7..4312cdd 100644 if (!this.options.onPermissionRequest) return; const signal = this.cancellationSignalForSession(params.sessionId); try { -@@ -4978,7 +5136,7 @@ var AcpClient = class { +@@ -4978,7 +5172,7 @@ sessionId: params.sessionId, raw: params, inferredKind: inferToolKind(params) @@ -466,7 +509,7 @@ index d454fd7..4312cdd 100644 return this.hostPermissionDecisionResponse(params, signal, decision); } catch (error) { return this.hostPermissionErrorResponse(params, signal, error); -@@ -5028,6 +5186,12 @@ var AcpClient = class { +@@ -5028,6 +5222,12 @@ attachAgentLifecycleObservers(child) { child.once("exit", (exitCode, signal) => { this.recordAgentExit("process_exit", exitCode, signal); @@ -479,7 +522,7 @@ index d454fd7..4312cdd 100644 }); child.once("close", (exitCode, signal) => { this.recordAgentExit("process_close", exitCode, signal); -@@ -5771,10 +5935,20 @@ function recordSessionUpdate(conversation, state, notification, timestamp = isoN +@@ -5771,10 +5971,20 @@ trimConversationForRuntime(conversation); return acpx; } @@ -502,7 +545,7 @@ index d454fd7..4312cdd 100644 updateConversationTimestamp(conversation, timestamp); trimConversationForRuntime(conversation); return true; -@@ -6435,6 +6609,27 @@ async function withConnectedSession(options) { +@@ -6435,6 +6645,27 @@ //#region src/runtime/engine/prompt-turn.ts const SESSION_REPLY_IDLE_MS = 1e3; const SESSION_REPLY_DRAIN_TIMEOUT_MS = 5e3; @@ -530,7 +573,7 @@ index d454fd7..4312cdd 100644 async function runPromptTurn(params) { try { const promptPromise = params.client.prompt(params.sessionId, params.prompt, params.onPromptRequestStarted, params.onElicitation); -@@ -6444,7 +6639,21 @@ async function runPromptTurn(params) { +@@ -6444,7 +6675,21 @@ idleMs: SESSION_REPLY_IDLE_MS, timeoutMs: SESSION_REPLY_DRAIN_TIMEOUT_MS }).catch(() => {}); @@ -552,15 +595,12 @@ index d454fd7..4312cdd 100644 return { stopReason: response.stopReason, source: "rpc" -@@ -6518,4 +6727,4 @@ var LiveSessionCheckpoint = class { +@@ -6518,4 +6763,4 @@ //#endregion export { writeSessionRecord as $, PERMISSION_POLICY_ACTIONS as $t, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as A, TimeoutError as At, getAcpxVersion as B, formatErrorMessage as Bt, mergeSessionOptions as C, PromptInputValidationError as Ct, applyLifecycleSnapshotToRecord as D, promptToDisplayText as Dt, applyConversation as E, parsePromptSource as Et, modelStateFromConfigOptions as F, normalizeAgentName$1 as Ft, findSession as G, toAcpErrorPayload as Gt, DEFAULT_HISTORY_LIMIT as H, normalizeOutputError as Ht, normalizeAgentCommandInput as I, resolveAgentArgv as It, listSessions as J, NON_INTERACTIVE_PERMISSION_POLICIES as Jt, findSessionByDirectoryWalk as K, AUTH_POLICIES as Kt, renderArgvIdentity as L, resolveAgentCommand as Lt, RequestedModelUnsupportedError as M, withTimeout as Mt, assertRequestedModelSupported as N, DEFAULT_AGENT_NAME as Nt, reconcileAgentSessionId as O, textPrompt as Ot, isRequestedModelUnsupportedError as P, listBuiltInAgents as Pt, resolveSessionRecord as Q, PERMISSION_MODES as Qt, runTimedExecFile as R, resolveCanonicalAgentName as Rt, advertisedModelState as S, parsePromptStopReason as St, sessionOptionsFromRecord as T, mergePromptSourceWithText as Tt, absolutePath as U, extractAcpError as Ut, permissionModeSatisfies as V, isRetryablePromptError as Vt, findGitRepositoryRoot as W, isAcpResourceNotFoundError as Wt, normalizeName as X, OUTPUT_ERROR_ORIGINS as Xt, listSessionsForAgent as Y, OUTPUT_ERROR_CODES as Yt, pruneSessions as Z, OUTPUT_FORMATS as Zt, createSessionConversation as _, sessionEventLockPath as _t, applyRequestedModelIfAdvertised as a, measurePerf as at, recordSessionUpdate as b, isAcpJsonRpcMessage as bt, setCurrentModelId as c, setPerfGauge as ct, setDesiredModelId as d, serializeSessionRecordForDisk as dt, SESSION_RECORD_SCHEMA as en, createAtomicWriteTempPath as et, syncAdvertisedModelState as f, normalizeRuntimeSessionId as ft, cloneSessionConversation as g, sessionEventActivePath as gt, cloneSessionAcpxState as h, sessionBaseDir$1 as ht, connectAndLoadSession as i, QueueProtocolError as in, incrementPerfCounter as it, REQUESTED_MODEL_UNSUPPORTED_REASONS as j, withInterrupt as jt, AcpClient as k, InterruptedError as kt, setDesiredConfigOption as l, startPerfTimer as lt, applyConfigOptionsToState as m, defaultSessionEventLog as mt, runPromptTurn as n, AgentSpawnError as nn, formatPerfMetric as nt, currentModelIdFromSetModelResponse as o, recordPerfDuration as ot, applyConfigOptionsToRecord as p, DEFAULT_EVENT_SEGMENT_MAX_BYTES as pt, isoNow$2 as q, EXIT_CODES as qt, withConnectedSession as r, QueueConnectionError as rn, getPerfMetricsSnapshot as rt, clearDesiredConfigOption as s, resetPerfMetrics as st, LiveSessionCheckpoint as t, AcpxOperationalError as tn, assertPersistedKeyPolicy as tt, setDesiredModeId as u, parseSessionRecord as ut, recordClientOperation as v, sessionEventSegmentPath as vt, persistSessionOptions as w, isPromptInput as wt, trimConversationForRuntime as x, parseJsonRpcErrorMessage as xt, recordPromptSubmission as y, extractSessionUpdateNotification as yt, splitCommandLine as z, exitCodeForOutputErrorCode as zt }; --//# sourceMappingURL=live-checkpoint-BSIrfgVo.js.map -\ No newline at end of file -+//# sourceMappingURL=live-checkpoint-BSIrfgVo.js.map +-//# sourceMappingURL=live-checkpoint-BSIrfgVo.js.map+//# sourceMappingURL=live-checkpoint-BSIrfgVo.js.map diff --git a/dist/runtime.d.ts b/dist/runtime.d.ts -index e8102ac..d3a9ba6 100644 --- a/dist/runtime.d.ts +++ b/dist/runtime.d.ts @@ -1,7 +1,8 @@ @@ -573,7 +613,7 @@ index e8102ac..d3a9ba6 100644 //#region src/agent-registry.d.ts declare const DEFAULT_AGENT_NAME = "codex"; //#endregion -@@ -44,6 +45,7 @@ type AcpRuntimeTurnAttachment = { +@@ -44,6 +45,7 @@ data: string; }; type AcpRuntimeTurnInput = { @@ -581,7 +621,7 @@ index e8102ac..d3a9ba6 100644 handle: AcpRuntimeHandle; text: string; attachments?: AcpRuntimeTurnAttachment[]; -@@ -141,6 +143,11 @@ type AcpTextDeltaOriginMeta = { +@@ -141,6 +143,11 @@ kind?: string; source?: string; }; @@ -593,7 +633,7 @@ index e8102ac..d3a9ba6 100644 type AcpRuntimeEvent = { type: "text_delta"; text: string; -@@ -186,6 +193,10 @@ type AcpRuntimeEvent = { +@@ -186,6 +193,10 @@ * non-null `input` schema. */ availableCommands?: AcpRuntimeAvailableCommand[]; @@ -604,7 +644,7 @@ index e8102ac..d3a9ba6 100644 } | { type: "tool_call"; text: string; -@@ -312,7 +323,49 @@ type AcpRuntimeOptions = { +@@ -312,7 +323,49 @@ elicitationModes?: readonly AcpElicitationMode[]; onPermissionRequest?: (req: AcpPermissionRequest, ctx: { signal: AbortSignal; @@ -654,7 +694,7 @@ index e8102ac..d3a9ba6 100644 }; type AcpFileSessionStoreOptions = { stateDir: string; -@@ -369,6 +422,7 @@ declare class AcpRuntimeManager { +@@ -369,6 +422,7 @@ private createAndSaveRuntimeRecord; private retainInitializedSessionOwner; startTurn(input: { @@ -662,7 +702,7 @@ index e8102ac..d3a9ba6 100644 handle: AcpRuntimeHandle; text: string; attachments?: AcpRuntimeTurnAttachment[]; -@@ -414,6 +468,7 @@ declare class AcpRuntimeManager { +@@ -414,6 +468,7 @@ private cleanupRuntimeTurn; private finalizeRuntimeTurnRecord; runTurn(input: { @@ -671,10 +711,9 @@ index e8102ac..d3a9ba6 100644 text: string; attachments?: AcpRuntimeTurnAttachment[]; diff --git a/dist/runtime.js b/dist/runtime.js -index a1f4a70..fe2484d 100644 --- a/dist/runtime.js +++ b/dist/runtime.js -@@ -371,7 +371,7 @@ const PROMPT_EVENT_PARSERS = { +@@ -371,7 +371,7 @@ current_mode_update: (payload) => statusUpdateEvent("current_mode_update", payload), config_option_update: (payload) => statusUpdateEvent("config_option_update", payload), session_info_update: (payload) => statusUpdateEvent("session_info_update", payload), @@ -683,10 +722,11 @@ index a1f4a70..fe2484d 100644 client_operation: clientOperationEvent, update: updateStatusEvent, done: () => null, -@@ -424,6 +424,34 @@ function availableCommandsUpdateEvent(payload) { +@@ -423,6 +423,34 @@ + tag: "available_commands_update", availableCommands }; - } ++} +function persistedGoalCapability(goal) { + if (!isRecord(goal) || goal.version !== 1 || goal.controlMethod !== "_session/goal" || !Array.isArray(goal.actions)) return; + const actions = goal.actions.filter((action) => ["set", "pause", "resume", "clear"].includes(action)); @@ -714,11 +754,10 @@ index a1f4a70..fe2484d 100644 + entries.push({ content, status, ...priority ? { priority } : {} }); + } + return { type: "plan", tag: "plan", entries }; -+} + } function normalizeUsageCost(value) { if (!isRecord(value)) return; - const amount = asOptionalFiniteNumber(value.amount); -@@ -812,7 +840,21 @@ var AcpRuntimeManager = class { +@@ -812,7 +840,21 @@ this.deps = deps; } createClient(options) { @@ -741,7 +780,7 @@ index a1f4a70..fe2484d 100644 } createSessionOwner(input) { const owner = { -@@ -821,12 +863,16 @@ var AcpRuntimeManager = class { +@@ -821,12 +863,16 @@ pendingSessionUpdates: [] }; input.client.setEventHandlers({ @@ -758,7 +797,7 @@ index a1f4a70..fe2484d 100644 const active = owner.activeTurn; if (active) { const { task, turn } = active; -@@ -863,6 +909,9 @@ var AcpRuntimeManager = class { +@@ -863,6 +909,9 @@ projection.checkpoint.request(); } routeOwnedClientOperation(owner, operation) { @@ -768,7 +807,7 @@ index a1f4a70..fe2484d 100644 const active = owner.activeTurn; if (!active) return; const { task, turn } = active; -@@ -1008,6 +1057,8 @@ var AcpRuntimeManager = class { +@@ -1008,6 +1057,8 @@ record.closedAt = void 0; record.protocolVersion = owner.client.initializeResult?.protocolVersion; record.agentCapabilities = owner.client.initializeResult?.agentCapabilities; @@ -777,7 +816,7 @@ index a1f4a70..fe2484d 100644 applyLifecycleSnapshotToRecord(record, owner.client.getAgentLifecycleSnapshot()); } async finishBufferedOwnerControl(owner, record) { -@@ -1086,6 +1137,11 @@ var AcpRuntimeManager = class { +@@ -1086,6 +1137,11 @@ record.closed = false; record.closedAt = void 0; this.closingActiveRecords.delete(record.acpxRecordId); @@ -789,7 +828,7 @@ index a1f4a70..fe2484d 100644 await this.options.sessionStore.save(record); return record; } -@@ -1149,6 +1205,8 @@ var AcpRuntimeManager = class { +@@ -1149,6 +1205,8 @@ this.closingActiveRecords.delete(record.acpxRecordId); record.protocolVersion = client.initializeResult?.protocolVersion; record.agentCapabilities = client.initializeResult?.agentCapabilities; @@ -798,7 +837,7 @@ index a1f4a70..fe2484d 100644 applyConfigOptionsToRecord(record, session.sessionResult); const modelApplication = await applyRequestedModelIfAdvertised({ client, -@@ -1301,6 +1359,7 @@ var AcpRuntimeManager = class { +@@ -1301,6 +1359,7 @@ client: turn.client, sessionId, prompt: task.promptInput, @@ -806,7 +845,7 @@ index a1f4a70..fe2484d 100644 timeoutMs: task.input.timeoutMs ?? this.options.timeoutMs, conversation: turn.conversation, promptMessageId: turn.promptMessageId, -@@ -1469,6 +1528,10 @@ var AcpRuntimeManager = class { +@@ -1469,6 +1528,10 @@ setSessionConfigOption: async (configId, value) => { return (await task.state.activeController.setResolvedSessionConfigOption(configId, value)).response; }, @@ -817,7 +856,7 @@ index a1f4a70..fe2484d 100644 setResolvedSessionConfigOption: async (configId, value) => await this.setRuntimeResolvedSessionConfigOption(task, turn, configId, value) }; } -@@ -1575,6 +1638,8 @@ var AcpRuntimeManager = class { +@@ -1575,6 +1638,8 @@ reconcileAgentSessionId(turn.record, turn.record.agentSessionId); turn.record.protocolVersion = turn.client.initializeResult?.protocolVersion; turn.record.agentCapabilities = turn.client.initializeResult?.agentCapabilities; @@ -826,10 +865,11 @@ index a1f4a70..fe2484d 100644 turn.record.acpx = turn.acpxState; applyConversation(turn.record, turn.conversation); applyLifecycleSnapshotToRecord(turn.record, turn.client.getAgentLifecycleSnapshot()); -@@ -1707,6 +1772,17 @@ var AcpRuntimeManager = class { +@@ -1706,6 +1771,17 @@ + applyDesiredConfigOptionToRecord(connectedRecord, configId, value); }); await this.options.sessionStore.save(result.record); - } ++ } + async requestExtension(input) { + const recordId = input.handle.acpxRecordId ?? input.handle.sessionKey; + return await this.withManagerLock(this.runtimeOperationLocks, recordId, async () => { @@ -840,11 +880,10 @@ index a1f4a70..fe2484d 100644 + return await client.requestExtension(input.method, input.params); + })).value; + }); -+ } + } async cancel(handle) { await this.activeControllers.get(handle.acpxRecordId ?? handle.sessionKey)?.requestCancelActivePrompt(); - } -@@ -2055,6 +2131,7 @@ var AcpxRuntime = class { +@@ -2055,6 +2131,7 @@ const turnPromise = this.getManager().then((manager) => manager.startTurn({ handle, text: input.text, @@ -852,7 +891,7 @@ index a1f4a70..fe2484d 100644 attachments: input.attachments, mode: input.mode, sessionMode: state.mode, -@@ -2087,6 +2164,7 @@ var AcpxRuntime = class { +@@ -2087,6 +2164,7 @@ yield* (await this.getManager()).runTurn({ handle, text: input.text, @@ -860,10 +899,11 @@ index a1f4a70..fe2484d 100644 attachments: input.attachments, mode: input.mode, sessionMode: state.mode, -@@ -2119,6 +2197,14 @@ var AcpxRuntime = class { +@@ -2118,6 +2196,14 @@ + async setConfigOption(input) { const { handle, state } = this.resolveManagerHandle(input.handle); await (await this.getManager()).setConfigOption(handle, input.key, input.value, state.mode); - } ++ } + async requestExtension(input) { + const { handle, state } = this.resolveManagerHandle(input.handle); + return await (await this.getManager()).requestExtension({ @@ -871,19 +911,15 @@ index a1f4a70..fe2484d 100644 + handle, + sessionMode: input.sessionMode ?? state.mode + }); -+ } + } async cancel(input) { const { handle } = this.resolveManagerHandle(input.handle); - await (await this.getManager()).cancel(handle); -@@ -2178,4 +2264,4 @@ function createRuntimeStore(options) { +@@ -2178,4 +2264,4 @@ //#endregion export { ACPX_BACKEND_ID, AcpRuntimeError, AcpxRuntime, DEFAULT_AGENT_NAME, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE, REQUESTED_MODEL_UNSUPPORTED_REASONS, RequestedModelUnsupportedError, createAcpRuntime, createAgentRegistry, createFileSessionStore, createRuntimeStore, decodeAcpxRuntimeHandleState, encodeAcpxRuntimeHandleState, isAcpRuntimeError, isRequestedModelUnsupportedError }; --//# sourceMappingURL=runtime.js.map -\ No newline at end of file -+//# sourceMappingURL=runtime.js.map +-//# sourceMappingURL=runtime.js.map+//# sourceMappingURL=runtime.js.map diff --git a/dist/session-options-DwRDODlr.d.ts b/dist/session-options-DwRDODlr.d.ts -index c3da164..5ccc8dd 100644 --- a/dist/session-options-DwRDODlr.d.ts +++ b/dist/session-options-DwRDODlr.d.ts @@ -1,4 +1,5 @@ @@ -892,7 +928,7 @@ index c3da164..5ccc8dd 100644 //#region src/prompt-content.d.ts type PromptInput = ContentBlock[]; //#endregion -@@ -27,6 +28,8 @@ type AcpElicitationContext = { +@@ -27,6 +28,8 @@ requestId: JsonRpcId; /** Aborts with the request itself or its owning prompt turn/session. */ signal: AbortSignal; @@ -901,7 +937,7 @@ index c3da164..5ccc8dd 100644 }; type AcpElicitationResponseMeta = { _meta?: Record | null; -@@ -116,6 +119,35 @@ type AcpClientOptions = { +@@ -116,6 +119,35 @@ }; env?: Record; }; @@ -937,7 +973,7 @@ index c3da164..5ccc8dd 100644 onAcpMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void; onAcpOutputMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void; onSessionUpdate?: (notification: SessionNotification) => void; -@@ -123,6 +155,8 @@ type AcpClientOptions = { +@@ -123,6 +155,8 @@ onPermissionEscalation?: (event: PermissionEscalationEvent) => void; onPermissionRequest?: (req: AcpPermissionRequest, ctx: { signal: AbortSignal; @@ -946,7 +982,7 @@ index c3da164..5ccc8dd 100644 }) => Promise; }; declare const SESSION_RECORD_SCHEMA: "acpx.session.v1"; -@@ -263,12 +297,15 @@ type SessionRecord = { +@@ -263,12 +297,15 @@ lastAgentDisconnectReason?: string; protocolVersion?: number; agentCapabilities?: AgentCapabilities; @@ -963,10 +999,8 @@ index c3da164..5ccc8dd 100644 acpx?: SessionAcpxState; importedFrom?: SessionImportedFrom; }; -@@ -295,4 +332,4 @@ type SessionAgentOptions = { +@@ -295,4 +332,4 @@ }; //#endregion export { SessionRecord as _, AcpElicitationHandler as a, AcpElicitationResponse as c, AuthPolicy as d, McpServer$1 as f, PermissionStats as g, PermissionPolicy as h, AcpElicitationContext as i, AcpPermissionDecision as l, PermissionMode as m, SystemPromptOption as n, AcpElicitationMode as o, NonInteractivePermissionPolicy as p, AcpClientOptions as r, AcpElicitationRequest as s, SessionAgentOptions as t, AcpPermissionRequest as u, PromptInput as v }; --//# sourceMappingURL=session-options-DwRDODlr.d.ts.map -\ No newline at end of file -+//# sourceMappingURL=session-options-DwRDODlr.d.ts.map +-//# sourceMappingURL=session-options-DwRDODlr.d.ts.map+//# sourceMappingURL=session-options-DwRDODlr.d.ts.map