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
348/**
349 * Attachments OpenCode can hand to a model as a native file part. Anything
350 * else (ZIP, binaries, image formats like BMP/AVIF/SVG that model APIs
351 * reject, or files over the direct-attachment size limit) would make the turn
352 * fail before it starts, so those ride only as the file path ProviderService
353 * puts in the prompt.
354 */
355const OPENCODE_NATIVE_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
356export const OPENCODE_NATIVE_FILE_PART_MAX_BYTES = 20 * 1024 * 1024;
357
358export function isOpenCodeNativeFilePart(input: {
359 readonly mimeType: string;
360 readonly sizeBytes: number;
361}): boolean {
362 if (input.sizeBytes > OPENCODE_NATIVE_FILE_PART_MAX_BYTES) {
363 return false;
364 }
365 const normalized = input.mimeType.trim().toLowerCase();
366 return (
367 OPENCODE_NATIVE_IMAGE_MIMES.has(normalized) ||
368 normalized.startsWith("text/") ||
369 normalized === "application/pdf"
370 );
371}
372
373export function toOpenCodeFileParts(input: {
374 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
375 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
376}): Array<FilePartInput> {
377 const parts: Array<FilePartInput> = [];
378
379 for (const attachment of input.attachments ?? []) {
380 if (!isOpenCodeNativeFilePart(attachment)) {
381 continue;
382 }
383 const attachmentPath = input.resolveAttachmentPath(attachment);
384 if (!attachmentPath) {
385 continue;
386 }
387
388 parts.push({
389 type: "file",
390 mime: attachment.mimeType,
391 filename: attachment.name,
392 url: NodeURL.pathToFileURL(attachmentPath).href,
393 });
394 }
395
396 return parts;
397}
398
399export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
400 if (runtimeMode === "full-access") {
401 return [{ permission: "*", pattern: "*", action: "allow" }];
402 }
403
404 // "Auto-accept edits" is documented as "auto-approve edits, ask before other
405 // actions", so prompting for every edit ignores the mode the user picked.
406 // "auto" is left asking on purpose: the docs say providers without an AI
407 // reviewer, OpenCode among them, fall back to Supervised for that mode.
408 const editAction = runtimeMode === "auto-accept-edits" ? "allow" : "ask";
409
410 return [
411 { permission: "*", pattern: "*", action: "ask" },
412 { permission: "bash", pattern: "*", action: "ask" },
413 { permission: "edit", pattern: "*", action: editAction },
414 { permission: "webfetch", pattern: "*", action: "ask" },
415 { permission: "websearch", pattern: "*", action: "ask" },
416 { permission: "codesearch", pattern: "*", action: "ask" },
417 { permission: "external_directory", pattern: "*", action: "ask" },
418 { permission: "doom_loop", pattern: "*", action: "ask" },
419 { permission: "question", pattern: "*", action: "allow" },
420 ];
421}
422
423export function toOpenCodePermissionReply(
424 decision: ProviderApprovalDecision,
425): "once" | "always" | "reject" {
426 switch (decision) {
427 case "accept":
428 return "once";
429 case "acceptForSession":
430 return "always";
431 case "decline":
432 case "cancel":
433 default:
434 return "reject";
435 }
436}
437
438export function toOpenCodeQuestionAnswers(
439 request: QuestionRequest,
440 answers: Record<string, unknown>,
441): Array<QuestionAnswer> {
442 return request.questions.map((question, index) => {
443 const raw =
444 answers[openCodeQuestionId(index, question)] ??
445 answers[question.header] ??
446 answers[question.question];
447 if (Array.isArray(raw)) {
448 return raw.filter((value): value is string => typeof value === "string");
449 }
450 if (typeof raw === "string") {
451 return raw.trim().length > 0 ? [raw] : [];
452 }
453 return [];
454 });
455}
456
457function ensureRuntimeError(
458 operation: OpenCodeRuntimeError["operation"],
459 detail: string,
460 cause: unknown,
461): OpenCodeRuntimeError {
462 return OpenCodeRuntimeError.is(cause)
463 ? cause
464 : new OpenCodeRuntimeError({ operation, detail, cause });
465}
466
467const makeOpenCodeRuntime = Effect.gen(function* () {
468 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
469 const netService = yield* NetService.NetService;
470 const hostPlatform = yield* HostProcessPlatform;
471 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
472 resolveSpawnCommand(command, args, env ? { env } : {});
473
474 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
475 Effect.gen(function* () {
476 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
477 const child = yield* spawner.spawn(
478 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
479 shell: spawnCommand.shell,
480 ...(input.cwd ? { cwd: input.cwd } : {}),
481 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
482 }),
483 );
484 const collectOptions =
485 input.maxOutputBytes === undefined ? undefined : { maxBytes: input.maxOutputBytes };
486 const [stdout, stderr, code] = yield* Effect.all(
487 [
488 collectStreamAsString(child.stdout, collectOptions),
489 collectStreamAsString(child.stderr, collectOptions),
490 child.exitCode,
491 ],
492 { concurrency: "unbounded" },
493 );
494 const exitCode = Number(code);
495 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
496 return yield* new OpenCodeRuntimeError({
497 operation: "runOpenCodeCommand",
498 detail: `spawn ${input.binaryPath} ENOENT`,
499 });
500 }
501 return {
502 stdout,
503 stderr,
504 code: exitCode,
505 } satisfies OpenCodeCommandResult;
506 }).pipe(
507 Effect.scoped,
508 Effect.mapError((cause) =>
509 ensureRuntimeError(
510 "runOpenCodeCommand",
511 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
512 cause,
513 ),
514 ),
515 );
516
517 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
518 Effect.gen(function* () {
519 // Bind this server's lifetime to the caller's scope. When the caller's
520 // scope closes, the spawned child is killed and all associated fibers
521 // are interrupted automatically — no `close()` method needed.
522 const runtimeScope = yield* Scope.Scope;
523
524 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
525 const port =
526 input.port ??
527 (yield* netService.findAvailablePort(0).pipe(
528 Effect.mapError(
529 (cause) =>
530 new OpenCodeRuntimeError({
531 operation: "startOpenCodeServerProcess",
532 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
533 cause,
534 }),
535 ),
536 ));
537 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
538 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
539 const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
540
541 const child = yield* spawner
542 .spawn(
543 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
544 detached: hostPlatform !== "win32",
545 shell: spawnCommand.shell,
546 env: {
547 ...input.environment,
548 // Respect an OPENCODE_CONFIG_CONTENT provided by the caller or
549 // the inherited process environment, only falling back to the
550 // empty config when neither is set. Setting it unconditionally
551 // previously clobbered the user's opencode config, hiding their
552 // providers/models. The value is set explicitly (rather than
553 // relying on inheritance) because `extendEnv` is false whenever
554 // `input.environment` is provided.
555 OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
556 },
557 extendEnv: input.environment === undefined,
558 }),
559 )
560 .pipe(
561 Effect.provideService(Scope.Scope, runtimeScope),
562 Effect.mapError(
563 (cause) =>
564 new OpenCodeRuntimeError({
565 operation: "startOpenCodeServerProcess",
566 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
567 cause,
568 }),
569 ),
570 );
571
572 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
573 hostPlatform === "win32"
574 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
575 : Effect.sync(() => {
576 try {
577 process.kill(-Number(child.pid), signal);
578 } catch {
579 // The direct child may already have exited after starting the
580 // server; the process group kill is best-effort cleanup for
581 // any serve process left in that group.
582 }
583 });
584 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
585 Effect.andThen(Effect.sleep("1 second")),
586 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
587 Effect.ignore,
588 );
589 yield* Scope.addFinalizer(runtimeScope, terminateChild);
590
591 const stdoutRef = yield* Ref.make("");
592 const stderrRef = yield* Ref.make("");
593 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
594
595 const setReadyFromStdoutChunk = (chunk: string) =>
596 Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(
597 Effect.flatMap((nextStdout) => {
598 const parsed = parseServerUrlFromOutput(nextStdout);
599 return parsed
600 ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)
601 : Effect.void;
602 }),
603 );
604
605 const stdoutFiber = yield* child.stdout.pipe(
606 Stream.decodeText(),
607 Stream.runForEach(setReadyFromStdoutChunk),
608 Effect.ignore,
609 Effect.forkIn(runtimeScope),
610 );
611 const stderrFiber = yield* child.stderr.pipe(
612 Stream.decodeText(),
613 Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),
614 Effect.ignore,
615 Effect.forkIn(runtimeScope),
616 );
617
618 const exitFiber = yield* child.exitCode.pipe(
619 Effect.flatMap((code) =>
620 Effect.gen(function* () {
621 const stdout = yield* Ref.get(stdoutRef);
622 const stderr = yield* Ref.get(stderrRef);
623 const exitCode = Number(code);
624 yield* Deferred.fail(
625 readyDeferred,
626 new OpenCodeRuntimeError({
627 operation: "startOpenCodeServerProcess",
628 detail: [
629 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
630 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
631 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
632 ]
633 .filter(Boolean)
634 .join("\n\n"),
635 cause: { exitCode, stdout, stderr },
636 }),
637 ).pipe(Effect.ignore);
638 }),
639 ),
640 Effect.ignore,
641 Effect.forkIn(runtimeScope),
642 );
643
644 const readyExit = yield* Effect.exit(
645 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
646 );
647
648 // Startup-time fibers are no longer needed once ready has resolved (either
649 // way). The exit fiber is only interrupted on failure; on success it keeps
650 // the caller's `exitCode` effect observable until the scope closes.
651 yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);
652 yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);
653
654 if (Exit.isFailure(readyExit)) {
655 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
656 const squashed = Cause.squash(readyExit.cause);
657 return yield* ensureRuntimeError(
658 "startOpenCodeServerProcess",
659 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
660 squashed,
661 );
662 }
663
664 const readyOption = readyExit.value;
665 if (Option.isNone(readyOption)) {
666 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
667 return yield* new OpenCodeRuntimeError({
668 operation: "startOpenCodeServerProcess",
669 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
670 });
671 }
672
673 return {
674 url: readyOption.value,
675 exitCode: child.exitCode.pipe(
676 Effect.map(Number),
677 Effect.orElseSucceed(() => 0),
678 ),
679 } satisfies OpenCodeServerProcess;
680 });
681
682 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
683 const serverUrl = input.serverUrl?.trim();
684 if (serverUrl) {
685 // We don't own externally-configured servers — no scope interaction.
686 return Effect.succeed({
687 url: serverUrl,
688 exitCode: null,
689 external: true,
690 });
691 }
692
693 return startOpenCodeServerProcess({
694 binaryPath: input.binaryPath,
695 ...(input.environment !== undefined ? { environment: input.environment } : {}),
696 ...(input.port !== undefined ? { port: input.port } : {}),
697 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
698 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
699 }).pipe(
700 Effect.map((server) => ({
701 url: server.url,
702 exitCode: server.exitCode,
703 external: false,
704 })),
705 );
706 };
707
708 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
709 createOpencodeClient({
710 baseUrl: input.baseUrl,
711 directory: input.directory,
712 ...(input.serverPassword
713 ? {
714 headers: {
715 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
716 },
717 }
718 : {}),
719 throwOnError: true,
720 });
721
722 const loadProviders = (client: OpencodeClient) =>
723 runOpenCodeSdk("provider.list", () => client.provider.list()).pipe(
724 Effect.filterMapOrFail(
725 (list) =>
726 list.data
727 ? Result.succeed(list.data)
728 : Result.fail(
729 new OpenCodeRuntimeError({
730 operation: "provider.list",
731 detail: "OpenCode provider list was empty.",
732 }),
733 ),
734 (result) => result,
735 ),
736 );
737
738 const loadAgents = (client: OpencodeClient) =>
739 runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
740 Effect.map((result) => result.data ?? []),
741 );
742
743 const loadSkills = (client: OpencodeClient) =>
744 runOpenCodeSdk("app.skills", () => client.app.skills()).pipe(
745 Effect.map((result) =>
746 (result.data ?? []).map((skill) => ({
747 name: skill.name,
748 ...(skill.description === undefined ? {} : { description: skill.description }),
749 location: skill.location,
750 })),
751 ),
752 Effect.orElseSucceed((): ReadonlyArray<OpenCodeSkill> => []),
753 );
754
755 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
756 Effect.all([loadProviders(client), loadAgents(client), loadSkills(client)], {
757 concurrency: "unbounded",
758 }).pipe(Effect.map(([providerList, agents, skills]) => ({ providerList, agents, skills })));
759
760 const loadInventoryFromCli: OpenCodeRuntimeShape["loadInventoryFromCli"] = (input) =>
761 Effect.gen(function* () {
762 const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
763 const commandContext = { cwd: input.cwd, ...env };
764
765 const runModelsCli = () =>
766 runOpenCodeCommand({
767 binaryPath: input.binaryPath,
768 args: ["models", "--verbose"],
769 ...commandContext,
770 }).pipe(Effect.exit);
771 const runAgentsCli = () =>
772 runOpenCodeCommand({
773 binaryPath: input.binaryPath,
774 args: ["agent", "list"],
775 ...commandContext,
776 }).pipe(Effect.exit);
777 const runSkillsCli = () =>
778 runOpenCodeCommand({
779 binaryPath: input.binaryPath,
780 args: ["debug", "skill"],
781 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
782 ...commandContext,
783 }).pipe(Effect.exit);
784
785 // First attempt — run all inventory commands in parallel.
786 const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(
787 [runModelsCli(), runAgentsCli(), runSkillsCli()],
788 { concurrency: "unbounded" },
789 );
790 let modelsResult = initialModelsResult;
791 let agentsResult = initialAgentsResult;
792 let skillsResult = initialSkillsResult;
793
794 // Retry once after 1s on transient failures (e.g. SQLite "database is locked")
795 const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
796 const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
797 const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;
798 if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {
799 yield* Effect.sleep("1 second");
800 const [m2, a2, s2] = yield* Effect.all(
801 [
802 needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
803 needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
804 needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),
805 ],
806 { concurrency: "unbounded" },
807 );
808 modelsResult = m2;
809 agentsResult = a2;
810 skillsResult = s2;
811 }
812
813 if (modelsResult._tag === "Failure") {
814 const cause = Cause.squash(modelsResult.cause);
815 return yield* ensureRuntimeError(
816 "loadInventoryFromCli",
817 `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
818 cause,
819 );
820 }
821 if (modelsResult.value.code !== 0) {
822 return yield* new OpenCodeRuntimeError({
823 operation: "loadInventoryFromCli",
824 detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
825 });
826 }
827
828 const parsed = parseModelsCliOutput(modelsResult.value.stdout);
829 const connected = [...parsed.connected];
830 const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
831 (provider) => ({
832 id: provider.id,
833 name: provider.name,
834 source: "config" as const,
835 env: [],
836 options: {},
837 models: provider.models,
838 }),
839 );
840
841 // Agent and skill metadata enrich the provider snapshot but are not required
842 // for an authoritative model inventory, so either may degrade to an empty list.
843 let agents: ReadonlyArray<Agent> = [];
844 if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
845 agents = parseAgentListCliOutput(agentsResult.value.stdout);
846 }
847 let skills: ReadonlyArray<OpenCodeSkill> = [];
848 if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {
849 skills = parseSkillsCliOutput(skillsResult.value.stdout);
850 }
851
852 return {
853 providerList: { all: allProviders, default: {}, connected },
854 agents,
855 skills,
856 };
857 });
858
859 return {
860 startOpenCodeServerProcess,
861 connectToOpenCodeServer,
862 runOpenCodeCommand,
863 createOpenCodeSdkClient,
864 loadOpenCodeInventory,
865 loadInventoryFromCli,
866 } satisfies OpenCodeRuntimeShape;
867});
868
869export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
870 "t3/provider/opencodeRuntime",
871) {}
872
873export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
874 Layer.provide(NetService.layer),
875);