Open History to see the last commit
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(" ");
73}
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 }
112}
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;
125}
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`;
142}
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;
163}
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;
169}
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";
187}
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 };
230}
231
232function nonEmptyProbeString(value: string): string | undefined {
233 const candidate = value.trim();
234 return candidate ? candidate : undefined;
235}
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 );
273}
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()];
312}
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 });
321}
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 fileSystem = yield* FileSystem.FileSystem;
435 // A deleted worktree can never answer the probe. Pending would make clients rescan it forever.
436 const cwdExists = yield* fileSystem.exists(cwd).pipe(Effect.orElseSucceed(() => true));
437 const probeResult = cwdExists
438 ? yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false).pipe(Effect.result)
439 : undefined;
440 const capabilities =
441 probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined;
442 return {
443 ...machineSnapshot,
444 skills,
445 slashCommands: dedupeSlashCommands([
446 COMPACT_SLASH_COMMAND,
447 ...(capabilities?.slashCommands ?? []),
448 ]),
449 slashCommandsPending: cwdExists && !capabilities,
450 };
451});
452
453export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
454 claudeSettings: ClaudeSettings,
455 resolveCapabilities?: (
456 claudeSettings: ClaudeSettings,
457 ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined, ClaudeCapabilitiesProbeError>,
458 environment?: NodeJS.ProcessEnv,
459 cwd?: string,
460 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
461 /** Shared with the adapter so turn events reuse the scoped-bucket names this probe saw. */
462 scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>,
463 resolveResetCredits?: (version: string) => Effect.Effect<ServerProviderResetCredits | undefined>,
464): Effect.fn.Return<
465 ServerProviderDraft,
466 never,
467 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
468> {
469 const resolvedEnvironment = environment ?? process.env;
470 const checkedAt = DateTime.formatIso(yield* DateTime.now);
471 const allModels = providerModelsFromSettings(
472 modelCatalog.models.map((entry) => entry.model),
473 claudeSettings.customModels,
474 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
475 );
476
477 if (!claudeSettings.enabled) {
478 return buildServerProvider({
479 presentation: CLAUDE_PRESENTATION,
480 enabled: false,
481 checkedAt,
482 models: allModels,
483 probe: {
484 installed: false,
485 version: null,
486 status: "warning",
487 auth: { status: "unknown" },
488 message: "Claude is disabled in T3 Code settings.",
489 },
490 });
491 }
492
493 const versionProbe = yield* runClaudeCommand(
494 claudeSettings,
495 ["--version"],
496 resolvedEnvironment,
497 cwd,
498 ).pipe(Effect.timeoutOption(CLAUDE_VERSION_CHECK_TIMEOUT_MS), Effect.result);
499
500 if (Result.isFailure(versionProbe)) {
501 const error = versionProbe.failure;
502 yield* Effect.logWarning("Claude Agent CLI health check failed.", {
503 errorTag: error._tag,
504 });
505 return buildServerProvider({
506 presentation: CLAUDE_PRESENTATION,
507 enabled: claudeSettings.enabled,
508 checkedAt,
509 models: allModels,
510 probe: {
511 installed: !isCommandMissingCause(error),
512 version: null,
513 status: "error",
514 auth: { status: "unknown" },
515 message: isCommandMissingCause(error)
516 ? "Claude Agent CLI (`claude`) was not found on PATH."
517 : "Failed to execute Claude Agent CLI health check.",
518 },
519 });
520 }
521
522 if (Option.isNone(versionProbe.success)) {
523 return buildServerProvider({
524 presentation: CLAUDE_PRESENTATION,
525 enabled: claudeSettings.enabled,
526 checkedAt,
527 models: allModels,
528 probe: {
529 installed: true,
530 version: null,
531 status: "error",
532 auth: { status: "unknown" },
533 message:
534 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
535 },
536 });
537 }
538
539 const version = versionProbe.success.value;
540 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
541 if (version.code !== 0) {
542 yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", {
543 exitCode: version.code,
544 stdoutLength: version.stdout.length,
545 stderrLength: version.stderr.length,
546 });
547 return buildServerProvider({
548 presentation: CLAUDE_PRESENTATION,
549 enabled: claudeSettings.enabled,
550 checkedAt,
551 models: allModels,
552 probe: {
553 installed: true,
554 version: parsedVersion,
555 status: "error",
556 auth: { status: "unknown" },
557 message: "Claude Agent CLI is installed but failed to run.",
558 },
559 });
560 }
561
562 const models = providerModelsFromSettings(
563 resolveClaudeModelsForVersion(modelCatalog, parsedVersion),
564 claudeSettings.customModels,
565 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
566 );
567 const updateRequiredModels = resolveClaudeUpdateRequiredModels(modelCatalog, parsedVersion);
568 const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion);
569
570 const probeResult = resolveCapabilities
571 ? yield* resolveCapabilities(claudeSettings).pipe(Effect.result)
572 : undefined;
573 const capabilities =
574 probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined;
575 const probeFailure =
576 probeResult && Result.isFailure(probeResult) ? probeResult.failure : undefined;
577 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
578 const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])];
579 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
580
581 if (!capabilities) {
582 return buildServerProvider({
583 presentation: CLAUDE_PRESENTATION,
584 enabled: claudeSettings.enabled,
585 checkedAt,
586 models,
587 updateRequiredModels,
588 slashCommands: dedupedSlashCommands,
589 skills,
590 probe: {
591 installed: true,
592 version: parsedVersion,
593 status: "warning",
594 auth: { status: "unknown" },
595 message: probeFailure
596 ? Cause.isTimeoutError(probeFailure)
597 ? `Timed out after ${CAPABILITIES_PROBE_TIMEOUT_MS / 1_000}s while checking Claude account status.`
598 : "Claude Agent CLI failed while checking account status."
599 : "Could not verify Claude authentication status from initialization result.",
600 },
601 });
602 }
603
604 // First-party account fields cannot verify custom endpoint credentials.
605 const endpoint = URL.parse(resolvedEnvironment.ANTHROPIC_BASE_URL?.trim() ?? "");
606 const customApiEndpoint =
607 endpoint !== null &&
608 (endpoint.protocol === "http:" || endpoint.protocol === "https:") &&
609 endpoint.hostname !== "" &&
610 endpoint.hostname !== "api.anthropic.com";
611 if (!customApiEndpoint && claudeAuthStatus(capabilities) === "unauthenticated") {
612 return buildServerProvider({
613 presentation: CLAUDE_PRESENTATION,
614 enabled: claudeSettings.enabled,
615 checkedAt,
616 models,
617 slashCommands: dedupedSlashCommands,
618 skills,
619 probe: {
620 installed: true,
621 version: parsedVersion,
622 status: "error",
623 auth: { status: "unauthenticated" },
624 message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
625 },
626 });
627 }
628
629 const authMetadata =
630 claudeAuthMetadata({
631 subscriptionType: capabilities.subscriptionType,
632 authMethod: capabilities.tokenSource,
633 }) ??
634 apiProviderAuthMetadata(capabilities.apiProvider) ??
635 (customApiEndpoint ? { type: "customEndpoint", label: "Custom API endpoint" } : undefined);
636 const usageCheckedAt = capabilities.usageCheckedAt ?? checkedAt;
637 const usageLimits = !capabilities.usage
638 ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" })
639 : scopedLimitNames
640 ? yield* recordClaudeUsageResponse(scopedLimitNames, {
641 response: capabilities.usage,
642 checkedAt: usageCheckedAt,
643 })
644 : claudeUsageResponseToLimits({
645 response: capabilities.usage,
646 checkedAt: usageCheckedAt,
647 }).limits;
648 const resetCredits =
649 resolveResetCredits &&
650 capabilities.subscriptionType &&
651 !usageLimits.unavailable &&
652 parsedVersion
653 ? yield* resolveResetCredits(parsedVersion)
654 : undefined;
655 return buildServerProvider({
656 presentation: CLAUDE_PRESENTATION,
657 enabled: claudeSettings.enabled,
658 checkedAt,
659 models,
660 updateRequiredModels,
661 slashCommands: dedupedSlashCommands,
662 skills,
663 probe: {
664 installed: true,
665 version: parsedVersion,
666 status: "ready",
667 auth: {
668 status: "authenticated",
669 ...(capabilities.email ? { email: capabilities.email } : {}),
670 ...(capabilities.workspaceId ? { workspaceId: capabilities.workspaceId } : {}),
671 ...(authMetadata ? authMetadata : {}),
672 },
673 ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
674 usageLimits: resetCredits ? { ...usageLimits, resetCredits } : usageLimits,
675 },
676 });
677});
678
679const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
680
681export const makePendingClaudeProvider = Effect.fn("ClaudeProvider.makePendingClaudeProvider")(
682 function* (
683 claudeSettings: ClaudeSettings,
684 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
685 ): Effect.fn.Return<ServerProviderDraft> {
686 const checkedAt = yield* nowIso;
687 const models = providerModelsFromSettings(
688 modelCatalog.models.map((entry) => entry.model),
689 claudeSettings.customModels,
690 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
691 );
692
693 if (!claudeSettings.enabled) {
694 return buildServerProvider({
695 presentation: CLAUDE_PRESENTATION,
696 enabled: false,
697 checkedAt,
698 models,
699 probe: {
700 installed: false,
701 version: null,
702 status: "warning",
703 auth: { status: "unknown" },
704 message: "Claude is disabled in T3 Code settings.",
705 },
706 });
707 }
708
709 return buildServerProvider({
710 presentation: CLAUDE_PRESENTATION,
711 enabled: true,
712 checkedAt,
713 models,
714 probe: {
715 installed: false,
716 version: null,
717 status: "warning",
718 auth: { status: "unknown" },
719 message: "Claude provider status has not been checked in this session yet.",
720 },
721 });
722 },
723);
724
725export { probeClaudeCapabilities };