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

ClaudeProvider.ts

800 lines27.3 KB

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