Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions apps/server/src/claudeModelOptions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,30 @@ const selection = (

describe("compileClaudeModelSelection", () => {
it("compiles context, effort, and settings together", () => {
expect(compileClaudeModelSelection(selection("claude-haiku-4-5-20251001", [])).apiModelId).toBe(
"claude-haiku-4-5-20251001",
);
expect(
compileClaudeModelSelection(
selection("claude-opus-4-6", [
{ id: "contextWindow", value: "1m" },
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
]),
),
).toMatchObject({
apiModelId: "claude-opus-4-6[1m]",
effort: "max",
settings: { fastMode: true },
});
compileClaudeModelSelection(selection("haiku", []), {
...BUNDLED_CLAUDE_MODEL_CATALOG,
gatewayModelIds: new Set(["haiku"]),
}),
).toMatchObject({ apiModelId: "haiku", pinnedAlias: "haiku" });
for (const model of ["claude-opus-4-6", "claude-opus-4-6-20261101"]) {
expect(
compileClaudeModelSelection(
selection(model, [
{ id: "contextWindow", value: "1m" },
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
]),
),
).toMatchObject({
apiModelId: model + "[1m]",
effort: "max",
settings: { fastMode: true },
});
}
});

it("runs Ultracode at the chosen effort and reads the old Ultracode effort as xhigh", () => {
Expand Down
13 changes: 10 additions & 3 deletions apps/server/src/claudeModelOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,18 @@ import {

const CLAUDE_CODE_MODEL_ALIASES = new Set(["opus", "sonnet", "haiku", "fable"]);

export function resolveClaudeGatewayAlias(catalog: ClaudeModelCatalog, model: string) {
return CLAUDE_CODE_MODEL_ALIASES.has(model) && catalog.gatewayModelIds?.has(model)
? model
: undefined;
}

export interface CompiledClaudeModelSelection {
readonly apiModelId: string;
readonly effort: string | undefined;
readonly promptEffort: string | undefined;
readonly settings: Readonly<Record<string, boolean>>;
/** The alias of a custom model named like one, which Claude Code would otherwise expand. */
/** A custom or gateway model ID that Claude Code would otherwise expand as an alias. */
readonly pinnedAlias: string | undefined;
readonly queryIdentity: string;
}
Expand Down Expand Up @@ -61,10 +67,11 @@ export function compileClaudeModelSelection(
const promptEffort = resolvePromptInjectedEffort(capabilities, rawEffort) ?? undefined;
// An alias the catalog routes a built-in model to is Claude Code's own and is not pinned.
const pinnedAlias =
CLAUDE_CODE_MODEL_ALIASES.has(apiModelId) &&
resolveClaudeGatewayAlias(catalog, selection.model) ??
(CLAUDE_CODE_MODEL_ALIASES.has(apiModelId) &&
resolveClaudeModelSlug(catalog, selection.model) === apiModelId
? apiModelId
: undefined;
: undefined);
return {
apiModelId,
effort,
Expand Down
3 changes: 1 addition & 2 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2374,8 +2374,7 @@ export function makeClaudeQueryOptions(input: {
...(typeof querySettings === "object" && querySettings !== null ? querySettings : {}),
autoCompactWindow: Number(autoCompactWindow),
} as ClaudeSdkSettings);
// Claude Code expands a bare alias to its own model, so a custom model with an alias's name
// pins the alias to itself.
// Claude Code expands bare aliases unless they are pinned to the exact model ID.
const aliasOverrideEnv =
compiledSelection.pinnedAlias === undefined
? undefined
Expand Down
81 changes: 42 additions & 39 deletions apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,44 +74,47 @@ it.effect("reports a deleted worktree's scan as finished, not pending", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);

it.effect("keeps the probe subprocess alive while gateway model discovery can finish", () =>
Effect.gen(function* () {
let abortSignal: AbortSignal | undefined;
const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
abortSignal = options?.abortController?.signal;
return {
initializationResult: async () => ({
account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" },
commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],
models: [{ value: "gateway/claude-relay", displayName: "Relay", description: "" }],
it.effect.each(["1", true])(
"keeps the probe subprocess alive for gateway discovery flag %s",
(enabled) =>
Effect.gen(function* () {
let abortSignal: AbortSignal | undefined;
const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
abortSignal = options?.abortController?.signal;
return {
initializationResult: async () => ({
account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" },
commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],
models: [{ value: "gateway/claude-relay", displayName: "Relay", description: "" }],
}),
usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: () =>
new Promise((_, reject) => reject(new Error("usage unavailable"))),
} as ReturnType<typeof ClaudeSdk.query>;
});
yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
const fileSystem = yield* FileSystem.FileSystem;
const configDir = yield* fileSystem.makeTempDirectoryScoped();
// Claude Code also reads these from settings.json, which is where gateway users set them.
yield* fileSystem.writeFileString(
`${configDir}/settings.json`,
JSON.stringify({
env: {
ANTHROPIC_BASE_URL: "https://gateway.example",
CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: enabled,
CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS: 1000,
},
}),
usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: () =>
new Promise((_, reject) => reject(new Error("usage unavailable"))),
} as ReturnType<typeof ClaudeSdk.query>;
});
yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
const fileSystem = yield* FileSystem.FileSystem;
const configDir = yield* fileSystem.makeTempDirectoryScoped();
// Claude Code also reads these from settings.json, which is where gateway users set them.
yield* fileSystem.writeFileString(
`${configDir}/settings.json`,
JSON.stringify({
env: {
ANTHROPIC_BASE_URL: "https://gateway.example",
CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: "1",
},
}),
);
const capabilities = yield* probeClaudeCapabilities(
yield* decodeClaudeSettings({ binaryPath: "claude" }),
{ PATH: (yield* HostProcess.Environment).PATH, CLAUDE_CONFIG_DIR: configDir },
);
assert.deepEqual(
capabilities.models?.map((model) => model.value),
["gateway/claude-relay"],
);
assert.equal(abortSignal?.aborted, false);
yield* TestClock.adjust("3 seconds");
assert.equal(abortSignal?.aborted, true);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
const capabilities = yield* probeClaudeCapabilities(
yield* decodeClaudeSettings({ binaryPath: "claude" }),
{ PATH: (yield* HostProcess.Environment).PATH, CLAUDE_CONFIG_DIR: configDir },
);
assert.deepEqual(
capabilities.models?.map((model) => model.value),
["gateway/claude-relay"],
);
assert.equal(abortSignal?.aborted, false);
yield* TestClock.adjust("1 second");
assert.equal(abortSignal?.aborted, true);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
25 changes: 22 additions & 3 deletions apps/server/src/provider/ClaudeCodeModelRoutes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ describe("Claude Code model routes", () => {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-haiku-4-5",
} satisfies ModelSelection;
const gatewayFable = { ...haiku, model: "fable-5.1" };
const routes = yield* makeClaudeCodeModelRoutes(
() => Effect.succeed("same settings"),
(cwd) => Effect.succeed(cwd === "/other" ? "other settings" : "same settings"),
"/state",
);
const early = yield* routes
Expand All @@ -30,10 +31,28 @@ describe("Claude Code model routes", () => {
yield* routes.record([
{ value: "haiku", resolvedModel: "us.anthropic.claude-haiku-4-5-20251001-v1:0" },
]);
yield* routes.recordGateway(["fable-5.1"]);
yield* routes.settle;
const catalog = yield* Fiber.join(early);
assert.strictEqual(resolveClaudeCatalogApiModelId(catalog, haiku), "haiku");
assert.strictEqual(resolveClaudeCatalogApiModelId(catalog, gatewayFable), "fable-5.1");
assert.strictEqual(
yield* routes.route(BUNDLED_CLAUDE_MODEL_CATALOG, "/other"),
BUNDLED_CLAUDE_MODEL_CATALOG,
);
assert.strictEqual(
yield* routes.route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project", {
availableModels: ["claude-fable-5-1"],
}),
BUNDLED_CLAUDE_MODEL_CATALOG,
);
yield* routes.recordGateway([]);
assert.strictEqual(
resolveClaudeCatalogApiModelId(yield* Fiber.join(early), haiku),
"haiku",
resolveClaudeCatalogApiModelId(
yield* routes.route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project"),
gatewayFable,
),
"claude-fable-5-1",
);

// A first check that never reaches the probe still releases waiting turns.
Expand Down
24 changes: 19 additions & 5 deletions apps/server/src/provider/ClaudeCodeModelRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ export const resolveClaudeModelSettingsKey = Effect.fn("resolveClaudeModelSettin
type ReportedModel = Pick<ClaudeModelInfo, "value" | "resolvedModel">;

/**
* Claude Code's reported model ids, applied to a turn only where its cwd resolves model settings
* as the probe's cwd did. `settle` releases turns waiting for the first probe, whatever its outcome.
* Model ids from Claude Code and the gateway apply where the model settings match the probe's.
* `settle` releases turns waiting for the first provider check.
*/
export const makeClaudeCodeModelRoutes = Effect.fn("makeClaudeCodeModelRoutes")(function* (
settingsKey: (cwd: string | null) => Effect.Effect<string | undefined>,
Expand All @@ -86,12 +86,21 @@ export const makeClaudeCodeModelRoutes = Effect.fn("makeClaudeCodeModelRoutes")(
readonly models: ReadonlyArray<ReportedModel>;
readonly settingsKey: string | undefined;
}>({ models: [], settingsKey: undefined });
const gateway = yield* Ref.make<{
readonly ids: ReadonlySet<string>;
readonly settingsKey: string | undefined;
}>({ ids: new Set(), settingsKey: undefined });
return {
record: Effect.fn("ClaudeCodeModelRoutes.record")(function* (
models: ReadonlyArray<ReportedModel>,
) {
yield* Ref.set(reported, { models, settingsKey: yield* settingsKey(probeCwd) });
}),
recordGateway: Effect.fn("ClaudeCodeModelRoutes.recordGateway")(function* (
ids: ReadonlyArray<string>,
) {
yield* Ref.set(gateway, { ids: new Set(ids), settingsKey: yield* settingsKey(probeCwd) });
}),
settle: Deferred.succeed(firstProbeSettled, undefined).pipe(Effect.asVoid),
route: Effect.fn("ClaudeCodeModelRoutes.route")(function* (
base: ClaudeModelCatalog,
Expand All @@ -106,11 +115,16 @@ export const makeClaudeCodeModelRoutes = Effect.fn("makeClaudeCodeModelRoutes")(
);
if (claudeModelSettingsKey(launchSettings ?? {}) !== NO_MODEL_SETTINGS_KEY) return base;
const { models, settingsKey: probeKey } = yield* Ref.get(reported);
const routed = withClaudeCodeModelRoutes(base, models);
const { ids, settingsKey: gatewayKey } = yield* Ref.get(gateway);
const routed = probeKey === undefined ? base : withClaudeCodeModelRoutes(base, models);
if (routed === base && (ids.size === 0 || gatewayKey === undefined)) return base;
// Project settings can point an alias at another model, so routes hold only where the
// cwd resolves the same model settings as the probe's.
if (routed === base || probeKey === undefined) return base;
return (yield* settingsKey(cwd)) === probeKey ? routed : base;
const cwdKey = yield* settingsKey(cwd);
const catalog = cwdKey === probeKey ? routed : base;
return ids.size > 0 && gatewayKey !== undefined && cwdKey === gatewayKey
? { ...catalog, gatewayModelIds: ids }
: catalog;
}),
};
});
88 changes: 87 additions & 1 deletion apps/server/src/provider/ClaudeModelCatalog.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { assert, describe, it } from "@effect/vitest";
import { type ModelSelection, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { buildServerProvider } from "@t3tools/provider-core/server/snapshotProbe";

import { applyClaudeGatewayModels } from "./Drivers/ClaudeGatewayModels.ts";

import { resolveProviderCatalog, type ModelManifestData } from "./ModelManifest.ts";
import {
Expand Down Expand Up @@ -75,6 +78,66 @@ const catalogFromManifest = (data: ModelManifestData) =>
resolveClaudeModelCatalog(resolveProviderCatalog(data, CLAUDE) ?? undefined);

describe("Claude model catalog", () => {
it("advertises discovered gateway models without requiring saved custom model settings", () => {
const opus = BUNDLED_CLAUDE_MODEL_CATALOG.models.find(
(entry) => entry.model.slug === "claude-opus-4-5",
)!.model;
const provider = buildServerProvider({
presentation: { displayName: "Claude" },
enabled: true,
checkedAt: "2026-11-01T00:00:00Z",
updateRequiredModels: [{ slug: "claude-haiku-5-5", name: "Haiku", minVersion: "2.1.293" }],
models: [
opus,
{
slug: "claude-opus-4-5-20251101",
name: "SDK dated Opus",
isCustom: false,
capabilities: { optionDescriptors: [] },
},
{ slug: "haiku", name: "Custom Haiku", isCustom: true, capabilities: null },
{ slug: "claude-sonnet-4-6", name: "Saved Sonnet", isCustom: false, capabilities: null },
{ slug: "known", name: "Known", isCustom: false, capabilities: null },
{ slug: "omitted", name: "Omitted", isCustom: false, capabilities: null },
{ slug: "saved", name: "Saved", isCustom: true, capabilities: null },
],
probe: {
installed: true,
version: "2.1.250",
status: "ready",
auth: { status: "authenticated" },
},
});
const result = applyClaudeGatewayModels(
provider,
[
{ id: "known" },
{ id: "claude-opus-4-5-20251101" },
{ id: "fable-5.1" },
{ id: "claude-haiku-5-5-20261101" },
{ id: "claude-haiku-4-5-20251001", display_name: "Gateway Haiku" },
{ id: "haiku" },
],
BUNDLED_CLAUDE_MODEL_CATALOG,
["saved", "haiku", "claude-sonnet-4-6"],
);
assert.strictEqual(result.modelsAuthoritative, true);
assert.deepStrictEqual(result.models, [
{ slug: "known", name: "Known", isCustom: false, capabilities: null },
{ ...opus, slug: "claude-opus-4-5-20251101" },
{
slug: "claude-haiku-4-5-20251001",
name: "Gateway Haiku",
isCustom: false,
capabilities: { optionDescriptors: [] },
},
{ slug: "haiku", name: "Custom Haiku", isCustom: true, capabilities: null },
{ slug: "claude-sonnet-4-6", name: "Saved Sonnet", isCustom: false, capabilities: null },
{ slug: "saved", name: "Saved", isCustom: true, capabilities: null },
]);
assert.deepStrictEqual(result.updateRequiredModels, provider.updateRequiredModels);
});

it("resolves capacity from selected options and fixed catalog windows without guessing custom models", () => {
const source = manifest();
const profile = source.providers!.claudeAgent!.profiles.synthetic!;
Expand Down Expand Up @@ -186,12 +249,26 @@ describe("Claude model catalog", () => {
aliases: ["claude-synthetic-next"],
status: "current",
},
...base.providers!.claudeAgent!.models,
...base.providers!.claudeAgent!.models.map((model) => ({
...model,
aliases: [...(model.aliases ?? []), "claude-synthetic-next-20251001"],
})),
],
},
},
};
const catalog = catalogFromManifest(input);
assert.strictEqual(
resolveClaudeModelSlug(catalog, "claude-synthetic-next-20251001"),
"claude-synthetic-next",
);
assert.strictEqual(
resolveClaudeCatalogApiModelId(catalog, {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-synthetic-next-20251001",
}),
"claude-synthetic-next-20251001[large]",
);
assert.strictEqual(resolveClaudeModelSlug(catalog, "synthetic"), "claude-synthetic-next");
assert.strictEqual(
resolveClaudeModelSlug(catalog, "claude-synthetic-next"),
Expand All @@ -205,6 +282,14 @@ describe("Claude model catalog", () => {
}),
"claude-synthetic-next[large]",
);
const gatewayCatalog = { ...catalog, gatewayModelIds: new Set(["synthetic"]) };
assert.strictEqual(
resolveClaudeCatalogApiModelId(gatewayCatalog, {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "synthetic",
}),
"synthetic[large]",
);
});

it("appends custom models with their own descriptors and keeps bare slugs opaque", () => {
Expand Down Expand Up @@ -314,6 +399,7 @@ describe("Claude model catalog", () => {
"us.anthropic.claude-opus-4-6-v1",
);
assert.strictEqual(apiModel(defaultBedrock, "claude-haiku-4-5"), "haiku");
assert.strictEqual(apiModel(defaultBedrock, "claude-haiku-4-5-20251001"), "haiku");
assert.strictEqual(apiModel(defaultBedrock, "claude-haiku-5-5"), "claude-haiku-5-5");

// First-party ids already are what Claude Code runs, even when an alias points elsewhere.
Expand Down
Loading
Loading