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

status.ts

1,200 lines41.0 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 ]),
557 )
558 .toSorted()
559 .join("\n");
560​
561// A cold OpenCode 2.2.5 503s model reads for about a minute while its location plugins activate.
562const PLUGIN_ACTIVATION_DEADLINE = "2 minutes";
563​
564const isServiceUnavailable = Schema.is(ServiceUnavailableError);
565const isActivatingPlugins = (error: unknown): boolean =>
566 OpenCodeRuntime.isOpenCodeRuntimeError(error)
567 ? isActivatingPlugins(error.cause)
568 : isServiceUnavailable(error) && error.service === "plugin";
569​
570/** A cold server can list a partial catalog; two agreeing reads reduce that startup race. */
571const settleOpenCode2Catalog = <E>(
572 list: Effect.Effect<ReadonlyArray<OpenCode2Model>, E>,
573 first?: ReadonlyArray<OpenCode2Model>,
574) =>
575 Effect.suspend(() => {
576 let previous = first && first.length > 0 ? catalogFingerprint(first) : undefined;
577 return (first ? Effect.delay(list, "250 millis") : list).pipe(
578 Effect.repeat({
579 until: (models) => {
580 const fingerprint = models.length > 0 ? catalogFingerprint(models) : undefined;
581 const settled = fingerprint !== undefined && fingerprint === previous;
582 previous = fingerprint;
583 return settled;
584 },
585 schedule: Schedule.spaced("250 millis"),
586 }),
587 );
588 });
589​
590const OPENCODE_2_CATALOG_SETTLE_TIMEOUT_MS = 5_000;
591​
592export const makeOpenCode2ModelLoader = <E>(
593 list: Effect.Effect<ReadonlyArray<OpenCode2Model>, E>,
594 environment?: NodeJS.ProcessEnv,
595) =>
596 Effect.sync(() => {
597 let lastLoaded: ReadonlyArray<OpenCode2Model> = [];
598 return Effect.suspend(() => {
599 let latest: ReadonlyArray<OpenCode2Model> = [];
600 const tracked = list.pipe(
601 Effect.tap((models) =>
602 Effect.sync(() => {
603 if (models.length > 0) latest = models;
604 }),
605 ),
606 );
607 // The first read can include a cold server start, so only settling shares the budget.
608 // Each retry borrows the managed server, so retries well inside its idle TTL keep it alive.
609 return tracked.pipe(
610 Effect.retry({ while: isActivatingPlugins, schedule: Schedule.spaced("1 second") }),
611 Effect.timeoutOption(PLUGIN_ACTIVATION_DEADLINE),
612 Effect.flatMap((first) =>
613 Option.isNone(first)
614 ? Effect.succeedNone
615 : settleOpenCode2Catalog(tracked, first.value).pipe(
616 Effect.timeoutOption(
617 resolveProviderProbeTimeoutMs(
618 "opencode",
619 OPENCODE_2_CATALOG_SETTLE_TIMEOUT_MS,
620 environment,
621 ),
622 ),
623 ),
624 ),
625 Effect.catch((error) =>
626 latest.length > 0 ? Effect.succeedSome(latest) : Effect.fail(error),
627 ),
628 Effect.map((loaded) => {
629 // Fresh progress may still be partial, but a warm cache must not freeze slow catalogs.
630 if (loaded._tag === "Some") lastLoaded = loaded.value;
631 else if (latest.length > 0) lastLoaded = latest;
632 return lastLoaded;
633 }),
634 );
635 });
636 });
637​
638/** None when the reads fail or never agree, so a partial catalog never passes for a settled one. */
639export const readSettledOpenCode2Catalog = <E>(
640 list: Effect.Effect<ReadonlyArray<OpenCode2Model>, E>,
641 environment?: NodeJS.ProcessEnv,
642) =>
643 settleOpenCode2Catalog(list).pipe(
644 Effect.timeoutOption(
645 resolveProviderProbeTimeoutMs("opencode", OPENCODE_2_CATALOG_SETTLE_TIMEOUT_MS, environment),
646 ),
647 Effect.orElseSucceed(() => Option.none<ReadonlyArray<OpenCode2Model>>()),
648 );
649​
650// The registry keeps this many per-directory snapshots; older directories need no watch.
651const WATCHED_DIRECTORIES = 16;
652​
653interface WatchedCatalog {
654 readonly read: Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError>;
655 previous: string | undefined;
657​
658/**
659 * OpenCode serves a startup snapshot until discovery ends and only `model.updated` says when, so
660 * no wait proves a catalog complete. The watch re-reads after each followed read and each change
661 * while the server's event stream lasts, borrowing nothing so a managed server still idles out.
662 */
663export const makeOpenCode2CatalogWatch = Effect.fn(
664 "OpencodeProviderStatus.makeOpenCode2CatalogWatch",
665)(function* (environment?: NodeJS.ProcessEnv) {
666 const scope = yield* Effect.scope;
667 const latest = yield* SubscriptionRef.make<ReadonlyArray<OpenCode2Model> | undefined>(undefined);
668 const rescans = yield* Queue.unbounded<string, Cause.Done>();
669 yield* Effect.addFinalizer(() => Queue.end(rescans));
670 const reads = yield* Queue.sliding<void>(1);
671 let following:
672 | {
673 readonly server: string;
674 machine: WatchedCatalog | undefined;
675 readonly directories: Map<string, WatchedCatalog>;
676 }
677 | undefined;
678 const reread = (
679 watched: WatchedCatalog,
680 changed: (catalog: ReadonlyArray<OpenCode2Model>) => Effect.Effect<unknown>,
681 read: Effect.Effect<
682 ReadonlyArray<OpenCode2Model>,
683 OpenCodeRuntime.OpenCodeRuntimeError
684 > = watched.read,
685 ) =>
686 read.pipe(
687 Effect.flatMap((catalog) => {
688 const fingerprint = catalog.length > 0 ? catalogFingerprint(catalog) : undefined;
689 if (fingerprint === undefined || fingerprint === watched.previous) return Effect.void;
690 watched.previous = fingerprint;
691 return changed(catalog);
692 }),
693 // A stopped server fails every read; that must not discard the catalog it had listed.
694 Effect.retry({ times: 3, schedule: Schedule.spaced("1 second") }),
695 // Nothing else bounds this read, and one that hangs would hold every later change.
696 Effect.timeout("30 seconds"),
697 Effect.ignore,
698 );
699 return {
700 /** The newest machine catalog the watch read; undefined when the last check knows better. */
701 changes: SubscriptionRef.changes(latest),
702 /** Directories whose catalog no longer matches the one their scan was given. */
703 rescans: Stream.fromQueue(rescans),
704 /**
705 * Call beside each catalog read. `read` must not borrow the server. A `directory` read
706 * reports the catalog its scan settled on, if any, and is rescanned once that changes.
707 */
708 follow: <E, SE>(
709 server: string,
710 subscribe: Effect.Effect<Stream.Stream<{ readonly type: string }, SE>, E, Scope.Scope>,
711 read: Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError>,
712 directory?: { readonly cwd: string; readonly settled?: ReadonlyArray<OpenCode2Model> },
713 ) =>
714 Effect.suspend(() => {
715 const started = following?.server !== server;
716 const watching = started
717 ? { server, machine: undefined, directories: new Map<string, WatchedCatalog>() }
718 : following!;
719 following = watching;
720 if (directory === undefined) {
721 watching.machine = { read, previous: watching.machine?.previous };
722 } else {
723 const { cwd, settled } = directory;
724 const previous = settled?.length
725 ? catalogFingerprint(settled)
726 : watching.directories.get(cwd)?.previous;
727 watching.directories.delete(cwd);
728 watching.directories.set(cwd, { read, previous });
729 for (const oldest of watching.directories.keys()) {
730 if (watching.directories.size <= WATCHED_DIRECTORIES) break;
731 watching.directories.delete(oldest);
732 }
733 }
734 const requested = Queue.offer(reads, undefined).pipe(Effect.asVoid);
735 if (!started) return requested;
736 const rereadAll = Effect.suspend(() =>
737 Effect.forEach(
738 [
739 ...(watching.machine
740 ? [reread(watching.machine, (catalog) => SubscriptionRef.set(latest, catalog))]
741 : []),
742 ...Array.from(watching.directories, ([cwd, watched]) =>
743 reread(watched, () => Queue.offer(rescans, cwd)),
744 ),
745 ],
746 (effect) => effect,
747 { concurrency: 4, discard: true },
748 ),
749 );
750 // A new server lists its startup snapshot first; nothing else reads it unless a check did.
751 const settleMachine = Effect.suspend(() => {
752 const machine = watching.machine;
753 return machine === undefined
754 ? Effect.void
755 : reread(
756 machine,
757 (catalog) => SubscriptionRef.set(latest, catalog),
758 readSettledOpenCode2Catalog(machine.read, environment).pipe(
759 Effect.map(Option.getOrElse((): ReadonlyArray<OpenCode2Model> => [])),
760 ),
761 );
762 });
763 const watch = subscribe.pipe(
764 Effect.tap(() => settleMachine),
765 Effect.flatMap((events) =>
766 events.pipe(
767 Stream.filter((event) => event.type === "model.updated"),
768 Stream.merge(Stream.fromQueue(reads), { haltStrategy: "left" }),
769 // OpenCode announces one change as a burst of events.
770 Stream.debounce("250 millis"),
771 Stream.runForEach(() => rereadAll),
772 Effect.ignore,
773 ),
774 ),
775 // Unwatched, a catalog kept from an earlier server would override every later check.
776 Effect.catch(() => SubscriptionRef.set(latest, undefined)),
777 Effect.scoped,
778 Effect.ensuring(
779 Effect.sync(() => {
780 if (following === watching) following = undefined;
781 }),
782 ),
783 );
784 return requested.pipe(Effect.andThen(Effect.forkIn(watch, scope)), Effect.asVoid);
785 }),
786 };
787});
788​
789const openCode2ReadyMessage = (version: string, count: number) =>
790 `OpenCode ${version} lists ${count} model${count === 1 ? "" : "s"}.`;
791​
792/** A catalog read after the check reports the same health the check would have. */
793export const withOpenCode2Catalog = (
794 snapshot: ServerProvider,
795 settings: Pick<OpenCodeSettings, "customModels">,
796 catalog: ReadonlyArray<OpenCode2Model>,
797): ServerProvider =>
798 snapshot.version === null || snapshot.status === "error" || snapshot.status === "disabled"
799 ? snapshot
800 : {
801 ...snapshot,
802 status: "ready",
803 auth: { ...snapshot.auth, status: "authenticated" },
804 message: openCode2ReadyMessage(snapshot.version, catalog.length),
805 models: openCode2ProviderModels(settings, catalog),
806 };
807​
808export interface OpenCode2Workspace {
809 readonly skills: ReadonlyArray<{
810 readonly id: string;
811 readonly name: string;
812 readonly path: string;
813 readonly description?: string | undefined;
814 }>;
815 readonly commands: ReadonlyArray<{
816 readonly name: string;
817 readonly description?: string | undefined;
818 }>;
820​
821/**
822 * Runs `onScanned` for each location whose scan ends, which OpenCode announces once, after loading
823 * the location, as `command.updated` plus `skill.updated`.
824 */
825export const followOpenCode2Scans = <E>(
826 events: Stream.Stream<
827 { readonly type: string; readonly location?: { readonly directory?: string } | undefined },
828 E
829 >,
830 onScanned: (directory: string) => Effect.Effect<void>,
831) => {
832 const pending = new Map<string, Set<string>>();
833 return events.pipe(
834 Stream.runForEach((event) => {
835 const directory = event.location?.directory;
836 if (directory === undefined) return Effect.void;
837 if (event.type !== "command.updated" && event.type !== "skill.updated") return Effect.void;
838 const seen = pending.get(directory) ?? new Set<string>();
839 pending.set(directory, seen.add(event.type));
840 if (seen.size < 2) return Effect.void;
841 pending.delete(directory);
842 return onScanned(directory);
843 }),
844 Effect.ignore,
845 );
846};
847​
848/**
849 * Until its scan ends a location lists only built-ins, even once the server lists it as loaded,
850 * and nothing but the scan's end tells the two apart. Unless the caller saw that scan end, read to
851 * boot the location, wait for its scan (`scanned` must listen before `read`), and read again.
852 */
853export const loadOpenCode2Workspace = Effect.fn("OpencodeProviderStatus.loadOpenCode2Workspace")(
854 function* <E>(
855 read: Effect.Effect<OpenCode2Workspace, E>,
856 scanned: Effect.Effect<void>,
857 sawScan: boolean,
858 environment?: NodeJS.ProcessEnv,
859 ) {
860 const first = yield* read;
861 if (sawScan) return first;
862 yield* scanned.pipe(
863 Effect.timeoutOption(resolveProviderProbeTimeoutMs("opencode", 10_000, environment)),
864 );
865 return yield* read;
866 },
867);
868​
869export function openCode2SkillsToServerProviderSkills(
870 skills: OpenCode2Workspace["skills"],
871): ReadonlyArray<ServerProviderSkill> {
872 return skills
873 .map((skill) => {
874 const description = trimOptional(skill.description);
875 return {
876 name: skill.id,
877 path: skill.path,
878 enabled: true,
879 ...(skill.name === skill.id ? {} : { displayName: skill.name }),
880 ...(description ? { description, shortDescription: description } : {}),
881 };
882 })
883 .toSorted((left, right) => left.name.localeCompare(right.name));
885​
886export function openCode2CommandsToServerProviderSlashCommands(
887 commands: OpenCode2Workspace["commands"],
888): ReadonlyArray<ServerProviderSlashCommand> {
889 const slashCommands: ServerProviderSlashCommand[] = [COMPACT_SLASH_COMMAND];
890 const names = new Set([COMPACT_SLASH_COMMAND.name]);
891 for (const command of commands) {
892 const name = trimOptional(command.name);
893 if (!name || names.has(name)) continue;
894 names.add(name);
895 const description = trimOptional(command.description);
896 slashCommands.push({ name, ...(description ? { description } : {}) });
897 }
898 return slashCommands;
900​
901// OpenCode has no reviewer; Auto asks like Supervised.
902const OPENCODE_2_PRESENTATION = {
903 ...OPENCODE_PRESENTATION,
904 showInteractionModeToggle: true,
905 supportedRuntimeModes: ["approval-required", "auto-accept-edits", "auto", "full-access"],
906} as const;
907​
908function openCode2ModelCapabilities(model: OpenCode2Model): ModelCapabilities {
909 return createModelCapabilities({
910 optionDescriptors: openCodeVariantDescriptors(
911 model.providerID,
912 model.variants.map((variant) => variant.id),
913 ),
914 });
916​
917export function openCode2ProviderModels(
918 settings: Pick<OpenCodeSettings, "customModels">,
919 catalog: ReadonlyArray<OpenCode2Model>,
920): ReadonlyArray<ServerProviderModel> {
921 return providerModelsFromSettings(
922 markOpenCodeLegacy(
923 catalog.map((model) => {
924 const subProvider = subProviderLabelFor(model);
925 return {
926 model: {
927 slug: `${model.providerID}/${model.id}`,
928 name: model.name,
929 ...(subProvider ? { subProvider } : {}),
930 isCustom: false,
931 capabilities: openCode2ModelCapabilities(model),
932 },
933 release: model,
934 };
935 }),
936 ).toSorted((left, right) => left.name.localeCompare(right.name)),
937 settings.customModels,
938 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
939 );
941​
942const checkOpenCode2 = Effect.fn("checkOpenCode2")(function* (
943 settings: OpenCodeSettings,
944 version: string,
945 checkedAt: string,
946 loadModels: Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError>,
947) {
948 const result = yield* Effect.exit(loadModels);
949 const probe = (status: "ready" | "warning" | "error", message: string) => ({
950 installed: true,
951 version,
952 status,
953 auth: { status: status === "ready" ? ("authenticated" as const) : ("unknown" as const) },
954 message,
955 });
956 if (result._tag === "Failure") {
957 yield* logDiscoveryFailure({
958 phase: "models",
959 isExternalServer: settings.serverUrl.trim().length > 0,
960 version,
961 cause: result.cause,
962 });
963 return buildServerProvider({
964 presentation: OPENCODE_2_PRESENTATION,
965 enabled: true,
966 checkedAt,
967 models: providerModelsFromSettings(
968 [],
969 settings.customModels,
970 DEFAULT_OPENCODE_MODEL_CAPABILITIES,
971 ),
972 slashCommands: [COMPACT_SLASH_COMMAND],
973 probe: probe("error", "OpenCode could not load its model list."),
974 });
975 }
976 if (result.value.length === 0) {
977 yield* logDiscoveryFailure({
978 phase: "models",
979 isExternalServer: settings.serverUrl.trim().length > 0,
980 version,
981 });
982 }
983 return buildServerProvider({
984 presentation: OPENCODE_2_PRESENTATION,
985 enabled: true,
986 checkedAt,
987 models: openCode2ProviderModels(settings, result.value),
988 slashCommands: [COMPACT_SLASH_COMMAND],
989 probe:
990 result.value.length > 0
991 ? probe("ready", openCode2ReadyMessage(version, result.value.length))
992 : probe("warning", "OpenCode 2 is running, but it did not list any models yet."),
993 });
994});
995​
996export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
997 openCodeSettings: OpenCodeSettings,
998 cwd: string,
999 probeRuntime: Effect.Effect<ProbedOpenCode, OpenCodeRuntime.OpenCodeRuntimeError>,
1000 loadOpenCode2Models: Effect.Effect<
1001 ReadonlyArray<OpenCode2Model>,
1002 OpenCodeRuntime.OpenCodeRuntimeError
1003 >,
1004 environment?: NodeJS.ProcessEnv,
1005 compatibility: ProviderCompatibilityLookup = noCompatibilityPolicy,
1006): Effect.fn.Return<
1007 ServerProviderDraft,
1008 never,
1009 OpenCodeRuntime.OpenCodeRuntime | OpenCodeServerOwner.OpenCodeServerOwner
1010> {
1011 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
1012 const serverOwner = yield* OpenCodeServerOwner.OpenCodeServerOwner;
1013 const checkedAt = DateTime.formatIso(yield* DateTime.now);
1014 const customModels = openCodeSettings.customModels;
1015 const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
1016​
1017 const fallback = (
1018 cause: unknown,
1019 version: string | null = null,
1020 phase: "version" | "inventory" = "version",
1021 ) => {
1022 const failure = formatOpenCodeProbeError({
1023 cause,
1024 isExternalServer,
1025 phase,
1026 serverUrl: openCodeSettings.serverUrl,
1027 });
1028 return buildServerProvider({
1029 presentation: OPENCODE_PRESENTATION,
1030 enabled: openCodeSettings.enabled,
1031 checkedAt,
1032 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
1033 probe: {
1034 installed: failure.installed,
1035 version,
1036 status: "error",
1037 auth: { status: failure.authStatus ?? "unknown" },
1038 message: failure.message,
1039 },
1040 });
1041 };
1042​
1043 if (!openCodeSettings.enabled) {
1044 return buildServerProvider({
1045 presentation: OPENCODE_PRESENTATION,
1046 enabled: false,
1047 checkedAt,
1048 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
1049 probe: {
1050 installed: false,
1051 version: null,
1052 status: "warning",
1053 auth: { status: "unknown" },
1054 message: isExternalServer
1055 ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
1056 : "OpenCode is disabled in T3 Code settings.",
1057 },
1058 });
1060​
1061 const probedExit = yield* Effect.exit(
1062 probeRuntime.pipe(
1063 Effect.mapError(
1064 (cause) =>
1065 new OpenCodeProbeError({
1066 cause,
1067 detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
1068 }),
1069 ),
1070 ),
1071 );
1072 if (probedExit._tag === "Failure") {
1073 yield* logDiscoveryFailure({ phase: "version", isExternalServer, cause: probedExit.cause });
1074 return fallback(Cause.squash(probedExit.cause));
1076 const probed = probedExit.value;
1077 if (probed.generation === "v2") {
1078 return yield* checkOpenCode2(openCodeSettings, probed.version, checkedAt, loadOpenCode2Models);
1080 const refuseBroken = Effect.fnUntraced(function* (detected: string) {
1081 const broken = brokenVersionDetail({
1082 name: "OpenCode",
1083 version: detected,
1084 advisory: yield* compatibility(ProviderDriverKind.make("opencode"), detected),
1085 });
1086 return broken === undefined
1087 ? undefined
1088 : buildServerProvider({
1089 presentation: OPENCODE_PRESENTATION,
1090 enabled: openCodeSettings.enabled,
1091 checkedAt,
1092 models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),
1093 probe: {
1094 installed: true,
1095 version: detected,
1096 status: "error",
1097 auth: { status: "unknown" },
1098 message: broken,
1099 },
1100 });
1101 });
1102 const refused = yield* refuseBroken(probed.version);
1103 if (refused !== undefined) return refused;
1104​
1105 const installedVersion = isExternalServer ? {} : { installedVersion: probed.version };
1106 let version = probed.version;
1107 const loadInventory = Effect.fnUntraced(function* (server: {
1108 readonly url: string;
1109 readonly serverPassword?: string;
1110 readonly version: string;
1111 }) {
1112 // Preserve the helper's version even when its inventory request fails.
1113 version = server.version;
1114 return yield* openCodeRuntime.loadOpenCodeInventory(
1115 openCodeRuntime.createOpenCodeSdkClient({
1116 baseUrl: server.url,
1117 directory: cwd,
1118 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
1119 }),
1120 );
1121 });
1122 const inventoryEffect = isExternalServer
1123 ? openCodeRuntime
1124 .connectToOpenCodeServer({
1125 binaryPath: openCodeSettings.binaryPath,
1126 directory: cwd,
1127 serverUrl: openCodeSettings.serverUrl,
1128 ...(settingsSecretLiteral(openCodeSettings.serverPassword)
1129 ? { serverPassword: settingsSecretLiteral(openCodeSettings.serverPassword) }
1130 : {}),
1131 ...(environment !== undefined ? { environment } : {}),
1132 })
1133 .pipe(Effect.flatMap(loadInventory), Effect.scoped)
1134 : serverOwner.withServer(loadInventory);
1135 const inventoryExit = yield* Effect.exit(
1136 inventoryEffect.pipe(
1137 Effect.mapError(
1138 (cause) =>
1139 new OpenCodeProbeError({
1140 cause,
1141 detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
1142 }),
1143 ),
1144 ),
1145 );
1146 // The server that answered can differ from the CLI the probe ran.
1147 const refusedServer = version === probed.version ? undefined : yield* refuseBroken(version);
1148 if (refusedServer !== undefined) return { ...refusedServer, ...installedVersion };
1149 if (inventoryExit._tag === "Failure") {
1150 yield* logDiscoveryFailure({
1151 phase: "inventory",
1152 isExternalServer,
1153 version,
1154 cause: inventoryExit.cause,
1155 });
1156 return {
1157 ...fallback(Cause.squash(inventoryExit.cause), version, "inventory"),
1158 ...installedVersion,
1159 };
1161​
1162 const catalogModels = openCodeProviderModels(openCodeSettings, inventoryExit.value);
1163 const models =
1164 catalogModels ??
1165 providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES);
1166 const skills = openCodeSkillsToServerProviderSkills(inventoryExit.value.skills);
1167 const connectedCount = inventoryExit.value.providerList.connected.length;
1168 const catalogReady = connectedCount > 0 && catalogModels !== undefined;
1169 if (connectedCount > 0 && catalogModels === undefined) {
1170 yield* logDiscoveryFailure({ phase: "inventory", isExternalServer, version });
1172 return {
1173 ...buildServerProvider({
1174 presentation: OPENCODE_PRESENTATION,
1175 enabled: true,
1176 checkedAt,
1177 models,
1178 skills,
1179 slashCommands: openCodeCommandsToServerProviderSlashCommands(inventoryExit.value.commands),
1180 probe: {
1181 installed: true,
1182 version,
1183 status: catalogReady ? "ready" : "warning",
1184 auth: {
1185 status: catalogReady ? "authenticated" : "unknown",
1186 type: "opencode",
1187 },
1188 message:
1189 connectedCount > 0 && !catalogReady
1190 ? "OpenCode upstream providers are connected, but it did not list any models yet."
1191 : connectedCount > 0
1192 ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
1193 : isExternalServer
1194 ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
1195 : "OpenCode is available, but it did not report any connected upstream providers.",
1196 },
1197 }),
1198 ...installedVersion,
1199 };
1200});