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

OpenCodeProvider.ts

677 lines21.5 KB

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";
12import * as Schedule from "effect/Schedule";
13​
14import { createModelCapabilities } from "@t3tools/shared/model";
15import { compareSemverVersions } from "@t3tools/shared/semver";
16import {
17 buildServerProvider,
18 COMPACT_SLASH_COMMAND,
19 nonEmptyTrimmed,
20 providerModelsFromSettings,
21 type ServerProviderDraft,
22} from "../providerSnapshot.ts";
23import * as OpenCodeRuntime from "../opencodeRuntime.ts";
24import type { ProbedOpenCode } from "../opencodeVersionProbe.ts";
25import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
26import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
27​
28const OPENCODE_PRESENTATION = {
29 displayName: "OpenCode",
30 showInteractionModeToggle: false,
31} as const;
32​
33class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
34 readonly cause?: unknown;
35 readonly detail: string;
36}> {}
37​
38function normalizeProbeMessage(message: string): string | undefined {
39 const trimmed = message.trim();
40 if (trimmed.length === 0) {
41 return undefined;
42 }
43 if (
44 trimmed === "An error occurred in Effect.tryPromise" ||
45 trimmed === "An error occurred in Effect.try"
46 ) {
47 return undefined;
48 }
49 return trimmed;
51​
52function normalizedErrorMessage(cause: unknown): string | undefined {
53 if (cause instanceof OpenCodeProbeError) {
54 return normalizeProbeMessage(cause.detail);
55 }
56​
57 if (!(cause instanceof Error)) {
58 return undefined;
59 }
60​
61 return normalizeProbeMessage(cause.message);
63​
64function formatOpenCodeProbeError(input: {
65 readonly cause: unknown;
66 readonly isExternalServer: boolean;
67 readonly phase: "version" | "inventory";
68 readonly serverUrl: string;
69}): { readonly installed: boolean; readonly message: string } {
70 const detail = normalizedErrorMessage(input.cause);
71 const lower = detail?.toLowerCase() ?? "";
72​
73 if (input.isExternalServer) {
74 if (
75 lower.includes("401") ||
76 lower.includes("403") ||
77 lower.includes("unauthorized") ||
78 lower.includes("forbidden")
79 ) {
80 return {
81 installed: true,
82 message: "OpenCode server rejected authentication. Check the server URL and password.",
83 };
84 }
85​
86 if (
87 lower.includes("econnrefused") ||
88 lower.includes("enotfound") ||
89 lower.includes("fetch failed") ||
90 lower.includes("networkerror") ||
91 lower.includes("timed out") ||
92 lower.includes("timeout") ||
93 lower.includes("socket hang up")
94 ) {
95 return {
96 installed: true,
97 message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
98 };
99 }
100​
101 return {
102 installed: true,
103 message: detail ?? "Failed to connect to the configured OpenCode server.",
104 };
105 }
106​
107 if (lower.includes("enoent") || lower.includes("notfound")) {
108 return {
109 installed: false,
110 message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
111 };
112 }
113​
114 if (lower.includes("quarantine")) {
115 return {
116 installed: true,
117 message:
118 "macOS is blocking the OpenCode binary (quarantine). Run `xattr -d com.apple.quarantine $(which opencode)` to fix this.",
119 };
120 }
121​
122 if (lower.includes("invalid code signature") || lower.includes("corrupted")) {
123 return {
124 installed: true,
125 message:
126 "macOS killed the OpenCode process due to an invalid code signature. The binary may be corrupted — try reinstalling OpenCode.",
127 };
128 }
129​
130 const failureLabel =
131 input.phase === "inventory"
132 ? "Failed to load OpenCode provider inventory"
133 : "Failed to execute OpenCode CLI health check";
134 return {
135 installed: true,
136 message: detail ? `${failureLabel}: ${detail}` : `${failureLabel}.`,
137 };
139​
140function titleCaseSlug(value: string): string {
141 const segments: Array<string> = [];
142 for (const segment of value.split(/[-_/]+/)) {
143 if (segment.length > 0) {
144 segments.push(segment.charAt(0).toUpperCase() + segment.slice(1));
145 }
146 }
147 return segments.join(" ");
149​
150function inferDefaultVariant(
151 providerID: string,
152 variants: ReadonlyArray<string>,
153): string | undefined {
154 if (variants.length === 1) {
155 return variants[0];
156 }
157 if (providerID === "anthropic" || providerID.startsWith("google")) {
158 return variants.includes("high") ? "high" : undefined;
159 }
160 if (providerID === "openai" || providerID === "opencode") {
161 return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
162 }
163 return undefined;
165​
166function inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {
167 return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined;
169​
170const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
171 optionDescriptors: [
172 {
173 id: "variant",
174 label: "Reasoning",
175 type: "select",
176 options: [
177 { id: "low", label: "Low" },
178 { id: "medium", label: "Medium", isDefault: true },
179 { id: "high", label: "High" },
180 { id: "xhigh", label: "Extra High" },
181 ],
182 currentValue: "medium",
183 },
184 {
185 id: "agent",
186 label: "Agent",
187 type: "select",
188 options: [
189 { id: "build", label: "Build", isDefault: true },
190 { id: "plan", label: "Plan" },
191 ],
192 currentValue: "build",
193 },
194 ],
195});
196​
197function openCodeCapabilitiesForModel(input: {
198 readonly providerID: string;
199 readonly model: ProviderListResponse["all"][number]["models"][string];
200 readonly agents: ReadonlyArray<Agent>;
201}): ModelCapabilities {
202 const rawVariantValues = Object.keys(input.model.variants ?? {});
203 // When a model advertises no variants, synthesize the standard reasoning
204 // levels so the composer still offers a Reasoning selector (mirrors the
205 // Codex/Grok experience where reasoning is always configurable). The set
206 // covers the common OpenCode variant spectrum; `inferDefaultVariant`
207 // picks the provider-appropriate default (e.g. medium for openai/opencode).
208 const variantValues =
209 rawVariantValues.length > 0 ? rawVariantValues : ["low", "medium", "high", "xhigh"];
210 const defaultVariant = inferDefaultVariant(input.providerID, variantValues);
211 const variantOptions = variantValues.map((value) =>
212 defaultVariant === value
213 ? { id: value, label: titleCaseSlug(value), isDefault: true as const }
214 : { id: value, label: titleCaseSlug(value) },
215 );
216 const primaryAgents = input.agents.filter(
217 (agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"),
218 );
219 const defaultAgent = inferDefaultAgent(primaryAgents);
220 const agentOptions = primaryAgents.map((agent) =>
221 defaultAgent === agent.name
222 ? { id: agent.name, label: titleCaseSlug(agent.name), isDefault: true as const }
223 : { id: agent.name, label: titleCaseSlug(agent.name) },
224 );
225 return createModelCapabilities({
226 optionDescriptors: [
227 ...(variantOptions.length > 0
228 ? [
229 {
230 id: "variant",
231 label: "Reasoning",
232 type: "select" as const,
233 options: variantOptions,
234 ...(defaultVariant ? { currentValue: defaultVariant } : {}),
235 },
236 ]
237 : []),
238 ...(agentOptions.length > 0
239 ? [
240 {
241 id: "agent",
242 label: "Agent",
243 type: "select" as const,
244 options: agentOptions,
245 ...(defaultAgent ? { currentValue: defaultAgent } : {}),
246 },
247 ]
248 : []),
249 ],
250 });
252​
253function flattenOpenCodeModels(
254 input: OpenCodeRuntime.OpenCodeInventory,
255): ReadonlyArray<ServerProviderModel> {
256 const connected = new Set(input.providerList.connected);
257 const models: Array<ServerProviderModel> = [];
258​
259 for (const provider of input.providerList.all) {
260 if (!connected.has(provider.id)) {
261 continue;
262 }
263​
264 for (const model of Object.values(provider.models)) {
265 const name = nonEmptyTrimmed(model.name);
266 if (!name) {
267 continue;
268 }
269​
270 const subProvider = nonEmptyTrimmed(provider.name);
271 models.push({
272 slug: `${provider.id}/${model.id}`,
273 name,
274 ...(subProvider ? { subProvider } : {}),
275 isCustom: false,
276 capabilities: openCodeCapabilitiesForModel({
277 providerID: provider.id,
278 model,
279 agents: input.agents,
280 }),
281 });
282 }
283 }
284​
285 return models.toSorted((left, right) => left.name.localeCompare(right.name));
287​
288function trimOptional(value: string | null | undefined): string | undefined {
289 const trimmed = value?.trim();
290 return trimmed && trimmed.length > 0 ? trimmed : undefined;
292​
293export function openCodeSkillsToServerProviderSkills(
294 input: OpenCodeRuntime.OpenCodeInventory["skills"] | undefined,
295): ReadonlyArray<ServerProviderSkill> {
296 const skills: ServerProviderSkill[] = [];
297 for (const skill of input ?? []) {
298 const name = trimOptional(skill.name);
299 const path = trimOptional(skill.location);
300 if (!name || !path) {
301 continue;
302 }
303​
304 const description = trimOptional(skill.description);
305 skills.push({
306 name,
307 path,
308 enabled: true,
309 ...(description ? { description, shortDescription: description } : {}),
310 });
311 }
312​
313 return skills.toSorted((left, right) => left.name.localeCompare(right.name));
315​
316export function openCodeCommandsToServerProviderSlashCommands(
317 input: OpenCodeRuntime.OpenCodeInventory["commands"],
318): ReadonlyArray<ServerProviderSlashCommand> {
319 const commands: ServerProviderSlashCommand[] = [COMPACT_SLASH_COMMAND];
320 const names = new Set([COMPACT_SLASH_COMMAND.name]);
321 for (const command of input ?? []) {
322 const name = trimOptional(command.name);
323 if (!name || names.has(name) || command.source === "skill") continue;
324 names.add(name);
325 const description = trimOptional(command.description);
326 const hint = trimOptional(command.hints.join(" "));
327 commands.push({
328 name,
329 ...(description ? { description } : {}),
330 ...(hint ? { input: { hint } } : {}),
331 });
332 }
333 return commands;
335​
336export const makePendingOpenCodeProvider = (
337 openCodeSettings: OpenCodeSettings,
338): Effect.Effect<ServerProviderDraft> =>
339 Effect.gen(function* () {
340 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
341 const models = providerModelsFromSettings(
342 [],
343 openCodeSettings.customModels,
344 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
345 );
346​
347 if (!openCodeSettings.enabled) {
348 return buildServerProvider({
349 presentation: OPENCODE_PRESENTATION,
350 enabled: false,
351 checkedAt,
352 models,
353 probe: {
354 installed: false,
355 version: null,
356 status: "warning",
357 auth: { status: "unknown" },
358 message:
359 openCodeSettings.serverUrl.trim().length > 0
360 ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
361 : "OpenCode is disabled in T3 Code settings.",
362 },
363 });
364 }
365​
366 return buildServerProvider({
367 presentation: OPENCODE_PRESENTATION,
368 enabled: true,
369 checkedAt,
370 models,
371 probe: {
372 installed: false,
373 version: null,
374 status: "warning",
375 auth: { status: "unknown" },
376 message: "OpenCode provider status has not been checked in this session yet.",
377 },
378 });
379 });
380​
381/** One model an OpenCode 2 server lists, as the status check reads it. */
382export interface OpenCode2Model {
383 readonly providerID: string;
384 readonly id: string;
385 readonly name: string;
386 readonly variants: ReadonlyArray<{ readonly id: string }>;
388​
389/**
390 * A server loads its catalog lazily and lists nothing for its first few
391 * hundred milliseconds, and a local instance starts a fresh server for each
392 * status check. So an empty list is read again for a while, and the last
393 * non-empty list stands in if the catalog still has not loaded.
394 */
395export const makeOpenCode2ModelLoader = <E>(
396 list: Effect.Effect<ReadonlyArray<OpenCode2Model>, E>,
397) =>
398 Effect.sync(() => {
399 let lastLoaded: ReadonlyArray<OpenCode2Model> = [];
400 return list.pipe(
401 Effect.repeat({
402 until: (models) => models.length > 0,
403 schedule: Schedule.spaced("250 millis"),
404 }),
405 Effect.timeoutOption("5 seconds"),
406 Effect.map((loaded) => {
407 if (loaded._tag === "Some" && loaded.value.length > 0) lastLoaded = loaded.value;
408 return lastLoaded;
409 }),
410 );
411 });
412​
413/**
414 * Every mode maps onto OpenCode 2 session rules. Auto asks like Supervised:
415 * OpenCode has no reviewer that approves routine actions.
416 */
417const OPENCODE_2_PRESENTATION = {
418 ...OPENCODE_PRESENTATION,
419 supportedRuntimeModes: ["approval-required", "auto-accept-edits", "auto", "full-access"],
420} as const;
421​
422function openCode2ModelCapabilities(model: OpenCode2Model): ModelCapabilities {
423 const variants = model.variants.map((variant) => variant.id);
424 const defaultVariant = inferDefaultVariant(model.providerID, variants);
425 return createModelCapabilities({
426 optionDescriptors:
427 variants.length === 0
428 ? []
429 : [
430 {
431 id: "variant",
432 label: "Reasoning",
433 type: "select",
434 options: variants.map((id) => ({
435 id,
436 label: titleCaseSlug(id),
437 ...(id === defaultVariant ? { isDefault: true } : {}),
438 })),
439 ...(defaultVariant === undefined ? {} : { currentValue: defaultVariant }),
440 },
441 ],
442 });
444​
445const checkOpenCode2 = Effect.fn("checkOpenCode2")(function* (
446 settings: OpenCodeSettings,
447 version: string,
448 checkedAt: string,
449 loadModels: Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError>,
450) {
451 const result = yield* Effect.exit(loadModels);
452 const probe = (status: "ready" | "warning" | "error", message: string) => ({
453 installed: true,
454 version,
455 status,
456 auth: { status: status === "ready" ? ("authenticated" as const) : ("unknown" as const) },
457 message,
458 });
459 if (result._tag === "Failure") {
460 // The detail can carry a response body; it stays in the log, not the status.
461 yield* Effect.logWarning("OpenCode 2 model list failed", result.cause);
462 return buildServerProvider({
463 presentation: OPENCODE_2_PRESENTATION,
464 enabled: true,
465 checkedAt,
466 models: providerModelsFromSettings(
467 [],
468 settings.customModels,
469 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
470 ),
471 probe: probe("error", "OpenCode could not load its model list."),
472 });
473 }
474 const models = providerModelsFromSettings(
475 result.value
476 .map((model) => ({
477 slug: `${model.providerID}/${model.id}`,
478 name: model.name,
479 isCustom: false,
480 capabilities: openCode2ModelCapabilities(model),
481 }))
482 .toSorted((left, right) => left.name.localeCompare(right.name)),
483 settings.customModels,
484 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
485 );
486 return buildServerProvider({
487 presentation: OPENCODE_2_PRESENTATION,
488 enabled: true,
489 checkedAt,
490 models,
491 probe:
492 result.value.length > 0
493 ? probe(
494 "ready",
495 `OpenCode ${version} lists ${result.value.length} model${result.value.length === 1 ? "" : "s"}.`,
496 )
497 : probe("warning", "OpenCode 2 is running, but it did not list any models yet."),
498 });
499});
500​
501/**
502 * `probeRuntime` is the driver's memoized version probe: `opencode --version` for a local binary,
503 * the version endpoints for a configured server. The status check refreshes it, so an in-place
504 * upgrade re-routes the instance.
505 */
506export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
507 openCodeSettings: OpenCodeSettings,
508 cwd: string,
509 probeRuntime: Effect.Effect<ProbedOpenCode, OpenCodeRuntime.OpenCodeRuntimeError>,
510 loadOpenCode2Models: Effect.Effect<
511 ReadonlyArray<OpenCode2Model>,
512 OpenCodeRuntime.OpenCodeRuntimeError
513 >,
514): Effect.fn.Return<
515 ServerProviderDraft,
516 never,
517 OpenCodeRuntime.OpenCodeRuntime | OpenCodeServerOwner.OpenCodeServerOwner
518> {
519 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
520 const serverOwner = yield* OpenCodeServerOwner.OpenCodeServerOwner;
521 const checkedAt = DateTime.formatIso(yield* DateTime.now);
522 const customModels = openCodeSettings.customModels;
523 const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
524​
525 const fallback = (
526 cause: unknown,
527 version: string | null = null,
528 phase: "version" | "inventory" = "version",
529 ) => {
530 const failure = formatOpenCodeProbeError({
531 cause,
532 isExternalServer,
533 phase,
534 serverUrl: openCodeSettings.serverUrl,
535 });
536 return buildServerProvider({
537 presentation: OPENCODE_PRESENTATION,
538 enabled: openCodeSettings.enabled,
539 checkedAt,
540 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
541 probe: {
542 installed: failure.installed,
543 version,
544 status: "error",
545 auth: { status: "unknown" },
546 message: failure.message,
547 },
548 });
549 };
550​
551 if (!openCodeSettings.enabled) {
552 return buildServerProvider({
553 presentation: OPENCODE_PRESENTATION,
554 enabled: false,
555 checkedAt,
556 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
557 probe: {
558 installed: false,
559 version: null,
560 status: "warning",
561 auth: { status: "unknown" },
562 message: isExternalServer
563 ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
564 : "OpenCode is disabled in T3 Code settings.",
565 },
566 });
567 }
568​
569 const probedExit = yield* Effect.exit(
570 probeRuntime.pipe(
571 Effect.mapError(
572 (cause) =>
573 new OpenCodeProbeError({
574 cause,
575 detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
576 }),
577 ),
578 ),
579 );
580 if (probedExit._tag === "Failure") return fallback(Cause.squash(probedExit.cause));
581 const probed = probedExit.value;
582 if (probed.generation === "v2") {
583 return yield* checkOpenCode2(openCodeSettings, probed.version, checkedAt, loadOpenCode2Models);
584 }
585 let version: string | null = probed.version;
586 if (compareSemverVersions(probed.version, OpenCodeRuntime.MINIMUM_OPENCODE_VERSION) < 0) {
587 return buildServerProvider({
588 presentation: OPENCODE_PRESENTATION,
589 enabled: openCodeSettings.enabled,
590 checkedAt,
591 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
592 probe: {
593 installed: true,
594 version: probed.version,
595 status: "error",
596 auth: { status: "unknown" },
597 message: `OpenCode v${probed.version} is too old. Upgrade to v${OpenCodeRuntime.MINIMUM_OPENCODE_VERSION} or newer.`,
598 },
599 });
600 }
601​
602 const loadInventory = (server: {
603 readonly url: string;
604 readonly serverPassword?: string;
605 readonly version: string;
606 }) =>
607 openCodeRuntime
608 .loadOpenCodeInventory(
609 openCodeRuntime.createOpenCodeSdkClient({
610 baseUrl: server.url,
611 directory: cwd,
612 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
613 }),
614 )
615 .pipe(Effect.map((inventory) => ({ inventory, version: server.version })));
616 const inventoryEffect = isExternalServer
617 ? openCodeRuntime
618 .connectToOpenCodeServer({
619 binaryPath: openCodeSettings.binaryPath,
620 directory: cwd,
621 serverUrl: openCodeSettings.serverUrl,
622 ...(openCodeSettings.serverPassword
623 ? { serverPassword: openCodeSettings.serverPassword }
624 : {}),
625 })
626 .pipe(Effect.flatMap(loadInventory), Effect.scoped)
627 : serverOwner.withServer(loadInventory);
628 const inventoryExit = yield* Effect.exit(
629 inventoryEffect.pipe(
630 Effect.mapError(
631 (cause) =>
632 new OpenCodeProbeError({
633 cause,
634 detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
635 }),
636 ),
637 ),
638 );
639 if (inventoryExit._tag === "Failure") {
640 return fallback(Cause.squash(inventoryExit.cause), version, "inventory");
641 }
642​
643 version = inventoryExit.value.version;
644​
645 const models = providerModelsFromSettings(
646 flattenOpenCodeModels(inventoryExit.value.inventory),
647 customModels,
648 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
649 );
650 const skills = openCodeSkillsToServerProviderSkills(inventoryExit.value.inventory.skills);
651 const connectedCount = inventoryExit.value.inventory.providerList.connected.length;
652 return buildServerProvider({
653 presentation: OPENCODE_PRESENTATION,
654 enabled: true,
655 checkedAt,
656 models,
657 skills,
658 slashCommands: openCodeCommandsToServerProviderSlashCommands(
659 inventoryExit.value.inventory.commands,
660 ),
661 probe: {
662 installed: true,
663 version,
664 status: connectedCount > 0 ? "ready" : "warning",
665 auth: {
666 status: connectedCount > 0 ? "authenticated" : "unknown",
667 type: "opencode",
668 },
669 message:
670 connectedCount > 0
671 ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
672 : isExternalServer
673 ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
674 : "OpenCode is available, but it did not report any connected upstream providers.",
675 },
676 });
677});