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