From 541f0db7f29db9fa2a69648a45feee883ba626e2 Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Tue, 17 Nov 2026 10:43:28 -0500 Subject: [PATCH 1/3] Retain screened ACP diagnostics for refused Sidekick resumes --- packages/acp/src/events.ts | 49 ++++-- packages/acp/src/provider.ts | 33 ++++- packages/acp/tests/certification-fixture.ts | 4 + packages/acp/tests/host-conversation.test.ts | 98 +++++++++++- packages/acp/tests/released-peer.ts | 6 +- packages/acp/tests/released-runtime.test.ts | 122 +++++++++++++-- packages/acp/vendor/acpx/MANIFEST.json | 6 +- packages/acp/vendor/acpx/PROVENANCE.md | 2 + .../acp/vendor/acpx/generated/runtime.d.ts | 2 + packages/acp/vendor/acpx/generated/runtime.js | 32 ++-- packages/agent/src/conversation.ts | 53 +++++-- packages/agent/src/errors.ts | 29 +++- packages/agent/src/function-components.ts | 28 +++- packages/agent/src/journal.ts | 25 +++- .../agent/tests/agent-conversation.test.ts | 140 ++++++++++++++++++ packages/cli/src/repl/sidekick/model.ts | 22 +++ packages/cli/src/repl/sidekick/owner.ts | 4 +- .../cli/tests/repl-sidekick-recovery.test.ts | 124 +++++++++++++++- packages/cli/tests/support/fake-acp.ts | 19 +++ specs/acp-client-spec.md | 37 ++++- specs/repl-spec.md | 14 ++ 21 files changed, 758 insertions(+), 91 deletions(-) diff --git a/packages/acp/src/events.ts b/packages/acp/src/events.ts index 79ee0d34c..97a82da3e 100644 --- a/packages/acp/src/events.ts +++ b/packages/acp/src/events.ts @@ -25,7 +25,11 @@ import { each, race, stream, until } from "effection"; import type { Channel, Operation } from "effection"; import type { AgentPromptCheckpoint, AgentPromptEvent, Session } from "@executablemd/agent/api"; -import type { AcpRuntimeTurn, AcpRuntimeTurnResult } from "./acpx-runtime.ts"; +import type { + AcpRuntimeTurn, + AcpRuntimeTurnResult, + AcpRuntimeTurnResultError, +} from "./acpx-runtime.ts"; import { checkpointFromResult } from "./checkpoint.ts"; import { XmdResponse, XMD_RESPONSE, xmdPromptEvent } from "./xmd-response.ts"; import type { Registration } from "./permission-bridge.ts"; @@ -182,29 +186,44 @@ function mapResult(result: AcpRuntimeTurnResult, requestId: string): AgentPrompt } return terminal; } - const failure = new Error(result.error.message); + return { + type: "terminal", + status: "failed", + error: withPromptDiagnostic(new Error(result.error.message), result.error, { + stage: "runtime-turn", + requestId, + }), + }; +} + +export type PromptDiagnosticSource = + | { stage: "runtime-turn"; requestId: string } + | { stage: "held-session-ensure" | "prompt-ensure" }; + +export function withPromptDiagnostic( + failure: Error, + facts: AcpRuntimeTurnResultError, + source: PromptDiagnosticSource, +): Error { Object.defineProperty(failure, "executablemd.agent.prompt-diagnostic", { value: { provider: "acp", operation: "session/prompt", - stage: "runtime-turn", - requestId, - ...(result.error.code === undefined ? {} : { code: result.error.code }), - ...(result.error.detailCode === undefined ? {} : { detailCode: result.error.detailCode }), - ...(result.error.retryable === undefined ? {} : { retryable: result.error.retryable }), - ...(result.error.origin === undefined ? {} : { origin: result.error.origin }), - ...(result.error.acp === undefined + ...source, + ...(facts.code === undefined ? {} : { code: facts.code }), + ...(facts.detailCode === undefined ? {} : { detailCode: facts.detailCode }), + ...(facts.retryable === undefined ? {} : { retryable: facts.retryable }), + ...(facts.origin === undefined ? {} : { origin: facts.origin }), + ...(facts.acp === undefined ? {} : { acp: { - code: result.error.acp.code, - message: result.error.acp.message, - ...(result.error.acp.details === undefined - ? {} - : { details: result.error.acp.details }), + code: facts.acp.code, + message: facts.acp.message, + ...(facts.acp.details === undefined ? {} : { details: facts.acp.details }), }, }), }, }); - return { type: "terminal", status: "failed", error: failure }; + return failure; } diff --git a/packages/acp/src/provider.ts b/packages/acp/src/provider.ts index 37b9333a1..0be0de12c 100644 --- a/packages/acp/src/provider.ts +++ b/packages/acp/src/provider.ts @@ -102,6 +102,7 @@ import { createAcpRuntime, createAgentRegistry, createRuntimeStore, + projectRuntimeError, resolveAgentCommand, } from "./acpx-runtime.ts"; import type { @@ -125,7 +126,8 @@ import { createPermissionBridge, strictPermissions, } from "./permission-bridge.ts"; -import { consumeTurn } from "./events.ts"; +import { consumeTurn, withPromptDiagnostic } from "./events.ts"; +import type { PromptDiagnosticSource } from "./events.ts"; import { capturePromptUsage, turnUsage } from "./usage.ts"; import type { PromptUsageHost, TurnUsage } from "./usage.ts"; import { checkpointFromResult } from "./checkpoint.ts"; @@ -1932,6 +1934,7 @@ function* useAcpxProviderState( * this ensure itself may perform. Never kept on the entry it returns. */ requestedModel?: string; + resumeFailureStage?: "held-session-ensure" | "prompt-ensure"; } function* ensureFromPrepared( @@ -2033,7 +2036,13 @@ function* useAcpxProviderState( // reported as an ordinary reattachment's is: the adapter's account, // with nothing created in its place. if (attachment === undefined) { - throw sessionResumeFailure(error, prepared.details.sessionKey); + throw sessionResumeFailure( + error, + prepared.details.sessionKey, + intent.resumeFailureStage === undefined + ? undefined + : { stage: intent.resumeFailureStage }, + ); } // An exact resume that the provider could not perform: it has no such // history, or it cannot resume by name at all. Either way the @@ -3183,6 +3192,7 @@ function* useAcpxProviderState( ...(resumeSessionId === undefined ? {} : { attachment: { resumeSessionId } }), state, ...modelRequest(desired), + resumeFailureStage: "prompt-ensure", materialization: constructing && adapterFor(agentName)?.acceptance === "first-turn-acceptance", deferEstablished: @@ -3316,7 +3326,10 @@ function* useAcpxProviderState( try { yield* until(turn.promptStarted); } catch (error) { - throw sessionResumeFailure(error, entry.session.sessionKey); + throw sessionResumeFailure(error, entry.session.sessionKey, { + stage: "runtime-turn", + requestId: turn.requestId, + }); } } @@ -4941,6 +4954,9 @@ function* useAcpxProviderState( : { build: construction.build, verifyReopening: construction.verifyReopening }), ...(resumeSessionId === undefined ? {} : { attachment: { resumeSessionId } }), state, + ...(selectedAgent === undefined + ? {} + : { resumeFailureStage: "held-session-ensure" }), ...(setup?.requestedModel === undefined ? {} : { requestedModel: setup.requestedModel }), @@ -5058,7 +5074,11 @@ function nativeIdentityRefusal(error: unknown): AttachmentRefused | undefined { } } -function sessionResumeFailure(error: unknown, sessionKey: string): unknown { +function sessionResumeFailure( + error: unknown, + sessionKey: string, + source?: PromptDiagnosticSource, +): unknown { const refusal = nativeIdentityRefusal(error); if (refusal) { return refusal; @@ -5068,7 +5088,10 @@ function sessionResumeFailure(error: unknown, sessionKey: string): unknown { error !== null && Reflect.get(error, "detailCode") === "SESSION_RESUME_REQUIRED" ) { - return new SessionResumeRequiredError(sessionKey, { cause: error }); + const failure = new SessionResumeRequiredError(sessionKey); + return source === undefined + ? failure + : withPromptDiagnostic(failure, projectRuntimeError(error), source); } return error; } diff --git a/packages/acp/tests/certification-fixture.ts b/packages/acp/tests/certification-fixture.ts index 06df38137..98b99734f 100644 --- a/packages/acp/tests/certification-fixture.ts +++ b/packages/acp/tests/certification-fixture.ts @@ -39,6 +39,10 @@ function answer(request) { reply(id,{sessionId,configOptions:options(),...(mode === "standard" || mode === "standard-wait" ? {} : {_meta:{agentSessionId:native()}})}); } else if (method === "session/load") { sessionId=params.sessionId; + if (mode === "distinct-refused") { + send({jsonrpc:"2.0",id,error:{code:-32041,message:"Internal error",data:{details:"Release the active writer before reconnecting.",unrelated:"private unrelated marker"}}}); + return; + } fs.readFile(file(),"utf8",(error,text) => { if (error) { send({jsonrpc:"2.0",id,error:{code:-32603,message:"missing controlled history"}});return; } marker=JSON.parse(text).marker; diff --git a/packages/acp/tests/host-conversation.test.ts b/packages/acp/tests/host-conversation.test.ts index 9c39891fc..32d215b2a 100644 --- a/packages/acp/tests/host-conversation.test.ts +++ b/packages/acp/tests/host-conversation.test.ts @@ -35,7 +35,7 @@ import { Ok, scoped, spawn, suspend, until, withResolvers } from "effection"; import type { Operation, Result } from "effection"; import { Component } from "@executablemd/core"; import { Agent } from "@executablemd/agent/api"; -import { installAgentComponents } from "@executablemd/agent/host"; +import { installAgentComponents, useAgentPromptPublisher } from "@executablemd/agent/host"; import type { FunctionComponentDefinition, Json } from "@executablemd/core"; import type { Session } from "@executablemd/agent/api"; import { useAgentConversation } from "@executablemd/agent/host"; @@ -1738,7 +1738,7 @@ describe( ); describe( - "a held Codex conversation across a host CLI upgrade", + "1388 — resume retention: a held Codex conversation across a host CLI upgrade", { sanitizeOps: false, sanitizeResources: false }, () => { for (const [mode, failure, errorName] of [ @@ -1746,6 +1746,7 @@ describe( ["normal", "reopened a different native conversation", "AttachmentRefused"], ["standard", "did not confirm the retained native conversation", "AttachmentRefused"], ["missing", "could not be resumed", "SessionResumeRequiredError"], + ["distinct-refused", "could not be resumed", "SessionResumeRequiredError"], ] as const) { it(`requires the new build's live identity (${mode})`, function* () { yield* withCertificationFixture(function* (f) { @@ -1779,9 +1780,29 @@ describe( target.observer.observation.path = "/opt/builds/codex-0.167.1"; target.observer.observation.versionOutput = "codex-cli 0.167.1\n"; target.observer.observation.digest = "b".repeat(64); + const begun: string[] = []; + const published: unknown[] = []; + const provider = target.installation(mode === "missing" ? command : f.command(mode)); const resumed = yield* withConversation( stream, - target.installation(mode === "missing" ? command : f.command(mode)), + { + ...provider, + *install() { + if (provider.install !== undefined) { + yield* provider.install(); + } + yield* useAgentPromptPublisher({ + *begin(text) { + begun.push(text); + return {}; + }, + *publish(publication) { + published.push(publication.begun); + yield* publication.append(); + }, + }); + }, + }, (chat) => chat.prompt("recall", { model: "selected", effort: "high" }), "codex", ); @@ -1822,7 +1843,76 @@ describe( expect(methods).not.toContain("session/set_config_option"); expect(methods).not.toContain("session/prompt"); expect(yield* until(target.store.load(key))).toEqual(record); - expect(stream.snapshot().map(serializeDurableEvent)).toEqual(lines); + if (errorName === "SessionResumeRequiredError") { + const after = stream.snapshot(); + expect(after.slice(0, lines.length).map(serializeDurableEvent)).toEqual(lines); + expect(after).toHaveLength(lines.length + 1); + const saved = turns(after).at(-1); + const expectedError = { + message: resumed.value.error.message, + name: errorName, + diagnostic: { + provider: "acp", + operation: "session/prompt", + stage: "held-session-ensure", + code: "RUNTIME", + detailCode: "SESSION_RESUME_REQUIRED", + origin: "acp", + retryable: true, + acp: + mode === "missing" + ? { code: -32603, message: "missing controlled history" } + : { + code: -32041, + message: "Internal error", + details: "Release the active writer before reconnecting.", + }, + }, + }; + expect(saved?.name).toBe("turn:2"); + expect(saved?.record).toEqual({ + sequence: expect.any(Number), + agent: "codex", + sessionKey: "", + status: "failed", + text: "", + error: expectedError, + }); + const event = after.at(-1); + expect(event?.type === "yield" && event.description.input).toBe("recall"); + expect(begun).toEqual([]); + expect(published).toEqual([undefined]); + expect(resumed.value.error.cause).toBe(undefined); + expect( + Reflect.get(resumed.value.error, "executablemd.agent.prompt-diagnostic"), + ).toEqual(expectedError.diagnostic); + if (mode === "distinct-refused") { + const attemptedCalls = (yield* f.calls()).length; + const later = yield* withConversation( + stream, + target.installation(f.command("distinct-next")), + (chat) => chat.prompt("recover"), + "codex", + ); + expect(answer(later)).toBe("remembered"); + const sent = (yield* f.calls()).slice(attemptedCalls); + expect(sent.filter((call) => call.method === "session/prompt")).toMatchObject([ + { sessionId: record.acpSessionId }, + ]); + expect(sent.map((call) => call.method)).not.toContain("session/new"); + expect(turns(stream.snapshot()).map((turn) => turn.name)).toEqual([ + "turn:1", + "turn:2", + "turn:3", + ]); + expect((yield* until(target.store.load(key)))?.agentSessionId).toBe( + record.agentSessionId, + ); + expect(yield* target.ownership.routes.read(tuple)).toEqual(route); + } + } else { + expect(stream.snapshot().map(serializeDurableEvent)).toEqual(lines); + } } }); }); diff --git a/packages/acp/tests/released-peer.ts b/packages/acp/tests/released-peer.ts index 970786670..2570436ac 100644 --- a/packages/acp/tests/released-peer.ts +++ b/packages/acp/tests/released-peer.ts @@ -75,7 +75,11 @@ function respond(request) { if (controlDirectory && request.method === "session/load") { fs.access(path.join(controlDirectory, "fail-load"), error => { if (error) loaded(); - else send({jsonrpc: "2.0", id: request.id, error: {code: -32603, message: "Controlled cold load failure"}}); + else fs.readFile(path.join(controlDirectory, "fail-load"), "utf8", (error, text) => { + if (error) throw error; + const failure = text === "enabled" ? {code: -32603, message: "Controlled cold load failure"} : JSON.parse(text); + send({jsonrpc: "2.0", id: request.id, error: failure}); + }); }); } else loaded(); } else if (request.method === "session/set_config_option") { diff --git a/packages/acp/tests/released-runtime.test.ts b/packages/acp/tests/released-runtime.test.ts index d8d339cc7..11ed991a9 100644 --- a/packages/acp/tests/released-runtime.test.ts +++ b/packages/acp/tests/released-runtime.test.ts @@ -30,7 +30,11 @@ import { retainedSession } from "../src/session-store.ts"; import { createAcpxProvider } from "../src/provider.ts"; import { useNormalizedOutput } from "@executablemd/core"; import { Agent, configurationOf } from "@executablemd/agent/api"; -import { agentIdentityComponents, installAgentComponents } from "@executablemd/agent/host"; +import { + agentIdentityComponents, + installAgentComponents, + parsePromptRecord, +} from "@executablemd/agent/host"; import type { AgentPromptEvent, Session } from "@executablemd/agent/api"; import { executeInstalled } from "@executablemd/core/host"; import { InMemoryStream } from "@executablemd/durable-streams"; @@ -43,7 +47,7 @@ import { l as runPromptTurn, } from "../vendor/acpx/generated/queue-owner-runtime-ucHvXJ33.js"; -import { STANDARD_AGENT_SOURCE, world } from "./released-peer.ts"; +import { AGENT_SOURCE, STANDARD_AGENT_SOURCE, world } from "./released-peer.ts"; function* runtimeWorld() { const current = yield* world(); @@ -1143,15 +1147,24 @@ describe("released response recovery", () => { }); describe( - "standard retained-session refusal", + "1388 — resume retention: standard retained-session refusal", { sanitizeOps: false, sanitizeResources: false }, () => { - for (const failure of ["fail-load", "no-load", "unused-no-load"]) { - it(`${failure} preserves conversation facts without replacement`, function* () { + for (const [failure, stage, detail] of [ + ["fail-load", "runtime-turn", "Release the active writer before reconnecting."], + ["fail-load", "runtime-turn", undefined], + ["fail-load", "runtime-turn", ""], + ["fail-load", "runtime-turn", ["ghp", "_", "abcdefghijklmnopqrstuvwxyz0123456789"].join("")], + ["fail-load", "prompt-ensure", "Release the active writer before reconnecting."], + ["no-load", "runtime-turn", undefined], + ["unused-no-load", "runtime-turn", undefined], + ] as const) { + const ensureRefusal = stage === "prompt-ensure"; + it(`${failure} at ${stage} preserves conversation facts without replacement (detail length ${detail?.length ?? "absent"})`, function* () { const current = yield* world(true); yield* writeTextFile( current.agent, - STANDARD_AGENT_SOURCE.replace( + (ensureRefusal ? AGENT_SOURCE : STANDARD_AGENT_SOURCE).replace( 'if (text !== "no-accept") update({sessionUpdate: "session_info_update", _meta: {"executablemd.session-materialization/v1": {state: "accepted"}}});', "", ), @@ -1181,7 +1194,17 @@ describe( } const baseline = yield* readTextFile(join(current.dir, "methods.jsonl")); const flag = join(current.dir, failure === "unused-no-load" ? "no-load" : failure); - yield* writeTextFile(flag, "enabled"); + const unrelated = "unrelated-adapter-envelope"; + yield* writeTextFile( + flag, + failure === "fail-load" + ? JSON.stringify({ + code: -32041, + message: "Internal error", + data: { details: detail, unrelated }, + }) + : "enabled", + ); const run = function* (text: string) { return yield* scoped(function* () { yield* installAgentComponents({ @@ -1191,6 +1214,23 @@ describe( factory: createAcpxProvider({ sessionStore: current.store, agentRegistry: current.registry, + ...(ensureRefusal + ? { + createRuntime(options: AcpRuntimeOptions) { + const runtime = createAcpRuntime(options); + const ensureSession = runtime.ensureSession.bind(runtime); + return Object.assign(runtime, { + ensureSession(input: AcpRuntimeEnsureInput) { + return ensureSession({ + ...input, + resumeSessionId: before.acpSessionId, + expectedAgentSessionId: before.agentSessionId, + }); + }, + }); + }, + } + : {}), advertiseNativeLaunch: [], advertiseClientNativeAttachment: [], *agentCwd() { @@ -1228,7 +1268,9 @@ describe( const doc = join(current.dir, "refusal.md"); yield* writeTextFile( doc, - ``, + ensureRefusal + ? `` + : ``, ); yield* useNormalizedOutput(); const journal = new InMemoryStream(); @@ -1256,6 +1298,54 @@ describe( }, }, }); + if (recorded?.type !== "yield" || recorded.result.status !== "ok") { + throw new Error("No canonical refusal"); + } + const saved = parsePromptRecord(recorded.result.value)?.error; + if (saved === undefined) { + throw new Error("No saved failure"); + } + const sensitive = detail?.startsWith("ghp_") === true; + expect(saved).toEqual({ + message: expect.stringContaining("Name a different "), + name: "SessionResumeRequiredError", + diagnostic: { + provider: "acp", + operation: "session/prompt", + stage, + ...(ensureRefusal ? {} : { requestId: expect.stringMatching(/^[0-9a-f-]+$/) }), + code: "RUNTIME", + detailCode: "SESSION_RESUME_REQUIRED", + origin: "acp", + retryable: true, + ...(failure !== "fail-load" + ? {} + : { + acp: { + code: -32041, + message: "Internal error", + ...(sensitive || detail === undefined ? {} : { details: detail }), + }, + }), + }, + }); + expect(JSON.stringify(refused.history)).not.toContain(unrelated); + if (sensitive) { + expect(JSON.stringify(refused.history)).not.toContain(detail); + } + if (refused.result.ok) { + throw new Error("The refused Prompt completed"); + } + const publicError = + refused.result.error instanceof AggregateError + ? refused.result.error.errors[0] + : refused.result.error; + expect(publicError?.name).toBe("SessionResumeRequiredError"); + expect(publicError?.message).toBe(saved.message); + expect(publicError?.cause).toBe(undefined); + expect(Reflect.get(publicError!, "executablemd.agent.prompt-diagnostic")).toEqual( + saved.diagnostic, + ); const delta = (yield* readTextFile(join(current.dir, "methods.jsonl"))).slice( baseline.length, ); @@ -1281,13 +1371,17 @@ describe( expect(after[field]).toEqual(before[field]); } expect(after.sessionMaterialization).toBe(undefined); - expect(after.agentSessionId).toBe(undefined); + expect(after.agentSessionId).toBe(before.agentSessionId); expect(after.messages.slice(0, before.messages.length)).toEqual(before.messages); - expect(after.messages.slice(before.messages.length)).toEqual([ - expect.objectContaining({ - User: expect.objectContaining({ content: [{ Text: "must not send" }] }), - }), - ]); + expect(after.messages.slice(before.messages.length)).toEqual( + ensureRefusal + ? [] + : [ + expect.objectContaining({ + User: expect.objectContaining({ content: [{ Text: "must not send" }] }), + }), + ], + ); yield* rm(flag); const recoveredBaseline = yield* readTextFile(join(current.dir, "methods.jsonl")); expect((yield* run("only the new prompt")).result.ok).toBe(true); diff --git a/packages/acp/vendor/acpx/MANIFEST.json b/packages/acp/vendor/acpx/MANIFEST.json index 7d81d1ee0..5c103376a 100644 --- a/packages/acp/vendor/acpx/MANIFEST.json +++ b/packages/acp/vendor/acpx/MANIFEST.json @@ -32,7 +32,7 @@ { "path": "PROVENANCE.md", "kind": "provenance", - "sha256": "1c1a19ac4d8765d90644a8a4a45013620b8204b37bf6967393778fbbe5e531b4" + "sha256": "b72b83f60af9e612a1f9472989766e5cc9209c8bf6da6f3d1e3d251a378d3666" }, { "path": "generated/agent-registry-CxpAF3nI.js", @@ -62,12 +62,12 @@ { "path": "generated/runtime.d.ts", "kind": "generated", - "sha256": "45d3d96fafbcd677e20b11d4dc38b23f37ca9237360f47858e7f468cd597d04f" + "sha256": "8ae4d54137e32f946978e1d3f0335a41c05f2eb8e863b2cb1ee495def8081cd2" }, { "path": "generated/runtime.js", "kind": "generated", - "sha256": "ca6a3124680ef66b05538d91d52602bbd338ab0d8e36f483102fe2961b6d9c78" + "sha256": "e23aa856836d23e139219ffee5771e9995f3cbdde819c20e0cbfe7fad71a48e2" }, { "path": "generated/session-options-D9KL7-d8.d.ts", diff --git a/packages/acp/vendor/acpx/PROVENANCE.md b/packages/acp/vendor/acpx/PROVENANCE.md index 869ed79b5..56e580d49 100644 --- a/packages/acp/vendor/acpx/PROVENANCE.md +++ b/packages/acp/vendor/acpx/PROVENANCE.md @@ -110,6 +110,8 @@ an explicit empty details string and excludes arbitrary raw `acp.data`. The uniquely named `XMD prompt diagnostic:` seam bounds this correction in Tier AV. Real adapter-child failures pass through this runtime into production Prompt publication and cold REPL Journal queries of `promptError`. +The same projection is available through the runtime entry for classified +resume refusals before a runtime turn exists or writes its prompt (#1388). Other arbitrary adapter data remains unavailable through this selected result. This correction establishes no cause for the historical `Internal error` incident, diff --git a/packages/acp/vendor/acpx/generated/runtime.d.ts b/packages/acp/vendor/acpx/generated/runtime.d.ts index b335af68b..5973581ca 100644 --- a/packages/acp/vendor/acpx/generated/runtime.d.ts +++ b/packages/acp/vendor/acpx/generated/runtime.d.ts @@ -322,6 +322,8 @@ type AcpRuntimeTurnResultError = { detailCode?: string; retryable?: boolean; }; +/** XMD prompt diagnostic: bounded runtime failure projection, also used before a turn exists. */ +export declare function projectRuntimeError(error: unknown): AcpRuntimeTurnResultError; /** XMD prompt usage: quota counters, under the adapter's own names. */ type AcpRuntimeQuotaTokens = { totalTokens?: number; diff --git a/packages/acp/vendor/acpx/generated/runtime.js b/packages/acp/vendor/acpx/generated/runtime.js index c6774a03b..328959508 100644 --- a/packages/acp/vendor/acpx/generated/runtime.js +++ b/packages/acp/vendor/acpx/generated/runtime.js @@ -2114,21 +2114,7 @@ var AcpRuntimeManager = class { failRuntimeTurn(task, error) { task.promptStarted.reject(error); task.sessionReady.reject(error); - const normalized = normalizeOutputError(error, { origin: "runtime" }); - // XMD prompt diagnostic: retain the extracted protocol facts, never raw data. - const acp = normalized.acp; - const details = acp?.data !== null && typeof acp?.data === "object" ? acp.data.details : void 0; - return { - status: "failed", - error: { - message: normalized.message, - ...normalized.origin !== void 0 ? { origin: normalized.origin } : {}, - ...acp ? { acp: { code: acp.code, message: acp.message, ...typeof details === "string" ? { details } : {} } } : {}, - ...normalized.code ? { code: normalized.code } : {}, - ...normalized.detailCode ? { detailCode: normalized.detailCode } : {}, - ...normalized.retryable !== void 0 ? { retryable: normalized.retryable } : {} - } - }; + return { status: "failed", error: projectRuntimeError(error) }; // XMD prompt diagnostic: } async finalizeRuntimeTurn(task, turn) { task.state.turnActive = false; @@ -3085,4 +3071,20 @@ function createAcpRuntime(options) { function createRuntimeStore(options) { return createFileSessionStore(options); } +// XMD prompt diagnostic: reuse the bounded turn projection for a refused ensure. +function projectRuntimeError(error) { + const normalized = normalizeOutputError(error, { origin: "runtime" }); + const acp = normalized.acp; + const details = acp?.data !== null && typeof acp?.data === "object" ? acp.data.details : void 0; + return { + message: normalized.message, + ...normalized.origin !== void 0 ? { origin: normalized.origin } : {}, + // XMD prompt diagnostic: only protocol code, message and data.details. + ...acp ? { acp: { code: acp.code, message: acp.message, ...typeof details === "string" ? { details } : {} } } : {}, + ...normalized.code ? { code: normalized.code } : {}, + ...normalized.detailCode ? { detailCode: normalized.detailCode } : {}, + ...normalized.retryable !== void 0 ? { retryable: normalized.retryable } : {} + }; +} +export { projectRuntimeError }; // XMD prompt diagnostic: export { ACPX_BACKEND_ID, AcpRuntimeError, AcpxRuntime, DEFAULT_AGENT_NAME, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE, REQUESTED_MODEL_UNSUPPORTED_REASONS, RequestedModelUnsupportedError, SharedAcpRuntime, createAcpRuntime, createAgentRegistry, createFileSessionStore, createRuntimeStore, createSharedAcpRuntime, decodeAcpxRuntimeHandleState, encodeAcpxRuntimeHandleState, inspectAgentModels, isAcpRuntimeError, isRequestedModelUnsupportedError }; diff --git a/packages/agent/src/conversation.ts b/packages/agent/src/conversation.ts index dac6999b7..32f7aaed2 100644 --- a/packages/agent/src/conversation.ts +++ b/packages/agent/src/conversation.ts @@ -109,8 +109,9 @@ import type { SessionConfiguration, } from "./agent-api.ts"; import { AgentInternal } from "./internal.ts"; -import { runPrompt } from "./function-components.ts"; +import { retainPromptFailure, runPrompt } from "./function-components.ts"; import type { Carried, DirectPromptTurn } from "./function-components.ts"; +import { readPromptDiagnostic, SESSION_RESUME_REQUIRED_ERROR } from "./errors.ts"; import { AGENT_PROMPT, parsePromptRecord, @@ -1119,6 +1120,7 @@ function conversationTurn( // than being journaled as a failed turn — and it is also the agent both // of this turn's operations are given. const agent = yield* provider.agent(request.agent); + let eagerRefusal: Error | undefined; yield* scoped(function* (): Operation { // The requirement travels inside the issuance, where the provider // reaches it only through the setup the coordinator delivers. A @@ -1134,6 +1136,16 @@ function conversationTurn( // ends the one use: what this says is which Session this request's // own setup finished with, and only the opener can ask. settled = issuance.completed(); + } catch (error) { + if ( + error instanceof Error && + error.name === SESSION_RESUME_REQUIRED_ERROR && + readPromptDiagnostic(error)?.stage === "held-session-ensure" + ) { + eagerRefusal = error; + return; + } + throw error; } finally { issuance.close(); } @@ -1234,6 +1246,24 @@ function conversationTurn( const failure = promptFailureFromRecord(record); job.answer.resolve(failure === undefined ? Ok(record.text) : Err(failure)); }); + if (eagerRefusal !== undefined) { + const refusal = eagerRefusal; + const sequence = yield* AgentInternal.operations.nextPromptSequence(); + const record = yield* persistPrompt( + { name: turnName(order), input: job.input }, + function* (): Operation { + return { + sequence, + agent, + sessionKey: "", + status: "failed", + text: "", + error: yield* retainPromptFailure(refusal), + }; + }, + ); + job.answer.resolve(Err(promptFailureFromRecord(record) ?? refusal)); + } } catch (error) { // A refusal before the turn started — an unavailable agent, an identity // the provider would not reattach, a conversation it put under settings @@ -1484,17 +1514,22 @@ function* openable(request: AgentConversationRequest): Operation; operation: z.ZodLiteral<"session/prompt">; - stage: z.ZodLiteral<"runtime-turn">; + stage: z.ZodEnum<{ + "runtime-turn": "runtime-turn"; + "prompt-ensure": "prompt-ensure"; + "held-session-ensure": "held-session-ensure"; + }>; requestId: z.ZodOptional; code: z.ZodOptional; detailCode: z.ZodOptional; @@ -36,7 +40,7 @@ const Diagnostic: z.ZodObject< .object({ provider: z.literal("acp"), operation: z.literal("session/prompt"), - stage: z.literal("runtime-turn"), + stage: z.enum(["runtime-turn", "prompt-ensure", "held-session-ensure"]), requestId: z.string().optional(), code: z.string().min(1).optional(), detailCode: z.string().min(1).optional(), @@ -55,13 +59,21 @@ const Diagnostic: z.ZodObject< type PromptDiagnostic = z.infer; +export const SESSION_RESUME_REQUIRED_ERROR = "SessionResumeRequiredError"; + export function readPromptDiagnostic(error: unknown): PromptDiagnostic | undefined { return isRecord(error) ? parsePromptDiagnostic(error[PROMPT_DIAGNOSTIC]) : undefined; } function parsePromptDiagnostic(value: unknown): PromptDiagnostic | undefined { const parsed = Diagnostic.safeParse(value); - return parsed.success ? parsed.data : undefined; + if ( + !parsed.success || + (parsed.data.stage !== "runtime-turn" && parsed.data.requestId !== undefined) + ) { + return undefined; + } + return parsed.data; } export class AgentPromptError extends Error { @@ -108,7 +120,7 @@ export function serializePromptFailure( if (error.name !== "Error") { serialized.name = error.name; } - if (error.cause instanceof Error) { + if (error.name !== SESSION_RESUME_REQUIRED_ERROR && error.cause instanceof Error) { serialized.cause = error.cause.message; } if (diagnostic !== undefined) { @@ -140,7 +152,14 @@ export function parsePromptFailure(value: unknown): SerializedPromptFailure | un } if (Object.hasOwn(value, "diagnostic")) { const diagnostic = parsePromptDiagnostic(value.diagnostic); - if (diagnostic === undefined) { + if ( + diagnostic === undefined || + (diagnostic.stage !== "runtime-turn" && + (name !== SESSION_RESUME_REQUIRED_ERROR || + Object.keys(value).some( + (key) => key !== "name" && key !== "message" && key !== "diagnostic", + ))) + ) { return undefined; } parsed.diagnostic = diagnostic; diff --git a/packages/agent/src/function-components.ts b/packages/agent/src/function-components.ts index d49ce32cc..6e0a3277e 100644 --- a/packages/agent/src/function-components.ts +++ b/packages/agent/src/function-components.ts @@ -72,7 +72,11 @@ import type { import type { LaunchIdentity } from "./launch-journal.ts"; import { installApproveAll, installAskPermission } from "./permission.ts"; import { AgentInternal, formatLocation } from "./internal.ts"; -import { readPromptDiagnostic, serializePromptFailure } from "./errors.ts"; +import { + readPromptDiagnostic, + serializePromptFailure, + SESSION_RESUME_REQUIRED_ERROR, +} from "./errors.ts"; import type { SerializedPromptFailure } from "./errors.ts"; import { auditedPromptStream, @@ -788,6 +792,10 @@ function* selectPromptDiagnostic(error: Error): Operation { + return serializePromptFailure(error, yield* selectPromptDiagnostic(error)); +} + /** * Consume one provider turn into the record the journal holds. * @@ -940,10 +952,7 @@ export function* runPrompt( result.stopReason = event.stopReason; } if (event.error) { - result.failure = serializePromptFailure( - event.error, - yield* selectPromptDiagnostic(event.error), - ); + result.failure = yield* retainPromptFailure(event.error); } const checkpoint = checkpointOf(event); if (checkpoint !== undefined) { @@ -1008,7 +1017,10 @@ export function* runPrompt( throw error; } consumed.status = "failed"; - consumed.failure = serializePromptFailure(error); + consumed.failure = + error instanceof Error && error.name === SESSION_RESUME_REQUIRED_ERROR + ? yield* retainPromptFailure(error) + : serializePromptFailure(error); } const status = consumed.status ?? "failed"; diff --git a/packages/agent/src/journal.ts b/packages/agent/src/journal.ts index 72b8c0e08..6e38938b2 100644 --- a/packages/agent/src/journal.ts +++ b/packages/agent/src/journal.ts @@ -75,7 +75,7 @@ import type { import { readConfiguration, serializeConfiguration } from "./configuration-record.ts"; import { readCheckpoint } from "./checkpoint.ts"; import type { AgentPromptCheckpoint } from "./checkpoint.ts"; -import { AgentPromptError, parsePromptFailure } from "./errors.ts"; +import { AgentPromptError, parsePromptFailure, SESSION_RESUME_REQUIRED_ERROR } from "./errors.ts"; import type { SerializedPromptFailure } from "./errors.ts"; import { AgentInternal } from "./internal.ts"; import { HostObservationFailure } from "./publication.ts"; @@ -708,7 +708,11 @@ export function promptFailureFromRecord(record: PromptRecord): AgentPromptError if (record.error?.diagnostic !== undefined) { options.diagnostic = record.error.diagnostic; } - return new AgentPromptError(message, options); + const failure = new AgentPromptError(message, options); + if (record.error?.name === SESSION_RESUME_REQUIRED_ERROR && record.error.cause === undefined) { + failure.name = SESSION_RESUME_REQUIRED_ERROR; + } + return failure; } function serializePromptRecord(record: PromptRecord): Json { @@ -930,6 +934,23 @@ export function parsePromptRecord(value: unknown): PromptRecord | undefined { if (!parsed) { return undefined; } + if ( + parsed.diagnostic?.stage === "held-session-ensure" && + (status !== "failed" || + sessionKey !== "" || + text !== "" || + Object.keys(value).some( + (key) => + key !== "sequence" && + key !== "agent" && + key !== "sessionKey" && + key !== "status" && + key !== "text" && + key !== "error", + )) + ) { + return undefined; + } record.error = parsed; } if (permissions !== undefined) { diff --git a/packages/agent/tests/agent-conversation.test.ts b/packages/agent/tests/agent-conversation.test.ts index da315b5a7..cce1481db 100644 --- a/packages/agent/tests/agent-conversation.test.ts +++ b/packages/agent/tests/agent-conversation.test.ts @@ -118,6 +118,7 @@ interface Traffic { } interface StubOptions { + readonly refuseSession?: () => Error | undefined; readonly freshSession?: boolean; /** Throw from the provider's own final `next()`, after its terminal event. */ readonly failsAfterTerminal?: boolean; @@ -283,6 +284,10 @@ function stub(traffic: Traffic, options: StubOptions = {}): ExecutionInstallatio if (!authorized.ok) { throw authorized.error; } + const refusal = options.refuseSession?.(); + if (refusal !== undefined) { + throw refusal; + } const session: Session = { sessionKey: options.places?.shift() ?? `stub:${routed.name ?? "default"}`, cwd: "/stub", @@ -3104,6 +3109,141 @@ describe("used held conversation continuation", () => { }); }); +describe("1388 — resume retention: held setup and recovery readers", () => { + const header = { provider: "acp", operation: "session/prompt", stage: "held-session-ensure" }; + const diagnostic = { ...header, acp: { code: -32041, details: "synthetic adapter detail" } }; + const message = "The retained session could not be resumed."; + const errorName = "SessionResumeRequiredError"; + + it("retains the fixed eager stage after an authenticated screening failure", function* () { + const history = new InMemoryStream(); + const traffic = fresh(); + let refuse = false; + const result = yield* withConversation( + history, + stub(traffic, { + asserts: () => "native-1388", + refuseSession() { + if (refuse) { + const error = new Error(message, { cause: new Error("unselected error envelope") }); + error.name = errorName; + return Object.assign(error, { "executablemd.agent.prompt-diagnostic": diagnostic }); + } + }, + }), + function* (chat) { + expect((yield* chat.prompt("establish")).ok).toBe(true); + refuse = true; + const failed = yield* chat.prompt("eager attempt"); + if (failed.ok) { + throw new Error("The refused session ran"); + } + expect(failed.error.name).toBe(errorName); + expect(failed.error.message).toBe(message); + expect(failed.error.cause).toBe(undefined); + expect(Reflect.get(failed.error, "executablemd.agent.prompt-diagnostic")).toEqual(header); + expect(traffic.prompts.map((one) => one.content)).toEqual(["establish"]); + refuse = false; + expect((yield* chat.prompt("fresh request")).ok).toBe(true); + }, + "chat-1", + [ + { + *install() { + yield* useSecretScannerFactory(() => ({ + // deno-lint-ignore require-yield + *scan(content) { + if (content === JSON.stringify(diagnostic)) { + throw new Error("synthetic diagnostic scan failure"); + } + return []; + }, + })); + }, + }, + ], + ); + expect(result.ok).toBe(true); + const retained = history.snapshot(); + expect(turnNames(retained)).toEqual(["turn:1", "turn:2", "turn:3"]); + const eager = record(retained, "turn:2"); + expect(eager.error).toEqual({ message, name: errorName, diagnostic: header }); + expect(eager.sequence).not.toBe(record(retained, "turn:1").sequence); + expect(eager.sequence).not.toBe(record(retained, "turn:3").sequence); + expect(traffic.facts.at(-1)).toEqual(traffic.facts.at(-2)); + const idle = fresh(); + expect((yield* withConversation(history, stub(idle), function* () {})).ok).toBe(true); + expect(idle.sessionAgents).toEqual([]); + expect(idle.prompts).toEqual([]); + expect(history.snapshot()).toEqual(retained); + + const invalid = new InMemoryStream(); + for (const event of retained) { + yield* invalid.append( + event.type === "yield" && event.description.name === "turn:2" + ? { + ...event, + result: { + status: "ok", + value: { + sequence: 1, + agent: AGENT, + sessionKey: "old", + status: "failed", + text: "", + error: { message, name: errorName, diagnostic: header }, + }, + }, + } + : event, + ); + } + const invalidBefore = invalid.snapshot(); + const opened = yield* withConversation(invalid, stub(idle), function* () { + throw new Error("Unreadable history opened"); + }); + expect(!opened.ok && opened.error.message).toContain('retained turn "turn:2" cannot be read'); + expect(idle.sessionAgents).toEqual([]); + expect(invalid.snapshot()).toEqual(invalidBefore); + }); + + it("refuses unsupported stages, ensure request IDs and inconsistent eager outcomes", function* () { + const base = { sequence: 1, agent: AGENT, sessionKey: "", status: "failed", text: "" }; + const failure = { message, name: errorName, diagnostic }; + expect(parsePromptRecord({ ...base, error: failure })?.error).toEqual(failure); + for (const fields of [ + { stage: "unsupported" }, + { stage: "prompt-ensure", requestId: "invented" }, + { requestId: "invented" }, + { extra: "unknown" }, + ]) { + expect( + parsePromptRecord({ + ...base, + error: { ...failure, diagnostic: { ...diagnostic, ...fields } }, + }), + ).toBe(undefined); + } + for (const fields of [ + { sessionKey: "previous" }, + { status: "cancelled" }, + { text: "not sent" }, + { agentSessionId: "previous" }, + { stopReason: "end_turn" }, + { withheld: true }, + { raised: true }, + { configuration: {} }, + { permissions: [] }, + { unexpected: true }, + ]) { + expect(parsePromptRecord({ ...base, ...fields, error: failure })).toBe(undefined); + } + expect(parsePromptRecord({ ...base, error: { ...failure, cause: "raw cause" } })).toBe( + undefined, + ); + }); +}); + /** * One contributed content layer, installed the way a held conversation's host * installs one: ordinary `Agent.prompt` middleware at the default `max`. diff --git a/packages/cli/src/repl/sidekick/model.ts b/packages/cli/src/repl/sidekick/model.ts index 90edb5d6e..4c1d5e438 100644 --- a/packages/cli/src/repl/sidekick/model.ts +++ b/packages/cli/src/repl/sidekick/model.ts @@ -575,6 +575,7 @@ export interface SidekickRequest { * whether this request was the one that ran it. */ readonly turn: number | undefined; + readonly resumeRefused?: true; } /** @@ -622,6 +623,13 @@ export function retryable( const request = known.requests.find( (one) => one.conversation === conversation && one.kind === "message" && one.message === message, ); + if (request?.resumeRefused === true) { + return Err( + new SidekickProjectionError( + "This conversation could not be resumed and is not offered for Retry.", + ), + ); + } if ( known.recoveries.some( (one) => @@ -706,6 +714,7 @@ export function requestsFromHistory( message: number | undefined; turn: number | undefined; outcomes: number; + resumeRefused?: true; }[] = []; /** The request whose records are still being read, per conversation. */ const current = new Map(); @@ -754,6 +763,18 @@ export function requestsFromHistory( // nothing is invented to. continue; } + const outcome = parsed.value.result; + if ( + outcome.status === "ok" && + parsePromptRecord(outcome.value)?.error?.diagnostic?.stage === "held-session-ensure" + ) { + // Automatic feedback writes its own request in begin, which this attempt + // never reached. Only an explicit, still-open message can own it. + if (holding.kind !== "message" || holding.outcomes !== 0) { + continue; + } + holding.resumeRefused = true; + } holding.outcomes += 1; if (holding.outcomes > 1) { return Err( @@ -775,6 +796,7 @@ export function requestsFromHistory( at: held.at, message: held.message, turn: held.turn, + ...(held.resumeRefused === true ? { resumeRefused: true as const } : {}), }), ), ), diff --git a/packages/cli/src/repl/sidekick/owner.ts b/packages/cli/src/repl/sidekick/owner.ts index a4e39c74a..3be526537 100644 --- a/packages/cli/src/repl/sidekick/owner.ts +++ b/packages/cli/src/repl/sidekick/owner.ts @@ -2865,7 +2865,7 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation { @@ -3285,6 +3286,7 @@ function* turnForRequest( status: saved.status, text: saved.text, withheld: saved.withheld === true, + resumeRefused: held.resumeRefused === true, }; } } diff --git a/packages/cli/tests/repl-sidekick-recovery.test.ts b/packages/cli/tests/repl-sidekick-recovery.test.ts index 6c6eac929..8a8246f21 100644 --- a/packages/cli/tests/repl-sidekick-recovery.test.ts +++ b/packages/cli/tests/repl-sidekick-recovery.test.ts @@ -1,3 +1,4 @@ +import type { PromptRecord } from "@executablemd/agent/host"; import { PLACEMENT } from "../src/repl/entry-placement.ts"; import { useSidekickOwner } from "../src/repl/sidekick/owner.ts"; import { rootReads } from "../src/repl/sidekick/requests.ts"; @@ -92,6 +93,7 @@ import { projectHistory, projectSidekick, recoveryRequired, + retryable, REPLY_WITHHELD, } from "../src/repl/sidekick/model.ts"; import { sidekickChatRows } from "../src/repl/program.ts"; @@ -176,7 +178,7 @@ function turn( /** The provider conversation this record names, which may be none. */ sessionKey?: string; stopReason?: string; - error?: { message: string }; + error?: PromptRecord["error"]; } = {}, ): SidekickRecord { const event: DurableEvent = { @@ -215,6 +217,78 @@ function turn( }; } +describe("1388 — resume retention: exact request ownership", () => { + const message: SidekickRecord = { + kind: "message", + id: "message-1", + origin: { kind: "ui" }, + conversation: CHAT, + turn: 1, + revision: 1, + text: "initial request", + }; + const resumeMessage = "The retained session could not be resumed."; + const prefix = [...opened(), message, turn(1, "answer"), reply(1, "answer")]; + + function eagerFailure(): SidekickRecord { + return turn(2, "", { + input: "new request and prior results", + status: "failed", + sessionKey: "", + error: { + message: resumeMessage, + name: "SessionResumeRequiredError", + diagnostic: { provider: "acp", operation: "session/prompt", stage: "held-session-ensure" }, + }, + }); + } + + it("keeps automatic feedback refused before begin as a standalone attempt", function* () { + const reading = project([...prefix, eagerFailure()]); + expect(reading.requests).toHaveLength(1); + expect(reading.requests[0]?.turn).toBe(1); + expect(reading.turns.at(-1)).toMatchObject({ + turn: 2, + asked: undefined, + sessionKey: undefined, + }); + expect(reading.chat.at(-1)).toMatchObject({ + kind: "incomplete", + turn: 2, + failure: resumeMessage, + }); + expect(reading.feedback).toEqual([]); + expect(reading.delivered).toEqual([]); + expect(reading.unestablished).toEqual([]); + expect(projectSidekick([...prefix, turn(2, "second outcome")]).ok).toBe(false); + }); + + it("associates the eager attempt with its own message carrying feedback and refuses Retry", function* () { + const next = { ...message, id: "message-2", turn: 2, text: "new request" }; + const feedback: SidekickRecord = { + kind: "feedback", + conversation: CHAT, + response: "r1", + turn: null, + text: "new request and prior results", + }; + const reading = project([...prefix, next, feedback, eagerFailure()]); + expect(reading.requests.map((request) => [request.message, request.turn])).toEqual([ + [1, 1], + [2, 2], + ]); + expect(reading.turns.at(-1)).toMatchObject({ asked: "person", title: "new request" }); + expect(reading.delivered).toEqual([]); + expect(retryable(reading, CHAT, 2).ok).toBe(false); + const ordinary = project([ + ...prefix, + next, + turn(2, "", { status: "failed", error: { message: "ordinary failure" } }), + ]); + expect(retryable(ordinary, CHAT, 2)).toEqual(Ok(next.text)); + }); +}); + function reply(order: number, text: string): SidekickRecord { return { kind: "response", @@ -4844,7 +4918,7 @@ describe("1183 — the exact live feedback request is the only exception", () => }); }); -describe("1269 — mounted retained recovery corrections", () => { +describe("1388 — resume retention and 1269 — mounted retained recovery corrections", () => { const savedText = "Continue the exact saved instruction."; const oldText = "Original chat remains readable."; const entryText = "An established entry remains readable."; @@ -5010,6 +5084,52 @@ describe("1269 — mounted retained recovery corrections", () => { expect(held.host.fake.prompts).toHaveLength(2); }); + it("keeps Start new chat and no Retry after a classified eager original refusal is saved", function* () { + const held = yield* retained(); + held.host.fake.refuseSessionResume(held.session, "Release the active writer."); + const before = yield* readSidekickRecords(held.chat.location.sidekick); + yield* scoped(function* () { + const page = yield* useReplPage({ + host: { ...held.host, profile: held.profile }, + location: held.location, + }); + yield* sendMessage(page, savedText); + yield* page.until( + "the saved fallback and new chat action", + (one) => one.shows("could not be resumed") && one.shows("[Start new chat]"), + ); + expect(page.screen().shows("Release the active writer.")).toBe(false); + expect(page.screen().shows("[Retry]")).toBe(false); + page.repl.terminal.end(); + yield* awaited("the REPL joining", () => page.repl.outcome() !== undefined); + }); + const after = yield* readSidekickRecords(held.chat.location.sidekick); + const reading = project(after); + expect(held.host.fake.prompts).toHaveLength(2); + expect(reading.active).toBe(held.conversation); + expect(reading.turns.at(-1)).toMatchObject({ + status: "failed", + sessionKey: undefined, + asked: "person", + title: savedText, + }); + expect(after.slice(before.length).filter((record) => record.kind === "feedback")).toEqual([]); + expect(JSON.stringify(after)).not.toContain("unrelated synthetic RPC payload"); + const attempt = reading.requests.at(-1); + expect(attempt?.resumeRefused).toBe(true); + if (attempt?.message === undefined) { + throw new Error("The eager attempt has no durable message"); + } + expect(retryable(reading, held.conversation, attempt.message).ok).toBe(false); + const reopened = yield* useReplPage({ + host: { ...held.host, profile: held.profile }, + location: held.location, + }); + yield* reopened.until("the retained local failure", (one) => one.shows("could not be resumed")); + expect(reopened.screen().shows("[Retry]")).toBe(false); + expect(yield* readSidekickRecords(held.chat.location.sidekick)).toEqual(after); + }); + for (const mode of ["prepared", "missing load"] as const) { it(`requires explicit local fallback after ${mode}`, function* () { const held = yield* retained(); diff --git a/packages/cli/tests/support/fake-acp.ts b/packages/cli/tests/support/fake-acp.ts index 454ef9726..661fe4e0c 100644 --- a/packages/cli/tests/support/fake-acp.ts +++ b/packages/cli/tests/support/fake-acp.ts @@ -299,6 +299,7 @@ export interface FakeAcp { */ unavailable(agent: string, reason: Error): void; missingSession(sessionKey: string): void; + refuseSessionResume(sessionKey: string, details?: string): void; /** * Report this native conversation identity instead of a derived one. * @@ -445,6 +446,7 @@ export function createFakeAcp(): FakeAcp { /** Agents whose session this runtime refuses to establish, by reason. */ const refusals = new Map(); const missingSessions = new Set(); + const refusedResumes = new Map(); let advertised: ScriptedConfiguration | undefined; /** The native identity every session of this runtime reports, when scripted. */ let asserted: string | undefined; @@ -619,6 +621,18 @@ export function createFakeAcp(): FakeAcp { missingSession(sessionKey) { missingSessions.add(sessionKey); }, + refuseSessionResume(sessionKey, details) { + const rpc = Object.assign(new Error("Internal error"), { + code: -32041, + data: { details, unrelated: "unrelated synthetic RPC payload" }, + }); + refusedResumes.set( + sessionKey, + Object.assign(new Error("Raw load failure", { cause: rpc }), { + detailCode: "SESSION_RESUME_REQUIRED", + }), + ); + }, identity(value) { asserted = value; }, @@ -749,6 +763,11 @@ export function createFakeAcp(): FakeAcp { }, ensureSession(input) { ensured.push(input); + const resumeRefusal = refusedResumes.get(input.sessionKey); + if (resumeRefusal !== undefined) { + refusedResumes.delete(input.sessionKey); + return Promise.reject(resumeRefusal); + } if (missingSessions.has(input.sessionKey)) { return Promise.reject(new Error("The exact retained backend session is missing.")); } diff --git a/specs/acp-client-spec.md b/specs/acp-client-spec.md index 1927fd018..8af1d60b3 100644 --- a/specs/acp-client-spec.md +++ b/specs/acp-client-spec.md @@ -1003,7 +1003,8 @@ anything opens. Resuming it would re-send a prompt the provider may already have accepted, and writing a terminal for it would make an unfinished turn look complete; reconciling it belongs to the host, with the provider's own account of that turn. Because the refusal happens before the execution exists, it -appends nothing to the history it refused. +appends nothing to the history it refused. A canonical Prompt value that fails +validation also refuses opening at this boundary, before provider work. The history is bound to its conversation by a durable record written on the first opening and replayed afterwards. A history established for another `id` @@ -1170,8 +1171,8 @@ record: | Field | Meaning | | --- | --- | -| `provider`, `operation`, `stage` | Exactly `acp`, `session/prompt`, `runtime-turn`: receipt of a failed runtime turn. | -| `requestId` | The actual runtime turn's request ID, when supplied; it need not be the wire JSON-RPC ID. | +| `provider`, `operation`, `stage` | The fixed provider and operation are `acp` and `session/prompt`. The stage is `runtime-turn`, `prompt-ensure` or `held-session-ensure`. The operation identifies the attempted Prompt and grants no wire receipt. | +| `requestId` | The actual turn's request ID, when supplied on `runtime-turn`. The ensure stages forbid this field. | | `code`, `detailCode` | Supplied nonempty runtime classifications. `RUNTIME` is the normalizer's fallback, not a backend diagnosis. | | `retryable` | A supplied boolean hint, including false; it grants no resend. | | `origin` | The supplied normalization layer: `cli`, `runtime`, `queue` or `acp`, not a proven root cause. | @@ -1181,7 +1182,23 @@ Conversation correlation stays in the existing `agent`, `sessionKey` and `agentSessionId` fields. No raw protocol payload, prompt, environment or unrelated history is added. A plain Error has no diagnostic; stream exceptions, cancellation and host permission refusal keep their existing paths. A -message-only upstream failure remains undiagnosed. Diagnostics establish +message-only upstream failure remains undiagnosed. An ordinary same-session +load or resume refusal retains the local fallback and the name +`SessionResumeRequiredError` without a raw upstream cause. ACP selects the +same bounded facts when the subscribed Prompt's ensure fails before a runtime +turn (`prompt-ensure`) or the runtime turn refuses before writing the prompt +(`runtime-turn`). Identity confirmation, ownership, configuration, permission +and cancellation keep their existing outcomes. + +When a held conversation's eager ensure refuses with that classification, +Agent waits for successful unwind and publishes one canonical failed Prompt +using the job's attempted input, resolved agent and next ordinal. This +`held-session-ensure` stage has empty text and an empty session key and carries +no native assertion, configuration, stop reason, permissions, checkpoint, +usage, raised marker or withheld reply. The attempt never begins the canonical +Prompt terminal, composes the input or emits `started`. The caller receives the +failure reconstructed from the saved value. Failure to publish retains its +existing durability precedence. Diagnostics establish neither backend acceptance nor a successful retry and never enter the agent's reply text. @@ -1191,13 +1208,18 @@ retained JSON representation, omits offending fields, then screens the complete selected diagnostic. Unsafe secondary text does not discard a safe protocol code. If policy authentication or screening fails, the whole optional diagnostic is absent; the original message, name, cause, status and partial -reply stay unchanged. Cancellation remains cancellation. Explicit host-disabled +reply stay unchanged. An eager held refusal instead keeps the three fixed +`provider`, `operation` and `stage` values and drops every optional fact. +Cancellation remains cancellation. Explicit host-disabled detection is respected. The complete event still crosses the unchanged rejection gate: upstream selection never repairs an event rejected by that gate. The current reader validates a present diagnostic completely and refuses -malformed or unknown members. An absent diagnostic preserves +malformed or unknown members, including a held ensure failure with +inconsistent surrounding Prompt fields. Deploy the reader and writer together. +Older readers refuse the new stages. This internal format has no downgrade +reader. An absent diagnostic preserves message/name/cause-only records without a migration or rewrite. Reconstructed thrown and aggregated Prompt failures keep the selected diagnostic under `executablemd.agent.prompt-diagnostic`. The existing REPL Journal query exposes @@ -2030,7 +2052,8 @@ its caller supplied, from Prompt `timeout` or the enclosing AgentProvider terminal in `checkpoint.ts` and `events.ts`. Cancellation and failure never acquire one, and no local runtime metadata patch remains. The pinned in-process runtime preserves normalized origin and selected protocol - code/message/details at `failRuntimeTurn`; arbitrary `acp.data` remains + code/message/details in the runtime failure projection used for terminal and + pre-prompt resume failures. Arbitrary `acp.data` remains excluded. The shared/queue result projection is unchanged. The generated correction and its matching declaration are recorded in vendor provenance and offline Tier AV. - **Serialization.** Prompts for one session run FIFO on that session's queue; different sessions run concurrently. A subscription enters that queue before diff --git a/specs/repl-spec.md b/specs/repl-spec.md index bc8ad5339..f3db3930b 100644 --- a/specs/repl-spec.md +++ b/specs/repl-spec.md @@ -1060,6 +1060,14 @@ refuses a selector supported only by an observation the former owner lost. ## Reading a previous chat +A retained eager resume refusal appears as one incomplete attempt. An +explicit message already has a durable request, including a message carrying +recovered feedback, so that request owns the attempt. Automatic feedback +records its request at canonical begin. A refusal before that boundary has +no established request and appears beside the preceding attempt on its own. +It creates no feedback intent or acknowledgement. A second ordinary outcome +for the same request still refuses the history. + Activating a Sidekick turn opens the chat that contains it and brings that turn into view. It sets `view=sidekick`, `right=sidekick` and that chat's own identifier, and preserves the conversation filter, the saved surface, the @@ -3158,6 +3166,12 @@ attach no host invocation observer. ## Who owns what +When eager ensure refuses to continue the original conversation, the failed +result still offers **Start new chat** after the attempt is saved. Retry +remains unavailable for that request while live and after reopening. A +subscription failure that reached canonical begin keeps its existing +recovery behavior. The entry Journal reads the canonical saved failure. + The host acquires one protected-input installation before each producing entry’s providers. It keeps that owner until those providers join, safely seals each independent output channel, and then disposes live input and pending text. Output received after disposal refuses instead of falling back to raw forwarding. Only the REPL terminal renderer writes presentation bytes while the interface From bdaa7c7a34cd9b3277762cdec8b282ed5777dbd7 Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Tue, 17 Nov 2026 11:36:54 -0500 Subject: [PATCH 2/3] Avoid mutating saved Prompt records in Bun tests --- packages/acp/tests/released-runtime.test.ts | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/packages/acp/tests/released-runtime.test.ts b/packages/acp/tests/released-runtime.test.ts index 11ed991a9..4cef788f4 100644 --- a/packages/acp/tests/released-runtime.test.ts +++ b/packages/acp/tests/released-runtime.test.ts @@ -1288,26 +1288,20 @@ describe( const recorded = refused.history.find( (event) => event.type === "yield" && event.description.type === "agent_prompt", ); - expect(recorded).toMatchObject({ - result: { - status: "ok", - value: { - status: "failed", - text: "", - error: { message: expect.stringContaining("Name a different ") }, - }, - }, - }); if (recorded?.type !== "yield" || recorded.result.status !== "ok") { throw new Error("No canonical refusal"); } - const saved = parsePromptRecord(recorded.result.value)?.error; - if (saved === undefined) { + const prompt = parsePromptRecord(recorded.result.value); + if (prompt?.error === undefined) { throw new Error("No saved failure"); } + const saved = prompt.error; + expect(prompt.status).toBe("failed"); + expect(prompt.text).toBe(""); + expect(saved.message).toContain("Name a different "); const sensitive = detail?.startsWith("ghp_") === true; expect(saved).toEqual({ - message: expect.stringContaining("Name a different "), + message: saved.message, name: "SessionResumeRequiredError", diagnostic: { provider: "acp", From 4c32dd3482fe08fbdb8f1515397b2c0761ff923f Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Tue, 17 Nov 2026 13:00:09 -0500 Subject: [PATCH 3/3] Keep pre-prompt resume diagnostic mapping in XMD --- packages/acp/src/provider.ts | 49 +++++++++++++++++-- packages/acp/tests/host-conversation.test.ts | 2 +- packages/acp/tests/released-runtime.test.ts | 2 +- packages/acp/vendor/acpx/MANIFEST.json | 6 +-- packages/acp/vendor/acpx/PROVENANCE.md | 2 - .../acp/vendor/acpx/generated/runtime.d.ts | 2 - packages/acp/vendor/acpx/generated/runtime.js | 32 ++++++------ .../agent/tests/agent-conversation.test.ts | 4 +- .../cli/tests/repl-sidekick-recovery.test.ts | 4 +- specs/acp-client-spec.md | 4 +- 10 files changed, 71 insertions(+), 36 deletions(-) diff --git a/packages/acp/src/provider.ts b/packages/acp/src/provider.ts index 0be0de12c..f9df5c7c9 100644 --- a/packages/acp/src/provider.ts +++ b/packages/acp/src/provider.ts @@ -102,7 +102,6 @@ import { createAcpRuntime, createAgentRegistry, createRuntimeStore, - projectRuntimeError, resolveAgentCommand, } from "./acpx-runtime.ts"; import type { @@ -115,6 +114,7 @@ import type { AcpRuntimeOptions, AcpRuntimeTurn, AcpRuntimeTurnResult, + AcpRuntimeTurnResultError, AcpRuntimeUsageBreakdown, AcpRuntimeUsageCost, AcpSessionRecord, @@ -5089,13 +5089,54 @@ function sessionResumeFailure( Reflect.get(error, "detailCode") === "SESSION_RESUME_REQUIRED" ) { const failure = new SessionResumeRequiredError(sessionKey); - return source === undefined - ? failure - : withPromptDiagnostic(failure, projectRuntimeError(error), source); + if (source === undefined) { + return failure; + } + const code = Reflect.get(error, "outputCode"); + const origin = Reflect.get(error, "origin"); + const retryable = Reflect.get(error, "retryable"); + return withPromptDiagnostic( + failure, + { + message: failure.message, + code: typeof code === "string" && code.trim().length > 0 ? code : "RUNTIME", + detailCode: "SESSION_RESUME_REQUIRED", + origin: origin === "cli" || origin === "queue" || origin === "acp" ? origin : "runtime", + ...(typeof retryable === "boolean" ? { retryable } : {}), + acp: resumeProtocolFacts(error), + }, + source, + ); } return error; } +function resumeProtocolFacts(error: unknown, depth = 0): AcpRuntimeTurnResultError["acp"] { + if (depth > 5 || typeof error !== "object" || error === null || Array.isArray(error)) { + return undefined; + } + const code = Reflect.get(error, "code"); + const message = Reflect.get(error, "message"); + if ( + typeof code === "number" && + Number.isFinite(code) && + typeof message === "string" && + message.length > 0 + ) { + const data = Reflect.get(error, "data"); + const details = + typeof data === "object" && data !== null ? Reflect.get(data, "details") : undefined; + return { code, message, ...(typeof details === "string" ? { details } : {}) }; + } + for (const key of ["acp", "error", "cause"]) { + const facts = resumeProtocolFacts(Reflect.get(error, key), depth + 1); + if (facts !== undefined) { + return facts; + } + } + return undefined; +} + export class SessionResumeRequiredError extends Error { constructor(sessionKey: string, options?: ErrorOptions) { super( diff --git a/packages/acp/tests/host-conversation.test.ts b/packages/acp/tests/host-conversation.test.ts index 32d215b2a..b94af54be 100644 --- a/packages/acp/tests/host-conversation.test.ts +++ b/packages/acp/tests/host-conversation.test.ts @@ -1738,7 +1738,7 @@ describe( ); describe( - "1388 — resume retention: a held Codex conversation across a host CLI upgrade", + "resume retention: a held Codex conversation across a host CLI upgrade", { sanitizeOps: false, sanitizeResources: false }, () => { for (const [mode, failure, errorName] of [ diff --git a/packages/acp/tests/released-runtime.test.ts b/packages/acp/tests/released-runtime.test.ts index 4cef788f4..47bcb1d0d 100644 --- a/packages/acp/tests/released-runtime.test.ts +++ b/packages/acp/tests/released-runtime.test.ts @@ -1147,7 +1147,7 @@ describe("released response recovery", () => { }); describe( - "1388 — resume retention: standard retained-session refusal", + "resume retention: standard retained-session refusal", { sanitizeOps: false, sanitizeResources: false }, () => { for (const [failure, stage, detail] of [ diff --git a/packages/acp/vendor/acpx/MANIFEST.json b/packages/acp/vendor/acpx/MANIFEST.json index 5c103376a..7d81d1ee0 100644 --- a/packages/acp/vendor/acpx/MANIFEST.json +++ b/packages/acp/vendor/acpx/MANIFEST.json @@ -32,7 +32,7 @@ { "path": "PROVENANCE.md", "kind": "provenance", - "sha256": "b72b83f60af9e612a1f9472989766e5cc9209c8bf6da6f3d1e3d251a378d3666" + "sha256": "1c1a19ac4d8765d90644a8a4a45013620b8204b37bf6967393778fbbe5e531b4" }, { "path": "generated/agent-registry-CxpAF3nI.js", @@ -62,12 +62,12 @@ { "path": "generated/runtime.d.ts", "kind": "generated", - "sha256": "8ae4d54137e32f946978e1d3f0335a41c05f2eb8e863b2cb1ee495def8081cd2" + "sha256": "45d3d96fafbcd677e20b11d4dc38b23f37ca9237360f47858e7f468cd597d04f" }, { "path": "generated/runtime.js", "kind": "generated", - "sha256": "e23aa856836d23e139219ffee5771e9995f3cbdde819c20e0cbfe7fad71a48e2" + "sha256": "ca6a3124680ef66b05538d91d52602bbd338ab0d8e36f483102fe2961b6d9c78" }, { "path": "generated/session-options-D9KL7-d8.d.ts", diff --git a/packages/acp/vendor/acpx/PROVENANCE.md b/packages/acp/vendor/acpx/PROVENANCE.md index 56e580d49..869ed79b5 100644 --- a/packages/acp/vendor/acpx/PROVENANCE.md +++ b/packages/acp/vendor/acpx/PROVENANCE.md @@ -110,8 +110,6 @@ an explicit empty details string and excludes arbitrary raw `acp.data`. The uniquely named `XMD prompt diagnostic:` seam bounds this correction in Tier AV. Real adapter-child failures pass through this runtime into production Prompt publication and cold REPL Journal queries of `promptError`. -The same projection is available through the runtime entry for classified -resume refusals before a runtime turn exists or writes its prompt (#1388). Other arbitrary adapter data remains unavailable through this selected result. This correction establishes no cause for the historical `Internal error` incident, diff --git a/packages/acp/vendor/acpx/generated/runtime.d.ts b/packages/acp/vendor/acpx/generated/runtime.d.ts index 5973581ca..b335af68b 100644 --- a/packages/acp/vendor/acpx/generated/runtime.d.ts +++ b/packages/acp/vendor/acpx/generated/runtime.d.ts @@ -322,8 +322,6 @@ type AcpRuntimeTurnResultError = { detailCode?: string; retryable?: boolean; }; -/** XMD prompt diagnostic: bounded runtime failure projection, also used before a turn exists. */ -export declare function projectRuntimeError(error: unknown): AcpRuntimeTurnResultError; /** XMD prompt usage: quota counters, under the adapter's own names. */ type AcpRuntimeQuotaTokens = { totalTokens?: number; diff --git a/packages/acp/vendor/acpx/generated/runtime.js b/packages/acp/vendor/acpx/generated/runtime.js index 328959508..c6774a03b 100644 --- a/packages/acp/vendor/acpx/generated/runtime.js +++ b/packages/acp/vendor/acpx/generated/runtime.js @@ -2114,7 +2114,21 @@ var AcpRuntimeManager = class { failRuntimeTurn(task, error) { task.promptStarted.reject(error); task.sessionReady.reject(error); - return { status: "failed", error: projectRuntimeError(error) }; // XMD prompt diagnostic: + const normalized = normalizeOutputError(error, { origin: "runtime" }); + // XMD prompt diagnostic: retain the extracted protocol facts, never raw data. + const acp = normalized.acp; + const details = acp?.data !== null && typeof acp?.data === "object" ? acp.data.details : void 0; + return { + status: "failed", + error: { + message: normalized.message, + ...normalized.origin !== void 0 ? { origin: normalized.origin } : {}, + ...acp ? { acp: { code: acp.code, message: acp.message, ...typeof details === "string" ? { details } : {} } } : {}, + ...normalized.code ? { code: normalized.code } : {}, + ...normalized.detailCode ? { detailCode: normalized.detailCode } : {}, + ...normalized.retryable !== void 0 ? { retryable: normalized.retryable } : {} + } + }; } async finalizeRuntimeTurn(task, turn) { task.state.turnActive = false; @@ -3071,20 +3085,4 @@ function createAcpRuntime(options) { function createRuntimeStore(options) { return createFileSessionStore(options); } -// XMD prompt diagnostic: reuse the bounded turn projection for a refused ensure. -function projectRuntimeError(error) { - const normalized = normalizeOutputError(error, { origin: "runtime" }); - const acp = normalized.acp; - const details = acp?.data !== null && typeof acp?.data === "object" ? acp.data.details : void 0; - return { - message: normalized.message, - ...normalized.origin !== void 0 ? { origin: normalized.origin } : {}, - // XMD prompt diagnostic: only protocol code, message and data.details. - ...acp ? { acp: { code: acp.code, message: acp.message, ...typeof details === "string" ? { details } : {} } } : {}, - ...normalized.code ? { code: normalized.code } : {}, - ...normalized.detailCode ? { detailCode: normalized.detailCode } : {}, - ...normalized.retryable !== void 0 ? { retryable: normalized.retryable } : {} - }; -} -export { projectRuntimeError }; // XMD prompt diagnostic: export { ACPX_BACKEND_ID, AcpRuntimeError, AcpxRuntime, DEFAULT_AGENT_NAME, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE, REQUESTED_MODEL_UNSUPPORTED_REASONS, RequestedModelUnsupportedError, SharedAcpRuntime, createAcpRuntime, createAgentRegistry, createFileSessionStore, createRuntimeStore, createSharedAcpRuntime, decodeAcpxRuntimeHandleState, encodeAcpxRuntimeHandleState, inspectAgentModels, isAcpRuntimeError, isRequestedModelUnsupportedError }; diff --git a/packages/agent/tests/agent-conversation.test.ts b/packages/agent/tests/agent-conversation.test.ts index cce1481db..50bf73aaf 100644 --- a/packages/agent/tests/agent-conversation.test.ts +++ b/packages/agent/tests/agent-conversation.test.ts @@ -3109,7 +3109,7 @@ describe("used held conversation continuation", () => { }); }); -describe("1388 — resume retention: held setup and recovery readers", () => { +describe("resume retention: held setup and recovery readers", () => { const header = { provider: "acp", operation: "session/prompt", stage: "held-session-ensure" }; const diagnostic = { ...header, acp: { code: -32041, details: "synthetic adapter detail" } }; const message = "The retained session could not be resumed."; @@ -3122,7 +3122,7 @@ describe("1388 — resume retention: held setup and recovery readers", () => { const result = yield* withConversation( history, stub(traffic, { - asserts: () => "native-1388", + asserts: () => "native-held-conversation", refuseSession() { if (refuse) { const error = new Error(message, { cause: new Error("unselected error envelope") }); diff --git a/packages/cli/tests/repl-sidekick-recovery.test.ts b/packages/cli/tests/repl-sidekick-recovery.test.ts index 8a8246f21..ccc4f4af7 100644 --- a/packages/cli/tests/repl-sidekick-recovery.test.ts +++ b/packages/cli/tests/repl-sidekick-recovery.test.ts @@ -217,7 +217,7 @@ function turn( }; } -describe("1388 — resume retention: exact request ownership", () => { +describe("resume retention: exact request ownership", () => { const message: SidekickRecord = { kind: "message", id: "message-1", @@ -4918,7 +4918,7 @@ describe("1183 — the exact live feedback request is the only exception", () => }); }); -describe("1388 — resume retention and 1269 — mounted retained recovery corrections", () => { +describe("resume retention and mounted retained recovery corrections", () => { const savedText = "Continue the exact saved instruction."; const oldText = "Original chat remains readable."; const entryText = "An established entry remains readable."; diff --git a/specs/acp-client-spec.md b/specs/acp-client-spec.md index 8af1d60b3..f9d842e96 100644 --- a/specs/acp-client-spec.md +++ b/specs/acp-client-spec.md @@ -2052,8 +2052,8 @@ its caller supplied, from Prompt `timeout` or the enclosing AgentProvider terminal in `checkpoint.ts` and `events.ts`. Cancellation and failure never acquire one, and no local runtime metadata patch remains. The pinned in-process runtime preserves normalized origin and selected protocol - code/message/details in the runtime failure projection used for terminal and - pre-prompt resume failures. Arbitrary `acp.data` remains + code/message/details at `failRuntimeTurn`. XMD selects the same fields from + pre-prompt resume errors and their causes. Arbitrary `acp.data` remains excluded. The shared/queue result projection is unchanged. The generated correction and its matching declaration are recorded in vendor provenance and offline Tier AV. - **Serialization.** Prompts for one session run FIFO on that session's queue; different sessions run concurrently. A subscription enters that queue before