Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCodeRuntime.ts

1,140 lines40.9 KB

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