diff --git a/packages/acp/src/events.ts b/packages/acp/src/events.ts index 79ee0d34c..930dc99e6 100644 --- a/packages/acp/src/events.ts +++ b/packages/acp/src/events.ts @@ -24,7 +24,12 @@ import { each, race, stream, until } from "effection"; import type { Channel, Operation } from "effection"; -import type { AgentPromptCheckpoint, AgentPromptEvent, Session } from "@executablemd/agent/api"; +import type { + AgentPromptCheckpoint, + AgentPromptEvent, + Session, + SessionConfiguration, +} from "@executablemd/agent/api"; import type { AcpRuntimeTurn, AcpRuntimeTurnResult } from "./acpx-runtime.ts"; import { checkpointFromResult } from "./checkpoint.ts"; import { XmdResponse, XMD_RESPONSE, xmdPromptEvent } from "./xmd-response.ts"; @@ -34,6 +39,7 @@ import type { TurnUsage } from "./usage.ts"; export interface TurnIdentity { agent: string; session: Session; + observedConfiguration?: SessionConfiguration | void; } /** @@ -65,7 +71,14 @@ export function* consumeTurn( closeFailed?: () => Operation, usage?: TurnUsage, ): Operation { - yield* channel.send({ type: "started", agent: identity.agent, session: identity.session }); + yield* channel.send({ + type: "started", + agent: identity.agent, + session: identity.session, + ...(identity.observedConfiguration === undefined + ? {} + : { observedConfiguration: identity.observedConfiguration }), + }); let text = ""; let terminal: AgentPromptEvent; let named: AgentPromptCheckpoint | undefined; diff --git a/packages/acp/src/provider.ts b/packages/acp/src/provider.ts index 37b9333a1..ec0312152 100644 --- a/packages/acp/src/provider.ts +++ b/packages/acp/src/provider.ts @@ -2887,7 +2887,20 @@ function* useAcpxProviderState( return { agent: agentName, sessionKey, - readStatus: () => until(readStatus.call(runtime, { handle: entry.handle })), + verify: agentName === "claude" && configuration !== undefined, + readStatus: () => + until( + readStatus.call(runtime, { + handle: entry.handle, + ...(agentName === "claude" && configuration !== undefined + ? { + verifyConfiguration: true, + ...modelRequest(configuration), + ...(configuration.effort === undefined ? {} : { inspectEffort: true }), + } + : {}), + }), + ), /** * One write, and the Promise it started, owned by this operation. * @@ -2899,7 +2912,7 @@ function* useAcpxProviderState( * yields, so restoration cannot begin until this exact write is done * moving the conversation. */ - write(optionId, value) { + write(optionId, value, restoreContextWindow) { return scoped(function* (): Operation { if (writeOption === undefined) { throw new AcpConfigurationError( @@ -2925,6 +2938,7 @@ function* useAcpxProviderState( handle: entry.handle, key: optionId, value, + ...(restoreContextWindow === undefined ? {} : { restoreContextWindow }), // The same attempt's requested model for ordinary and restoring // writes alike: either may be the one that reconnects. ...modelRequest(configuration), @@ -2990,10 +3004,16 @@ function* useAcpxProviderState( configuration, ); return { - ...(configuration.model === undefined ? {} : { model: selectors.model?.set.selected ?? "" }), + ...(configuration.model === undefined + ? {} + : { + model: selectors.native?.matches + ? configuration.model + : (selectors.model?.set.selected ?? ""), + }), ...(configuration.effort === undefined ? {} - : { effort: selectors.effort?.set.selected ?? "" }), + : { effort: selectors.native?.effort ?? selectors.effort?.set.selected ?? "" }), }; } @@ -3195,7 +3215,8 @@ function* useAcpxProviderState( // under the wrong model is a turn that cannot be taken back, so the // values are applied and verified first and the turn only follows a // configuration this provider put into force. - if (desired !== undefined) { + const verifyAtDispatch = desired !== undefined && agentName === "claude"; + if (desired !== undefined && !verifyAtDispatch) { yield* configureSession(agentName, entry, desired); } @@ -3232,37 +3253,38 @@ function* useAcpxProviderState( // The runtime that made this handle, never "the" runtime: a turn // started through another partition would be a second child in a // conversation the first already owns. - const turn = entry.runtime.runtime.startTurn({ - handle: entry.handle, - text: content, - ...(options?.images === undefined ? {} : { attachments: [...options.images] }), - mode: "prompt", - requestId, - timeoutMs, - ...modelRequest(desired), - ...(callbacks === undefined - ? {} - : { - onElicitation: (request, context) => - scope - .run(function* (): Operation< - Result - > { - try { - return Ok(yield* callbacks.elicitation(request, context.signal)); - } catch (error) { - return Err(toError(error)); - } - }) - .then((result) => { - if (!result.ok) { - throw result.error; - } - return result.value; - }), - }), - }); - activeTurns.add(turn); + const start = () => + entry.runtime.runtime.startTurn({ + handle: entry.handle, + text: content, + ...(options?.images === undefined ? {} : { attachments: [...options.images] }), + mode: "prompt", + requestId, + timeoutMs, + ...modelRequest(desired), + ...(desired?.effort === undefined ? {} : { requestedEffort: desired.effort }), + ...(callbacks === undefined + ? {} + : { + onElicitation: (request, context) => + scope + .run(function* (): Operation< + Result + > { + try { + return Ok(yield* callbacks.elicitation(request, context.signal)); + } catch (error) { + return Err(toError(error)); + } + }) + .then((result) => { + if (!result.ok) { + throw result.error; + } + return result.value; + }), + }), + }); const usage: TurnUsage | undefined = reportUsage === undefined || promptUsageHost === undefined ? undefined @@ -3280,8 +3302,13 @@ function* useAcpxProviderState( }, }), }); + const dispatched: { turn?: AcpRuntimeTurn } = {}; let completed = false; yield* ensure(function* () { + const turn = dispatched.turn; + if (turn === undefined) { + return; + } activeTurns.delete(turn); if (!completed) { try { @@ -3292,9 +3319,7 @@ function* useAcpxProviderState( } }); - // Registered after the turn exists and before its events are - // consumed, so a permission request arriving mid-turn reaches the - // turn it belongs to and nothing else. + // Register before dispatch so the first permission request reaches its turn. const denials = { denied: false }; if (strict) { const sessionKey = entry.session.sessionKey; @@ -3306,18 +3331,58 @@ function* useAcpxProviderState( }); } + let observedConfiguration: SessionConfiguration | void = undefined; + const awaitsMaterialization = + constructing && + adapterFor(agentName)?.acceptance === "first-turn-acceptance" && + prepared.kind === "details"; + function startTracked(): AcpRuntimeTurn { + const turn = start(); + dispatched.turn = turn; + activeTurns.add(turn); + return turn; + } + function* dispatch(): Operation { + yield* scoped(function* () { + const turn = startTracked(); + let accepted = false; + yield* ensure(function* () { + if (accepted) { + return; + } + yield* until(turn.cancel()); + yield* until(turn.result); + completed = true; + }); + try { + observedConfiguration = yield* until(turn.promptStarted); + } catch (error) { + throw sessionResumeFailure(error, entry.session.sessionKey); + } + accepted = true; + }); + } + if (desired !== undefined && verifyAtDispatch) { + yield* applySessionConfiguration( + configurationTarget(agentName, entry, true, desired), + desired, + dispatch, + ); + } else if (awaitsMaterialization) { + startTracked(); + } else { + yield* dispatch(); + } + const turn = dispatched.turn; + if (turn === undefined) { + throw new Error("The prompt dispatch did not produce a turn."); + } if ( constructing && adapterFor(agentName)?.acceptance === "first-turn-acceptance" && prepared.kind === "details" ) { yield* materialize(entry, prepared.details, turn, usage); - } else { - try { - yield* until(turn.promptStarted); - } catch (error) { - throw sessionResumeFailure(error, entry.session.sessionKey); - } } const channel = createChannel(); @@ -3331,7 +3396,7 @@ function* useAcpxProviderState( // under. A record is written from this, so it has to be what // actually ran rather than what an element once held. A name // resolves to the session it named, which carries no settings. - { agent: agentName, session: ranIn ?? entry.session }, + { agent: agentName, session: ranIn ?? entry.session, observedConfiguration }, channel, () => { completed = true; diff --git a/packages/acp/src/session-configuration.ts b/packages/acp/src/session-configuration.ts index 690b541c4..7e90cc5d8 100644 --- a/packages/acp/src/session-configuration.ts +++ b/packages/acp/src/session-configuration.ts @@ -31,6 +31,13 @@ export interface RecognizedSelector { export interface AgentOptionSelectors { readonly model: RecognizedSelector | null; readonly effort: RecognizedSelector | null; + readonly variantUnavailable?: true; + readonly native?: { + readonly model: string; + readonly effort?: string; + readonly contextWindow?: number; + readonly matches: boolean; + }; } /** @@ -181,6 +188,7 @@ function recognize( setting: string, category: string, id: string, + observed?: string, ): RecognizedSelector | null { const found = candidate(entries, setting, category, id); if (found === undefined) { @@ -196,12 +204,12 @@ function recognize( `select from it`, ); } - const selected = text(found.currentValue); + const selected = observed ?? text(found.currentValue); if (selected === undefined) { throw malformed(`this agent's ${setting} selector reports no current value`); } const options = choices(found.options, setting); - if (!options.some((entry) => entry.id === selected)) { + if (observed === undefined && !options.some((entry) => entry.id === selected)) { throw malformed( `this agent reports the ${setting} "${selected}" as current and does not offer it, so ` + `what this conversation is running under is not something it stated`, @@ -217,14 +225,31 @@ function recognize( * recognized is read strictly, because a selector read past is a selector * written to by guesswork. */ -export function readAgentOptions(status: AcpRuntimeStatus): AgentOptionSelectors { +export function readAgentOptions(status: AcpRuntimeStatus, verify = false): AgentOptionSelectors { const entries = advertised(status); if (entries === undefined) { return { model: null, effort: null }; } + const report = + verify && isRecord(status.details) ? status.details.claudeConfiguration : undefined; + const model = isRecord(report) ? text(report.model) : undefined; + const native = + isRecord(report) && model !== undefined + ? { + model, + effort: text(report.effort), + contextWindow: + typeof report.contextWindow === "number" && report.contextWindow > 0 + ? report.contextWindow + : undefined, + matches: report.matches === true, + } + : undefined; return { - model: recognize(entries, "model", "model", "model"), - effort: recognize(entries, "effort", "thought_level", "effort"), + model: recognize(entries, "model", "model", "model", native?.model), + effort: recognize(entries, "effort", "thought_level", "effort", native?.effort), + ...(native === undefined ? {} : { native }), + ...(isRecord(report) && report.variantUnavailable === true ? { variantUnavailable: true } : {}), }; } @@ -277,12 +302,13 @@ export interface ConfigurationTarget { readonly agent: string; readonly sessionKey: string; readStatus(): Operation; - write(optionId: string, value: string): Operation; + write(optionId: string, value: string, restoreContextWindow?: number): Operation; markUnusable(): void; + readonly verify?: boolean; } function* read(target: ConfigurationTarget): Operation { - return readAgentOptions(yield* target.readStatus()); + return readAgentOptions(yield* target.readStatus(), target.verify); } /** @@ -301,11 +327,15 @@ function* read(target: ConfigurationTarget): Operation { export function* applySessionConfiguration( target: ConfigurationTarget, request: SessionConfiguration, + beforeSettled?: () => Operation, ): Operation { return yield* scoped(function* (): Operation { const initial = yield* read(target); const priorModel = initial.model?.set.selected; - const priorEffort = initial.effort?.set.selected; + const priorEffort = initial.native ? initial.native.effort : initial.effort?.set.selected; + const priorWindow = initial.native?.contextWindow; + const modelMatches = (state: AgentOptionSelectors): boolean => + state.native?.matches ?? state.model?.set.selected === request.model; // A started write is a write that may have landed, so this is set before // one is issued rather than after it answers: an adapter that applies the // value and then fails its response has still applied it. @@ -317,21 +347,37 @@ export function* applySessionConfiguration( function* restore(): Operation { try { const current = yield* read(target); - if (priorModel !== undefined && current.model !== null) { - if (current.model.set.selected !== priorModel) { - yield* target.write(current.model.optionId, priorModel); + if ( + priorModel !== undefined && + current.model !== null && + (current.model.set.selected !== priorModel || + current.native?.contextWindow !== priorWindow) + ) { + if (initial.native !== undefined && priorWindow === undefined) { + return false; } + yield* target.write(current.model.optionId, priorModel, priorWindow); } const refreshed = yield* read(target); - if (priorEffort !== undefined && refreshed.effort !== null) { - if (refreshed.effort.set.selected !== priorEffort) { - yield* target.write(refreshed.effort.optionId, priorEffort); + if ( + priorEffort !== undefined && + (refreshed.native ? refreshed.native.effort : refreshed.effort?.set.selected) !== + priorEffort + ) { + const optionId = refreshed.effort?.optionId ?? initial.effort?.optionId; + if (optionId === undefined && priorWindow === undefined) { + return false; } + yield* target.write(optionId ?? "effort", priorEffort, priorWindow); } const verified = yield* read(target); - const modelBack = priorModel === undefined || verified.model?.set.selected === priorModel; - const effortBack = - priorEffort === undefined || verified.effort?.set.selected === priorEffort; + const modelBack = + (priorModel === undefined || verified.model?.set.selected === priorModel) && + verified.native?.contextWindow === priorWindow; + const restoredEffort = verified.native + ? verified.native.effort + : verified.effort?.set.selected; + const effortBack = priorEffort === undefined || restoredEffort === priorEffort; return modelBack && effortBack; } catch { return false; @@ -362,6 +408,13 @@ export function* applySessionConfiguration( try { if (request.model !== undefined) { + if (initial.variantUnavailable) { + throw configurationFailure( + `Claude cannot verify the requested context variant "${request.model}" before its first prompt`, + "configuration-mismatch", + "model", + ); + } if (initial.model === null) { throw configurationFailure( modelUnavailable(target.agent), @@ -374,7 +427,7 @@ export function* applySessionConfiguration( unknownModel(target.agent, request.model, initial.model.set), ); } - if (initial.model.set.selected !== request.model) { + if (!modelMatches(initial)) { touched = true; yield* target.write(initial.model.optionId, request.model); } @@ -383,7 +436,7 @@ export function* applySessionConfiguration( // The refreshed answer, and the only source of effort choices for the // model this conversation is now on. const refreshed = request.model === undefined ? initial : yield* read(target); - if (request.model !== undefined && refreshed.model?.set.selected !== request.model) { + if (request.model !== undefined && !modelMatches(refreshed)) { throw configurationFailure( `this agent did not apply the model "${request.model}" to session ` + `"${target.sessionKey}", and reports "${refreshed.model?.set.selected ?? "nothing"}"`, @@ -393,6 +446,9 @@ export function* applySessionConfiguration( } if (request.effort === undefined) { + if (beforeSettled !== undefined) { + yield* beforeSettled(); + } settled = true; return refreshed; } @@ -406,13 +462,26 @@ export function* applySessionConfiguration( invalidEffort(model ?? "the current model", request.effort, refreshed.effort.set), ); } - if (refreshed.effort.set.selected !== request.effort) { + if ( + (refreshed.native ? refreshed.native.effort : refreshed.effort.set.selected) !== + request.effort + ) { + if (refreshed.native !== undefined && priorEffort === undefined) { + throw configurationFailure( + `Claude cannot verify the prior effort for session "${target.sessionKey}"`, + "configuration-mismatch", + "effort", + ); + } touched = true; yield* target.write(refreshed.effort.optionId, request.effort); } const verified = yield* read(target); - if (verified.effort?.set.selected !== request.effort) { + if ( + (verified.native ? verified.native.effort : verified.effort?.set.selected) !== + request.effort + ) { throw configurationFailure( `this agent did not apply the effort level "${request.effort}" to session ` + `"${target.sessionKey}", and reports "${verified.effort?.set.selected ?? "nothing"}"`, @@ -420,7 +489,7 @@ export function* applySessionConfiguration( "effort", ); } - if (request.model !== undefined && verified.model?.set.selected !== request.model) { + if (request.model !== undefined && !modelMatches(verified)) { throw configurationFailure( `this agent stopped reporting the model "${request.model}" for session ` + `"${target.sessionKey}" while its effort level was applied`, @@ -428,6 +497,9 @@ export function* applySessionConfiguration( "model", ); } + if (beforeSettled !== undefined) { + yield* beforeSettled(); + } settled = true; return verified; } catch (error) { diff --git a/packages/acp/tests/adapter-protocol.test.ts b/packages/acp/tests/adapter-protocol.test.ts index d0133f75d..75e738c0a 100644 --- a/packages/acp/tests/adapter-protocol.test.ts +++ b/packages/acp/tests/adapter-protocol.test.ts @@ -1117,21 +1117,6 @@ describe("Tier EA — the Claude adapter's resumed model under an explicit use ( for (const [name, environment, refusal] of [ ["absent", { FAKE_CLAUDE_CONTEXT_USAGE: "absent" }, "reported no model"], ["failed", { FAKE_CLAUDE_CONTEXT_USAGE: "fail" }, "could not report the model it runs"], - [ - "unrepresentable", - { - FAKE_CLAUDE_MODELS: JSON.stringify([ - { - value: "default", - resolvedModel: "claude-fable-5-1", - displayName: "D", - description: "", - }, - { value: "fable", resolvedModel: "claude-fable-5-1", displayName: "F", description: "" }, - ]), - }, - "none of its offered models names exactly", - ], ] as const) { it(`EA17: a marked resume refuses a ${name} observation as an invalid request`, function* () { const { adapter, sessionId, cwd } = yield* useResumable("fable", environment); @@ -1154,16 +1139,15 @@ describe("Tier EA — the Claude adapter's resumed model under an explicit use ( }); } - it("EA18: without the marker, resume and new keep the existing model choice", function* () { - const { adapter, sessionId, cwd } = yield* useResumable("claude-fable-5"); + it("EA18: unmarked resume preserves an unlisted model and fresh selection keeps its defaults", function* () { + const { adapter, sessionId, cwd } = yield* useResumable("claude-fable-5-2"); const resumed = yield* adapter.request("session/resume", { sessionId, cwd, mcpServers: [], }); - // The global preference is reasserted, exactly as before. - expect(reportedModel(resumed)).toBe("fable"); - expect(yield* modelWrites(adapter)).toEqual(["fable"]); + expect(reportedModel(resumed)).toBe("claude-fable-5-2"); + expect(yield* modelWrites(adapter)).toEqual([]); // A fresh session ignores the marker: there is nothing resumed to observe. const fresh = yield* adapter.request("session/new", { cwd, diff --git a/packages/acp/tests/claude-reconnect.test.ts b/packages/acp/tests/claude-reconnect.test.ts index 41a4bb16f..847158dcf 100644 --- a/packages/acp/tests/claude-reconnect.test.ts +++ b/packages/acp/tests/claude-reconnect.test.ts @@ -286,13 +286,12 @@ describe( }); }); - it("CR3: an unflagged use keeps the provider-default behavior, even after a flagged one", function* () { + it("CR3: an unchanged cold use preserves the live model regardless of an earlier selection", function* () { const world = yield* useWorld("fable"); yield* scoped(function* () { const runtime = runtimeFor(world); yield* ensure(() => until(runtime.shutdown())); - // Never configured: the global preference governs, as it always has, - // and each resume reasserts it. + // The global preference seeds fresh selection. yield* ownedTurn(world, runtime, "first"); yield* ownedTurn(world, runtime, "second"); const unconfigured = observed(yield* logged(world)); @@ -300,21 +299,20 @@ describe( "claude-fable-5-1", "claude-fable-5-1", ]); - expect(unconfigured.modelWrites).toEqual(["fable"]); + expect(unconfigured.modelWrites).toEqual([]); }); const flagged = yield* useWorld("fable"); yield* scoped(function* () { const runtime = runtimeFor(flagged); yield* ensure(() => until(runtime.shutdown())); - // A flagged use leaves nothing behind for a later unflagged one: that - // reconnect reasserts the global preference and the saved selection is - // replayed over it, exactly as before. + // Resuming a configured conversation without a new choice gives the + // native model no new selection authority. yield* established(flagged, runtime, EXPLICIT); const before = (yield* logged(flagged)).length; yield* ownedTurn(flagged, runtime, "unflagged"); const after = observed((yield* logged(flagged)).slice(before)); - expect(after.modelWrites).toEqual(["fable", EXPLICIT]); + expect(after.modelWrites).toEqual([]); expect(after.prompts.map((prompt) => prompt.model)).toEqual([EXPLICIT]); }); }); @@ -360,12 +358,39 @@ describe( yield* ensure(() => until(runtime.shutdown())); yield* established(world, runtime, EXPLICIT); const session = observed(yield* logged(world)).prompts[0]?.session; - // A native owner changed the model while ACP held nothing. + const earlier = yield* until(runtime.ensureSession(input(world, EXPLICIT))); + const checked = yield* until( + runtime.getStatus({ + handle: earlier, + requestedModel: EXPLICIT, + verifyConfiguration: true, + }), + ); + expect(checked.details?.claudeConfiguration).toMatchObject({ + model: EXPLICIT, + matches: true, + }); + yield* until(runtime.close({ handle: earlier, reason: "the checked client was lost" })); + // The attachment that checked the model cannot certify the next client. const conversation = join(world.state, `${encodeURIComponent(session ?? "")}.json`); const persisted = JSON.parse(yield* readTextFile(conversation)); yield* writeTextFile(conversation, JSON.stringify({ ...persisted, model: ANOTHER })); const before = (yield* logged(world)).length; + const late = runtime.startTurn({ + handle: earlier, + text: "before selection", + mode: "prompt", + requestId: "late-check", + requestedModel: EXPLICIT, + }); + expect(yield* until(late.result)).toMatchObject({ + status: "failed", + error: { message: expect.stringContaining("did not verify") }, + }); + expect(observed((yield* logged(world)).slice(before)).prompts).toEqual([]); + yield* until(runtime.close({ handle: earlier, reason: "refused final attachment" })); + yield* ownedWrite(world, runtime, "model", EXPLICIT, EXPLICIT); yield* ownedTurn(world, runtime, "after native", EXPLICIT); const after = observed((yield* logged(world)).slice(before)); // The reconnect saw the real change, so the selection is written back @@ -375,7 +400,7 @@ describe( }); }); - it("CR6: an unrepresentable or unreadable resumed model refuses before any prompt", function* () { + it("CR6: an offered alias verifies its native model and an unreadable resume refuses", function* () { const world = yield* useWorld(); const aliasOnly = JSON.stringify([ { @@ -389,20 +414,54 @@ describe( resolvedModel: "claude-fable-5-1", displayName: "Fable", description: "", + supportsEffort: true, + supportedEffortLevels: ["low", "high"], }, ]); yield* scoped(function* () { const runtime = runtimeFor(world, { FAKE_CLAUDE_MODELS: aliasOnly }); yield* ensure(() => until(runtime.shutdown())); yield* ownedWrite(world, runtime, "model", "fable", "fable"); - // The backend reports the concrete model behind the alias. Nothing offered - // names it exactly, so a use naming its own model refuses rather than - // inventing that row or reading it as the alias. - const refused = yield* refusalOfTurn(world, runtime, "flagged", "fable"); - expect(refused).toContain("claude-fable-5-1"); - expect(observed(yield* logged(world)).prompts).toEqual([]); - // Without the fact, the existing behavior stands. + expect(yield* ownedTurn(world, runtime, "flagged", "fable")).toEqual({ + status: "completed", + }); expect(yield* ownedTurn(world, runtime, "unflagged")).toEqual({ status: "completed" }); + expect(observed(yield* logged(world)).prompts.map((event) => event.model)).toEqual([ + "claude-fable-5-1", + "claude-fable-5-1", + ]); + const before = (yield* logged(world)).length; + const handle = yield* until(runtime.ensureSession(input(world))); + yield* ensure(() => until(runtime.close({ handle, reason: "alias effort" }))); + const choices = yield* until( + runtime.getStatus({ handle, verifyConfiguration: true, inspectEffort: true }), + ); + expect(choices.details?.claudeConfiguration).toMatchObject({ + model: "claude-fable-5-1", + configOptions: expect.arrayContaining([ + expect.objectContaining({ + id: "effort", + options: expect.arrayContaining([expect.objectContaining({ value: "low" })]), + }), + ]), + }); + yield* until(runtime.setConfigOption({ handle, key: "effort", value: "low" })); + const turn = runtime.startTurn({ + handle, + text: "same alias with low effort", + mode: "prompt", + requestId: "alias-effort", + requestedEffort: "low", + }); + expect((yield* until(turn.result)).status).toBe("completed"); + const changes = (yield* logged(world)).slice(before); + expect( + changes.filter((event) => event.control === "effort").map((event) => event.effort), + ).toEqual(["low"]); + expect(observed(changes)).toEqual({ + modelWrites: [], + prompts: [{ session: handle.agentSessionId, model: "claude-fable-5-1", effort: "low" }], + }); }); const unreadable = yield* useWorld(); @@ -416,6 +475,18 @@ describe( const refused = yield* refusalOfTurn(unreadable, failing, "flagged", EXPLICIT); expect(refused).toContain("could not report the model it runs"); expect(observed(yield* logged(unreadable)).prompts.length).toBe(prompts); + + const wrong = runtimeFor(unreadable, { FAKE_CLAUDE_CONFIRMATION: "mismatch" }); + yield* ensure(() => until(wrong.shutdown())); + const before = (yield* logged(unreadable)).length; + expect( + yield* refusalOfTurn(unreadable, wrong, "wrong native identity", EXPLICIT), + ).toContain("identity confirmation failed"); + const attempted = (yield* logged(unreadable)).slice(before); + expect(observed(attempted)).toEqual({ modelWrites: [], prompts: [] }); + expect( + attempted.filter((entry) => entry.event === "started").map((entry) => entry.resumed), + ).toEqual([true]); }); }); }, @@ -581,8 +652,9 @@ function deliveredCoordinator(): AgentLaunchCoordinator { function* configuredPrompt( configuration: SessionConfiguration | undefined, text: string, + name = "sidekick", ): Operation { - const issuance = openSessionRequest(undefined, "sidekick"); + const issuance = openSessionRequest(undefined, name); issuance.configure(configuration); try { const use = yield* Agent.operations.session(issuance.request); @@ -676,6 +748,117 @@ describe( const changed = observed((yield* logged(world)).slice(change)); expect(changed.modelWrites).toEqual([ANOTHER]); expect(changed.prompts).toEqual([{ session, model: ANOTHER, effort: "high" }]); + const nativeId = sessionOf(first)?.agentSessionId; + if (nativeId === undefined || session === undefined) { + throw new Error("the prepared adapter did not establish a native session"); + } + for (const model of ["claude-opus-5-5", "claude-fable-5-2"]) { + for (const record of world.records.values()) { + const prior = record.acpx; + record.acpx = { + ...prior, + session_options: { ...prior?.session_options, model: EXPLICIT }, + desired_config_options: { + ...prior?.desired_config_options, + model: ANOTHER, + effort: "low", + }, + }; + } + yield* writeTextFile( + join(world.state, `${encodeURIComponent(session)}.json`), + JSON.stringify({ model, effort: "high" }), + ); + const from = (yield* logged(world)).length; + const use = yield* configuredPrompt(undefined, `unchanged ${model}`); + expect(sessionOf(use)?.agentSessionId).toBe(nativeId); + const events = (yield* logged(world)).slice(from); + expect(observed(events)).toEqual({ + modelWrites: [], + prompts: [{ session, model, effort: "high" }], + }); + expect(events.filter((event) => event.control === "effort")).toEqual([]); + const cold = events.filter((event) => event.event === "started"); + expect(cold.length).toBeGreaterThan(0); + expect(cold.every((event) => event.resumed && event.session === session)).toBe(true); + expect(events.filter((event) => event.event === "exit")).toHaveLength(cold.length); + const launches = events.flatMap((event) => + event.argv === undefined ? [] : [event.argv], + ); + expect(launches).toHaveLength(cold.length); + expect( + launches.flat().some((arg) => arg === "--model" || arg.startsWith("--model=")), + ).toBe(false); + } + + function* refused( + configuration: SessionConfiguration, + name = "sidekick", + ): Operation { + try { + yield* configuredPrompt(configuration, "refused", name); + return ""; + } catch (error) { + return String(error); + } + } + + const persisted = join(world.state, `${encodeURIComponent(session)}.json`); + yield* writeTextFile( + persisted, + JSON.stringify({ model: ANOTHER, effort: "high", hideEffort: true }), + ); + const beforeUnattested = (yield* logged(world)).length; + expect(yield* refused({ effort: "low" })).toContain("cannot verify the prior effort"); + const unattested = (yield* logged(world)).slice(beforeUnattested); + expect(unattested.filter((event) => event.control === "effort")).toEqual([]); + expect(observed(unattested)).toEqual({ modelWrites: [], prompts: [] }); + const afterRefusal = yield* configuredPrompt(undefined, "continue without an effort write"); + expect(sessionOf(afterRefusal)?.agentSessionId).toBe(nativeId); + expect(observed((yield* logged(world)).slice(beforeUnattested)).prompts).toEqual([ + { session, model: ANOTHER, effort: "high" }, + ]); + yield* writeTextFile(persisted, JSON.stringify({ model: ANOTHER, effort: "high" })); + + const variant = { model: "sonnet[1m]", effort: "high" }; + const variantStart = (yield* logged(world)).length; + yield* configuredPrompt(variant, "verified variant"); + expect(observed((yield* logged(world)).slice(variantStart))).toEqual({ + modelWrites: ["sonnet[1m]"], + prompts: [{ session, model: ANOTHER, effort: "high" }], + }); + + for (const rejectRestoration of [false, true]) { + yield* writeTextFile( + persisted, + JSON.stringify({ + model: "claude-opus-5-5", + effort: "high", + contextWindow: 200_000, + contradictVariant: true, + rejectRestoration, + }), + ); + const start = (yield* logged(world)).length; + const failure = yield* refused(variant); + expect(failure).toContain("did not apply the model"); + const attempts = (yield* logged(world)).slice(start); + expect(observed(attempts).prompts).toEqual([]); + if (!rejectRestoration) { + const writes = attempts + .filter((event) => event.control === "set_model" || event.control === "effort") + .map((event) => (event.control === "effort" ? event.effort : event.model)); + expect(writes).toEqual(["sonnet[1m]", "claude-opus-5-5", "high"]); + } else { + expect(failure).toContain("Restoring the prior configuration failed"); + expect(yield* refused(variant)).toContain("will not be used again"); + } + } + const beforeFresh = (yield* logged(world)).length; + expect(yield* refused(variant, "fresh")).toContain( + "cannot verify the requested context variant", + ); + expect(observed((yield* logged(world)).slice(beforeFresh)).prompts).toEqual([]); }); }); }, @@ -689,9 +872,9 @@ function* refusalOfTurn( requestedModel: string, ): Operation { return yield* scoped(function* () { - const handle = yield* until(runtime.ensureSession(input(world, requestedModel))); - yield* ensure(() => until(runtime.close({ handle, reason: "refused" }))); try { + const handle = yield* until(runtime.ensureSession(input(world, requestedModel))); + yield* ensure(() => until(runtime.close({ handle, reason: "refused" }))); const turn = runtime.startTurn({ handle, text, diff --git a/packages/acp/tests/fixtures/fake-claude-cli.cjs b/packages/acp/tests/fixtures/fake-claude-cli.cjs index 1f834f31f..696042cd6 100755 --- a/packages/acp/tests/fixtures/fake-claude-cli.cjs +++ b/packages/acp/tests/fixtures/fake-claude-cli.cjs @@ -54,6 +54,26 @@ const CATALOG = STATE_DIR supportsEffort: true, supportedEffortLevels: ["low", "medium", "high"], }, + { + value: "opus", + resolvedModel: "claude-opus-4-6", + displayName: "Opus", + description: "", + }, + { + value: "claude-fable-5-1", + resolvedModel: "claude-fable-5-1", + displayName: "Fable 5.1", + description: "", + }, + { + value: "sonnet[1m]", + resolvedModel: "claude-sonnet-5-5", + displayName: "Sonnet 1M", + description: "", + supportsEffort: true, + supportedEffortLevels: ["low", "medium", "high"], + }, { value: "fable", resolvedModel: "claude-fable-5-1", @@ -255,9 +275,16 @@ function answerStateful(message) { response: { subtype: "success", request_id: message.request_id, response }, }); if (request.subtype === "set_model") { - state.model = request.model ?? "default"; + const model = request.model ?? "default"; + if (model === "sonnet[1m]" && state.contradictVariant) { + state.model = "claude-sonnet-5-5"; + state.effort = "low"; + } else if (!(state.rejectRestoration && model === "claude-opus-5-5")) { + state.model = model; + } + state.contextWindow = model === "sonnet[1m]" && !state.contradictVariant ? 1_000_000 : 200_000; persist(); - log({ control: "set_model", session: SESSION, model: state.model }); + log({ control: "set_model", session: SESSION, model }); succeed({}); return true; } @@ -270,6 +297,10 @@ function answerStateful(message) { succeed({}); return true; } + if (request.subtype === "get_settings") { + succeed(state.hideEffort ? {} : { effective: { effortLevel: state.effort } }); + return true; + } if (request.subtype === "get_context_usage") { log({ control: "get_context_usage", session: SESSION, model: running() }); if (process.env.FAKE_CLAUDE_CONTEXT_USAGE === "fail") { @@ -287,7 +318,7 @@ function answerStateful(message) { categories: [], totalTokens: 0, maxTokens: 200000, - rawMaxTokens: 200000, + rawMaxTokens: state.contextWindow ?? 200_000, percentage: 0, gridRows: [], model: process.env.FAKE_CLAUDE_CONTEXT_USAGE === "absent" ? undefined : running(), @@ -342,7 +373,12 @@ process.stdin.on("data", (chunk) => { // Only Query failure releases this lookup, so setup cannot outrun the contradiction. continue; } - if (STATE_DIR && answerStateful(message)) { + if ( + (STATE_DIR || + message.request?.subtype === "get_context_usage" || + message.request?.subtype === "get_settings") && + answerStateful(message) + ) { continue; } emit({ diff --git a/packages/acp/tests/helpers.ts b/packages/acp/tests/helpers.ts index 1c7a98f7c..24f5360e8 100644 --- a/packages/acp/tests/helpers.ts +++ b/packages/acp/tests/helpers.ts @@ -106,6 +106,7 @@ export interface ScriptedTurn { accepted?: boolean; /** Withhold acceptance until `accept()`, however the turn itself is driven. */ manualAcceptance?: boolean; + observedConfiguration?: { model: string; effort?: string }; } export interface FakeTurn { @@ -540,7 +541,7 @@ export function createFakeRuntime(): FakeRuntimeHarness { refuse(); }, turn: { - promptStarted: Promise.resolve(), + promptStarted: Promise.resolve(script.observedConfiguration), requestId: input.requestId, events: { [Symbol.asyncIterator](): AsyncIterator { diff --git a/packages/acp/tests/host-conversation.test.ts b/packages/acp/tests/host-conversation.test.ts index 9c39891fc..16191da45 100644 --- a/packages/acp/tests/host-conversation.test.ts +++ b/packages/acp/tests/host-conversation.test.ts @@ -390,6 +390,35 @@ function answer(settled: Result>): string { } describe("Tier HC — a host conversation across the provider's own commit window", () => { + it("reopening retains the started attachment's verbatim settings", function* () { + const target = host(); + const history = new InMemoryStream(); + target.harness.script({}); + target.harness.script({ + observedConfiguration: { model: "claude-fable-5-2", effort: "high" }, + result: { status: "failed", error: { message: "failed after prompt dispatch" } }, + }); + const ran = yield* withConversation(history, target.installation, function* (chat) { + expect((yield* chat.prompt("initial turn")).ok).toBe(true); + expect((yield* chat.prompt("continued turn")).ok).toBe(false); + }); + expect(ran.ok).toBe(true); + const { stream, lines } = yield* reread(history); + const priorEnsures = target.harness.ensureCalls.length; + const reopened = yield* withConversation(stream, target.installation, function* () { + const saved = turns(yield* stream.readAll()); + expect(saved.at(-1)?.record.configuration).toEqual({ + model: "claude-fable-5-2", + effort: "high", + }); + expect(saved.at(-1)?.record.agentSessionId).toBe(NATIVE); + }); + expect(reopened.ok).toBe(true); + expect(target.harness.ensureCalls).toHaveLength(priorEnsures); + expect(asked(target)).toEqual(["initial turn", "continued turn"]); + expect((yield* stream.readAll()).map(serializeDurableEvent)).toEqual(lines); + }); + /** * The window SM9 describes, met by a conversation rather than by a document. * diff --git a/packages/acp/vendor/acpx/MANIFEST.json b/packages/acp/vendor/acpx/MANIFEST.json index 7d81d1ee0..3bc836b20 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": "af34f38d9efc7db560c793637f5a2e19360e08a75318984d57e7832d23e2c0d2" }, { "path": "generated/agent-registry-CxpAF3nI.js", @@ -57,17 +57,17 @@ { "path": "generated/queue-owner-runtime-ucHvXJ33.js", "kind": "generated", - "sha256": "ed1eb5498c31fffbd843afae8d540361a335006ce8876881ccebb87126885a07" + "sha256": "6d54f8c5c19a166b2295bf680ffe2e69158096c85d974d967b453164748c13c3" }, { "path": "generated/runtime.d.ts", "kind": "generated", - "sha256": "45d3d96fafbcd677e20b11d4dc38b23f37ca9237360f47858e7f468cd597d04f" + "sha256": "4009a64570169728896d78e82b2ae41affeed23f60f7abefe095d7b50e889bf3" }, { "path": "generated/runtime.js", "kind": "generated", - "sha256": "ca6a3124680ef66b05538d91d52602bbd338ab0d8e36f483102fe2961b6d9c78" + "sha256": "5a4a3e67862999ff65d02c10de77cf5cb5d3029168a7119bf6931e8f0aba77a2" }, { "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..3829870fa 100644 --- a/packages/acp/vendor/acpx/PROVENANCE.md +++ b/packages/acp/vendor/acpx/PROVENANCE.md @@ -249,3 +249,16 @@ Normalization, record readback and IPC keep that field. This changes launch-opti plumbing only; the Claude adapter and SDK producer inputs are unchanged. The `claude-workflow-role` CLI profile selects these options for workflow roles. Ordinary interactive sessions retain their original defaults. + +### Claude configuration on the connected session + +The `XMD Claude configuration:` changes apply to the maintained adapter +advertising its native observation request. Load and resume omit saved startup +model metadata. Replay skips the saved model and the retained/current model +and effort control keys. In-process transactions can read that connection's +model, context window and attested effort. Immediately before prompt dispatch, +ACPX verifies requested configuration against the attachment about to receive +the prompt. The prompt-written signal carries that attachment's observation. +For an effort request, the transaction reads live effort choices and the +connected adapter validates that control again on dispatch. +Exact model restoration supplies the transaction's prior context window. diff --git a/packages/acp/vendor/acpx/generated/queue-owner-runtime-ucHvXJ33.js b/packages/acp/vendor/acpx/generated/queue-owner-runtime-ucHvXJ33.js index d95b9fb95..95dd64d41 100644 --- a/packages/acp/vendor/acpx/generated/queue-owner-runtime-ucHvXJ33.js +++ b/packages/acp/vendor/acpx/generated/queue-owner-runtime-ucHvXJ33.js @@ -3081,9 +3081,15 @@ var AcpClient = class { } /** XMD requested model: only its presence reaches Claude load/resume metadata, never session/new. */ continuationMeta() { - const meta = this.sessionMeta(); + // XMD Claude configuration: saved startup model applies only to session/new. const { command, args } = resolveAgentCommandParts(this.options.agentCommand, this.options.agentArgv); - if (this.options.requestedModel === void 0 || !isClaudeAcpCommand(command, args)) return meta; + const claude = isClaudeAcpCommand(command, args); + const options = this.options.sessionOptions; + const meta = claude && this.supportsClaudeConfiguration() + ? buildClaudeCodeOptionsMeta({ ...options, model: void 0 }, true) + : this.sessionMeta(); + if (this.options.requestedModel === void 0 || !claude) return meta; + // XMD Claude configuration: explicit intent is metadata only. return { ...meta, "executablemd.has-explicit-model/v1": true @@ -3265,14 +3271,27 @@ var AcpClient = class { modeId }), authority, (error) => maybeWrapSessionControlError("session/set_mode", error, `for mode "${modeId}"`)); } - async setSessionConfigOption(sessionId, configId, value, models, authority) { + // XMD Claude configuration: negotiate the maintained adapter's read on this client. + supportsClaudeConfiguration() { + return this.initResult?.agentCapabilities?._meta?.["executablemd.claude-configuration/v1"] === true; + } + async observeClaudeConfiguration(sessionId, requestedModel, authority, inspectEffort) { + if (!this.supportsClaudeConfiguration()) return; + const connection = this.getConnection(); + return await this.runConnectionRequest(() => connection.agent.request("_executablemd/session_configuration", { + sessionId, requestedModel, inspectEffort + }), authority); + } + async setSessionConfigOption(sessionId, configId, value, models, authority, restoreContextWindow) { + // XMD Claude configuration: only rollback can restore an unlisted exact model. assertControlAuthority(authority); - const resolvedValue = models?.configId === configId ? this.resolveSessionModelId(value, models) : value; + const resolvedValue = restoreContextWindow === void 0 && models?.configId === configId ? this.resolveSessionModelId(value, models) : value; const connection = this.getConnection(); return normalizeConfigOptionAcknowledgement(await this.runConnectionRequest(() => connection.agent.request(methods.agent.session.setConfigOption, { sessionId, configId, - value: resolvedValue + value: resolvedValue, + ...restoreContextWindow === void 0 ? {} : { _meta: { "executablemd.restore-context/v1": restoreContextWindow } } }), authority, (error) => maybeWrapSessionControlError("session/set_config_option", error, `for "${configId}"="${value}"`))); } async setSessionModel(sessionId, modelId, models, authority) { @@ -5246,10 +5265,21 @@ async function replaySessionPreferences(params) { }); const effectiveModels = resolveModeReplayModels(modeMetadata, params.sessionModels); const replacingModel = replacesModel(params.replacingConfigOption, effectiveModels, params.originalAcpx); + // XMD Claude configuration: retain the active native model and effort on load/resume. + const observes = !params.createdFreshSession && params.client.supportsClaudeConfiguration?.(); + const priorControls = params.originalAcpx?.config_options ?? []; + const currentControls = params.record.acpx?.config_options ?? []; + const observedKeys = new Set(["model", "effort", ...[...priorControls, ...currentControls] + .filter((option) => option.category === "model" || option.category === "thought_level") + .map((option) => option.id)]); + // XMD Claude configuration: skip stale entries before replay checks or setters. + const desiredConfigOptions = observes + ? Object.fromEntries(Object.entries(params.desiredConfigOptions).filter(([key]) => !observedKeys.has(key))) + : replacingModel ? {} : params.desiredConfigOptions; modelReplay = await replayDesiredModel({ client: params.client, sessionId: params.sessionId, - desiredModelId: replacingModel ? void 0 : params.desiredModelId, + desiredModelId: observes || replacingModel ? void 0 : params.desiredModelId, replay, previousSessionId: params.originalSessionId, record: params.record, @@ -5263,7 +5293,8 @@ async function replaySessionPreferences(params) { client: params.client, record: params.record, sessionId: params.sessionId, - desiredConfigOptions: replacingModel ? {} : params.desiredConfigOptions, + // XMD Claude configuration: unrelated controls retain their replay owner. + desiredConfigOptions, replay, acceptedConfigOptions: modelReplay.configOptions, replacingConfigOption: replacingModel ? void 0 : params.replacingConfigOption, diff --git a/packages/acp/vendor/acpx/generated/runtime.d.ts b/packages/acp/vendor/acpx/generated/runtime.d.ts index b335af68b..cc1f312f7 100644 --- a/packages/acp/vendor/acpx/generated/runtime.d.ts +++ b/packages/acp/vendor/acpx/generated/runtime.d.ts @@ -123,6 +123,8 @@ type AcpRuntimeTurnInput = AcpControlAuthority & { onPermissionRequest?: AcpPermissionHandler; /** Handles ACP elicitation requests owned by this prompt turn. */ onElicitation?: AcpElicitationHandler; + /** XMD Claude configuration: the effort requested on the final attachment. */ + requestedEffort?: string; /** XMD requested model: the model requested by this turn's use; see `AcpRuntimeEnsureInput.requestedModel`. */ requestedModel?: string; }; @@ -366,7 +368,8 @@ interface AcpRuntimeTurn { readonly materialized: Promise; readonly requestId: string; /** Resolves after the underlying writable transport accepts the prompt request. */ - readonly promptStarted: Promise; + // XMD Claude configuration: the exact settings observed for this written prompt. + readonly promptStarted: Promise; readonly events: AsyncIterable; /** * Canonical completion signal for the turn. Resolves only after final record @@ -408,6 +411,10 @@ interface AcpRuntime { }): Promise | AcpRuntimeCapabilities; getStatus?(input: { handle: AcpRuntimeHandle; + // XMD Claude configuration: read the actual backend for an in-place transaction. + verifyConfiguration?: boolean; + requestedModel?: string; + inspectEffort?: boolean; signal?: AbortSignal; }): Promise; /** Authority gates dispatch; an issued control still settles its response and saved state. */ @@ -423,6 +430,8 @@ interface AcpRuntime { handle: AcpRuntimeHandle; key: string; value: string; + /** XMD Claude configuration: prior native window for model restoration. */ + restoreContextWindow?: number; /** XMD requested model: the model requested by this write's use; see `AcpRuntimeEnsureInput.requestedModel`. */ requestedModel?: string; }): Promise; @@ -779,6 +788,10 @@ export declare class SharedAcpRuntime { runTurn(input: AcpRuntimeTurnInput): AsyncGenerator; getStatus(input: { handle: AcpRuntimeHandle; + // XMD Claude configuration: read the actual backend for an in-place transaction. + verifyConfiguration?: boolean; + requestedModel?: string; + inspectEffort?: boolean; }): Promise; getCapabilities(input?: { handle?: AcpRuntimeHandle; @@ -808,6 +821,8 @@ export declare class SharedAcpRuntime { handle: AcpRuntimeHandle; key: string; value: string; + /** XMD Claude configuration: prior native window for model restoration. */ + restoreContextWindow?: number; /** XMD requested model: the model requested by this write's use; see `AcpRuntimeEnsureInput.requestedModel`. */ requestedModel?: string; }): Promise; @@ -862,7 +877,8 @@ export declare class AcpxRuntime implements AcpxRuntimeLike { startTurn(input: AcpRuntimeTurnInput): { requestId: string; readonly materialized: Promise; - readonly promptStarted: Promise; + // XMD Claude configuration: the exact settings observed for this written prompt. + readonly promptStarted: Promise; events: { [Symbol.asyncIterator](): AsyncGenerator; }; @@ -880,6 +896,10 @@ export declare class AcpxRuntime implements AcpxRuntimeLike { }): Promise; getStatus(input: { handle: AcpRuntimeHandle; + // XMD Claude configuration: read the actual backend for an in-place transaction. + verifyConfiguration?: boolean; + requestedModel?: string; + inspectEffort?: boolean; signal?: AbortSignal; }): Promise; setMode(input: AcpControlAuthority & { @@ -894,6 +914,8 @@ export declare class AcpxRuntime implements AcpxRuntimeLike { handle: AcpRuntimeHandle; key: string; value: string; + /** XMD Claude configuration: prior native window for model restoration. */ + restoreContextWindow?: number; /** XMD requested model: the model requested by this write's use; see `AcpRuntimeEnsureInput.requestedModel`. */ requestedModel?: string; }): Promise; diff --git a/packages/acp/vendor/acpx/generated/runtime.js b/packages/acp/vendor/acpx/generated/runtime.js index c6774a03b..42f2e3941 100644 --- a/packages/acp/vendor/acpx/generated/runtime.js +++ b/packages/acp/vendor/acpx/generated/runtime.js @@ -49,6 +49,11 @@ function resolveSupportedConfigOptionId(record, configId) { const supportedText = supported.length > 0 ? supported.join(", ") : "none"; throw new AcpRuntimeError("ACP_BACKEND_UNSUPPORTED_CONTROL", `ACP session ${record.acpxRecordId} does not advertise config option '${configId}'. Supported config options: ${supportedText}.`); } +// XMD Claude configuration: the connected adapter validates live effort support. +function resolveControlConfigOptionId(record, key, restoreContextWindow) { + if (restoreContextWindow !== void 0 || key === "effort" && record.agentCapabilities?._meta?.["executablemd.claude-configuration/v1"] === true) return key; + return resolveSupportedConfigOptionId(record, key); +} // src/runtime/public/shared.ts function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); @@ -1798,7 +1803,15 @@ var AcpRuntimeManager = class { stopReason: "cancelled" }; else { - const response = await this.runRuntimePrompt(task, turn, sessionId); + // XMD Claude configuration: read the actual attachment before prompt dispatch. + const observed = await withTimeout(turn.client.observeClaudeConfiguration(sessionId, task.input.requestedModel, task.input), task.input.timeoutMs ?? this.options.timeoutMs); + if (observed && (observed.matches !== true || observed.model && task.input.requestedEffort !== void 0 && observed.effort !== task.input.requestedEffort)) { + throw new Error("Claude did not verify the requested configuration on the prompt attachment."); + } + const configuration = typeof observed?.model === "string" && observed.model.length > 0 + ? { model: observed.model, ...(typeof observed.effort === "string" ? { effort: observed.effort } : {}) } : void 0; + const response = this.cancelRuntimeTurnBeforePrompt(task) ? { stopReason: "cancelled" } : + await this.runRuntimePrompt(task, turn, sessionId, configuration); // XMD prompt usage: selected before the response metadata is projected. Object.assign(usage, xmdPromptUsageReadings(response)); this.updateCompletedRuntimeTurn(turn); @@ -1820,7 +1833,8 @@ var AcpRuntimeManager = class { } task.settleResult(withXmdPromptUsage(terminalResult, usage)); } - async runRuntimePrompt(task, turn, sessionId) { + async runRuntimePrompt(task, turn, sessionId, configuration) { + // XMD Claude configuration: carry the observation only after the prompt is written. return await runPromptTurn({ client: turn.client, sessionId, @@ -1828,7 +1842,7 @@ var AcpRuntimeManager = class { timeoutMs: task.input.timeoutMs ?? this.options.timeoutMs, conversation: turn.conversation, promptMessageId: turn.promptMessageId, - onPromptRequestWritten: () => task.promptStarted.resolve(), + onPromptRequestWritten: () => task.promptStarted.resolve(configuration), onElicitation: task.input.onElicitation, onPermissionRequest: task.input.onPermissionRequest, authority: task.input @@ -2195,9 +2209,23 @@ var AcpRuntimeManager = class { yield* turn.events; yield legacyTerminalEventFromTurnResult(await turn.result); } - getStatus(handle) { + // XMD Claude configuration: configuration transactions read the connected backend. + getStatus(handle, sessionMode, verifyConfiguration, requestedModel, inspectEffort) { this.assertOpen(); - return this.trackTask(this.readStatus(handle)); + if (!verifyConfiguration) return this.trackTask(this.readStatus(handle)); + const recordId = handle.acpxRecordId ?? handle.sessionKey; + return this.withManagerLock(this.runtimeOperationLocks, recordId, async () => { + const record = await this.requireRecord(recordId); + if (!record.agentCapabilities?._meta?.["executablemd.claude-configuration/v1"]) return await this.readStatus(handle); + // XMD Claude configuration: a cold read uses the normal control attachment owner. + return await this.withRuntimeControlSession(record, sessionMode, async ({ client, sessionId, record: connectedRecord }) => { + const status = runtimeStatusFromRecord(connectedRecord); + const observed = await withTimeout(client.observeClaudeConfiguration(sessionId, requestedModel, void 0, inspectEffort), this.options.timeoutMs); + status.details.claudeConfiguration = observed; + if (observed?.configOptions !== void 0) status.details.configOptions = observed.configOptions; + return status; + }, void 0, void 0, requestedModel); + }); } async readStatus(handle) { const recordId = handle.acpxRecordId ?? handle.sessionKey; @@ -2246,11 +2274,12 @@ var AcpRuntimeManager = class { }, { replacingConfigOption: { key: "model" } }, authority); } // XMD requested model: ordinary and restoring writes carry the same request. - async setConfigOption(handle, key, value, sessionMode = "persistent", authority, requestedModel) { + async setConfigOption(handle, key, value, sessionMode = "persistent", authority, requestedModel, restoreContextWindow) { + // XMD Claude configuration: carry exact context for an owned restoration. const recordId = handle.acpxRecordId ?? handle.sessionKey; - return await this.withManagerLock(this.runtimeOperationLocks, recordId, async () => this.setConfigOptionWithOwnership(handle, key, value, sessionMode, authority, requestedModel), authority); + return await this.withManagerLock(this.runtimeOperationLocks, recordId, async () => this.setConfigOptionWithOwnership(handle, key, value, sessionMode, authority, requestedModel, restoreContextWindow), authority); } - async setConfigOptionWithOwnership(handle, key, value, sessionMode, authority, requestedModel) { + async setConfigOptionWithOwnership(handle, key, value, sessionMode, authority, requestedModel, restoreContextWindow) { const record = await this.requireRecord(handle.acpxRecordId ?? handle.sessionKey); assertControlAuthority(authority); const controller = this.activeControllers.get(record.acpxRecordId); @@ -2259,7 +2288,8 @@ var AcpRuntimeManager = class { return response; } return await this.withRuntimeControlSession(record, sessionMode, async ({ client, sessionId, record: connectedRecord }) => { - const configId = resolveSupportedConfigOptionId(connectedRecord, key); + // XMD Claude configuration: effort support can be established on this client. + const configId = resolveControlConfigOptionId(connectedRecord, key, restoreContextWindow); const models = advertisedModelState(connectedRecord.acpx); const { modelConfigId, resolvedValue } = resolveRequestedConfigOption({ configId, @@ -2267,12 +2297,13 @@ var AcpRuntimeManager = class { models, agentCommand: connectedRecord.agentCommand }); - const response = await client.setSessionConfigOption(sessionId, configId, value, models, authority); + // XMD Claude configuration: rollback changes the exact prior wire model and context. + const response = await client.setSessionConfigOption(sessionId, configId, value, models, authority, restoreContextWindow); connectedRecord.acpx = applyConfigOptionSelection(connectedRecord.acpx, configId, value, response, modelConfigId, resolvedValue); return response; }, { replacingConfigOption: { key, - resolve: (connectedRecord) => resolveSupportedConfigOptionId(connectedRecord, key) + resolve: (connectedRecord) => resolveControlConfigOptionId(connectedRecord, key, restoreContextWindow) // XMD requested model: this control may construct the attaching client. } }, authority, requestedModel); } @@ -2936,6 +2967,8 @@ var AcpxRuntime = class { assertActive: input.assertActive, onElicitation: input.onElicitation, onPermissionRequest: input.onPermissionRequest, + // XMD Claude configuration: verify the requested effort on this attachment. + requestedEffort: input.requestedEffort, // XMD requested model: consumed only by this attaching client. requestedModel })); @@ -2987,9 +3020,10 @@ var AcpxRuntime = class { const { handle } = this.resolveManagerHandle(input.handle); return capabilitiesFromRecord(await this.options.sessionStore.load(handle.acpxRecordId ?? handle.sessionKey)); } + // XMD Claude configuration: direct in-process verification; shared status remains passive. async getStatus(input) { - const { handle } = this.resolveManagerHandle(input.handle); - return await (await this.getManager()).getStatus(handle); + const { handle, state } = this.resolveManagerHandle(input.handle); + return await (await this.getManager()).getStatus(handle, state.mode, input.verifyConfiguration, input.requestedModel, input.inspectEffort); } async setMode(input) { const { handle, state } = this.resolveManagerHandle(input.handle); @@ -3003,7 +3037,7 @@ var AcpxRuntime = class { const { handle, state } = this.resolveManagerHandle(input.handle); // XMD requested model: validate before manager work begins. const requestedModel = requestedModelOf(input); - return await (await this.getManager()).setConfigOption(handle, input.key, input.value, state.mode, input, requestedModel); + return await (await this.getManager()).setConfigOption(handle, input.key, input.value, state.mode, input, requestedModel, input.restoreContextWindow); } async cancel(input) { const { handle } = this.resolveManagerHandle(input.handle); diff --git a/packages/acp/vendor/adapters/MANIFEST.json b/packages/acp/vendor/adapters/MANIFEST.json index 5d51f9955..d74f65165 100644 --- a/packages/acp/vendor/adapters/MANIFEST.json +++ b/packages/acp/vendor/adapters/MANIFEST.json @@ -41,8 +41,8 @@ "license": "Apache-2.0", "contract": "_meta.claudeCode.assistantMessageUuid", "materializationContract": "session_info_update _meta[executablemd.session-materialization/v1]", - "byteLength": 2006701, - "sha256": "7bb5296c72adb4268f8dc9ed484b53fd2aa6b1b16ab30868d7b8dfb63501257e", + "byteLength": 2010285, + "sha256": "cb4a7b653a041c2b7d3aa13d4dfbaee891ab4a75cbdb0b65d066cce761895783", "files": [ "package/LICENSE", "package/README.md", diff --git a/packages/acp/vendor/adapters/PROVENANCE.md b/packages/acp/vendor/adapters/PROVENANCE.md index 580ce35a6..bf64b3767 100644 --- a/packages/acp/vendor/adapters/PROVENANCE.md +++ b/packages/acp/vendor/adapters/PROVENANCE.md @@ -266,19 +266,18 @@ verified build input. They, the pristine SDK and the transform are absent from the runtime archive; repository preparation reproduces the shipped bytes from pinned public inputs instead. -### Claude resumed model under an explicit use - -The readable `claude/adapter.patch` extends producer -`e3a6ceb7a50e1151fb49322ea83d331a4c8b74ca` with one local change for #1177; no -upstream commit carries it. A `session/load` or `session/resume` whose `_meta` -carries `"executablemd.has-explicit-model/v1": true` belongs to a client use -that names its own model. On that branch only, `createSession` skips -`getAvailableModels`' environment/settings reassertion and calls -`observeResumedModel`: the backend's `getContextUsage` model is the current -model selection verbatim, with the offered catalog and allowlist unchanged. A -failed or empty report, or one no offered model names exactly, refuses with an -invalid-request error before any prompt, so a client never reads it as a missing -conversation to replace. The marker is never passed into SDK options. Fresh, -unmarked and effort-only initialization keep the existing priority. The recipe -records the changed patch, `src/acp-agent.ts` postimage, `dist/acp-agent.js` -runtime and output hashes; source, SDK and compiler pins are unchanged. +### Claude configuration on load and resume + +The maintained patch reads the backend model verbatim for a saved conversation. +The original catalog remains available for deliberate selection. The adapter +reads live effort without applying a settings-derived default on resume. +`_executablemd/session_configuration` reads the model and context from the +connected Query and uses the offered model's SDK-provided identity when verifying +an explicit alias. A requested effort change uses the SDK effort choices for +the observed model, including a verified alias. The connected Query attests +the current effort before the setter can run. A context variant requires +matching native context evidence before the user prompt. The first prompt +cannot establish that evidence for a +fresh variant selection, so the check refuses. Recipe inputs and the built +output record the maintained patch independently of the unchanged source, SDK +and compiler pins. diff --git a/packages/acp/vendor/adapters/claude/adapter.patch b/packages/acp/vendor/adapters/claude/adapter.patch index e9f2828c6..36799f2e2 100644 --- a/packages/acp/vendor/adapters/claude/adapter.patch +++ b/packages/acp/vendor/adapters/claude/adapter.patch @@ -1,5 +1,5 @@ diff --git a/src/acp-agent.ts b/src/acp-agent.ts -index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804b711d5c4 100644 +index e32f603e7cb85544a9ebf108489fcf98932d14a2..eb8647a97c3ac3a0fbe5cc535ef437e4df16082d 100644 --- a/src/acp-agent.ts +++ b/src/acp-agent.ts @@ -81,7 +81,7 @@ import { @@ -57,7 +57,15 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 input: Pushable; cancelled: boolean; /** FIFO of in-flight prompts. The head is the turn the SDK is currently -@@ -1175,6 +1200,13 @@ const SESSION_ENDED_MESSAGE = "The Claude Agent session has ended. Please start +@@ -625,6 +650,7 @@ export type Session = { + * happens to equal DEFAULT_CONTEXT_WINDOW must not be mistaken for "unseeded" + * and clobbered by a "1m" text match. */ + contextWindowAuthoritative: boolean; ++ observing: boolean; + /** Stable identifier of the LLM backend this session's query was created + * against, derived from the routing-relevant vars of the exact `env` handed + * to the SDK at query creation (see {@link providerCacheKeyFor}). The context +@@ -1175,6 +1201,13 @@ const SESSION_ENDED_MESSAGE = "The Claude Agent session has ended. Please start // message and without invoking the model. const LOCAL_ONLY_COMMANDS = new Set(["/context", "/heapdump", "/extra-usage"]); @@ -71,7 +79,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 // The Claude SDK persists local slash command invocations (e.g. `/model`) and // their output as user messages in the session transcript, wrapping the // payload in these XML-like markers that the CLI uses for its own display. -@@ -1389,6 +1421,19 @@ function raceWithAbort(operation: Promise, signal: AbortSignal): Promise(operation: Promise, signal: AbortSignal): Promise | null = null; @@ -100,7 +108,15 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 private readonly exitPlan: ExitPlanCoordinator; /** Grace period before a `session/cancel` forces a wedged prompt loop to * return "cancelled". See {@link DEFAULT_FORCE_CANCEL_GRACE_MS}. Mutable so -@@ -2350,6 +2397,30 @@ export class ClaudeAcpAgent { +@@ -1569,6 +1617,7 @@ export class ClaudeAcpAgent { + protocolVersion: 1, + agentCapabilities: { + _meta: { ++ "executablemd.claude-configuration/v1": true, + claudeCode: { + promptQueueing: true, + }, +@@ -2350,6 +2399,30 @@ export class ClaudeAcpAgent { resetTurnScratch(); }; @@ -131,7 +147,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 /** Ensure there is an active turn before a user-turn result that carries no * echo to activate it, by promoting the queue head. Most turns are * activated by their replayed user message before their result, but some -@@ -2577,7 +2648,32 @@ export class ClaudeAcpAgent { +@@ -2577,7 +2650,32 @@ export class ClaudeAcpAgent { // carries its own copy. session.emittedAssistantText = false; } @@ -165,7 +181,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 }; /** Reject the active turn (auth required, error result, …) without tearing -@@ -2674,7 +2770,7 @@ export class ClaudeAcpAgent { +@@ -2674,7 +2772,7 @@ export class ClaudeAcpAgent { try { while (true) { @@ -174,7 +190,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 .next() .then((result) => ({ kind: "message" as const, result })); const nextMessage = pendingNext; -@@ -2845,6 +2941,7 @@ export class ClaudeAcpAgent { +@@ -2845,6 +2943,7 @@ export class ClaudeAcpAgent { const queued = findUnsettledTurn(frame.command_uuid); if (queued) { queued.commandStarted = true; @@ -182,7 +198,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 } // ...and promote an already-orphaned command: once dispatched, // a bare `cancelled` no longer means "dropped without running". -@@ -4273,6 +4370,7 @@ export class ClaudeAcpAgent { +@@ -4273,6 +4372,7 @@ export class ClaudeAcpAgent { // result re-emit the answer. activateTurn(queued); } @@ -190,7 +206,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 break; } if ("isReplay" in message && message.isReplay) { -@@ -4297,6 +4395,17 @@ export class ClaudeAcpAgent { +@@ -4297,6 +4397,17 @@ export class ClaudeAcpAgent { // window. Subagent messages are excluded to keep the snapshot // aligned with what the user's current selection is producing. if (message.type === "assistant" && message.parent_tool_use_id === null) { @@ -208,7 +224,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 lastAssistantUsage = snapshotFromUsage(message.message.usage); lastAssistantTotalUsage = totalTokens(lastAssistantUsage); session.contextUsedTokens = lastAssistantTotalUsage; -@@ -4946,9 +5055,21 @@ export class ClaudeAcpAgent { +@@ -4946,9 +5057,21 @@ export class ClaudeAcpAgent { } session.queryClosed = true; session.consumer = undefined; @@ -233,7 +249,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 } /** Cleanly tear down a session: cancel in-flight work, release stream -@@ -4958,7 +5079,12 @@ export class ClaudeAcpAgent { +@@ -4958,7 +5081,12 @@ export class ClaudeAcpAgent { if (!session) { return; } @@ -247,7 +263,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 // cancel() arms the force-cancel floor and interrupts gracefully, but a // wedged consumer only wakes when `cancelController` aborts — closeQueryStream // below doesn't touch it. Since we're tearing the session down anyway, wake -@@ -4968,18 +5094,65 @@ export class ClaudeAcpAgent { +@@ -4968,18 +5096,65 @@ export class ClaudeAcpAgent { // until it fires). disarmForceCancel(session); session.cancelController?.abort(); @@ -316,7 +332,101 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 } async closeSession(params: CloseSessionRequest): Promise { -@@ -5997,10 +6170,14 @@ export class ClaudeAcpAgent { +@@ -5004,6 +5179,47 @@ export class ClaudeAcpAgent { + return this.sessionModes.setSessionMode(params); + } + ++ async observeSessionConfiguration({ sessionId, requestedModel, inspectEffort }: ConfigurationCheck) { ++ const session = this.sessions[sessionId]; ++ if (!session || session.queryClosed) { ++ throw RequestError.resourceNotFound(sessionId); ++ } ++ const offered = requestedModel === undefined ? undefined : ++ session.modelInfos.find((model) => model.value === requestedModel); ++ const variant = offered && (contextHintOf(offered.value) ?? contextHintOf(offered.resolvedModel ?? "")); ++ if (!session.observing) { ++ return { ++ variantUnavailable: Boolean(variant), ++ matches: requestedModel === undefined || ++ (offered !== undefined && !variant && session.models.currentModelId === requestedModel), ++ }; ++ } ++ const observed = await observeResumedModel(session.query, session.modelInfos); ++ const model = observed.modelState.currentModelId; ++ const contextWindow = observed.resumedContextWindow; ++ const effort = await readNativeEffort(session.query); ++ if (contextWindow !== null) { ++ session.contextWindowSize = contextWindow; ++ session.contextWindowAuthoritative = true; ++ } ++ const matches = requestedModel === undefined || (offered !== undefined && ++ (model === offered.value || ++ (variant && (model === stripContextHints(offered.value) || ++ stripContextHints(model) === stripContextHints(offered.value))) || ++ (offered.resolvedModel !== undefined && ++ (model === offered.resolvedModel || (variant && ++ stripContextHints(model) === stripContextHints(offered.resolvedModel))))) && ++ (!variant || contextWindow === Number(variant.slice(0, -1)) * 1_000_000)); ++ if (inspectEffort || requestedModel !== undefined) { ++ const option = effortConfigOption( ++ observedEffortModel(session.modelInfos, model, contextWindow), effort, ++ ); ++ session.configOptions = session.configOptions.filter((entry) => entry.id !== EFFORT_CONFIG_ID); ++ if (option !== undefined) session.configOptions.push(option); ++ } ++ return { model, contextWindow, effort, matches, configOptions: session.configOptions }; ++ } ++ + async setSessionConfigOption( + params: SetSessionConfigOptionRequest, + ): Promise { +@@ -5019,6 +5235,20 @@ export class ClaudeAcpAgent { + throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE); + } + ++ const restoreWindow = params._meta?.["executablemd.restore-context/v1"]; ++ if (params.configId === EFFORT_CONFIG_ID && typeof restoreWindow === "number" && ++ session.observing && typeof params.value === "string") { ++ await session.query.applyFlagSettings({ effortLevel: toSdkEffortLevel(params.value) }); ++ return { configOptions: session.configOptions }; ++ } ++ if (params.configId === EFFORT_CONFIG_ID && session.observing) { ++ const observation = await this.observeSessionConfiguration({ ++ sessionId: params.sessionId, inspectEffort: true, ++ }); ++ if (observation.effort === undefined) { ++ throw RequestError.invalidParams({ message: "Claude could not report its prior effort" }); ++ } ++ } + const option = session.configOptions.find((o) => o.id === params.configId); + if (!option) { + throw new Error(`Unknown config option: ${params.configId}`); +@@ -5036,6 +5266,15 @@ export class ClaudeAcpAgent { + throw new Error(`Invalid value for config option ${params.configId}: ${params.value}`); + } + ++ if (params.configId === MODEL_CONFIG_ID && typeof restoreWindow === "number" && session.observing) { ++ const hinted = restoreWindow >= 1_000_000 && !contextHintOf(params.value) ++ ? `${params.value}[${restoreWindow / 1_000_000}m]` ++ : params.value; ++ await session.query.setModel(hinted); ++ await this.applyConfigOptionValue(params.sessionId, session, params.configId, params.value); ++ return { configOptions: session.configOptions }; ++ } ++ + const allValues = + "options" in option && Array.isArray(option.options) + ? option.options.flatMap((o) => ("options" in o ? o.options : [o])) +@@ -5809,7 +6048,7 @@ export class ClaudeAcpAgent { + const newEffortOpt = session.configOptions.find((o) => o.id === EFFORT_CONFIG_ID); + const newEffort = + typeof newEffortOpt?.currentValue === "string" ? newEffortOpt.currentValue : undefined; +- if (newEffort !== currentEffort) { ++ if (!session.observing && newEffort !== currentEffort) { + await session.query.applyFlagSettings({ + effortLevel: toSdkEffortLevel(newEffort), + }); +@@ -5997,10 +6236,14 @@ export class ClaudeAcpAgent { if (existingSession) { const fingerprint = computeSessionFingerprint(params); if (fingerprint === existingSession.sessionFingerprint) { @@ -331,7 +441,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 }; } -@@ -6026,6 +6203,7 @@ export class ClaudeAcpAgent { +@@ -6026,6 +6269,7 @@ export class ClaudeAcpAgent { sessionId: response.sessionId, modes: response.modes, configOptions: response.configOptions, @@ -339,7 +449,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 }; } -@@ -6058,572 +6236,751 @@ export class ClaudeAcpAgent { +@@ -6058,572 +6302,730 @@ export class ClaudeAcpAgent { } } @@ -486,9 +596,6 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 - const forwardSubagentText = - supportsSubagentTranscript(this.clientCapabilities) || - userProvidedOptions?.forwardSubagentText === true; -- -- // Configure thinking behavior from environment variable -- const thinking = resolveThinkingConfig(process.env.MAX_THINKING_TOKENS, this.logger); + settingsManager = new SettingsManager(params.cwd, { + logger: this.logger, + }); @@ -497,8 +604,8 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + throw new Error("Claude adapter closed during session setup"); + } -- // Parse model configuration from environment (e.g. Bedrock model overrides) -- const modelConfig = parseModelConfig(process.env.CLAUDE_MODEL_CONFIG); +- // Configure thinking behavior from environment variable +- const thinking = resolveThinkingConfig(process.env.MAX_THINKING_TOKENS, this.logger); + const mcpServers: Record = {}; + if (Array.isArray(params.mcpServers)) { + for (const server of params.mcpServers) { @@ -525,13 +632,8 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + } + } -- // Elicitation modes the connected client advertised. We only forward -- // elicitations (and only re-enable AskUserQuestion) for modes the client -- // can actually render. -- const elicitationSupport: ElicitationSupport = { -- form: !!this.clientCapabilities?.elicitation?.form, -- url: !!this.clientCapabilities?.elicitation?.url, -- }; +- // Parse model configuration from environment (e.g. Bedrock model overrides) +- const modelConfig = parseModelConfig(process.env.CLAUDE_MODEL_CONFIG); + let systemPrompt: Options["systemPrompt"] = { type: "preset", preset: "claude_code" }; + if (params._meta?.systemPrompt) { + const customPrompt = params._meta.systemPrompt; @@ -552,6 +654,41 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + } + } +- // Elicitation modes the connected client advertised. We only forward +- // elicitations (and only re-enable AskUserQuestion) for modes the client +- // can actually render. +- const elicitationSupport: ElicitationSupport = { +- form: !!this.clientCapabilities?.elicitation?.form, +- url: !!this.clientCapabilities?.elicitation?.url, +- }; ++ const permissionMode = resolvePermissionMode( ++ settingsManager.getSettings().permissions?.defaultMode, ++ this.logger, ++ ); ++ const initialPermissionMode = creationOpts.permissionMode ?? permissionMode; ++ ++ // Extract options from _meta if provided ++ const sessionMeta = params._meta as NewSessionMeta | undefined; ++ const observing = creationOpts.resume !== undefined && !creationOpts.forkSession; ++ const userProvidedOptions = sessionMeta?.claudeCode?.options; ++ const forwardSubagentText = ++ supportsSubagentTranscript(this.clientCapabilities) || ++ userProvidedOptions?.forwardSubagentText === true; ++ ++ // Configure thinking behavior from environment variable ++ const thinking = resolveThinkingConfig(process.env.MAX_THINKING_TOKENS, this.logger); ++ ++ // Parse model configuration from environment (e.g. Bedrock model overrides) ++ const modelConfig = parseModelConfig(process.env.CLAUDE_MODEL_CONFIG); ++ ++ // Elicitation modes the connected client advertised. We only forward ++ // elicitations (and only re-enable AskUserQuestion) for modes the client ++ // can actually render. ++ const elicitationSupport: ElicitationSupport = { ++ form: !!this.clientCapabilities?.elicitation?.form, ++ url: !!this.clientCapabilities?.elicitation?.url, ++ }; + - // AskUserQuestion surfaces as a `permission_ask_user_question` dialog that - // we render as a form elicitation. Without form-elicitation support there - // is no way to present it over ACP, so keep it disabled in that case. @@ -580,33 +717,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 - ...(userProvidedOptions?.additionalDirectories ?? []), - ...acpAdditionalDirectories, - ]; -+ const permissionMode = resolvePermissionMode( -+ settingsManager.getSettings().permissions?.defaultMode, -+ this.logger, -+ ); -+ const initialPermissionMode = creationOpts.permissionMode ?? permissionMode; -+ -+ // Extract options from _meta if provided -+ const sessionMeta = params._meta as NewSessionMeta | undefined; -+ const userProvidedOptions = sessionMeta?.claudeCode?.options; -+ const forwardSubagentText = -+ supportsSubagentTranscript(this.clientCapabilities) || -+ userProvidedOptions?.forwardSubagentText === true; -+ -+ // Configure thinking behavior from environment variable -+ const thinking = resolveThinkingConfig(process.env.MAX_THINKING_TOKENS, this.logger); -+ -+ // Parse model configuration from environment (e.g. Bedrock model overrides) -+ const modelConfig = parseModelConfig(process.env.CLAUDE_MODEL_CONFIG); -+ -+ // Elicitation modes the connected client advertised. We only forward -+ // elicitations (and only re-enable AskUserQuestion) for modes the client -+ // can actually render. -+ const elicitationSupport: ElicitationSupport = { -+ form: !!this.clientCapabilities?.elicitation?.form, -+ url: !!this.clientCapabilities?.elicitation?.url, -+ }; - +- - const fileChangeAuditSupport = supportsAgentFileChangeReport(this.clientCapabilities) - ? createFileChangeAuditSupport({ - cwd: params.cwd, @@ -821,6 +932,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + settingSources: ["user", "project", "local"], + ...(thinking !== undefined && { thinking }), + ...userProvidedOptions, ++ ...(observing && { model: undefined }), + ...(settings && { settings }), + env, + // Override certain fields that must be controlled by ACP @@ -1184,7 +1296,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + : initializationResult.models; + + const { modelState: models, resumedContextWindow } = -+ creationOpts.resume !== undefined && continuesExplicitModel(params._meta) ++ observing + ? await observeResumedModel(q, allowedModels) + : await getAvailableModels( + q, @@ -1226,33 +1338,9 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + // unfiltered list, so fall back to that before treating the model as + // unknown — otherwise auto mode would be spuriously clamped and the + // Fast-mode/Effort options hidden for a model that supports them. -+ const allowlistedModelInfo = allowedModels.find((m) => m.value === models.currentModelId); -+ const fallbackModelInfo = allowlistedModelInfo -+ ? undefined -+ : (resolveModelPreference(initializationResult.models, models.currentModelId) ?? undefined); -+ const currentModelInfo = allowlistedModelInfo ?? fallbackModelInfo; -+ // Register the fallback-resolved capabilities under the verbatim live id -+ // so every modelInfos consumer (buildConfigOptions' effort lookup, later -+ // rebuilds via session.modelInfos) agrees with the gating below. The -+ // picker options themselves come from `models.availableModels`, so this -+ // adds no selectable entry. The spread keeps every capability flag -+ // (current and future); the identity fields are overridden because the -+ // fuzzy-matched sibling's resolvedModel/displayName/description can -+ // describe a different context lane and would poison later resolvedModel -+ // matching (syncModelAfterRefusalFallback) and context-window inference -+ // (applyConfigOptionValue) if they traveled under this id. -+ const modelInfos = fallbackModelInfo -+ ? [ -+ ...allowedModels, -+ { -+ ...fallbackModelInfo, -+ value: models.currentModelId, -+ displayName: models.currentModelId, -+ description: "", -+ resolvedModel: undefined, -+ }, -+ ] -+ : allowedModels; ++ const currentModelInfo = observing ? undefined : ++ allowedModels.find((model) => model.value === models.currentModelId); ++ const modelInfos = allowedModels; + const { modes, autoModeFallbackWarningPending } = await this.sessionModes.initialize({ + query: q, + requestedMode: initialPermissionMode, @@ -1370,7 +1458,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + modes, + models, + modelInfos, -+ settingsManager.getSettings().effortLevel, ++ observing ? await readNativeEffort(q) : settingsManager.getSettings().effortLevel, + agents, + currentAgent, + fastMode, @@ -1388,7 +1476,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + // Apply the initial effort level to the SDK so it matches the UI default + const initialEffort = configOptions.find((o) => o.id === EFFORT_CONFIG_ID); + if ( -+ initialEffort && ++ !observing && initialEffort && + typeof initialEffort.currentValue === "string" && + initialEffort.currentValue !== "default" + ) { @@ -1426,7 +1514,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + const seededWindow = + resumedContextWindow !== null + ? { size: resumedContextWindow, authoritative: true } -+ : immediateContextWindow(providerCacheKey, models.currentModelId, allowlistedModelInfo); ++ : immediateContextWindow(providerCacheKey, models.currentModelId, currentModelInfo); + + const sessionIdentity = await confirmation; + // Optional SDK lookups can fall back after the reader has already refused identity. @@ -1555,6 +1643,7 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + fastModeEnabled, + fastModeDisabledReason, + abortController, ++ observing, + emitRawSDKMessages: sessionMeta?.claudeCode?.emitRawSDKMessages ?? false, + forwardSubagentText, + contextWindowSize: seededWindow.size, @@ -1620,36 +1709,132 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 } /** -@@ -7574,6 +7931,68 @@ async function readResumedLiveModel( - } - } +@@ -7143,6 +7545,55 @@ export type FastModeOptionState = { + disabledReason?: FastModeDisabledReason; + }; -+/** The continuation marker a client sends when its use names a model. */ -+const HAS_EXPLICIT_MODEL_META = "executablemd.has-explicit-model/v1"; ++function observedEffortModel( ++ models: ModelInfo[], live: string, window: number | null, ++): ModelInfo | undefined { ++ const supportsContext = (model: ModelInfo) => { ++ const hint = contextHintOf(model.value) ?? contextHintOf(model.resolvedModel ?? ""); ++ return !hint || window === Number(hint.slice(0, -1)) * 1_000_000; ++ }; ++ return models.find((row) => row.value === live && supportsContext(row)) ?? ++ models.find((row) => row.value !== "default" && ++ row.resolvedModel === live && supportsContext(row)) ?? ++ models.find((row) => row.value === "default" && ++ row.resolvedModel === live && supportsContext(row)); ++} ++ ++function effortConfigOption( ++ currentModelInfo: ModelInfo | undefined, ++ currentEffortLevel: string | undefined, ++): SessionConfigOption | undefined { ++ const supportedLevels = currentModelInfo?.supportsEffort ++ ? (currentModelInfo.supportedEffortLevels ?? []) ++ : []; ++ ++ if (supportedLevels.length === 0) return undefined; ++ const effortOptions = [ ++ { value: "default", name: "Default" }, ++ ...supportedLevels.map((level) => ({ ++ value: level, ++ name: level ++ .split(/[_-]/) ++ .map((part) => (part ? part.charAt(0).toUpperCase() + part.slice(1) : part)) ++ .join(" "), ++ })), ++ ]; + -+/** Whether this load/resume belongs to a use that explicitly names a model. */ -+function continuesExplicitModel(meta: unknown): boolean { -+ return ( -+ typeof meta === "object" && -+ meta !== null && -+ (meta as Record)[HAS_EXPLICIT_MODEL_META] === true ++ const includes = (l: string) => l === "default" || (supportedLevels as string[]).includes(l); ++ const validEffort = ++ currentEffortLevel && includes(currentEffortLevel) ? currentEffortLevel : "default"; ++ ++ return { ++ id: EFFORT_CONFIG_ID, ++ name: "Effort", ++ description: "Available effort levels for this model", ++ category: "thought_level", ++ type: "select", ++ currentValue: validEffort, ++ options: effortOptions, ++ }; ++} ++ + export function buildConfigOptions( + modes: SessionModeState, + models: SessionModelState, +@@ -7181,38 +7632,11 @@ export function buildConfigOptions( + }, + ]; + +- // Add effort level option based on the currently selected model +- const currentModelInfo = modelInfos.find((m) => m.value === models.currentModelId); +- const supportedLevels = currentModelInfo?.supportsEffort +- ? (currentModelInfo.supportedEffortLevels ?? []) +- : []; +- +- if (supportedLevels.length > 0) { +- const effortOptions = [ +- { value: "default", name: "Default" }, +- ...supportedLevels.map((level) => ({ +- value: level, +- name: level +- .split(/[_-]/) +- .map((part) => (part ? part.charAt(0).toUpperCase() + part.slice(1) : part)) +- .join(" "), +- })), +- ]; +- +- const includes = (l: string) => l === "default" || (supportedLevels as string[]).includes(l); +- const validEffort = +- currentEffortLevel && includes(currentEffortLevel) ? currentEffortLevel : "default"; +- +- options.push({ +- id: EFFORT_CONFIG_ID, +- name: "Effort", +- description: "Available effort levels for this model", +- category: "thought_level", +- type: "select", +- currentValue: validEffort, +- options: effortOptions, +- }); +- } ++ const effort = effortConfigOption( ++ modelInfos.find((model) => model.value === models.currentModelId), ++ currentEffortLevel, + ); ++ if (effort !== undefined) options.push(effort); + + // Surface the Fast mode toggle only when the current model supports it. The + // option renders as a native boolean toggle for Clients that opted in, and a +@@ -7574,6 +7998,58 @@ async function readResumedLiveModel( + } + } + ++async function readNativeEffort(query: Query): Promise { ++ if (!("getSettings" in query) || typeof query.getSettings !== "function") { ++ return undefined; ++ } ++ try { ++ const result: unknown = await query.getSettings(); ++ if (typeof result !== "object" || result === null || !("effective" in result)) { ++ return undefined; ++ } ++ const settings = result.effective; ++ if (typeof settings !== "object" || settings === null) { ++ return undefined; ++ } ++ if (!("effortLevel" in settings) || settings.effortLevel === null) { ++ return "default"; ++ } ++ return typeof settings.effortLevel === "string" ? settings.effortLevel : undefined; ++ } catch { ++ return undefined; ++ } +} + -+/** -+ * The model a resumed session runs, reported exactly, for a use that names its -+ * own model. -+ * -+ * Nothing is reasserted: the client applies its own exact selection next, so an -+ * environment or settings preference written here would only be written back. -+ * The backend's report is the answer verbatim — no picker matching, alias, hint -+ * reconstruction or default row stands in for it — and one this session's -+ * offered models cannot represent refuses rather than inventing a selectable -+ * entry. A failed or empty report refuses too, before any prompt. -+ * -+ * Refused as an invalid request so a client does not mistake it for a missing -+ * conversation and create a replacement. -+ */ +async function observeResumedModel( + query: Query, + models: ModelInfo[], @@ -1667,12 +1852,6 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 + if (typeof observed !== "string" || observed.length === 0) { + throw RequestError.invalidRequest(undefined, "the resumed session reported no model"); + } -+ if (!models.some((model) => model.value === observed)) { -+ throw RequestError.invalidRequest( -+ { model: observed }, -+ `the resumed session runs "${observed}", which none of its offered models names exactly`, -+ ); -+ } + return { + modelState: { + availableModels: models.map((model) => ({ @@ -1689,6 +1868,44 @@ index e32f603e7cb85544a9ebf108489fcf98932d14a2..96a816b3d4321ead8c2790f617b87804 async function getAvailableModels( query: Query, models: ModelInfo[], +@@ -8664,6 +9140,28 @@ export async function runPromptWithCancellation( + } + } + ++interface ConfigurationCheck { ++ sessionId: string; ++ requestedModel?: string; ++ inspectEffort?: boolean; ++} ++ ++function parseConfigurationCheck(input: unknown): ConfigurationCheck { ++ if (typeof input !== "object" || input === null || !("sessionId" in input) || ++ typeof input.sessionId !== "string") { ++ throw RequestError.invalidParams(); ++ } ++ const requestedModel = "requestedModel" in input ? input.requestedModel : undefined; ++ if (requestedModel !== undefined && typeof requestedModel !== "string") { ++ throw RequestError.invalidParams(); ++ } ++ const inspectEffort = "inspectEffort" in input ? input.inspectEffort : undefined; ++ if (inspectEffort !== undefined && typeof inspectEffort !== "boolean") { ++ throw RequestError.invalidParams(); ++ } ++ return { sessionId: input.sessionId, requestedModel, inspectEffort }; ++} ++ + export function runAcp(logger?: Logger) { + const input = nodeToWebWritable(process.stdout); + const output = nodeToWebReadable(process.stdin); +@@ -8688,6 +9186,8 @@ export function runAcp(logger?: Logger) { + .onRequest(methods.agent.session.resume, (ctx) => agent.resumeSession(ctx.params)) + .onRequest(methods.agent.session.close, (ctx) => agent.closeSession(ctx.params)) + .onRequest(methods.agent.session.setMode, (ctx) => agent.setSessionMode(ctx.params)) ++ .onRequest("_executablemd/session_configuration", { parse: parseConfigurationCheck }, ++ (ctx) => agent.observeSessionConfiguration(ctx.params)) + .onRequest(methods.agent.session.setConfigOption, (ctx) => + agent.setSessionConfigOption(ctx.params), + ) diff --git a/src/claude-sdk.ts b/src/claude-sdk.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b7d1f0b92a2ee959d336959bc93ffe349c69e98 diff --git a/packages/acp/vendor/adapters/claude/recipe.json b/packages/acp/vendor/adapters/claude/recipe.json index 1356de6bb..676849b9d 100644 --- a/packages/acp/vendor/adapters/claude/recipe.json +++ b/packages/acp/vendor/adapters/claude/recipe.json @@ -32,7 +32,7 @@ "node": ">=14.17" } }, - "patchSha256": "c263bcb53645128b81d8cd1cb4bf2d38b2efdee07546222101e58cdea1dd2cbd", + "patchSha256": "7b34df97cf7bf307a4abf7ee3432b07d44065712b17e3716c08f5aa2beedc78e", "transformSha256": "d20ae1bc7335768bdf417831cdac359cb40cfd786adb6bfd78b3808253d8030b", "preimages": { "src/acp-agent.ts": "a52b723182828025341f5111109f4b902beaae22589b77d52f9236f279ef2a1c", @@ -46,7 +46,7 @@ "src/tools.ts": "7f5affb80dc728e6c6ec6378871a4a67f284382c5b66b9a96fd30f453b7c3905" }, "postimages": { - "src/acp-agent.ts": "74727abef9a9f44916ca126bcf2a65f399fea07dbab587df008e440960e83a39", + "src/acp-agent.ts": "cd936e351dabc95279379ca091f5448ea2e865313bda46378bb94533306bc0da", "src/claude-sdk.ts": "b80d272dea9583ecae6ca2c86477cae7f7f9186b8cefdbb1ad1fb6c05e3ddc9a", "src/file-change-audit.ts": "14a9ad8488c5793cb49172ac86d7fd481cd2b23da6589b2275ff3a429eb9b324", "src/index.ts": "c6f3d6074749e0ff466e10cc32e1798be8da0b271e8ba201a6ecb330badf1261", @@ -57,7 +57,7 @@ "src/tools.ts": "ff8c9d821ce82462a659bc5d5c85299f9419072daa14c52208fa31fed5945e7c" }, "runtime": { - "dist/acp-agent.js": "1b3831c6f3f96a1548d9a9311c9e50d99478ffd98d5fced1070f11aaa667e241", + "dist/acp-agent.js": "0c95381c71a2d42aa27f195bace08226cb1c7fa3c5b0026f6677abdaf5fbb9d7", "dist/claude-sdk.js": "b80d272dea9583ecae6ca2c86477cae7f7f9186b8cefdbb1ad1fb6c05e3ddc9a", "dist/clear-context-coordinator.js": "854e5fccdbb3343c57ddf158fb8a1dd5d34d7b13483032437c2fed6c898154a6", "dist/permissions/effects.js": "f2d2ce76f2012b6062ad565b079c2078ae4dbf9282f505876ff38313c521745b", @@ -126,9 +126,9 @@ "package.json" ], "expected": { - "sha256": "7bb5296c72adb4268f8dc9ed484b53fd2aa6b1b16ab30868d7b8dfb63501257e", - "byteLength": 2006701, - "moduleSha256": "f63fb8d356622bb09750168d4682878fe2126f5b033abdd3c5acfafe5ee06ce9" + "sha256": "cb4a7b653a041c2b7d3aa13d4dfbaee891ab4a75cbdb0b65d066cce761895783", + "byteLength": 2010285, + "moduleSha256": "7c94ee201eb97d210522f89073d819d6cf344a8a3fe936f2f128ee0716391db6" }, "metadata": { "name": "@agentclientprotocol/claude-agent-acp", @@ -145,7 +145,15 @@ }, "./*": "./*" }, - "keywords": ["claude", "acp", "agent", "anthropic", "typescript", "sdk", "code"], + "keywords": [ + "claude", + "acp", + "agent", + "anthropic", + "typescript", + "sdk", + "code" + ], "homepage": "https://github.com/agentclientprotocol/claude-agent-acp#readme", "bugs": { "url": "https://github.com/agentclientprotocol/claude-agent-acp/issues" @@ -164,5 +172,5 @@ "zod": "^3.25.0 || ^4.0.0" } }, - "inputsSha256": "00a6a5eaac8b937d546f14ecdc6ae80e6b4ba815abda33c640c4777d93541f0a" + "inputsSha256": "331025f3392d9f0f750a4431161930230c502b85195b354dbc972de32486e71a" } diff --git a/packages/agent/src/agent-api.ts b/packages/agent/src/agent-api.ts index ddc331883..3d9df2291 100644 --- a/packages/agent/src/agent-api.ts +++ b/packages/agent/src/agent-api.ts @@ -131,7 +131,12 @@ export type ChildAnswerPromptEvent = export type AgentPromptEvent = | ChildAnswerPromptEvent - | { type: "started"; agent: Agent; session: Session } + | { + type: "started"; + agent: Agent; + session: Session; + observedConfiguration?: SessionConfiguration; + } | { type: "text_delta"; text: string } | { type: "terminal"; diff --git a/packages/agent/src/function-components.ts b/packages/agent/src/function-components.ts index d49ce32cc..58dfc8000 100644 --- a/packages/agent/src/function-components.ts +++ b/packages/agent/src/function-components.ts @@ -406,6 +406,7 @@ interface ConsumedTurn { * the one that actually ran. */ ranIn?: Session; + observedConfiguration?: import("./agent-api.ts").SessionConfiguration; status?: PromptRecord["status"]; stopReason?: string; failure?: SerializedPromptFailure; @@ -512,6 +513,7 @@ interface HeldPromptTurn { readonly images: PromptOptions["images"]; admitted: boolean; stream?: Stream; + observedConfiguration?: import("./agent-api.ts").SessionConfiguration; /** The native subscription reached its own `done`. */ settled: boolean; /** What the native subscription threw, if it failed on the way out. */ @@ -698,6 +700,12 @@ function* installHeldPromptTerminal( if (event.done) { checked.settled = true; checked.text = event.value; + } else if ( + event.value.type === "started" && + event.value.session === direct.session && + event.value.observedConfiguration !== undefined + ) { + checked.observedConfiguration = { ...event.value.observedConfiguration }; } return event; }, @@ -921,6 +929,9 @@ export function* runPrompt( // For a configured turn that is the authentic use it was verified // under, which is what the record is written from. result.ranIn = event.session; + if (held === undefined && event.observedConfiguration !== undefined) { + result.observedConfiguration = { ...event.observedConfiguration }; + } if (event.session.agentSessionId !== undefined) { result.agentSessionId = event.session.agentSessionId; } @@ -1041,8 +1052,9 @@ export function* runPrompt( // the conversation was under these settings: a prompt that failed while they // were still being applied ran under nothing, and one that started and then // failed still ran under exactly them. - const configuration = yield* sessionUseConfiguration(consumed.ranIn); - if (configuration !== undefined && consumed.started === true) { + const observed = held?.observedConfiguration ?? consumed.observedConfiguration; + const configuration = observed ?? (yield* sessionUseConfiguration(consumed.ranIn)); + if (configuration !== undefined && (consumed.started === true || observed !== undefined)) { record.configuration = configuration; } if (consumed.stopReason !== undefined) { diff --git a/packages/cli/src/repl/application.ts b/packages/cli/src/repl/application.ts index 870bf7e7d..90a3b1989 100644 --- a/packages/cli/src/repl/application.ts +++ b/packages/cli/src/repl/application.ts @@ -17,7 +17,7 @@ import { VIEWPORT } from "./components/viewport.ts"; import { boundaries, caretFor, eraseAt, insertAt } from "./caret.ts"; import type { ReplCaret } from "./caret.ts"; -import type { MessageOrigin } from "./sidekick/history.ts"; +import type { MessageOrigin, PreferenceChoices } from "./sidekick/history.ts"; import { Ok, type Result } from "effection"; import type { Json } from "@executablemd/durable-streams"; import type { AgentOption, AgentOptions, SessionConfiguration } from "@executablemd/agent/api"; @@ -843,6 +843,7 @@ export interface ReplConfiguring { readonly model: string | undefined; /** The effort this would ask for, which belongs to `model`. */ readonly effort: string | undefined; + readonly selected: PreferenceChoices; /** Whether the agent field is the one text acts on. */ readonly naming: boolean; /** Why the last Apply did not happen, for the drawer to say. */ @@ -871,6 +872,7 @@ export const NOT_CONFIGURING: ReplConfiguring = Object.freeze({ agent: "", model: undefined, effort: undefined, + selected: Object.freeze({}), naming: false, refusal: undefined, offered: undefined, @@ -1313,6 +1315,7 @@ export type ReplIntent = readonly revision: number; readonly model?: string; readonly effort?: string; + readonly selected: PreferenceChoices; } /** * Start a new conversation with this agent, by the exact name entered. @@ -3170,6 +3173,7 @@ export function reduceRepl( agent: live.sidekick?.agent ?? "", model: live.sidekick?.requested?.model, effort: live.sidekick?.requested?.effort, + selected: Object.freeze({}), // What the agent advertised, kept across a close for the // conversation it was read of. Choices are not selections: a list // this agent gave for this conversation is still true, so @@ -3242,6 +3246,7 @@ export function reduceRepl( // of the one before it behind rather than carrying a level that // model may not have at all. effort: undefined, + selected: Object.freeze({ model: true }), refusal: undefined, revision: state.configuring.revision + 1, }), @@ -3267,6 +3272,7 @@ export function reduceRepl( configuring: Object.freeze({ ...state.configuring, effort: action.effort, + selected: Object.freeze({ ...state.configuring.selected, effort: true }), refusal: undefined, revision: state.configuring.revision + 1, }), @@ -3311,6 +3317,7 @@ export function reduceRepl( kind: "save-configuration", conversation: held.conversation, revision: held.revision, + selected: held.selected, ...(held.model === undefined ? {} : { model: held.model }), ...(held.effort === undefined ? {} : { effort: held.effort }), }, diff --git a/packages/cli/src/repl/program.ts b/packages/cli/src/repl/program.ts index 9d2beb1b5..d35ce4518 100644 --- a/packages/cli/src/repl/program.ts +++ b/packages/cli/src/repl/program.ts @@ -4978,7 +4978,7 @@ function* perform( // A record in this history and nothing else: no handle, no provider // call and no turn. So it is taken while a message cycle runs, and the // turn already in flight keeps the settings it was handed. - const saved = yield* chat.owner.configure(desired); + const saved = yield* chat.owner.configure(desired, intent.selected); chat.saved(intent.conversation, intent.revision, saved); }); if (refused !== undefined) { diff --git a/packages/cli/src/repl/sidekick/history.ts b/packages/cli/src/repl/sidekick/history.ts index 8ae2eebe2..c0515bfca 100644 --- a/packages/cli/src/repl/sidekick/history.ts +++ b/packages/cli/src/repl/sidekick/history.ts @@ -68,6 +68,7 @@ import { } from "@executablemd/durable-streams"; import type { DurableEvent, DurableStream, SerializedError } from "@executablemd/durable-streams"; import { call, ensure, Ok, scoped, withResolvers } from "effection"; +import { AGENT_PROMPT } from "@executablemd/agent/host"; import type { Operation, Result } from "effection"; import { createHash } from "node:crypto"; @@ -202,6 +203,17 @@ export interface PreferencesRecord { readonly conversation: string; readonly model: string | null; readonly effort: string | null; + readonly selected?: PreferenceChoices; +} + +export interface PreferenceChoices { + readonly model?: true; + readonly effort?: true; +} + +export interface PreferencePositions { + readonly model?: number; + readonly effort?: number; } /** @@ -270,6 +282,7 @@ export interface EventRecord { readonly conversation: string; readonly sequence: number; readonly event: string; + readonly selectedAt?: PreferencePositions; } /** What a completed turn's response actually rendered to. */ @@ -597,7 +610,7 @@ function conversationOf(value: Record): ConversationRecord | un } function preferences(value: Record): PreferencesRecord | undefined { - if (!exactly(value, ["kind", "conversation", "model", "effort"])) { + if (!exactly(value, ["kind", "conversation", "model", "effort"], ["selected"])) { return undefined; } const held = str(value.conversation); @@ -609,7 +622,28 @@ function preferences(value: Record): PreferencesRecord | undefi if (model === undefined || effort === undefined) { return undefined; } - return { kind: "preferences", conversation: held, model, effort }; + const selected = value.selected; + if (selected === undefined) { + return { kind: "preferences", conversation: held, model, effort }; + } + if ( + !plain(selected) || + !exactly(selected, [], ["model", "effort"]) || + (Object.hasOwn(selected, "model") && (selected.model !== true || model === null)) || + (Object.hasOwn(selected, "effort") && (selected.effort !== true || effort === null)) + ) { + return undefined; + } + return { + kind: "preferences", + conversation: held, + model, + effort, + selected: { + ...(selected.model === true ? { model: true } : {}), + ...(selected.effort === true ? { effort: true } : {}), + }, + }; } function reference(value: Record): ReferenceRecord | undefined { @@ -665,7 +699,7 @@ function message(value: Record): MessageRecord | undefined { } function eventRecord(value: Record): EventRecord | undefined { - if (!exactly(value, ["kind", "conversation", "sequence", "event"])) { + if (!exactly(value, ["kind", "conversation", "sequence", "event"], ["selectedAt"])) { return undefined; } const held = str(value.conversation); @@ -676,10 +710,40 @@ function eventRecord(value: Record): EventRecord | undefined { } // The canonical record it carries has to be one, or this line is describing a // turn nobody can read back. - if (!parseDurableEvent(event).ok) { + const parsed = parseDurableEvent(event); + if (!parsed.ok) { return undefined; } - return { kind: "event", conversation: held, sequence, event }; + const selectedAt = value.selectedAt; + if (selectedAt === undefined) { + return { kind: "event", conversation: held, sequence, event }; + } + if ( + !plain(selectedAt) || + !exactly(selectedAt, [], ["model", "effort"]) || + parsed.value.type !== "yield" || + parsed.value.description.type !== AGENT_PROMPT + ) { + return undefined; + } + const model = whole(selectedAt.model); + const effort = whole(selectedAt.effort); + if ( + (Object.hasOwn(selectedAt, "model") && model === undefined) || + (Object.hasOwn(selectedAt, "effort") && effort === undefined) + ) { + return undefined; + } + return { + kind: "event", + conversation: held, + sequence, + event, + selectedAt: { + ...(model === undefined ? {} : { model }), + ...(effort === undefined ? {} : { effort }), + }, + }; } function response(value: Record): ResponseRecord | undefined { @@ -1359,6 +1423,7 @@ export function conversationStream( writer: SidekickWriter, conversation: string, retained: readonly SidekickRecord[] = [], + selection?: () => PreferencePositions | undefined, ): DurableStream { let sequence = retained.filter( (record) => record.kind === "event" && record.conversation === conversation, @@ -1382,11 +1447,16 @@ export function conversationStream( return events; }, *append(event: DurableEvent): Operation { + const selectedAt = + event.type === "yield" && event.description.type === AGENT_PROMPT + ? selection?.() + : undefined; yield* writer.append({ kind: "event", conversation, sequence: sequence, event: serializeDurableEvent(event), + ...(selectedAt === undefined ? {} : { selectedAt }), }); sequence += 1; }, diff --git a/packages/cli/src/repl/sidekick/model.ts b/packages/cli/src/repl/sidekick/model.ts index 90edb5d6e..84b322683 100644 --- a/packages/cli/src/repl/sidekick/model.ts +++ b/packages/cli/src/repl/sidekick/model.ts @@ -47,6 +47,7 @@ import { parseDurableEvent } from "@executablemd/durable-streams"; import type { ConversationRecord, ControlRecord, + PreferencePositions, ResponseRecord, RetainedPrefix, SidekickRecord, @@ -130,6 +131,11 @@ export interface SidekickConversation { * while they were still being applied carries no member and supplies none. */ readonly verified: SessionConfiguration | undefined; + readonly claudeConfiguration?: { + readonly continued: boolean; + readonly pending: PreferencePositions; + readonly settings: SessionConfiguration; + }; } /** @@ -911,8 +917,11 @@ function slot(conversation: string, response: string, at: number): string { * those is a file describing something that did not happen, and rounding it to * the nearest readable shape would show somebody a conversation they never had. */ -export function projectSidekick(records: readonly SidekickRecord[]): Result { - const projected = projectHistory(records); +export function projectSidekick( + records: readonly SidekickRecord[], + handingOff?: { readonly conversation: string; readonly message: number }, +): Result { + const projected = projectHistory(records, handingOff); return projected.ok ? Ok(projected.value.reading) : projected; } @@ -924,7 +933,10 @@ export interface ProjectedHistory { } /** {@link projectSidekick}, keeping the record positions a live owner's exception needs. */ -export function projectHistory(records: readonly SidekickRecord[]): Result { +export function projectHistory( + records: readonly SidekickRecord[], + handingOff?: { readonly conversation: string; readonly message: number }, +): Result { // The request boundaries first, by the same rules the live owner reads them // by. Everything below that associates a message, a reply or an orientation // with a saved turn asks these rather than comparing numbers. @@ -932,6 +944,15 @@ export function projectHistory(records: readonly SidekickRecord[]): Result(); + for (const request of requests.value) { + if ( + request.turn === undefined && + !(request.conversation === handingOff?.conversation && request.message === handingOff.message) + ) { + latestUncertain.set(request.conversation, request.at); + } + } const recovery = recoveryFacts(records, requests.value); if (!recovery.ok) { return recovery; @@ -1043,6 +1064,9 @@ export function projectHistory(records: readonly SidekickRecord[]): Result; + continued: boolean; + selected: Partial>; + lastOutcome: number; } >(); const order: string[] = []; @@ -1099,6 +1123,9 @@ export function projectHistory(records: readonly SidekickRecord[]): Result(); const feedback = new Map(); const readingRequest = new Map(); + const legacySelections = new Set(); + const consumedSelections = { model: new Set(), effort: new Set() }; + const settings = ["model", "effort"] as const; const responses = new Map(); function acceptedFeedback( record: Pick, @@ -1170,6 +1197,9 @@ export function projectHistory(records: readonly SidekickRecord[]): Result(), at: new Map(), verified: new Map(), + continued: false, + selected: {}, + lastOutcome: -1, }); order.push(record.conversation); } else { @@ -1190,13 +1220,30 @@ export function projectHistory(records: readonly SidekickRecord[]): Result= index || + preference?.kind !== "preferences" || + preference.conversation !== record.conversation || + preference[setting] === null || + !(preference.selected?.[setting] || legacySelections.has(at)) || + consumedSelections[setting].has(at) + ) { + return Err( + new SidekickProjectionError( + `this chat history associates ${setting} with an invalid preference (record ${position}).`, + ), + ); + } + } + } if (turn === undefined || canonical.result.status !== "ok") { // A turn whose outcome the journal does not hold is an unfinished // fact rather than a completed turn. It establishes nothing. @@ -1255,6 +1334,17 @@ export function projectHistory(records: readonly SidekickRecord[]): Result { const held = conversations.get(id)!; + const pending = { ...held.selected }; + const uncertainAt = latestUncertain.get(id) ?? -1; + for (const setting of settings) { + const at = pending[setting]; + if (at !== undefined && at < uncertainAt && legacySelections.has(at)) { + delete pending[setting]; + } + } + const selected: SessionConfiguration = Object.fromEntries( + settings.flatMap((setting) => { + const at = pending[setting]; + const preference = at === undefined ? undefined : records[at]; + return preference?.kind === "preferences" && preference[setting] !== null + ? [[setting, preference[setting]]] + : []; + }), + ); return Object.freeze({ id, agent: held.agent, @@ -1571,6 +1692,15 @@ export function projectHistory(records: readonly SidekickRecord[]): Result left - right), ), verified: lastVerified(held.verified), + ...(held.agent === "claude" + ? { + claudeConfiguration: Object.freeze({ + continued: held.continued, + pending: Object.freeze(pending), + settings: Object.freeze(selected), + }), + } + : {}), }); }), ), diff --git a/packages/cli/src/repl/sidekick/owner.ts b/packages/cli/src/repl/sidekick/owner.ts index a4e39c74a..a2ed47b2e 100644 --- a/packages/cli/src/repl/sidekick/owner.ts +++ b/packages/cli/src/repl/sidekick/owner.ts @@ -129,7 +129,12 @@ import { ReplHost } from "../host.ts"; import { readPromptImage } from "./asset-image.ts"; import { API } from "@executablemd/runtime"; import { conversationStream, failedOutcome } from "./history.ts"; -import type { SidekickRecord, SidekickWriter } from "./history.ts"; +import type { + PreferenceChoices, + PreferencePositions, + SidekickRecord, + SidekickWriter, +} from "./history.ts"; import { applicableHumanStop, projectHistory, @@ -630,7 +635,7 @@ export interface SidekickOwner { * that has not produced one yet there is nothing for it to be about, and it * refuses rather than attaching itself to whichever setup wins. */ - configure(desired: SessionConfiguration): Operation>; + configure(desired: SessionConfiguration, selected?: PreferenceChoices): Operation>; /** * Run this Sidekick's work under a different agent from now on. * @@ -900,12 +905,17 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation } | undefined; /** Which response each begun turn belongs to, by the handle it began with. */ - const begun = new WeakMap(); + const begun = new WeakMap(); /** * The turn a Sessions reading would draw, or none because none is running. @@ -1008,7 +1018,8 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation { - const slot = registering; + const registration = registering; + const slot = registration?.at; registering = undefined; const preparing = preparingInput; preparingInput = undefined; @@ -1018,8 +1029,8 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation { - const slot = typeof handle === "object" && handle !== null ? begun.get(handle) : undefined; + const slot = + typeof handle === "object" && handle !== null ? begun.get(handle)?.at : undefined; if (slot === undefined || watching === undefined || watching.at !== slot) { // A turn this process is no longer watching: stopped, replaced, or // already answered. It changes nothing. @@ -1057,10 +1069,11 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation { - const slot = + const registration = typeof publication.begun === "object" && publication.begun !== null ? begun.get(publication.begun) : undefined; + const slot = registration?.at; const key = publication.association?.sessionKey; // This publication's own association, for the exact row it began. A // key established here makes that live turn a member of its provider @@ -1079,7 +1092,12 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation + publishing?.at.conversation === conversation ? publishing.selectedAt : undefined, + ), id: conversation, agent, // This conversation's own publisher, beside what the assembly @@ -2108,7 +2128,13 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation> { + function* configure( + desired: SessionConfiguration, + selected: PreferenceChoices = { + ...(desired.model === undefined ? {} : { model: true }), + ...(desired.effort === undefined ? {} : { effort: true }), + }, + ): Operation> { // Saving is not inspecting. A preference is a record in this history and // nothing else: it opens no handle, asks the provider nothing and sends no // turn, so there is nothing about a running cycle that it has to wait for. @@ -2123,6 +2149,7 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation> { yield* paired.writer.append({ kind: "preferences", conversation, model: requested.model ?? null, effort: requested.effort ?? null, + ...(selected === undefined ? {} : { selected }), }); yield* refresh(); const settled = history(); @@ -2718,8 +2747,10 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation { + if (registering?.at === at) { + registering = undefined; + } if (watching === live) { // Cancelled or unwound before anything saved the outcome. What was // shown stays, as an attempt that did not finish. @@ -2727,29 +2758,6 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation one.id === conversation, + )?.claudeConfiguration; + const configuration = claude?.continued + ? Object.keys(claude.settings).length === 0 + ? undefined + : claude.settings + : desired(settings.value, conversation); + const selectedAt = + claude === undefined + ? undefined + : { + ...(claude.pending.model !== undefined && + configuration?.model === claude.settings.model + ? { model: claude.pending.model } + : {}), + ...(claude.pending.effort !== undefined && + configuration?.effort === claude.settings.effort + ? { effort: claude.pending.effort } + : {}), + }; + registering = { at, selectedAt }; const replied = yield* handle.prompt( request, - desired(settings.value, conversation), + configuration, sending.kind === "feedback" ? sending.images : sending.finished?.images, ); // A withheld reply is a completion the provider made, so the TODO batch diff --git a/packages/cli/tests/repl-sidekick-configuration.test.ts b/packages/cli/tests/repl-sidekick-configuration.test.ts index 72c37c239..bd230cc9f 100644 --- a/packages/cli/tests/repl-sidekick-configuration.test.ts +++ b/packages/cli/tests/repl-sidekick-configuration.test.ts @@ -44,6 +44,7 @@ import { awaitedFact, MOUNTED_AGENT, OTHER_MOUNTED_AGENT, + useMountedHost, } from "./support/mounted-repl.ts"; import { settledReading } from "./support/mounted-history.ts"; import type { MountedRepl } from "./support/mounted-repl.ts"; @@ -94,10 +95,14 @@ const NAMED: Readonly> = Object.freeze({ }); import { PAIRED_DIRECTORY, + parseSidekickRecord, readSidekickRecords, + serializeSidekickRecord, SIDEKICK_FILE, } from "../src/repl/sidekick/history.ts"; -import { readdir, readFile } from "node:fs/promises"; +import { ReplHost } from "../src/repl/host.ts"; +import { projectSidekick } from "../src/repl/sidekick/model.ts"; +import { readdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { until } from "effection"; @@ -1880,6 +1885,270 @@ describe("Tier CFG — one order for everything this conversation writes", () => effort: { balanced: { selected: "medium", choices: [{ id: "medium", name: "Medium" }] } }, } as const; + it("Claude recovers a provider-owned identity without reapplying the legacy preference", function* () { + const sessionKey = "sidekick-pending-host-ack"; + const native = "native-claude"; + const model = "claude-fable-5-2"; + const refused = "the host could not retain this Claude session"; + const assertions: string[] = []; + const host = yield* useMountedHost({ + sidekickAgent: "claude", + usageAcp: { + agentRegistry: makeRegistry({ claude: "claude-cmd" }), + advertiseNativeLaunch: [], + advertiseClientNativeAttachment: [], + nativeAdapters: { + claude: { + launcher: "claude", + identity: "provider-returned", + acceptance: "first-turn-acceptance", + resume: () => [], + }, + }, + sessions: { + *requestSession() { + return { sessionKey, cwd: yield* API.Env.operations.cwd(), state: "new" }; + }, + // deno-lint-ignore require-yield + *recordSessionIdentity(_, identity) { + assertions.push(identity.agentSessionId ?? ""); + if (assertions.length === 1) throw new Error(refused); + }, + }, + }, + }); + const page = yield* useReplPage({ host }); + const { fake } = page.repl; + fake.identity(native); + fake.configuration(OFFERED); + fake.script({ reply: "Unacknowledged." }); + yield* sendMessage(page, "first"); + yield* page.until( + "the host refused the promoted identity", + (one) => one.shows(refused) && one.shows("[Resume queue]"), + ); + const retained = yield* settledReading(page.repl); + const message = retained.chat.find((record) => record.kind === "message"); + if (message?.kind !== "message") throw new Error("The first message was not retained."); + const first = retained.chat.filter((record) => record.kind === "event"); + expect(first.map((record) => JSON.parse(record.event).result?.value)).toContainEqual( + expect.objectContaining({ sessionKey, status: "failed" }), + ); + expect(first.some((record) => record.event.includes('"agentSessionId"'))).toBe(false); + expect(assertions).toEqual([native]); + page.repl.terminal.end(); + yield* awaited("the first REPL to join", () => page.repl.outcome() !== undefined); + const closed = page.repl.outcome(); + if (!closed?.ok) throw new Error("The first REPL did not close cleanly."); + + const storage = join(host.root, PAIRED_DIRECTORY, retained.execution, SIDEKICK_FILE); + const legacy = serializeSidekickRecord({ + kind: "preferences", + conversation: message.conversation, + model: "fast", + effort: null, + }); + // Reconstruct the pre-choice-record history format for this older chat. + const lines = (yield* until(readFile(storage, "utf8"))).split("\n").map((line) => { + const record = parseSidekickRecord(line); + if ( + record?.kind !== "event" || + JSON.parse(record.event).description?.type !== "agent_prompt" + ) { + return line; + } + return serializeSidekickRecord({ ...record, selectedAt: undefined }).trimEnd(); + }); + const offset = lines.findIndex((line) => { + const record = parseSidekickRecord(line); + return record?.kind === "message" && record.id === message.id; + }); + if (offset < 0) throw new Error("The retained chat lost its first message."); + lines.splice(offset, 0, legacy.trimEnd()); + yield* until(writeFile(storage, lines.join("\n"))); + const prior = projectSidekick(yield* readSidekickRecords(storage)); + if (!prior.ok) throw prior.error; + expect(prior.value.conversations.at(-1)?.claudeConfiguration?.pending).toEqual({}); + + const next = yield* useReplPage({ host, location: closed.value.location }); + if (next.screen().shows("[Resume queue]")) yield* next.press("[Resume queue]"); + const writes = applied(fake).length; + fake.script({ + reply: "Same native Claude history.", + observedConfiguration: { model }, + }); + yield* conversed(next, "continue", "Same native Claude history."); + expect(fake.turns.at(-1)?.requestedModel).toBeUndefined(); + expect(fake.turns.at(-1)?.handle.agentSessionId).toBe(native); + expect(fake.ensured.at(-1)).toMatchObject({ + sessionKey, + resumeSessionId: `acp:${sessionKey}`, + }); + expect(applied(fake).slice(writes)).toEqual([]); + expect(assertions.every((identity) => identity === native)).toBe(true); + expect(assertions.length).toBeGreaterThan(1); + yield* openConfigure(next); + yield* next.until( + "the saved Asked model and the exact Verified model", + (one) => + drawerShows(one, "Requested: model=fast") && drawerShows(one, `Verified: model=${model}`), + ); + }); + + it("a verified Claude turn consumes its own Apply and keeps a later same-model Apply", function* () { + const host = yield* useMountedHost({ + sidekickAgent: "claude", + usageAcp: { + agentRegistry: makeRegistry({ claude: "claude-cmd" }), + advertiseNativeLaunch: [], + advertiseClientNativeAttachment: [], + }, + }); + const page = yield* useReplPage({ host }); + const { fake } = page.repl; + fake.configuration(OFFERED); + fake.script({ reply: "First Claude turn." }); + yield* conversed(page, "hello", "First Claude turn."); + fake.script({ + reply: "Continued Claude turn.", + observedConfiguration: { model: "claude-opus-5-5" }, + }); + yield* conversed(page, "continue", "Continued Claude turn."); + yield* openConfigure(page); + yield* page.until("the verbatim verified model", (one) => + drawerShows(one, "Verified: model=claude-opus-5-5"), + ); + yield* offeredChoice(page, "Fast"); + yield* chooseNamed(page, "fast"); + yield* applyConfigure(page); + yield* drawerGone(page); + + fake.script({ reply: "Held Claude turn.", held: true }); + yield* sendMessage(page, "hold this"); + yield* fake.holdingTurns(1); + expect(fake.turns.at(-1)?.requestedModel).toBe("fast"); + + yield* openConfigure(page); + yield* offeredChoice(page, "Fast"); + yield* chooseNamed(page, "fast"); + yield* applyConfigure(page); + yield* drawerGone(page); + fake.releaseTurn(); + yield* page.until( + "the held reply and idle Sidekick", + (one) => one.shows("Held Claude turn.") && sidekickIdle(one), + ); + + fake.script({ reply: "Later Apply." }); + yield* conversed(page, "apply the newer selection", "Later Apply."); + expect(fake.turns.at(-1)?.requestedModel).toBe("fast"); + + // Applying the prefilled values does not create another model request. + yield* openConfigure(page); + yield* offeredChoice(page, "Fast"); + yield* applyConfigure(page); + yield* drawerGone(page); + fake.script({ reply: "Ordinary continuation." }); + yield* conversed(page, "continue", "Ordinary continuation."); + expect(fake.turns.at(-1)?.requestedModel).toBeUndefined(); + + const { chat } = yield* settledReading(page.repl); + const applies = chat.flatMap((record, at) => + record.kind === "preferences" && record.selected?.model ? [at] : [], + ); + expect(applies).toHaveLength(2); + expect( + chat.flatMap((record) => + record.kind === "event" && record.selectedAt?.model !== undefined + ? [record.selectedAt.model] + : [], + ), + ).toEqual(applies); + + yield* openConfigure(page); + yield* offeredChoice(page, "Fast"); + yield* chooseNamed(page, "fast"); + yield* applyConfigure(page); + yield* drawerGone(page); + const beforeRefusal = fake.turns.length; + fake.configuration(undefined); + yield* sendMessage(page, "try the pending selection"); + yield* page.until( + "the pre-start refusal", + (one) => + one.shows("Model choices are unavailable for claude.") && one.shows("[Resume queue]"), + ); + expect(fake.turns).toHaveLength(beforeRefusal); + + fake.configuration(OFFERED); + fake.script({ failure: "failed after the native prompt started" }); + yield* page.press("[Resume queue]"); + yield* sendMessage(page, "try the pending selection again"); + yield* fake.startedTurns(beforeRefusal + 1); + expect(fake.turns.at(-1)?.requestedModel).toBe("fast"); + yield* page.until( + "the post-start failure", + (one) => one.shows("failed after the native prompt started") && one.shows("[Resume queue]"), + ); + yield* page.press("[Resume queue]"); + fake.script({ reply: "The retry consumed the choice." }); + yield* conversed(page, "continue", "The retry consumed the choice."); + expect(fake.turns.at(-1)?.requestedModel).toBeUndefined(); + + yield* openConfigure(page); + yield* offeredChoice(page, "High"); + yield* chooseNamed(page, "high"); + yield* applyConfigure(page); + yield* drawerGone(page); + const beforeEffort = fake.configCalls.length; + fake.script({ reply: "Only effort changed." }); + yield* conversed(page, "continue with high effort", "Only effort changed."); + expect(fake.turns.at(-1)?.requestedModel).toBeUndefined(); + expect(fake.configCalls.slice(beforeEffort).filter((call) => call.startsWith("set "))).toEqual([ + "set effort=high", + ]); + + const retained = yield* settledReading(page.repl); + const active = [...retained.chat] + .reverse() + .find((record) => record.kind === "conversation" && record.phase === "activated"); + if (active?.kind !== "conversation") { + throw new Error("The first Claude turn never activated its conversation."); + } + page.repl.terminal.end(); + yield* awaited("the first REPL to join", () => page.repl.outcome() !== undefined); + const closed = page.repl.outcome(); + if (!closed?.ok) { + throw new Error("The first REPL did not close cleanly."); + } + const storage = join(host.root, PAIRED_DIRECTORY, retained.execution, SIDEKICK_FILE); + yield* ReplHost.operations.appendRecord( + storage, + serializeSidekickRecord({ + kind: "preferences", + conversation: active.conversation, + model: "fast", + effort: null, + }), + ); + const beforeReopen = fake.turns.length; + const cold = yield* useReplPage({ host, location: closed.value.location }); + expect(fake.turns).toHaveLength(beforeReopen); + fake.script({ reply: "Legacy Apply reached the next turn." }); + yield* conversed(cold, "apply the retained choice", "Legacy Apply reached the next turn."); + expect(fake.turns.at(-1)?.requestedModel).toBe("fast"); + + const history = (yield* settledReading(cold.repl)).chat; + const uncertain = history.map((record) => record.kind).lastIndexOf("message"); + const ambiguous = projectSidekick(history.slice(0, uncertain + 1)); + if (!ambiguous.ok) { + throw ambiguous.error; + } + expect(ambiguous.value.requests.at(-1)?.turn).toBeUndefined(); + expect(ambiguous.value.preferences?.model).toBe("fast"); + expect(ambiguous.value.conversations.at(-1)?.claudeConfiguration?.pending).toEqual({}); + }); + it("CFG8: a save queues behind the reply being written, and both land in order", function* () { const gate = appendGate(); const page = yield* useReplPage({ gate }); diff --git a/packages/cli/tests/support/fake-acp.ts b/packages/cli/tests/support/fake-acp.ts index 454ef9726..1046f4a91 100644 --- a/packages/cli/tests/support/fake-acp.ts +++ b/packages/cli/tests/support/fake-acp.ts @@ -102,6 +102,7 @@ export interface ScriptedTurn { * may promote. */ readonly accepted?: boolean; + readonly observedConfiguration?: { model: string; effort?: string }; /** * Leave this turn unfinished until it is cancelled. * @@ -950,7 +951,7 @@ export function createFakeAcp(): FakeAcp { return { requestId: input.requestId, - promptStarted: Promise.resolve(), + promptStarted: Promise.resolve(turn.observedConfiguration), materialized, events: { [Symbol.asyncIterator](): AsyncIterator { diff --git a/packages/cli/tests/support/mounted-repl.ts b/packages/cli/tests/support/mounted-repl.ts index 946505545..d3eace8fa 100644 --- a/packages/cli/tests/support/mounted-repl.ts +++ b/packages/cli/tests/support/mounted-repl.ts @@ -736,6 +736,8 @@ export function* useMountedHost( | "agentRegistry" | "advertiseNativeLaunch" | "advertiseClientNativeAttachment" + | "nativeAdapters" + | "sessions" >; readonly agentCwd?: AcpxProviderDependencies["agentCwd"]; } = {}, diff --git a/scripts/tests/acpx-vendor.test.ts b/scripts/tests/acpx-vendor.test.ts index 448ceac44..91e4537c4 100644 --- a/scripts/tests/acpx-vendor.test.ts +++ b/scripts/tests/acpx-vendor.test.ts @@ -40,6 +40,7 @@ const SEAMS: readonly string[] = [ "XMD requested model:", "XMD workflow role controls:", "XMD exact-model replay:", + "XMD Claude configuration:", "XMD verified resume:", "XMD retained command:", ]; diff --git a/specs/acp-client-spec.md b/specs/acp-client-spec.md index 1927fd018..32a8264de 100644 --- a/specs/acp-client-spec.md +++ b/specs/acp-client-spec.md @@ -392,10 +392,10 @@ Session accepts optional `model` and `effort` props: Values are exact provider ids — whatever the agent advertises, spelled the way it spells them. XMD translates no alias and substitutes no near value. -Omission is not a value. With neither prop the conversation keeps whatever it -is already using and nothing is read or written about either setting; with only -`model` the effort level is left alone; with only `effort` it applies to the -model the conversation is already on. +Omission requests no configuration change. With neither prop the conversation +keeps its settings. With only `model` the effort level is left alone. With only +`effort` it applies to the current model. A prepared Claude reconnect also reports +the settings it observes. Configuration is not an `Agent.session()` argument. Session middleware receives only a name or opaque request and returns the Session selected by its final @@ -503,21 +503,31 @@ checks `requestedModel !== undefined` and derives the existing `_meta["executablemd.has-explicit-model/v1"]: true` marker. The model string stays within the runtime; `session/new` and other adapters carry no marker. -On such a resume the prepared Claude adapter reasserts no environment or -settings model. It reads the model the resumed backend reports and advertises -that exact string as the current model selection — no picker alias, default -row, context-hint reconstruction or requested value substitutes for it. An -unreadable or empty report, or one no offered model names exactly, refuses the -load or resume as an invalid request before any prompt; this includes a -concrete model offered only through an alias, and a context hint the offered -ids do not spell. Fresh, unconfigured and effort-only sessions keep the -adapter's existing initialization. - -ACPX's reconnect replay of a saved model selection writes nothing when the -resumed session already reports exactly that saved id. A different reported id -is written back through the existing replay, and the steps above verify it. -Repeated operations under an unchanged selection therefore add no model write, -while a genuine change is written once and verified before the next prompt. +A verified load or resume with the prepared Claude adapter first observes the +native conversation. Startup metadata omits the saved model. The adapter reads +the backend's exact model and available context evidence, and reports effective +effort when the backend attests it. It applies no environment or settings model +and leaves native effort in place. A missing or unreadable model refuses before +prompting. The current model may be absent from the offered list. + +ACPX skips the saved model and retained model and effort controls on this +attachment before validating replay values. It identifies model-valued controls +from the retained and live selectors, and continues to replay unrelated +controls. Explicit intent is supplied by the final authentic use. + +A deliberate choice still names an offered row. The prepared adapter compares +the chosen model or its SDK-reported resolved identity against the native +observation. An effort change on a resumed model uses the effort choices +the SDK associates with that native identity, including a verified offered +alias for it. This lookup preserves the observed model ID and does not +require a model write. A resumed session must report its prior effort before +an effort setter can run. A context variant requires matching evidence from +the active Query. A fresh variant without live pre-prompt evidence refuses. +The check runs on the attachment that forwards the prompt. If configuration +may have been applied before a failure, restoration verifies the exact prior +native model and context first, then effort. The transaction may restore its +own observed prior model outside the catalog. Unverified restoration fences the +session. The configured-session carrier is issued by the Agent package after `session()` resolves an exact value registered by the installed provider. An Agent-owned @@ -571,8 +581,9 @@ because effort choices belong to a model. Reading is strict about the selector it recognized and incurious about the rest. A selector with the wrong type, two equally preferred candidates, a duplicate value id, a missing id or name, or a current value the agent does not -offer fails the operation rather than reading as "this agent offers you -nothing". +offer fails discovery. The prepared Claude configuration transaction accepts +a native current observation outside the offered list. Only offered rows are +eligible for fresh selection and deliberate changes. ## The provider-factory seam @@ -1122,7 +1133,11 @@ The configuration is retained only after the provider emits `started`: a turn that started is one the provider put under exactly those settings, while a configuration refusal started no turn and retains none. A prompt that starts and later fails or is cancelled retains the configuration it ran under. An -unconfigured prompt omits it. A `sequence` records execution order explicitly, +unconfigured prompt ordinarily omits it. A prepared Claude continuation +retains the exact observed model and any attested effort from the attachment +bound to its started event. This records the settings in use while the final +authentic Session remains the authority for what may change. +A `sequence` records execution order explicitly, and per-location ordinals keep durable identities stable across Each loops. For a held conversation the retained `input` is the final composed text the diff --git a/specs/repl-spec.md b/specs/repl-spec.md index bc8ad5339..fd7076e46 100644 --- a/specs/repl-spec.md +++ b/specs/repl-spec.md @@ -3619,6 +3619,26 @@ and `prompt`; an unreadable preference refuses rather than falling back. A save acknowledged before handoff belongs to that turn; one acknowledged after belongs to the next. +For an established Claude conversation, Apply records which settings the person +selected in this drawer. Prefilled values still supply the Asked reading. A +model choice counts even when it repeats the saved selection. It supersedes a +pending effort choice from the previous model. An effort-only Apply leaves the +pending model choice in place. A conversation without retained provider +placement uses its full saved configuration. A retained Prompt placement is +enough to use outstanding choices alone, including when the provider retained +the native identity before the host could acknowledge it. + +The held Claude turn receives only the outstanding choices for its conversation. +Its Prompt outcome and the Sidekick record positions of the choices it received +are saved together in the conversation stream. A verified start consumes those +exact choices, including when the turn later fails or is cancelled. A pre-start +refusal leaves them pending. A later Apply has a different position even when its +values are identical. Reopening derives this same state from the acknowledged +records. An older preference without recorded choice actions remains eligible +when the history establishes an Apply after the last settled turn and before any +later handoff. The Asked reading still shows a saved preference whose ordering +does not establish a pending choice. + The shared chat writer serializes physical append and in-memory publication as one operation for messages, feedback, controls, canonical turn events and preferences. Callers queue in arrival order. A cancelled waiter removes only @@ -3651,10 +3671,8 @@ drawer. A route drawer in front of Configure owns Escape while it is there: the first one closes that drawer and exposes the Configure held underneath with every choice still in it, and the next one closes Configure. A Configure that is not the thing on the screen — behind another pane, another tab, or a drawer in -front of it — consumes no Escape at all. A saved model or effort is used by the *next* turn, which -is where an agent can actually be asked: saving asks nothing of it, stops -nothing, and leaves a turn already running on the settings it was given. A -setting left out asks for no change to it and resets nothing. +front of it — consumes no Escape at all. Saving leaves a running turn on the +settings it was given. A setting left out of a turn asks for no change. Entering a different agent is explicitly starting a new conversation, and the control says so before it is pressed. The old chat and what it was with stay in @@ -3681,8 +3699,8 @@ differs. After a host Codex upgrade, the installed build must confirm the original conversation on a live load before Sidekick uses it. The Sidekick's own controls apply to every turn as it is built — no provider tools, no MCP servers, strict permission routing and every native -permission request denied — and the turn's model and effort are applied and -read back before it is sent. Reopening asks for nothing. A resume, identity, +permission request denied — and the settings requested for the turn are applied +and read back before it is sent. Reopening asks for nothing. A resume, identity, build or configuration the provider cannot actually perform fails that message and leaves the chat, its turns and its history standing; nothing is created in their place, and the person is told why rather than being given a new @@ -3707,10 +3725,8 @@ the agent has answered for itself; an agent that cannot be reached is refused in its own words, leaving the conversation a person was in exactly where it was. Nothing falls back to another agent, and making the change sends nothing. -Which model and effort it runs under is a request this history holds and the -next turn puts into effect, because a configuration can only be asked of an -agent on a turn. It is applied model first — effort levels belong to a model — -and read back, so a turn that happened ran under what was asked for. An agent +The turn applies any requested configuration model first, because effort levels +belong to a model. It verifies the requested settings before sending. An agent that refuses the request leaves the turn unsent and says what it does offer, and the request stays recorded: a Sidekick that quietly dropped it would answer as something nobody chose. What a person chooses between is the agent's own answer,