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

ClaudeProvider.ts

791 lines27.2 KB

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