Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeProvider.ts

761 lines26.1 KB

1import {
2 type ClaudeSettings,
3 type ModelCapabilities,
4 type ServerProvider,
5 type ServerProviderSlashCommand,
6 type ServerProviderResetCredits,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as DateTime from "effect/DateTime";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Ref from "effect/Ref";
15import * as Result from "effect/Result";
16import { ChildProcess, ChildProcessSpawner } from "effect/process";
17import { createModelCapabilities } from "@t3tools/shared/model";
18import { resolveSpawnCommand } from "@t3tools/shared/shell";
19import {
20 query as claudeQuery,
21 type ModelInfo as ClaudeModelInfo,
22 type Options as ClaudeQueryOptions,
23 type SlashCommand as ClaudeSlashCommand,
24 type SDKControlGetUsageResponse,
25 type SDKUserMessage,
26 type SettingSource,
27} from "@anthropic-ai/claude-agent-sdk";
28​
29import {
30 buildServerProvider,
31 COMPACT_SLASH_COMMAND,
32 DEFAULT_TIMEOUT_MS,
33 isCommandMissingCause,
34 parseGenericCliVersion,
35 providerModelsFromSettings,
36 spawnAndCollect,
37 type ServerProviderDraft,
38} from "@t3tools/provider-core/server/snapshotProbe";
39import { resolveClaudeSdkExecutablePath } from "./Drivers/ClaudeExecutable.ts";
40import { hasClaudeManagedMcpConfig, makeClaudeEnvironment } from "./Drivers/ClaudeHome.ts";
41import { discoverClaudeSkills, readClaudeSettingsEnv } from "./Drivers/ClaudeSkills.ts";
42import type { ProviderWorkspaceSnapshot } from "@t3tools/provider-core/server/driver";
43import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
44import {
45 type ClaudeScopedLimitNames,
46 claudeUsageResponseToLimits,
47 recordClaudeUsageResponse,
48} from "./claudeUsageLimits.ts";
49import {
50 BUNDLED_CLAUDE_MODEL_CATALOG,
51 type ClaudeModelCatalog,
52 claudeReportedModels,
53 formatClaudeVersionUpgradeMessage,
54 resolveClaudeModelsForVersion,
55 resolveClaudeUpdateRequiredModels,
56} from "./ClaudeModelCatalog.ts";
57​
58const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
59 optionDescriptors: [],
60});
61​
62const CLAUDE_PRESENTATION = {
63 displayName: "Claude",
64 showInteractionModeToggle: true,
65 reportsContextWindow: true,
66} as const;
67function toTitleCaseWords(value: string): string {
68 const parts: Array<string> = [];
69 for (const part of value.split(/[\s_-]+/g)) {
70 if (part.length > 0) {
71 parts.push(part[0]!.toUpperCase() + part.slice(1).toLowerCase());
72 }
73 }
74 return parts.join(" ");
76​
77function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
78 const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
79 if (!normalized) return undefined;
80​
81 switch (normalized) {
82 case "claudemaxsubscription":
83 case "claudemax5xsubscription":
84 return "Max";
85 case "claudemax20xsubscription":
86 return "Ultra";
87 case "claudeenterprisesubscription":
88 return "Enterprise";
89 case "claudeteamsubscription":
90 return "Team";
91 case "claudeprosubscription":
92 return "Pro";
93 case "claudefreesubscription":
94 return "Free";
95 case "max":
96 case "maxplan":
97 case "max5":
98 return "Max";
99 case "max20":
100 return "Ultra";
101 case "enterprise":
102 return "Enterprise";
103 case "team":
104 return "Team";
105 case "pro":
106 return "Pro";
107 case "free":
108 return "Free";
109 default:
110 return toTitleCaseWords(subscriptionType!);
111 }
113​
114function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
115 const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
116 if (!normalized) return undefined;
117 if (
118 normalized === "apikey" ||
119 normalized === "anthropicapikey" ||
120 normalized === "anthropicauthtoken"
121 ) {
122 return "apiKey";
123 }
124 return undefined;
126​
127function formatClaudeSubscriptionAuthLabel(subscriptionType: string): string {
128 const subscriptionLabel =
129 claudeSubscriptionLabel(subscriptionType) ?? toTitleCaseWords(subscriptionType);
130 const normalized = subscriptionLabel.toLowerCase().replace(/[\s_-]+/g, "");
131​
132 if (normalized.startsWith("claude") && normalized.endsWith("subscription")) {
133 return subscriptionLabel;
134 }
135 if (normalized.startsWith("claude")) {
136 return `${subscriptionLabel} Subscription`;
137 }
138 if (normalized.endsWith("subscription")) {
139 return `Claude ${subscriptionLabel}`;
140 }
141 return `Claude ${subscriptionLabel} Subscription`;
143​
144function claudeAuthMetadata(input: {
145 readonly subscriptionType: string | undefined;
146 readonly authMethod: string | undefined;
147}): { readonly type: string; readonly label: string } | undefined {
148 if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
149 return {
150 type: "apiKey",
151 label: "Claude API Key",
152 };
153 }
154​
155 if (input.subscriptionType) {
156 return {
157 type: input.subscriptionType,
158 label: formatClaudeSubscriptionAuthLabel(input.subscriptionType),
159 };
160 }
161​
162 return undefined;
164​
165function apiProviderAuthMetadata(
166 apiProvider: string | undefined,
167): { readonly type: string; readonly label: string } | undefined {
168 return apiProvider === "bedrock" ? { type: "bedrock", label: "Amazon Bedrock" } : undefined;
170​
171/** Probe completion only proves Claude started. Only tokenSource: "none" disproves auth. */
172function claudeAuthStatus(
173 capabilities: Pick<
174 ClaudeCapabilitiesProbe,
175 "email" | "subscriptionType" | "tokenSource" | "apiKeySource" | "apiProvider"
176 >,
177): "authenticated" | "unauthenticated" {
178 if (capabilities.apiProvider !== undefined && capabilities.apiProvider !== "firstParty") {
179 return "authenticated";
180 }
181 if (capabilities.tokenSource !== "none") return "authenticated";
182 // API keys can authenticate with tokenSource: none; also check key and account fields.
183 const hasApiKey = Boolean(capabilities.apiKeySource) && capabilities.apiKeySource !== "none";
184 return hasApiKey || capabilities.email || capabilities.subscriptionType
185 ? "authenticated"
186 : "unauthenticated";
188​
189// Bedrock initialization includes backend startup and awsAuthRefresh, taking longer than first-party auth.
190const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000;
191// Native CLI startup on Windows can exceed the shared probe deadline.
192const CLAUDE_VERSION_CHECK_TIMEOUT_MS = 20_000;
193​
194const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [
195 "user",
196 "project",
197 "local",
198] as const satisfies ReadonlyArray<SettingSource>;
199​
200export function buildClaudeCapabilitiesProbeQueryOptions(input: {
201 readonly executablePath: string;
202 readonly abortController: AbortController;
203 readonly environment: NodeJS.ProcessEnv;
204 readonly cwd: string | undefined;
205 readonly managedMcpConfig: boolean;
206}): ClaudeQueryOptions {
207 return {
208 persistSession: false,
209 pathToClaudeCodeExecutable: input.executablePath,
210 abortController: input.abortController,
211 settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES],
212 // Keep settings for slash-command discovery, but disable hooks so health checks do not run SessionStart repeatedly.
213 settings: { disableAllHooks: true },
214 allowedTools: [],
215 // Exclude filesystem MCP servers; omit strict mode when managed-mcp.json already excludes them and forbids the flag.
216 mcpServers: {},
217 ...(input.managedMcpConfig ? {} : { strictMcpConfig: true }),
218 env: {
219 ...input.environment,
220 // Disable claude.ai MCP separately; it is discovered outside filesystem config.
221 ENABLE_CLAUDEAI_MCP_SERVERS: "false",
222 // Skipping this avoids a Windows tasklist | findstr process tree on every refresh.
223 FORCE_CODE_TERMINAL: undefined,
224 CLAUDE_CODE_AUTO_CONNECT_IDE: "0",
225 CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL: "1",
226 },
227 ...(input.cwd ? { cwd: input.cwd } : {}),
228 stderr: () => {},
229 };
231​
232function nonEmptyProbeString(value: string): string | undefined {
233 const candidate = value.trim();
234 return candidate ? candidate : undefined;
236​
237export type ClaudeCapabilitiesProbe = {
238 readonly email: string | undefined;
239 readonly workspaceId?: string | undefined;
240 readonly subscriptionType: string | undefined;
241 readonly tokenSource: string | undefined;
242 readonly apiKeySource: string | undefined;
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;
250};
251​
252function parseClaudeInitializationCommands(
253 commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
254): ReadonlyArray<ServerProviderSlashCommand> {
255 return dedupeSlashCommands(
256 (commands ?? []).flatMap((command) => {
257 const name = nonEmptyProbeString(command.name);
258 if (!name) {
259 return [];
260 }
261​
262 const description = nonEmptyProbeString(command.description);
263 const argumentHint = nonEmptyProbeString(command.argumentHint);
264​
265 return [
266 {
267 name,
268 ...(description ? { description } : {}),
269 ...(argumentHint ? { input: { hint: argumentHint } } : {}),
270 } satisfies ServerProviderSlashCommand,
271 ];
272 }),
273 );
275​
276function dedupeSlashCommands(
277 commands: ReadonlyArray<ServerProviderSlashCommand>,
278): ReadonlyArray<ServerProviderSlashCommand> {
279 const commandsByName = new Map<string, ServerProviderSlashCommand>();
280​
281 for (const command of commands) {
282 const name = nonEmptyProbeString(command.name);
283 if (!name) {
284 continue;
285 }
286​
287 const key = name.toLowerCase();
288 const existing = commandsByName.get(key);
289 if (!existing) {
290 commandsByName.set(key, {
291 ...command,
292 name,
293 });
294 continue;
295 }
296​
297 commandsByName.set(key, {
298 ...existing,
299 ...(existing.description
300 ? {}
301 : command.description
302 ? { description: command.description }
303 : {}),
304 ...(existing.input?.hint
305 ? {}
306 : command.input?.hint
307 ? { input: { hint: command.input.hint } }
308 : {}),
309 });
310 }
311​
312 return [...commandsByName.values()];
314​
315function waitForAbortSignal(signal: AbortSignal): Promise<void> {
316 if (signal.aborted) {
317 return Promise.resolve();
318 }
319 return new Promise((resolve) => {
320 signal.addEventListener("abort", () => resolve(), { once: true });
321 });
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 */
328function 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;
337​
338/** A never-yielding prompt allows local initialization IPC without sending an Anthropic request. */
339const probeClaudeCapabilities = (
340 claudeSettings: ClaudeSettings,
341 environment?: NodeJS.ProcessEnv,
342 cwd?: string,
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(
352 claudeSettings.binaryPath,
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
366 prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
367 await waitForAbortSignal(abort.signal);
368 })(),
369 options: buildClaudeCapabilitiesProbeQueryOptions({
370 executablePath,
371 abortController: abort,
372 environment: claudeEnvironment,
373 cwd,
374 managedMcpConfig,
375 }),
376 });
377 const init = await q.initializationResult();
378 return { q, init, graceMs };
379 });
380 }).pipe(
381 Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
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 // `behaviors`: with a few GB of transcripts it outlasts the deadline.
387 const usageCheckedAt = DateTime.formatIso(yield* DateTime.now);
388 const usageResult = includeUsage
389 ? yield* Effect.tryPromise(() =>
390 q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true }),
391 ).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result)
392 : undefined;
393 const usage =
394 usageResult && Result.isSuccess(usageResult)
395 ? {
396 rate_limits_available: usageResult.success.rate_limits_available,
397 rate_limits: usageResult.success.rate_limits,
398 }
399 : undefined;
400 const account = init.account as
401 | {
402 readonly email?: string;
403 readonly subscriptionType?: string;
404 readonly tokenSource?: string;
405 readonly apiKeySource?: string;
406 readonly apiProvider?: string;
407 }
408 | undefined;
409 return {
410 email: account?.email,
411 subscriptionType: account?.subscriptionType,
412 tokenSource: account?.tokenSource,
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;
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 ),
431 );
432};
433​
434type ClaudeCapabilitiesProbeError = Effect.Error<ReturnType<typeof probeClaudeCapabilities>>;
435​
436const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
437 claudeSettings: ClaudeSettings,
438 args: ReadonlyArray<string>,
439 environment?: NodeJS.ProcessEnv,
440 cwd?: string,
441) {
442 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
443 const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {
444 env: claudeEnvironment,
445 });
446 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
447 env: claudeEnvironment,
448 shell: spawnCommand.shell,
449 ...(cwd ? { cwd } : {}),
450 });
451 return yield* spawnAndCollect(claudeSettings.binaryPath, command);
452});
453​
454export const probeClaudeWorkspaceSnapshot = Effect.fn("probeClaudeWorkspaceSnapshot")(function* (
455 claudeSettings: ClaudeSettings,
456 machineSnapshot: ServerProvider,
457 cwd: string,
458 environment?: NodeJS.ProcessEnv,
459): Effect.fn.Return<ProviderWorkspaceSnapshot, never, FileSystem.FileSystem | Path.Path> {
460 if (!claudeSettings.enabled) return machineSnapshot;
461 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, environment);
462 const fileSystem = yield* FileSystem.FileSystem;
463 // A deleted worktree can never answer the probe. Pending would make clients rescan it forever.
464 const cwdExists = yield* fileSystem.exists(cwd).pipe(Effect.orElseSucceed(() => true));
465 const probeResult = cwdExists
466 ? yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false).pipe(Effect.result)
467 : undefined;
468 const capabilities =
469 probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined;
470 return {
471 ...machineSnapshot,
472 skills,
473 slashCommands: dedupeSlashCommands([
474 COMPACT_SLASH_COMMAND,
475 ...(capabilities?.slashCommands ?? []),
476 ]),
477 slashCommandsPending: cwdExists && !capabilities,
478 };
479});
480​
481export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
482 claudeSettings: ClaudeSettings,
483 resolveCapabilities?: (
484 claudeSettings: ClaudeSettings,
485 ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined, ClaudeCapabilitiesProbeError>,
486 environment?: NodeJS.ProcessEnv,
487 cwd?: string,
488 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
489 /** Shared with the adapter so turn events reuse the scoped-bucket names this probe saw. */
490 scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>,
491 resolveResetCredits?: (version: string) => Effect.Effect<ServerProviderResetCredits | undefined>,
492): Effect.fn.Return<
493 ServerProviderDraft,
494 never,
495 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
496> {
497 const resolvedEnvironment = environment ?? process.env;
498 const checkedAt = DateTime.formatIso(yield* DateTime.now);
499 const allModels = providerModelsFromSettings(
500 modelCatalog.models.map((entry) => entry.model),
501 claudeSettings.customModels,
502 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
503 );
504​
505 if (!claudeSettings.enabled) {
506 return buildServerProvider({
507 presentation: CLAUDE_PRESENTATION,
508 enabled: false,
509 checkedAt,
510 models: allModels,
511 probe: {
512 installed: false,
513 version: null,
514 status: "warning",
515 auth: { status: "unknown" },
516 message: "Claude is disabled in T3 Code settings.",
517 },
518 });
519 }
520​
521 const versionProbe = yield* runClaudeCommand(
522 claudeSettings,
523 ["--version"],
524 resolvedEnvironment,
525 cwd,
526 ).pipe(Effect.timeoutOption(CLAUDE_VERSION_CHECK_TIMEOUT_MS), Effect.result);
527​
528 if (Result.isFailure(versionProbe)) {
529 const error = versionProbe.failure;
530 yield* Effect.logWarning("Claude Agent CLI health check failed.", {
531 errorTag: error._tag,
532 });
533 return buildServerProvider({
534 presentation: CLAUDE_PRESENTATION,
535 enabled: claudeSettings.enabled,
536 checkedAt,
537 models: allModels,
538 probe: {
539 installed: !isCommandMissingCause(error),
540 version: null,
541 status: "error",
542 auth: { status: "unknown" },
543 message: isCommandMissingCause(error)
544 ? "Claude Agent CLI (`claude`) was not found on PATH."
545 : "Failed to execute Claude Agent CLI health check.",
546 },
547 });
548 }
549​
550 if (Option.isNone(versionProbe.success)) {
551 return buildServerProvider({
552 presentation: CLAUDE_PRESENTATION,
553 enabled: claudeSettings.enabled,
554 checkedAt,
555 models: allModels,
556 probe: {
557 installed: true,
558 version: null,
559 status: "error",
560 auth: { status: "unknown" },
561 message:
562 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
563 },
564 });
565 }
566​
567 const version = versionProbe.success.value;
568 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
569 if (version.code !== 0) {
570 yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", {
571 exitCode: version.code,
572 stdoutLength: version.stdout.length,
573 stderrLength: version.stderr.length,
574 });
575 return buildServerProvider({
576 presentation: CLAUDE_PRESENTATION,
577 enabled: claudeSettings.enabled,
578 checkedAt,
579 models: allModels,
580 probe: {
581 installed: true,
582 version: parsedVersion,
583 status: "error",
584 auth: { status: "unknown" },
585 message: "Claude Agent CLI is installed but failed to run.",
586 },
587 });
588 }
589​
590 const updateRequiredModels = resolveClaudeUpdateRequiredModels(modelCatalog, parsedVersion);
591 const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion);
592​
593 const probeResult = resolveCapabilities
594 ? yield* resolveCapabilities(claudeSettings).pipe(Effect.result)
595 : undefined;
596 const capabilities =
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);
611​
612 if (!capabilities) {
613 return buildServerProvider({
614 presentation: CLAUDE_PRESENTATION,
615 enabled: claudeSettings.enabled,
616 checkedAt,
617 models,
618 updateRequiredModels,
619 slashCommands: dedupedSlashCommands,
620 skills,
621 probe: {
622 installed: true,
623 version: parsedVersion,
624 status: "warning",
625 auth: { status: "unknown" },
626 message: probeFailure
627 ? Cause.isTimeoutError(probeFailure)
628 ? `Timed out after ${CAPABILITIES_PROBE_TIMEOUT_MS / 1_000}s while checking Claude account status.`
629 : "Claude Agent CLI failed while checking account status."
630 : "Could not verify Claude authentication status from initialization result.",
631 },
632 });
633 }
634​
635 // First-party account fields cannot verify custom endpoint credentials.
636 const baseUrl =
637 (yield* readClaudeSettingsEnv(claudeSettings, cwd, resolvedEnvironment)).ANTHROPIC_BASE_URL ??
638 resolvedEnvironment.ANTHROPIC_BASE_URL;
639 const endpoint = URL.parse(baseUrl?.trim() ?? "");
640 const customApiEndpoint =
641 endpoint !== null &&
642 (endpoint.protocol === "http:" || endpoint.protocol === "https:") &&
643 endpoint.hostname !== "" &&
644 endpoint.hostname !== "api.anthropic.com";
645 if (!customApiEndpoint && claudeAuthStatus(capabilities) === "unauthenticated") {
646 return buildServerProvider({
647 presentation: CLAUDE_PRESENTATION,
648 enabled: claudeSettings.enabled,
649 checkedAt,
650 models,
651 updateRequiredModels,
652 slashCommands: dedupedSlashCommands,
653 skills,
654 probe: {
655 installed: true,
656 version: parsedVersion,
657 status: "error",
658 auth: { status: "unauthenticated" },
659 message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
660 },
661 });
662 }
663​
664 // A proxy's ANTHROPIC_AUTH_TOKEN reads as an API key; the endpoint is what the token is for.
665 const authMetadata =
666 apiProviderAuthMetadata(capabilities.apiProvider) ??
667 (customApiEndpoint ? { type: "customEndpoint", label: "Custom API endpoint" } : undefined) ??
668 claudeAuthMetadata({
669 subscriptionType: capabilities.subscriptionType,
670 authMethod: capabilities.tokenSource,
671 });
672 const usageCheckedAt = capabilities.usageCheckedAt ?? checkedAt;
673 const usageLimits = !capabilities.usage
674 ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" })
675 : scopedLimitNames
676 ? yield* recordClaudeUsageResponse(scopedLimitNames, {
677 response: capabilities.usage,
678 checkedAt: usageCheckedAt,
679 })
680 : claudeUsageResponseToLimits({
681 response: capabilities.usage,
682 checkedAt: usageCheckedAt,
683 }).limits;
684 const resetCredits =
685 resolveResetCredits &&
686 capabilities.subscriptionType &&
687 !usageLimits.unavailable &&
688 parsedVersion
689 ? yield* resolveResetCredits(parsedVersion)
690 : undefined;
691 return buildServerProvider({
692 presentation: CLAUDE_PRESENTATION,
693 enabled: claudeSettings.enabled,
694 checkedAt,
695 models,
696 updateRequiredModels,
697 slashCommands: dedupedSlashCommands,
698 skills,
699 probe: {
700 installed: true,
701 version: parsedVersion,
702 status: "ready",
703 auth: {
704 status: "authenticated",
705 ...(capabilities.email ? { email: capabilities.email } : {}),
706 ...(capabilities.workspaceId ? { workspaceId: capabilities.workspaceId } : {}),
707 ...(authMetadata ? authMetadata : {}),
708 },
709 ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
710 usageLimits: resetCredits ? { ...usageLimits, resetCredits } : usageLimits,
711 },
712 });
713});
714​
715const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
716​
717export const makePendingClaudeProvider = Effect.fn("ClaudeProvider.makePendingClaudeProvider")(
718 function* (
719 claudeSettings: ClaudeSettings,
720 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
721 ): Effect.fn.Return<ServerProviderDraft> {
722 const checkedAt = yield* nowIso;
723 const models = providerModelsFromSettings(
724 modelCatalog.models.map((entry) => entry.model),
725 claudeSettings.customModels,
726 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
727 );
728​
729 if (!claudeSettings.enabled) {
730 return buildServerProvider({
731 presentation: CLAUDE_PRESENTATION,
732 enabled: false,
733 checkedAt,
734 models,
735 probe: {
736 installed: false,
737 version: null,
738 status: "warning",
739 auth: { status: "unknown" },
740 message: "Claude is disabled in T3 Code settings.",
741 },
742 });
743 }
744​
745 return buildServerProvider({
746 presentation: CLAUDE_PRESENTATION,
747 enabled: true,
748 checkedAt,
749 models,
750 probe: {
751 installed: false,
752 version: null,
753 status: "warning",
754 auth: { status: "unknown" },
755 message: "Claude provider status has not been checked in this session yet.",
756 },
757 });
758 },
759);
760​
761export { probeClaudeCapabilities };