TypeScript
fix(server): recognize a Claude proxy set in Claude's settings.json (#26937)
Md Ehsanul Haque1854e14d0943
diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.tsindex 93baa797e7f..95f5c6709a4 100644--- a/apps/server/src/provider/ClaudeProvider.ts+++ b/apps/server/src/provider/ClaudeProvider.ts@@ -37,7 +37,7 @@ import {} from "@t3tools/provider-core/server/snapshotProbe";import { resolveClaudeSdkExecutablePath } from "./Drivers/ClaudeExecutable.ts";import { hasClaudeManagedMcpConfig, makeClaudeEnvironment } from "./Drivers/ClaudeHome.ts";-import { discoverClaudeSkills } from "./Drivers/ClaudeSkills.ts";+import { discoverClaudeSkills, readClaudeSettingsBaseUrl } from "./Drivers/ClaudeSkills.ts";import type { ProviderWorkspaceSnapshot } from "@t3tools/provider-core/server/driver";import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";import {@@ -600,7 +600,10 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(}// First-party account fields cannot verify custom endpoint credentials.- const endpoint = URL.parse(resolvedEnvironment.ANTHROPIC_BASE_URL?.trim() ?? "");+ const baseUrl =+ (yield* readClaudeSettingsBaseUrl(claudeSettings, cwd, resolvedEnvironment)) ??+ resolvedEnvironment.ANTHROPIC_BASE_URL;+ const endpoint = URL.parse(baseUrl?.trim() ?? "");const customApiEndpoint =endpoint !== null &&(endpoint.protocol === "http:" || endpoint.protocol === "https:") &&@@ -625,13 +628,14 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(});}+ // A proxy's ANTHROPIC_AUTH_TOKEN reads as an API key; the endpoint is what the token is for.const authMetadata =+ apiProviderAuthMetadata(capabilities.apiProvider) ??+ (customApiEndpoint ? { type: "customEndpoint", label: "Custom API endpoint" } : undefined) ??claudeAuthMetadata({subscriptionType: capabilities.subscriptionType,authMethod: capabilities.tokenSource,- }) ??- apiProviderAuthMetadata(capabilities.apiProvider) ??- (customApiEndpoint ? { type: "customEndpoint", label: "Custom API endpoint" } : undefined);+ });const usageCheckedAt = capabilities.usageCheckedAt ?? checkedAt;const usageLimits = !capabilities.usage? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" })diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.ts b/apps/server/src/provider/Drivers/ClaudeSkills.tsindex bc68e42b76a..6aff76d250a 100644--- a/apps/server/src/provider/Drivers/ClaudeSkills.ts+++ b/apps/server/src/provider/Drivers/ClaudeSkills.ts@@ -119,7 +119,8 @@ function claudeManagedSettingsPath(return "/etc/claude-code/managed-settings.json";}-function skillOverrideSettingsPaths(+/** Claude Code settings files, lowest precedence first. */+function claudeSettingsPaths(path: Path.Path,configDirPath: string,cwd: string | undefined,@@ -247,7 +248,7 @@ const readSkillSettings = Effect.fn("readSkillSettings")(function* (const enabledPlugins = new Map<string, boolean>();const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd);- for (const settingsPath of skillOverrideSettingsPaths(+ for (const settingsPath of claudeSettingsPaths(path,configDirPath,cwd,@@ -427,6 +428,43 @@ const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(functreturn path.join(home, ".claude");});+const SettingsBaseUrl = fromLenientJson(+ Schema.Struct({+ env: Schema.optional(Schema.Struct({ ANTHROPIC_BASE_URL: Schema.optional(Schema.String) })),+ }),+);+const decodeSettingsBaseUrl = Schema.decodeUnknownEffect(SettingsBaseUrl);++/** ANTHROPIC_BASE_URL from Claude's settings `env`, which Claude Code applies over the process env. */+export const readClaudeSettingsBaseUrl = Effect.fn("readClaudeSettingsBaseUrl")(function* (+ config: Pick<ClaudeSettings, "homePath">,+ cwd: string | undefined,+ environment: NodeJS.ProcessEnv,+): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const platform = yield* HostProcess.Platform;+ const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, cwd);+ let baseUrl: string | undefined;+ for (const settingsPath of claudeSettingsPaths(+ path,+ configDirPath,+ undefined,+ platform,+ environment,+ )) {+ const contents = yield* fileSystem+ .readFileString(settingsPath)+ .pipe(Effect.orElseSucceed(() => undefined));+ if (contents === undefined) continue;+ const parsed = yield* decodeSettingsBaseUrl(contents).pipe(+ Effect.orElseSucceed(() => undefined),+ );+ baseUrl = parsed?.env?.ANTHROPIC_BASE_URL ?? baseUrl;+ }+ return baseUrl;+});+// Claude's --add-dir is repeatable and variadic; parseCliArgs keeps only one value.export function claudeLaunchArgDirectories(launchArgs?: string): ReadonlyArray<string> {const directories: string[] = [];diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.tsindex 10771e63665..60aad9c5997 100644--- a/apps/server/src/provider/ProviderRegistry.test.ts+++ b/apps/server/src/provider/ProviderRegistry.test.ts@@ -1,7 +1,4 @@-import * as HostProcess from "@t3tools/shared/HostProcess";import * as CodexErrors from "effect-codex-app-server/errors";-import * as Path from "effect/Path";-import * as FileSystem from "effect/FileSystem";import { vi } from "vite-plus/test";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import * as CodexInstallation from "./CodexInstallation.ts";@@ -14,7 +11,9 @@ import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";import * as Fiber from "effect/Fiber";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";+import * as Path from "effect/Path";import * as PubSub from "effect/PubSub";import * as Ref from "effect/Ref";import * as Schema from "effect/Schema";@@ -38,6 +37,7 @@ import {} from "@t3tools/contracts";import { HttpClient, HttpClientResponse } from "effect/http";import { ChildProcessSpawner } from "effect/process";+import * as HostProcess from "@t3tools/shared/HostProcess";import { deepMerge } from "@t3tools/shared/Struct";import { createModelCapabilities } from "@t3tools/shared/model";import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";@@ -340,6 +340,13 @@ const layerTestNodeServices = Layer.mergeAll(Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {getEnvironmentId: Effect.succeed(EnvironmentId.make("00000000-0000-4000-8000-000000000001")),}),+ // An empty home, so the developer's own Claude settings never reach provider probes.+ Layer.effect(+ HostProcess.HomeDirectory,+ Effect.gen(function* () {+ return yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();+ }),+ ).pipe(Layer.provide(NodeServices.layer)),);it.layer(@@ -2539,6 +2546,68 @@ it.layer(),);+ it.effect.each([+ {+ settings: { env: { ANTHROPIC_BASE_URL: "https://hub.example.ts.net:8317" } },+ baseUrl: "https://api.anthropic.com",+ type: "customEndpoint",+ label: "Custom API endpoint",+ },+ {+ settings: { env: { ANTHROPIC_BASE_URL: "https://api.anthropic.com" } },+ baseUrl: "https://proxy.example",+ type: "apiKey",+ label: "Claude API Key",+ },+ {+ settings: {},+ baseUrl: "https://proxy.example",+ type: "customEndpoint",+ label: "Custom API endpoint",+ },+ ])(+ "uses the settings endpoint before the process endpoint: $type / $baseUrl",+ ({ settings, baseUrl, type, label }) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const configDir = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-claude-settings-",+ });+ yield* fileSystem.writeFileString(+ path.join(configDir, "settings.json"),+ JSON.stringify(settings),+ );+ const stateDir = yield* fileSystem.makeTempDirectoryScoped();+ yield* fileSystem.makeDirectory(path.join(stateDir, ".claude"));+ yield* fileSystem.writeFileString(+ path.join(stateDir, ".claude", "settings.json"),+ JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://state-dir.example" } }),+ );+ const status = yield* checkClaudeProviderStatus(+ { ...defaultClaudeSettings, homePath: configDir },+ claudeCapabilities({+ tokenSource: "ANTHROPIC_AUTH_TOKEN",+ apiKeySource: "none",+ apiProvider: "firstParty",+ }),+ { ANTHROPIC_BASE_URL: baseUrl },+ stateDir,+ );+ assert.strictEqual(status.status, "ready");+ assert.strictEqual(status.auth.type, type);+ assert.strictEqual(status.auth.label, label);+ }).pipe(+ Effect.provide(+ layerMockSpawner((args) => {+ const joined = args.join(" ");+ if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };+ throw new Error(`Unexpected args: ${joined}`);+ }),+ ),+ ),+ );+it.effect.each(["https://api.anthropic.com","https://api.anthropic.com:443",