Open History to see the last commit
1import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe";
2import {
3 ProviderDriverKind,
4 type ModelCapabilities,
5 type ProviderOptionDescriptor,
6 type ServerProvider,
7 type ServerProviderModel,
8 type ServerProviderSkill,
9 type ServerProviderSlashCommand,
10 settingsSecretLiteral,
11} from "@t3tools/contracts";
12import type { OpenCodeSettings } from "../settings.ts";
13import * as Cause from "effect/Cause";
14import * as Schema from "effect/Schema";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Option from "effect/Option";
18import * as Queue from "effect/Queue";
19import * as Schedule from "effect/Schedule";
20import type * as Scope from "effect/Scope";
21import * as Stream from "effect/Stream";
22import * as SubscriptionRef from "effect/SubscriptionRef";
23
24import { createModelCapabilities, DEFAULT_VARIANT_CHOICE_ID } from "@t3tools/shared/model";
25import {
26 brokenVersionDetail,
27 noCompatibilityPolicy,
28 type ProviderCompatibilityLookup,
29} from "@t3tools/provider-core/server/compatibility";
30import {
31 buildServerProvider,
32 COMPACT_SLASH_COMMAND,
33 nonEmptyTrimmed,
34 providerModelsFromSettings,
35 type ServerProviderDraft,
36} from "@t3tools/provider-core/server/snapshotProbe";
37import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
38import type { ProbedOpenCode } from "./versionProbe.ts";
39import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
40import { ServiceUnavailableError } from "@opencode/protocol/errors";
41import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
42
43const OPENCODE_PRESENTATION = {
44 displayName: "OpenCode",
45 showInteractionModeToggle: false,
46} as const;
47
48class OpenCodeProbeError extends Schema.TaggedError<OpenCodeProbeError>()("OpenCodeProbeError", {
49 cause: Schema.optional(Schema.Defect()),
50 detail: Schema.String,
51}) {}
52
53const isOpenCodeProbeError = Schema.is(OpenCodeProbeError);
54
55function normalizeProbeMessage(message: string): string | undefined {
56 const trimmed = message.trim();
57 if (trimmed.length === 0) {
58 return undefined;
59 }
60 if (
61 trimmed === "An error occurred in Effect.tryPromise" ||
62 trimmed === "An error occurred in Effect.try"
63 ) {
64 return undefined;
65 }
66 return trimmed;
67}
68
69function normalizedErrorMessage(cause: unknown): string | undefined {
70 if (isOpenCodeProbeError(cause)) {
71 return normalizeProbeMessage(cause.detail);
72 }
73
74 if (!(cause instanceof Error)) {
75 return undefined;
76 }
77
78 return normalizeProbeMessage(cause.message);
79}
80
81function formatOpenCodeProbeError(input: {
82 readonly cause: unknown;
83 readonly isExternalServer: boolean;
84 readonly phase: "version" | "inventory";
85 readonly serverUrl: string;
86}): {
87 readonly installed: boolean;
88 readonly message: string;
89 readonly authStatus?: "unauthenticated";
90} {
91 const detail = normalizedErrorMessage(input.cause);
92 const lower = detail?.toLowerCase() ?? "";
93
94 if (input.isExternalServer) {
95 // Bare auth-code digits can be part of the endpoint's port or path.
96 if (
97 /(?:^|\s)(?:status(?:\s+code)?(?:\s*[:=]\s*|\s+)|http(?:\/\d(?:\.\d)?)?\s+)(?:401|403)\b/.test(
98 lower,
99 ) ||
100 /\b(?:unauthorized|forbidden)\b/.test(lower)
101 ) {
102 return {
103 installed: true,
104 authStatus: "unauthenticated",
105 message: "OpenCode server rejected authentication. Check the server URL and password.",
106 };
107 }
108
109 if (
110 lower.includes("econnrefused") ||
111 lower.includes("enotfound") ||
112 lower.includes("fetch failed") ||
113 lower.includes("networkerror") ||
114 lower.includes("timed out") ||
115 lower.includes("timeout") ||
116 lower.includes("socket hang up")
117 ) {
118 return {
119 installed: true,
120 message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
121 };
122 }
123
124 return {
125 installed: true,
126 message: detail ?? "Failed to connect to the configured OpenCode server.",
127 };
128 }
129
130 if (lower.includes("enoent") || lower.includes("notfound")) {
131 return {
132 installed: false,
133 message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
134 };
135 }
136
137 if (lower.includes("quarantine")) {
138 return {
139 installed: true,
140 message:
141 "macOS is blocking the OpenCode binary (quarantine). Run `xattr -d com.apple.quarantine $(which opencode)` to fix this.",
142 };
143 }
144
145 if (lower.includes("invalid code signature") || lower.includes("corrupted")) {
146 return {
147 installed: true,
148 message:
149 "macOS killed the OpenCode process due to an invalid code signature. The binary may be corrupted. Try reinstalling OpenCode.",
150 };
151 }
152
153 const failureLabel =
154 input.phase === "inventory"
155 ? "Failed to load OpenCode provider inventory"
156 : "Failed to execute OpenCode CLI health check";
157 return {
158 installed: true,
159 message: detail ? `${failureLabel}: ${detail}` : `${failureLabel}.`,
160 };
161}
162
163// The status check owns the span; keep handled failures visible without adding another span.
164const logDiscoveryFailure = Effect.fnUntraced(function* (input: {
165 readonly phase: "version" | "inventory" | "models";
166 readonly isExternalServer: boolean;
167 readonly version?: string;
168 readonly cause?: Cause.Cause<unknown>;
169}) {
170 const outcome = input.cause ? "failed" : "empty";
171 const attributes = {
172 provider: "opencode",
173 phase: input.phase,
174 outcome,
175 serverMode: input.isExternalServer ? "external" : "managed",
176 ...(input.version === undefined ? {} : { version: input.version }),
177 };
178 yield* Effect.annotateCurrentSpan({
179 "discovery.phase": input.phase,
180 "discovery.outcome": outcome,
181 });
182 yield* (
183 input.cause
184 ? Effect.logWarning("OpenCode discovery failed", input.cause)
185 : Effect.logWarning("OpenCode discovery failed")
186 ).pipe(Effect.annotateLogs(attributes));
187});
188
189function titleCaseSlug(value: string): string {
190 const segments: Array<string> = [];
191 for (const segment of value.split(/[-_/]+/)) {
192 if (segment.length > 0) {
193 segments.push(segment.charAt(0).toUpperCase() + segment.slice(1));
194 }
195 }
196 return segments.join(" ");
197}
198
199function reasoningVariantLabel(value: string): string {
200 return value === "xhigh" ? "Extra High" : titleCaseSlug(value);
201}
202
203function inferDefaultVariant(
204 providerID: string,
205 variants: ReadonlyArray<string>,
206): string | undefined {
207 if (variants.length === 1) {
208 return variants[0];
209 }
210 if (providerID === "anthropic" || providerID.startsWith("google")) {
211 return variants.includes("high") ? "high" : undefined;
212 }
213 if (providerID === "openai" || providerID === "opencode" || providerID === "opencode-go") {
214 return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
215 }
216 return undefined;
217}
218
219/** The Default choice sends no variant, so a user who picked a level can return to OpenCode's own default. */
220function openCodeVariantDescriptors(
221 providerID: string,
222 variants: ReadonlyArray<string>,
223): Array<ProviderOptionDescriptor> {
224 if (variants.length === 0) return [];
225 const inferred = inferDefaultVariant(providerID, variants);
226 const options = variants.map((id) => ({
227 id,
228 label: reasoningVariantLabel(id),
229 ...(id === inferred ? { isDefault: true } : {}),
230 }));
231 return [
232 {
233 id: "variant",
234 label: "Reasoning",
235 type: "select",
236 options: [{ id: DEFAULT_VARIANT_CHOICE_ID, label: "Default" }, ...options],
237 currentValue: DEFAULT_VARIANT_CHOICE_ID,
238 },
239 ];
240}
241
242function inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {
243 return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined;
244}
245
246const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
247 optionDescriptors: [
248 {
249 id: "variant",
250 label: "Reasoning",
251 type: "select",
252 options: [
253 { id: "low", label: "Low" },
254 { id: "medium", label: "Medium", isDefault: true },
255 { id: "high", label: "High" },
256 { id: "xhigh", label: "Extra High" },
257 ],
258 currentValue: "medium",
259 },
260 {
261 id: "agent",
262 label: "Agent",
263 type: "select",
264 options: [
265 { id: "build", label: "Build", isDefault: true },
266 { id: "plan", label: "Plan" },
267 ],
268 currentValue: "build",
269 },
270 ],
271});
272
273function openCodeCapabilitiesForModel(input: {
274 readonly providerID: string;
275 readonly model: ProviderListResponse["all"][number]["models"][string];
276 readonly agents: ReadonlyArray<Agent>;
277}): ModelCapabilities {
278 const variantValues = Object.keys(input.model.variants ?? {});
279 const primaryAgents = input.agents.filter(
280 (agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"),
281 );
282 const defaultAgent = inferDefaultAgent(primaryAgents);
283 const agentOptions = primaryAgents.map((agent) =>
284 defaultAgent === agent.name
285 ? { id: agent.name, label: titleCaseSlug(agent.name), isDefault: true as const }
286 : { id: agent.name, label: titleCaseSlug(agent.name) },
287 );
288 return createModelCapabilities({
289 optionDescriptors: [
290 ...openCodeVariantDescriptors(input.providerID, variantValues),
291 ...(agentOptions.length > 0
292 ? [
293 {
294 id: "agent",
295 label: "Agent",
296 type: "select" as const,
297 options: agentOptions,
298 ...(defaultAgent ? { currentValue: defaultAgent } : {}),
299 },
300 ]
301 : []),
302 ],
303 });
304}
305
306interface OpenCodeRelease {
307 readonly providerID: string;
308 readonly id: string;
309 readonly family?: string | undefined;
310 readonly released?: number | undefined;
311 readonly deprecated?: boolean | undefined;
312 /** Base input and output price, which a model size keeps when it is renamed. */
313 readonly price?: string | undefined;
314}
315
316export const openCodePrice = (cost: { readonly input: number; readonly output: number }) =>
317 `${cost.input}/${cost.output}`;
318
319/**
320 * `claude-opus-5` and `claude-opus-5-5` are one release line; `gemini-4-carbon` is another.
321 * A parameter count such as `8b` or `70b` names a size, so it stays in the line.
322 */
323const releaseLine = (id: string) =>
324 id
325 .toLowerCase()
326 .split(/[-_]/)
327 .map((token) => (/^\d+(\.\d+)?[bm]$/.test(token) ? token : token.replace(/[\d.]+/g, "")))
328 .join("");
329
330/**
331 * One OpenCode family can hold several model sizes, such as Gemini 4 Carbon and Hydrogen.
332 * A release is legacy when deprecated, or when its family in the same sub-provider has a
333 * newer active release whose id differs only in version or that is sold at the same price.
334 */
335function markOpenCodeLegacy(
336 entries: ReadonlyArray<{
337 readonly model: ServerProviderModel;
338 readonly release: OpenCodeRelease;
339 }>,
340): Array<ServerProviderModel> {
341 const familyKey = ({ providerID, family }: OpenCodeRelease) =>
342 family ? `${providerID}/${family}` : undefined;
343 const active = new Map<
344 string,
345 Array<{ readonly released: number; readonly line: string; readonly price: string | undefined }>
346 >();
347 for (const { release } of entries) {
348 const key = familyKey(release);
349 if (key === undefined || release.released === undefined || release.deprecated) continue;
350 const releases = active.get(key) ?? [];
351 releases.push({
352 released: release.released,
353 line: releaseLine(release.id),
354 price: release.price,
355 });
356 active.set(key, releases);
357 }
358 return entries.map(({ model, release }) => {
359 const key = familyKey(release);
360 const { released, price } = release;
361 const line = releaseLine(release.id);
362 const superseded =
363 key !== undefined &&
364 released !== undefined &&
365 (active.get(key) ?? []).some(
366 (other) =>
367 other.released > released &&
368 (other.line === line || (price !== undefined && other.price === price)),
369 );
370 return release.deprecated || superseded ? { ...model, isLegacy: true } : model;
371 });
372}
373
374function flattenOpenCodeModels(
375 input: Pick<OpenCodeRuntime.OpenCodeInventory, "providerList" | "agents">,
376): ReadonlyArray<ServerProviderModel> {
377 const connected = new Set(input.providerList.connected);
378 const entries: Array<{ model: ServerProviderModel; release: OpenCodeRelease }> = [];
379
380 for (const provider of input.providerList.all) {
381 if (!connected.has(provider.id)) {
382 continue;
383 }
384
385 for (const model of Object.values(provider.models)) {
386 const name = nonEmptyTrimmed(model.name);
387 if (!name) {
388 continue;
389 }
390
391 const subProvider = nonEmptyTrimmed(provider.name);
392 const released = Date.parse(model.release_date);
393 entries.push({
394 model: {
395 slug: `${provider.id}/${model.id}`,
396 name,
397 ...(subProvider ? { subProvider } : {}),
398 isCustom: false,
399 capabilities: openCodeCapabilitiesForModel({
400 providerID: provider.id,
401 model,
402 agents: input.agents,
403 }),
404 },
405 release: {
406 providerID: provider.id,
407 id: model.id,
408 family: model.family,
409 released: Number.isNaN(released) ? undefined : released,
410 deprecated: model.status === "deprecated",
411 price: model.cost ? openCodePrice(model.cost) : undefined,
412 },
413 });
414 }
415 }
416
417 return markOpenCodeLegacy(entries).toSorted((left, right) => left.name.localeCompare(right.name));
418}
419
420/** Undefined when OpenCode lists no models, so callers can keep the catalog they have. */
421export function openCodeProviderModels(
422 settings: Pick<OpenCodeSettings, "customModels">,
423 catalog: Pick<OpenCodeRuntime.OpenCodeInventory, "providerList" | "agents">,
424): ReadonlyArray<ServerProviderModel> | undefined {
425 const models = flattenOpenCodeModels(catalog);
426 return models.length === 0
427 ? undefined
428 : providerModelsFromSettings(
429 models,
430 settings.customModels,
431 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
432 );
433}
434
435function trimOptional(value: string | null | undefined): string | undefined {
436 const trimmed = value?.trim();
437 return trimmed && trimmed.length > 0 ? trimmed : undefined;
438}
439
440export function openCodeSkillsToServerProviderSkills(
441 input: OpenCodeRuntime.OpenCodeInventory["skills"] | undefined,
442): ReadonlyArray<ServerProviderSkill> {
443 const skills: ServerProviderSkill[] = [];
444 for (const skill of input ?? []) {
445 const name = trimOptional(skill.name);
446 const path = trimOptional(skill.location);
447 if (!name || !path) {
448 continue;
449 }
450
451 const description = trimOptional(skill.description);
452 skills.push({
453 name,
454 path,
455 enabled: true,
456 ...(description ? { description, shortDescription: description } : {}),
457 });
458 }
459
460 return skills.toSorted((left, right) => left.name.localeCompare(right.name));
461}
462
463export function openCodeCommandsToServerProviderSlashCommands(
464 input: OpenCodeRuntime.OpenCodeInventory["commands"],
465): ReadonlyArray<ServerProviderSlashCommand> {
466 const commands: ServerProviderSlashCommand[] = [COMPACT_SLASH_COMMAND];
467 const names = new Set([COMPACT_SLASH_COMMAND.name]);
468 for (const command of input ?? []) {
469 const name = trimOptional(command.name);
470 if (!name || names.has(name) || command.source === "skill") continue;
471 names.add(name);
472 const description = trimOptional(command.description);
473 const hint = trimOptional(command.hints.join(" "));
474 commands.push({
475 name,
476 ...(description ? { description } : {}),
477 ...(hint ? { input: { hint } } : {}),
478 });
479 }
480 return commands;
481}
482
483export const makePendingOpenCodeProvider = Effect.fn(
484 "OpencodeProviderStatus.makePendingOpenCodeProvider",
485)(function* (openCodeSettings: OpenCodeSettings): Effect.fn.Return<ServerProviderDraft> {
486 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
487 const models = providerModelsFromSettings(
488 [],
489 openCodeSettings.customModels,
490 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
491 );
492
493 if (!openCodeSettings.enabled) {
494 return buildServerProvider({
495 presentation: OPENCODE_PRESENTATION,
496 enabled: false,
497 checkedAt,
498 models,
499 probe: {
500 installed: false,
501 version: null,
502 status: "warning",
503 auth: { status: "unknown" },
504 message:
505 openCodeSettings.serverUrl.trim().length > 0
506 ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
507 : "OpenCode is disabled in T3 Code settings.",
508 },
509 });
510 }
511
512 return buildServerProvider({
513 presentation: OPENCODE_PRESENTATION,
514 enabled: true,
515 checkedAt,
516 models,
517 probe: {
518 installed: false,
519 version: null,
520 status: "warning",
521 auth: { status: "unknown" },
522 message: "OpenCode provider status has not been checked in this session yet.",
523 },
524 });
525});
526
527export interface OpenCode2Model extends OpenCodeRelease {
528 readonly name: string;
529 readonly providerName?: string;
530 readonly variants: ReadonlyArray<{ readonly id: string }>;
531}
532
533// Sub-provider names distinguish overlapping catalog entries.
534function subProviderLabelFor(input: {
535 readonly providerID: string;
536 readonly providerName?: string;
537}): string | undefined {
538 const label = nonEmptyTrimmed(input.providerName) ?? input.providerID;
539 return label.toLowerCase() === OPENCODE_PRESENTATION.displayName.toLowerCase()
540 ? undefined
541 : label;
542}
543
544const catalogFingerprint = (models: ReadonlyArray<OpenCode2Model>) =>
545 models
546 .map((model) =>
547 JSON.stringify([
548 model.providerID,
549 model.id,
550 model.name,
551 model.providerName,
552 model.variants.map((variant) => variant.id).toSorted(),
553 model.family,
554 model.released,
555 model.deprecated,
556 model.price,
557 ]),
558 )
559 .toSorted()
560 .join("\n");
561
562// A cold OpenCode 2.2.5 503s model reads for about a minute while its location plugins activate.
563const PLUGIN_ACTIVATION_DEADLINE = "2 minutes";
564
565const isServiceUnavailable = Schema.is(ServiceUnavailableError);
566const isActivatingPlugins = (error: unknown): boolean =>
567 OpenCodeRuntime.isOpenCodeRuntimeError(error)
568 ? isActivatingPlugins(error.cause)
569 : isServiceUnavailable(error) && error.service === "plugin";
570
571/** A cold server can list a partial catalog; two agreeing reads reduce that startup race. */
572const settleOpenCode2Catalog = <E>(
573 list: Effect.Effect<ReadonlyArray<OpenCode2Model>, E>,
574 first?: ReadonlyArray<OpenCode2Model>,
575) =>
576 Effect.suspend(() => {
577 let previous = first && first.length > 0 ? catalogFingerprint(first) : undefined;
578 return (first ? Effect.delay(list, "250 millis") : list).pipe(
579 Effect.repeat({
580 until: (models) => {
581 const fingerprint = models.length > 0 ? catalogFingerprint(models) : undefined;
582 const settled = fingerprint !== undefined && fingerprint === previous;
583 previous = fingerprint;
584 return settled;
585 },
586 schedule: Schedule.spaced("250 millis"),
587 }),
588 );
589 });
590
591const OPENCODE_2_CATALOG_SETTLE_TIMEOUT_MS = 5_000;
592
593export const makeOpenCode2ModelLoader = <E>(
594 list: Effect.Effect<ReadonlyArray<OpenCode2Model>, E>,
595 environment?: NodeJS.ProcessEnv,
596) =>
597 Effect.sync(() => {
598 let lastLoaded: ReadonlyArray<OpenCode2Model> = [];
599 return Effect.suspend(() => {
600 let latest: ReadonlyArray<OpenCode2Model> = [];
601 const tracked = list.pipe(
602 Effect.tap((models) =>
603 Effect.sync(() => {
604 if (models.length > 0) latest = models;
605 }),
606 ),
607 );
608 // The first read can include a cold server start, so only settling shares the budget.
609 // Each retry borrows the managed server, so retries well inside its idle TTL keep it alive.
610 return tracked.pipe(
611 Effect.retry({ while: isActivatingPlugins, schedule: Schedule.spaced("1 second") }),
612 Effect.timeoutOption(PLUGIN_ACTIVATION_DEADLINE),
613 Effect.flatMap((first) =>
614 Option.isNone(first)
615 ? Effect.succeedNone
616 : settleOpenCode2Catalog(tracked, first.value).pipe(
617 Effect.timeoutOption(
618 resolveProviderProbeTimeoutMs(
619 "opencode",
620 OPENCODE_2_CATALOG_SETTLE_TIMEOUT_MS,
621 environment,
622 ),
623 ),
624 ),
625 ),
626 Effect.catch((error) =>
627 latest.length > 0 ? Effect.succeedSome(latest) : Effect.fail(error),
628 ),
629 Effect.map((loaded) => {
630 // Fresh progress may still be partial, but a warm cache must not freeze slow catalogs.
631 if (loaded._tag === "Some") lastLoaded = loaded.value;
632 else if (latest.length > 0) lastLoaded = latest;
633 return lastLoaded;
634 }),
635 );
636 });
637 });
638
639/** None when the reads fail or never agree, so a partial catalog never passes for a settled one. */
640export const readSettledOpenCode2Catalog = <E>(
641 list: Effect.Effect<ReadonlyArray<OpenCode2Model>, E>,
642 environment?: NodeJS.ProcessEnv,
643) =>
644 settleOpenCode2Catalog(list).pipe(
645 Effect.timeoutOption(
646 resolveProviderProbeTimeoutMs("opencode", OPENCODE_2_CATALOG_SETTLE_TIMEOUT_MS, environment),
647 ),
648 Effect.orElseSucceed(() => Option.none<ReadonlyArray<OpenCode2Model>>()),
649 );
650
651// The registry keeps this many per-directory snapshots; older directories need no watch.
652const WATCHED_DIRECTORIES = 16;
653
654interface WatchedCatalog {
655 readonly read: Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError>;
656 previous: string | undefined;
657}
658
659/**
660 * OpenCode serves a startup snapshot until discovery ends and only `model.updated` says when, so
661 * no wait proves a catalog complete. The watch re-reads after each followed read and each change
662 * while the server's event stream lasts, borrowing nothing so a managed server still idles out.
663 */
664export const makeOpenCode2CatalogWatch = Effect.fn(
665 "OpencodeProviderStatus.makeOpenCode2CatalogWatch",
666)(function* (environment?: NodeJS.ProcessEnv) {
667 const scope = yield* Effect.scope;
668 const latest = yield* SubscriptionRef.make<ReadonlyArray<OpenCode2Model> | undefined>(undefined);
669 const rescans = yield* Queue.unbounded<string, Cause.Done>();
670 yield* Effect.addFinalizer(() => Queue.end(rescans));
671 const reads = yield* Queue.sliding<void>(1);
672 let following:
673 | {
674 readonly server: string;
675 machine: WatchedCatalog | undefined;
676 readonly directories: Map<string, WatchedCatalog>;
677 }
678 | undefined;
679 const reread = (
680 watched: WatchedCatalog,
681 changed: (catalog: ReadonlyArray<OpenCode2Model>) => Effect.Effect<unknown>,
682 read: Effect.Effect<
683 ReadonlyArray<OpenCode2Model>,
684 OpenCodeRuntime.OpenCodeRuntimeError
685 > = watched.read,
686 ) =>
687 read.pipe(
688 Effect.flatMap((catalog) => {
689 const fingerprint = catalog.length > 0 ? catalogFingerprint(catalog) : undefined;
690 if (fingerprint === undefined || fingerprint === watched.previous) return Effect.void;
691 watched.previous = fingerprint;
692 return changed(catalog);
693 }),
694 // A stopped server fails every read; that must not discard the catalog it had listed.
695 Effect.retry({ times: 3, schedule: Schedule.spaced("1 second") }),
696 // Nothing else bounds this read, and one that hangs would hold every later change.
697 Effect.timeout("30 seconds"),
698 Effect.ignore,
699 );
700 return {
701 /** The newest machine catalog the watch read; undefined when the last check knows better. */
702 changes: SubscriptionRef.changes(latest),
703 /** Directories whose catalog no longer matches the one their scan was given. */
704 rescans: Stream.fromQueue(rescans),
705 /**
706 * Call beside each catalog read. `read` must not borrow the server. A `directory` read
707 * reports the catalog its scan settled on, if any, and is rescanned once that changes.
708 */
709 follow: <E, SE>(
710 server: string,
711 subscribe: Effect.Effect<Stream.Stream<{ readonly type: string }, SE>, E, Scope.Scope>,
712 read: Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError>,
713 directory?: { readonly cwd: string; readonly settled?: ReadonlyArray<OpenCode2Model> },
714 ) =>
715 Effect.suspend(() => {
716 const started = following?.server !== server;
717 const watching = started
718 ? { server, machine: undefined, directories: new Map<string, WatchedCatalog>() }
719 : following!;
720 following = watching;
721 if (directory === undefined) {
722 watching.machine = { read, previous: watching.machine?.previous };
723 } else {
724 const { cwd, settled } = directory;
725 const previous = settled?.length
726 ? catalogFingerprint(settled)
727 : watching.directories.get(cwd)?.previous;
728 watching.directories.delete(cwd);
729 watching.directories.set(cwd, { read, previous });
730 for (const oldest of watching.directories.keys()) {
731 if (watching.directories.size <= WATCHED_DIRECTORIES) break;
732 watching.directories.delete(oldest);
733 }
734 }
735 const requested = Queue.offer(reads, undefined).pipe(Effect.asVoid);
736 if (!started) return requested;
737 const rereadAll = Effect.suspend(() =>
738 Effect.forEach(
739 [
740 ...(watching.machine
741 ? [reread(watching.machine, (catalog) => SubscriptionRef.set(latest, catalog))]
742 : []),
743 ...Array.from(watching.directories, ([cwd, watched]) =>
744 reread(watched, () => Queue.offer(rescans, cwd)),
745 ),
746 ],
747 (effect) => effect,
748 { concurrency: 4, discard: true },
749 ),
750 );
751 // A new server lists its startup snapshot first; nothing else reads it unless a check did.
752 const settleMachine = Effect.suspend(() => {
753 const machine = watching.machine;
754 return machine === undefined
755 ? Effect.void
756 : reread(
757 machine,
758 (catalog) => SubscriptionRef.set(latest, catalog),
759 readSettledOpenCode2Catalog(machine.read, environment).pipe(
760 Effect.map(Option.getOrElse((): ReadonlyArray<OpenCode2Model> => [])),
761 ),
762 );
763 });
764 const watch = subscribe.pipe(
765 Effect.tap(() => settleMachine),
766 Effect.flatMap((events) =>
767 events.pipe(
768 Stream.filter((event) => event.type === "model.updated"),
769 Stream.merge(Stream.fromQueue(reads), { haltStrategy: "left" }),
770 // OpenCode announces one change as a burst of events.
771 Stream.debounce("250 millis"),
772 Stream.runForEach(() => rereadAll),
773 Effect.ignore,
774 ),
775 ),
776 // Unwatched, a catalog kept from an earlier server would override every later check.
777 Effect.catch(() => SubscriptionRef.set(latest, undefined)),
778 Effect.scoped,
779 Effect.ensuring(
780 Effect.sync(() => {
781 if (following === watching) following = undefined;
782 }),
783 ),
784 );
785 return requested.pipe(Effect.andThen(Effect.forkIn(watch, scope)), Effect.asVoid);
786 }),
787 };
788});
789
790const openCode2ReadyMessage = (version: string, count: number) =>
791 `OpenCode ${version} lists ${count} model${count === 1 ? "" : "s"}.`;
792
793/** A catalog read after the check reports the same health the check would have. */
794export const withOpenCode2Catalog = (
795 snapshot: ServerProvider,
796 settings: Pick<OpenCodeSettings, "customModels">,
797 catalog: ReadonlyArray<OpenCode2Model>,
798): ServerProvider =>
799 snapshot.version === null || snapshot.status === "error" || snapshot.status === "disabled"
800 ? snapshot
801 : {
802 ...snapshot,
803 status: "ready",
804 auth: { ...snapshot.auth, status: "authenticated" },
805 message: openCode2ReadyMessage(snapshot.version, catalog.length),
806 models: openCode2ProviderModels(settings, catalog),
807 };
808
809export interface OpenCode2Workspace {
810 readonly skills: ReadonlyArray<{
811 readonly id: string;
812 readonly name: string;
813 readonly path: string;
814 readonly description?: string | undefined;
815 }>;
816 readonly commands: ReadonlyArray<{
817 readonly name: string;
818 readonly description?: string | undefined;
819 }>;
820}
821
822/**
823 * Runs `onScanned` for each location whose scan ends, which OpenCode announces once, after loading
824 * the location, as `command.updated` plus `skill.updated`.
825 */
826export const followOpenCode2Scans = <E>(
827 events: Stream.Stream<
828 { readonly type: string; readonly location?: { readonly directory?: string } | undefined },
829 E
830 >,
831 onScanned: (directory: string) => Effect.Effect<void>,
832) => {
833 const pending = new Map<string, Set<string>>();
834 return events.pipe(
835 Stream.runForEach((event) => {
836 const directory = event.location?.directory;
837 if (directory === undefined) return Effect.void;
838 if (event.type !== "command.updated" && event.type !== "skill.updated") return Effect.void;
839 const seen = pending.get(directory) ?? new Set<string>();
840 pending.set(directory, seen.add(event.type));
841 if (seen.size < 2) return Effect.void;
842 pending.delete(directory);
843 return onScanned(directory);
844 }),
845 Effect.ignore,
846 );
847};
848
849/**
850 * Until its scan ends a location lists only built-ins, even once the server lists it as loaded,
851 * and nothing but the scan's end tells the two apart. Unless the caller saw that scan end, read to
852 * boot the location, wait for its scan (`scanned` must listen before `read`), and read again.
853 */
854export const loadOpenCode2Workspace = Effect.fn("OpencodeProviderStatus.loadOpenCode2Workspace")(
855 function* <E>(
856 read: Effect.Effect<OpenCode2Workspace, E>,
857 scanned: Effect.Effect<void>,
858 sawScan: boolean,
859 environment?: NodeJS.ProcessEnv,
860 ) {
861 const first = yield* read;
862 if (sawScan) return first;
863 yield* scanned.pipe(
864 Effect.timeoutOption(resolveProviderProbeTimeoutMs("opencode", 10_000, environment)),
865 );
866 return yield* read;
867 },
868);
869
870export function openCode2SkillsToServerProviderSkills(
871 skills: OpenCode2Workspace["skills"],
872): ReadonlyArray<ServerProviderSkill> {
873 return skills
874 .map((skill) => {
875 const description = trimOptional(skill.description);
876 return {
877 name: skill.id,
878 path: skill.path,
879 enabled: true,
880 ...(skill.name === skill.id ? {} : { displayName: skill.name }),
881 ...(description ? { description, shortDescription: description } : {}),
882 };
883 })
884 .toSorted((left, right) => left.name.localeCompare(right.name));
885}
886
887export function openCode2CommandsToServerProviderSlashCommands(
888 commands: OpenCode2Workspace["commands"],
889): ReadonlyArray<ServerProviderSlashCommand> {
890 const slashCommands: ServerProviderSlashCommand[] = [COMPACT_SLASH_COMMAND];
891 const names = new Set([COMPACT_SLASH_COMMAND.name]);
892 for (const command of commands) {
893 const name = trimOptional(command.name);
894 if (!name || names.has(name)) continue;
895 names.add(name);
896 const description = trimOptional(command.description);
897 slashCommands.push({ name, ...(description ? { description } : {}) });
898 }
899 return slashCommands;
900}
901
902// OpenCode has no reviewer; Auto asks like Supervised.
903const OPENCODE_2_PRESENTATION = {
904 ...OPENCODE_PRESENTATION,
905 showInteractionModeToggle: true,
906 supportedRuntimeModes: ["approval-required", "auto-accept-edits", "auto", "full-access"],
907} as const;
908
909function openCode2ModelCapabilities(model: OpenCode2Model): ModelCapabilities {
910 return createModelCapabilities({
911 optionDescriptors: openCodeVariantDescriptors(
912 model.providerID,
913 model.variants.map((variant) => variant.id),
914 ),
915 });
916}
917
918export function openCode2ProviderModels(
919 settings: Pick<OpenCodeSettings, "customModels">,
920 catalog: ReadonlyArray<OpenCode2Model>,
921): ReadonlyArray<ServerProviderModel> {
922 return providerModelsFromSettings(
923 markOpenCodeLegacy(
924 catalog.map((model) => {
925 const subProvider = subProviderLabelFor(model);
926 return {
927 model: {
928 slug: `${model.providerID}/${model.id}`,
929 name: model.name,
930 ...(subProvider ? { subProvider } : {}),
931 isCustom: false,
932 capabilities: openCode2ModelCapabilities(model),
933 },
934 release: model,
935 };
936 }),
937 ).toSorted((left, right) => left.name.localeCompare(right.name)),
938 settings.customModels,
939 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
940 );
941}
942
943const checkOpenCode2 = Effect.fn("checkOpenCode2")(function* (
944 settings: OpenCodeSettings,
945 version: string,
946 checkedAt: string,
947 loadModels: Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError>,
948) {
949 const result = yield* Effect.exit(loadModels);
950 const probe = (status: "ready" | "warning" | "error", message: string) => ({
951 installed: true,
952 version,
953 status,
954 auth: { status: status === "ready" ? ("authenticated" as const) : ("unknown" as const) },
955 message,
956 });
957 if (result._tag === "Failure") {
958 yield* logDiscoveryFailure({
959 phase: "models",
960 isExternalServer: settings.serverUrl.trim().length > 0,
961 version,
962 cause: result.cause,
963 });
964 return buildServerProvider({
965 presentation: OPENCODE_2_PRESENTATION,
966 enabled: true,
967 checkedAt,
968 models: providerModelsFromSettings(
969 [],
970 settings.customModels,
971 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
972 ),
973 slashCommands: [COMPACT_SLASH_COMMAND],
974 probe: probe("error", "OpenCode could not load its model list."),
975 });
976 }
977 if (result.value.length === 0) {
978 yield* logDiscoveryFailure({
979 phase: "models",
980 isExternalServer: settings.serverUrl.trim().length > 0,
981 version,
982 });
983 }
984 return buildServerProvider({
985 presentation: OPENCODE_2_PRESENTATION,
986 enabled: true,
987 checkedAt,
988 models: openCode2ProviderModels(settings, result.value),
989 slashCommands: [COMPACT_SLASH_COMMAND],
990 probe:
991 result.value.length > 0
992 ? probe("ready", openCode2ReadyMessage(version, result.value.length))
993 : probe("warning", "OpenCode 2 is running, but it did not list any models yet."),
994 });
995});
996
997export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
998 openCodeSettings: OpenCodeSettings,
999 cwd: string,
1000 probeRuntime: Effect.Effect<ProbedOpenCode, OpenCodeRuntime.OpenCodeRuntimeError>,
1001 loadOpenCode2Models: Effect.Effect<
1002 ReadonlyArray<OpenCode2Model>,
1003 OpenCodeRuntime.OpenCodeRuntimeError
1004 >,
1005 environment?: NodeJS.ProcessEnv,
1006 compatibility: ProviderCompatibilityLookup = noCompatibilityPolicy,
1007): Effect.fn.Return<
1008 ServerProviderDraft,
1009 never,
1010 OpenCodeRuntime.OpenCodeRuntime | OpenCodeServerOwner.OpenCodeServerOwner
1011> {
1012 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
1013 const serverOwner = yield* OpenCodeServerOwner.OpenCodeServerOwner;
1014 const checkedAt = DateTime.formatIso(yield* DateTime.now);
1015 const customModels = openCodeSettings.customModels;
1016 const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
1017
1018 const fallback = (
1019 cause: unknown,
1020 version: string | null = null,
1021 phase: "version" | "inventory" = "version",
1022 ) => {
1023 const failure = formatOpenCodeProbeError({
1024 cause,
1025 isExternalServer,
1026 phase,
1027 serverUrl: openCodeSettings.serverUrl,
1028 });
1029 return buildServerProvider({
1030 presentation: OPENCODE_PRESENTATION,
1031 enabled: openCodeSettings.enabled,
1032 checkedAt,
1033 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
1034 probe: {
1035 installed: failure.installed,
1036 version,
1037 status: "error",
1038 auth: { status: failure.authStatus ?? "unknown" },
1039 message: failure.message,
1040 },
1041 });
1042 };
1043
1044 if (!openCodeSettings.enabled) {
1045 return buildServerProvider({
1046 presentation: OPENCODE_PRESENTATION,
1047 enabled: false,
1048 checkedAt,
1049 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
1050 probe: {
1051 installed: false,
1052 version: null,
1053 status: "warning",
1054 auth: { status: "unknown" },
1055 message: isExternalServer
1056 ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
1057 : "OpenCode is disabled in T3 Code settings.",
1058 },
1059 });
1060 }
1061
1062 const probedExit = yield* Effect.exit(
1063 probeRuntime.pipe(
1064 Effect.mapError(
1065 (cause) =>
1066 new OpenCodeProbeError({
1067 cause,
1068 detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
1069 }),
1070 ),
1071 ),
1072 );
1073 if (probedExit._tag === "Failure") {
1074 yield* logDiscoveryFailure({ phase: "version", isExternalServer, cause: probedExit.cause });
1075 return fallback(Cause.squash(probedExit.cause));
1076 }
1077 const probed = probedExit.value;
1078 if (probed.generation === "v2") {
1079 return yield* checkOpenCode2(openCodeSettings, probed.version, checkedAt, loadOpenCode2Models);
1080 }
1081 const refuseBroken = Effect.fnUntraced(function* (detected: string) {
1082 const broken = brokenVersionDetail({
1083 name: "OpenCode",
1084 version: detected,
1085 advisory: yield* compatibility(ProviderDriverKind.make("opencode"), detected),
1086 });
1087 return broken === undefined
1088 ? undefined
1089 : buildServerProvider({
1090 presentation: OPENCODE_PRESENTATION,
1091 enabled: openCodeSettings.enabled,
1092 checkedAt,
1093 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
1094 probe: {
1095 installed: true,
1096 version: detected,
1097 status: "error",
1098 auth: { status: "unknown" },
1099 message: broken,
1100 },
1101 });
1102 });
1103 const refused = yield* refuseBroken(probed.version);
1104 if (refused !== undefined) return refused;
1105
1106 const installedVersion = isExternalServer ? {} : { installedVersion: probed.version };
1107 let version = probed.version;
1108 const loadInventory = Effect.fnUntraced(function* (server: {
1109 readonly url: string;
1110 readonly serverPassword?: string;
1111 readonly version: string;
1112 }) {
1113 // Preserve the helper's version even when its inventory request fails.
1114 version = server.version;
1115 return yield* openCodeRuntime.loadOpenCodeInventory(
1116 openCodeRuntime.createOpenCodeSdkClient({
1117 baseUrl: server.url,
1118 directory: cwd,
1119 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
1120 }),
1121 );
1122 });
1123 const inventoryEffect = isExternalServer
1124 ? openCodeRuntime
1125 .connectToOpenCodeServer({
1126 binaryPath: openCodeSettings.binaryPath,
1127 directory: cwd,
1128 serverUrl: openCodeSettings.serverUrl,
1129 ...(settingsSecretLiteral(openCodeSettings.serverPassword)
1130 ? { serverPassword: settingsSecretLiteral(openCodeSettings.serverPassword) }
1131 : {}),
1132 ...(environment !== undefined ? { environment } : {}),
1133 })
1134 .pipe(Effect.flatMap(loadInventory), Effect.scoped)
1135 : serverOwner.withServer(loadInventory);
1136 const inventoryExit = yield* Effect.exit(
1137 inventoryEffect.pipe(
1138 Effect.mapError(
1139 (cause) =>
1140 new OpenCodeProbeError({
1141 cause,
1142 detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
1143 }),
1144 ),
1145 ),
1146 );
1147 // The server that answered can differ from the CLI the probe ran.
1148 const refusedServer = version === probed.version ? undefined : yield* refuseBroken(version);
1149 if (refusedServer !== undefined) return { ...refusedServer, ...installedVersion };
1150 if (inventoryExit._tag === "Failure") {
1151 yield* logDiscoveryFailure({
1152 phase: "inventory",
1153 isExternalServer,
1154 version,
1155 cause: inventoryExit.cause,
1156 });
1157 return {
1158 ...fallback(Cause.squash(inventoryExit.cause), version, "inventory"),
1159 ...installedVersion,
1160 };
1161 }
1162
1163 const catalogModels = openCodeProviderModels(openCodeSettings, inventoryExit.value);
1164 const models =
1165 catalogModels ??
1166 providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES);
1167 const skills = openCodeSkillsToServerProviderSkills(inventoryExit.value.skills);
1168 const connectedCount = inventoryExit.value.providerList.connected.length;
1169 const catalogReady = connectedCount > 0 && catalogModels !== undefined;
1170 if (connectedCount > 0 && catalogModels === undefined) {
1171 yield* logDiscoveryFailure({ phase: "inventory", isExternalServer, version });
1172 }
1173 return {
1174 ...buildServerProvider({
1175 presentation: OPENCODE_PRESENTATION,
1176 enabled: true,
1177 checkedAt,
1178 models,
1179 skills,
1180 slashCommands: openCodeCommandsToServerProviderSlashCommands(inventoryExit.value.commands),
1181 probe: {
1182 installed: true,
1183 version,
1184 status: catalogReady ? "ready" : "warning",
1185 auth: {
1186 status: catalogReady ? "authenticated" : "unknown",
1187 type: "opencode",
1188 },
1189 message:
1190 connectedCount > 0 && !catalogReady
1191 ? "OpenCode upstream providers are connected, but it did not list any models yet."
1192 : connectedCount > 0
1193 ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
1194 : isExternalServer
1195 ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
1196 : "OpenCode is available, but it did not report any connected upstream providers.",
1197 },
1198 }),
1199 ...installedVersion,
1200 };
1201});