diff --git a/.changeset/acp-per-session-thought-levels.md b/.changeset/acp-per-session-thought-levels.md new file mode 100644 index 0000000..d281936 --- /dev/null +++ b/.changeset/acp-per-session-thought-levels.md @@ -0,0 +1,15 @@ +--- +"@pwrdrvr/agent-acp": patch +--- + +Make a low-effort reasoning request actually lower an ACP agent's thinking when that agent offers only graded levels, and choose the level from the session's own option menu rather than whichever session wrote last. + +Three fixes, which only work together. Each is guarded by its own test. + +**Graded thought levels.** `reasoningValueForThoughtLevel` mapped a low-effort token only onto an off-like value (`off` / `none` / `disabled` / `no`). An agent that offers graded levels and no off got nothing. That covers Kimi's K3, whose thinking option is `low` / `high` / `max` / `on`. A low-effort token now falls back to the `low` level (also `minimal` / `min` / `minimum`) when there is no off. Off still wins where both exist, and a value that already read as on (say, "On (minimal budget)") still reads as on. Before this, `reasoning: "low"` changed nothing on any Kimi model: K2.7 Coding offers only `on`, and K3's `low` never matched. + +**Per-session option menus.** A pooled `AcpAgentClient` serves many sessions, but it kept one client-wide `runtimeCapabilities`, overwritten by every `session/new`, option write, and load. `applyReasoning(threadId, …)` and `setModel(threadId, …)` read that shared snapshot. Once sessions can be on different models (0.16.0), and the model decides which thought levels exist, a session could be matched against another session's menu. For example, an enrichment on K3 with a chat thread opened after it on K2.7 got a `low` request matched against `[on]`, and no write was sent. The reverse sent `thinking=low` to a K2.7 session, which the agent refuses. Each session now keeps its own menus, taken from its `session/new` / `session/load` result and refreshed by its own option writes. `setModel`, `applyReasoning`, and a session's runtime-capability notifications read those. A session's menus are built on what `initialize` reported, never on the client-wide snapshot. Before, a new session inherited any menu its `session/new` omitted from whichever session wrote last, current values included, and could skip a write it believed was already applied. The client-wide snapshot remains for agent-level questions (session load, MCP transport support). An option write's reply now updates the session's runtime state as well as its menus, so options the write reshaped report where the agent actually put them. + +**`config_option_update` in the ACP 1.3 shape.** ACP 1.3 defines this update as the full `configOptions` set. The parser read only a single changed option (`update.configOption`), so the spec shape was dropped entirely. Kimi emits it after every model change, and it is the only report `session/set_model` gives (that call answers `{}`). The full set now replaces the session's menus and current values, including `currentModelId`, however the update is keyed (`sessionUpdate`, `session_update`, `kind`, `type`). That means a model the agent changed no longer loses to a stale requested one in `thread_settings`. + +Measured against Kimi Code CLI 2.0.0, with two sessions on one client and the prompt refused locally so no model turn ran: `startThread({ model: "kimi-code/k3" })`, then a chat thread on the default model, then `startTurn({ reasoning: "low" })` on the first. 0.16.0 sends no thinking write. This change sends `thinking=low`, and Kimi's reply confirms `model=kimi-code/k3 thinking=low`. diff --git a/packages/agent-acp/src/acp-client.ts b/packages/agent-acp/src/acp-client.ts index 15cad15..27d5a03 100644 --- a/packages/agent-acp/src/acp-client.ts +++ b/packages/agent-acp/src/acp-client.ts @@ -47,11 +47,13 @@ import { acpRuntimeSupportsSseMcp, acpSessionRuntimeStateFromCapabilities, acpSessionRuntimeStateFromUpdate, + configOptionUpdateSet, mergeAcpRuntimeState, modeLabelFor, modelConfigOption, modelIdFromCapabilities, normalizeAcpRuntimeCapabilities, + runtimeStateFromConfigOptionSet, type AcpRuntimeCapabilities, type AcpRuntimeConfigOptionValue, type AcpSessionRuntimeState @@ -146,6 +148,13 @@ type AcpSessionState = { normalizer: AcpSessionNormalizer; turnId: string | undefined; runtimeState: AcpSessionRuntimeState | undefined; + /** THIS session's option menus (models, modes, config options): what its + * `session/new` / `session/load` returned, refreshed by its own option writes + * and `config_option_update`s. One pooled client serves many sessions and + * the menus differ between them — on Kimi the model decides which thought + * levels exist — so anything choosing a value FOR a session reads this, never + * the client-wide `runtimeCapabilities` whichever session wrote last. */ + runtimeCapabilities: AcpRuntimeCapabilities | undefined; /** The in-flight `session/prompt` completion chain for the active turn. * `startTurnNative` resolves at turn START and streams terminal events from * this chain when the request settles; `undefined` between turns. Awaited by @@ -198,6 +207,11 @@ export class AcpAgentClient implements AgentBackend { private unsubscribeRequest: (() => void) | undefined = undefined; private initialized = false; private runtimeCapabilities?: AcpRuntimeCapabilities; + /** What `initialize` reported: agent-level, and never any one session's. The + * base a session's own menus are built on — the client-wide snapshot above is + * whichever session wrote last, and a fresh session must not inherit its + * menus or their current values. */ + private initializeCapabilities?: AcpRuntimeCapabilities; constructor(options: AcpAgentClientOptions) { this.transport = options.transport; @@ -482,6 +496,7 @@ export class AcpAgentClient implements AgentBackend { normalizer: new AcpSessionNormalizer({ quirks: this.strategy.quirks }), turnId: undefined, runtimeState: undefined, + runtimeCapabilities: undefined, pendingTurn: undefined, pendingInstructions: options.instructions, mcpServerNames: configuredMcpServers.map((server) => server.name) @@ -544,6 +559,7 @@ export class AcpAgentClient implements AgentBackend { normalizer: new AcpSessionNormalizer({ quirks: this.strategy.quirks }), turnId: undefined, runtimeState: undefined, + runtimeCapabilities: undefined, pendingTurn: undefined, pendingInstructions: options.instructions, // Remember ONLY the MCP servers attached to THIS session so the host's @@ -557,9 +573,11 @@ export class AcpAgentClient implements AgentBackend { const runtimeCapabilities = this.captureRuntimeCapabilities( options.lifecycle === "load" ? "session-load" : "session-new", - result + result, + this.sessionBase(session) ); if (runtimeCapabilities) { + session.runtimeCapabilities = runtimeCapabilities; const runtimeState = acpSessionRuntimeStateFromCapabilities( runtimeCapabilities, this.now() @@ -779,12 +797,13 @@ export class AcpAgentClient implements AgentBackend { * `session/set_model` answers `{}` and refreshes only via an async * notification. On Kimi the model DETERMINES which thought levels exist — * `K2.7 Coding` offers only `on`, `K3` offers `low`/`high`/`max` — and - * `applyReasoning` picks from `runtimeCapabilities` on the following + * `applyReasoning` picks from THIS session's menus on the following * `startTurn`, so the refresh this write leaves behind is what it reads. */ async setModel(threadId: string, modelId: string): Promise { + const capabilities = this.sessionCapabilities(threadId); const advertisesModelsCapability = - (this.runtimeCapabilities?.models?.availableModels?.length ?? 0) > 0; - const option = modelConfigOption(this.runtimeCapabilities); + (capabilities?.models?.availableModels?.length ?? 0) > 0; + const option = modelConfigOption(capabilities); if (!advertisesModelsCapability && option !== undefined) { await this.setRuntimeOption(threadId, "modelConfigOption", option.id, modelId); return; @@ -861,8 +880,13 @@ export class AcpAgentClient implements AgentBackend { }, ACP_REQUEST_TIMEOUT_MS ); - const runtimeCapabilities = this.captureRuntimeCapabilities("initialize", result); + const runtimeCapabilities = this.captureRuntimeCapabilities( + "initialize", + result, + this.initializeCapabilities + ); if (runtimeCapabilities) { + this.initializeCapabilities = runtimeCapabilities; this.notifyRuntimeCapabilities({ runtimeCapabilities }); } this.initialized = true; @@ -892,18 +916,33 @@ export class AcpAgentClient implements AgentBackend { return; } + // ACP's `config_option_update` carries the FULL option set, and changing one + // option can reshape another (Kimi's thought levels follow the model) — so + // this session's menus are replaced from it, not just its current values. + if (configOptionUpdateSet(update) !== undefined) { + const refreshed = this.captureRuntimeCapabilities( + // A live refresh of this session's menus, not a load: keep the source + // they were opened with. + session.runtimeCapabilities?.source ?? "session-new", + update, + this.sessionBase(session) + ); + if (refreshed) session.runtimeCapabilities = refreshed; + } + // Runtime-state changes (mode/model/config) ride session/update too. const runtimeState = acpSessionRuntimeStateFromUpdate(update, this.now()); if (runtimeState) { session.runtimeState = mergeAcpRuntimeState(session.runtimeState, runtimeState); - if (this.runtimeCapabilities) { + const capabilities = this.sessionCapabilities(session.threadId); + if (capabilities) { this.notifyRuntimeCapabilities({ threadId: session.threadId, - runtimeCapabilities: this.runtimeCapabilities, + runtimeCapabilities: capabilities, runtimeState: session.runtimeState }); } - this.emitThreadSettings(session, this.runtimeCapabilities, session.runtimeState); + this.emitThreadSettings(session, capabilities, session.runtimeState); return; } @@ -1014,7 +1053,12 @@ export class AcpAgentClient implements AgentBackend { optionId, value ); - const runtimeCapabilities = this.captureRuntimeCapabilities("session-load", result); + const runtimeCapabilities = this.captureRuntimeCapabilities( + "session-load", + result, + this.sessionBase(session) + ); + if (runtimeCapabilities) session.runtimeCapabilities = runtimeCapabilities; const requested: AcpSessionRuntimeState = source === "configOption" ? { configValues: { [optionId]: value }, updatedAt: this.now() } @@ -1031,7 +1075,16 @@ export class AcpAgentClient implements AgentBackend { } : { currentModelId: value, updatedAt: this.now() }; session.runtimeState = mergeAcpRuntimeState(session.runtimeState, requested); - const effectiveCapabilities = runtimeCapabilities ?? this.runtimeCapabilities; + // A write can reshape OTHER options (Kimi moves thinking when the model + // changes), and a reply carrying the full set says how. The agent's report + // goes last: it is what the session is actually at. + const reply = asRecord(result); + const reported = runtimeStateFromConfigOptionSet( + reply?.configOptions ?? reply?.config_options, + this.now() + ); + if (reported) session.runtimeState = mergeAcpRuntimeState(session.runtimeState, reported); + const effectiveCapabilities = this.sessionCapabilities(threadId); if (effectiveCapabilities) { this.notifyRuntimeCapabilities({ threadId, @@ -1081,7 +1134,8 @@ export class AcpAgentClient implements AgentBackend { * If nothing matches we leave it alone — the caller's `.catch` debug-logs. */ private async applyReasoning(threadId: string, reasoning: string): Promise { const target = reasoning.toLowerCase(); - const modes = this.runtimeCapabilities?.modes?.availableModes ?? []; + const capabilities = this.sessionCapabilities(threadId); + const modes = capabilities?.modes?.availableModes ?? []; const modeMatch = modes.find( (mode) => mode.id.toLowerCase() === target || @@ -1091,7 +1145,7 @@ export class AcpAgentClient implements AgentBackend { await this.setMode(threadId, modeMatch.id); return; } - const thinking = this.runtimeCapabilities?.configOptions?.find( + const thinking = capabilities?.configOptions?.find( (option) => option.category === "thought_level" || option.id === "thinking" ); if (thinking !== undefined) { @@ -1124,17 +1178,20 @@ export class AcpAgentClient implements AgentBackend { }; } + /** Normalize `result` into a capability snapshot, filling what it omits from + * `base`. Required, not defaulted: an explicit `undefined` would trigger a + * default parameter, and the only default on hand is the client-wide + * snapshot — which may be another session's. */ private captureRuntimeCapabilities( source: AcpRuntimeCapabilities["source"], - result: unknown + result: unknown, + base: AcpRuntimeCapabilities | undefined ): AcpRuntimeCapabilities | undefined { const runtimeCapabilities = normalizeAcpRuntimeCapabilities({ value: result, now: this.now(), source, - ...(this.runtimeCapabilities !== undefined - ? { initialize: this.runtimeCapabilities } - : {}) + ...(base !== undefined ? { initialize: base } : {}) }); if (runtimeCapabilities) { this.runtimeCapabilities = runtimeCapabilities; @@ -1142,6 +1199,18 @@ export class AcpAgentClient implements AgentBackend { return runtimeCapabilities; } + /** The option menus to consult when choosing a value for `threadId`. A + * session with none of its own gets the agent-level `initialize` menus, never + * another session's. */ + private sessionCapabilities(threadId: string): AcpRuntimeCapabilities | undefined { + return this.sessionBase(this.sessions.get(threadId)); + } + + /** What a session's menus are built on: its own, or `initialize`'s. */ + private sessionBase(session: AcpSessionState | undefined): AcpRuntimeCapabilities | undefined { + return session?.runtimeCapabilities ?? this.initializeCapabilities; + } + private notifyRuntimeCapabilities(event: { threadId?: string | undefined; runtimeCapabilities: AcpRuntimeCapabilities; @@ -1243,21 +1312,27 @@ const HIGH_EFFORT_TOKENS = new Set([ "think" ]); -/** Classify a thinking/thought-level option VALUE as on/off-like from its value - * id + label (e.g. `{ value: "off", label: "Thinking Off" }` → "off"). */ +/** Classify a thinking/thought-level option VALUE from its value id + label + * (e.g. `{ value: "off", label: "Thinking Off" }` → "off"). "low" is a graded + * level that still thinks, just less: some agents offer no off at all — Kimi's + * K3 advertises exactly `low` / `high` / `max` / `on`. */ function thoughtLevelPolarity( value: AcpRuntimeConfigOptionValue -): "on" | "off" | "other" { +): "on" | "low" | "off" | "other" { const haystack = `${value.value} ${value.label ?? ""}`.toLowerCase(); if (/\b(off|none|disabled?|no)\b/.test(haystack)) return "off"; if (/\b(on|enabled?|high|full|yes)\b/.test(haystack)) return "on"; + // After "on", so a value that already read as on (e.g. "On (minimal budget)") + // keeps doing so; only what used to be "other" can become "low". + if (/\b(low|minimal|min|minimum)\b/.test(haystack)) return "low"; return "other"; } /** Pick the value to set on a "thinking" config option for a neutral reasoning - * token: low-effort → the OFF-like value, high-effort → the ON-like value. - * Returns undefined when the token isn't an effort signal we recognize, or the - * option has no value of the needed polarity (caller leaves the option alone). + * token: high-effort → the ON-like value; low-effort → the OFF-like value, or, + * when the agent offers only graded levels, the LOW one — the closest thing to + * off it has. Returns undefined when the token isn't an effort signal we + * recognize, or the option has no value to match (caller leaves it alone). * Exported for testing. */ export function reasoningValueForThoughtLevel( reasoning: string, @@ -1267,8 +1342,12 @@ export function reasoningValueForThoughtLevel( const wantOff = LOW_EFFORT_TOKENS.has(token); const wantOn = HIGH_EFFORT_TOKENS.has(token); if (!wantOff && !wantOn) return undefined; - const desired = wantOff ? "off" : "on"; - return values.find((value) => thoughtLevelPolarity(value) === desired)?.value; + const withPolarity = (polarity: ReturnType) => + values.find((value) => thoughtLevelPolarity(value) === polarity); + if (wantOn) return withPolarity("on")?.value; + // Off beats low: where an agent can switch thinking off entirely, that is + // what a low-effort caller (one-shot enrichment) is asking for. + return (withPolarity("off") ?? withPolarity("low"))?.value; } function buildApprovalRequest(args: { diff --git a/packages/agent-acp/src/normalizer/runtime-capabilities.ts b/packages/agent-acp/src/normalizer/runtime-capabilities.ts index 39f1372..3aac2ac 100644 --- a/packages/agent-acp/src/normalizer/runtime-capabilities.ts +++ b/packages/agent-acp/src/normalizer/runtime-capabilities.ts @@ -8,7 +8,7 @@ // Ported from PwrAgnt acp-runtime-capabilities.ts, retargeted off @pwragent/shared // onto neutral local types. -import { asRecord, readBoolean, readString } from "./content"; +import { asRecord, readBoolean, readKind, readString } from "./content"; export type AcpRuntimeConfigOptionValue = { value: string; @@ -196,9 +196,11 @@ export function acpRuntimeSupportsSseMcp( export function modelConfigOption( capabilities: AcpRuntimeCapabilities | undefined ): AcpRuntimeConfigOption | undefined { - return capabilities?.configOptions?.find( - (option) => option.category === "model" || option.id === "model" - ); + return capabilities?.configOptions?.find(isModelConfigOption); +} + +function isModelConfigOption(option: AcpRuntimeConfigOption): boolean { + return option.category === "model" || option.id === "model"; } /** The effective model id the agent will run with, agnostic of HOW it advertises @@ -280,6 +282,9 @@ export function acpSessionRuntimeStateFromUpdate( return currentModeId ? { currentModeId, updatedAt: now } : undefined; } if (kind === "config_option_update") { + const fullSet = configOptionUpdateSet(update); + if (fullSet !== undefined) return runtimeStateFromConfigOptionSet(fullSet, now); + // Older agents sent the single option that changed. const configOption = asRecord(update.configOption ?? update.config_option) ?? update; const id = readString(configOption, "id") ?? @@ -306,6 +311,37 @@ export function mergeAcpRuntimeState( }; } +/** The option set a `config_option_update` carries in the ACP 1.3 shape — the + * FULL `configOptions` list — or undefined for any other update, including the + * older single-option form. The one place that recognizes this shape: menus and + * runtime state must agree on which updates carry it. */ +export function configOptionUpdateSet(update: Record): unknown[] | undefined { + if (readKind(update) !== "config_option_update") return undefined; + const set = update.configOptions ?? update.config_options; + return Array.isArray(set) ? set : undefined; +} + +/** Every current value in a full option set, and the model among them: a model + * the agent changed (or one `session/set_model` changed, which answers `{}` and + * reports only via `config_option_update`) must not leave a stale + * `currentModelId` winning in thread settings. Undefined for an empty set. */ +export function runtimeStateFromConfigOptionSet( + set: unknown, + now: number +): AcpSessionRuntimeState | undefined { + const options = readConfigOptions(set); + const configValues = Object.fromEntries( + options.flatMap((option) => + option.currentValue !== undefined ? [[option.id, option.currentValue]] : [] + ) + ); + if (Object.keys(configValues).length === 0) return undefined; + const state: AcpSessionRuntimeState = { configValues, updatedAt: now }; + const model = options.find(isModelConfigOption)?.currentValue; + if (model !== undefined) state.currentModelId = model; + return state; +} + /** Resolve the human-facing label for a mode id from the capabilities snapshot. */ export function modeLabelFor( capabilities: AcpRuntimeCapabilities | undefined, diff --git a/packages/agent-acp/test/per-session-capabilities.test.ts b/packages/agent-acp/test/per-session-capabilities.test.ts new file mode 100644 index 0000000..ed8881e --- /dev/null +++ b/packages/agent-acp/test/per-session-capabilities.test.ts @@ -0,0 +1,282 @@ +import { describe, expect, it } from "vitest"; +import type { NormalizedThreadEvent } from "@pwrdrvr/agent-core"; +import { AcpAgentClient } from "../src/acp-client"; +import { kimiStrategy } from "../src/strategies/index"; +import { FakeAcpAgentTransport } from "./fake-acp-agent"; + +const K27 = "kimi-code/kimi-for-coding"; +const K3 = "kimi-code/k3"; + +/** Kimi Code CLI 2.0.0's measured thought levels: the model DECIDES the menu. */ +function thinkingLevels(model: string): string[] { + return model === K3 ? ["low", "high", "max", "on"] : ["on"]; +} + +function kimiConfigOptions(model: string, thinking = "on"): Record[] { + return [ + { + type: "select", + id: "model", + name: "Model", + category: "model", + currentValue: model, + options: [ + { value: K27, name: "K2.7 Coding" }, + { value: K3, name: "K3" } + ] + }, + { + type: "select", + id: "thinking", + name: "Thinking", + category: "thought_level", + currentValue: thinking, + options: thinkingLevels(model).map((value) => ({ value, name: value })) + } + ]; +} + +/** A Kimi-shaped agent: each session has its own model, and a thought level its + * model does not offer is refused — as the real CLI refuses it. */ +class KimiLikeTransport extends FakeAcpAgentTransport { + private sessionCount = 0; + private readonly sessionModels = new Map(); + + override async request( + method: string, + params?: Record, + timeoutMs?: number + ): Promise { + if (method === "session/new") { + await super.request(method, params, timeoutMs); + const sessionId = `session-${++this.sessionCount}`; + this.sessionModels.set(sessionId, K27); + return { sessionId, configOptions: kimiConfigOptions(K27) }; + } + if (method === "session/set_config_option") { + await super.request(method, params, timeoutMs); + const sessionId = String(params?.sessionId); + const value = String(params?.value); + if (params?.configId === "model") { + this.sessionModels.set(sessionId, value); + return { configOptions: kimiConfigOptions(value) }; + } + const model = this.sessionModels.get(sessionId) ?? K27; + if (!thinkingLevels(model).includes(value)) { + throw new Error(`thinking "${value}" is not offered by ${model}`); + } + return { configOptions: kimiConfigOptions(model, value) }; + } + return await super.request(method, params, timeoutMs); + } +} + +function thinkingWrites(transport: FakeAcpAgentTransport): Array> { + return transport.requests + .filter((r) => r.method === "session/set_config_option" && r.params?.configId === "thinking") + .map((r) => r.params ?? {}); +} + +async function startLowTurn( + client: AcpAgentClient, + transport: FakeAcpAgentTransport, + threadId: string +): Promise { + await client.startTurn({ threadId, input: { text: "describe" }, reasoning: "low" }); + transport.finishPrompt(); +} + +describe("one pooled client, sessions on different models", () => { + it("maps reasoning against the session's own thought levels, not the last session opened", async () => { + const transport = new KimiLikeTransport(); + const client = new AcpAgentClient({ transport, strategy: kimiStrategy }); + + const enrichment = await client.startThread({ model: K3 }); // session-1, low offered + await client.startThread(); // session-2 opens on K2.7 — [on] only + + await startLowTurn(client, transport, enrichment.threadId); + + // Read from the client-wide snapshot, this saw session-2's [on] menu and + // sent nothing: K3 ran with thinking on. + expect(thinkingWrites(transport)).toEqual([ + { sessionId: "session-1", configId: "thinking", value: "low" } + ]); + }); + + it("does not send a thought level the session's own model lacks", async () => { + const transport = new KimiLikeTransport(); + const client = new AcpAgentClient({ transport, strategy: kimiStrategy }); + + const chat = await client.startThread(); // session-1 on K2.7 — [on] only + await client.startThread({ model: K3 }); // session-2 — client-wide menu now K3's + + await startLowTurn(client, transport, chat.threadId); + + // Read from the client-wide snapshot, this sent thinking=low to a K2.7 + // session, which the agent refuses. + expect(thinkingWrites(transport)).toEqual([]); + }); + + it("refreshes a session's menus from a full-set config_option_update", async () => { + const transport = new KimiLikeTransport(); + const client = new AcpAgentClient({ transport, strategy: kimiStrategy }); + const thread = await client.startThread(); // K2.7 — [on] only + + // The ACP 1.3 shape: the WHOLE option set, as Kimi emits after a model change. + transport.emitSessionUpdate("session-1", { + sessionUpdate: "config_option_update", + configOptions: kimiConfigOptions(K3) + }); + await startLowTurn(client, transport, thread.threadId); + + expect(thinkingWrites(transport)).toEqual([ + { sessionId: "session-1", configId: "thinking", value: "low" } + ]); + }); + + it("reports the model a full-set config_option_update carries", async () => { + const transport = new KimiLikeTransport(); + const client = new AcpAgentClient({ transport, strategy: kimiStrategy }); + const models: Array = []; + client.onEvent((event: NormalizedThreadEvent) => { + if (event.kind === "thread_settings") models.push(event.settings.model); + }); + await client.startThread({ model: K27 }); + + transport.emitSessionUpdate("session-1", { + sessionUpdate: "config_option_update", + configOptions: kimiConfigOptions(K3) + }); + + // The earlier write recorded currentModelId=K27; the agent's own report of + // the new model must win, not the stale request. + expect(models.at(-1)).toBe(K3); + }); +}); + +describe("a session's menus are its own from the moment it opens", () => { + /** An agent that advertises thinking ONLY at initialize — session/new carries + * no menus — so a new session's menus come entirely from its base. */ + const THINK = (current: string) => [ + { + type: "select", + id: "thinking", + name: "Thinking", + category: "thought_level", + currentValue: current, + options: [ + { value: "off", name: "Off" }, + { value: "on", name: "On" } + ] + } + ]; + + class InitializeMenusTransport extends FakeAcpAgentTransport { + private sessionCount = 0; + override async request( + method: string, + params?: Record, + timeoutMs?: number + ): Promise { + if (method === "initialize") { + await super.request(method, params, timeoutMs); + return { protocolVersion: 1, configOptions: THINK("on") }; + } + if (method === "session/new") { + await super.request(method, params, timeoutMs); + return { sessionId: `session-${++this.sessionCount}` }; + } + if (method === "session/set_config_option") { + await super.request(method, params, timeoutMs); + return { configOptions: THINK(String(params?.value)) }; + } + return await super.request(method, params, timeoutMs); + } + } + + it("does not inherit another session's current values when it opens", async () => { + const transport = new InitializeMenusTransport(); + const client = new AcpAgentClient({ transport, strategy: kimiStrategy }); + + const first = await client.startThread(); + await startLowTurn(client, transport, first.threadId); // session-1 → off + const second = await client.startThread(); // must start from initialize's "on" + await startLowTurn(client, transport, second.threadId); + + // Built on the client-wide snapshot, session-2 opened believing it was + // already "off" (session-1's value) and skipped its own write. + expect(thinkingWrites(transport)).toEqual([ + { sessionId: "session-1", configId: "thinking", value: "off" }, + { sessionId: "session-2", configId: "thinking", value: "off" } + ]); + }); + + it("records a loaded session's menus as its own", async () => { + const transport = new FakeAcpAgentTransport({ + initialize: { protocolVersion: 1, agentCapabilities: { loadSession: true } }, + "session/load": { configOptions: kimiConfigOptions(K3) }, + "session/set_config_option": { configOptions: kimiConfigOptions(K3, "low") } + }); + const client = new AcpAgentClient({ transport, strategy: kimiStrategy }); + + const loaded = await client.loadThreadNative({ sessionId: "session-9" }); + await startLowTurn(client, transport, loaded.threadId); + + expect(thinkingWrites(transport)).toEqual([ + { sessionId: "session-9", configId: "thinking", value: "low" } + ]); + }); +}); + +describe("full-set config_option_update, in every spelling", () => { + it.each([ + ["sessionUpdate", { sessionUpdate: "config_option_update", configOptions: kimiConfigOptions(K3) }], + ["session_update + config_options", { session_update: "config_option_update", config_options: kimiConfigOptions(K3) }], + ["kind", { kind: "config_option_update", configOptions: kimiConfigOptions(K3) }] + ])("refreshes the session's menus when keyed by %s", async (_label, update) => { + const transport = new KimiLikeTransport(); + const client = new AcpAgentClient({ transport, strategy: kimiStrategy }); + const thread = await client.startThread(); // K2.7 — [on] only + + transport.emitSessionUpdate("session-1", update); + await startLowTurn(client, transport, thread.threadId); + + // The runtime state and the menus must agree on which updates carry a full + // set; a `kind`-keyed one used to update the state and leave the menus stale. + expect(thinkingWrites(transport)).toEqual([ + { sessionId: "session-1", configId: "thinking", value: "low" } + ]); + }); +}); + +describe("an option write's reply updates runtime state, not only menus", () => { + it("takes the agent's reported values for options the write reshaped", async () => { + // Kimi 0.29.2 moved thinking to `high` when the model switched to K3. + const transport = new FakeAcpAgentTransport({ + "session/new": { sessionId: "session-1", configOptions: kimiConfigOptions(K27) }, + "session/set_config_option": { configOptions: kimiConfigOptions(K3, "high") } + }); + const client = new AcpAgentClient({ transport, strategy: kimiStrategy }); + const states: Array | undefined> = []; + client.onRuntimeCapabilities((event) => states.push(event.runtimeState?.configValues)); + + await client.startThread({ model: K3 }); + + expect(states.at(-1)).toMatchObject({ model: K3, thinking: "high" }); + }); +}); + +it("labels a notification-driven refresh with the session's own source, not a load", async () => { + const transport = new KimiLikeTransport(); + const client = new AcpAgentClient({ transport, strategy: kimiStrategy }); + const sources: string[] = []; + client.onRuntimeCapabilities((event) => sources.push(event.runtimeCapabilities.source)); + await client.startThread(); + + transport.emitSessionUpdate("session-1", { + sessionUpdate: "config_option_update", + configOptions: kimiConfigOptions(K3) + }); + + expect(sources.at(-1)).toBe("session-new"); +}); diff --git a/packages/agent-acp/test/reasoning-thought-level.test.ts b/packages/agent-acp/test/reasoning-thought-level.test.ts index af157a0..8fed254 100644 --- a/packages/agent-acp/test/reasoning-thought-level.test.ts +++ b/packages/agent-acp/test/reasoning-thought-level.test.ts @@ -30,6 +30,36 @@ describe("reasoningValueForThoughtLevel", () => { expect(reasoningValueForThoughtLevel("", ON_OFF)).toBeUndefined(); }); + it("falls back to the LOW graded level when the agent offers no off", () => { + // Kimi K3: graded levels, no way to switch thinking off. + const graded = [ + { value: "low", label: "Low" }, + { value: "high", label: "High" }, + { value: "max", label: "Max" }, + { value: "on", label: "On" } + ]; + expect(reasoningValueForThoughtLevel("low", graded)).toBe("low"); + expect(reasoningValueForThoughtLevel("high", graded)).toBe("high"); + }); + + it("keeps a value that reads as on as on, even with a low-word in its label", () => { + const labelled = [ + { value: "on", label: "On (minimal budget)" }, + { value: "off", label: "Off" } + ]; + expect(reasoningValueForThoughtLevel("high", labelled)).toBe("on"); + expect(reasoningValueForThoughtLevel("low", labelled)).toBe("off"); + }); + + it("prefers off over a graded low level when both are offered", () => { + const both = [ + { value: "off", label: "Off" }, + { value: "low", label: "Low" }, + { value: "high", label: "High" } + ]; + expect(reasoningValueForThoughtLevel("low", both)).toBe("off"); + }); + it("returns undefined when the option has no value of the needed polarity", () => { // Only an ON-like value exists → a low-effort request can't be satisfied. expect(reasoningValueForThoughtLevel("low", [{ value: "on", label: "On" }])).toBeUndefined();