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

ClaudeProvider.ts

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