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