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";
54export interface OpenCodeServerProcess {
55 readonly url: string;
56 readonly exitCode: Effect.Effect<number, never>;
57}
58
59export interface OpenCodeServerConnection {
60 readonly url: string;
61 readonly exitCode: Effect.Effect<number, never> | null;
62 readonly external: boolean;
63}
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);
73}
74
75function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
76 const result = encodeUnknownJsonStringExit(input);
77 return Exit.isSuccess(result) ? result.value : undefined;
78}
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);
94}
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;
110}
111
112export interface OpenCodeInventory {
113 readonly providerList: ProviderListResponse;
114 readonly agents: ReadonlyArray<Agent>;
115 readonly skills: ReadonlyArray<OpenCodeSkill>;
116}
117
118export interface ParsedOpenCodeModelSlug {
119 readonly providerID: string;
120 readonly modelID: string;
121}
122
123export interface OpenCodeSkill {
124 readonly name?: string | null;
125 readonly description?: string | null;
126 readonly location?: string | null;
127 readonly content?: 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 content: Schema.optionalKey(Schema.NullOr(Schema.String)),
135});
136const decodeOpenCodeSkillsCliOutputExit = Schema.decodeUnknownExit(
137 Schema.fromJsonString(Schema.Array(OpenCodeSkillSchema)),
138);
139
140export interface OpenCodeRuntimeShape {
141 /**
142 * Spawns a local OpenCode server process. Its lifetime is bound to the caller's
143 * `Scope.Scope` — the child is killed automatically when that scope closes.
144 * Consumers that want a long-lived server must create and hold a scope explicitly
145 * (see {@link Scope.make}) and close it when done.
146 */
147 readonly startOpenCodeServerProcess: (input: {
148 readonly binaryPath: string;
149 readonly environment?: NodeJS.ProcessEnv;
150 readonly port?: number;
151 readonly hostname?: string;
152 readonly timeoutMs?: number;
153 }) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
154 /**
155 * Returns a handle to either an externally-managed OpenCode server (when
156 * `serverUrl` is provided — no lifetime is attached to the caller's scope) or a
157 * freshly spawned local server whose lifetime is bound to the caller's scope.
158 */
159 readonly connectToOpenCodeServer: (input: {
160 readonly binaryPath: string;
161 readonly serverUrl?: string | null;
162 readonly environment?: NodeJS.ProcessEnv;
163 readonly port?: number;
164 readonly hostname?: string;
165 readonly timeoutMs?: number;
166 }) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
167 readonly runOpenCodeCommand: (input: {
168 readonly binaryPath: string;
169 readonly args: ReadonlyArray<string>;
170 readonly environment?: NodeJS.ProcessEnv;
171 readonly cwd?: string;
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 return [
377 { permission: "*", pattern: "*", action: "ask" },
378 { permission: "bash", pattern: "*", action: "ask" },
379 { permission: "edit", pattern: "*", action: "ask" },
380 { permission: "webfetch", pattern: "*", action: "ask" },
381 { permission: "websearch", pattern: "*", action: "ask" },
382 { permission: "codesearch", pattern: "*", action: "ask" },
383 { permission: "external_directory", pattern: "*", action: "ask" },
384 { permission: "doom_loop", pattern: "*", action: "ask" },
385 { permission: "question", pattern: "*", action: "allow" },
386 ];
387}
388
389export function toOpenCodePermissionReply(
390 decision: ProviderApprovalDecision,
391): "once" | "always" | "reject" {
392 switch (decision) {
393 case "accept":
394 return "once";
395 case "acceptForSession":
396 return "always";
397 case "decline":
398 case "cancel":
399 default:
400 return "reject";
401 }
402}
403
404export function toOpenCodeQuestionAnswers(
405 request: QuestionRequest,
406 answers: Record<string, unknown>,
407): Array<QuestionAnswer> {
408 return request.questions.map((question, index) => {
409 const raw =
410 answers[openCodeQuestionId(index, question)] ??
411 answers[question.header] ??
412 answers[question.question];
413 if (Array.isArray(raw)) {
414 return raw.filter((value): value is string => typeof value === "string");
415 }
416 if (typeof raw === "string") {
417 return raw.trim().length > 0 ? [raw] : [];
418 }
419 return [];
420 });
421}
422
423function ensureRuntimeError(
424 operation: OpenCodeRuntimeError["operation"],
425 detail: string,
426 cause: unknown,
427): OpenCodeRuntimeError {
428 return OpenCodeRuntimeError.is(cause)
429 ? cause
430 : new OpenCodeRuntimeError({ operation, detail, cause });
431}
432
433const makeOpenCodeRuntime = Effect.gen(function* () {
434 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
435 const netService = yield* NetService.NetService;
436 const hostPlatform = yield* HostProcessPlatform;
437 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
438 resolveSpawnCommand(command, args, env ? { env } : {});
439
440 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
441 Effect.gen(function* () {
442 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
443 const child = yield* spawner.spawn(
444 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
445 shell: spawnCommand.shell,
446 ...(input.cwd ? { cwd: input.cwd } : {}),
447 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
448 }),
449 );
450 const [stdout, stderr, code] = yield* Effect.all(
451 [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],
452 { concurrency: "unbounded" },
453 );
454 const exitCode = Number(code);
455 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
456 return yield* new OpenCodeRuntimeError({
457 operation: "runOpenCodeCommand",
458 detail: `spawn ${input.binaryPath} ENOENT`,
459 });
460 }
461 return {
462 stdout,
463 stderr,
464 code: exitCode,
465 } satisfies OpenCodeCommandResult;
466 }).pipe(
467 Effect.scoped,
468 Effect.mapError((cause) =>
469 ensureRuntimeError(
470 "runOpenCodeCommand",
471 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
472 cause,
473 ),
474 ),
475 );
476
477 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
478 Effect.gen(function* () {
479 // Bind this server's lifetime to the caller's scope. When the caller's
480 // scope closes, the spawned child is killed and all associated fibers
481 // are interrupted automatically — no `close()` method needed.
482 const runtimeScope = yield* Scope.Scope;
483
484 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
485 const port =
486 input.port ??
487 (yield* netService.findAvailablePort(0).pipe(
488 Effect.mapError(
489 (cause) =>
490 new OpenCodeRuntimeError({
491 operation: "startOpenCodeServerProcess",
492 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
493 cause,
494 }),
495 ),
496 ));
497 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
498 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
499 const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
500
501 const child = yield* spawner
502 .spawn(
503 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
504 detached: hostPlatform !== "win32",
505 shell: spawnCommand.shell,
506 env: {
507 ...input.environment,
508 // Respect an OPENCODE_CONFIG_CONTENT provided by the caller or
509 // the inherited process environment, only falling back to the
510 // empty config when neither is set. Setting it unconditionally
511 // previously clobbered the user's opencode config, hiding their
512 // providers/models. The value is set explicitly (rather than
513 // relying on inheritance) because `extendEnv` is false whenever
514 // `input.environment` is provided.
515 OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
516 },
517 extendEnv: input.environment === undefined,
518 }),
519 )
520 .pipe(
521 Effect.provideService(Scope.Scope, runtimeScope),
522 Effect.mapError(
523 (cause) =>
524 new OpenCodeRuntimeError({
525 operation: "startOpenCodeServerProcess",
526 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
527 cause,
528 }),
529 ),
530 );
531
532 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
533 hostPlatform === "win32"
534 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
535 : Effect.sync(() => {
536 try {
537 process.kill(-Number(child.pid), signal);
538 } catch {
539 // The direct child may already have exited after starting the
540 // server; the process group kill is best-effort cleanup for
541 // any serve process left in that group.
542 }
543 });
544 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
545 Effect.andThen(Effect.sleep("1 second")),
546 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
547 Effect.ignore,
548 );
549 yield* Scope.addFinalizer(runtimeScope, terminateChild);
550
551 const stdoutRef = yield* Ref.make("");
552 const stderrRef = yield* Ref.make("");
553 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
554
555 const setReadyFromStdoutChunk = (chunk: string) =>
556 Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(
557 Effect.flatMap((nextStdout) => {
558 const parsed = parseServerUrlFromOutput(nextStdout);
559 return parsed
560 ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)
561 : Effect.void;
562 }),
563 );
564
565 const stdoutFiber = yield* child.stdout.pipe(
566 Stream.decodeText(),
567 Stream.runForEach(setReadyFromStdoutChunk),
568 Effect.ignore,
569 Effect.forkIn(runtimeScope),
570 );
571 const stderrFiber = yield* child.stderr.pipe(
572 Stream.decodeText(),
573 Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),
574 Effect.ignore,
575 Effect.forkIn(runtimeScope),
576 );
577
578 const exitFiber = yield* child.exitCode.pipe(
579 Effect.flatMap((code) =>
580 Effect.gen(function* () {
581 const stdout = yield* Ref.get(stdoutRef);
582 const stderr = yield* Ref.get(stderrRef);
583 const exitCode = Number(code);
584 yield* Deferred.fail(
585 readyDeferred,
586 new OpenCodeRuntimeError({
587 operation: "startOpenCodeServerProcess",
588 detail: [
589 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
590 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
591 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
592 ]
593 .filter(Boolean)
594 .join("\n\n"),
595 cause: { exitCode, stdout, stderr },
596 }),
597 ).pipe(Effect.ignore);
598 }),
599 ),
600 Effect.ignore,
601 Effect.forkIn(runtimeScope),
602 );
603
604 const readyExit = yield* Effect.exit(
605 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
606 );
607
608 // Startup-time fibers are no longer needed once ready has resolved (either
609 // way). The exit fiber is only interrupted on failure; on success it keeps
610 // the caller's `exitCode` effect observable until the scope closes.
611 yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);
612 yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);
613
614 if (Exit.isFailure(readyExit)) {
615 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
616 const squashed = Cause.squash(readyExit.cause);
617 return yield* ensureRuntimeError(
618 "startOpenCodeServerProcess",
619 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
620 squashed,
621 );
622 }
623
624 const readyOption = readyExit.value;
625 if (Option.isNone(readyOption)) {
626 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
627 return yield* new OpenCodeRuntimeError({
628 operation: "startOpenCodeServerProcess",
629 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
630 });
631 }
632
633 return {
634 url: readyOption.value,
635 exitCode: child.exitCode.pipe(
636 Effect.map(Number),
637 Effect.orElseSucceed(() => 0),
638 ),
639 } satisfies OpenCodeServerProcess;
640 });
641
642 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
643 const serverUrl = input.serverUrl?.trim();
644 if (serverUrl) {
645 // We don't own externally-configured servers — no scope interaction.
646 return Effect.succeed({
647 url: serverUrl,
648 exitCode: null,
649 external: true,
650 });
651 }
652
653 return startOpenCodeServerProcess({
654 binaryPath: input.binaryPath,
655 ...(input.environment !== undefined ? { environment: input.environment } : {}),
656 ...(input.port !== undefined ? { port: input.port } : {}),
657 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
658 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
659 }).pipe(
660 Effect.map((server) => ({
661 url: server.url,
662 exitCode: server.exitCode,
663 external: false,
664 })),
665 );
666 };
667
668 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
669 createOpencodeClient({
670 baseUrl: input.baseUrl,
671 directory: input.directory,
672 ...(input.serverPassword
673 ? {
674 headers: {
675 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
676 },
677 }
678 : {}),
679 throwOnError: true,
680 });
681
682 const loadProviders = (client: OpencodeClient) =>
683 runOpenCodeSdk("provider.list", () => client.provider.list()).pipe(
684 Effect.filterMapOrFail(
685 (list) =>
686 list.data
687 ? Result.succeed(list.data)
688 : Result.fail(
689 new OpenCodeRuntimeError({
690 operation: "provider.list",
691 detail: "OpenCode provider list was empty.",
692 }),
693 ),
694 (result) => result,
695 ),
696 );
697
698 const loadAgents = (client: OpencodeClient) =>
699 runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
700 Effect.map((result) => result.data ?? []),
701 );
702
703 const loadSkills = (client: OpencodeClient) =>
704 runOpenCodeSdk("app.skills", () => client.app.skills()).pipe(
705 Effect.map((result) => (result.data ?? []) as ReadonlyArray<OpenCodeSkill>),
706 Effect.orElseSucceed((): ReadonlyArray<OpenCodeSkill> => []),
707 );
708
709 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
710 Effect.all([loadProviders(client), loadAgents(client), loadSkills(client)], {
711 concurrency: "unbounded",
712 }).pipe(Effect.map(([providerList, agents, skills]) => ({ providerList, agents, skills })));
713
714 const loadInventoryFromCli: OpenCodeRuntimeShape["loadInventoryFromCli"] = (input) =>
715 Effect.gen(function* () {
716 const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
717 const commandContext = { cwd: input.cwd, ...env };
718
719 const runModelsCli = () =>
720 runOpenCodeCommand({
721 binaryPath: input.binaryPath,
722 args: ["models", "--verbose"],
723 ...commandContext,
724 }).pipe(Effect.exit);
725 const runAgentsCli = () =>
726 runOpenCodeCommand({
727 binaryPath: input.binaryPath,
728 args: ["agent", "list"],
729 ...commandContext,
730 }).pipe(Effect.exit);
731 const runSkillsCli = () =>
732 runOpenCodeCommand({
733 binaryPath: input.binaryPath,
734 args: ["debug", "skill"],
735 ...commandContext,
736 }).pipe(Effect.exit);
737
738 // First attempt — run all inventory commands in parallel.
739 const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(
740 [runModelsCli(), runAgentsCli(), runSkillsCli()],
741 { concurrency: "unbounded" },
742 );
743 let modelsResult = initialModelsResult;
744 let agentsResult = initialAgentsResult;
745 let skillsResult = initialSkillsResult;
746
747 // Retry once after 1s on transient failures (e.g. SQLite "database is locked")
748 const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
749 const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
750 const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;
751 if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {
752 yield* Effect.sleep("1 second");
753 const [m2, a2, s2] = yield* Effect.all(
754 [
755 needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
756 needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
757 needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),
758 ],
759 { concurrency: "unbounded" },
760 );
761 modelsResult = m2;
762 agentsResult = a2;
763 skillsResult = s2;
764 }
765
766 if (modelsResult._tag === "Failure") {
767 const cause = Cause.squash(modelsResult.cause);
768 return yield* ensureRuntimeError(
769 "loadInventoryFromCli",
770 `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
771 cause,
772 );
773 }
774 if (modelsResult.value.code !== 0) {
775 return yield* new OpenCodeRuntimeError({
776 operation: "loadInventoryFromCli",
777 detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
778 });
779 }
780
781 const parsed = parseModelsCliOutput(modelsResult.value.stdout);
782 const connected = [...parsed.connected];
783 const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
784 (provider) => ({
785 id: provider.id,
786 name: provider.name,
787 source: "config" as const,
788 env: [],
789 options: {},
790 models: provider.models,
791 }),
792 );
793
794 // Agent and skill metadata enrich the provider snapshot but are not required
795 // for an authoritative model inventory, so either may degrade to an empty list.
796 let agents: ReadonlyArray<Agent> = [];
797 if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
798 agents = parseAgentListCliOutput(agentsResult.value.stdout);
799 }
800 let skills: ReadonlyArray<OpenCodeSkill> = [];
801 if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {
802 skills = parseSkillsCliOutput(skillsResult.value.stdout);
803 }
804
805 return {
806 providerList: { all: allProviders, default: {}, connected },
807 agents,
808 skills,
809 };
810 });
811
812 return {
813 startOpenCodeServerProcess,
814 connectToOpenCodeServer,
815 runOpenCodeCommand,
816 createOpenCodeSdkClient,
817 loadOpenCodeInventory,
818 loadInventoryFromCli,
819 } satisfies OpenCodeRuntimeShape;
820});
821
822export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
823 "t3/provider/opencodeRuntime",
824) {}
825
826export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
827 Layer.provide(NetService.layer),
828);