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 { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
37import { resolveSpawnCommand } from "@t3tools/shared/shell";
38const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
39const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
40
41export const MINIMUM_OPENCODE_VERSION = "1.14.19";
42const OPENCODE_HEALTH_TIMEOUT = "5 seconds";
43
44const OpenCodeHealthSchema = Schema.Struct({
45 healthy: Schema.Literal(true),
46 version: Schema.String,
47});
48const decodeOpenCodeHealth = Schema.decodeUnknownEffect(OpenCodeHealthSchema);
49
50export function resolveOpenCodeConfigContent(
51 inputEnvironment: Readonly<Record<string, string | undefined>> | undefined,
52 inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env,
53): string {
54 return (
55 inputEnvironment?.OPENCODE_CONFIG_CONTENT ??
56 inheritedEnvironment.OPENCODE_CONFIG_CONTENT ??
57 OPENCODE_EMPTY_CONFIG_CONTENT
58 );
59}
60
61export function resolveOpenCodeServerPassword(
62 input: {
63 readonly external: boolean;
64 readonly serverPassword?: string;
65 readonly environment?: Readonly<Record<string, string | undefined>>;
66 },
67 inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env,
68): string | undefined {
69 if (input.serverPassword !== undefined) {
70 return input.serverPassword;
71 }
72 if (input.external) {
73 return undefined;
74 }
75 return input.environment === undefined
76 ? inheritedEnvironment.OPENCODE_SERVER_PASSWORD
77 : input.environment.OPENCODE_SERVER_PASSWORD;
78}
79
80const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
81const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000;
82const DEFAULT_HOSTNAME = "127.0.0.1";
83const OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS = 64 * 1024;
84const OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
85export interface OpenCodeServerProcess {
86 readonly url: string;
87 readonly serverPassword?: string;
88 readonly version: string;
89 readonly isRunning: Effect.Effect<boolean>;
90 readonly exitCode: Effect.Effect<number, never>;
91}
92
93export interface OpenCodeServerConnection {
94 readonly url: string;
95 readonly serverPassword?: string;
96 readonly version: string;
97 readonly exitCode: Effect.Effect<number, never> | null;
98 readonly external: boolean;
99}
100
101const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
102export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
103 readonly operation: string;
104 readonly cause?: unknown;
105 readonly detail: string;
106}> {
107 static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
108 P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
109}
110
111function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
112 const result = encodeUnknownJsonStringExit(input);
113 return Exit.isSuccess(result) ? result.value : undefined;
114}
115
116export function openCodeRuntimeErrorDetail(cause: unknown): string {
117 if (OpenCodeRuntimeError.is(cause)) return cause.detail;
118 if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
119 if (cause && typeof cause === "object") {
120 // SDK v2 throws { response, request, error? } shapes — extract what's useful
121 const anyCause = cause as Record<string, unknown>;
122 const status = (anyCause.response as { status?: number } | undefined)?.status;
123 const body = anyCause.error ?? anyCause.data ?? anyCause.body;
124 const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);
125 if (encodedBody) {
126 return `status=${status ?? "?"} body=${encodedBody}`;
127 }
128 }
129 return String(cause);
130}
131
132export const runOpenCodeSdk = <A>(
133 operation: string,
134 fn: (signal: AbortSignal) => Promise<A>,
135): Effect.Effect<A, OpenCodeRuntimeError> =>
136 Effect.tryPromise({
137 try: fn,
138 catch: (cause) =>
139 new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
140 }).pipe(Effect.withSpan(`opencode.${operation}`));
141
142export const verifyOpenCodeServerVersion = Effect.fn("verifyOpenCodeServerVersion")(function* (
143 client: OpencodeClient,
144) {
145 const healthOption = yield* runOpenCodeSdk("global.health", (signal) =>
146 client.global.health({ signal }),
147 ).pipe(Effect.timeoutOption(OPENCODE_HEALTH_TIMEOUT));
148 if (Option.isNone(healthOption)) {
149 return yield* new OpenCodeRuntimeError({
150 operation: "global.health",
151 detail: "Timed out while checking the OpenCode server version.",
152 });
153 }
154
155 const health = yield* decodeOpenCodeHealth(healthOption.value.data).pipe(
156 Effect.mapError(
157 (cause) =>
158 new OpenCodeRuntimeError({
159 operation: "global.health",
160 detail: `OpenCode server returned an invalid health response. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
161 cause,
162 }),
163 ),
164 );
165 if (parseSemver(health.version) === null) {
166 return yield* new OpenCodeRuntimeError({
167 operation: "global.health",
168 detail: `OpenCode server returned an invalid version. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
169 });
170 }
171 if (compareSemverVersions(health.version, MINIMUM_OPENCODE_VERSION) < 0) {
172 return yield* new OpenCodeRuntimeError({
173 operation: "global.health",
174 detail: `OpenCode v${health.version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
175 });
176 }
177 return health.version;
178});
179
180export interface OpenCodeCommandResult {
181 readonly stdout: string;
182 readonly stderr: string;
183 readonly code: number;
184}
185
186export interface OpenCodeInventory {
187 readonly providerList: ProviderListResponse;
188 readonly agents: ReadonlyArray<Agent>;
189 readonly skills: ReadonlyArray<OpenCodeSkill>;
190}
191
192export interface ParsedOpenCodeModelSlug {
193 readonly providerID: string;
194 readonly modelID: string;
195}
196
197export interface OpenCodeSkill {
198 readonly name?: string | null;
199 readonly description?: string | null;
200 readonly location?: string | null;
201}
202
203const OpenCodeSkillSchema = Schema.Struct({
204 name: Schema.optionalKey(Schema.NullOr(Schema.String)),
205 description: Schema.optionalKey(Schema.NullOr(Schema.String)),
206 location: Schema.optionalKey(Schema.NullOr(Schema.String)),
207});
208const decodeOpenCodeSkillsCliOutputExit = Schema.decodeUnknownExit(
209 Schema.fromJsonString(Schema.Array(OpenCodeSkillSchema)),
210);
211
212export interface OpenCodeRuntimeShape {
213 /**
214 * Spawns a local OpenCode server process. Its lifetime is bound to the caller's
215 * `Scope.Scope` — the child is killed automatically when that scope closes.
216 * Consumers that want a long-lived server must create and hold a scope explicitly
217 * (see {@link Scope.make}) and close it when done.
218 */
219 readonly startOpenCodeServerProcess: (input: {
220 readonly binaryPath: string;
221 readonly directory: string;
222 readonly serverPassword?: string;
223 readonly environment?: NodeJS.ProcessEnv;
224 readonly port?: number;
225 readonly hostname?: string;
226 readonly timeoutMs?: number;
227 }) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
228 /**
229 * Returns a handle to either an externally-managed OpenCode server (when
230 * `serverUrl` is provided — no lifetime is attached to the caller's scope) or a
231 * freshly spawned local server whose lifetime is bound to the caller's scope.
232 */
233 readonly connectToOpenCodeServer: (input: {
234 readonly binaryPath: string;
235 readonly directory: string;
236 readonly serverUrl?: string | null;
237 readonly serverPassword?: string;
238 readonly environment?: NodeJS.ProcessEnv;
239 readonly port?: number;
240 readonly hostname?: string;
241 readonly timeoutMs?: number;
242 }) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
243 readonly runOpenCodeCommand: (input: {
244 readonly binaryPath: string;
245 readonly args: ReadonlyArray<string>;
246 readonly environment?: NodeJS.ProcessEnv;
247 readonly cwd?: string;
248 readonly maxOutputBytes?: number;
249 }) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
250 readonly createOpenCodeSdkClient: (input: OpenCodeSdkClientInput) => OpencodeClient;
251 readonly loadOpenCodeInventory: (
252 client: OpencodeClient,
253 ) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
254 readonly loadOpenCodeSkills: (
255 client: OpencodeClient,
256 ) => Effect.Effect<ReadonlyArray<OpenCodeSkill>, OpenCodeRuntimeError>;
257 readonly loadInventoryFromCli: (input: {
258 readonly binaryPath: string;
259 readonly cwd: string;
260 readonly environment?: NodeJS.ProcessEnv;
261 }) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
262 readonly loadSkillsFromCli: (input: {
263 readonly binaryPath: string;
264 readonly cwd: string;
265 readonly environment?: NodeJS.ProcessEnv;
266 }) => Effect.Effect<ReadonlyArray<OpenCodeSkill>, OpenCodeRuntimeError>;
267}
268
269export interface OpenCodeSdkClientInput {
270 readonly baseUrl: string;
271 readonly directory: string;
272 // Callers must explicitly identify managed or externally configured servers.
273 readonly external: boolean;
274 readonly serverPassword?: string;
275}
276
277// Directory routing treats non-loopback external URLs as remote. This hostname policy
278// cannot distinguish SSH tunnels or same-host LAN URLs. Malformed URLs retain the
279// local-directory policy.
280export function isLoopbackBaseUrl(baseUrl: string): boolean {
281 let hostname: string;
282 try {
283 hostname = new URL(baseUrl).hostname;
284 } catch {
285 return true;
286 }
287
288 return isLoopbackHostname(hostname.toLowerCase());
289}
290
291// URL brackets IPv6 literals and normalizes IPv4 spellings such as `127.1`.
292// Domains such as `127.example.com` remain names, not IPv4 literals.
293function isLoopbackHostname(hostname: string): boolean {
294 if (hostname.startsWith("[") && hostname.endsWith("]")) {
295 const address = hostname.slice(1, -1);
296 // An IPv4-mapped address is serialised in hex, so `::ffff:127.0.0.1` arrives as
297 // `::ffff:7f00:1`. Match the mapped 127.0.0.0/8 range, not the readable spelling.
298 return (
299 address === "::1" || address === "::" || /^::ffff:7f[\da-f]{2}:[\da-f]{1,4}$/u.test(address)
300 );
301 }
302
303 const octets = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(hostname);
304 if (octets) {
305 // Only a real IPv4 literal reaches here, so the first octet can be trusted.
306 return octets[1] === "127" || hostname === "0.0.0.0";
307 }
308
309 // RFC 6761 reserves `localhost` and everything under it for loopback. `URL` keeps the
310 // root label on a domain, so `localhost.` arrives with its trailing dot still attached.
311 const name = hostname.endsWith(".") ? hostname.slice(0, -1) : hostname;
312 return name === "localhost" || name.endsWith(".localhost");
313}
314
315export function buildOpenCodeSdkClientConfig(input: OpenCodeSdkClientInput) {
316 const sendDirectory = !input.external || isLoopbackBaseUrl(input.baseUrl);
317 return {
318 baseUrl: input.baseUrl,
319 ...(sendDirectory ? { directory: input.directory } : {}),
320 ...(input.serverPassword
321 ? {
322 headers: {
323 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
324 },
325 }
326 : {}),
327 throwOnError: true as const,
328 };
329}
330
331function parseServerUrlFromOutput(output: string): string | null {
332 for (const line of output.split("\n")) {
333 if (!line.startsWith(OPENCODE_SERVER_READY_PREFIX)) {
334 continue;
335 }
336 const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
337 return match?.[1] ?? null;
338 }
339 return null;
340}
341
342const SLUG_LINE_RE = /^(\S+\/\S+)\s*$/;
343const AGENT_HEADER_RE = /^(.+)\s+\((\S+)\)\s*$/;
344
345// Agents that are always hidden in OpenCode but the CLI "agent list" command
346// does not expose the hidden flag. Keep in sync with OpenCode agent
347// definitions (in the OpenCode repo: packages/opencode/src/agent/agent.ts).
348const KNOWN_HIDDEN_AGENTS = new Set(["compaction", "summary", "title"]);
349
350/** @internal */
351export function parseModelsCliOutput(stdout: string): {
352 readonly providers: ReadonlyMap<
353 string,
354 { readonly id: string; readonly name: string; readonly models: { [key: string]: Model } }
355 >;
356 readonly connected: ReadonlyArray<string>;
357} {
358 const providers = new Map<
359 string,
360 { id: string; name: string; models: { [key: string]: Model } }
361 >();
362 const lines = stdout.split("\n");
363 let currentSlug: string | null = null;
364 const jsonLines: Array<string> = [];
365
366 const flushModel = () => {
367 if (currentSlug !== null && jsonLines.length > 0) {
368 const jsonStr = jsonLines.join("\n").trim();
369 if (jsonStr.length > 0) {
370 try {
371 const model = JSON.parse(jsonStr) as Model;
372 const separator = currentSlug.indexOf("/");
373 if (separator > 0) {
374 const providerID = currentSlug.slice(0, separator);
375 const modelID = currentSlug.slice(separator + 1);
376 let provider = providers.get(providerID);
377 if (!provider) {
378 provider = { id: providerID, name: providerID, models: {} };
379 providers.set(providerID, provider);
380 }
381 provider.models[modelID] = model;
382 }
383 } catch {
384 // Skip unparseable model JSON
385 }
386 }
387 }
388 currentSlug = null;
389 jsonLines.length = 0;
390 };
391
392 for (const line of lines) {
393 // A model's JSON body is a single `JSON.stringify` line starting with `{`,
394 // while a provider/model slug is a bare `provider/model` header. Only the
395 // latter can be a slug: without this guard a body line with no interior
396 // whitespace and a `/` in one of its values (e.g. an OpenRouter model whose
397 // `id` is `vendor/model`) matches SLUG_LINE_RE, so flushModel runs against
398 // an empty body and the model is silently dropped.
399 const slugMatch = line.trimStart().startsWith("{") ? null : SLUG_LINE_RE.exec(line);
400 if (slugMatch) {
401 flushModel();
402 currentSlug = slugMatch[1]!;
403 } else if (currentSlug !== null) {
404 jsonLines.push(line);
405 }
406 }
407 flushModel();
408
409 return { providers, connected: [...providers.keys()] };
410}
411
412/** @internal */
413export function parseAgentListCliOutput(stdout: string): ReadonlyArray<Agent> {
414 const agents: Array<Agent> = [];
415 const lines = stdout.split("\n");
416 let currentHeader: { name: string; mode: string } | null = null;
417 const blockLines: Array<string> = [];
418
419 const flushAgent = () => {
420 if (currentHeader !== null) {
421 const jsonStr = blockLines.join("\n").trim();
422 if (jsonStr.length > 0) {
423 try {
424 const permission = JSON.parse(jsonStr);
425 agents.push({
426 name: currentHeader.name,
427 mode: currentHeader.mode as Agent["mode"],
428 hidden: KNOWN_HIDDEN_AGENTS.has(currentHeader.name),
429 permission,
430 options: {},
431 });
432 } catch {
433 // Skip unparseable agent
434 }
435 }
436 }
437 currentHeader = null;
438 blockLines.length = 0;
439 };
440
441 for (const line of lines) {
442 const match = AGENT_HEADER_RE.exec(line);
443 if (match) {
444 flushAgent();
445 currentHeader = { name: match[1]!, mode: match[2]! };
446 } else if (currentHeader !== null) {
447 blockLines.push(line);
448 }
449 }
450 flushAgent();
451
452 return agents;
453}
454
455/** @internal */
456export function parseSkillsCliOutput(stdout: string): ReadonlyArray<OpenCodeSkill> {
457 const result = decodeOpenCodeSkillsCliOutputExit(stdout);
458 return Exit.isSuccess(result) ? result.value : [];
459}
460
461export function parseOpenCodeModelSlug(
462 slug: string | null | undefined,
463): ParsedOpenCodeModelSlug | null {
464 if (typeof slug !== "string") {
465 return null;
466 }
467
468 const trimmed = slug.trim();
469 const separator = trimmed.indexOf("/");
470 if (separator <= 0 || separator === trimmed.length - 1) {
471 return null;
472 }
473
474 return {
475 providerID: trimmed.slice(0, separator),
476 modelID: trimmed.slice(separator + 1),
477 };
478}
479
480export function openCodeQuestionId(
481 index: number,
482 question: QuestionRequest["questions"][number],
483): string {
484 const header = question.header
485 .trim()
486 .toLowerCase()
487 .replace(/[^a-z0-9_-]+/g, "-");
488 return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
489}
490
491/**
492 * Attachments OpenCode can hand to a model as a native file part. Anything
493 * else (ZIP, binaries, image formats like BMP/AVIF/SVG that model APIs
494 * reject, or files over the direct-attachment size limit) would make the turn
495 * fail before it starts, so those ride only as the file path ProviderService
496 * puts in the prompt.
497 */
498const OPENCODE_NATIVE_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
499export const OPENCODE_NATIVE_FILE_PART_MAX_BYTES = 20 * 1024 * 1024;
500
501export function isOpenCodeNativeFilePart(input: {
502 readonly mimeType: string;
503 readonly sizeBytes: number;
504}): boolean {
505 if (input.sizeBytes > OPENCODE_NATIVE_FILE_PART_MAX_BYTES) {
506 return false;
507 }
508 const normalized = input.mimeType.trim().toLowerCase();
509 return (
510 OPENCODE_NATIVE_IMAGE_MIMES.has(normalized) ||
511 normalized.startsWith("text/") ||
512 normalized === "application/pdf"
513 );
514}
515
516export function toOpenCodeFileParts(input: {
517 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
518 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
519}): Array<FilePartInput> {
520 const parts: Array<FilePartInput> = [];
521
522 for (const attachment of input.attachments ?? []) {
523 if (!isOpenCodeNativeFilePart(attachment)) {
524 continue;
525 }
526 const attachmentPath = input.resolveAttachmentPath(attachment);
527 if (!attachmentPath) {
528 continue;
529 }
530
531 parts.push({
532 type: "file",
533 mime: attachment.mimeType,
534 filename: attachment.name,
535 url: NodeURL.pathToFileURL(attachmentPath).href,
536 });
537 }
538
539 return parts;
540}
541
542export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
543 if (runtimeMode === "full-access") {
544 return [
545 { permission: "*", pattern: "*", action: "allow" },
546 { permission: "external_directory", pattern: "*", action: "allow" },
547 ];
548 }
549
550 // "Auto-accept edits" is documented as "auto-approve edits, ask before other
551 // actions", so prompting for every edit ignores the mode the user picked.
552 // "auto" is left asking on purpose: the docs say providers without an AI
553 // reviewer, OpenCode among them, fall back to Supervised for that mode.
554 const editAction = runtimeMode === "auto-accept-edits" ? "allow" : "ask";
555
556 // Session rules override OpenCode's agent defaults. Allow reads and task
557 // updates, but keep its default approval rules for environment files.
558 return [
559 { permission: "*", pattern: "*", action: "ask" },
560 { permission: "read", pattern: "*", action: "allow" },
561 { permission: "read", pattern: "*.env", action: "ask" },
562 { permission: "read", pattern: "*.env.*", action: "ask" },
563 { permission: "read", pattern: "*.env.example", action: "allow" },
564 { permission: "glob", pattern: "*", action: "allow" },
565 { permission: "grep", pattern: "*", action: "allow" },
566 { permission: "lsp", pattern: "*", action: "allow" },
567 { permission: "skill", pattern: "*", action: "allow" },
568 { permission: "todowrite", pattern: "*", action: "allow" },
569 { permission: "bash", pattern: "*", action: "ask" },
570 { permission: "edit", pattern: "*", action: editAction },
571 { permission: "webfetch", pattern: "*", action: "ask" },
572 { permission: "websearch", pattern: "*", action: "ask" },
573 { permission: "codesearch", pattern: "*", action: "ask" },
574 { permission: "external_directory", pattern: "*", action: "ask" },
575 { permission: "doom_loop", pattern: "*", action: "ask" },
576 { permission: "question", pattern: "*", action: "allow" },
577 ];
578}
579
580export function toOpenCodePermissionReply(
581 decision: ProviderApprovalDecision,
582): "once" | "always" | "reject" {
583 switch (decision) {
584 case "accept":
585 return "once";
586 case "acceptForSession":
587 case "acceptAlways":
588 return "always";
589 case "decline":
590 case "cancel":
591 default:
592 return "reject";
593 }
594}
595
596export function toOpenCodeQuestionAnswers(
597 request: QuestionRequest,
598 answers: Record<string, unknown>,
599): Array<QuestionAnswer> {
600 return request.questions.map((question, index) => {
601 const raw =
602 answers[openCodeQuestionId(index, question)] ??
603 answers[question.header] ??
604 answers[question.question];
605 if (Array.isArray(raw)) {
606 return raw.filter((value): value is string => typeof value === "string");
607 }
608 if (typeof raw === "string") {
609 return raw.trim().length > 0 ? [raw] : [];
610 }
611 return [];
612 });
613}
614
615function ensureRuntimeError(
616 operation: OpenCodeRuntimeError["operation"],
617 detail: string,
618 cause: unknown,
619): OpenCodeRuntimeError {
620 return OpenCodeRuntimeError.is(cause)
621 ? cause
622 : new OpenCodeRuntimeError({ operation, detail, cause });
623}
624
625const makeOpenCodeRuntime = Effect.gen(function* () {
626 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
627 const netService = yield* NetService.NetService;
628 const hostPlatform = yield* HostProcessPlatform;
629 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
630 resolveSpawnCommand(command, args, env ? { env } : {});
631
632 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
633 Effect.gen(function* () {
634 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
635 const child = yield* spawner.spawn(
636 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
637 detached: hostPlatform !== "win32",
638 shell: spawnCommand.shell,
639 ...(input.cwd ? { cwd: input.cwd } : {}),
640 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
641 }),
642 );
643 const terminateCommandGroup =
644 hostPlatform === "win32"
645 ? child.kill({ killSignal: "SIGKILL" }).pipe(Effect.asVoid)
646 : Effect.sync(() => {
647 try {
648 process.kill(-Number(child.pid), "SIGKILL");
649 } catch {
650 // The command and its process group may already have exited.
651 }
652 });
653 yield* Effect.addFinalizer(() => terminateCommandGroup.pipe(Effect.ignore));
654 const collectOptions =
655 input.maxOutputBytes === undefined ? undefined : { maxBytes: input.maxOutputBytes };
656 const [stdout, stderr, code] = yield* Effect.all(
657 [
658 collectStreamAsString(child.stdout, collectOptions),
659 collectStreamAsString(child.stderr, collectOptions),
660 child.exitCode,
661 ],
662 { concurrency: "unbounded" },
663 );
664 const exitCode = Number(code);
665 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
666 return yield* new OpenCodeRuntimeError({
667 operation: "runOpenCodeCommand",
668 detail: `spawn ${input.binaryPath} ENOENT`,
669 });
670 }
671 return {
672 stdout,
673 stderr,
674 code: exitCode,
675 } satisfies OpenCodeCommandResult;
676 }).pipe(
677 Effect.scoped,
678 Effect.mapError((cause) =>
679 ensureRuntimeError(
680 "runOpenCodeCommand",
681 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
682 cause,
683 ),
684 ),
685 );
686
687 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
688 createOpencodeClient(buildOpenCodeSdkClientConfig(input));
689
690 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
691 Effect.gen(function* () {
692 // Bind this server's lifetime to the caller's scope. When the caller's
693 // scope closes, the spawned child is killed and all associated fibers
694 // are interrupted automatically — no `close()` method needed.
695 const runtimeScope = yield* Scope.Scope;
696
697 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
698 const port =
699 input.port ??
700 (yield* netService.findAvailablePort(0).pipe(
701 Effect.mapError(
702 (cause) =>
703 new OpenCodeRuntimeError({
704 operation: "startOpenCodeServerProcess",
705 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
706 cause,
707 }),
708 ),
709 ));
710 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
711 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
712 const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
713 const serverPassword = resolveOpenCodeServerPassword({
714 external: false,
715 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
716 ...(input.environment !== undefined ? { environment: input.environment } : {}),
717 });
718
719 const child = yield* spawner
720 .spawn(
721 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
722 detached: hostPlatform !== "win32",
723 shell: spawnCommand.shell,
724 env: {
725 ...input.environment,
726 ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),
727 // Respect an OPENCODE_CONFIG_CONTENT provided by the caller or
728 // the inherited process environment, only falling back to the
729 // empty config when neither is set. Setting it unconditionally
730 // previously clobbered the user's opencode config, hiding their
731 // providers/models. The value is set explicitly (rather than
732 // relying on inheritance) because `extendEnv` is false whenever
733 // `input.environment` is provided.
734 OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
735 },
736 extendEnv: input.environment === undefined,
737 }),
738 )
739 .pipe(
740 Effect.provideService(Scope.Scope, runtimeScope),
741 Effect.mapError(
742 (cause) =>
743 new OpenCodeRuntimeError({
744 operation: "startOpenCodeServerProcess",
745 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
746 cause,
747 }),
748 ),
749 );
750
751 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
752 hostPlatform === "win32"
753 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
754 : Effect.sync(() => {
755 try {
756 process.kill(-Number(child.pid), signal);
757 } catch {
758 // The direct child may already have exited after starting the
759 // server; the process group kill is best-effort cleanup for
760 // any serve process left in that group.
761 }
762 });
763 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
764 Effect.andThen(Effect.sleep("1 second")),
765 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
766 Effect.ignore,
767 );
768 yield* Scope.addFinalizer(runtimeScope, terminateChild);
769
770 const stdoutRef = yield* Ref.make<string | null>("");
771 const stderrRef = yield* Ref.make<string | null>("");
772 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
773
774 const setReadyFromStdoutChunk = (chunk: string) =>
775 Ref.modify(stdoutRef, (stdout) => {
776 if (stdout === null) {
777 return [null, null] as const;
778 }
779 const nextStdout = `${stdout}${chunk}`;
780 return [
781 parseServerUrlFromOutput(nextStdout),
782 nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
783 ] as const;
784 }).pipe(
785 Effect.flatMap((parsed) =>
786 parsed ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) : Effect.void,
787 ),
788 );
789
790 const stdoutFiber = yield* child.stdout.pipe(
791 Stream.decodeText(),
792 Stream.runForEach(setReadyFromStdoutChunk),
793 Effect.ignore,
794 Effect.forkIn(runtimeScope),
795 );
796 const stderrFiber = yield* child.stderr.pipe(
797 Stream.decodeText(),
798 Stream.runForEach((chunk) =>
799 Ref.update(stderrRef, (stderr) =>
800 stderr === null
801 ? null
802 : `${stderr}${chunk}`.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
803 ),
804 ),
805 Effect.ignore,
806 Effect.forkIn(runtimeScope),
807 );
808
809 const exitFiber = yield* child.exitCode.pipe(
810 Effect.flatMap((code) =>
811 Effect.gen(function* () {
812 const stdout = (yield* Ref.get(stdoutRef)) ?? "";
813 const stderr = (yield* Ref.get(stderrRef)) ?? "";
814 const exitCode = Number(code);
815 yield* Deferred.fail(
816 readyDeferred,
817 new OpenCodeRuntimeError({
818 operation: "startOpenCodeServerProcess",
819 detail: [
820 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
821 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
822 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
823 ]
824 .filter(Boolean)
825 .join("\n\n"),
826 cause: { exitCode, stdout, stderr },
827 }),
828 ).pipe(Effect.ignore);
829 }),
830 ),
831 Effect.ignore,
832 Effect.forkIn(runtimeScope),
833 );
834
835 const readyExit = yield* Effect.exit(
836 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
837 );
838
839 if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {
840 yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);
841 }
842
843 if (Exit.isFailure(readyExit)) {
844 const squashed = Cause.squash(readyExit.cause);
845 return yield* ensureRuntimeError(
846 "startOpenCodeServerProcess",
847 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
848 squashed,
849 );
850 }
851
852 const readyOption = readyExit.value;
853 if (Option.isNone(readyOption)) {
854 return yield* new OpenCodeRuntimeError({
855 operation: "startOpenCodeServerProcess",
856 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
857 });
858 }
859
860 // Keep draining both pipes until the process scope closes. Stopping the
861 // readers can block OpenCode when its output buffers fill. Startup output
862 // is no longer needed, so discard later output instead of retaining it.
863 yield* Ref.set(stdoutRef, null);
864 yield* Ref.set(stderrRef, null);
865
866 const url = readyOption.value;
867 const version = yield* verifyOpenCodeServerVersion(
868 createOpenCodeSdkClient({
869 baseUrl: url,
870 directory: input.directory,
871 external: false,
872 ...(serverPassword !== undefined ? { serverPassword } : {}),
873 }),
874 );
875
876 return {
877 url,
878 ...(serverPassword !== undefined ? { serverPassword } : {}),
879 version,
880 isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
881 exitCode: child.exitCode.pipe(
882 Effect.map(Number),
883 Effect.orElseSucceed(() => 0),
884 ),
885 } satisfies OpenCodeServerProcess;
886 });
887
888 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
889 const serverUrl = input.serverUrl?.trim();
890 if (serverUrl) {
891 const serverPassword = resolveOpenCodeServerPassword({
892 external: true,
893 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
894 });
895 return verifyOpenCodeServerVersion(
896 createOpenCodeSdkClient({
897 baseUrl: serverUrl,
898 directory: input.directory,
899 external: true,
900 ...(serverPassword !== undefined ? { serverPassword } : {}),
901 }),
902 ).pipe(
903 Effect.map((version) => ({
904 url: serverUrl,
905 ...(serverPassword !== undefined ? { serverPassword } : {}),
906 version,
907 exitCode: null,
908 external: true,
909 })),
910 );
911 }
912
913 return startOpenCodeServerProcess({
914 binaryPath: input.binaryPath,
915 directory: input.directory,
916 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
917 ...(input.environment !== undefined ? { environment: input.environment } : {}),
918 ...(input.port !== undefined ? { port: input.port } : {}),
919 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
920 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
921 }).pipe(
922 Effect.map((server) => ({
923 url: server.url,
924 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
925 version: server.version,
926 exitCode: server.exitCode,
927 external: false,
928 })),
929 );
930 };
931
932 const loadProviders = (client: OpencodeClient) =>
933 runOpenCodeSdk("provider.list", (signal) => client.provider.list(undefined, { signal })).pipe(
934 Effect.filterMapOrFail(
935 (list) =>
936 list.data
937 ? Result.succeed(list.data)
938 : Result.fail(
939 new OpenCodeRuntimeError({
940 operation: "provider.list",
941 detail: "OpenCode provider list was empty.",
942 }),
943 ),
944 (result) => result,
945 ),
946 );
947
948 const loadAgents = (client: OpencodeClient) =>
949 runOpenCodeSdk("app.agents", (signal) => client.app.agents(undefined, { signal })).pipe(
950 Effect.map((result) => result.data ?? []),
951 Effect.orElseSucceed((): ReadonlyArray<Agent> => []),
952 );
953
954 const loadOpenCodeSkills: OpenCodeRuntimeShape["loadOpenCodeSkills"] = (client) =>
955 runOpenCodeSdk("app.skills", (signal) => client.app.skills(undefined, { signal })).pipe(
956 Effect.map((result) =>
957 (result.data ?? []).map((skill) => ({
958 name: skill.name,
959 ...(skill.description === undefined ? {} : { description: skill.description }),
960 location: skill.location,
961 })),
962 ),
963 );
964 const loadSkills = (client: OpencodeClient) =>
965 loadOpenCodeSkills(client).pipe(Effect.orElseSucceed((): ReadonlyArray<OpenCodeSkill> => []));
966
967 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
968 Effect.all([loadProviders(client), loadAgents(client), loadSkills(client)], {
969 concurrency: "unbounded",
970 }).pipe(Effect.map(([providerList, agents, skills]) => ({ providerList, agents, skills })));
971
972 const loadInventoryFromCli: OpenCodeRuntimeShape["loadInventoryFromCli"] = (input) =>
973 Effect.gen(function* () {
974 const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
975 const commandContext = { cwd: input.cwd, ...env };
976
977 const runModelsCli = () =>
978 runOpenCodeCommand({
979 binaryPath: input.binaryPath,
980 args: ["models", "--verbose"],
981 ...commandContext,
982 }).pipe(Effect.exit);
983 const runAgentsCli = () =>
984 runOpenCodeCommand({
985 binaryPath: input.binaryPath,
986 args: ["agent", "list"],
987 ...commandContext,
988 }).pipe(Effect.exit);
989 const runSkillsCli = () =>
990 runOpenCodeCommand({
991 binaryPath: input.binaryPath,
992 args: ["debug", "skill"],
993 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
994 ...commandContext,
995 }).pipe(Effect.exit);
996
997 // First attempt — run all inventory commands in parallel.
998 const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(
999 [runModelsCli(), runAgentsCli(), runSkillsCli()],
1000 { concurrency: "unbounded" },
1001 );
1002 let modelsResult = initialModelsResult;
1003 let agentsResult = initialAgentsResult;
1004 let skillsResult = initialSkillsResult;
1005
1006 // Retry once after 1s on transient failures (e.g. SQLite "database is locked")
1007 const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
1008 const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
1009 const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;
1010 if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {
1011 yield* Effect.sleep("1 second");
1012 const [m2, a2, s2] = yield* Effect.all(
1013 [
1014 needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
1015 needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
1016 needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),
1017 ],
1018 { concurrency: "unbounded" },
1019 );
1020 modelsResult = m2;
1021 agentsResult = a2;
1022 skillsResult = s2;
1023 }
1024
1025 if (modelsResult._tag === "Failure") {
1026 const cause = Cause.squash(modelsResult.cause);
1027 return yield* ensureRuntimeError(
1028 "loadInventoryFromCli",
1029 `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
1030 cause,
1031 );
1032 }
1033 if (modelsResult.value.code !== 0) {
1034 return yield* new OpenCodeRuntimeError({
1035 operation: "loadInventoryFromCli",
1036 detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
1037 });
1038 }
1039
1040 const parsed = parseModelsCliOutput(modelsResult.value.stdout);
1041 const connected = [...parsed.connected];
1042 const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
1043 (provider) => ({
1044 id: provider.id,
1045 name: provider.name,
1046 source: "config" as const,
1047 env: [],
1048 options: {},
1049 models: provider.models,
1050 }),
1051 );
1052
1053 // Agent and skill metadata enrich the provider snapshot but are not required
1054 // for an authoritative model inventory, so either may degrade to an empty list.
1055 let agents: ReadonlyArray<Agent> = [];
1056 if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
1057 agents = parseAgentListCliOutput(agentsResult.value.stdout);
1058 }
1059 let skills: ReadonlyArray<OpenCodeSkill> = [];
1060 if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {
1061 skills = parseSkillsCliOutput(skillsResult.value.stdout);
1062 }
1063
1064 return {
1065 providerList: { all: allProviders, default: {}, connected },
1066 agents,
1067 skills,
1068 };
1069 });
1070
1071 const loadSkillsFromCli: OpenCodeRuntimeShape["loadSkillsFromCli"] = (input) =>
1072 runOpenCodeCommand({
1073 binaryPath: input.binaryPath,
1074 args: ["debug", "skill"],
1075 cwd: input.cwd,
1076 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
1077 ...(input.environment !== undefined ? { environment: input.environment } : {}),
1078 }).pipe(
1079 Effect.flatMap((result) =>
1080 result.code === 0
1081 ? Effect.succeed(parseSkillsCliOutput(result.stdout))
1082 : Effect.fail(
1083 new OpenCodeRuntimeError({
1084 operation: "loadSkillsFromCli",
1085 detail: `OpenCode skills command exited with code ${result.code}.`,
1086 }),
1087 ),
1088 ),
1089 );
1090
1091 return {
1092 startOpenCodeServerProcess,
1093 connectToOpenCodeServer,
1094 runOpenCodeCommand,
1095 createOpenCodeSdkClient,
1096 loadOpenCodeInventory,
1097 loadOpenCodeSkills,
1098 loadInventoryFromCli,
1099 loadSkillsFromCli,
1100 } satisfies OpenCodeRuntimeShape;
1101});
1102
1103export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
1104 "t3/provider/opencodeRuntime",
1105) {}
1106
1107export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
1108 Layer.provide(NetService.layer),
1109);