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

status.ts

1,204 lines41.1 KB

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