@devries-cameron20 / t3code Mirror · read-only / commits / bf9b8b7845
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 16:00 UTC

fix(server): Claude on Bedrock runs the model picked in the composer (#24695)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Victor committed Nov 14, 2026 at 01:51 UTC bf9b8b784582d39b3a9712f37ebef852359f0d93
10 files changed +804 -98
apps/server/src/claudeModelOptions.ts
+18 -1
@@ -12,14 +12,19 @@ import {
12 normalizeClaudeCatalogEffort,
13 resolveClaudeCatalogApiModelId,
14 resolveClaudeCatalogEffort,
15 + resolveClaudeModelSlug,
16 type ClaudeModelCatalog,
17 } from "./provider/ClaudeModelCatalog.ts";
18
19 +const CLAUDE_CODE_MODEL_ALIASES = new Set(["opus", "sonnet", "haiku", "fable"]);
20 +
21 export interface CompiledClaudeModelSelection {
22 readonly apiModelId: string;
23 readonly effort: string | undefined;
24 readonly promptEffort: string | undefined;
25 readonly settings: Readonly<Record<string, boolean>>;
26 + /** The alias of a custom model named like one, which Claude Code would otherwise expand. */
27 + readonly pinnedAlias: string | undefined;
28 readonly queryIdentity: string;
29 }
30
@@ -51,11 +56,23 @@ export function compileClaudeModelSelection(
56 };
57 const apiModelId = resolveClaudeCatalogApiModelId(catalog, selection);
58 const promptEffort = resolvePromptInjectedEffort(capabilities, rawEffort) ?? undefined;
59 + // An alias the catalog routes a built-in model to is Claude Code's own and is not pinned.
60 + const pinnedAlias =
61 + CLAUDE_CODE_MODEL_ALIASES.has(apiModelId) &&
62 + resolveClaudeModelSlug(catalog, selection.model) === apiModelId
63 + ? apiModelId
64 + : undefined;
65 return {
66 apiModelId,
67 effort,
68 promptEffort,
69 settings,
59 - queryIdentity: JSON.stringify({ apiModelId, effort: effort ?? null, settings }),
70 + pinnedAlias,
71 + queryIdentity: JSON.stringify({
72 + apiModelId,
73 + effort: effort ?? null,
74 + settings,
75 + pinnedAlias: pinnedAlias ?? null,
76 + }),
77 };
78 }
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+313 -1
@@ -70,6 +70,7 @@ import * as Option from "effect/Option";
70 import * as Path from "effect/Path";
71 import * as PubSub from "effect/PubSub";
72 import * as Queue from "effect/Queue";
73 +import * as Ref from "effect/Ref";
74 import * as Schema from "effect/Schema";
75 import * as Scope from "effect/Scope";
76 import * as Stream from "effect/Stream";
@@ -101,8 +102,15 @@ import { ClaudeExecutableFileCheck } from "../../provider/Drivers/ClaudeExecutab
102 import {
103 BUNDLED_CLAUDE_MODEL_CATALOG,
104 type ClaudeModelCatalog,
105 + resolveClaudeModelCatalog,
106 scopeClaudeModelCatalog,
107 + withClaudeCodeModelRoutes,
108 } from "../../provider/ClaudeModelCatalog.ts";
109 +import {
110 + makeClaudeCodeModelRoutes,
111 + resolveClaudeModelSettingsKey,
112 +} from "../../provider/ClaudeCodeModelRoutes.ts";
113 +import { resolveProviderCatalog } from "../../provider/ModelManifest.ts";
114 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
115 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
116 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
@@ -162,6 +170,9 @@ const CUSTOM_MODEL_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
170 },
171 ],
172 });
173 +const ALIAS_CUSTOM_MODEL_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
174 + customModels: ["haiku", "sonnet"],
175 +});
176 const ULTRACODE_CUSTOM_MODEL_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
177 customModels: [
178 {
@@ -3392,6 +3403,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3403 readonly allocateSessionId?: Effect.Effect<string>;
3404 readonly offer?: (message: SDKUserMessage) => Effect.Effect<void>;
3405 readonly promptSuggestions?: boolean;
3406 + readonly routeModelCatalog?: ClaudeAdapterV2.ClaudeAdapterV2Options["routeModelCatalog"];
3407 }) =>
3408 Effect.gen(function* () {
3409 const fileSystem = yield* FileSystem.FileSystem;
@@ -3455,6 +3467,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3467 path: yield* Path.Path,
3468 random: yield* SecureRandom.SecureRandom,
3469 idAllocator,
3470 + ...(options?.routeModelCatalog ? { routeModelCatalog: options.routeModelCatalog } : {}),
3471 continuationRequests: {
3472 offer: (request) =>
3473 Effect.sync(() => {
@@ -6245,6 +6258,174 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6258 ),
6259 );
6260
6261 + it.effect("sends the model id Claude Code reported for the selected catalog model", () =>
6262 + Effect.scoped(
6263 + Effect.gen(function* () {
6264 + const modelCatalog = yield* Ref.make(BUNDLED_CLAUDE_MODEL_CATALOG);
6265 + const harness = yield* makeWakeHarnessWithOptions({
6266 + modelCatalog: Ref.get(modelCatalog),
6267 + settings: ALIAS_CUSTOM_MODEL_CLAUDE_SETTINGS,
6268 + close: Queue.shutdown,
6269 + freshQueueOnReopen: true,
6270 + // Bedrock with ANTHROPIC_DEFAULT_*_MODEL set, as the probe reports it.
6271 + routeModelCatalog: (catalog) =>
6272 + Effect.succeed(
6273 + withClaudeCodeModelRoutes(catalog, [
6274 + { value: "default", resolvedModel: "global.anthropic.claude-sonnet-6" },
6275 + { value: "sonnet", resolvedModel: "global.anthropic.claude-sonnet-6" },
6276 + { value: "haiku", resolvedModel: "global.anthropic.claude-haiku-6" },
6277 + ]),
6278 + ),
6279 + });
6280 + const now = yield* DateTime.now;
6281 + const turn = (ordinal: number, model: string) =>
6282 + makeClaudeTestTurnInput({
6283 + threadId: harness.threadId,
6284 + providerThread: harness.providerThread,
6285 + now,
6286 + attemptId: RunAttemptId.make(`attempt-reported-model:${ordinal}`),
6287 + text: `Request ${ordinal}`,
6288 + attachments: [],
6289 + providerTurnOrdinal: ordinal,
6290 + modelSelection: { instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, model },
6291 + });
6292 + // Models the live manifest delivers after a release, so the bundled catalog lacks them.
6293 + const manifestCatalog = resolveClaudeModelCatalog(
6294 + resolveProviderCatalog(
6295 + {
6296 + version: 1,
6297 + currentModels: {},
6298 + providers: {
6299 + claudeAgent: {
6300 + profiles: {},
6301 + models: [
6302 + { slug: "claude-haiku-6", name: "Claude Haiku 6", status: "current" },
6303 + { slug: "claude-sonnet-6", name: "Claude Sonnet 6", status: "current" },
6304 + ],
6305 + },
6306 + },
6307 + },
6308 + ProviderDriverKind.make("claudeAgent"),
6309 + ) ?? undefined,
6310 + );
6311 + yield* Ref.set(modelCatalog, manifestCatalog);
6312 +
6313 + const openedPins = () => {
6314 + const env = (
6315 + harness.getOpenedOptions()?.settings as { env?: Record<string, string> } | undefined
6316 + )?.env;
6317 + return [env?.ANTHROPIC_DEFAULT_HAIKU_MODEL, env?.ANTHROPIC_DEFAULT_SONNET_MODEL];
6318 + };
6319 + yield* harness.runtime.startTurn(turn(1, "claude-haiku-6"));
6320 + assert.equal(harness.getOpenedOptions()?.model, "haiku");
6321 + // The user's ANTHROPIC_DEFAULT_HAIKU_MODEL maps the routed alias to the Bedrock id.
6322 + assert.deepEqual(openedPins(), [undefined, undefined]);
6323 + yield* harness.offerAndWait(turnOneResult);
6324 + yield* Queue.take(harness.terminalReceipts);
6325 +
6326 + yield* harness.runtime.startTurn(turn(2, "claude-sonnet-6"));
6327 + assert.deepEqual(harness.liveSelectionChanges[0], { model: "sonnet" });
6328 + yield* harness.offerAndWait(
6329 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000b02", result: "Two." }),
6330 + );
6331 + yield* Queue.take(harness.terminalReceipts);
6332 +
6333 + // Custom models named like an alias pin it, so a change of pin reopens Claude Code.
6334 + yield* harness.runtime.startTurn(turn(3, "haiku"));
6335 + assert.deepEqual(openedPins(), ["haiku", undefined]);
6336 + yield* harness.offerAndWait(
6337 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000b03", result: "Three." }),
6338 + );
6339 + yield* Queue.take(harness.terminalReceipts);
6340 + yield* harness.runtime.startTurn(turn(4, "sonnet"));
6341 + assert.deepEqual(openedPins(), [undefined, "sonnet"]);
6342 + yield* harness.offerAndWait(
6343 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000b04", result: "Four." }),
6344 + );
6345 + yield* Queue.take(harness.terminalReceipts);
6346 + yield* harness.runtime.startTurn(turn(5, "claude-haiku-6"));
6347 + assert.deepEqual(openedPins(), [undefined, undefined]);
6348 + }).pipe(
6349 + Effect.provide(
6350 + Layer.mergeAll(
6351 + IdAllocator.layer,
6352 + McpProviderSessions.layer,
6353 + NodeServices.layer,
6354 + NodeCrypto.layer,
6355 + ),
6356 + ),
6357 + ),
6358 + ),
6359 + );
6360 +
6361 + it.effect("keeps the reported model id when a running turn is steered or changes effort", () =>
6362 + Effect.scoped(
6363 + Effect.gen(function* () {
6364 + const harness = yield* makeWakeHarnessWithOptions({
6365 + routeModelCatalog: (catalog) =>
6366 + Effect.succeed(
6367 + withClaudeCodeModelRoutes(catalog, [
6368 + { value: "haiku", resolvedModel: "global.anthropic.claude-haiku-5-5" },
6369 + ]),
6370 + ),
6371 + });
6372 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
6373 + const haiku = {
6374 + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6375 + model: "claude-haiku-5-5",
6376 + } satisfies ModelSelection;
6377 + const input = makeClaudeTestTurnInput({
6378 + threadId: harness.threadId,
6379 + providerThread: harness.providerThread,
6380 + now: yield* DateTime.now,
6381 + attemptId: RunAttemptId.make("attempt-reported-model-live-change"),
6382 + text: "Run the slow build.",
6383 + attachments: [],
6384 + modelSelection: haiku,
6385 + });
6386 + yield* harness.runtime.startTurn(input);
6387 + assert.equal(harness.getOpenedOptions()?.model, "haiku");
6388 +
6389 + yield* harness.runtime.steerTurn({
6390 + threadId: harness.threadId,
6391 + runId: input.runId,
6392 + providerThread: harness.providerThread,
6393 + providerTurnId: idAllocator.derive.providerTurn({
6394 + driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
6395 + nativeTurnId: `turn:${input.attemptId}`,
6396 + }),
6397 + modelSelection: haiku,
6398 + message: {
6399 + createdBy: "user",
6400 + creationSource: "web",
6401 + messageId: MessageId.make("steer-reported-model"),
6402 + text: "Also check the tests.",
6403 + attachments: [],
6404 + },
6405 + });
6406 + assert.deepEqual(harness.liveSelectionChanges, []);
6407 + assert.lengthOf(harness.offeredMessages, 2);
6408 +
6409 + yield* harness.runtime.applyModelSelection!({
6410 + providerThread: harness.providerThread,
6411 + modelSelection: { ...haiku, options: [{ id: "effort", value: "high" }] },
6412 + });
6413 + assert.deepEqual(harness.liveSelectionChanges, [
6414 + { effortLevel: "high", fastMode: null, ultracode: null },
6415 + ]);
6416 + }).pipe(
6417 + Effect.provide(
6418 + Layer.mergeAll(
6419 + IdAllocator.layer,
6420 + McpProviderSessions.layer,
6421 + NodeServices.layer,
6422 + NodeCrypto.layer,
6423 + ),
6424 + ),
6425 + ),
6426 + ),
6427 + );
6428 +
6429 it.effect.each([
6430 {
6431 content: { type: "advisor_tool_result_error", error_code: "overloaded" },
@@ -6310,6 +6491,130 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6491 ),
6492 );
6493
6494 + it.effect(
6495 + "sends Claude Code's reported model id only where the cwd resolves it as the probe did",
6496 + () =>
6497 + Effect.gen(function* () {
6498 + const fileSystem = yield* FileSystem.FileSystem;
6499 + const path = yield* Path.Path;
6500 + const sdk = yield* Effect.promise(() =>
6501 + vi.importActual<typeof ClaudeSdk>("@anthropic-ai/claude-agent-sdk"),
6502 + );
6503 + vi.mocked(ClaudeSdk.resolveSettings).mockImplementation(sdk.resolveSettings);
6504 + const probeCwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-probe-" });
6505 + const project = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-project-" });
6506 + const overridden = yield* fileSystem.makeTempDirectoryScoped({
6507 + prefix: "t3-claude-local-",
6508 + });
6509 + yield* fileSystem.makeDirectory(path.join(overridden, ".claude"));
6510 + yield* fileSystem.writeFileString(
6511 + path.join(overridden, ".claude", "settings.local.json"),
6512 + JSON.stringify({
6513 + env: { ANTHROPIC_DEFAULT_HAIKU_MODEL: "global.anthropic.claude-sonnet-4-6" },
6514 + }),
6515 + );
6516 + const routes = yield* makeClaudeCodeModelRoutes(
6517 + (cwd) =>
6518 + resolveClaudeModelSettingsKey(["project", "local"], cwd).pipe(
6519 + Effect.provideService(FileSystem.FileSystem, fileSystem),
6520 + Effect.provideService(Path.Path, path),
6521 + ),
6522 + probeCwd,
6523 + );
6524 + yield* routes.record([
6525 + { value: "haiku", resolvedModel: "us.anthropic.claude-haiku-4-5-20251001-v1:0" },
6526 + ]);
6527 + yield* routes.settle;
6528 + const openedModel = (cwd: string, launchSettings?: Record<string, unknown>) =>
6529 + Effect.scoped(
6530 + Effect.gen(function* () {
6531 + const harness = yield* makeWakeHarnessWithOptions({
6532 + routeModelCatalog: routes.route,
6533 + settings: {
6534 + ...DEFAULT_CLAUDE_SETTINGS,
6535 + launchArgs:
6536 + launchSettings === undefined
6537 + ? ""
6538 + : `--settings '${JSON.stringify(launchSettings)}'`,
6539 + },
6540 + });
6541 + yield* harness.runtime.startTurn(
6542 + makeClaudeTestTurnInput({
6543 + threadId: harness.threadId,
6544 + providerThread: harness.providerThread,
6545 + now: yield* DateTime.now,
6546 + attemptId: RunAttemptId.make("attempt-reported-model-cwd"),
6547 + text: "Request",
6548 + attachments: [],
6549 + modelSelection: {
6550 + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6551 + model: "claude-haiku-4-5",
6552 + },
6553 + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
6554 + runtimeMode: "full-access",
6555 + interactionMode: "default",
6556 + cwd,
6557 + }),
6558 + }),
6559 + );
6560 + return harness.getOpenedOptions()?.model;
6561 + }),
6562 + );
6563 +
6564 + assert.equal(yield* openedModel(project), "haiku");
6565 + assert.equal(
6566 + yield* openedModel(project, {
6567 + env: { ANTHROPIC_DEFAULT_HAIKU_MODEL: "global.anthropic.claude-sonnet-4-6" },
6568 + }),
6569 + "claude-haiku-4-5",
6570 + );
6571 + assert.equal(yield* openedModel(project, { env: { FOO: "1" } }), "haiku");
6572 + // Claude Code resolves `haiku` to Sonnet there, so the slug is the only safe id.
6573 + assert.equal(yield* openedModel(overridden), "claude-haiku-4-5");
6574 +
6575 + // A linked worktree and a repository subdirectory read the main checkout's local file.
6576 + const repo = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-repo-" });
6577 + const worktree = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-wt-" });
6578 + const worktreeGitDir = path.join(repo, ".git", "worktrees", "wt");
6579 + yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true });
6580 + yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n");
6581 + yield* fileSystem.writeFileString(
6582 + path.join(worktree, ".git"),
6583 + `gitdir: ${worktreeGitDir}\n`,
6584 + );
6585 + yield* fileSystem.makeDirectory(path.join(repo, ".claude"));
6586 + yield* fileSystem.makeDirectory(path.join(repo, "packages", "app"), { recursive: true });
6587 + const rootLocal = (settings: object) =>
6588 + fileSystem.writeFileString(
6589 + path.join(repo, ".claude", "settings.local.json"),
6590 + JSON.stringify(settings),
6591 + );
6592 + yield* rootLocal({
6593 + env: { ANTHROPIC_DEFAULT_HAIKU_MODEL: "global.anthropic.claude-sonnet-4-6" },
6594 + });
6595 + assert.equal(
6596 + yield* openedModel(worktree),
6597 + (yield* HostProcess.Platform) === "win32" ? "haiku" : "claude-haiku-4-5",
6598 + );
6599 + assert.equal(
6600 + yield* openedModel(path.join(repo, "packages", "app")),
6601 + (yield* HostProcess.Platform) === "win32" ? "haiku" : "claude-haiku-4-5",
6602 + );
6603 + yield* rootLocal({ env: { FOO: "1" } });
6604 + assert.equal(yield* openedModel(worktree), "haiku");
6605 + }).pipe(
6606 + Effect.scoped,
6607 + Effect.provide(
6608 + Layer.mergeAll(
6609 + IdAllocator.layer,
6610 + McpProviderSessions.layer,
6611 + NodeServices.layer,
6612 + NodeCrypto.layer,
6613 + ),
6614 + ),
6615 + ),
6616 + );
6617 +
6618 describe("MCP elicitations", () => {
6619 const testLayer = Layer.mergeAll(
6620 IdAllocator.layer,
@@ -15347,7 +15652,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
15652
15653 it.effect("leaves buffered wake messages for the continuation queued behind a user turn", () =>
15654 Effect.gen(function* () {
15350 - const harness = yield* makeWakeHarness;
15655 + const fileSystem = yield* FileSystem.FileSystem;
15656 + const directory = yield* fileSystem.makeTempDirectoryScoped();
15657 + const settingsPath = NodePath.join(directory, "settings.json");
15658 + yield* fileSystem.writeFileString(settingsPath, "{}");
15659 + const harness = yield* makeWakeHarnessWithOptions({
15660 + settings: { ...DEFAULT_CLAUDE_SETTINGS, launchArgs: `--settings "${settingsPath}"` },
15661 + });
15662 const now = yield* DateTime.now;
15663
15664 yield* harness.runtime.startTurn(
@@ -15367,6 +15678,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
15678 yield* Queue.offer(harness.sdkMessages, wakeResult);
15679 yield* harness.awaitContinuation(1);
15680
15681 + yield* fileSystem.remove(settingsPath);
15682 yield* harness.runtime.startTurn(
15683 makeClaudeTestTurnInput({
15684 threadId: harness.threadId,
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+91 -80
@@ -187,6 +187,7 @@ import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
187 import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
188 import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
189 import {
190 + claudeLocalSettingsDirectory,
191 claudeSignedOutMessage,
192 makeClaudeEnvironment,
193 mergeClaudeProcessEnvironment,
@@ -1891,7 +1892,8 @@ function canApplyClaudeSelectionLive(
1892 ): boolean {
1893 return (
1894 live.settings.alwaysThinkingEnabled === next.settings.alwaysThinkingEnabled &&
1894 - (next.effort !== undefined || live.effort === undefined)
1895 + (next.effort !== undefined || live.effort === undefined) &&
1896 + live.pinnedAlias === next.pinnedAlias
1897 );
1898 }
1899
@@ -1987,8 +1989,6 @@ const subagentDeviceInstructions: HookCallback = () =>
1989 },
1990 });
1991
1990 -const CLAUDE_CODE_MODEL_ALIASES = new Set(["opus", "sonnet", "haiku", "fable"]);
1991 -
1992 export function makeClaudeQueryOptions(input: {
1993 readonly modelSelection: ModelSelection;
1994 readonly modelCatalog?: ClaudeModelCatalog;
@@ -2070,12 +2070,13 @@ export function makeClaudeQueryOptions(input: {
2070 } as ClaudeSdkSettings);
2071 // Claude Code expands a bare alias to its own model, so a custom model with an alias's name
2072 // pins the alias to itself.
2073 - const aliasOverrideEnv = CLAUDE_CODE_MODEL_ALIASES.has(compiledSelection.apiModelId)
2074 - ? {
2075 - [`ANTHROPIC_DEFAULT_${compiledSelection.apiModelId.toUpperCase()}_MODEL`]:
2076 - compiledSelection.apiModelId,
2077 - }
2078 - : undefined;
2073 + const aliasOverrideEnv =
2074 + compiledSelection.pinnedAlias === undefined
2075 + ? undefined
2076 + : {
2077 + [`ANTHROPIC_DEFAULT_${compiledSelection.pinnedAlias.toUpperCase()}_MODEL`]:
2078 + compiledSelection.pinnedAlias,
2079 + };
2080 // A settings file path cannot take extra keys, so it goes through unchanged.
2081 const effectiveQuerySettings =
2082 (input.toolSearchOverride === undefined &&
@@ -5284,6 +5285,15 @@ export interface ClaudeAdapterV2Options {
5285 readonly queryRunner: ClaudeAgentSdkQueryRunnerShape;
5286 readonly scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>;
5287 readonly onUsageLimits?: ManagedServerProvider["applyUsageLimits"];
5288 + /**
5289 + * Applies Claude Code's reported model ids for a turn's cwd, so turns send ids its backend
5290 + * accepts. Defaults to the catalog unchanged.
5291 + */
5292 + readonly routeModelCatalog?: (
5293 + catalog: ClaudeModelCatalog,
5294 + cwd: string | null,
5295 + launchSettings?: ClaudeSdkSettings,
5296 + ) => Effect.Effect<ClaudeModelCatalog>;
5297 readonly continuationRequests?: {
5298 readonly offer: (
5299 request: ProviderContinuationRequests.ProviderContinuationRequest,
@@ -5365,6 +5375,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5375 };
5376 },
5377 );
5378 + const routeModelCatalog = adapterOptions.routeModelCatalog ?? Effect.succeed;
5379
5380 // Claude Code's own subagent TTL setting, in its precedence order. Unset or unreadable means
5381 // Anthropic's default applies.
@@ -5401,44 +5412,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5412 }),
5413 Effect.orElseSucceed(() => undefined),
5414 );
5404 - // A worktree's .git file points at <main>/.git/worktrees/<name>, whose commondir leads back to
5405 - // <main>/.git. A bare repository has no main checkout, so its worktree keeps its own file.
5406 - const mainCheckoutRoot = (checkout: string) =>
5407 - fileSystem.readFileString(path.join(checkout, ".git")).pipe(
5408 - Effect.flatMap((pointer) => {
5409 - const gitDir = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();
5410 - if (gitDir === undefined) return Effect.succeed(checkout);
5411 - const worktreeGitDir = path.resolve(checkout, gitDir);
5412 - return fileSystem.readFileString(path.join(worktreeGitDir, "commondir")).pipe(
5413 - Effect.map((commonDir) => {
5414 - const common = path.resolve(worktreeGitDir, commonDir.trim());
5415 - return path.basename(common) === ".git" ? path.dirname(common) : checkout;
5416 - }),
5417 - );
5418 - }),
5419 - Effect.orElseSucceed(() => checkout),
5420 - );
5421 - // Claude Code keeps .claude/settings.local.json at the repository root, or in cwd outside a
5422 - // repository, on Windows, or when the root is home. Its owner check is skipped: missing it only
5423 - // leaves tool search on, Claude Code's default.
5424 - const localSettingsDirectory = Effect.fn("ClaudeAdapterV2.localSettingsDirectory")(function* (
5425 - cwd: string,
5426 - ) {
5427 - if ((yield* HostProcess.Platform) === "win32") return cwd;
5428 - for (let directory = cwd; ; directory = path.dirname(directory)) {
5429 - const isCheckout = yield* fileSystem
5430 - .exists(path.join(directory, ".git"))
5431 - .pipe(Effect.orElseSucceed(() => false));
5432 - if (isCheckout) {
5433 - const root = yield* mainCheckoutRoot(directory);
5434 - return root === (yield* HostProcess.HomeDirectory) ? cwd : root;
5435 - }
5436 - if (path.dirname(directory) === directory) return cwd;
5437 - }
5438 - });
5415 const settingsFilesByPrecedence = Effect.fn("ClaudeAdapterV2.settingsFilesByPrecedence")(
5416 function* (cwd: string | null) {
5441 - const localDirectory = cwd === null ? null : yield* localSettingsDirectory(cwd);
5417 + const localDirectory =
5418 + cwd === null
5419 + ? null
5420 + : yield* claudeLocalSettingsDirectory(cwd).pipe(
5421 + Effect.provideService(FileSystem.FileSystem, fileSystem),
5422 + Effect.provideService(Path.Path, path),
5423 + );
5424 return [
5425 ...(cwd === null || localDirectory === null
5426 ? []
@@ -12105,6 +12087,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12087 return false;
12088 });
12089
12090 + const routedCatalogFor = (live: ClaudeLiveQueryContext) =>
12091 + routeModelCatalog(modelCatalog, live.settingsCwd, live.launchArgSettings);
12092 +
12093 const applySelectionLive = Effect.fnUntraced(function* (
12094 live: ClaudeLiveQueryContext,
12095 selection: CompiledClaudeModelSelection,
@@ -12143,10 +12128,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12128 : { allowedTools: queryPolicy.allowedTools }),
12129 });
12130 const queryPolicyKey = claudeEffectiveQueryPolicyKey(queryPolicy, mcpOverrides);
12146 - const compiledSelection = compileClaudeModelSelection(
12147 - turnInput.modelSelection,
12148 - modelCatalog,
12149 - );
12131 const resumeSessionAt = yield* getNativeConversationHeadId(turnInput.providerThread);
12132 const existing = yield* Ref.get(queryContext);
12133 // Continuations drain existing output without prompting; retain the live process regardless of selection.
@@ -12158,6 +12139,26 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12139 ) {
12140 return existing;
12141 }
12142 + const reuseLaunchSettings =
12143 + existing !== null &&
12144 + existing.nativeThreadId === nativeThreadId &&
12145 + existing.queryPolicyKey === queryPolicyKey &&
12146 + !existing.stopping;
12147 + const readLaunchSettings = readClaudeLaunchArgSettings({
12148 + settings: adapterOptions.settings,
12149 + cwd: turnInput.runtimePolicy.cwd,
12150 + fileSystem,
12151 + path,
12152 + });
12153 + let launchArgSettings = reuseLaunchSettings
12154 + ? existing.launchArgSettings
12155 + : yield* readLaunchSettings;
12156 + let catalog = yield* routeModelCatalog(
12157 + modelCatalog,
12158 + turnInput.runtimePolicy.cwd,
12159 + launchArgSettings,
12160 + );
12161 + let compiledSelection = compileClaudeModelSelection(turnInput.modelSelection, catalog);
12162 if (
12163 existing !== null &&
12164 existing.nativeThreadId === nativeThreadId &&
@@ -12208,32 +12209,29 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12209 return yield* new ClaudeBackgroundWorkBlocksQueryReplacementError();
12210 }
12211
12211 - // Read before closing the live process so a bad path leaves it running.
12212 - const [appendSystemPromptFileText, { launchArgSettings, toolSearchOverride }] =
12213 - yield* Effect.all(
12214 - [
12215 - readClaudeAppendSystemPromptFile({
12216 - settings: adapterOptions.settings,
12217 - cwd: turnInput.runtimePolicy.cwd,
12218 - fileSystem,
12219 - path,
12220 - }),
12221 - Effect.gen(function* () {
12222 - const launchArgSettings = yield* readClaudeLaunchArgSettings({
12223 - settings: adapterOptions.settings,
12224 - cwd: turnInput.runtimePolicy.cwd,
12225 - fileSystem,
12226 - path,
12227 - });
12228 - const toolSearchOverride = yield* resolveToolSearchOverride(
12229 - turnInput.runtimePolicy.cwd,
12230 - launchArgSettings,
12231 - );
12232 - return { launchArgSettings, toolSearchOverride };
12233 - }),
12234 - ],
12235 - { concurrency: "unbounded" },
12212 + if (reuseLaunchSettings) {
12213 + launchArgSettings = yield* readLaunchSettings;
12214 + catalog = yield* routeModelCatalog(
12215 + modelCatalog,
12216 + turnInput.runtimePolicy.cwd,
12217 + launchArgSettings,
12218 );
12219 + compiledSelection = compileClaudeModelSelection(turnInput.modelSelection, catalog);
12220 + }
12221 +
12222 + // Read before closing the live process so a bad path leaves it running.
12223 + const [appendSystemPromptFileText, toolSearchOverride] = yield* Effect.all(
12224 + [
12225 + readClaudeAppendSystemPromptFile({
12226 + settings: adapterOptions.settings,
12227 + cwd: turnInput.runtimePolicy.cwd,
12228 + fileSystem,
12229 + path,
12230 + }),
12231 + resolveToolSearchOverride(turnInput.runtimePolicy.cwd, launchArgSettings),
12232 + ],
12233 + { concurrency: "unbounded" },
12234 + );
12235 const closedExistingNativeThreadId = existing !== null ? existing.nativeThreadId : null;
12236 clearedNativeSessions.delete(nativeThreadId);
12237 if (existing !== null) {
@@ -12254,7 +12252,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12252 resumeSessionAt !== undefined || openedWithResume || hasPersistedProviderTurn;
12253 const queryOptions = makeClaudeQueryOptions({
12254 modelSelection: turnInput.modelSelection,
12257 - modelCatalog,
12255 + modelCatalog: catalog,
12256 nativeThreadId,
12257 title: turnInput.appThread.title,
12258 resume: shouldResume,
@@ -13063,7 +13061,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13061 const steerSelection =
13062 turnInput.modelSelection === undefined
13063 ? undefined
13066 - : compileClaudeModelSelection(turnInput.modelSelection, modelCatalog);
13064 + : compileClaudeModelSelection(
13065 + turnInput.modelSelection,
13066 + yield* routedCatalogFor(existing),
13067 + );
13068 const liveSteerSelection =
13069 steerSelection !== undefined &&
13070 existing.selection.queryIdentity !== steerSelection.queryIdentity &&
@@ -13480,12 +13481,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13481 modelSelection,
13482 }) {
13483 const live = yield* Ref.get(queryContext);
13483 - const selection = compileClaudeModelSelection(modelSelection, modelCatalog);
13484 - // A model change still waits for the next turn, which checks it against the turn's permission mode.
13484 if (
13485 live === null ||
13486 live.stopping ||
13488 - live.nativeThreadId !== providerThread.nativeThreadRef?.nativeId ||
13487 + live.nativeThreadId !== providerThread.nativeThreadRef?.nativeId
13488 + ) {
13489 + return;
13490 + }
13491 + const selection = compileClaudeModelSelection(
13492 + modelSelection,
13493 + yield* routedCatalogFor(live),
13494 + );
13495 + // A model change still waits for the next turn, which checks it against the turn's permission mode.
13496 + if (
13497 live.selection.queryIdentity === selection.queryIdentity ||
13498 live.selection.apiModelId !== selection.apiModelId ||
13499 !canApplyClaudeSelectionLive(live.selection, selection)
@@ -13863,7 +13871,10 @@ export type ClaudeAdapterV2DriverEnv =
13871 export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")(
13872 function* (
13873 input: ProviderAdapterDriverCreateInput<ClaudeSettings>,
13866 - hooks: Pick<ClaudeAdapterV2Options, "scopedLimitNames" | "onUsageLimits" | "modelCatalog"> = {},
13874 + hooks: Pick<
13875 + ClaudeAdapterV2Options,
13876 + "scopedLimitNames" | "onUsageLimits" | "modelCatalog" | "routeModelCatalog"
13877 + > = {},
13878 ) {
13879 const { instanceId, environment, enabled, config } = input;
13880 const fileSystem = yield* FileSystem.FileSystem;
apps/server/src/provider/ClaudeCodeModelRoutes.test.ts new
+67
@@ -0,0 +1,67 @@
1 +import { assert, describe, it } from "@effect/vitest";
2 +import { type ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
3 +import * as Effect from "effect/Effect";
4 +import * as Fiber from "effect/Fiber";
5 +import * as Option from "effect/Option";
6 +import * as TestClock from "effect/testing/TestClock";
7 +
8 +import { makeClaudeCodeModelRoutes } from "./ClaudeCodeModelRoutes.ts";
9 +import {
10 + BUNDLED_CLAUDE_MODEL_CATALOG,
11 + resolveClaudeCatalogApiModelId,
12 +} from "./ClaudeModelCatalog.ts";
13 +
14 +describe("Claude Code model routes", () => {
15 + it.effect(
16 + "a turn that starts before the first probe settles waits and then gets its routes",
17 + () =>
18 + Effect.gen(function* () {
19 + const haiku = {
20 + instanceId: ProviderInstanceId.make("claudeAgent"),
21 + model: "claude-haiku-4-5",
22 + } satisfies ModelSelection;
23 + const routes = yield* makeClaudeCodeModelRoutes(
24 + () => Effect.succeed("same settings"),
25 + "/state",
26 + );
27 + const early = yield* routes
28 + .route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project")
29 + .pipe(Effect.forkChild({ startImmediately: true }));
30 + yield* routes.record([
31 + { value: "haiku", resolvedModel: "us.anthropic.claude-haiku-4-5-20251001-v1:0" },
32 + ]);
33 + yield* routes.settle;
34 + assert.strictEqual(
35 + resolveClaudeCatalogApiModelId(yield* Fiber.join(early), haiku),
36 + "haiku",
37 + );
38 +
39 + // A first check that never reaches the probe still releases waiting turns.
40 + const unprobed = yield* makeClaudeCodeModelRoutes(
41 + () => Effect.succeed("same settings"),
42 + "/state",
43 + );
44 + const waiting = yield* unprobed
45 + .route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project")
46 + .pipe(Effect.forkChild({ startImmediately: true }));
47 + yield* unprobed.settle;
48 + assert.strictEqual(yield* Fiber.join(waiting), BUNDLED_CLAUDE_MODEL_CATALOG);
49 +
50 + const stuck = yield* makeClaudeCodeModelRoutes(
51 + () => Effect.succeed("same settings"),
52 + "/state",
53 + );
54 + const fallback = yield* stuck
55 + .route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project")
56 + .pipe(Effect.forkChild({ startImmediately: true }));
57 + yield* TestClock.adjust("2 minutes");
58 + assert.strictEqual(yield* Fiber.join(fallback), BUNDLED_CLAUDE_MODEL_CATALOG);
59 + // Later turns, steers and effort changes do not wait for the stuck probe again.
60 + const later = yield* stuck
61 + .route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project")
62 + .pipe(Effect.timeoutOption("1 second"), Effect.forkChild({ startImmediately: true }));
63 + yield* TestClock.adjust("1 second");
64 + assert.deepStrictEqual(yield* Fiber.join(later), Option.some(BUNDLED_CLAUDE_MODEL_CATALOG));
65 + }),
66 + );
67 +});
apps/server/src/provider/ClaudeCodeModelRoutes.ts new
+116
@@ -0,0 +1,116 @@
1 +import {
2 + type ModelInfo as ClaudeModelInfo,
3 + resolveSettings as resolveClaudeSettings,
4 + type SettingSource,
5 + type Settings as ClaudeSdkSettings,
6 +} from "@anthropic-ai/claude-agent-sdk";
7 +import * as Deferred from "effect/Deferred";
8 +import * as Effect from "effect/Effect";
9 +import * as Ref from "effect/Ref";
10 +import * as Schema from "effect/Schema";
11 +
12 +import { claudeLocalSettingsDirectory } from "./Drivers/ClaudeHome.ts";
13 +import { type ClaudeModelCatalog, withClaudeCodeModelRoutes } from "./ClaudeModelCatalog.ts";
14 +
15 +// Env names that pick the backend, its region, or the model a family alias resolves to.
16 +const MODEL_SETTINGS_ENV_PREFIXES = [
17 + "ANTHROPIC_",
18 + "CLAUDE_CODE_USE_",
19 + "AWS_",
20 + "CLOUD_ML_",
21 + "VERTEX_",
22 +];
23 +
24 +/** Equal keys mean Claude Code resolves model ids the same way under both settings. */
25 +function claudeModelSettingsKey(settings: ClaudeSdkSettings): string {
26 + const sortedEntries = (record: Readonly<Record<string, string | undefined>> | undefined) =>
27 + Object.entries(record ?? {}).toSorted(([a], [b]) => a.localeCompare(b));
28 + return JSON.stringify([
29 + settings.availableModels ?? null,
30 + sortedEntries(settings.modelOverrides),
31 + sortedEntries(settings.env).filter(([name]) =>
32 + MODEL_SETTINGS_ENV_PREFIXES.some((prefix) => name.startsWith(prefix)),
33 + ),
34 + ]);
35 +}
36 +
37 +const NO_MODEL_SETTINGS_KEY = claudeModelSettingsKey({});
38 +
39 +class ClaudeModelSettingsReadError extends Schema.TaggedError<ClaudeModelSettingsReadError>()(
40 + "ClaudeModelSettingsReadError",
41 + { cause: Schema.Defect() },
42 +) {}
43 +
44 +export const resolveClaudeModelSettingsKey = Effect.fn("resolveClaudeModelSettingsKey")(function* (
45 + settingSources: ReadonlyArray<SettingSource>,
46 + cwd: string | null,
47 +) {
48 + // The SDK reads the local file from cwd, Claude Code from the main checkout's root. No key, so
49 + // no routes, when that root file touches model settings.
50 + const localDirectory = cwd === null ? null : yield* claudeLocalSettingsDirectory(cwd);
51 + if (localDirectory !== null && localDirectory !== cwd) {
52 + const rootLocal = yield* Effect.tryPromise({
53 + try: () => resolveClaudeSettings({ cwd: localDirectory, settingSources: ["local"] }),
54 + catch: (cause) => new ClaudeModelSettingsReadError({ cause }),
55 + }).pipe(
56 + Effect.map(({ sources }) => sources.find(({ source }) => source === "local")?.settings),
57 + Effect.orElseSucceed(() => undefined),
58 + );
59 + if (claudeModelSettingsKey(rootLocal ?? {}) !== NO_MODEL_SETTINGS_KEY) return undefined;
60 + }
61 + return yield* Effect.tryPromise({
62 + try: () =>
63 + resolveClaudeSettings({
64 + ...(cwd === null ? {} : { cwd }),
65 + settingSources: [...settingSources],
66 + }),
67 + catch: (cause) => new ClaudeModelSettingsReadError({ cause }),
68 + }).pipe(
69 + Effect.map(({ effective }) => claudeModelSettingsKey(effective)),
70 + Effect.orElseSucceed(() => undefined),
71 + );
72 +});
73 +
74 +type ReportedModel = Pick<ClaudeModelInfo, "value" | "resolvedModel">;
75 +
76 +/**
77 + * Claude Code's reported model ids, applied to a turn only where its cwd resolves model settings
78 + * as the probe's cwd did. `settle` releases turns waiting for the first probe, whatever its outcome.
79 + */
80 +export const makeClaudeCodeModelRoutes = Effect.fn("makeClaudeCodeModelRoutes")(function* (
81 + settingsKey: (cwd: string | null) => Effect.Effect<string | undefined>,
82 + probeCwd: string,
83 +) {
84 + const firstProbeSettled = yield* Deferred.make<void>();
85 + const reported = yield* Ref.make<{
86 + readonly models: ReadonlyArray<ReportedModel>;
87 + readonly settingsKey: string | undefined;
88 + }>({ models: [], settingsKey: undefined });
89 + return {
90 + record: Effect.fn("ClaudeCodeModelRoutes.record")(function* (
91 + models: ReadonlyArray<ReportedModel>,
92 + ) {
93 + yield* Ref.set(reported, { models, settingsKey: yield* settingsKey(probeCwd) });
94 + }),
95 + settle: Deferred.succeed(firstProbeSettled, undefined).pipe(Effect.asVoid),
96 + route: Effect.fn("ClaudeCodeModelRoutes.route")(function* (
97 + base: ClaudeModelCatalog,
98 + cwd: string | null,
99 + launchSettings?: ClaudeSdkSettings,
100 + ) {
101 + // Leave room for the sequential version and capability probes before falling back once;
102 + // an expired wait counts as settled so later calls do not wait again.
103 + yield* Deferred.await(firstProbeSettled).pipe(
104 + Effect.timeoutOption("2 minutes"),
105 + Effect.andThen(Deferred.succeed(firstProbeSettled, undefined)),
106 + );
107 + if (claudeModelSettingsKey(launchSettings ?? {}) !== NO_MODEL_SETTINGS_KEY) return base;
108 + const { models, settingsKey: probeKey } = yield* Ref.get(reported);
109 + const routed = withClaudeCodeModelRoutes(base, models);
110 + // Project settings can point an alias at another model, so routes hold only where the
111 + // cwd resolves the same model settings as the probe's.
112 + if (routed === base || probeKey === undefined) return base;
113 + return (yield* settingsKey(cwd)) === probeKey ? routed : base;
114 + }),
115 + };
116 +});
apps/server/src/provider/ClaudeModelCatalog.test.ts
+62 -1
@@ -1,8 +1,9 @@
1 import { assert, describe, it } from "@effect/vitest";
2 -import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
2 +import { type ModelSelection, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
3
4 import { resolveProviderCatalog, type ModelManifestData } from "./ModelManifest.ts";
5 import {
6 + BUNDLED_CLAUDE_MODEL_CATALOG,
7 capClaudeCatalogEffort,
8 type ClaudeModelCatalog,
9 formatClaudeVersionUpgradeMessage,
@@ -16,6 +17,7 @@ import {
17 resolveClaudeModelSlug,
18 resolveClaudeUpdateRequiredModels,
19 scopeClaudeModelCatalog,
20 + withClaudeCodeModelRoutes,
21 } from "./ClaudeModelCatalog.ts";
22
23 const manifest = (): ModelManifestData => ({
@@ -233,6 +235,65 @@ describe("Claude model catalog", () => {
235 );
236 });
237
238 + // Rows Claude Code 2.1.310 reports from initialization for each configuration.
239 + it("sends the model id Claude Code reports when it serves a catalog model under another id", () => {
240 + const apiModel = (
241 + catalog: ClaudeModelCatalog,
242 + model: string,
243 + options?: ModelSelection["options"],
244 + ) =>
245 + resolveClaudeCatalogApiModelId(catalog, {
246 + instanceId: ProviderInstanceId.make("claudeAgent"),
247 + model,
248 + ...(options ? { options } : {}),
249 + });
250 +
251 + // Bedrock with ANTHROPIC_DEFAULT_*_MODEL and an availableModels allowlist of their ids.
252 + const configuredBedrock = withClaudeCodeModelRoutes(BUNDLED_CLAUDE_MODEL_CATALOG, [
253 + { value: "default", resolvedModel: "global.anthropic.claude-opus-5-5" },
254 + { value: "sonnet", resolvedModel: "global.anthropic.claude-sonnet-5-5[1m]" },
255 + { value: "opus", resolvedModel: "global.anthropic.claude-opus-5-5" },
256 + { value: "haiku", resolvedModel: "global.anthropic.claude-haiku-5-5" },
257 + ]);
258 + assert.strictEqual(apiModel(configuredBedrock, "claude-haiku-5-5"), "haiku");
259 + assert.strictEqual(apiModel(configuredBedrock, "haiku-5.5"), "haiku");
260 + assert.strictEqual(apiModel(configuredBedrock, "claude-sonnet-5-5"), "sonnet");
261 + assert.strictEqual(apiModel(configuredBedrock, "claude-opus-5-5"), "opus");
262 + assert.strictEqual(apiModel(configuredBedrock, "claude-opus-5"), "claude-opus-5");
263 +
264 + // Bedrock with no model settings: Claude Code's `haiku` is Haiku 4.5 there.
265 + const defaultBedrock = withClaudeCodeModelRoutes(BUNDLED_CLAUDE_MODEL_CATALOG, [
266 + {
267 + value: "us.anthropic.claude-opus-4-6-v1",
268 + resolvedModel: "us.anthropic.claude-opus-4-6-v1",
269 + },
270 + {
271 + value: "us.anthropic.claude-opus-4-6-v1[1m]",
272 + resolvedModel: "us.anthropic.claude-opus-4-6-v1[1m]",
273 + },
274 + { value: "haiku", resolvedModel: "us.anthropic.claude-haiku-4-5-20251001-v1:0" },
275 + ]);
276 + assert.strictEqual(
277 + apiModel(defaultBedrock, "claude-opus-4-6", [{ id: "contextWindow", value: "1m" }]),
278 + "us.anthropic.claude-opus-4-6-v1[1m]",
279 + );
280 + assert.strictEqual(
281 + apiModel(defaultBedrock, "claude-opus-4-6", [{ id: "contextWindow", value: "200k" }]),
282 + "us.anthropic.claude-opus-4-6-v1",
283 + );
284 + assert.strictEqual(apiModel(defaultBedrock, "claude-haiku-4-5"), "haiku");
285 + assert.strictEqual(apiModel(defaultBedrock, "claude-haiku-5-5"), "claude-haiku-5-5");
286 +
287 + // First-party ids already are what Claude Code runs, even when an alias points elsewhere.
288 + const firstParty = withClaudeCodeModelRoutes(BUNDLED_CLAUDE_MODEL_CATALOG, [
289 + { value: "default", resolvedModel: "claude-opus-5-5" },
290 + { value: "opus", resolvedModel: "claude-opus-5-5" },
291 + { value: "claude-fable-5-1[1m]", resolvedModel: "claude-fable-5-1[1m]" },
292 + { value: "haiku", resolvedModel: "claude-haiku-4-5-20251001" },
293 + ]);
294 + assert.strictEqual(firstParty, BUNDLED_CLAUDE_MODEL_CATALOG);
295 + });
296 +
297 it("marks effort options that would run above the cap without changing ids or defaults", () => {
298 const effortModel = (slug: string) => ({
299 slug,
apps/server/src/provider/ClaudeModelCatalog.ts
+41 -1
@@ -32,6 +32,8 @@ export interface ClaudeCatalogModel {
32 readonly model: ServerProviderModel;
33 readonly runtime: ClaudeCodeProfile;
34 readonly compatibility: ClaudeCodeCompatibility;
35 + /** What to send Claude Code instead of the slug, from its own model list. */
36 + readonly apiModel?: string;
37 }
38
39 export interface ClaudeModelCatalog {
@@ -235,6 +237,44 @@ function resolveClaudeCatalogModel(
237 );
238 }
239
240 +// Cloud backends decorate first-party ids: Bedrock adds a region prefix and a
241 +// version ("us.anthropic.claude-opus-4-6-v1"), Vertex adds "@<date>".
242 +function stripClaudeBackendDecoration(wireModel: string): string {
243 + return wireModel
244 + .replace(/^(?:[a-z-]+\.)?anthropic\./, "")
245 + .replace(/-v\d+(?::\d+)?$/, "")
246 + .replace(/@[^@]*$/, "");
247 +}
248 +
249 +/**
250 + * On Bedrock, Vertex and similar backends Claude Code does not accept the first-party slug: it
251 + * either sends it verbatim or, when `availableModels` excludes it, silently runs the default
252 + * model instead. Its model list names the id that does work, often a family alias that
253 + * `ANTHROPIC_DEFAULT_*_MODEL` points at a backend id.
254 + */
255 +export function withClaudeCodeModelRoutes(
256 + catalog: ClaudeModelCatalog,
257 + reportedModels: ReadonlyArray<Pick<ClaudeModelInfo, "value" | "resolvedModel">>,
258 +): ClaudeModelCatalog {
259 + const apiModels = new Map<string, string>();
260 + for (const reported of reportedModels) {
261 + if (reported.value === "default") continue;
262 + const wireModel = stripClaudeContextWindowSuffix(reported.resolvedModel ?? reported.value);
263 + const firstPartyModel = stripClaudeBackendDecoration(wireModel);
264 + if (firstPartyModel === wireModel) continue;
265 + const entry = resolveClaudeCatalogModel(catalog, firstPartyModel);
266 + if (!entry || apiModels.has(entry.model.slug)) continue;
267 + apiModels.set(entry.model.slug, stripClaudeContextWindowSuffix(reported.value));
268 + }
269 + if (apiModels.size === 0) return catalog;
270 + return {
271 + models: catalog.models.map((entry) => {
272 + const apiModel = apiModels.get(entry.model.slug);
273 + return apiModel ? { ...entry, apiModel } : entry;
274 + }),
275 + };
276 +}
277 +
278 export function resolveClaudeModelSlug(catalog: ClaudeModelCatalog, slugOrAlias: string): string {
279 return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.slug ?? slugOrAlias;
280 }
@@ -506,7 +546,7 @@ export function resolveClaudeCatalogApiModelId(
546 modelSelection: ModelSelection,
547 ): string {
548 const entry = resolveClaudeCatalogModel(catalog, modelSelection.model);
509 - const slug = entry?.model.slug ?? modelSelection.model;
549 + const slug = entry?.apiModel ?? entry?.model.slug ?? modelSelection.model;
550 const descriptors = getProviderOptionDescriptors({
551 caps: entry?.model.capabilities ?? EMPTY_CAPABILITIES,
552 selections: modelSelection.options,
apps/server/src/provider/Drivers/ClaudeDriver.ts
+31 -1
@@ -36,6 +36,10 @@ import {
36 import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
37 import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
38 import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts";
39 +import {
40 + makeClaudeCodeModelRoutes,
41 + resolveClaudeModelSettingsKey,
42 +} from "../ClaudeCodeModelRoutes.ts";
43 import {
44 defaultProviderContinuationIdentity,
45 type ProviderDriver,
@@ -146,6 +150,23 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
150 });
151
152 const scopedLimitNames = yield* makeClaudeScopedLimitNames;
153 + // The SDK's user source is the host's home, not a custom one; same rule as the adapter.
154 + const customHome =
155 + effectiveConfig.homePath.trim().length > 0 ||
156 + processEnv.CLAUDE_CONFIG_DIR !== (yield* HostProcess.Environment).CLAUDE_CONFIG_DIR;
157 + // Only a successful probe records routes, so a failed one never sends turns back to slugs
158 + // the backend rejects.
159 + const modelRoutes = yield* makeClaudeCodeModelRoutes(
160 + (cwd) =>
161 + resolveClaudeModelSettingsKey(
162 + customHome ? ["project", "local"] : ["user", "project", "local"],
163 + cwd,
164 + ).pipe(
165 + Effect.provideService(FileSystem.FileSystem, fileSystem),
166 + Effect.provideService(Path.Path, path),
167 + ),
168 + stateDir,
169 + );
170 const orchestrationAdapter = yield* createClaudeAdapterV2(
171 {
172 instanceId,
@@ -159,6 +180,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
180 scopedLimitNames,
181 onUsageLimits: (update) => snapshot.applyUsageLimits(update),
182 modelCatalog,
183 + routeModelCatalog: modelRoutes.route,
184 },
185 ).pipe(
186 Effect.mapError(
@@ -175,6 +197,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
197 effectiveConfig,
198 processEnv,
199 modelCatalog,
200 + modelRoutes.route,
201 );
202
203 // Per-instance capabilities cache: keyed on binary + resolved HOME so
@@ -193,7 +216,12 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
216 })),
217 ),
218 ),
196 - Effect.tap(({ capabilities }) => Ref.set(lastGoodCapabilities, capabilities)),
219 + Effect.tap(({ capabilities }) =>
220 + Ref.set(lastGoodCapabilities, capabilities).pipe(
221 + Effect.andThen(modelRoutes.record(capabilities.models ?? [])),
222 + ),
223 + ),
224 + Effect.ensuring(modelRoutes.settle),
225 Effect.catch((error) =>
226 Ref.getAndSet(lastGoodCapabilities, undefined).pipe(
227 Effect.flatMap((capabilities) =>
@@ -262,6 +290,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
290 Effect.map(stampIdentity),
291 ),
292 ),
293 + // Disabled, failed version checks and interruption never reach the probe.
294 + Effect.ensuring(modelRoutes.settle),
295 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
296 Effect.provideService(FileSystem.FileSystem, fileSystem),
297 Effect.provideService(Path.Path, path),
apps/server/src/provider/Drivers/ClaudeHome.ts
+43
@@ -100,6 +100,49 @@ export const hasClaudeManagedMcpConfig = Effect.fn("hasClaudeManagedMcpConfig")(
100 return yield* fileSystem.exists(managedMcpConfigPath).pipe(Effect.orElseSucceed(() => false));
101 });
102
103 +// A worktree's .git file points at <main>/.git/worktrees/<name>, whose commondir leads back to
104 +// <main>/.git. A bare repository has no main checkout, so its worktree keeps its own file.
105 +// Untraced because claudeLocalSettingsDirectory already owns the span.
106 +const mainCheckoutRoot = Effect.fnUntraced(function* (checkout: string) {
107 + const fileSystem = yield* FileSystem.FileSystem;
108 + const path = yield* Path.Path;
109 + return yield* fileSystem.readFileString(path.join(checkout, ".git")).pipe(
110 + Effect.flatMap((pointer) => {
111 + const gitDir = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();
112 + if (gitDir === undefined) return Effect.succeed(checkout);
113 + const worktreeGitDir = path.resolve(checkout, gitDir);
114 + return fileSystem.readFileString(path.join(worktreeGitDir, "commondir")).pipe(
115 + Effect.map((commonDir) => {
116 + const common = path.resolve(worktreeGitDir, commonDir.trim());
117 + return path.basename(common) === ".git" ? path.dirname(common) : checkout;
118 + }),
119 + );
120 + }),
121 + Effect.orElseSucceed(() => checkout),
122 + );
123 +});
124 +
125 +// Claude Code keeps .claude/settings.local.json at the repository root, or in cwd outside a
126 +// repository, on Windows, or when the root is home. Its owner check is skipped, so callers must
127 +// stay safe when Claude Code ignores the root file.
128 +export const claudeLocalSettingsDirectory = Effect.fn("claudeLocalSettingsDirectory")(function* (
129 + cwd: string,
130 +) {
131 + const fileSystem = yield* FileSystem.FileSystem;
132 + const path = yield* Path.Path;
133 + if ((yield* HostProcess.Platform) === "win32") return cwd;
134 + for (let directory = cwd; ; directory = path.dirname(directory)) {
135 + const isCheckout = yield* fileSystem
136 + .exists(path.join(directory, ".git"))
137 + .pipe(Effect.orElseSucceed(() => false));
138 + if (isCheckout) {
139 + const root = yield* mainCheckoutRoot(directory);
140 + return root === (yield* HostProcess.HomeDirectory) ? cwd : root;
141 + }
142 + if (path.dirname(directory) === directory) return cwd;
143 + }
144 +});
145 +
146 export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationGroupKey")(
147 function* (
148 config: Pick<ClaudeSettings, "homePath">,
apps/server/src/textGeneration/ClaudeTextGeneration.ts
+22 -13
@@ -2,6 +2,7 @@ import * as Effect from "effect/Effect";
2 import * as FileSystem from "effect/FileSystem";
3 import * as Option from "effect/Option";
4 import * as Schema from "effect/Schema";
5 +import * as Scope from "effect/Scope";
6 import * as Stream from "effect/Stream";
7 import { ChildProcess, ChildProcessSpawner } from "effect/process";
8
@@ -97,6 +98,10 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
98 claudeSettings: ClaudeSettings,
99 environment?: NodeJS.ProcessEnv,
100 modelCatalog: Effect.Effect<ClaudeModelCatalog> = Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG),
101 + routeModelCatalog: (
102 + catalog: ClaudeModelCatalog,
103 + cwd: string,
104 + ) => Effect.Effect<ClaudeModelCatalog> = Effect.succeed,
105 ) {
106 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
107 const fileSystem = yield* FileSystem.FileSystem;
@@ -146,9 +151,19 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
151 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
152 S["Type"],
153 TextGenerationError,
149 - S["DecodingServices"]
154 + S["DecodingServices"] | Scope.Scope
155 > {
151 - const catalog = yield* scopedModelCatalog;
156 + const workingDirectory =
157 + operation === "generateThreadTitle"
158 + ? yield* fileSystem
159 + .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" })
160 + .pipe(
161 + Effect.mapError((cause) =>
162 + normalizeCliError("claude", operation, cause, "Failed to create title directory"),
163 + ),
164 + )
165 + : cwd;
166 + const catalog = yield* routeModelCatalog(yield* scopedModelCatalog, workingDirectory);
167 const resolvedModelSelection = {
168 ...modelSelection,
169 model: resolveClaudeModelSlug(catalog, modelSelection.model),
@@ -200,16 +215,6 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
215 const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* (
216 noSessionPersistence: boolean,
217 ) {
203 - const workingDirectory =
204 - operation === "generateThreadTitle"
205 - ? yield* fileSystem
206 - .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" })
207 - .pipe(
208 - Effect.mapError((cause) =>
209 - normalizeCliError("claude", operation, cause, "Failed to create title directory"),
210 - ),
211 - )
212 - : cwd;
218 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
219 const spawnCommand = yield* resolveSpawnCommand(
220 claudeSettings.binaryPath || "claude",
@@ -344,5 +349,9 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
349 );
350 });
351
347 - return TextGenerationOperations.fromRunner("ClaudeTextGeneration", runClaudeJson);
352 + return TextGenerationOperations.fromRunner(
353 + "ClaudeTextGeneration",
354 + <S extends Schema.Top>(request: TextGenerationOperations.Request<S>) =>
355 + Effect.scoped(runClaudeJson(request)),
356 + );
357 });