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