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