Open History to see the last commit
1import {
2 type ModelCapabilities,
3 type OpenCodeSettings,
4 type ServerProviderModel,
5 type ServerProviderSkill,
6 type ServerProviderSlashCommand,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as Data from "effect/Data";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12
13import { createModelCapabilities } from "@t3tools/shared/model";
14import { compareSemverVersions } from "@t3tools/shared/semver";
15import {
16 buildServerProvider,
17 COMPACT_SLASH_COMMAND,
18 nonEmptyTrimmed,
19 parseGenericCliVersion,
20 providerModelsFromSettings,
21 type ServerProviderDraft,
22} from "../providerSnapshot.ts";
23import {
24 MINIMUM_OPENCODE_VERSION,
25 OpenCodeRuntime,
26 openCodeRuntimeErrorDetail,
27 type OpenCodeInventory,
28} from "../opencodeRuntime.ts";
29import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
30import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
31
32const OPENCODE_PRESENTATION = {
33 displayName: "OpenCode",
34 showInteractionModeToggle: false,
35} as const;
36const OPENCODE_VERSION_PROBE_TIMEOUT = "4 seconds";
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 phase: "version" | "inventory";
73 readonly serverUrl: string;
74}): { readonly installed: boolean; readonly message: string } {
75 const detail = normalizedErrorMessage(input.cause);
76 const lower = detail?.toLowerCase() ?? "";
77
78 if (input.isExternalServer) {
79 if (
80 lower.includes("401") ||
81 lower.includes("403") ||
82 lower.includes("unauthorized") ||
83 lower.includes("forbidden")
84 ) {
85 return {
86 installed: true,
87 message: "OpenCode server rejected authentication. Check the server URL and password.",
88 };
89 }
90
91 if (
92 lower.includes("econnrefused") ||
93 lower.includes("enotfound") ||
94 lower.includes("fetch failed") ||
95 lower.includes("networkerror") ||
96 lower.includes("timed out") ||
97 lower.includes("timeout") ||
98 lower.includes("socket hang up")
99 ) {
100 return {
101 installed: true,
102 message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
103 };
104 }
105
106 return {
107 installed: true,
108 message: detail ?? "Failed to connect to the configured OpenCode server.",
109 };
110 }
111
112 if (lower.includes("enoent") || lower.includes("notfound")) {
113 return {
114 installed: false,
115 message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
116 };
117 }
118
119 if (lower.includes("quarantine")) {
120 return {
121 installed: true,
122 message:
123 "macOS is blocking the OpenCode binary (quarantine). Run `xattr -d com.apple.quarantine $(which opencode)` to fix this.",
124 };
125 }
126
127 if (lower.includes("invalid code signature") || lower.includes("corrupted")) {
128 return {
129 installed: true,
130 message:
131 "macOS killed the OpenCode process due to an invalid code signature. The binary may be corrupted — try reinstalling OpenCode.",
132 };
133 }
134
135 const failureLabel =
136 input.phase === "inventory"
137 ? "Failed to load OpenCode provider inventory"
138 : "Failed to execute OpenCode CLI health check";
139 return {
140 installed: true,
141 message: detail ? `${failureLabel}: ${detail}` : `${failureLabel}.`,
142 };
143}
144
145function titleCaseSlug(value: string): string {
146 const segments: Array<string> = [];
147 for (const segment of value.split(/[-_/]+/)) {
148 if (segment.length > 0) {
149 segments.push(segment.charAt(0).toUpperCase() + segment.slice(1));
150 }
151 }
152 return segments.join(" ");
153}
154
155function inferDefaultVariant(
156 providerID: string,
157 variants: ReadonlyArray<string>,
158): string | undefined {
159 if (variants.length === 1) {
160 return variants[0];
161 }
162 if (providerID === "anthropic" || providerID.startsWith("google")) {
163 return variants.includes("high") ? "high" : undefined;
164 }
165 if (providerID === "openai" || providerID === "opencode") {
166 return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
167 }
168 return undefined;
169}
170
171function inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {
172 return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined;
173}
174
175const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
176 optionDescriptors: [
177 {
178 id: "variant",
179 label: "Reasoning",
180 type: "select",
181 options: [
182 { id: "low", label: "Low" },
183 { id: "medium", label: "Medium", isDefault: true },
184 { id: "high", label: "High" },
185 { id: "xhigh", label: "Extra High" },
186 ],
187 currentValue: "medium",
188 },
189 {
190 id: "agent",
191 label: "Agent",
192 type: "select",
193 options: [
194 { id: "build", label: "Build", isDefault: true },
195 { id: "plan", label: "Plan" },
196 ],
197 currentValue: "build",
198 },
199 ],
200});
201
202function openCodeCapabilitiesForModel(input: {
203 readonly providerID: string;
204 readonly model: ProviderListResponse["all"][number]["models"][string];
205 readonly agents: ReadonlyArray<Agent>;
206}): ModelCapabilities {
207 const rawVariantValues = Object.keys(input.model.variants ?? {});
208 // When a model advertises no variants, synthesize the standard reasoning
209 // levels so the composer still offers a Reasoning selector (mirrors the
210 // Codex/Grok experience where reasoning is always configurable). The set
211 // covers the common OpenCode variant spectrum; `inferDefaultVariant`
212 // picks the provider-appropriate default (e.g. medium for openai/opencode).
213 const variantValues =
214 rawVariantValues.length > 0 ? rawVariantValues : ["low", "medium", "high", "xhigh"];
215 const defaultVariant = inferDefaultVariant(input.providerID, variantValues);
216 const variantOptions = variantValues.map((value) =>
217 defaultVariant === value
218 ? { id: value, label: titleCaseSlug(value), isDefault: true as const }
219 : { id: value, label: titleCaseSlug(value) },
220 );
221 const primaryAgents = input.agents.filter(
222 (agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"),
223 );
224 const defaultAgent = inferDefaultAgent(primaryAgents);
225 const agentOptions = primaryAgents.map((agent) =>
226 defaultAgent === agent.name
227 ? { id: agent.name, label: titleCaseSlug(agent.name), isDefault: true as const }
228 : { id: agent.name, label: titleCaseSlug(agent.name) },
229 );
230 return createModelCapabilities({
231 optionDescriptors: [
232 ...(variantOptions.length > 0
233 ? [
234 {
235 id: "variant",
236 label: "Reasoning",
237 type: "select" as const,
238 options: variantOptions,
239 ...(defaultVariant ? { currentValue: defaultVariant } : {}),
240 },
241 ]
242 : []),
243 ...(agentOptions.length > 0
244 ? [
245 {
246 id: "agent",
247 label: "Agent",
248 type: "select" as const,
249 options: agentOptions,
250 ...(defaultAgent ? { currentValue: defaultAgent } : {}),
251 },
252 ]
253 : []),
254 ],
255 });
256}
257
258function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {
259 const connected = new Set(input.providerList.connected);
260 const models: Array<ServerProviderModel> = [];
261
262 for (const provider of input.providerList.all) {
263 if (!connected.has(provider.id)) {
264 continue;
265 }
266
267 for (const model of Object.values(provider.models)) {
268 const name = nonEmptyTrimmed(model.name);
269 if (!name) {
270 continue;
271 }
272
273 const subProvider = nonEmptyTrimmed(provider.name);
274 models.push({
275 slug: `${provider.id}/${model.id}`,
276 name,
277 ...(subProvider ? { subProvider } : {}),
278 isCustom: false,
279 capabilities: openCodeCapabilitiesForModel({
280 providerID: provider.id,
281 model,
282 agents: input.agents,
283 }),
284 });
285 }
286 }
287
288 return models.toSorted((left, right) => left.name.localeCompare(right.name));
289}
290
291function trimOptional(value: string | null | undefined): string | undefined {
292 const trimmed = value?.trim();
293 return trimmed && trimmed.length > 0 ? trimmed : undefined;
294}
295
296export function openCodeSkillsToServerProviderSkills(
297 input: OpenCodeInventory["skills"] | undefined,
298): ReadonlyArray<ServerProviderSkill> {
299 const skills: ServerProviderSkill[] = [];
300 for (const skill of input ?? []) {
301 const name = trimOptional(skill.name);
302 const path = trimOptional(skill.location);
303 if (!name || !path) {
304 continue;
305 }
306
307 const description = trimOptional(skill.description);
308 skills.push({
309 name,
310 path,
311 enabled: true,
312 ...(description ? { description, shortDescription: description } : {}),
313 });
314 }
315
316 return skills.toSorted((left, right) => left.name.localeCompare(right.name));
317}
318
319export function openCodeCommandsToServerProviderSlashCommands(
320 input: OpenCodeInventory["commands"],
321): ReadonlyArray<ServerProviderSlashCommand> {
322 const commands: ServerProviderSlashCommand[] = [COMPACT_SLASH_COMMAND];
323 const names = new Set([COMPACT_SLASH_COMMAND.name]);
324 for (const command of input ?? []) {
325 const name = trimOptional(command.name);
326 if (!name || names.has(name) || command.source === "skill") continue;
327 names.add(name);
328 const description = trimOptional(command.description);
329 const hint = trimOptional(command.hints.join(" "));
330 commands.push({
331 name,
332 ...(description ? { description } : {}),
333 ...(hint ? { input: { hint } } : {}),
334 });
335 }
336 return commands;
337}
338
339export const makePendingOpenCodeProvider = (
340 openCodeSettings: OpenCodeSettings,
341): Effect.Effect<ServerProviderDraft> =>
342 Effect.gen(function* () {
343 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
344 const models = providerModelsFromSettings(
345 [],
346 openCodeSettings.customModels,
347 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
348 );
349
350 if (!openCodeSettings.enabled) {
351 return buildServerProvider({
352 presentation: OPENCODE_PRESENTATION,
353 enabled: false,
354 checkedAt,
355 models,
356 probe: {
357 installed: false,
358 version: null,
359 status: "warning",
360 auth: { status: "unknown" },
361 message:
362 openCodeSettings.serverUrl.trim().length > 0
363 ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
364 : "OpenCode is disabled in T3 Code settings.",
365 },
366 });
367 }
368
369 return buildServerProvider({
370 presentation: OPENCODE_PRESENTATION,
371 enabled: true,
372 checkedAt,
373 models,
374 probe: {
375 installed: false,
376 version: null,
377 status: "warning",
378 auth: { status: "unknown" },
379 message: "OpenCode provider status has not been checked in this session yet.",
380 },
381 });
382 });
383
384export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
385 openCodeSettings: OpenCodeSettings,
386 cwd: string,
387 environment?: NodeJS.ProcessEnv,
388): Effect.fn.Return<
389 ServerProviderDraft,
390 never,
391 OpenCodeRuntime | OpenCodeServerOwner.OpenCodeServerOwner
392> {
393 const openCodeRuntime = yield* OpenCodeRuntime;
394 const serverOwner = yield* OpenCodeServerOwner.OpenCodeServerOwner;
395 const resolvedEnvironment = environment ?? process.env;
396 const checkedAt = DateTime.formatIso(yield* DateTime.now);
397 const customModels = openCodeSettings.customModels;
398 const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
399
400 const fallback = (
401 cause: unknown,
402 version: string | null = null,
403 phase: "version" | "inventory" = "version",
404 ) => {
405 const failure = formatOpenCodeProbeError({
406 cause,
407 isExternalServer,
408 phase,
409 serverUrl: openCodeSettings.serverUrl,
410 });
411 return buildServerProvider({
412 presentation: OPENCODE_PRESENTATION,
413 enabled: openCodeSettings.enabled,
414 checkedAt,
415 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
416 probe: {
417 installed: failure.installed,
418 version,
419 status: "error",
420 auth: { status: "unknown" },
421 message: failure.message,
422 },
423 });
424 };
425
426 if (!openCodeSettings.enabled) {
427 return buildServerProvider({
428 presentation: OPENCODE_PRESENTATION,
429 enabled: false,
430 checkedAt,
431 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
432 probe: {
433 installed: false,
434 version: null,
435 status: "warning",
436 auth: { status: "unknown" },
437 message: isExternalServer
438 ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
439 : "OpenCode is disabled in T3 Code settings.",
440 },
441 });
442 }
443
444 let version: string | null = null;
445 if (!isExternalServer) {
446 const versionExit = yield* Effect.exit(
447 openCodeRuntime
448 .runOpenCodeCommand({
449 binaryPath: openCodeSettings.binaryPath,
450 args: ["--version"],
451 environment: resolvedEnvironment,
452 })
453 .pipe(
454 Effect.mapError(
455 (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
456 ),
457 Effect.timeoutOrElse({
458 duration: OPENCODE_VERSION_PROBE_TIMEOUT,
459 orElse: () =>
460 Effect.fail(
461 new OpenCodeProbeError({
462 detail: `OpenCode CLI version probe timed out after ${OPENCODE_VERSION_PROBE_TIMEOUT}.`,
463 }),
464 ),
465 }),
466 ),
467 );
468 if (versionExit._tag === "Failure") {
469 return fallback(Cause.squash(versionExit.cause));
470 }
471 version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
472
473 if (!version) {
474 return fallback(
475 new Error(
476 `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
477 ),
478 null,
479 );
480 }
481 if (compareSemverVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
482 return buildServerProvider({
483 presentation: OPENCODE_PRESENTATION,
484 enabled: openCodeSettings.enabled,
485 checkedAt,
486 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
487 probe: {
488 installed: true,
489 version,
490 status: "error",
491 auth: { status: "unknown" },
492 message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
493 },
494 });
495 }
496 }
497
498 const loadInventory = (server: {
499 readonly url: string;
500 readonly serverPassword?: string;
501 readonly version: string;
502 }) =>
503 openCodeRuntime
504 .loadOpenCodeInventory(
505 openCodeRuntime.createOpenCodeSdkClient({
506 baseUrl: server.url,
507 directory: cwd,
508 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
509 }),
510 )
511 .pipe(Effect.map((inventory) => ({ inventory, version: server.version })));
512 const inventoryEffect = isExternalServer
513 ? openCodeRuntime
514 .connectToOpenCodeServer({
515 binaryPath: openCodeSettings.binaryPath,
516 directory: cwd,
517 serverUrl: openCodeSettings.serverUrl,
518 ...(openCodeSettings.serverPassword
519 ? { serverPassword: openCodeSettings.serverPassword }
520 : {}),
521 })
522 .pipe(Effect.flatMap(loadInventory), Effect.scoped)
523 : serverOwner.withServer(loadInventory);
524 const inventoryExit = yield* Effect.exit(
525 inventoryEffect.pipe(
526 Effect.mapError(
527 (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
528 ),
529 ),
530 );
531 if (inventoryExit._tag === "Failure") {
532 return fallback(Cause.squash(inventoryExit.cause), version, "inventory");
533 }
534
535 version = inventoryExit.value.version;
536
537 const models = providerModelsFromSettings(
538 flattenOpenCodeModels(inventoryExit.value.inventory),
539 customModels,
540 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
541 );
542 const skills = openCodeSkillsToServerProviderSkills(inventoryExit.value.inventory.skills);
543 const connectedCount = inventoryExit.value.inventory.providerList.connected.length;
544 return buildServerProvider({
545 presentation: OPENCODE_PRESENTATION,
546 enabled: true,
547 checkedAt,
548 models,
549 skills,
550 slashCommands: openCodeCommandsToServerProviderSlashCommands(
551 inventoryExit.value.inventory.commands,
552 ),
553 probe: {
554 installed: true,
555 version,
556 status: connectedCount > 0 ? "ready" : "warning",
557 auth: {
558 status: connectedCount > 0 ? "authenticated" : "unknown",
559 type: "opencode",
560 },
561 message:
562 connectedCount > 0
563 ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
564 : isExternalServer
565 ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
566 : "OpenCode is available, but it did not report any connected upstream providers.",
567 },
568 });
569});