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