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

ClaudeProvider.ts

721 lines24.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 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 } 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 return "Max";
82 case "claudemax5xsubscription":
83 return "Max 5x";
84 case "claudemax20xsubscription":
85 return "Max 20x";
86 case "claudeenterprisesubscription":
87 return "Enterprise";
88 case "claudeteamsubscription":
89 return "Team";
90 case "claudeprosubscription":
91 return "Pro";
92 case "claudefreesubscription":
93 return "Free";
94 case "max":
95 case "maxplan":
96 return "Max";
97 case "max5":
98 return "Max 5x";
99 case "max20":
100 return "Max 20x";
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 /** Undefined means get_usage failed; absent windows on success mean no subscription windows, as with API keys. */
247 readonly usage?: Pick<SDKControlGetUsageResponse, "rate_limits_available" | "rate_limits">;
248 readonly usageCheckedAt?: string;
249};
250​
251function parseClaudeInitializationCommands(
252 commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
253): ReadonlyArray<ServerProviderSlashCommand> {
254 return dedupeSlashCommands(
255 (commands ?? []).flatMap((command) => {
256 const name = nonEmptyProbeString(command.name);
257 if (!name) {
258 return [];
259 }
260​
261 const description = nonEmptyProbeString(command.description);
262 const argumentHint = nonEmptyProbeString(command.argumentHint);
263​
264 return [
265 {
266 name,
267 ...(description ? { description } : {}),
268 ...(argumentHint ? { input: { hint: argumentHint } } : {}),
269 } satisfies ServerProviderSlashCommand,
270 ];
271 }),
272 );
274​
275function dedupeSlashCommands(
276 commands: ReadonlyArray<ServerProviderSlashCommand>,
277): ReadonlyArray<ServerProviderSlashCommand> {
278 const commandsByName = new Map<string, ServerProviderSlashCommand>();
279​
280 for (const command of commands) {
281 const name = nonEmptyProbeString(command.name);
282 if (!name) {
283 continue;
284 }
285​
286 const key = name.toLowerCase();
287 const existing = commandsByName.get(key);
288 if (!existing) {
289 commandsByName.set(key, {
290 ...command,
291 name,
292 });
293 continue;
294 }
295​
296 commandsByName.set(key, {
297 ...existing,
298 ...(existing.description
299 ? {}
300 : command.description
301 ? { description: command.description }
302 : {}),
303 ...(existing.input?.hint
304 ? {}
305 : command.input?.hint
306 ? { input: { hint: command.input.hint } }
307 : {}),
308 });
309 }
310​
311 return [...commandsByName.values()];
313​
314function waitForAbortSignal(signal: AbortSignal): Promise<void> {
315 if (signal.aborted) {
316 return Promise.resolve();
317 }
318 return new Promise((resolve) => {
319 signal.addEventListener("abort", () => resolve(), { once: true });
320 });
322​
323/** A never-yielding prompt allows local initialization IPC without sending an Anthropic request. */
324const probeClaudeCapabilities = (
325 claudeSettings: ClaudeSettings,
326 environment?: NodeJS.ProcessEnv,
327 cwd?: string,
328 includeUsage = true,
329) => {
330 const abort = new AbortController();
331 return Effect.gen(function* () {
332 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
333 const executablePath = yield* resolveClaudeSdkExecutablePath(
334 claudeSettings.binaryPath,
335 claudeEnvironment,
336 );
337 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
338 return yield* Effect.tryPromise(async () => {
339 const q = claudeQuery({
340 // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API
341 prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
342 await waitForAbortSignal(abort.signal);
343 })(),
344 options: buildClaudeCapabilitiesProbeQueryOptions({
345 executablePath,
346 abortController: abort,
347 environment: claudeEnvironment,
348 cwd,
349 managedMcpConfig,
350 }),
351 });
352 const init = await q.initializationResult();
353 return { q, init };
354 });
355 }).pipe(
356 Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
357 Effect.flatMap(({ q, init }) =>
358 Effect.gen(function* () {
359 // Usage has its own deadline so a slow optional request cannot discard initialization.
360 // Only the rate limits are read, so skip the local transcript scan that fills
361 // `behaviors`: with a few GB of transcripts it outlasts the deadline.
362 const usageCheckedAt = DateTime.formatIso(yield* DateTime.now);
363 const usageResult = includeUsage
364 ? yield* Effect.tryPromise(() =>
365 q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true }),
366 ).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result)
367 : undefined;
368 const usage =
369 usageResult && Result.isSuccess(usageResult)
370 ? {
371 rate_limits_available: usageResult.success.rate_limits_available,
372 rate_limits: usageResult.success.rate_limits,
373 }
374 : undefined;
375 const account = init.account as
376 | {
377 readonly email?: string;
378 readonly subscriptionType?: string;
379 readonly tokenSource?: string;
380 readonly apiKeySource?: string;
381 readonly apiProvider?: string;
382 }
383 | undefined;
384 return {
385 email: account?.email,
386 subscriptionType: account?.subscriptionType,
387 tokenSource: account?.tokenSource,
388 apiKeySource: account?.apiKeySource,
389 apiProvider: account?.apiProvider,
390 slashCommands: parseClaudeInitializationCommands(init.commands),
391 ...(usage ? { usage, usageCheckedAt } : {}),
392 } satisfies ClaudeCapabilitiesProbe;
393 }),
394 ),
395 Effect.ensuring(
396 Effect.sync(() => {
397 if (!abort.signal.aborted) abort.abort();
398 }),
399 ),
400 Effect.tapError((error) =>
401 Effect.logWarning("Claude capability probe failed.", { errorTag: error._tag }),
402 ),
403 );
404};
405​
406type ClaudeCapabilitiesProbeError = Effect.Error<ReturnType<typeof probeClaudeCapabilities>>;
407​
408const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
409 claudeSettings: ClaudeSettings,
410 args: ReadonlyArray<string>,
411 environment?: NodeJS.ProcessEnv,
412 cwd?: string,
413) {
414 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
415 const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {
416 env: claudeEnvironment,
417 });
418 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
419 env: claudeEnvironment,
420 shell: spawnCommand.shell,
421 ...(cwd ? { cwd } : {}),
422 });
423 return yield* spawnAndCollect(claudeSettings.binaryPath, command);
424});
425​
426export const probeClaudeWorkspaceSnapshot = Effect.fn("probeClaudeWorkspaceSnapshot")(function* (
427 claudeSettings: ClaudeSettings,
428 machineSnapshot: ServerProvider,
429 cwd: string,
430 environment?: NodeJS.ProcessEnv,
431): Effect.fn.Return<ProviderWorkspaceSnapshot, never, FileSystem.FileSystem | Path.Path> {
432 if (!claudeSettings.enabled) return machineSnapshot;
433 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, environment);
434 const probeResult = yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false).pipe(
435 Effect.result,
436 );
437 const capabilities = Result.isSuccess(probeResult) ? probeResult.success : undefined;
438 return {
439 ...machineSnapshot,
440 skills,
441 slashCommands: dedupeSlashCommands([
442 COMPACT_SLASH_COMMAND,
443 ...(capabilities?.slashCommands ?? []),
444 ]),
445 slashCommandsPending: !capabilities,
446 };
447});
448​
449export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
450 claudeSettings: ClaudeSettings,
451 resolveCapabilities?: (
452 claudeSettings: ClaudeSettings,
453 ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined, ClaudeCapabilitiesProbeError>,
454 environment?: NodeJS.ProcessEnv,
455 cwd?: string,
456 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
457 /** Shared with the adapter so turn events reuse the scoped-bucket names this probe saw. */
458 scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>,
459 resolveResetCredits?: (version: string) => Effect.Effect<ServerProviderResetCredits | undefined>,
460): Effect.fn.Return<
461 ServerProviderDraft,
462 never,
463 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
464> {
465 const resolvedEnvironment = environment ?? process.env;
466 const checkedAt = DateTime.formatIso(yield* DateTime.now);
467 const allModels = providerModelsFromSettings(
468 modelCatalog.models.map((entry) => entry.model),
469 claudeSettings.customModels,
470 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
471 );
472​
473 if (!claudeSettings.enabled) {
474 return buildServerProvider({
475 presentation: CLAUDE_PRESENTATION,
476 enabled: false,
477 checkedAt,
478 models: allModels,
479 probe: {
480 installed: false,
481 version: null,
482 status: "warning",
483 auth: { status: "unknown" },
484 message: "Claude is disabled in T3 Code settings.",
485 },
486 });
487 }
488​
489 const versionProbe = yield* runClaudeCommand(
490 claudeSettings,
491 ["--version"],
492 resolvedEnvironment,
493 cwd,
494 ).pipe(Effect.timeoutOption(CLAUDE_VERSION_CHECK_TIMEOUT_MS), Effect.result);
495​
496 if (Result.isFailure(versionProbe)) {
497 const error = versionProbe.failure;
498 yield* Effect.logWarning("Claude Agent CLI health check failed.", {
499 errorTag: error._tag,
500 });
501 return buildServerProvider({
502 presentation: CLAUDE_PRESENTATION,
503 enabled: claudeSettings.enabled,
504 checkedAt,
505 models: allModels,
506 probe: {
507 installed: !isCommandMissingCause(error),
508 version: null,
509 status: "error",
510 auth: { status: "unknown" },
511 message: isCommandMissingCause(error)
512 ? "Claude Agent CLI (`claude`) was not found on PATH."
513 : "Failed to execute Claude Agent CLI health check.",
514 },
515 });
516 }
517​
518 if (Option.isNone(versionProbe.success)) {
519 return buildServerProvider({
520 presentation: CLAUDE_PRESENTATION,
521 enabled: claudeSettings.enabled,
522 checkedAt,
523 models: allModels,
524 probe: {
525 installed: true,
526 version: null,
527 status: "error",
528 auth: { status: "unknown" },
529 message:
530 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
531 },
532 });
533 }
534​
535 const version = versionProbe.success.value;
536 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
537 if (version.code !== 0) {
538 yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", {
539 exitCode: version.code,
540 stdoutLength: version.stdout.length,
541 stderrLength: version.stderr.length,
542 });
543 return buildServerProvider({
544 presentation: CLAUDE_PRESENTATION,
545 enabled: claudeSettings.enabled,
546 checkedAt,
547 models: allModels,
548 probe: {
549 installed: true,
550 version: parsedVersion,
551 status: "error",
552 auth: { status: "unknown" },
553 message: "Claude Agent CLI is installed but failed to run.",
554 },
555 });
556 }
557​
558 const models = providerModelsFromSettings(
559 resolveClaudeModelsForVersion(modelCatalog, parsedVersion),
560 claudeSettings.customModels,
561 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
562 );
563 const updateRequiredModels = resolveClaudeUpdateRequiredModels(modelCatalog, parsedVersion);
564 const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion);
565​
566 const probeResult = resolveCapabilities
567 ? yield* resolveCapabilities(claudeSettings).pipe(Effect.result)
568 : undefined;
569 const capabilities =
570 probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined;
571 const probeFailure =
572 probeResult && Result.isFailure(probeResult) ? probeResult.failure : undefined;
573 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
574 const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])];
575 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
576​
577 if (!capabilities) {
578 return buildServerProvider({
579 presentation: CLAUDE_PRESENTATION,
580 enabled: claudeSettings.enabled,
581 checkedAt,
582 models,
583 updateRequiredModels,
584 slashCommands: dedupedSlashCommands,
585 skills,
586 probe: {
587 installed: true,
588 version: parsedVersion,
589 status: "warning",
590 auth: { status: "unknown" },
591 message: probeFailure
592 ? Cause.isTimeoutError(probeFailure)
593 ? `Timed out after ${CAPABILITIES_PROBE_TIMEOUT_MS / 1_000}s while checking Claude account status.`
594 : "Claude Agent CLI failed while checking account status."
595 : "Could not verify Claude authentication status from initialization result.",
596 },
597 });
598 }
599​
600 // First-party account fields cannot verify custom endpoint credentials.
601 const endpoint = URL.parse(resolvedEnvironment.ANTHROPIC_BASE_URL?.trim() ?? "");
602 const customApiEndpoint =
603 endpoint !== null &&
604 (endpoint.protocol === "http:" || endpoint.protocol === "https:") &&
605 endpoint.hostname !== "" &&
606 endpoint.hostname !== "api.anthropic.com";
607 if (!customApiEndpoint && claudeAuthStatus(capabilities) === "unauthenticated") {
608 return buildServerProvider({
609 presentation: CLAUDE_PRESENTATION,
610 enabled: claudeSettings.enabled,
611 checkedAt,
612 models,
613 slashCommands: dedupedSlashCommands,
614 skills,
615 probe: {
616 installed: true,
617 version: parsedVersion,
618 status: "error",
619 auth: { status: "unauthenticated" },
620 message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
621 },
622 });
623 }
624​
625 const authMetadata =
626 claudeAuthMetadata({
627 subscriptionType: capabilities.subscriptionType,
628 authMethod: capabilities.tokenSource,
629 }) ??
630 apiProviderAuthMetadata(capabilities.apiProvider) ??
631 (customApiEndpoint ? { type: "customEndpoint", label: "Custom API endpoint" } : undefined);
632 const usageCheckedAt = capabilities.usageCheckedAt ?? checkedAt;
633 const usageLimits = !capabilities.usage
634 ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" })
635 : scopedLimitNames
636 ? yield* recordClaudeUsageResponse(scopedLimitNames, {
637 response: capabilities.usage,
638 checkedAt: usageCheckedAt,
639 })
640 : claudeUsageResponseToLimits({
641 response: capabilities.usage,
642 checkedAt: usageCheckedAt,
643 }).limits;
644 const resetCredits =
645 resolveResetCredits &&
646 capabilities.subscriptionType &&
647 !usageLimits.unavailable &&
648 parsedVersion
649 ? yield* resolveResetCredits(parsedVersion)
650 : undefined;
651 return buildServerProvider({
652 presentation: CLAUDE_PRESENTATION,
653 enabled: claudeSettings.enabled,
654 checkedAt,
655 models,
656 updateRequiredModels,
657 slashCommands: dedupedSlashCommands,
658 skills,
659 probe: {
660 installed: true,
661 version: parsedVersion,
662 status: "ready",
663 auth: {
664 status: "authenticated",
665 ...(capabilities.email ? { email: capabilities.email } : {}),
666 ...(capabilities.workspaceId ? { workspaceId: capabilities.workspaceId } : {}),
667 ...(authMetadata ? authMetadata : {}),
668 },
669 ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
670 usageLimits: resetCredits ? { ...usageLimits, resetCredits } : usageLimits,
671 },
672 });
673});
674​
675const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
676​
677export const makePendingClaudeProvider = Effect.fn("ClaudeProvider.makePendingClaudeProvider")(
678 function* (
679 claudeSettings: ClaudeSettings,
680 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
681 ): Effect.fn.Return<ServerProviderDraft> {
682 const checkedAt = yield* nowIso;
683 const models = providerModelsFromSettings(
684 modelCatalog.models.map((entry) => entry.model),
685 claudeSettings.customModels,
686 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
687 );
688​
689 if (!claudeSettings.enabled) {
690 return buildServerProvider({
691 presentation: CLAUDE_PRESENTATION,
692 enabled: false,
693 checkedAt,
694 models,
695 probe: {
696 installed: false,
697 version: null,
698 status: "warning",
699 auth: { status: "unknown" },
700 message: "Claude is disabled in T3 Code settings.",
701 },
702 });
703 }
704​
705 return buildServerProvider({
706 presentation: CLAUDE_PRESENTATION,
707 enabled: true,
708 checkedAt,
709 models,
710 probe: {
711 installed: false,
712 version: null,
713 status: "warning",
714 auth: { status: "unknown" },
715 message: "Claude provider status has not been checked in this session yet.",
716 },
717 });
718 },
719);
720​
721export { probeClaudeCapabilities };