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