@devries-cameron20 / t3code-1 / commits / dd69b31665
Fork 0

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

feat(server): list Claude models reported by Claude Code (#30511)

Co-authored-by: Otavio Salvador <otavio@ossystems.com.br> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 3, 2026 at 17:10 UTC dd69b316656119b4613b13f3c076f45d4dbda2ce
5 files changed +225 -13
apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts
+46
@@ -2,12 +2,16 @@
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { ClaudeSettings, type ServerProvider } from "@t3tools/contracts";
4 import { vi } from "vite-plus/test";
5 +import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
6 import { assert, it } from "@effect/vitest";
7 import * as Effect from "effect/Effect";
8 +import * as FileSystem from "effect/FileSystem";
9 import * as Schema from "effect/Schema";
10 +import * as TestClock from "effect/testing/TestClock";
11
12 import {
13 buildClaudeCapabilitiesProbeQueryOptions,
14 + probeClaudeCapabilities,
15 probeClaudeWorkspaceSnapshot,
16 } from "./ClaudeProvider.ts";
17
@@ -41,3 +45,45 @@ it.effect("reports a deleted worktree's scan as finished, not pending", () =>
45 assert.strictEqual(snapshot.slashCommandsPending, false);
46 }).pipe(Effect.provide(NodeServices.layer)),
47 );
48 +
49 +it.effect("keeps the probe subprocess alive while gateway model discovery can finish", () =>
50 + Effect.gen(function* () {
51 + let abortSignal: AbortSignal | undefined;
52 + const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
53 + abortSignal = options?.abortController?.signal;
54 + return {
55 + initializationResult: async () => ({
56 + account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" },
57 + commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],
58 + models: [{ value: "gateway/claude-relay", displayName: "Relay", description: "" }],
59 + }),
60 + usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: () =>
61 + new Promise((_, reject) => reject(new Error("usage unavailable"))),
62 + } as ReturnType<typeof ClaudeSdk.query>;
63 + });
64 + yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
65 + const fileSystem = yield* FileSystem.FileSystem;
66 + const configDir = yield* fileSystem.makeTempDirectoryScoped();
67 + // Claude Code also reads these from settings.json, which is where gateway users set them.
68 + yield* fileSystem.writeFileString(
69 + `${configDir}/settings.json`,
70 + JSON.stringify({
71 + env: {
72 + ANTHROPIC_BASE_URL: "https://gateway.example",
73 + CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: "1",
74 + },
75 + }),
76 + );
77 + const capabilities = yield* probeClaudeCapabilities(
78 + yield* decodeClaudeSettings({ binaryPath: "claude" }),
79 + { PATH: process.env.PATH, CLAUDE_CONFIG_DIR: configDir },
80 + );
81 + assert.deepEqual(
82 + capabilities.models?.map((model) => model.value),
83 + ["gateway/claude-relay"],
84 + );
85 + assert.equal(abortSignal?.aborted, false);
86 + yield* TestClock.adjust("3 seconds");
87 + assert.equal(abortSignal?.aborted, true);
88 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
89 +);
apps/server/src/provider/ClaudeModelCatalog.ts
+61
@@ -6,6 +6,7 @@ import {
6 type ServerProviderModel,
7 type ServerProviderUpdateRequiredModel,
8 } from "@t3tools/contracts";
9 +import type { ModelInfo as ClaudeModelInfo } from "@anthropic-ai/claude-agent-sdk";
10 import * as Option from "effect/Option";
11 import {
12 getModelSelectionStringOptionValue,
@@ -114,6 +115,66 @@ export function scopeClaudeModelCatalog(
115 return { models: [...builtInModels, ...customCatalogModels] };
116 }
117
118 +const CLAUDE_EFFORT_LABELS: Readonly<Record<string, string>> = {
119 + low: "Low",
120 + medium: "Medium",
121 + high: "High",
122 + xhigh: "Extra High",
123 + max: "Max",
124 +};
125 +
126 +function stripClaudeContextWindowSuffix(value: string): string {
127 + return value.replace(/\[[^\]]*\]$/, "").trim();
128 +}
129 +
130 +export function claudeReportedModels(
131 + catalog: ClaudeModelCatalog,
132 + customModels: ReadonlyArray<CustomModelSetting>,
133 + reported: ReadonlyArray<ClaudeModelInfo> | undefined,
134 +): ReadonlyArray<ServerProviderModel> {
135 + if (!reported?.length) return [];
136 + const known = new Set(
137 + [
138 + ...catalog.models.flatMap(({ model }) => [model.slug, ...(model.aliases ?? [])]),
139 + ...readCustomModelEntries(customModels).map((entry) => entry.slug),
140 + ].map((id) => stripClaudeContextWindowSuffix(id).toLowerCase()),
141 + );
142 + const models: Array<ServerProviderModel> = [];
143 + for (const info of reported) {
144 + const slug = info.value.trim();
145 + // `default` is Claude Code's pointer at its own default model, not a model.
146 + if (!slug || slug === "default") continue;
147 + const ids = [slug, info.resolvedModel ?? ""]
148 + .map((id) => stripClaudeContextWindowSuffix(id).toLowerCase())
149 + .filter((id) => id.length > 0);
150 + if (ids.some((id) => known.has(id))) continue;
151 + for (const id of ids) known.add(id);
152 + const efforts = info.supportsEffort ? (info.supportedEffortLevels ?? []) : [];
153 + models.push({
154 + slug,
155 + name: info.displayName.trim() || slug,
156 + isCustom: false,
157 + capabilities: {
158 + optionDescriptors: efforts.length
159 + ? [
160 + {
161 + id: "effort",
162 + label: "Reasoning",
163 + type: "select",
164 + // `default` is not an effort, so choosing it sends none and Claude Code picks.
165 + options: [
166 + { id: "default", label: "Default", isDefault: true },
167 + ...efforts.map((id) => ({ id, label: CLAUDE_EFFORT_LABELS[id] ?? id })),
168 + ],
169 + },
170 + ]
171 + : [],
172 + },
173 + });
174 + }
175 + return models;
176 +}
177 +
178 function resolveClaudeCatalogModel(
179 catalog: ClaudeModelCatalog,
180 slugOrAlias: string | null | undefined,
apps/server/src/provider/ClaudeProvider.ts
+46 -13
@@ -18,6 +18,7 @@ import { createModelCapabilities } from "@t3tools/shared/model";
18 import { resolveSpawnCommand } from "@t3tools/shared/shell";
19 import {
20 query as claudeQuery,
21 + type ModelInfo as ClaudeModelInfo,
22 type Options as ClaudeQueryOptions,
23 type SlashCommand as ClaudeSlashCommand,
24 type SDKControlGetUsageResponse,
@@ -48,6 +49,7 @@ import {
49 import {
50 BUNDLED_CLAUDE_MODEL_CATALOG,
51 type ClaudeModelCatalog,
52 + claudeReportedModels,
53 formatClaudeVersionUpgradeMessage,
54 resolveClaudeModelsForVersion,
55 resolveClaudeUpdateRequiredModels,
@@ -241,6 +243,7 @@ export type ClaudeCapabilitiesProbe = {
243 /** OAuth applies only to firstParty; Bedrock uses external AWS credentials and omits subscription/token fields. */
244 readonly apiProvider: string | undefined;
245 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
246 + readonly models?: ReadonlyArray<ClaudeModelInfo>;
247 /** Undefined means get_usage failed; absent windows on success mean no subscription windows, as with API keys. */
248 readonly usage?: Pick<SDKControlGetUsageResponse, "rate_limits_available" | "rate_limits">;
249 readonly usageCheckedAt?: string;
@@ -318,6 +321,20 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {
321 });
322 }
323
324 +/**
325 + * With gateway model discovery on, Claude Code refreshes its model cache in the background after
326 + * initialization, so the probe subprocess outlives init by Claude Code's discovery timeout.
327 + */
328 +function claudeGatewayDiscoveryGraceMs(environment: Readonly<Record<string, unknown>>): number {
329 + const enabled = String(environment.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY ?? "")
330 + .trim()
331 + .toLowerCase();
332 + if (!enabled || enabled === "0" || enabled === "false") return 0;
333 + if (!String(environment.ANTHROPIC_BASE_URL ?? "").trim()) return 0;
334 + const configured = Number(environment.CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS);
335 + return Number.isFinite(configured) && configured > 0 ? configured : 3_000;
336 +}
337 +
338 /** A never-yielding prompt allows local initialization IPC without sending an Anthropic request. */
339 const probeClaudeCapabilities = (
340 claudeSettings: ClaudeSettings,
@@ -326,6 +343,9 @@ const probeClaudeCapabilities = (
343 includeUsage = true,
344 ) => {
345 const abort = new AbortController();
346 + const abortProbe = Effect.sync(() => {
347 + if (!abort.signal.aborted) abort.abort();
348 + });
349 return Effect.gen(function* () {
350 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
351 const executablePath = yield* resolveClaudeSdkExecutablePath(
@@ -333,6 +353,13 @@ const probeClaudeCapabilities = (
353 claudeEnvironment,
354 );
355 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
356 + // Workspace probes (no usage) discard models; the machine probe refreshes the shared cache.
357 + const graceMs = includeUsage
358 + ? claudeGatewayDiscoveryGraceMs({
359 + ...claudeEnvironment,
360 + ...(yield* readClaudeSettingsEnv(claudeSettings, cwd, claudeEnvironment)),
361 + })
362 + : 0;
363 return yield* Effect.tryPromise(async () => {
364 const q = claudeQuery({
365 // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API
@@ -348,11 +375,11 @@ const probeClaudeCapabilities = (
375 }),
376 });
377 const init = await q.initializationResult();
351 - return { q, init };
378 + return { q, init, graceMs };
379 });
380 }).pipe(
381 Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
355 - Effect.flatMap(({ q, init }) =>
382 + Effect.flatMap(({ q, init, graceMs }) =>
383 Effect.gen(function* () {
384 // Usage has its own deadline so a slow optional request cannot discard initialization.
385 // Only the rate limits are read, so skip the local transcript scan that fills
@@ -386,15 +413,18 @@ const probeClaudeCapabilities = (
413 apiKeySource: account?.apiKeySource,
414 apiProvider: account?.apiProvider,
415 slashCommands: parseClaudeInitializationCommands(init.commands),
416 + ...(init.models?.length ? { models: init.models } : {}),
417 ...(usage ? { usage, usageCheckedAt } : {}),
418 } satisfies ClaudeCapabilitiesProbe;
391 - }),
392 - ),
393 - Effect.ensuring(
394 - Effect.sync(() => {
395 - if (!abort.signal.aborted) abort.abort();
396 - }),
419 + }).pipe(
420 + Effect.tap(() =>
421 + graceMs > 0
422 + ? Effect.sleep(graceMs).pipe(Effect.andThen(abortProbe), Effect.forkDetach)
423 + : abortProbe,
424 + ),
425 + ),
426 ),
427 + Effect.onError(() => abortProbe),
428 Effect.tapError((error) =>
429 Effect.logWarning("Claude capability probe failed.", { errorTag: error._tag }),
430 ),
@@ -557,11 +587,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
587 });
588 }
589
560 - const models = providerModelsFromSettings(
561 - resolveClaudeModelsForVersion(modelCatalog, parsedVersion),
562 - claudeSettings.customModels,
563 - DEFAULT_CLAUDE_MODEL_CAPABILITIES,
564 - );
590 const updateRequiredModels = resolveClaudeUpdateRequiredModels(modelCatalog, parsedVersion);
591 const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion);
592
@@ -572,6 +597,14 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
597 probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined;
598 const probeFailure =
599 probeResult && Result.isFailure(probeResult) ? probeResult.failure : undefined;
600 + const models = providerModelsFromSettings(
601 + [
602 + ...resolveClaudeModelsForVersion(modelCatalog, parsedVersion),
603 + ...claudeReportedModels(modelCatalog, claudeSettings.customModels, capabilities?.models),
604 + ],
605 + claudeSettings.customModels,
606 + DEFAULT_CLAUDE_MODEL_CAPABILITIES,
607 + );
608 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
609 const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])];
610 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
apps/server/src/provider/Drivers/ClaudeSkills.ts
+3
@@ -436,6 +436,9 @@ const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(funct
436 const SettingsEnv = Schema.Struct({
437 ANTHROPIC_BASE_URL: Schema.optional(Schema.String),
438 CLAUDE_CODE_ENTRYPOINT: Schema.optional(Schema.String),
439 + // Unquoted JSON values must not fail the decode and drop ANTHROPIC_BASE_URL with them.
440 + CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: Schema.optional(Schema.Unknown),
441 + CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS: Schema.optional(Schema.Unknown),
442 });
443 const decodeSettingsEnv = Schema.decodeUnknownEffect(
444 fromLenientJson(Schema.Struct({ env: Schema.optional(SettingsEnv) })),
apps/server/src/provider/ProviderRegistry.test.ts
+69
@@ -6,6 +6,7 @@ import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
6 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
7 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
8 import * as NodeServices from "@effect/platform-node/NodeServices";
9 +import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
10 import { describe, it, assert, expect } from "@effect/vitest";
11 import * as DateTime from "effect/DateTime";
12 import * as Deferred from "effect/Deferred";
@@ -44,6 +45,7 @@ import { createModelCapabilities } from "@t3tools/shared/model";
45 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
46
47 import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
48 +import { BUNDLED_CLAUDE_MODEL_CATALOG } from "./ClaudeModelCatalog.ts";
49 import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
50 import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
51 import * as AntigravityInstallation from "./AntigravityInstallation.ts";
@@ -175,6 +177,7 @@ type TestClaudeCapabilities = {
177 readonly apiKeySource: string | undefined;
178 readonly apiProvider: string | undefined;
179 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
180 + readonly models?: ReadonlyArray<ModelInfo>;
181 };
182
183 function claudeCapabilities(overrides: Partial<TestClaudeCapabilities> = {}) {
@@ -3038,6 +3041,72 @@ it.layer(
3041 });
3042
3043 describe("checkClaudeProviderStatus", () => {
3044 + it.effect("adds models Claude Code reports that the catalog does not know", () =>
3045 + Effect.gen(function* () {
3046 + const status = yield* checkClaudeProviderStatus(
3047 + {
3048 + ...defaultClaudeSettings,
3049 + customModels: [{ slug: "gateway/kimi-3[1m]", name: "Kimi (mine)" }],
3050 + },
3051 + claudeCapabilities({
3052 + models: [
3053 + { value: "default", displayName: "Default", description: "" },
3054 + { value: "sonnet", displayName: "Sonnet", description: "" },
3055 + { value: "claude-haiku-4-5[1m]", displayName: "Haiku", description: "" },
3056 + {
3057 + value: "best",
3058 + resolvedModel: "claude-opus-5[1m]",
3059 + displayName: "Best",
3060 + description: "",
3061 + },
3062 + { value: "gateway/kimi-3[1m]", displayName: "Kimi 3", description: "" },
3063 + { value: "gateway/glm-5[1m]", displayName: "GLM 5", description: "" },
3064 + { value: "gateway/glm-5", displayName: "GLM 5 again", description: "" },
3065 + {
3066 + value: "gateway/claude-relay",
3067 + displayName: "Claude Relay",
3068 + description: "",
3069 + supportsEffort: true,
3070 + supportedEffortLevels: ["low", "high"],
3071 + },
3072 + ],
3073 + }),
3074 + );
3075 + const catalogSlugs = new Set(BUNDLED_CLAUDE_MODEL_CATALOG.models.map((m) => m.model.slug));
3076 + const added = status.models.filter((model) => !catalogSlugs.has(model.slug));
3077 +
3078 + assert.deepStrictEqual(
3079 + added.map((model) => [model.slug, model.name, model.isCustom]),
3080 + [
3081 + ["gateway/glm-5[1m]", "GLM 5", false],
3082 + ["gateway/claude-relay", "Claude Relay", false],
3083 + ["gateway/kimi-3[1m]", "Kimi (mine)", true],
3084 + ],
3085 + );
3086 + assert.deepStrictEqual(added[0]?.capabilities?.optionDescriptors, []);
3087 + assert.deepStrictEqual(added[1]?.capabilities?.optionDescriptors, [
3088 + {
3089 + id: "effort",
3090 + label: "Reasoning",
3091 + type: "select",
3092 + options: [
3093 + { id: "default", label: "Default", isDefault: true },
3094 + { id: "low", label: "Low" },
3095 + { id: "high", label: "High" },
3096 + ],
3097 + },
3098 + ]);
3099 + }).pipe(
3100 + Effect.provide(
3101 + layerMockSpawner((args) => {
3102 + const joined = args.join(" ");
3103 + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
3104 + throw new Error(`Unexpected args: ${joined}`);
3105 + }),
3106 + ),
3107 + ),
3108 + );
3109 +
3110 it.effect("reports a logged-out CLI as unauthenticated", () =>
3111 Effect.gen(function* () {
3112 const status = yield* checkClaudeProviderStatus(