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

opencodeRuntime.ts

750 lines25.7 KB

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.UnknownFromJsonString);
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>;
47​
48export interface OpenCodeServerConnection {
49 readonly url: string;
50 readonly exitCode: Effect.Effect<number, never> | null;
51 readonly external: boolean;
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);
63​
64function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
65 const result = encodeUnknownJsonStringExit(input);
66 return Exit.isSuccess(result) ? result.value : undefined;
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);
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;
100​
101export interface OpenCodeInventory {
102 readonly providerList: ProviderListResponse;
103 readonly agents: ReadonlyArray<Agent>;
105​
106export interface ParsedOpenCodeModelSlug {
107 readonly providerID: string;
108 readonly modelID: string;
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>;
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;
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 const slugMatch = SLUG_LINE_RE.exec(line);
220 if (slugMatch) {
221 flushModel();
222 currentSlug = slugMatch[1]!;
223 } else if (currentSlug !== null) {
224 jsonLines.push(line);
225 }
226 }
227 flushModel();
228​
229 return { providers, connected: [...providers.keys()] };
231​
232/** @internal */
233export function parseAgentListCliOutput(stdout: string): ReadonlyArray<Agent> {
234 const agents: Array<Agent> = [];
235 const lines = stdout.split("\n");
236 let currentHeader: { name: string; mode: string } | null = null;
237 const blockLines: Array<string> = [];
238​
239 const flushAgent = () => {
240 if (currentHeader !== null) {
241 const jsonStr = blockLines.join("\n").trim();
242 if (jsonStr.length > 0) {
243 try {
244 const permission = JSON.parse(jsonStr);
245 agents.push({
246 name: currentHeader.name,
247 mode: currentHeader.mode as Agent["mode"],
248 hidden: KNOWN_HIDDEN_AGENTS.has(currentHeader.name),
249 permission,
250 options: {},
251 });
252 } catch {
253 // Skip unparseable agent
254 }
255 }
256 }
257 currentHeader = null;
258 blockLines.length = 0;
259 };
260​
261 for (const line of lines) {
262 const match = AGENT_HEADER_RE.exec(line);
263 if (match) {
264 flushAgent();
265 currentHeader = { name: match[1]!, mode: match[2]! };
266 } else if (currentHeader !== null) {
267 blockLines.push(line);
268 }
269 }
270 flushAgent();
271​
272 return agents;
274​
275export function parseOpenCodeModelSlug(
276 slug: string | null | undefined,
277): ParsedOpenCodeModelSlug | null {
278 if (typeof slug !== "string") {
279 return null;
280 }
281​
282 const trimmed = slug.trim();
283 const separator = trimmed.indexOf("/");
284 if (separator <= 0 || separator === trimmed.length - 1) {
285 return null;
286 }
287​
288 return {
289 providerID: trimmed.slice(0, separator),
290 modelID: trimmed.slice(separator + 1),
291 };
293​
294export function openCodeQuestionId(
295 index: number,
296 question: QuestionRequest["questions"][number],
297): string {
298 const header = question.header
299 .trim()
300 .toLowerCase()
301 .replace(/[^a-z0-9_-]+/g, "-");
302 return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
304​
305export function toOpenCodeFileParts(input: {
306 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
307 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
308}): Array<FilePartInput> {
309 const parts: Array<FilePartInput> = [];
310​
311 for (const attachment of input.attachments ?? []) {
312 const attachmentPath = input.resolveAttachmentPath(attachment);
313 if (!attachmentPath) {
314 continue;
315 }
316​
317 parts.push({
318 type: "file",
319 mime: attachment.mimeType,
320 filename: attachment.name,
321 url: NodeURL.pathToFileURL(attachmentPath).href,
322 });
323 }
324​
325 return parts;
327​
328export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
329 if (runtimeMode === "full-access") {
330 return [{ permission: "*", pattern: "*", action: "allow" }];
331 }
332​
333 return [
334 { permission: "*", pattern: "*", action: "ask" },
335 { permission: "bash", pattern: "*", action: "ask" },
336 { permission: "edit", pattern: "*", action: "ask" },
337 { permission: "webfetch", pattern: "*", action: "ask" },
338 { permission: "websearch", pattern: "*", action: "ask" },
339 { permission: "codesearch", pattern: "*", action: "ask" },
340 { permission: "external_directory", pattern: "*", action: "ask" },
341 { permission: "doom_loop", pattern: "*", action: "ask" },
342 { permission: "question", pattern: "*", action: "allow" },
343 ];
345​
346export function toOpenCodePermissionReply(
347 decision: ProviderApprovalDecision,
348): "once" | "always" | "reject" {
349 switch (decision) {
350 case "accept":
351 return "once";
352 case "acceptForSession":
353 return "always";
354 case "decline":
355 case "cancel":
356 default:
357 return "reject";
358 }
360​
361export function toOpenCodeQuestionAnswers(
362 request: QuestionRequest,
363 answers: Record<string, unknown>,
364): Array<QuestionAnswer> {
365 return request.questions.map((question, index) => {
366 const raw =
367 answers[openCodeQuestionId(index, question)] ??
368 answers[question.header] ??
369 answers[question.question];
370 if (Array.isArray(raw)) {
371 return raw.filter((value): value is string => typeof value === "string");
372 }
373 if (typeof raw === "string") {
374 return raw.trim().length > 0 ? [raw] : [];
375 }
376 return [];
377 });
379​
380function ensureRuntimeError(
381 operation: OpenCodeRuntimeError["operation"],
382 detail: string,
383 cause: unknown,
384): OpenCodeRuntimeError {
385 return OpenCodeRuntimeError.is(cause)
386 ? cause
387 : new OpenCodeRuntimeError({ operation, detail, cause });
389​
390const makeOpenCodeRuntime = Effect.gen(function* () {
391 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
392 const netService = yield* NetService.NetService;
393 const hostPlatform = yield* HostProcessPlatform;
394 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
395 resolveSpawnCommand(command, args, env ? { env } : {});
396​
397 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
398 Effect.gen(function* () {
399 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
400 const child = yield* spawner.spawn(
401 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
402 shell: spawnCommand.shell,
403 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
404 }),
405 );
406 const [stdout, stderr, code] = yield* Effect.all(
407 [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],
408 { concurrency: "unbounded" },
409 );
410 const exitCode = Number(code);
411 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
412 return yield* new OpenCodeRuntimeError({
413 operation: "runOpenCodeCommand",
414 detail: `spawn ${input.binaryPath} ENOENT`,
415 });
416 }
417 return {
418 stdout,
419 stderr,
420 code: exitCode,
421 } satisfies OpenCodeCommandResult;
422 }).pipe(
423 Effect.scoped,
424 Effect.mapError((cause) =>
425 ensureRuntimeError(
426 "runOpenCodeCommand",
427 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
428 cause,
429 ),
430 ),
431 );
432​
433 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
434 Effect.gen(function* () {
435 // Bind this server's lifetime to the caller's scope. When the caller's
436 // scope closes, the spawned child is killed and all associated fibers
437 // are interrupted automatically — no `close()` method needed.
438 const runtimeScope = yield* Scope.Scope;
439​
440 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
441 const port =
442 input.port ??
443 (yield* netService.findAvailablePort(0).pipe(
444 Effect.mapError(
445 (cause) =>
446 new OpenCodeRuntimeError({
447 operation: "startOpenCodeServerProcess",
448 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
449 cause,
450 }),
451 ),
452 ));
453 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
454 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
455 const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
456​
457 const child = yield* spawner
458 .spawn(
459 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
460 detached: hostPlatform !== "win32",
461 shell: spawnCommand.shell,
462 env: {
463 ...input.environment,
464 OPENCODE_CONFIG_CONTENT: OPENCODE_EMPTY_CONFIG_CONTENT,
465 },
466 extendEnv: input.environment === undefined,
467 }),
468 )
469 .pipe(
470 Effect.provideService(Scope.Scope, runtimeScope),
471 Effect.mapError(
472 (cause) =>
473 new OpenCodeRuntimeError({
474 operation: "startOpenCodeServerProcess",
475 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
476 cause,
477 }),
478 ),
479 );
480​
481 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
482 hostPlatform === "win32"
483 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
484 : Effect.sync(() => {
485 try {
486 process.kill(-Number(child.pid), signal);
487 } catch {
488 // The direct child may already have exited after starting the
489 // server; the process group kill is best-effort cleanup for
490 // any serve process left in that group.
491 }
492 });
493 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
494 Effect.andThen(Effect.sleep("1 second")),
495 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
496 Effect.ignore,
497 );
498 yield* Scope.addFinalizer(runtimeScope, terminateChild);
499​
500 const stdoutRef = yield* Ref.make("");
501 const stderrRef = yield* Ref.make("");
502 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
503​
504 const setReadyFromStdoutChunk = (chunk: string) =>
505 Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(
506 Effect.flatMap((nextStdout) => {
507 const parsed = parseServerUrlFromOutput(nextStdout);
508 return parsed
509 ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)
510 : Effect.void;
511 }),
512 );
513​
514 const stdoutFiber = yield* child.stdout.pipe(
515 Stream.decodeText(),
516 Stream.runForEach(setReadyFromStdoutChunk),
517 Effect.ignore,
518 Effect.forkIn(runtimeScope),
519 );
520 const stderrFiber = yield* child.stderr.pipe(
521 Stream.decodeText(),
522 Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),
523 Effect.ignore,
524 Effect.forkIn(runtimeScope),
525 );
526​
527 const exitFiber = yield* child.exitCode.pipe(
528 Effect.flatMap((code) =>
529 Effect.gen(function* () {
530 const stdout = yield* Ref.get(stdoutRef);
531 const stderr = yield* Ref.get(stderrRef);
532 const exitCode = Number(code);
533 yield* Deferred.fail(
534 readyDeferred,
535 new OpenCodeRuntimeError({
536 operation: "startOpenCodeServerProcess",
537 detail: [
538 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
539 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
540 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
541 ]
542 .filter(Boolean)
543 .join("\n\n"),
544 cause: { exitCode, stdout, stderr },
545 }),
546 ).pipe(Effect.ignore);
547 }),
548 ),
549 Effect.ignore,
550 Effect.forkIn(runtimeScope),
551 );
552​
553 const readyExit = yield* Effect.exit(
554 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
555 );
556​
557 // Startup-time fibers are no longer needed once ready has resolved (either
558 // way). The exit fiber is only interrupted on failure; on success it keeps
559 // the caller's `exitCode` effect observable until the scope closes.
560 yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);
561 yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);
562​
563 if (Exit.isFailure(readyExit)) {
564 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
565 const squashed = Cause.squash(readyExit.cause);
566 return yield* ensureRuntimeError(
567 "startOpenCodeServerProcess",
568 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
569 squashed,
570 );
571 }
572​
573 const readyOption = readyExit.value;
574 if (Option.isNone(readyOption)) {
575 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
576 return yield* new OpenCodeRuntimeError({
577 operation: "startOpenCodeServerProcess",
578 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
579 });
580 }
581​
582 return {
583 url: readyOption.value,
584 exitCode: child.exitCode.pipe(
585 Effect.map(Number),
586 Effect.orElseSucceed(() => 0),
587 ),
588 } satisfies OpenCodeServerProcess;
589 });
590​
591 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
592 const serverUrl = input.serverUrl?.trim();
593 if (serverUrl) {
594 // We don't own externally-configured servers — no scope interaction.
595 return Effect.succeed({
596 url: serverUrl,
597 exitCode: null,
598 external: true,
599 });
600 }
601​
602 return startOpenCodeServerProcess({
603 binaryPath: input.binaryPath,
604 ...(input.environment !== undefined ? { environment: input.environment } : {}),
605 ...(input.port !== undefined ? { port: input.port } : {}),
606 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
607 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
608 }).pipe(
609 Effect.map((server) => ({
610 url: server.url,
611 exitCode: server.exitCode,
612 external: false,
613 })),
614 );
615 };
616​
617 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
618 createOpencodeClient({
619 baseUrl: input.baseUrl,
620 directory: input.directory,
621 ...(input.serverPassword
622 ? {
623 headers: {
624 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
625 },
626 }
627 : {}),
628 throwOnError: true,
629 });
630​
631 const loadProviders = (client: OpencodeClient) =>
632 runOpenCodeSdk("provider.list", () => client.provider.list()).pipe(
633 Effect.filterMapOrFail(
634 (list) =>
635 list.data
636 ? Result.succeed(list.data)
637 : Result.fail(
638 new OpenCodeRuntimeError({
639 operation: "provider.list",
640 detail: "OpenCode provider list was empty.",
641 }),
642 ),
643 (result) => result,
644 ),
645 );
646​
647 const loadAgents = (client: OpencodeClient) =>
648 runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
649 Effect.map((result) => result.data ?? []),
650 );
651​
652 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
653 Effect.all([loadProviders(client), loadAgents(client)], { concurrency: "unbounded" }).pipe(
654 Effect.map(([providerList, agents]) => ({ providerList, agents })),
655 );
656​
657 const loadInventoryFromCli: OpenCodeRuntimeShape["loadInventoryFromCli"] = (input) =>
658 Effect.gen(function* () {
659 const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
660​
661 const runModelsCli = () =>
662 runOpenCodeCommand({
663 binaryPath: input.binaryPath,
664 args: ["models", "--verbose"],
665 ...env,
666 }).pipe(Effect.exit);
667 const runAgentsCli = () =>
668 runOpenCodeCommand({ binaryPath: input.binaryPath, args: ["agent", "list"], ...env }).pipe(
669 Effect.exit,
670 );
671​
672 // First attempt — run both in parallel
673 let [modelsResult, agentsResult] = yield* Effect.all([runModelsCli(), runAgentsCli()], {
674 concurrency: "unbounded",
675 });
676​
677 // Retry once after 1s on transient failures (e.g. SQLite "database is locked")
678 const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
679 const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
680 if (needsModelsRetry || needsAgentsRetry) {
681 yield* Effect.sleep("1 second");
682 const [m2, a2] = yield* Effect.all(
683 [
684 needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
685 needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
686 ],
687 { concurrency: "unbounded" },
688 );
689 modelsResult = m2;
690 agentsResult = a2;
691 }
692​
693 if (modelsResult._tag === "Failure") {
694 const cause = Cause.squash(modelsResult.cause);
695 return yield* ensureRuntimeError(
696 "loadInventoryFromCli",
697 `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
698 cause,
699 );
700 }
701 if (modelsResult.value.code !== 0) {
702 return yield* new OpenCodeRuntimeError({
703 operation: "loadInventoryFromCli",
704 detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
705 });
706 }
707​
708 const parsed = parseModelsCliOutput(modelsResult.value.stdout);
709 const connected = [...parsed.connected];
710 const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
711 (provider) => ({
712 id: provider.id,
713 name: provider.name,
714 source: "config" as const,
715 env: [],
716 options: {},
717 models: provider.models,
718 }),
719 );
720​
721 // Agent metadata enriches model capabilities but is not required for an
722 // authoritative model inventory, so it may still degrade to an empty list.
723 let agents: ReadonlyArray<Agent> = [];
724 if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
725 agents = parseAgentListCliOutput(agentsResult.value.stdout);
726 }
727​
728 return {
729 providerList: { all: allProviders, default: {}, connected },
730 agents,
731 };
732 });
733​
734 return {
735 startOpenCodeServerProcess,
736 connectToOpenCodeServer,
737 runOpenCodeCommand,
738 createOpenCodeSdkClient,
739 loadOpenCodeInventory,
740 loadInventoryFromCli,
741 } satisfies OpenCodeRuntimeShape;
742});
743​
744export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
745 "t3/provider/opencodeRuntime",
746) {}
747​
748export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
749 Layer.provide(NetService.layer),
750);