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

opencodeRuntime.ts

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