Compare commits

..

6 Commits

Author SHA1 Message Date
Sampanna Dahal
dc769c132c fix: pass a model id the picker does not list to Claude Code (#1630)
Fixes #1033. Same goal as #1034, which was closed because its rebase
reverted #1458. This version is written against current `main` and keeps
#1458's error codes.

## Problem

`session/set_config_option` refuses a model id that resolves to no entry
of the model option, even when Claude Code runs it. With telemetry off,
Claude Code 2.1.318 lists `default, opus, claude-fable-5-1[1m], sonnet,
haiku`. Against 0.107.0:

```
claude-opus-5-5   -> ok, now opus
claude-fable-5-1  -> ok, now claude-fable-5-1[1m]
claude-fable-5-2  -> -32602 Invalid value for config option model: claude-fable-5-2
claude-opus-4-6   -> -32602 Invalid value for config option model: claude-opus-4-6
```

`ANTHROPIC_MODEL` and a typed `/model` already reach these models, and
the option lists such a model once the session runs it
(`buildModelConfigOption`). Only this path refuses.

## Change

A model id that resolves to no entry goes to `query.setModel` as it is
(`configOptionValue` marks it `unlisted`, and `setSelectedModel` sends
it, shared by v1 and v2). Claude Code is the one that decides. Checked
against CLI 2.1.318 through the SDK's `setModel`:

| Request | Claude Code |
|---|---|
| `claude-fable-5-2`, `claude-opus-4-6`, `claude-opus-4-6[1m]` |
accepted |
| `gpt-4`, `not-a-model`, `son`, `foo-sonnet` | `Model '…' not found` |
| `claude-fable-5-2` with `availableModels: ["sonnet"]` | `Model
"claude-fable-5-2" is restricted by your organization's settings` |

A refusal from Claude Code becomes `-32602` with its reason (`Invalid
value for config option model: gpt-4. Model 'gpt-4' not found`), and the
option stays as it was. For a listed value, a `setModel` failure stays
the internal error it was.

Two cases still refuse without asking Claude Code:

- **A session whose models a `providers/set` gateway listed.** Only
those models can run there, but Claude Code would accept the id. v1
records this as `Session.modelsNarrowedByGateway`; v2 as
`ConfigSetup.narrowsModels`, from `routing.narrowsModels`.
- **Restoring the replaced query's choices after a restart**
(`restoreSessionChoices`, `SessionConfig.restoreFrom`). A model the new
provider dropped falls back as before ("reports the actual fallback when
a model disappears or its switch is refused").

Initial `configOptions` at setup behave like
`session/set_config_option`, as documented: an unlisted id goes to
Claude Code, and an entry it refuses is skipped.

## Tests

- **Updated.** The junk-id cases (`gpt-4`, `not-a-model`, `son`,
`foo-sonnet` in v1; `not-a-model` in v2 and in the setup entries) now
have the mock refuse unknown ids, as Claude Code does. They expect
`-32602` with Claude Code's reason and an unchanged option. "lists an
off-list current model until the session switches away" no longer
expects re-selecting that id to fail.
- **New (v1 and v2):** an unlisted id that Claude Code accepts becomes
the current value and is listed. A gateway-listed session refuses an
unlisted id without calling `setModel`.
- `npm run check`, `npm run build`, and `npm run test:run` all pass
(4146 passed, 34 skipped).
- **End to end:** I built this branch and drove it over ACP stdio
against Claude Code 2.1.318. `claude-fable-5-2` and `claude-opus-4-6`
switch, `gpt-4` gets `-32602 … Model 'gpt-4' not found`, and
`claude-opus-5-5` still resolves to `opus`.

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-16 14:30:58 +01:00
acp-release-bot[bot]
b437e4ee16 chore(main): release 0.107.2 (#1635)
🤖 I have created a release *beep* *boop*
---


##
[0.107.2](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.1...v0.107.2)
(2026-11-16)


### Bug Fixes

* end the turn task of a cycle that has no turn to claim its result
([#1622](https://github.com/agentclientprotocol/claude-agent-acp/issues/1622))
([8de4981](8de49818f1))
* keep Fast mode on when it is turned on after a model switch or
mid-turn
([#1637](https://github.com/agentclientprotocol/claude-agent-acp/issues/1637))
([81650db](81650db3d3))
* list a live Monitor whose task Claude Code reports as local_bash
([#1607](https://github.com/agentclientprotocol/claude-agent-acp/issues/1607))
([41417f6](41417f6eee))
* read the Claude Code stream after a query restart, not at the next
prompt
([#1636](https://github.com/agentclientprotocol/claude-agent-acp/issues/1636))
([c03b66c](c03b66cc9f))
* read the Claude Code stream after every session setup, not at the
first prompt
([#1623](https://github.com/agentclientprotocol/claude-agent-acp/issues/1623))
([7d9e1f6](7d9e1f6135))
* reject the SDK no-token sentinel in auth guards
([#1609](https://github.com/agentclientprotocol/claude-agent-acp/issues/1609))
([c203b91](c203b919ec))
* update to @anthropic-ai/claude-agent-sdk 0.3.325
([#1634](https://github.com/agentclientprotocol/claude-agent-acp/issues/1634))
([db54135](db5413513c))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-16 11:36:50 +00:00
Ben Brandt
81650db3d3 fix: keep Fast mode on when it is turned on after a model switch or mid-turn (#1637)
A user reported that turning Fast mode on "does nothing or keeps getting
reset". This fixes two causes, in both cores.

## Turning Fast mode back on did nothing

Claude Code acts on `applyFlagSettings({ fastMode: true })` only when
its flag does not already hold `true`, and ignores a repeat. Its flag
stays `true` when it stops serving Fast mode at a model switch: Fable
5.2 and Mythos 5.2 take only a Fast mode that was turned on while they
were selected.

So with Fast mode on under Opus:

1. The user switches to Fable 5.2. The toggle still shows on.
2. The next `system`/init reports `fast_mode_state: "off"` with no
reason, and the adapter turns the toggle off.
3. The user turns it on again. The adapter sends `fastMode: true`, which
Claude Code ignores.
4. The next prompt turns the toggle off again.

The adapter now sends `fastMode: false` before `fastMode: true`. This is
a workaround for that Claude Code behaviour (CLI 2.1.325), and
`applyFastModeFlag` in `session-fast-mode.ts` says so.

## A toggle changed during a turn flipped back when the turn ended

Claude Code reads the `fastMode` flag once when a turn starts and builds
that turn's init and its result from the one reading. The result
therefore reported the value from before the request, and the adapter
mirrored it until the next turn's init.

A result that repeats its turn's init is now ignored
(`fastModeResultIsNews`). A result that says more, such as an
`extra_usage_disabled` refusal, is mirrored as before, with its notice.

## Not changed

- Fast mode is still dropped at a switch to Fable 5.2, as in Claude
Code. The toggle shows on until the next prompt's init turns it off,
without a notice. It can now be turned on again.
- A request that Claude Code applies after it read the flag and before
it sent the init is not covered: that init reports the earlier value
too, and the next turn's init corrects the toggle.

## Verification

Drove the built adapter over ACP against Claude Code 2.1.325, with and
without the change. The org check was skipped
(`CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1`) and the prompts were
`/context` only, so this shows the toggle state and makes no model
request.

| step | `fast` on main | `fast` with this change |
| --- | --- | --- |
| turn Fast mode on (Opus 5.5), prompt | on | on |
| switch to Fable 5.2, prompt | off | off |
| turn Fast mode on, prompt | off | on |

The mid-turn case was not run against the real CLI, because it needs a
model turn. It is covered by the tests below.

## Tests

- v1 and v2: a client turns Fast mode on during a turn whose result
repeats the init, and the option stays on. On v1 the same flow with an
`extra_usage_disabled` result turns it off.
- v1 and v2: the requests sent for the toggle are `fastMode: false`,
then `fastMode: true`.
- Unit cases for `fastModeResultIsNews`.

The flow and request tests fail without the change.
2026-11-16 11:33:03 +00:00
Ben Brandt
c03b66cc9f fix: read the Claude Code stream after a query restart, not at the next prompt (#1636)
## Summary

Follow-up to #1623, which left this case open.

On v1, `replaceSessionQuery` resumes a session on a new query in two
cases: a provider change (`providers/set`, `providers/disable`) and a
sign-out respawn under `--hide-claude-auth`. The reader of the old query
ends with that query, and nothing started one for the new query until
the next prompt.

Claude Code can run a cycle of its own on the new query before that
prompt, for example a cron prompt or the follow-up to a finished
background task. Its output waited in the stream. At the next prompt the
consumer read the backlog with the prompt's turn queued, and the first
result in it, which has no `origin`, went to that turn. The prompt
resolved with another cycle's usage and stop reason. #1623 fixed the
same for `session/load`, `session/resume` and `session/fork`.

`replaceSessionQuery` now starts the reader once the session's choices
are restored and published.

## Design

- No new mechanism. `ensureConsumer` already owns starting the reader,
and `replaceSessionQuery` is the one function both restarts go through,
so one call covers the provider restart and the sign-out respawn.
- The reader starts after `restoreSessionChoices` and the
`config_option_update`, so what it reports is read against the restored
state. A setup has the same order: choices first, then the reader.
- The `queryClosed` check is at the call site, as in
`afterSetupResponse`, and not inside `ensureConsumer`. `prompt()` relies
on a consumer that starts on a closed stream to reject its queued turn.
- v2 needs no change: it reads every query from `Session.start()`, a
restart's included. A test now pins that.

Not addressed, as in #1623: a prompt sent while such a cycle is still
running can claim that cycle's result.

## Tests

- v1 (`provider-session-configuration.test.ts`): the new query of a
provider restart sends a cron cycle before the next prompt. The cycle is
read without a prompt, and the prompt gets its own usage. Fails without
the fix.
- v2 (`acp-v2.test.ts`): the same cycle after `providers/set` is
reported as it comes. v2 passed this before the change.
- `providers.test.ts`: the query mock's stream now stays open until
`close()`, like Claude Code's. It ended at once, so the reader that now
starts at a restart closed the query, and "switches every loaded session
through proxy replacements and back to native routing" saw a `close()`
it did not expect.
- Two comments said the reader starts only at a prompt
(`ensureConsumer`, and the Remote Control command). Both now name the
setup and the restart.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,183 tests
pass)
- Not run against the real CLI: no provider restart or sign-out respawn
was driven live.
2026-11-16 11:30:10 +00:00
Jonathan Ellis
7d9e1f6135 fix: read the Claude Code stream after every session setup, not at the first prompt (#1623)
On v1, `ensureConsumer` started only from `prompt()`, Remote Control and
the clear-context coordinator. `session/load`, `session/resume` and
`session/fork` did not start it. A resumed session can run cycles before
the first prompt: a cron prompt that came due while the bridge was down,
or the follow-up of a background task that finished. That output waited
in the stream. When the first prompt arrived, the consumer read the
backlog first, with the prompt's turn queued at the head and not yet
echoed. The first result in the backlog was a cron cycle's, which has no
`origin`, so it took the user lane and `ensureActiveTurn` gave it to the
queued head. The prompt resolved with another cycle's usage and stop
reason, and its own cycle then ran with no turn to claim it.

This change starts the consumer in `afterSetupResponse`, the existing
step that already runs after a setup response and sends the commands and
starts MCP authentication. It runs after a load's replay, so live output
cannot interleave with the replayed history. `ensureConsumer` is
idempotent, so a prompt that arrives later finds the consumer running,
and one that arrives first starts it as before.

## Design

- No new component: `ensureConsumer` already owns starting the reader,
and `afterSetupResponse` already owns "what follows a setup response".
The change is one call and the comments that said otherwise.
- Every setup starts the reader, new sessions included, not only resumed
ones. This is the rule v2 already has (`Session.start()` calls
`consume()` when the session opens), it needs no flag that tells a
resumed setup from a new one, and a new session has no history from
which Claude Code could start a cycle, so for it the early read only
means nothing waits unread.
- It does not start in `createSession`: a load replays history after
`createSession`, and live output from the reader would interleave with
it. `afterSetupResponse` runs after the replay.
- One behavior change: a stream that ends before the first prompt now
closes the session at that moment (the consumer's existing stream-end
handling and `queryClosed`) and not at the first prompt.
- The query mocks in `create-session-options.test.ts` returned an empty
stream, which Claude Code does not. With a reader running from setup,
the empty stream closed the session at once, so the mock now keeps the
stream open until `close()`, like Claude Code's.

## v2

Not affected. `Session.start()` calls `consume(query)` when the session
opens, for new, resumed and forked sessions alike, so output before the
first prompt is reported as it comes. A test in
`src/tests/v2/acp-v2.test.ts` resumes a session that runs a cron cycle
before the first prompt and checks that the cycle is reported apart from
the prompt's turn, with its own usage. It passes with and without this
change.

## Tests

`it.each(["resumeSession", "loadSession"])` in the `session/fork`
describe of `src/tests/v1/acp-agent.test.ts`: that describe holds
`forkingAgent`, the only helper that drives the real setup methods with
a scripted query. It gained a `backlog` parameter for what Claude Code
sends before the first prompt. The test sends a cron cycle (no origin)
and a task-notification cycle as the backlog, waits until the consumer
has read them, then prompts, and checks that the prompt's response
carries its own usage (7 input tokens, not the cron cycle's 111).
Without the fix the consumer never starts before the prompt, so the wait
times out, and with the wait replaced by a fixed delay the response
carries the cron cycle's usage.

This is independent of #1620: each fix passes its own tests alone. #1620
is the case where an unclaimed result leaves the turn task open; this
change removes the way a loaded session got there at its first prompt.

Fixes #1621.

## Validation

Rebased on `main` at 7e857d5.

- `npm run check` and `npm run build` pass.
- `npm run test:run`: 4,135 passed, 36 skipped, 1 failed. The failure is
`tools.test.ts` "picks up a rewrite that restored the modification time
of the file", which also fails on `main` at 7e857d5 without this change.
- The new v1 test fails on `main`, and passes with the fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:16:46 +00:00
Slapoguzov Alexander
c203b919ec fix: reject the SDK no-token sentinel in auth guards (#1609)
The SDK reports `tokenSource: "none"` for a signed-out first-party
account. That non-empty string currently passes the `--hide-claude-auth`
credential guard and suppresses the subscription check. Treat the
sentinel as absent in both shared predicates, so signed-out sessions and
prompts are refused and a known subscription without another credential
retains its specific auth-required reason. Accepted keys, bearer/setup
tokens, external providers and unavailable-account fail-open behavior
are preserved.

Validation: 413 tests pass across the v1 authorization and v2 protocol
suites; 13 regression cases fail on unchanged main. TypeScript build and
lint/format checks pass. Native ACP v1/v2 signed-out session creation
returns auth-required with isolated configuration, no prompts and zero
loopback endpoint requests. Independently reviewed. The full repository
suite and live provider/client acceptance were not run.

Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-16 11:14:18 +00:00
20 changed files with 944 additions and 109 deletions

View File

@@ -1,3 +1,3 @@
{
".": "0.107.1"
".": "0.107.2"
}

View File

@@ -1,5 +1,18 @@
# Changelog
## [0.107.2](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.1...v0.107.2) (2026-11-16)
### Bug Fixes
* end the turn task of a cycle that has no turn to claim its result ([#1622](https://github.com/agentclientprotocol/claude-agent-acp/issues/1622)) ([8de4981](https://github.com/agentclientprotocol/claude-agent-acp/commit/8de49818f1172c5187496a736f721dc6d2ba3fec))
* keep Fast mode on when it is turned on after a model switch or mid-turn ([#1637](https://github.com/agentclientprotocol/claude-agent-acp/issues/1637)) ([81650db](https://github.com/agentclientprotocol/claude-agent-acp/commit/81650db3d3ca6f7b640fd5e1bbb5e1ff45f62fb7))
* list a live Monitor whose task Claude Code reports as local_bash ([#1607](https://github.com/agentclientprotocol/claude-agent-acp/issues/1607)) ([41417f6](https://github.com/agentclientprotocol/claude-agent-acp/commit/41417f6eeeb5010c0eb439e256032cd7e9a44e37))
* read the Claude Code stream after a query restart, not at the next prompt ([#1636](https://github.com/agentclientprotocol/claude-agent-acp/issues/1636)) ([c03b66c](https://github.com/agentclientprotocol/claude-agent-acp/commit/c03b66cc9f1aa6aa5e56668ac05e5a7f48418850))
* read the Claude Code stream after every session setup, not at the first prompt ([#1623](https://github.com/agentclientprotocol/claude-agent-acp/issues/1623)) ([7d9e1f6](https://github.com/agentclientprotocol/claude-agent-acp/commit/7d9e1f6135b2c85cd8bdd0e76bc2bcf00795e6c9))
* reject the SDK no-token sentinel in auth guards ([#1609](https://github.com/agentclientprotocol/claude-agent-acp/issues/1609)) ([c203b91](https://github.com/agentclientprotocol/claude-agent-acp/commit/c203b919ecca8a58e11bebb72274a5a203653d88))
* update to @anthropic-ai/claude-agent-sdk 0.3.325 ([#1634](https://github.com/agentclientprotocol/claude-agent-acp/issues/1634)) ([db54135](https://github.com/agentclientprotocol/claude-agent-acp/commit/db5413513cbe58c045885e6bb015abfdb76be524))
## [0.107.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.0...v0.107.1) (2026-11-16)

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@agentclientprotocol/claude-agent-acp",
"version": "0.107.1",
"version": "0.107.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@agentclientprotocol/claude-agent-acp",
"version": "0.107.1",
"version": "0.107.2",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "2.7.0",

View File

@@ -3,7 +3,7 @@
"publishConfig": {
"access": "public"
},
"version": "0.107.1",
"version": "0.107.2",
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
"main": "dist/lib.js",
"types": "dist/lib.d.ts",

View File

@@ -77,6 +77,11 @@ const API_KEY_SOURCES_ABOVE_SUBSCRIPTION: ReadonlySet<string> = new Set([
"/login managed key",
]);
/** `none` is the SDK's explicit no-token source. */
function hasTokenSource(account: AccountInfo): boolean {
return Boolean(account.tokenSource && account.tokenSource !== "none");
}
/**
* True when a turn on this account is paid by a claude.ai subscription.
*
@@ -85,8 +90,8 @@ const API_KEY_SOURCES_ABOVE_SUBSCRIPTION: ReadonlySet<string> = new Set([
* proves it, and an unknown value keeps the guard on.
*
* - `subscriptionType` must be set. Without it the CLI reports no subscription.
* - `tokenSource` must be absent. The CLI sets it in place of the subscription
* when a bearer or OAuth environment token pays for the turn.
* - `tokenSource` must be absent, empty, or `none`. A bearer or OAuth
* environment token takes precedence over the subscription.
* - `apiProvider` must be absent or `firstParty`. The SDK documents that the
* Anthropic OAuth login applies only to `firstParty`; for a third-party
* backend such as `bedrock`, `vertex`, `foundry` or `gateway` the other
@@ -99,7 +104,7 @@ export function billsClaudeSubscription(account: AccountInfo | undefined): boole
if (!account?.subscriptionType) {
return false;
}
if (account.tokenSource) {
if (hasTokenSource(account)) {
return false;
}
if (account.apiProvider !== undefined && account.apiProvider !== "firstParty") {
@@ -125,7 +130,7 @@ export function holdsNonSubscriptionCredential(account: AccountInfo | undefined)
if (account.apiProvider !== undefined && account.apiProvider !== "firstParty") {
return true;
}
if (account.tokenSource) {
if (hasTokenSource(account)) {
return true;
}
return API_KEY_SOURCES_ABOVE_SUBSCRIPTION.has(account.apiKeySource ?? "");

View File

@@ -192,12 +192,20 @@ export function buildConfigOptions(
* a fallback for resolutions that don't map back onto a selectable option
* (e.g. a fuzzy hit on an out-of-picker verbatim entry). `value` is then the
* canonical option value, the model id rather than the alias.
*
* With `passUnlisted`, a model value that resolves to none of the entries is
* returned as it is, marked `unlisted`, for Claude Code to decide: the CLI's
* picker leaves out models it runs, such as `claude-fable-5-2` before a CLI
* lists it, or `claude-opus-4-6` once a newer Opus replaces it.
* {@link setSelectedModel} refuses it with invalid params when Claude Code
* does. Without it, such a value is refused here.
*/
export function configOptionValue(
option: SessionConfigOption,
params: SetSessionConfigOptionRequest,
modelInfos: ModelInfo[],
): { enabled: boolean } | { value: string } {
passUnlisted = false,
): { enabled: boolean } | { value: string; unlisted?: true } {
const expectedType = option.type === "boolean" ? "boolean" : "string";
if (typeof params.value !== expectedType) {
throw RequestError.invalidParams(
@@ -233,6 +241,9 @@ export function configOptionValue(
}));
validValue = toOptionValue(resolveModelPreference(optionInfos, requested));
}
if (!validValue && passUnlisted && requested.trim() !== "") {
return { value: requested.trim(), unlisted: true };
}
}
if (!validValue) {
throw RequestError.invalidParams(
@@ -242,3 +253,59 @@ export function configOptionValue(
}
return { value: validValue.value };
}
/**
* The codes with which Claude Code's `setModel` refuses a model id that the
* session cannot use: an id it does not know (`not_found`,
* `catalog_unknown`), one that settings restrict (`restricted_by_org`: an
* `availableModels` allowlist, a managed `deniedModels` entry), one the
* account or this CLI does not offer, and a `[1m]` form that is turned off or
* that the model lacks.
*
* Claude Code sends the code as `error_code` of its answer and the SDK
* (0.3.325) copies it to `errorCode` of the error that `setModel()` rejects
* with. The SDK's types do not declare it.
*/
const UNUSABLE_MODEL_ERROR_CODES: ReadonlySet<string> = new Set([
"not_found",
"catalog_unknown",
"restricted_by_org",
"unavailable_for_account",
"not_offered",
"alias_1m_disabled",
"alias_1m_unsupported",
]);
/** Whether `setModel()` rejected with `error` because the session cannot use the model id. */
function refusesModelId(error: unknown): error is Error {
if (!(error instanceof Error)) return false;
const code = (error as { errorCode?: unknown }).errorCode;
return typeof code === "string" && UNUSABLE_MODEL_ERROR_CODES.has(code);
}
/**
* Switches `query` to the model that {@link configOptionValue} selected.
*
* When Claude Code refuses an `unlisted` id as one the session cannot use
* (see {@link UNUSABLE_MODEL_ERROR_CODES}), that is invalid params with Claude
* Code's reason ("Model 'gpt-4' not found"), as for a value the option lacks.
* Every other failure is thrown as it is and reaches the client as an
* internal error: a failed switch to a listed value, and a failure that does
* not judge the id, such as `auth_failed`, `rate_limit`, `check_unreachable`
* (the API did not answer), `blocked_by_hook`, a closed query, or a refusal
* without a code.
*/
export async function setSelectedModel(
query: Pick<Query, "setModel">,
selected: { value: string; unlisted?: true },
): Promise<void> {
try {
await query.setModel(selected.value);
} catch (error) {
if (!selected.unlisted || !refusesModelId(error)) throw error;
throw RequestError.invalidParams(
undefined,
`Invalid value for config option ${MODEL_CONFIG_ID}: ${selected.value}. ${error.message}`,
);
}
}

View File

@@ -130,6 +130,27 @@ export function resolveFastModeEnabled(params: SetSessionConfigOptionRequest): b
);
}
/** Set the Fast mode flag on Claude Code, through `applyFlagSettings`.
*
* Turning it on sends `fastMode: false` first, a workaround for Claude Code
* (CLI 2.1.325): it acts on `fastMode: true` only when its flag does not hold
* `true` already, and ignores a repeat. Its flag stays `true` while it stops
* serving Fast mode at a model switch (Fable 5.2 and Mythos 5.2 take only a
* Fast mode that was turned on while they were selected) and reports
* `fast_mode_state: "off"`. Without the reset, turning the toggle back on
* changes nothing there, and the next `system`/init turns it off again.
*
* A refusal of the reset changes nothing. If Claude Code takes the reset and
* refuses `true`, it is left off; the caller's option keeps its value, and the
* next `system`/init turns off an option that reads on. */
export async function applyFastModeFlag(
applyFlagSettings: (settings: { fastMode: boolean }) => Promise<void>,
enabled: boolean,
): Promise<void> {
if (enabled) await applyFlagSettings({ fastMode: false });
await applyFlagSettings({ fastMode: enabled });
}
/** Per-model Fast mode state threaded into `buildConfigOptions`. The
* option is only surfaced when the current model `supported`s fast mode. */
export type FastModeOptionState = {
@@ -162,8 +183,10 @@ export type FastModeOptionState = {
* `notice` is set when the user had Fast mode on and the SDK turned it off
* with a retained reason: the description carries the same explanation, but a
* toggle silently snapping back is worth saying out loud once. Off with no
* reason, `sdk_opt_in_required` or `pending` stays quiet: a `result` can carry
* the turn-start snapshot, so a notice there would falsely say "turned off". */
* reason, `sdk_opt_in_required` or `pending` stays quiet: a report can carry
* the flag as it was before a request of ours (see
* {@link fastModeResultIsNews}), so a notice there would falsely say "turned
* off". */
export function fastModeStateChange(
current: { enabled: boolean; disabledReason?: FastModeDisabledReason },
state: FastModeState | undefined,
@@ -195,6 +218,41 @@ export function fastModeStateChange(
};
}
/** A Fast mode report of Claude Code: the `fast_mode_state` and
* `fast_mode_disabled_reason` of a `system`/init or of a result. */
export type FastModeReport = {
state: FastModeState | undefined;
reason: FastModeDisabledReason | undefined;
};
/** Whether a result's Fast mode report says something that `init`, the report
* of its turn's `system`/init, did not.
*
* Claude Code (CLI 2.1.325) reads the `fastMode` flag once when a turn starts
* and builds that turn's init and result from the one reading. A result that
* repeats its init therefore predates a `session/set_config_option` that
* arrived in between: mirroring it would turn the toggle back, until the next
* turn's init. What a result adds is what Claude Code evaluates when it sends
* it: a refusal by the account or the model, or the end of one.
*
* Reasons compare as retained ({@link normalizeFastModeDisabledReason}):
* turning Fast mode on mid-turn drops `sdk_opt_in_required` from the result,
* which is no news. True without an init, as for a result whose turn sent none.
*
* Not covered: a request that Claude Code applies after it read the flag and
* before it sent the init. That init reports the earlier value too, and the
* next turn's init corrects the toggle. */
export function fastModeResultIsNews(
init: FastModeReport | undefined,
result: FastModeReport,
): boolean {
if (init === undefined) return true;
return (
result.state !== init.state ||
normalizeFastModeDisabledReason(result.reason) !== normalizeFastModeDisabledReason(init.reason)
);
}
/** The notice of Fast mode that the SDK turned off, and its transcript line
* for a client without `notice` updates. */
export type FastModeOffNotice = {

View File

@@ -62,6 +62,19 @@ export function startupFailure(reason: string, cliMessage: string): Error {
});
}
/**
* The error `setModel()` rejects with when Claude Code refuses the switch, as
* SDK 0.3.325 builds it from the CLI's answer: `errorCode` is the answer's
* `error_code`, such as `not_found` for "Model 'gpt-4' not found".
*/
export function setModelRefusal(message: string, errorCode: string): Error {
return Object.assign(new Error(message), {
telemetryMessage: "Claude Code control request failed (set_model)",
errorClass: "control_request_failed",
errorCode,
});
}
/**
* Declares the client capabilities through `initialize`, as a real client
* does. The agent reads its capability choices only there.

View File

@@ -15020,8 +15020,9 @@ describe("session/fork", () => {
const modes = { currentModeId: "plan", availableModes: [] };
/** An agent whose sessions start without Claude Code: each one gets a
* scripted query that runs `turn` for every prompt. */
function forkingAgent(turn: (prompt: any) => any[] = () => []) {
* scripted query that runs `turn` for every prompt, after it sent `backlog`
* with no prompt open. */
function forkingAgent(turn: (prompt: any) => any[] = () => [], backlog: any[] = []) {
const updates: SessionNotification[] = [];
const agent = new ClaudeAcpAgent(
{ sessionUpdate: async (n: SessionNotification) => updates.push(n) } as unknown as AcpClient,
@@ -15035,6 +15036,7 @@ describe("session/fork", () => {
const sessionId = options.resume as string;
const input = new Pushable<any>();
async function* answer() {
yield* backlog;
for await (const prompt of input) yield* turn(prompt);
}
agent.sessions[sessionId] = mockSessionState(
@@ -15115,6 +15117,57 @@ describe("session/fork", () => {
expect(agent.sessions["fork-id"]).toBe(forked);
});
// After a bridge restart, Claude Code runs a cron cycle and a background
// task's follow-up before the first prompt. Nothing read the stream until
// then, and the prompt took the cron cycle's result as its own.
it.each(["resumeSession", "loadSession"] as const)(
"reads what Claude Code sends before the first prompt after %s (#1621)",
async (method) => {
const state = (state: "running" | "idle") => ({
type: "system",
subtype: "session_state_changed",
state,
uuid: randomUUID(),
session_id: "resumed-id",
});
const usage = (input: number, output: number) => ({
input_tokens: input,
output_tokens: output,
cache_read_input_tokens: 0,
cache_creation_input_tokens: 0,
});
const { agent } = forkingAgent(
(prompt) => [
userEcho(prompt),
state("running"),
successfulResultMessage({ usage: usage(7, 3) }),
state("idle"),
],
[
// A cron prompt: its result has no origin.
state("running"),
successfulResultMessage({ usage: usage(111, 11) }),
state("idle"),
state("running"),
successfulResultMessage({ origin: { kind: "task-notification" }, usage: usage(222, 22) }),
state("idle"),
],
);
// Only a load replays the transcript.
if (method === "loadSession") vi.mocked(getSessionMessages).mockResolvedValueOnce([]);
await agent[method]({ sessionId: "resumed-id", cwd: "/workspace", mcpServers: [] });
// The reader starts after the response.
await vi.waitFor(() => expect(agent.sessions["resumed-id"].lastSessionState).toBe("idle"));
const response = await agent.prompt({
sessionId: "resumed-id",
prompt: [{ type: "text", text: "go on" }],
});
expect(response.usage).toMatchObject({ inputTokens: 7, outputTokens: 3 });
},
);
it("fails when the forked session cannot start", async () => {
const { agent, createSession } = forkingAgent();
createSession.mockRejectedValueOnce(new Error("Claude Code did not start"));

View File

@@ -8,6 +8,7 @@ import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
import { AcpClient } from "../../acp-client.js";
import {
billsClaudeSubscription,
holdsNonSubscriptionCredential,
CLAUDE_LOGIN_REQUIRED_MESSAGE,
CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_MESSAGE,
CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_REASON,
@@ -372,6 +373,32 @@ describe("authorization", () => {
return { cwd: process.cwd(), mcpServers: [] };
}
describe("tokenSource", () => {
it.each([
[undefined, false],
["", false],
["none", false],
["ANTHROPIC_AUTH_TOKEN", true],
["CLAUDE_CODE_OAUTH_TOKEN", true],
["a-future-token-source", true],
] as const)("classifies tokenSource %s", (tokenSource, hasToken) => {
const account = { tokenSource, apiProvider: "firstParty" } satisfies AccountInfo;
expect(holdsNonSubscriptionCredential(account)).toBe(hasToken);
expect(billsClaudeSubscription({ ...account, subscriptionType: "pro" })).toBe(!hasToken);
});
it.each([
{ apiKeySource: "ANTHROPIC_API_KEY" },
{ apiKeySource: "apiKeyHelper" },
{ apiKeySource: "/login managed key" },
{ apiProvider: "bedrock" },
] as const)("preserves an accepted credential beside tokenSource none: %j", (credential) => {
const account = { tokenSource: "none", subscriptionType: "pro", ...credential };
expect(holdsNonSubscriptionCredential(account)).toBe(true);
expect(billsClaudeSubscription(account)).toBe(false);
});
});
describe("billsClaudeSubscription", () => {
/** Every member of the SDK's `ApiKeySource` enum, plus a value no
* current CLI emits: the field is an open `string`, so an unknown one
@@ -445,6 +472,16 @@ describe("authorization", () => {
const CASES: Array<{ name: string; account: AccountInfo; verdict: Verdict }> = [
{ name: "a logged-out CLI", account: {}, verdict: "signedOut" },
{
name: "the SDK reporting no token",
account: { tokenSource: "none", apiProvider: "firstParty" },
verdict: "signedOut",
},
{
name: "a subscription with no token",
account: { tokenSource: "none", subscriptionType: "pro", apiProvider: "firstParty" },
verdict: "subscription",
},
{
name: "an account with no key in use",
account: { apiKeySource: "none" },
@@ -753,15 +790,26 @@ describe("authorization", () => {
prompt: [{ type: "text" as const, text: "hello" }],
});
it("rejects a turn when the live account became a subscription", async () => {
it.each([
[{ subscriptionType: "pro", apiKeySource: "none" }, refusal],
[
{ tokenSource: "none", apiProvider: "firstParty" },
{
code: AUTH_REQUIRED_CODE,
message: `Authentication required: ${LOGIN_REQUIRED_MESSAGE}`,
data: undefined,
},
],
[{ tokenSource: "none", subscriptionType: "pro", apiProvider: "firstParty" }, refusal],
])("rejects a turn before insertion for account %j", async (account, expectedRefusal) => {
const [agent] = await createAgentMock();
hideClaudeAuth();
// Spawn-time account passes; the store changes underneath the session.
const accountInfo = vi.fn(async () => ({ subscriptionType: "pro", apiKeySource: "none" }));
// Start with a legal session, then exercise the per-turn policy independently.
const accountInfo = vi.fn(async () => account);
mockAccount(SIGNED_IN_WITH_KEY, { accountInfo });
const { sessionId } = await agent.newSession(newSessionParams());
await expect(agent.prompt(promptParams(sessionId))).rejects.toMatchObject(refusal);
await expect(agent.prompt(promptParams(sessionId))).rejects.toMatchObject(expectedRefusal);
expect(accountInfo).toHaveBeenCalledTimes(1);
// Refused before anything reached the SDK: no turn was queued.
expect(agent.sessions[sessionId].turnQueue ?? []).toHaveLength(0);

View File

@@ -11,7 +11,7 @@ import type { AcpClient } from "../../acp-client.js";
import type { AcpSessionNotification } from "../../acp-subagents.js";
import { ALLOW_BYPASS } from "../../permissions/modes.js";
import { NativeSubagentRuntime } from "../../native-subagents.js";
import { startupFailure } from "../helpers.js";
import { setModelRefusal, startupFailure } from "../helpers.js";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
@@ -46,9 +46,19 @@ vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
...actual,
query: (args: { prompt: unknown; options: Options }) => {
capturedOptions = args.options;
// Like Claude Code's, the stream stays open until the query is closed.
let streamClosed = () => {};
const closed = new Promise<void>((resolve) => (streamClosed = resolve));
return makeMockQuery({
interrupt: () => (interruptImpl ? interruptImpl() : Promise.resolve(undefined)),
close: () => closeSpy(),
close: () => {
closeSpy();
streamClosed();
},
next: async () => {
await closed;
return { done: true as const, value: undefined };
},
initializationResult: async () => {
await initGate;
if (initError) throw initError;
@@ -1494,9 +1504,13 @@ describe("createSession options merging", () => {
it.each([
["an unknown configId", { configId: "nope", value: "x" }],
["a boolean for a select", { configId: "model", type: "boolean" as const, value: true }],
["a value the option does not offer", { configId: "model", value: "gpt-4" }],
["a model Claude Code does not know", { configId: "model", value: "gpt-4" }],
])("skips an entry with %s and sets the entries after it", async (_name, entry) => {
const plain = await agent.newSession({ cwd, mcpServers: [] });
// An id the option does not list goes to Claude Code, which refuses an unknown one.
setModelImpl = async (model) => {
throw setModelRefusal(`Model '${model}' not found`, "not_found");
};
const response = await agent.newSession({
cwd,

View File

@@ -1,6 +1,10 @@
import { describe, it, expect, vi } from "vitest";
import type { ClientCapabilities, SessionNotification } from "@agentclientprotocol/sdk/unstable";
import type { FastModeDisabledReason, ModelInfo } from "@anthropic-ai/claude-agent-sdk";
import type {
FastModeDisabledReason,
FastModeState,
ModelInfo,
} from "@anthropic-ai/claude-agent-sdk";
import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
import {
buildConfigOptions,
@@ -8,6 +12,7 @@ import {
} from "../../session-config-options.js";
import {
createFastModeConfigOption,
fastModeResultIsNews,
fastModeStateEnabled,
normalizeFastModeDisabledReason,
resolveFastModeEnabled,
@@ -197,6 +202,30 @@ describe("normalizeFastModeDisabledReason", () => {
);
});
describe("fastModeResultIsNews", () => {
type Report = [FastModeState | undefined, FastModeDisabledReason | undefined];
it.each([
["has no init to repeat", undefined, ["off", undefined], true],
["repeats its init", ["off", undefined], ["off", undefined], false],
// Turning Fast mode on mid-turn drops `sdk_opt_in_required` from the result.
[
"differs only by an unexplained reason",
["off", "sdk_opt_in_required"],
["off", undefined],
false,
],
["adds a refusal", ["off", undefined], ["off", "extra_usage_disabled"], true],
["reports another state", ["off", "network_error"], ["on", undefined], true],
] as [string, Report | undefined, Report, boolean][])(
"tells whether a result that %s is news",
(_case, init, result, news) => {
const report = ([state, reason]: Report) => ({ state, reason });
expect(fastModeResultIsNews(init && report(init), report(result))).toBe(news);
},
);
});
describe("buildConfigOptions Fast mode", () => {
it("omits the Fast mode option when the model does not support it", () => {
const options = buildConfigOptions(MODES, MODELS, MODEL_INFOS, undefined, [], "default", {
@@ -271,7 +300,8 @@ describe("setSessionConfigOption Fast mode toggle", () => {
type: "boolean",
value: true,
});
expect(applyFlagSettings).toHaveBeenCalledWith({ fastMode: true });
// Off first: Claude Code ignores a `true` while its flag holds `true`.
expect(applyFlagSettings.mock.calls).toEqual([[{ fastMode: false }], [{ fastMode: true }]]);
expect(onResponse.configOptions).toContainEqual(createFastModeConfigOption(true, true));
expect(
(agent as unknown as { sessions: Record<string, { fastModeEnabled: boolean }> }).sessions[
@@ -285,7 +315,7 @@ describe("setSessionConfigOption Fast mode toggle", () => {
type: "boolean",
value: false,
});
expect(applyFlagSettings).toHaveBeenLastCalledWith({ fastMode: false });
expect(applyFlagSettings.mock.calls.slice(2)).toEqual([[{ fastMode: false }]]);
expect(offResponse.configOptions).toContainEqual(createFastModeConfigOption(false, true));
});
@@ -569,12 +599,18 @@ describe("syncFastModeState (SDK-driven state changes)", () => {
});
});
describe("Fast mode that Claude Code refuses during a turn", () => {
describe("Fast mode that Claude Code reports during a turn", () => {
const SESSION_ID = "test-session";
/** A session whose Claude Code answers the first prompt with a `system`/init
* that reports Fast mode off with `reason`, as it does on every turn. */
async function setupTurn(reason: FastModeDisabledReason) {
* that reports Fast mode off with `reason`, as it does on every turn, and
* then with a result that carries the `result` fields. `duringTurn` runs
* between the two, once the adapter has handled the init. */
async function setupTurn(
reason: FastModeDisabledReason,
result: Record<string, unknown> = {},
duringTurn: (agent: ClaudeAcpAgent) => Promise<unknown> = async () => {},
) {
const updates: SessionNotification[] = [];
const client = {
sessionUpdate: async (n: SessionNotification) => {
@@ -595,7 +631,8 @@ describe("Fast mode that Claude Code refuses during a turn", () => {
fast_mode_disabled_reason: reason,
session_id: SESSION_ID,
};
yield successfulResultMessage();
await duringTurn(agent);
yield successfulResultMessage(result);
yield { type: "system", subtype: "session_state_changed", state: "idle" };
}
const query = Object.assign(wrapQuery(messages()), { applyFlagSettings: async () => {} });
@@ -653,4 +690,41 @@ describe("Fast mode that Claude Code refuses during a turn", () => {
},
]);
});
/**
* Scenario:
* 1. A turn's init reports Fast mode off (`sdk_opt_in_required`: no opt-in yet).
* 2. The client turns Fast mode on while the turn runs.
* 3. The turn's result reports Fast mode off: Claude Code read the flag when
* the turn started. It carries no reason, or the account's refusal.
* Expected:
* - Without a reason the result repeats the init: `fast` stays on, with no update.
* - With `extra_usage_disabled`, `fast` reads off again.
*/
it.each([
["keeps", "repeats the init", {}, true],
["turns off", "adds a refusal", { fast_mode_disabled_reason: "extra_usage_disabled" }, false],
])(
"%s a Fast mode that the client turned on during the turn when the result %s",
async (_outcome, _result, reported, enabled) => {
const { agent, updates } = await setupTurn(
"sdk_opt_in_required",
{ fast_mode_state: "off", ...reported },
(agent) =>
agent.setSessionConfigOption({
sessionId: SESSION_ID,
configId: "fast",
type: "boolean",
value: true,
}),
);
await agent.prompt({ sessionId: SESSION_ID, prompt: [{ type: "text", text: "hi" }] });
expect(agent.sessions[SESSION_ID].fastModeEnabled).toBe(enabled);
expect(updates.filter((n) => n.update.sessionUpdate === "config_option_update")).toHaveLength(
enabled ? 0 : 1,
);
},
);
});

View File

@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -64,6 +65,8 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
let rejectConfigUpdate: boolean;
let models: typeof MODELS;
let mcpServers: Array<{ name: string; status: string }>;
/** What a query that resumes a session sends before it reads a prompt. */
let backlog: any[];
function createQuery(request: { options: Options; prompt: AsyncIterable<any> }) {
const state = {
@@ -108,6 +111,7 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
}),
close: vi.fn(),
[Symbol.asyncIterator]: async function* () {
if (request.options.resume) yield* backlog;
for await (const message of request.prompt) {
calls.push({ prompt: message.message.content, state: { ...state } });
yield userEcho(message);
@@ -137,6 +141,7 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
rejectConfigUpdate = false;
models = MODELS;
mcpServers = [];
backlog = [];
sdk.query.mockImplementation((request) => {
const query = createQuery(request);
queries.push(query);
@@ -340,6 +345,18 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
expect(updates.at(-1).update.configOptions).toEqual(agent.sessions[sessionId].configOptions);
});
// The gateway of `providers/set` listed the models, so only those can run
// there, though Claude Code would take the id.
it("refuses a model id the option does not list without asking Claude Code", async () => {
const { sessionId } = await newSession();
await expect(select(sessionId, "model", "claude-fable-5-2")).rejects.toMatchObject({
code: -32602,
message: expect.stringMatching(/Invalid value for config option model: claude-fable-5-2$/),
});
expect(lastQuery().setModel).not.toHaveBeenCalledWith("claude-fable-5-2");
});
it("restores Auto once the restored model supports it", async () => {
models = MODELS.map((model) =>
model.value === "sonnet" ? { ...model, supportsAutoMode: false } : model,
@@ -639,6 +656,33 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
]);
});
// Claude Code can run a cycle of its own on the new query before the next
// prompt, for example a cron prompt. The reader of the old query ended with
// that query.
it("reads what the new query sends before the next prompt", async () => {
const { sessionId } = await newSession();
// The reader of the first query starts in a timer after the setup response.
// Without this wait the timer would run after the restart and start the
// reader of the new query.
await new Promise((resolve) => setTimeout(resolve, 0));
const state = (state: "running" | "idle") => ({
type: "system",
subtype: "session_state_changed",
state,
uuid: randomUUID(),
session_id: sessionId,
});
const usage = { ...successfulResultMessage().usage, input_tokens: 111 };
// A cron prompt: its result has no origin.
backlog = [state("running"), successfulResultMessage({ usage }), state("idle")];
await refresh();
await vi.waitFor(() => expect(agent.sessions[sessionId].lastSessionState).toBe("idle"));
const response = await prompt(sessionId);
expect(response.usage).toMatchObject({ inputTokens: 0 });
});
it("reports a failed client MCP server once across a provider refresh", async () => {
mcpServers = [{ name: "client-fs", status: "failed" }];
const { sessionId } = await agent.newSession({

View File

@@ -4,20 +4,28 @@ import { AcpClient } from "../../acp-client.js";
import { loggableBaseUrl } from "../../providers.js";
const mockQuery = vi.hoisted(() =>
vi.fn(() => ({
initializationResult: vi.fn().mockResolvedValue({
models: [
{ value: "id", displayName: "name", description: "description", supportsAutoMode: true },
],
}),
setModel: vi.fn(),
setPermissionMode: vi.fn(),
supportedCommands: vi.fn().mockResolvedValue([]),
close: vi.fn(),
interrupt: vi.fn().mockResolvedValue(undefined),
getContextUsage: vi.fn().mockResolvedValue({ totalTokens: 0, rawMaxTokens: 200000 }),
[Symbol.asyncIterator]: async function* () {},
})),
vi.fn(() => {
// Like Claude Code's, the stream stays open until the query is closed.
const closed = Promise.withResolvers<void>();
return {
initializationResult: vi.fn().mockResolvedValue({
models: [
{ value: "id", displayName: "name", description: "description", supportsAutoMode: true },
],
}),
setModel: vi.fn(),
setPermissionMode: vi.fn(),
supportedCommands: vi.fn().mockResolvedValue([]),
close: vi.fn(() => closed.resolve()),
interrupt: vi.fn().mockResolvedValue(undefined),
getContextUsage: vi.fn().mockResolvedValue({ totalTokens: 0, rawMaxTokens: 200000 }),
next: async () => {
await closed.promise;
return { done: true as const, value: undefined };
},
[Symbol.asyncIterator]: async function* () {},
};
}),
);
vi.mock("@anthropic-ai/claude-agent-sdk", async () => ({

View File

@@ -3,7 +3,7 @@ import { SessionNotification } from "@agentclientprotocol/sdk/unstable";
import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
import type { ClaudeAcpAgent as ClaudeAcpAgentType } from "../../v1/acp-agent.js";
import type { AcpClient } from "../../acp-client.js";
import { makeMockQuery } from "../helpers.js";
import { makeMockQuery, setModelRefusal } from "../helpers.js";
const { registerHookCallbackSpy } = vi.hoisted(() => ({
registerHookCallbackSpy: vi.fn(),
@@ -331,18 +331,22 @@ describe("session config options", () => {
expect(modelOption?.currentValue).toBe("claude-sonnet-4-6");
});
// "a" is a substring of "Claude", "son" of "sonnet": only whole words match.
// "a" is a substring of "Claude", "son" of "sonnet": only whole words match,
// so each goes to Claude Code as it is, which refuses an id it does not know.
it.each(["gpt-4", "not-a-model", "son", "foo-sonnet"])(
"rejects the model %s and leaves the model as it was",
"rejects the model %s that Claude Code refuses and leaves the model as it was",
async (value) => {
setModelSpy.mockRejectedValue(setModelRefusal(`Model '${value}' not found`, "not_found"));
await expect(
agent.setSessionConfigOption({ sessionId: SESSION_ID, configId: "model", value }),
).rejects.toMatchObject({
code: -32602,
message: expect.stringContaining(`Invalid value for config option model: ${value}`),
message: expect.stringContaining(
`Invalid value for config option model: ${value}. Model '${value}' not found`,
),
});
expect(setModelSpy).not.toHaveBeenCalled();
expect(setModelSpy).toHaveBeenCalledWith(value);
const session = (
agent as unknown as {
sessions: Record<string, { configOptions: typeof MOCK_CONFIG_OPTIONS }>;
@@ -354,6 +358,28 @@ describe("session config options", () => {
},
);
// These failures do not judge the id, which Claude Code may well run.
it.each([
setModelRefusal("Authentication failed. Please check your API credentials.", "auth_failed"),
setModelRefusal("Network error. Please check your internet connection.", "check_unreachable"),
setModelRefusal("Model switch blocked by a PreModelSwitch hook: not now", "blocked_by_hook"),
// A query that closed: the SDK's own error, with no code.
new Error("Query closed before response received"),
])(
"keeps a failed switch to an unlisted model as the error it is: $message",
async (failure) => {
setModelSpy.mockRejectedValue(failure);
await expect(
agent.setSessionConfigOption({
sessionId: SESSION_ID,
configId: "model",
value: "claude-fable-5-2",
}),
).rejects.toBe(failure);
},
);
it("rejects a non-string value for a select option with invalid params", async () => {
await expect(
agent.setSessionConfigOption({
@@ -1169,13 +1195,21 @@ describe("session config options", () => {
value: "claude-sonnet-4-6",
});
expect(modelValues(switched.configOptions)).toEqual(["claude-opus-4-5", "claude-sonnet-4-6"]);
await expect(
agent.setSessionConfigOption({
sessionId: SESSION_ID,
configId: "model",
value: "claude-offlist-9",
}),
).rejects.toThrow("Invalid value");
});
it("passes a model id the option does not list to Claude Code, and lists it once Claude Code takes it", async () => {
const response = await agent.setSessionConfigOption({
sessionId: SESSION_ID,
configId: "model",
value: "claude-fable-5-2",
});
expect(setModelSpy).toHaveBeenCalledWith("claude-fable-5-2");
const model = response.configOptions?.find((o) => o.id === "model");
expect(model?.currentValue).toBe("claude-fable-5-2");
expect(
(model as { options: { value: string }[] } | undefined)?.options.map((o) => o.value),
).toEqual(["claude-opus-4-5", "claude-sonnet-4-6", "claude-fable-5-2"]);
});
it("setSessionMode also syncs configOptions", async () => {

View File

@@ -36,7 +36,7 @@ import {
v2ConfigOptions,
} from "../../v2/session-requests.js";
import { encodeProjectPath } from "../../session-index/project-dirs.js";
import { startupFailure } from "../helpers.js";
import { setModelRefusal, startupFailure } from "../helpers.js";
import packageJson from "../../../package.json" with { type: "json" };
const execFileSpy = vi.hoisted(() => vi.fn());
@@ -1221,9 +1221,11 @@ describe("ACP v2 sessions", () => {
{ value: "reviewer", name: "reviewer", description: "Reviews changes" },
],
});
// Each value goes to Claude Code before the option shows it.
// Each value goes to Claude Code before the option shows it. Fast mode
// goes off first: Claude Code ignores a `true` while its flag holds `true`.
expect(sdk.flagSettings).toEqual([
{ effortLevel: "high" },
{ fastMode: false },
{ fastMode: true },
{ ultracode: true },
{ agent: "reviewer" },
@@ -1255,9 +1257,9 @@ describe("ACP v2 sessions", () => {
],
// "a" is a substring of "claude": a substring match would pick Opus.
[
"a model the session does not offer",
"a model Claude Code does not know",
{ configId: "model", type: "id", value: "not-a-model" },
"Invalid value for config option model: not-a-model",
"Invalid value for config option model: not-a-model. Model 'not-a-model' not found",
],
[
"a mode the session does not offer",
@@ -1274,6 +1276,10 @@ describe("ACP v2 sessions", () => {
async (_case, request, message) => {
const models: Array<string | undefined> = [];
sdk.setModel = async (model) => {
// Claude Code refuses an id it does not know.
if (model === "not-a-model") {
throw setModelRefusal(`Model '${model}' not found`, "not_found");
}
models.push(model);
};
const client = v2Client();
@@ -1300,6 +1306,140 @@ describe("ACP v2 sessions", () => {
},
);
it("passes a model id the option does not list to Claude Code, and lists it once Claude Code takes it", async () => {
const models: Array<string | undefined> = [];
sdk.setModel = async (model) => {
models.push(model);
};
const client = v2Client();
const response = await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
const response = await agent.request(v2.methods.agent.session.setConfigOption, {
sessionId,
configId: "model",
type: "id",
value: "claude-fable-5-2",
});
await client.authUpdate(1);
return response;
});
expect(models).toEqual(["claude-fable-5-2"]);
const model = response.configOptions.find((option) => option.configId === "model");
expect(model?.currentValue).toBe("claude-fable-5-2");
expect(
(model as { options: { value: string }[] } | undefined)?.options.map(
(entry) => entry.value,
),
).toContain("claude-fable-5-2");
});
it("refuses a model id the option does not list when a gateway listed the models", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response(JSON.stringify({ data: [{ id: OPUS.value }] }))),
);
const models: Array<string | undefined> = [];
sdk.setModel = async (model) => {
models.push(model);
};
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
await agent.request(v2.methods.agent.providers.set, {
providerId: "main",
apiType: "anthropic",
baseUrl: "https://gateway.example.com",
});
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
await expect(
agent.request(v2.methods.agent.session.setConfigOption, {
sessionId,
configId: "model",
type: "id",
value: "claude-fable-5-2",
}),
).rejects.toMatchObject({
code: -32602,
message: expect.stringMatching(
/Invalid value for config option model: claude-fable-5-2$/,
),
});
await client.authUpdate(1);
});
expect(models).not.toContain("claude-fable-5-2");
});
// The failure does not judge the id, which Claude Code may well run.
it("answers a failed switch to an unlisted model with an internal error when Claude Code did not refuse the id", async () => {
sdk.setModel = async () => {
throw setModelRefusal(
"Authentication failed. Please check your API credentials.",
"auth_failed",
);
};
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
await expect(
agent.request(v2.methods.agent.session.setConfigOption, {
sessionId,
configId: "model",
type: "id",
value: "claude-fable-5-2",
}),
).rejects.toMatchObject({ code: -32603 });
await client.authUpdate(1);
});
});
// The query of a restart may run on a provider that cannot serve the model
// of the query it replaces, though Claude Code would take the id.
it("does not pass the model of a replaced query to Claude Code when the new query does not list it", async () => {
vi.stubGlobal(
"fetch",
vi.fn(
async () =>
new Response(JSON.stringify({ data: [{ id: OPUS.value }, { id: HAIKU.value }] })),
),
);
const models: Array<string | undefined> = [];
sdk.setModel = async (model) => {
models.push(model);
};
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
await agent.request(v2.methods.agent.providers.set, {
providerId: "main",
apiType: "anthropic",
baseUrl: "https://gateway.example.com",
});
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
await agent.request(v2.methods.agent.session.setConfigOption, {
sessionId,
configId: "model",
type: "id",
value: HAIKU.value,
});
// Without the gateway, the session's new query lists Opus only.
sdk.initializationResult = async () => ({ models: [OPUS] });
await agent.request(v2.methods.agent.providers.disable, { providerId: "main" });
await client.authUpdate(1);
});
expect(models).toEqual([HAIKU.value]);
expect(
client
.updates("config_option_update")
.at(-1)
?.configOptions.find((option) => option.configId === "model"),
).toMatchObject({ currentValue: OPUS.value });
});
it("rebuilds the options for a model switch, and clears an effort the new model lacks", async () => {
const client = v2Client();
const response = await client.app.connectWith(connectRouter(), async (agent) => {
@@ -1399,6 +1539,7 @@ describe("ACP v2 sessions", () => {
expect(sdk.queryOptions[1].effort).toBeUndefined();
expect(sdk.flagSettings).toEqual([
{ ultracode: true },
{ fastMode: false },
{ fastMode: true },
{ effortLevel: "low", ultracode: true },
{ agent: "reviewer" },
@@ -1490,6 +1631,48 @@ describe("ACP v2 sessions", () => {
});
});
/**
* Scenario:
* 1. A turn's `system`/init reports Fast mode off (`sdk_opt_in_required`: no opt-in yet).
* 2. The client turns Fast mode on while the turn runs.
* 3. The turn's result reports Fast mode off without a reason: Claude Code
* read the flag when the turn started.
* Expected:
* - The `fast` option stays on: the only update is the one that turned it on.
*/
it("keeps a Fast mode that the client turned on during the turn", async () => {
const initHandled = Promise.withResolvers<void>();
const turnedOn = Promise.withResolvers<void>();
scriptTurns(async function* (options) {
yield fastModeInit(options, "off", "sdk_opt_in_required");
initHandled.resolve();
await turnedOn.promise;
yield assistantText(options, "Done.");
yield result(options, { fast_mode_state: "off" });
yield idleState(options);
});
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
await agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: text("hi") });
await initHandled.promise;
await agent.request(v2.methods.agent.session.setConfigOption, {
sessionId,
configId: "fast",
type: "boolean",
value: true,
});
turnedOn.resolve();
await vi.waitFor(() => expect(turnTrace(client.sessionUpdates)).toContain("idle end_turn"));
await client.authUpdate(1);
});
const updates = client.updates("config_option_update");
expect(updates).toHaveLength(1);
expect(fastOption(updates[0])).toMatchObject({ currentValue: true });
});
it("reports a refusal fallback with a notice and follows the model it swapped to", async () => {
sdk.initializationResult = async () => ({ models: [OPUS, HAIKU] });
scriptTurns(async function* (options) {
@@ -4573,6 +4756,69 @@ describe("ACP v2 model cycles that Claude Code starts on its own", () => {
expect(turnTrace(client.sessionUpdates).at(-1)).toBe("idle end_turn");
});
// A resumed session can run cycles before its first prompt, for example a
// cron prompt. v2 reads the query from the start of the session, so that
// output is reported as it comes and does not answer the prompt.
it("reports a cycle that a resumed session runs before the first prompt, apart from the prompt's turn", async () => {
sdk.run = async function* (prompts, options) {
const input = prompts[Symbol.asyncIterator]();
if (!options.resume) {
while (!(await input.next()).done);
return;
}
// A cron prompt: its result has no origin.
yield assistantText(options, "Checked the build.", "msg_cron");
yield result(options, { usage: { ...result(options).usage, input_tokens: 111 } });
yield idleState(options);
const { value } = await input.next();
yield {
type: "user",
message: value!.message,
parent_tool_use_id: null,
uuid: value!.uuid,
session_id: options.sessionId,
isReplay: true,
};
yield assistantText(options, "Here is the answer.");
yield result(options, { usage: { ...result(options).usage, input_tokens: 7 } });
yield idleState(options);
while (!(await input.next()).done);
};
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
await agent.request(v2.methods.agent.session.close, { sessionId });
await agent.request(v2.methods.agent.session.resume, { sessionId, cwd });
await vi.waitFor(() =>
expect(turnTrace(client.sessionUpdates)).toContain("agent_message_chunk"),
);
await agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: text("hi") });
await vi.waitFor(() =>
expect(
turnTrace(client.sessionUpdates).filter((state) => state.startsWith("idle end")),
).toHaveLength(2),
);
await client.authUpdate(1);
});
// Without the `idle` that the resume reports.
expect(turnTrace(client.sessionUpdates).filter((state) => state !== "idle")).toEqual([
"running",
"agent_message_chunk",
"idle end_turn",
"user_message",
"running",
"agent_message_chunk",
"idle end_turn",
]);
expect(
client
.updates("state_update")
.filter((update: any) => update.stopReason)
.map((update: any) => update.usage.inputTokens),
).toEqual([111, 7]);
});
it("ends the tool call that a cancelled cycle runs with Claude Code's result, before idle cancelled", async () => {
const interrupted = Promise.withResolvers<void>();
sdk.interrupt = async () => interrupted.resolve();
@@ -9991,6 +10237,36 @@ describe("ACP v2 providers", () => {
});
});
// The new query of a restart can run a cycle before the next prompt, for
// example a cron prompt. v2 reads every query from its start, so the cycle
// is reported as it comes.
it("reports a cycle that the new query of a restart runs before the next prompt", async () => {
sdk.run = async function* (prompts, options) {
if (options.resume) {
// A cron prompt: its result has no origin.
yield assistantText(options, "Checked the build.", "msg_cron");
yield result(options);
yield idleState(options);
}
const input = prompts[Symbol.asyncIterator]();
while (!(await input.next()).done);
};
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
await agent.request(v2.methods.agent.session.new, { cwd });
await setGateway(agent);
await vi.waitFor(() =>
expect(turnTrace(client.sessionUpdates)).toEqual([
"running",
"agent_message_chunk",
"idle end_turn",
]),
);
await client.authUpdate(1);
});
});
it("routes only the sessions started after a gateway login", async () => {
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
@@ -10180,7 +10456,7 @@ describe("ACP v2 subscription guard (--hide-claude-auth)", () => {
});
/** Each query caches the next of `accounts` at its start, and the last one after them. */
function accountsAtStart(...accounts: Array<Record<string, unknown>>) {
function accountsAtStart(...accounts: Array<Record<string, unknown> | undefined>) {
let started = 0;
sdk.initializationResult = async () => ({
...(await sdkDefaults.initializationResult()),
@@ -10191,6 +10467,12 @@ describe("ACP v2 subscription guard (--hide-claude-auth)", () => {
it.each([
["a subscription would pay", SUBSCRIPTION, NOT_SUPPORTED],
["the account holds no credential", {}, { code: -32000, data: undefined }],
[
"the SDK reports no token",
{ tokenSource: "none", apiProvider: "firstParty" },
{ code: -32000, data: undefined },
],
["a subscription has no token", { ...SUBSCRIPTION, tokenSource: "none" }, NOT_SUPPORTED],
])("refuses session/new when %s", async (_case, account, refusal) => {
accountsAtStart(account);
const client = v2Client();
@@ -10202,16 +10484,45 @@ describe("ACP v2 subscription guard (--hide-claude-auth)", () => {
});
});
it("refuses a prompt before insertion when the cached account bills a subscription", async () => {
it.each([
["an API key", { ...API_KEY, tokenSource: "none" }],
["an API key helper", { apiKeySource: "apiKeyHelper", tokenSource: "none" }],
["a Console key", { apiKeySource: "/login managed key", tokenSource: "none" }],
["a bearer token", { tokenSource: "ANTHROPIC_AUTH_TOKEN" }],
["a setup token", { tokenSource: "CLAUDE_CODE_OAUTH_TOKEN" }],
["external credentials", { apiProvider: "bedrock", tokenSource: "none" }],
["an unavailable account", undefined],
])("allows session/new with %s", async (_case, account) => {
accountsAtStart(account);
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
await expect(agent.request(v2.methods.agent.session.new, { cwd })).resolves.toMatchObject({
sessionId: expect.any(String),
});
});
});
it.each([
[SUBSCRIPTION, NOT_SUPPORTED],
[
{ tokenSource: "none", apiProvider: "firstParty" },
{ code: -32000, data: undefined },
],
[{ ...SUBSCRIPTION, tokenSource: "none" }, NOT_SUPPORTED],
])("refuses a prompt before insertion for account %j", async (account, refusal) => {
accountsAtStart(API_KEY);
scriptTurns(async function* (options) {
yield result(options);
});
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
sdk.accountInfo = async () => SUBSCRIPTION;
sdk.accountInfo = async () => account;
await expect(
agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: text("hi") }),
).rejects.toMatchObject(NOT_SUPPORTED);
).rejects.toMatchObject(refusal);
await client.authUpdate(1);
});

View File

@@ -405,15 +405,19 @@ import {
clientSupportsBooleanConfigOptions,
clientSupportsRecommendedConfigValue,
configOptionValue,
setSelectedModel,
discoverCustomAgents,
} from "../session-config-options.js";
import {
applyFastModeFlag,
createFastModeConfigOption,
FAST_MODE_CONFIG_ID,
fastModeResultIsNews,
fastModeStateChange,
fastModeStateEnabled,
normalizeFastModeDisabledReason,
type FastModeOptionState,
type FastModeReport,
} from "../session-fast-mode.js";
import {
cacheResultContextWindow,
@@ -1070,11 +1074,15 @@ export type Session = {
/** Why the SDK currently can't serve Fast mode: the last
* `fast_mode_disabled_reason` that `explainFastModeDisabledReason` explains.
* {@link normalizeFastModeDisabledReason} drops the two it doesn't,
* `sdk_opt_in_required` and `pending`, to `undefined`. Refreshed from every
* `fast_mode_disabled_reason` the SDK reports on `system`/init and user-turn
* `result`s; surfaced in the Fast mode option's description so a toggle that
* snaps back off explains itself. */
* `sdk_opt_in_required` and `pending`, to `undefined`. Refreshed from the
* `fast_mode_disabled_reason` the SDK reports on every `system`/init, and on
* a user-turn `result` that does not repeat its init; surfaced in the Fast
* mode option's description so a toggle that snaps back off explains itself. */
fastModeDisabledReason?: FastModeDisabledReason;
/** The Fast mode report of the last `system`/init, until a result of a
* prompt takes it: a result that repeats it is not mirrored (see
* {@link fastModeResultIsNews}). */
fastModeInitReport?: FastModeReport;
abortController: AbortController;
/** Signal the consumer races `query.next()` against. Aborted by cancel()
* (after a grace period) to force the active turn to settle "cancelled" when
@@ -1122,6 +1130,10 @@ export type Session = {
* the process-wide provider config can change while a session is being
* created, while the query stays baked to the env it was created with. */
providerCacheKey: string;
/** A `providers/set` gateway listed the models, so only those can run: a
* model id the option does not list is refused rather than passed to
* Claude Code (`configOptionValue`). */
modelsNarrowedByGateway?: boolean;
/** Accumulated task list for the session, keyed by task ID. Task IDs are
* per-session, so this state must not be shared across sessions. */
taskState: TaskState;
@@ -2475,8 +2487,10 @@ export class ClaudeAcpAgent {
}
// Once Remote Control is on, other clients can start turns or send
// messages on their own. Something has to read the query stream for
// those to reach this client, and a command that answers without a turn
// would otherwise leave the stream unread until the next prompt.
// those to reach this client. The reader starts after the session's
// setup response and after a query restart; a command that comes before
// the setup's timer ran (see `afterSetupResponse`) answers without a
// turn and would leave the stream unread until that timer.
this.ensureConsumer(session, params.sessionId);
// Answered by the adapter without a model turn.
events.inserted(randomUUID());
@@ -3071,7 +3085,9 @@ export class ClaudeAcpAgent {
}
/** Lazily start the per-session consumer that drains the SDK query stream for
* the session's whole life. Idempotent: only the first `prompt()` starts it. */
* the session's whole life. Idempotent: the first caller starts it, a
* session setup (see `afterSetupResponse`), a query restart (see
* `replaceSessionQuery`) or a `prompt()`. */
private ensureConsumer(session: Session, sessionId: string): void {
if (session.consumer) {
return;
@@ -4696,6 +4712,10 @@ export class ClaudeAcpAgent {
// A fresh `system`/init (e.g. after reinitialize) can carry an
// updated Fast mode state; reconcile it with what we seeded at
// session creation.
session.fastModeInitReport = {
state: message.fast_mode_state,
reason: message.fast_mode_disabled_reason,
};
await this.syncFastModeState(
params.sessionId,
session,
@@ -5563,17 +5583,27 @@ export class ClaudeAcpAgent {
const pendingExitPlanModeInterruption = session.pendingExitPlanModeInterruption;
const pendingExitPlanContextReset = session.pendingExitPlanContextReset;
try {
// Reconcile the Fast mode toggle with the SDK's reported state.
// Reconcile the Fast mode toggle with the SDK's reported state,
// unless the result repeats its turn's init (see
// `fastModeResultIsNews`).
// Gated to user-driven turns like every other side effect below;
// an autonomous cycle's state lands on the next user turn's
// result. Runs even when the turn errors or was cancelled.
if (!isAutonomousResult) {
await this.syncFastModeState(
params.sessionId,
session,
message.fast_mode_state,
message.fast_mode_disabled_reason,
);
const fastModeInitReport = session.fastModeInitReport;
session.fastModeInitReport = undefined;
const fastModeReport = {
state: message.fast_mode_state,
reason: message.fast_mode_disabled_reason,
};
if (fastModeResultIsNews(fastModeInitReport, fastModeReport)) {
await this.syncFastModeState(
params.sessionId,
session,
message.fast_mode_state,
message.fast_mode_disabled_reason,
);
}
}
// A user-turn result needs an active turn so its stop reason is
@@ -7777,11 +7807,14 @@ export class ClaudeAcpAgent {
/**
* `duringSetup`: the value is one of a setup request's `configOptions`. No
* mode update goes out, and the warning of an Auto mode fallback waits for
* the next prompt.
* the next prompt. `restoring`: the value is the replaced query's
* (`restoreSessionChoices`), so a model id the option does not list is
* refused rather than passed to Claude Code.
*/
private async selectSessionConfigOption(
params: SetSessionConfigOptionRequest,
duringSetup = false,
restoring = false,
): Promise<SetSessionConfigOptionResponse> {
const session = this.sessions[params.sessionId];
if (!session) {
@@ -7799,7 +7832,12 @@ export class ClaudeAcpAgent {
if (!option) {
throw RequestError.invalidParams(undefined, `Unknown config option: ${params.configId}`);
}
const selected = configOptionValue(option, params, session.modelInfos);
const selected = configOptionValue(
option,
params,
session.modelInfos,
!restoring && !session.modelsNarrowedByGateway,
);
if ("enabled" in selected) {
if (params.configId === FAST_MODE_CONFIG_ID) {
await this.applyFastMode(session, selected.enabled);
@@ -7819,7 +7857,7 @@ export class ClaudeAcpAgent {
);
if (!duringSetup) await this.sessionModes.publishCurrent(params.sessionId, effectiveValue);
} else if (params.configId === MODEL_CONFIG_ID) {
await this.sessions[params.sessionId].query.setModel(resolvedValue);
await setSelectedModel(this.sessions[params.sessionId].query, selected);
}
// Effort SDK sync is handled inside applyConfigOptionValue so that direct
// effort changes and effort changes induced by a model switch go through
@@ -9231,9 +9269,9 @@ export class ClaudeAcpAgent {
}
/**
* The work that follows a session setup response: the session's commands,
* the current states of the subagents a load replayed, and MCP server
* authentication.
* The work that follows a session setup response: reading the session's
* query, the session's commands, the current states of the subagents a load
* replayed, and MCP server authentication.
*
* Call it in the same synchronous step as the handler's `return`: an
* `await` between them would let the timer run before the response. The ACP
@@ -9248,6 +9286,14 @@ export class ClaudeAcpAgent {
*/
private afterSetupResponse(sessionId: string, mcpServers: McpServer[]): void {
setTimeout(() => {
// Claude Code can run cycles of its own before the first prompt, for
// example a cron prompt or a finished background task of a session that a
// bridge restart resumed. Output that nothing reads waits in the stream,
// and the first prompt would take the first result in it as its answer.
// After the load's replay, so live output does not interleave with the
// replayed history.
const session = this.sessions[sessionId];
if (session && !session.queryClosed) this.ensureConsumer(session, sessionId);
this.sendAvailableCommandsUpdate(sessionId);
void this.publishCurrentSubagentStates(sessionId);
startMcpAuthentication(this, sessionId, mcpServers);
@@ -9569,8 +9615,9 @@ export class ClaudeAcpAgent {
* option is guaranteed to be present in `configOptions`. */
private async applyFastMode(session: Session, enabled: boolean): Promise<void> {
// Apply the SDK flag first so a rejected control request leaves both the
// session state and the config option untouched (no UI/SDK desync).
await session.query.applyFlagSettings({ fastMode: enabled });
// session state and the config option untouched (see `applyFastModeFlag`
// for a refusal after its reset).
await applyFastModeFlag((settings) => session.query.applyFlagSettings(settings), enabled);
session.fastModeEnabled = enabled;
this.refreshFastModeOption(session, enabled);
}
@@ -10470,6 +10517,7 @@ export class ClaudeAcpAgent {
contextWindowSize: seededWindow.size,
contextWindowAuthoritative: seededWindow.authoritative,
providerCacheKey,
modelsNarrowedByGateway: resolvedProvider?.listedModels !== undefined,
taskState,
subagentChecklists: creationOpts.replayState?.subagentChecklists ?? new Set(),
toolUseCache: {},
@@ -10605,7 +10653,7 @@ export class ClaudeAcpAgent {
}
}
/** Recreates the session's query and restores its choices and reported MCP servers, unless it was closed meanwhile. */
/** Recreates the session's query, restores its choices and reported MCP servers, and starts reading it, unless it was closed meanwhile. */
private async replaceSessionQuery(
sessionId: string,
session: Session,
@@ -10638,6 +10686,12 @@ export class ClaudeAcpAgent {
error,
);
});
// The reader of the old query ended with that query. Claude Code can run
// cycles of its own on the new one before the next prompt, for example a
// cron prompt or the follow-up to a finished background task, and that
// prompt would take the first unread result as its answer. After the
// choices are restored, so the reader reports against the restored state.
if (!recreated.queryClosed) this.ensureConsumer(recreated, sessionId);
}
/** Re-applies the choices of `previous` to the session that replaced it; a choice the new query rejects is logged. */
@@ -10658,7 +10712,8 @@ export class ClaudeAcpAgent {
};
const select = (configId: string, value: string) =>
restore(`${configId} "${value}"`, () =>
this.selectSessionConfigOption({ sessionId, configId, value }),
// A model the new query does not list falls back: it may be one the new provider cannot serve.
this.selectSessionConfigOption({ sessionId, configId, value }, false, true),
);
// First: the model decides which modes, effort levels, Fast mode and ultracode exist.

View File

@@ -1186,6 +1186,7 @@ class V2Agent implements AgentHandle, SessionConnection {
client,
effortSettings: () => mergeEffortSettings(settings.getSettings(), configured),
recommendedValue: this.air.recommendedValue,
narrowsModels: routing.narrowsModels,
},
(notification) => session.output.emitV1([notification]),
this.logger,

View File

@@ -51,6 +51,7 @@ import {
AGENT_CONFIG_ID,
buildConfigOptions,
configOptionValue,
setSelectedModel,
discoverCustomAgents,
} from "../session-config-options.js";
import {
@@ -62,11 +63,14 @@ import {
type EffortState,
} from "../session-effort.js";
import {
applyFastModeFlag,
createFastModeConfigOption,
FAST_MODE_CONFIG_ID,
fastModeResultIsNews,
fastModeStateChange,
fastModeStateEnabled,
normalizeFastModeDisabledReason,
type FastModeReport,
} from "../session-fast-mode.js";
import {
MODEL_CONFIG_ID,
@@ -116,6 +120,8 @@ export interface ConfigSetup {
effortSettings(): Settings;
/** The client declared AIR's `recommendedValue` (see the module doc). */
recommendedValue: boolean;
/** A `providers/set` gateway listed the models, so only those can run. */
narrowsModels: boolean;
}
export class SessionConfig {
@@ -128,10 +134,14 @@ export class SessionConfig {
private effort: EffortState;
private fastModeEnabled: boolean;
private fastModeDisabledReason: FastModeDisabledReason | undefined;
/** The Fast mode report of the last `system`/init, until a result of a prompt takes it. */
private fastModeInitReport: FastModeReport | undefined;
private ultracodeEnabled: boolean;
private readonly ultracodeWorkflowsEnabled: boolean | undefined;
/** The end of the last change (see the module doc). */
private changes: Promise<void> = Promise.resolve();
/** A model id the option does not list goes to Claude Code (`configOptionValue`), unless a gateway listed the models. */
private readonly passUnlistedModels: boolean;
private constructor(
private readonly sessionId: string,
@@ -157,7 +167,9 @@ export class SessionConfig {
private readonly notify: (notification: SessionNotification) => void,
private readonly logger: Logger,
autoModeFallbackWarningPending: boolean,
narrowsModels: boolean,
) {
this.passUnlistedModels = !narrowsModels;
this.session = {
query,
modes,
@@ -294,6 +306,7 @@ export class SessionConfig {
notify,
logger,
autoModeFallbackWarningPending,
setup.narrowsModels,
);
}
@@ -379,7 +392,8 @@ export class SessionConfig {
};
const select = (configId: string, value: string) =>
restore(`${configId} "${value}"`, () =>
this.apply({ sessionId: this.sessionId, configId, type: "id", value }),
// A model the new query does not list falls back: it may be one the new provider cannot serve.
this.apply({ sessionId: this.sessionId, configId, type: "id", value }, false, true),
);
const model = previous.session.models.currentModelId;
if (this.session.models.currentModelId !== model) await select(MODEL_CONFIG_ID, model);
@@ -425,10 +439,15 @@ export class SessionConfig {
return result;
}
/** `duringSetup`: see {@link setInitial}. */
/**
* `duringSetup`: see {@link setInitial}. `restoring`: the value is the
* previous query's ({@link restoreFrom}), so a model id the option does not
* list is refused rather than passed to Claude Code.
*/
private async apply(
params: v2.SetSessionConfigOptionRequest,
duringSetup = false,
restoring = false,
): Promise<void> {
const request = v1SetSessionConfigOptionRequest(params);
const option = this.session.configOptions.find((entry) => entry.id === request.configId);
@@ -438,7 +457,12 @@ export class SessionConfig {
`Unknown config option: ${request.configId}`,
);
}
const selected = configOptionValue(option, request, this.modelInfos);
const selected = configOptionValue(
option,
request,
this.modelInfos,
this.passUnlistedModels && !restoring,
);
if ("enabled" in selected) {
if (request.configId === FAST_MODE_CONFIG_ID) await this.setFastMode(selected.enabled);
else await this.setUltracode(selected.enabled);
@@ -450,7 +474,7 @@ export class SessionConfig {
await this.applyMode(value as PermissionMode, duringSetup);
return;
case MODEL_CONFIG_ID:
await this.session.query.setModel(value);
await setSelectedModel(this.session.query, selected);
await this.recordModel(value, duringSetup);
return;
case EFFORT_CONFIG_ID:
@@ -527,22 +551,28 @@ export class SessionConfig {
}
/**
* Claude Code reported a Fast mode state (`system`/init, a result). Returns
* whether the option changed. Without a Fast mode option the model does not
* support it, and the state says nothing of the user's intent, which stays
* for a model that does (see `fastModeStateChange`).
* Claude Code reported a Fast mode state, on a `system`/init or on a result
* (`from`). Returns whether the option changed. A result that repeats the
* init of its turn changes nothing (see `fastModeResultIsNews`). Without a
* Fast mode option the model does not support it, and the state says nothing
* of the user's intent, which stays for a model that does (see
* `fastModeStateChange`).
*/
fastModeReported(
state: FastModeState | undefined,
reason: FastModeDisabledReason | undefined,
): boolean {
fastModeReported(report: FastModeReport, from: "init" | "result"): boolean {
if (from === "init") {
this.fastModeInitReport = report;
} else {
const init = this.fastModeInitReport;
this.fastModeInitReport = undefined;
if (!fastModeResultIsNews(init, report)) return false;
}
if (!this.session.configOptions.some((option) => option.id === FAST_MODE_CONFIG_ID)) {
return false;
}
const change = fastModeStateChange(
{ enabled: this.fastModeEnabled, disabledReason: this.fastModeDisabledReason },
state,
reason,
report.state,
report.reason,
);
if (!change) return false;
this.fastModeEnabled = change.enabled;
@@ -581,9 +611,12 @@ export class SessionConfig {
this.setCurrentValue(AGENT_CONFIG_ID, value);
}
/** Applied first, so a rejected control request leaves the option as it was. */
/**
* Applied first, so a rejected control request leaves the option as it was
* (see `applyFastModeFlag` for a refusal after its reset).
*/
private async setFastMode(enabled: boolean): Promise<void> {
await this.session.query.applyFlagSettings({ fastMode: enabled });
await applyFastModeFlag((settings) => this.session.query.applyFlagSettings(settings), enabled);
this.fastModeEnabled = enabled;
this.refreshFastModeOption();
}

View File

@@ -839,12 +839,16 @@ export class V2Session implements RequestTarget {
this.reports.modelChanged(id, info);
}
/** Claude Code reported a Fast mode state, on `system`/init or a result. */
private fastModeReported(message: {
fast_mode_state?: FastModeState;
fast_mode_disabled_reason?: FastModeDisabledReason;
}): void {
if (this.config.fastModeReported(message.fast_mode_state, message.fast_mode_disabled_reason)) {
/** Claude Code reported a Fast mode state, on a `system`/init or on a result (`from`). */
private fastModeReported(
message: {
fast_mode_state?: FastModeState;
fast_mode_disabled_reason?: FastModeDisabledReason;
},
from: "init" | "result",
): void {
const report = { state: message.fast_mode_state, reason: message.fast_mode_disabled_reason };
if (this.config.fastModeReported(report, from)) {
this.send({ sessionUpdate: "config_option_update", configOptions: this.config.options() });
}
}
@@ -990,7 +994,7 @@ export class V2Session implements RequestTarget {
if (message.capabilities?.includes("msg_lifecycle_v1")) this.lifecycleFrames = true;
this.elicitations.init(message.capabilities);
// A fresh init (such as after a reinitialize) can carry another Fast mode state.
this.fastModeReported(message);
this.fastModeReported(message, "init");
this.reports.handle(message);
// Its terminal-bound commands leave the list.
if (this.commands.init(message)) this.resendCommands();
@@ -1172,7 +1176,7 @@ export class V2Session implements RequestTarget {
// A cycle that Claude Code started on its own leaves its Fast mode state
// to the next result of a prompt.
if (!(message.origin && AUTONOMOUS_RESULT_ORIGINS.has(message.origin.kind))) {
this.fastModeReported(message);
this.fastModeReported(message, "result");
}
this.reports.result(message);
// Before the result's text below, which can repeat the failed request's.