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