Open History to see the last commit
1import {
2 type ModelCapabilities,
3 type OpenCodeSettings,
4 type ServerProviderModel,
5 type ServerProviderSkill,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import * as Data from "effect/Data";
9import * as DateTime from "effect/DateTime";
10import * as Effect from "effect/Effect";
11
12import { createModelCapabilities } from "@t3tools/shared/model";
13import { compareSemverVersions } from "@t3tools/shared/semver";
14import {
15 sanitizeTerminalValue,
16 stripTerminalEscapes,
17} from "@t3tools/shared/stripTerminalEscapes";
18import {
19 buildServerProvider,
20 nonEmptyTrimmed,
21 parseGenericCliVersion,
22 providerModelsFromSettings,
23 type ServerProviderDraft,
24} from "../providerSnapshot.ts";
25import {
26 OpenCodeRuntime,
27 openCodeRuntimeErrorDetail,
28 type OpenCodeInventory,
29} from "../opencodeRuntime.ts";
30import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
31
32const OPENCODE_PRESENTATION = {
33 displayName: "OpenCode",
34 showInteractionModeToggle: false,
35} as const;
36const MINIMUM_OPENCODE_VERSION = "1.14.19";
37
38class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
39 readonly cause: unknown;
40 readonly detail: string;
41}> {}
42
43function normalizeProbeMessage(message: string): string | undefined {
44 const trimmed = message.trim();
45 if (trimmed.length === 0) {
46 return undefined;
47 }
48 if (
49 trimmed === "An error occurred in Effect.tryPromise" ||
50 trimmed === "An error occurred in Effect.try"
51 ) {
52 return undefined;
53 }
54 return trimmed;
55}
56
57function normalizedErrorMessage(cause: unknown): string | undefined {
58 if (cause instanceof OpenCodeProbeError) {
59 return normalizeProbeMessage(cause.detail);
60 }
61
62 if (!(cause instanceof Error)) {
63 return undefined;
64 }
65
66 return normalizeProbeMessage(cause.message);
67}
68
69function formatOpenCodeProbeError(input: {
70 readonly cause: unknown;
71 readonly isExternalServer: boolean;
72 readonly serverUrl: string;
73}): { readonly installed: boolean; readonly message: string } {
74 const detail = normalizedErrorMessage(input.cause);
75 const lower = detail?.toLowerCase() ?? "";
76
77 if (input.isExternalServer) {
78 if (
79 lower.includes("401") ||
80 lower.includes("403") ||
81 lower.includes("unauthorized") ||
82 lower.includes("forbidden")
83 ) {
84 return {
85 installed: true,
86 message: "OpenCode server rejected authentication. Check the server URL and password.",
87 };
88 }
89
90 if (
91 lower.includes("econnrefused") ||
92 lower.includes("enotfound") ||
93 lower.includes("fetch failed") ||
94 lower.includes("networkerror") ||
95 lower.includes("timed out") ||
96 lower.includes("timeout") ||
97 lower.includes("socket hang up")
98 ) {
99 return {
100 installed: true,
101 message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
102 };
103 }
104
105 return {
106 installed: true,
107 message: detail ?? "Failed to connect to the configured OpenCode server.",
108 };
109 }
110
111 if (lower.includes("enoent") || lower.includes("notfound")) {
112 return {
113 installed: false,
114 message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
115 };
116 }
117
118 if (lower.includes("quarantine")) {
119 return {
120 installed: true,
121 message:
122 "macOS is blocking the OpenCode binary (quarantine). Run `xattr -d com.apple.quarantine $(which opencode)` to fix this.",
123 };
124 }
125
126 if (lower.includes("invalid code signature") || lower.includes("corrupted")) {
127 return {
128 installed: true,
129 message:
130 "macOS killed the OpenCode process due to an invalid code signature. The binary may be corrupted — try reinstalling OpenCode.",
131 };
132 }
133
134 return {
135 installed: true,
136 message: detail
137 ? `Failed to execute OpenCode CLI health check: ${detail}`
138 : "Failed to execute OpenCode CLI health check.",
139 };
140}
141
142function titleCaseSlug(value: string): string {
143 const segments: Array<string> = [];
144 for (const segment of value.split(/[-_/]+/)) {
145 if (segment.length > 0) {
146 segments.push(segment.charAt(0).toUpperCase() + segment.slice(1));
147 }
148 }
149 return segments.join(" ");
150}
151
152function inferDefaultVariant(
153 providerID: string,
154 variants: ReadonlyArray<string>,
155): string | undefined {
156 if (variants.length === 1) {
157 return variants[0];
158 }
159 if (providerID === "anthropic" || providerID.startsWith("google")) {
160 return variants.includes("high") ? "high" : undefined;
161 }
162 if (providerID === "openai" || providerID === "opencode") {
163 return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
164 }
165 return undefined;
166}
167
168function inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {
169 return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined;
170}
171
172const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
173 optionDescriptors: [],
174});
175
176function openCodeCapabilitiesForModel(input: {
177 readonly providerID: string;
178 readonly model: ProviderListResponse["all"][number]["models"][string];
179 readonly agents: ReadonlyArray<Agent>;
180}): ModelCapabilities {
181 const variantValues = Object.keys(input.model.variants ?? {}).map(sanitizeTerminalValue);
182 const defaultVariant = inferDefaultVariant(input.providerID, variantValues);
183 const variantOptions = variantValues.map((value) =>
184 defaultVariant === value
185 ? { id: value, label: titleCaseSlug(value), isDefault: true as const }
186 : { id: value, label: titleCaseSlug(value) },
187 );
188 const sanitizedAgents = input.agents.map((agent) => ({
189 ...agent,
190 name: sanitizeTerminalValue(agent.name),
191 }));
192 const primaryAgents = sanitizedAgents.filter(
193 (agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"),
194 );
195 const defaultAgent = inferDefaultAgent(primaryAgents);
196 const agentOptions = primaryAgents.map((agent) =>
197 defaultAgent === agent.name
198 ? { id: agent.name, label: titleCaseSlug(agent.name), isDefault: true as const }
199 : { id: agent.name, label: titleCaseSlug(agent.name) },
200 );
201 return createModelCapabilities({
202 optionDescriptors: [
203 ...(variantOptions.length > 0
204 ? [
205 {
206 id: "variant",
207 label: "Variant",
208 type: "select" as const,
209 options: variantOptions,
210 ...(defaultVariant ? { currentValue: defaultVariant } : {}),
211 },
212 ]
213 : []),
214 ...(agentOptions.length > 0
215 ? [
216 {
217 id: "agent",
218 label: "Agent",
219 type: "select" as const,
220 options: agentOptions,
221 ...(defaultAgent ? { currentValue: defaultAgent } : {}),
222 },
223 ]
224 : []),
225 ],
226 });
227}
228
229function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {
230 const connected = new Set(input.providerList.connected);
231 const models: Array<ServerProviderModel> = [];
232
233 for (const provider of input.providerList.all) {
234 if (!connected.has(provider.id)) {
235 continue;
236 }
237
238 for (const model of Object.values(provider.models)) {
239 const name = nonEmptyTrimmed(model.name);
240 if (!name) {
241 continue;
242 }
243
244 const subProvider = nonEmptyTrimmed(provider.name);
245 models.push({
246 slug: `${provider.id}/${model.id}`,
247 name,
248 ...(subProvider ? { subProvider } : {}),
249 isCustom: false,
250 capabilities: openCodeCapabilitiesForModel({
251 providerID: provider.id,
252 model,
253 agents: input.agents,
254 }),
255 });
256 }
257 }
258
259 return models.toSorted((left, right) => left.name.localeCompare(right.name));
260}
261
262function trimOptional(value: string | null | undefined): string | undefined {
263 const trimmed = value?.trim();
264 return trimmed && trimmed.length > 0 ? trimmed : undefined;
265}
266
267function flattenOpenCodeSkills(input: OpenCodeInventory): ReadonlyArray<ServerProviderSkill> {
268 const skills: ServerProviderSkill[] = [];
269 for (const skill of input.skills ?? []) {
270 const name = trimOptional(skill.name);
271 const path = trimOptional(skill.location);
272 if (!name || !path) {
273 continue;
274 }
275
276 const description = trimOptional(skill.description);
277 skills.push({
278 name,
279 path,
280 enabled: true,
281 ...(description ? { description, shortDescription: description } : {}),
282 });
283 }
284
285 return skills.toSorted((left, right) => left.name.localeCompare(right.name));
286}
287
288export const makePendingOpenCodeProvider = (
289 openCodeSettings: OpenCodeSettings,
290): Effect.Effect<ServerProviderDraft> =>
291 Effect.gen(function* () {
292 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
293 const models = providerModelsFromSettings(
294 [],
295 openCodeSettings.customModels,
296 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
297 );
298
299 if (!openCodeSettings.enabled) {
300 return buildServerProvider({
301 presentation: OPENCODE_PRESENTATION,
302 enabled: false,
303 checkedAt,
304 models,
305 probe: {
306 installed: false,
307 version: null,
308 status: "warning",
309 auth: { status: "unknown" },
310 message:
311 openCodeSettings.serverUrl.trim().length > 0
312 ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
313 : "OpenCode is disabled in T3 Code settings.",
314 },
315 });
316 }
317
318 return buildServerProvider({
319 presentation: OPENCODE_PRESENTATION,
320 enabled: true,
321 checkedAt,
322 models,
323 probe: {
324 installed: false,
325 version: null,
326 status: "warning",
327 auth: { status: "unknown" },
328 message: "OpenCode provider status has not been checked in this session yet.",
329 },
330 });
331 });
332
333export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
334 openCodeSettings: OpenCodeSettings,
335 cwd: string,
336 environment?: NodeJS.ProcessEnv,
337): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {
338 const openCodeRuntime = yield* OpenCodeRuntime;
339 const resolvedEnvironment = environment ?? process.env;
340 const checkedAt = DateTime.formatIso(yield* DateTime.now);
341 const customModels = openCodeSettings.customModels;
342 const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
343
344 const fallback = (cause: unknown, version: string | null = null) => {
345 const failure = formatOpenCodeProbeError({
346 cause,
347 isExternalServer,
348 serverUrl: openCodeSettings.serverUrl,
349 });
350 return buildServerProvider({
351 presentation: OPENCODE_PRESENTATION,
352 enabled: openCodeSettings.enabled,
353 checkedAt,
354 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
355 probe: {
356 installed: failure.installed,
357 version,
358 status: "error",
359 auth: { status: "unknown" },
360 message: failure.message,
361 },
362 });
363 };
364
365 if (!openCodeSettings.enabled) {
366 return buildServerProvider({
367 presentation: OPENCODE_PRESENTATION,
368 enabled: false,
369 checkedAt,
370 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
371 probe: {
372 installed: false,
373 version: null,
374 status: "warning",
375 auth: { status: "unknown" },
376 message: isExternalServer
377 ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
378 : "OpenCode is disabled in T3 Code settings.",
379 },
380 });
381 }
382
383 let version: string | null = null;
384 if (!isExternalServer) {
385 const versionExit = yield* Effect.exit(
386 openCodeRuntime
387 .runOpenCodeCommand({
388 binaryPath: openCodeSettings.binaryPath,
389 args: ["--version"],
390 environment: resolvedEnvironment,
391 })
392 .pipe(
393 Effect.mapError(
394 (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
395 ),
396 ),
397 );
398 if (versionExit._tag === "Failure") {
399 return fallback(Cause.squash(versionExit.cause));
400 }
401 version = parseGenericCliVersion(stripTerminalEscapes(versionExit.value.stdout)) ?? null;
402
403 if (!version) {
404 return fallback(
405 new Error(
406 `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
407 ),
408 null,
409 );
410 }
411 if (compareSemverVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
412 return buildServerProvider({
413 presentation: OPENCODE_PRESENTATION,
414 enabled: openCodeSettings.enabled,
415 checkedAt,
416 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
417 probe: {
418 installed: true,
419 version,
420 status: "error",
421 auth: { status: "unknown" },
422 message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
423 },
424 });
425 }
426 }
427
428 const inventoryExit = yield* Effect.exit(
429 (isExternalServer
430 ? Effect.scoped(
431 Effect.gen(function* () {
432 const server = yield* openCodeRuntime.connectToOpenCodeServer({
433 binaryPath: openCodeSettings.binaryPath,
434 serverUrl: openCodeSettings.serverUrl,
435 environment: resolvedEnvironment,
436 });
437 return yield* openCodeRuntime.loadOpenCodeInventory(
438 openCodeRuntime.createOpenCodeSdkClient({
439 baseUrl: server.url,
440 directory: cwd,
441 ...(openCodeSettings.serverPassword
442 ? { serverPassword: openCodeSettings.serverPassword }
443 : {}),
444 }),
445 );
446 }),
447 )
448 : openCodeRuntime.loadInventoryFromCli({
449 binaryPath: openCodeSettings.binaryPath,
450 cwd,
451 environment: resolvedEnvironment,
452 })
453 ).pipe(
454 Effect.mapError(
455 (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
456 ),
457 ),
458 );
459 if (inventoryExit._tag === "Failure") {
460 return fallback(Cause.squash(inventoryExit.cause), version);
461 }
462
463 const models = providerModelsFromSettings(
464 flattenOpenCodeModels(inventoryExit.value),
465 customModels,
466 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
467 );
468 const skills = flattenOpenCodeSkills(inventoryExit.value);
469 const connectedCount = inventoryExit.value.providerList.connected.length;
470 return buildServerProvider({
471 presentation: OPENCODE_PRESENTATION,
472 enabled: true,
473 checkedAt,
474 models,
475 skills,
476 probe: {
477 installed: true,
478 version,
479 status: connectedCount > 0 ? "ready" : "warning",
480 auth: {
481 status: connectedCount > 0 ? "authenticated" : "unknown",
482 type: "opencode",
483 },
484 message:
485 connectedCount > 0
486 ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
487 : isExternalServer
488 ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
489 : "OpenCode is available, but it did not report any connected upstream providers.",
490 },
491 });
492});