Compare commits

...

3 Commits

Author SHA1 Message Date
acp-release-bot[bot]
7ad73cceb9 chore(main): release 0.107.3 (#1640)
🤖 I have created a release *beep* *boop*
---


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


### Bug Fixes

* allow Claude Enterprise accounts under --hide-claude-auth
([#1641](https://github.com/agentclientprotocol/claude-agent-acp/issues/1641))
([be2219c](be2219cef1))
* pass a model id the picker does not list to Claude Code
([#1630](https://github.com/agentclientprotocol/claude-agent-acp/issues/1630))
([dc769c1](dc769c132c))

---
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 15:34:42 +01:00
Andrey Bragin
be2219cef1 fix: allow Claude Enterprise accounts under --hide-claude-auth (#1641)
## Problem

Under `--hide-claude-auth` the subscription guard refuses every
claude.ai account, Claude Enterprise included, so Enterprise users in
Air get `authRequired` (`claude_subscription_not_supported`) on every
session and prompt. Enterprise plans are allowed in this integration
(IJAI-2528).

## Change

- `isClaudeEnterprisePlan()` matches "Claude Enterprise" (the SDK's
`AccountInfo.subscriptionType`) and "enterprise" (older CLIs). Any other
name, including a custom `plan_display_name`, is still refused.
- `claudeAuthRefusal()` is now the guard's single decision, used by v1
and v2 session creation and the per-prompt guard instead of three copies
of the same check.

Free, Pro, Max and Team stay refused, and the claude.ai login method
stays hidden under the flag.

## Testing

v1 and v2 tests: Enterprise is allowed, Team is refused. `npm run build`
and `npm run check` pass. 24 tests in `create-session-options`,
`providers`, `session-index` and the v2 provider tests fail locally on
`main` too. Not checked against a real Enterprise account.
2026-11-16 15:30:58 +01:00
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
16 changed files with 443 additions and 70 deletions

View File

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

View File

@@ -1,5 +1,13 @@
# Changelog
## [0.107.3](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.2...v0.107.3) (2026-11-16)
### Bug Fixes
* allow Claude Enterprise accounts under --hide-claude-auth ([#1641](https://github.com/agentclientprotocol/claude-agent-acp/issues/1641)) ([be2219c](https://github.com/agentclientprotocol/claude-agent-acp/commit/be2219cef1f5b2b93129d5eef4b80574f57bdb1b))
* pass a model id the picker does not list to Claude Code ([#1630](https://github.com/agentclientprotocol/claude-agent-acp/issues/1630)) ([dc769c1](https://github.com/agentclientprotocol/claude-agent-acp/commit/dc769c132cacc8bbc7aff0d512e5ab587a1802e3))
## [0.107.2](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.1...v0.107.2) (2026-11-16)

4
package-lock.json generated
View File

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

View File

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

View File

@@ -1,9 +1,11 @@
/**
* `--hide-claude-auth`: this integration must never bill a claude.ai
* subscription. Under the flag the agent hides the claude.ai login method from
* `initialize`, and refuses with `authRequired` every session and every turn
* that a subscription would pay for. `v1/acp-agent.ts` decides when the guard
* applies (flag on, no provider override); this module decides what it refuses.
* subscription, except a Claude Enterprise plan. Under the flag the agent hides
* the claude.ai login method from `initialize`, and refuses with `authRequired`
* every session and every turn that a Free, Pro, Max or Team plan would pay
* for. `v1/acp-agent.ts` and `v2/subscription-guard.ts` decide when the guard
* applies (flag on, no provider override); {@link claudeAuthRefusal} decides
* what it refuses.
*
* The guard judges the `AccountInfo` that the SDK caches at `initialize`. That
* cache never changes during the life of a query, but the CLI itself picks up
@@ -113,6 +115,20 @@ export function billsClaudeSubscription(account: AccountInfo | undefined): boole
return !API_KEY_SOURCES_ABOVE_SUBSCRIPTION.has(account.apiKeySource ?? "");
}
/**
* True when `subscriptionType` names a Claude Enterprise plan, which the flag
* lets pay for turns: Anthropic allows an Enterprise plan in third-party
* integrations.
*
* The SDK's `AccountInfo` carries the CLI's display name, "Claude Enterprise";
* older CLIs report the raw plan, "enterprise". Any other value is refused,
* including a "Claude <name>" built from a custom `plan_display_name` in the
* claude.ai profile: the guard cannot tell which plan that name belongs to.
*/
export function isClaudeEnterprisePlan(subscriptionType: string | undefined): boolean {
return /^(claude\s+)?enterprise$/i.test(subscriptionType?.trim() ?? "");
}
/**
* True when the account already holds a credential this integration accepts:
* a third-party backend, a bearer or OAuth environment token, or one of the
@@ -136,6 +152,27 @@ export function holdsNonSubscriptionCredential(account: AccountInfo | undefined)
return API_KEY_SOURCES_ABOVE_SUBSCRIPTION.has(account.apiKeySource ?? "");
}
/**
* The refusal the flag gives a session or turn on `account`, or `undefined`
* when the account may run it:
*
* - a subscription pays, and it is not {@link isClaudeEnterprisePlan}:
* {@link claudeSubscriptionNotSupportedError};
* - no subscription pays and the account holds no other credential (signed
* out): {@link claudeLoginRequiredError}.
*
* Session creation on v1 and v2 and the per-turn guard all decide through
* this function.
*/
export function claudeAuthRefusal(account: AccountInfo): RequestError | undefined {
if (billsClaudeSubscription(account)) {
return isClaudeEnterprisePlan(account.subscriptionType)
? undefined
: claudeSubscriptionNotSupportedError();
}
return holdsNonSubscriptionCredential(account) ? undefined : claudeLoginRequiredError();
}
export function claudeSubscriptionNotSupportedError(): RequestError {
return RequestError.authRequired(
{ reason: CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_REASON satisfies AuthRequiredReason },
@@ -219,8 +256,8 @@ type GuardOptions = {
* real account. This guard does not see the residual case the module header
* names either.
*
* A turn is refused when the account bills a subscription, and also when it
* holds nothing this integration accepts, which is the user signing out in
* A turn is refused when the account bills a subscription other than Claude
* Enterprise, and also when it holds nothing this integration accepts, which is the user signing out in
* mid-session. The refusal mirrors the signed-out path exactly (see
* `failActiveWithSessionFailure` for `auth_required` in `v1/acp-agent.ts`): every
* client gets the `authRequired` JSON-RPC rejection that starts its own auth
@@ -262,13 +299,7 @@ async function evaluateGuard(options: GuardOptions): Promise<RequestError | unde
error instanceof Error ? error.message : String(error),
);
}
if (billsClaudeSubscription(account)) {
return claudeSubscriptionNotSupportedError();
}
if (!holdsNonSubscriptionCredential(account)) {
return claudeLoginRequiredError();
}
return undefined;
return claudeAuthRefusal(account);
}
/** The account the SDK cached at `initialize`. `undefined` when the query

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

@@ -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

@@ -9,6 +9,7 @@ import { AcpClient } from "../../acp-client.js";
import {
billsClaudeSubscription,
holdsNonSubscriptionCredential,
isClaudeEnterprisePlan,
CLAUDE_LOGIN_REQUIRED_MESSAGE,
CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_MESSAGE,
CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_REASON,
@@ -466,6 +467,24 @@ describe("authorization", () => {
});
});
describe("isClaudeEnterprisePlan", () => {
it.each([
["Claude Enterprise", true],
["enterprise", true],
[" claude ENTERPRISE ", true],
["Claude Team", false],
["Claude Max", false],
["pro", false],
// A custom `plan_display_name` does not say which plan it belongs to.
["Claude Enterprise Trial", false],
["Claude Acme Enterprise", false],
["", false],
[undefined, false],
])("classifies subscriptionType %j", (subscriptionType, expected) => {
expect(isClaudeEnterprisePlan(subscriptionType)).toBe(expected);
});
});
describe("fails closed at session creation", () => {
/** What the flag does with an account at session creation. */
type Verdict = "subscription" | "signedOut" | "allowed";
@@ -508,6 +527,16 @@ describe("authorization", () => {
account: { tokenSource: "ANTHROPIC_AUTH_TOKEN" },
verdict: "allowed",
},
{
name: "a Claude Enterprise plan",
account: { subscriptionType: "Claude Enterprise", apiProvider: "firstParty" },
verdict: "allowed",
},
{
name: "a Claude Team plan",
account: { subscriptionType: "Claude Team", apiProvider: "firstParty" },
verdict: "subscription",
},
{ name: "bedrock", account: { apiProvider: "bedrock" }, verdict: "allowed" },
{ name: "vertex", account: { apiProvider: "vertex" }, verdict: "allowed" },
];
@@ -938,10 +967,13 @@ describe("authorization", () => {
expect(accountInfo).not.toHaveBeenCalled();
});
it("lets the turn through when the live account is not a subscription", async () => {
it.each([
["an API key", { apiKeySource: "ANTHROPIC_API_KEY" }],
["a Claude Enterprise plan", { subscriptionType: "Claude Enterprise" }],
])("lets the turn through when the live account is %s", async (_case, account) => {
const [agent] = await createAgentMock();
hideClaudeAuth();
const accountInfo = vi.fn(async () => ({ apiKeySource: "ANTHROPIC_API_KEY" }));
const accountInfo = vi.fn(async () => account);
mockAccount(SIGNED_IN_WITH_KEY, { accountInfo });
const { sessionId } = await agent.newSession(newSessionParams());

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";
@@ -1504,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

@@ -345,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,

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());
@@ -1257,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",
@@ -1276,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();
@@ -1302,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) => {
@@ -10335,6 +10473,11 @@ describe("ACP v2 subscription guard (--hide-claude-auth)", () => {
{ code: -32000, data: undefined },
],
["a subscription has no token", { ...SUBSCRIPTION, tokenSource: "none" }, NOT_SUPPORTED],
[
"a Claude Team plan would pay",
{ ...SUBSCRIPTION, subscriptionType: "Claude Team" },
NOT_SUPPORTED,
],
])("refuses session/new when %s", async (_case, account, refusal) => {
accountsAtStart(account);
const client = v2Client();
@@ -10353,6 +10496,7 @@ describe("ACP v2 subscription guard (--hide-claude-auth)", () => {
["a bearer token", { tokenSource: "ANTHROPIC_AUTH_TOKEN" }],
["a setup token", { tokenSource: "CLAUDE_CODE_OAUTH_TOKEN" }],
["external credentials", { apiProvider: "bedrock", tokenSource: "none" }],
["a Claude Enterprise plan", { ...SUBSCRIPTION, subscriptionType: "Claude Enterprise" }],
["an unavailable account", undefined],
])("allows session/new with %s", async (_case, account) => {
accountsAtStart(account);

View File

@@ -258,11 +258,8 @@ import {
supportsAirSessionFailures,
} from "../session-failure-extension.js";
import {
billsClaudeSubscription,
claudeLoginRequiredError,
claudeAuthRefusal,
type ClaudeSubscriptionGuardState,
claudeSubscriptionNotSupportedError,
holdsNonSubscriptionCredential,
refuseClaudeSubscriptionTurn,
shouldHideClaudeAuth,
warnClaudeSubscriptionGuardDegraded,
@@ -405,6 +402,7 @@ import {
clientSupportsBooleanConfigOptions,
clientSupportsRecommendedConfigValue,
configOptionValue,
setSelectedModel,
discoverCustomAgents,
} from "../session-config-options.js";
import {
@@ -1129,6 +1127,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;
@@ -7802,11 +7804,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) {
@@ -7824,7 +7829,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);
@@ -7844,7 +7854,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
@@ -10275,15 +10285,14 @@ export class ClaudeAcpAgent {
logger: this.logger,
cause: "the CLI reported no account at initialize",
});
} else if (billsClaudeSubscription(initializationResult.account)) {
throw claudeSubscriptionNotSupportedError();
} else if (!holdsNonSubscriptionCredential(initializationResult.account)) {
// Fail closed: the account holds nothing this integration can bill.
// A logged-out session must never exist, because the CLI can pick up
// a claude.ai login by itself and AIR resumes a parked prompt on the
// SAME session after a sign-in. Refusing before the session exists
// makes every sign-in lead to a new session and a fresh `initialize`.
throw claudeLoginRequiredError();
} else {
// Fail closed on a signed-out account too: a logged-out session must
// never exist, because the CLI can pick up a claude.ai login by itself
// and AIR resumes a parked prompt on the SAME session after a sign-in.
// Refusing before the session exists makes every sign-in lead to a new
// session and a fresh `initialize`.
const refusal = claudeAuthRefusal(initializationResult.account);
if (refusal) throw refusal;
}
}
@@ -10504,6 +10513,7 @@ export class ClaudeAcpAgent {
contextWindowSize: seededWindow.size,
contextWindowAuthoritative: seededWindow.authoritative,
providerCacheKey,
modelsNarrowedByGateway: resolvedProvider?.listedModels !== undefined,
taskState,
subagentChecklists: creationOpts.replayState?.subagentChecklists ?? new Set(),
toolUseCache: {},
@@ -10698,7 +10708,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 {
@@ -119,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 {
@@ -137,6 +140,8 @@ export class SessionConfig {
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,
@@ -162,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,
@@ -299,6 +306,7 @@ export class SessionConfig {
notify,
logger,
autoModeFallbackWarningPending,
setup.narrowsModels,
);
}
@@ -384,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);
@@ -430,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);
@@ -443,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);
@@ -455,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:

View File

@@ -1,12 +1,13 @@
/**
* The `--hide-claude-auth` subscription guard on the v2 core: this
* integration never bills a claude.ai subscription. The policy is the v1
* core's (`hide-claude-auth.ts`):
* integration never bills a claude.ai subscription other than Claude
* Enterprise. The policy is the v1 core's (`claudeAuthRefusal` in
* `hide-claude-auth.ts`):
*
* - It holds while the flag is on and no provider or gateway login routes
* the traffic away from the CLI's own login.
* - A session does not start on an account that a subscription would pay
* for (`authRequired` with the `claude_subscription_not_supported`
* - A session does not start on an account that a Free, Pro, Max or Team
* plan would pay for (`authRequired` with the `claude_subscription_not_supported`
* reason), or that holds no credential this integration accepts
* (`authRequired`).
* - Each prompt reads the account that the query cached at its start, and is
@@ -23,11 +24,8 @@ import type { AccountInfo, Query } from "@anthropic-ai/claude-agent-sdk";
import type { Logger } from "../logger.js";
import { type AuthStatusKind, fromAccountInfo } from "../auth-status.js";
import {
billsClaudeSubscription,
claudeLoginRequiredError,
claudeAuthRefusal,
type ClaudeSubscriptionGuardState,
claudeSubscriptionNotSupportedError,
holdsNonSubscriptionCredential,
refuseClaudeSubscriptionTurn,
shouldHideClaudeAuth,
warnClaudeSubscriptionGuardDegraded,
@@ -79,10 +77,9 @@ export class SubscriptionGuard {
logger: this.logger,
cause: "the CLI reported no account at initialize",
});
} else if (billsClaudeSubscription(account)) {
throw claudeSubscriptionNotSupportedError();
} else if (!holdsNonSubscriptionCredential(account)) {
throw claudeLoginRequiredError();
} else {
const refusal = claudeAuthRefusal(account);
if (refusal) throw refusal;
}
}
this.sessions.set(sessionId, session);