Open History to see the last commit
1import * as NodeURL from "node:url";
2
3import type { ChatAttachment, ProviderApprovalDecision, RuntimeMode } from "@t3tools/contracts";
4import {
5 createOpencodeClient,
6 type Agent,
7 type FilePartInput,
8 type Model,
9 type OpencodeClient,
10 type PermissionRuleset,
11 type ProviderListResponse,
12 type QuestionAnswer,
13 type QuestionRequest,
14} from "@opencode-ai/sdk/v2";
15import * as Cause from "effect/Cause";
16import * as Context from "effect/Context";
17import * as Data from "effect/Data";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Exit from "effect/Exit";
21import * as Fiber from "effect/Fiber";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as P from "effect/Predicate";
25import * as Ref from "effect/Ref";
26import * as Result from "effect/Result";
27import * as Scope from "effect/Scope";
28import * as Schema from "effect/Schema";
29import * as Stream from "effect/Stream";
30import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
31
32import { isWindowsCommandNotFound } from "../processRunner.ts";
33import { collectStreamAsString } from "./providerSnapshot.ts";
34import * as NetService from "@t3tools/shared/Net";
35import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
36import { resolveSpawnCommand } from "@t3tools/shared/shell";
37const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
38const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
39
40const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
41const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000;
42const DEFAULT_HOSTNAME = "127.0.0.1";
43export interface OpenCodeServerProcess {
44 readonly url: string;
45 readonly exitCode: Effect.Effect<number, never>;
46}
47
48export interface OpenCodeServerConnection {
49 readonly url: string;
50 readonly exitCode: Effect.Effect<number, never> | null;
51 readonly external: boolean;
52}
53
54const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
55export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
56 readonly operation: string;
57 readonly cause?: unknown;
58 readonly detail: string;
59}> {
60 static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
61 P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
62}
63
64function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
65 const result = encodeUnknownJsonStringExit(input);
66 return Exit.isSuccess(result) ? result.value : undefined;
67}
68
69export function openCodeRuntimeErrorDetail(cause: unknown): string {
70 if (OpenCodeRuntimeError.is(cause)) return cause.detail;
71 if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
72 if (cause && typeof cause === "object") {
73 // SDK v2 throws { response, request, error? } shapes — extract what's useful
74 const anyCause = cause as Record<string, unknown>;
75 const status = (anyCause.response as { status?: number } | undefined)?.status;
76 const body = anyCause.error ?? anyCause.data ?? anyCause.body;
77 const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);
78 if (encodedBody) {
79 return `status=${status ?? "?"} body=${encodedBody}`;
80 }
81 }
82 return String(cause);
83}
84
85export const runOpenCodeSdk = <A>(
86 operation: string,
87 fn: () => Promise<A>,
88): Effect.Effect<A, OpenCodeRuntimeError> =>
89 Effect.tryPromise({
90 try: fn,
91 catch: (cause) =>
92 new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
93 }).pipe(Effect.withSpan(`opencode.${operation}`));
94
95export interface OpenCodeCommandResult {
96 readonly stdout: string;
97 readonly stderr: string;
98 readonly code: number;
99}
100
101export interface OpenCodeInventory {
102 readonly providerList: ProviderListResponse;
103 readonly agents: ReadonlyArray<Agent>;
104}
105
106export interface ParsedOpenCodeModelSlug {
107 readonly providerID: string;
108 readonly modelID: string;
109}
110
111export interface OpenCodeRuntimeShape {
112 /**
113 * Spawns a local OpenCode server process. Its lifetime is bound to the caller's
114 * `Scope.Scope` — the child is killed automatically when that scope closes.
115 * Consumers that want a long-lived server must create and hold a scope explicitly
116 * (see {@link Scope.make}) and close it when done.
117 */
118 readonly startOpenCodeServerProcess: (input: {
119 readonly binaryPath: string;
120 readonly environment?: NodeJS.ProcessEnv;
121 readonly port?: number;
122 readonly hostname?: string;
123 readonly timeoutMs?: number;
124 }) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
125 /**
126 * Returns a handle to either an externally-managed OpenCode server (when
127 * `serverUrl` is provided — no lifetime is attached to the caller's scope) or a
128 * freshly spawned local server whose lifetime is bound to the caller's scope.
129 */
130 readonly connectToOpenCodeServer: (input: {
131 readonly binaryPath: string;
132 readonly serverUrl?: string | null;
133 readonly environment?: NodeJS.ProcessEnv;
134 readonly port?: number;
135 readonly hostname?: string;
136 readonly timeoutMs?: number;
137 }) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
138 readonly runOpenCodeCommand: (input: {
139 readonly binaryPath: string;
140 readonly args: ReadonlyArray<string>;
141 readonly environment?: NodeJS.ProcessEnv;
142 }) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
143 readonly createOpenCodeSdkClient: (input: {
144 readonly baseUrl: string;
145 readonly directory: string;
146 readonly serverPassword?: string;
147 }) => OpencodeClient;
148 readonly loadOpenCodeInventory: (
149 client: OpencodeClient,
150 ) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
151 readonly loadInventoryFromCli: (input: {
152 readonly binaryPath: string;
153 readonly environment?: NodeJS.ProcessEnv;
154 }) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
155}
156
157function parseServerUrlFromOutput(output: string): string | null {
158 for (const line of output.split("\n")) {
159 if (!line.startsWith(OPENCODE_SERVER_READY_PREFIX)) {
160 continue;
161 }
162 const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
163 return match?.[1] ?? null;
164 }
165 return null;
166}
167
168const SLUG_LINE_RE = /^(\S+\/\S+)\s*$/;
169const AGENT_HEADER_RE = /^(.+)\s+\((\S+)\)\s*$/;
170
171// Agents that are always hidden in OpenCode but the CLI "agent list" command
172// does not expose the hidden flag. Keep in sync with OpenCode agent
173// definitions (in the OpenCode repo: packages/opencode/src/agent/agent.ts).
174const KNOWN_HIDDEN_AGENTS = new Set(["compaction", "summary", "title"]);
175
176/** @internal */
177export function parseModelsCliOutput(stdout: string): {
178 readonly providers: ReadonlyMap<
179 string,
180 { readonly id: string; readonly name: string; readonly models: { [key: string]: Model } }
181 >;
182 readonly connected: ReadonlyArray<string>;
183} {
184 const providers = new Map<
185 string,
186 { id: string; name: string; models: { [key: string]: Model } }
187 >();
188 const lines = stdout.split("\n");
189 let currentSlug: string | null = null;
190 const jsonLines: Array<string> = [];
191
192 const flushModel = () => {
193 if (currentSlug !== null && jsonLines.length > 0) {
194 const jsonStr = jsonLines.join("\n").trim();
195 if (jsonStr.length > 0) {
196 try {
197 const model = JSON.parse(jsonStr) as Model;
198 const separator = currentSlug.indexOf("/");
199 if (separator > 0) {
200 const providerID = currentSlug.slice(0, separator);
201 const modelID = currentSlug.slice(separator + 1);
202 let provider = providers.get(providerID);
203 if (!provider) {
204 provider = { id: providerID, name: providerID, models: {} };
205 providers.set(providerID, provider);
206 }
207 provider.models[modelID] = model;
208 }
209 } catch {
210 // Skip unparseable model JSON
211 }
212 }
213 }
214 currentSlug = null;
215 jsonLines.length = 0;
216 };
217
218 for (const line of lines) {
219 // A model's JSON body is a single `JSON.stringify` line starting with `{`,
220 // while a provider/model slug is a bare `provider/model` header. Only the
221 // latter can be a slug: without this guard a body line with no interior
222 // whitespace and a `/` in one of its values (e.g. an OpenRouter model whose
223 // `id` is `vendor/model`) matches SLUG_LINE_RE, so flushModel runs against
224 // an empty body and the model is silently dropped.
225 const slugMatch = line.trimStart().startsWith("{") ? null : SLUG_LINE_RE.exec(line);
226 if (slugMatch) {
227 flushModel();
228 currentSlug = slugMatch[1]!;
229 } else if (currentSlug !== null) {
230 jsonLines.push(line);
231 }
232 }
233 flushModel();
234
235 return { providers, connected: [...providers.keys()] };
236}
237
238/** @internal */
239export function parseAgentListCliOutput(stdout: string): ReadonlyArray<Agent> {
240 const agents: Array<Agent> = [];
241 const lines = stdout.split("\n");
242 let currentHeader: { name: string; mode: string } | null = null;
243 const blockLines: Array<string> = [];
244
245 const flushAgent = () => {
246 if (currentHeader !== null) {
247 const jsonStr = blockLines.join("\n").trim();
248 if (jsonStr.length > 0) {
249 try {
250 const permission = JSON.parse(jsonStr);
251 agents.push({
252 name: currentHeader.name,
253 mode: currentHeader.mode as Agent["mode"],
254 hidden: KNOWN_HIDDEN_AGENTS.has(currentHeader.name),
255 permission,
256 options: {},
257 });
258 } catch {
259 // Skip unparseable agent
260 }
261 }
262 }
263 currentHeader = null;
264 blockLines.length = 0;
265 };
266
267 for (const line of lines) {
268 const match = AGENT_HEADER_RE.exec(line);
269 if (match) {
270 flushAgent();
271 currentHeader = { name: match[1]!, mode: match[2]! };
272 } else if (currentHeader !== null) {
273 blockLines.push(line);
274 }
275 }
276 flushAgent();
277
278 return agents;
279}
280
281export function parseOpenCodeModelSlug(
282 slug: string | null | undefined,
283): ParsedOpenCodeModelSlug | null {
284 if (typeof slug !== "string") {
285 return null;
286 }
287
288 const trimmed = slug.trim();
289 const separator = trimmed.indexOf("/");
290 if (separator <= 0 || separator === trimmed.length - 1) {
291 return null;
292 }
293
294 return {
295 providerID: trimmed.slice(0, separator),
296 modelID: trimmed.slice(separator + 1),
297 };
298}
299
300export function openCodeQuestionId(
301 index: number,
302 question: QuestionRequest["questions"][number],
303): string {
304 const header = question.header
305 .trim()
306 .toLowerCase()
307 .replace(/[^a-z0-9_-]+/g, "-");
308 return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
309}
310
311export function toOpenCodeFileParts(input: {
312 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
313 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
314}): Array<FilePartInput> {
315 const parts: Array<FilePartInput> = [];
316
317 for (const attachment of input.attachments ?? []) {
318 const attachmentPath = input.resolveAttachmentPath(attachment);
319 if (!attachmentPath) {
320 continue;
321 }
322
323 parts.push({
324 type: "file",
325 mime: attachment.mimeType,
326 filename: attachment.name,
327 url: NodeURL.pathToFileURL(attachmentPath).href,
328 });
329 }
330
331 return parts;
332}
333
334export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
335 if (runtimeMode === "full-access") {
336 return [{ permission: "*", pattern: "*", action: "allow" }];
337 }
338
339 return [
340 { permission: "*", pattern: "*", action: "ask" },
341 { permission: "bash", pattern: "*", action: "ask" },
342 { permission: "edit", pattern: "*", action: "ask" },
343 { permission: "webfetch", pattern: "*", action: "ask" },
344 { permission: "websearch", pattern: "*", action: "ask" },
345 { permission: "codesearch", pattern: "*", action: "ask" },
346 { permission: "external_directory", pattern: "*", action: "ask" },
347 { permission: "doom_loop", pattern: "*", action: "ask" },
348 { permission: "question", pattern: "*", action: "allow" },
349 ];
350}
351
352export function toOpenCodePermissionReply(
353 decision: ProviderApprovalDecision,
354): "once" | "always" | "reject" {
355 switch (decision) {
356 case "accept":
357 return "once";
358 case "acceptForSession":
359 return "always";
360 case "decline":
361 case "cancel":
362 default:
363 return "reject";
364 }
365}
366
367export function toOpenCodeQuestionAnswers(
368 request: QuestionRequest,
369 answers: Record<string, unknown>,
370): Array<QuestionAnswer> {
371 return request.questions.map((question, index) => {
372 const raw =
373 answers[openCodeQuestionId(index, question)] ??
374 answers[question.header] ??
375 answers[question.question];
376 if (Array.isArray(raw)) {
377 return raw.filter((value): value is string => typeof value === "string");
378 }
379 if (typeof raw === "string") {
380 return raw.trim().length > 0 ? [raw] : [];
381 }
382 return [];
383 });
384}
385
386function ensureRuntimeError(
387 operation: OpenCodeRuntimeError["operation"],
388 detail: string,
389 cause: unknown,
390): OpenCodeRuntimeError {
391 return OpenCodeRuntimeError.is(cause)
392 ? cause
393 : new OpenCodeRuntimeError({ operation, detail, cause });
394}
395
396const makeOpenCodeRuntime = Effect.gen(function* () {
397 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
398 const netService = yield* NetService.NetService;
399 const hostPlatform = yield* HostProcessPlatform;
400 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
401 resolveSpawnCommand(command, args, env ? { env } : {});
402
403 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
404 Effect.gen(function* () {
405 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
406 const child = yield* spawner.spawn(
407 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
408 shell: spawnCommand.shell,
409 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
410 }),
411 );
412 const [stdout, stderr, code] = yield* Effect.all(
413 [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],
414 { concurrency: "unbounded" },
415 );
416 const exitCode = Number(code);
417 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
418 return yield* new OpenCodeRuntimeError({
419 operation: "runOpenCodeCommand",
420 detail: `spawn ${input.binaryPath} ENOENT`,
421 });
422 }
423 return {
424 stdout,
425 stderr,
426 code: exitCode,
427 } satisfies OpenCodeCommandResult;
428 }).pipe(
429 Effect.scoped,
430 Effect.mapError((cause) =>
431 ensureRuntimeError(
432 "runOpenCodeCommand",
433 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
434 cause,
435 ),
436 ),
437 );
438
439 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
440 Effect.gen(function* () {
441 // Bind this server's lifetime to the caller's scope. When the caller's
442 // scope closes, the spawned child is killed and all associated fibers
443 // are interrupted automatically — no `close()` method needed.
444 const runtimeScope = yield* Scope.Scope;
445
446 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
447 const port =
448 input.port ??
449 (yield* netService.findAvailablePort(0).pipe(
450 Effect.mapError(
451 (cause) =>
452 new OpenCodeRuntimeError({
453 operation: "startOpenCodeServerProcess",
454 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
455 cause,
456 }),
457 ),
458 ));
459 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
460 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
461 const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
462
463 const child = yield* spawner
464 .spawn(
465 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
466 detached: hostPlatform !== "win32",
467 shell: spawnCommand.shell,
468 env: {
469 ...input.environment,
470 OPENCODE_CONFIG_CONTENT: OPENCODE_EMPTY_CONFIG_CONTENT,
471 },
472 extendEnv: input.environment === undefined,
473 }),
474 )
475 .pipe(
476 Effect.provideService(Scope.Scope, runtimeScope),
477 Effect.mapError(
478 (cause) =>
479 new OpenCodeRuntimeError({
480 operation: "startOpenCodeServerProcess",
481 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
482 cause,
483 }),
484 ),
485 );
486
487 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
488 hostPlatform === "win32"
489 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
490 : Effect.sync(() => {
491 try {
492 process.kill(-Number(child.pid), signal);
493 } catch {
494 // The direct child may already have exited after starting the
495 // server; the process group kill is best-effort cleanup for
496 // any serve process left in that group.
497 }
498 });
499 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
500 Effect.andThen(Effect.sleep("1 second")),
501 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
502 Effect.ignore,
503 );
504 yield* Scope.addFinalizer(runtimeScope, terminateChild);
505
506 const stdoutRef = yield* Ref.make("");
507 const stderrRef = yield* Ref.make("");
508 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
509
510 const setReadyFromStdoutChunk = (chunk: string) =>
511 Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(
512 Effect.flatMap((nextStdout) => {
513 const parsed = parseServerUrlFromOutput(nextStdout);
514 return parsed
515 ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)
516 : Effect.void;
517 }),
518 );
519
520 const stdoutFiber = yield* child.stdout.pipe(
521 Stream.decodeText(),
522 Stream.runForEach(setReadyFromStdoutChunk),
523 Effect.ignore,
524 Effect.forkIn(runtimeScope),
525 );
526 const stderrFiber = yield* child.stderr.pipe(
527 Stream.decodeText(),
528 Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),
529 Effect.ignore,
530 Effect.forkIn(runtimeScope),
531 );
532
533 const exitFiber = yield* child.exitCode.pipe(
534 Effect.flatMap((code) =>
535 Effect.gen(function* () {
536 const stdout = yield* Ref.get(stdoutRef);
537 const stderr = yield* Ref.get(stderrRef);
538 const exitCode = Number(code);
539 yield* Deferred.fail(
540 readyDeferred,
541 new OpenCodeRuntimeError({
542 operation: "startOpenCodeServerProcess",
543 detail: [
544 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
545 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
546 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
547 ]
548 .filter(Boolean)
549 .join("\n\n"),
550 cause: { exitCode, stdout, stderr },
551 }),
552 ).pipe(Effect.ignore);
553 }),
554 ),
555 Effect.ignore,
556 Effect.forkIn(runtimeScope),
557 );
558
559 const readyExit = yield* Effect.exit(
560 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
561 );
562
563 // Startup-time fibers are no longer needed once ready has resolved (either
564 // way). The exit fiber is only interrupted on failure; on success it keeps
565 // the caller's `exitCode` effect observable until the scope closes.
566 yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);
567 yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);
568
569 if (Exit.isFailure(readyExit)) {
570 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
571 const squashed = Cause.squash(readyExit.cause);
572 return yield* ensureRuntimeError(
573 "startOpenCodeServerProcess",
574 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
575 squashed,
576 );
577 }
578
579 const readyOption = readyExit.value;
580 if (Option.isNone(readyOption)) {
581 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
582 return yield* new OpenCodeRuntimeError({
583 operation: "startOpenCodeServerProcess",
584 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
585 });
586 }
587
588 return {
589 url: readyOption.value,
590 exitCode: child.exitCode.pipe(
591 Effect.map(Number),
592 Effect.orElseSucceed(() => 0),
593 ),
594 } satisfies OpenCodeServerProcess;
595 });
596
597 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
598 const serverUrl = input.serverUrl?.trim();
599 if (serverUrl) {
600 // We don't own externally-configured servers — no scope interaction.
601 return Effect.succeed({
602 url: serverUrl,
603 exitCode: null,
604 external: true,
605 });
606 }
607
608 return startOpenCodeServerProcess({
609 binaryPath: input.binaryPath,
610 ...(input.environment !== undefined ? { environment: input.environment } : {}),
611 ...(input.port !== undefined ? { port: input.port } : {}),
612 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
613 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
614 }).pipe(
615 Effect.map((server) => ({
616 url: server.url,
617 exitCode: server.exitCode,
618 external: false,
619 })),
620 );
621 };
622
623 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
624 createOpencodeClient({
625 baseUrl: input.baseUrl,
626 directory: input.directory,
627 ...(input.serverPassword
628 ? {
629 headers: {
630 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
631 },
632 }
633 : {}),
634 throwOnError: true,
635 });
636
637 const loadProviders = (client: OpencodeClient) =>
638 runOpenCodeSdk("provider.list", () => client.provider.list()).pipe(
639 Effect.filterMapOrFail(
640 (list) =>
641 list.data
642 ? Result.succeed(list.data)
643 : Result.fail(
644 new OpenCodeRuntimeError({
645 operation: "provider.list",
646 detail: "OpenCode provider list was empty.",
647 }),
648 ),
649 (result) => result,
650 ),
651 );
652
653 const loadAgents = (client: OpencodeClient) =>
654 runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
655 Effect.map((result) => result.data ?? []),
656 );
657
658 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
659 Effect.all([loadProviders(client), loadAgents(client)], { concurrency: "unbounded" }).pipe(
660 Effect.map(([providerList, agents]) => ({ providerList, agents })),
661 );
662
663 const loadInventoryFromCli: OpenCodeRuntimeShape["loadInventoryFromCli"] = (input) =>
664 Effect.gen(function* () {
665 const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
666
667 const runModelsCli = () =>
668 runOpenCodeCommand({
669 binaryPath: input.binaryPath,
670 args: ["models", "--verbose"],
671 ...env,
672 }).pipe(Effect.exit);
673 const runAgentsCli = () =>
674 runOpenCodeCommand({ binaryPath: input.binaryPath, args: ["agent", "list"], ...env }).pipe(
675 Effect.exit,
676 );
677
678 // First attempt — run both in parallel
679 let [modelsResult, agentsResult] = yield* Effect.all([runModelsCli(), runAgentsCli()], {
680 concurrency: "unbounded",
681 });
682
683 // Retry once after 1s on transient failures (e.g. SQLite "database is locked")
684 const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
685 const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
686 if (needsModelsRetry || needsAgentsRetry) {
687 yield* Effect.sleep("1 second");
688 const [m2, a2] = yield* Effect.all(
689 [
690 needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
691 needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
692 ],
693 { concurrency: "unbounded" },
694 );
695 modelsResult = m2;
696 agentsResult = a2;
697 }
698
699 if (modelsResult._tag === "Failure") {
700 const cause = Cause.squash(modelsResult.cause);
701 return yield* ensureRuntimeError(
702 "loadInventoryFromCli",
703 `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
704 cause,
705 );
706 }
707 if (modelsResult.value.code !== 0) {
708 return yield* new OpenCodeRuntimeError({
709 operation: "loadInventoryFromCli",
710 detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
711 });
712 }
713
714 const parsed = parseModelsCliOutput(modelsResult.value.stdout);
715 const connected = [...parsed.connected];
716 const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
717 (provider) => ({
718 id: provider.id,
719 name: provider.name,
720 source: "config" as const,
721 env: [],
722 options: {},
723 models: provider.models,
724 }),
725 );
726
727 // Agent metadata enriches model capabilities but is not required for an
728 // authoritative model inventory, so it may still degrade to an empty list.
729 let agents: ReadonlyArray<Agent> = [];
730 if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
731 agents = parseAgentListCliOutput(agentsResult.value.stdout);
732 }
733
734 return {
735 providerList: { all: allProviders, default: {}, connected },
736 agents,
737 };
738 });
739
740 return {
741 startOpenCodeServerProcess,
742 connectToOpenCodeServer,
743 runOpenCodeCommand,
744 createOpenCodeSdkClient,
745 loadOpenCodeInventory,
746 loadInventoryFromCli,
747 } satisfies OpenCodeRuntimeShape;
748});
749
750export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
751 "t3/provider/opencodeRuntime",
752) {}
753
754export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
755 Layer.provide(NetService.layer),
756);