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

OpenCodeRuntime.ts

1,145 lines40.6 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"] = Effect.fn(
608 "OpenCodeRuntime.runOpenCodeCommand",
609 )(
610 function* (input) {
611 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
612 const child = yield* spawner.spawn(
613 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
614 detached: hostPlatform !== "win32",
615 shell: spawnCommand.shell,
616 ...(input.cwd ? { cwd: input.cwd } : {}),
617 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
618 }),
619 );
620 const terminateCommandGroup =
621 hostPlatform === "win32"
622 ? child.kill({ killSignal: "SIGKILL" }).pipe(Effect.asVoid)
623 : Effect.sync(() => {
624 try {
625 signalProcessGroup(Number(child.pid), "SIGKILL");
626 } catch {}
627 });
628 yield* Effect.addFinalizer(() => terminateCommandGroup.pipe(Effect.ignore));
629 const collectOptions =
630 input.maxOutputBytes === undefined ? undefined : { maxBytes: input.maxOutputBytes };
631 const [stdout, stderr, code] = yield* Effect.all(
632 [
633 collectStreamAsString(child.stdout, collectOptions),
634 collectStreamAsString(child.stderr, collectOptions),
635 child.exitCode,
636 ],
637 { concurrency: "unbounded" },
638 );
639 const exitCode = Number(code);
640 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
641 return yield* new OpenCodeRuntimeError({
642 operation: "runOpenCodeCommand",
643 detail: `spawn ${input.binaryPath} ENOENT`,
644 });
645 }
646 return {
647 stdout,
648 stderr,
649 code: exitCode,
650 } satisfies OpenCodeCommandResult;
651 },
652 (effect, input) =>
653 effect.pipe(
654 Effect.scoped,
655 Effect.mapError((cause) =>
656 ensureRuntimeError(
657 "runOpenCodeCommand",
658 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
659 cause,
660 ),
661 ),
662 ),
663 );
664​
665 const createOpenCodeSdkClient: OpenCodeRuntime["Service"]["createOpenCodeSdkClient"] = (input) =>
666 createOpencodeClient({
667 baseUrl: input.baseUrl,
668 directory: input.directory,
669 ...(input.serverPassword
670 ? {
671 headers: {
672 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
673 },
674 }
675 : {}),
676 throwOnError: true,
677 });
678​
679 const startServerAttempt: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = Effect.fn(
680 "OpenCodeRuntime.startServerAttempt",
681 )(function* (input) {
682 const runtimeScope = yield* Scope.Scope;
683​
684 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
685 const port =
686 input.port ??
687 (yield* netService.findAvailablePort(0).pipe(
688 Effect.mapError(
689 (cause) =>
690 new OpenCodeRuntimeError({
691 operation: "startOpenCodeServerProcess",
692 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
693 cause,
694 }),
695 ),
696 ));
697 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
698 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
699 const launch = yield* agentScope.wrap({
700 command: input.binaryPath,
701 args,
702 name: "opencode",
703 env: input.environment,
704 });
705 const spawnCommand = yield* resolveCommand(launch.command, launch.args, input.environment);
706 const serverPassword = resolveOpenCodeServerPassword({
707 external: false,
708 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
709 ...(input.environment !== undefined ? { environment: input.environment } : {}),
710 });
711​
712 // Scopes close in reverse order. Forking this before the group kill is
713 // registered forgets the ledger entry only once the group is stopped.
714 const ledgerScope = yield* Scope.fork(runtimeScope);
715 const child = yield* spawner
716 .spawn(
717 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
718 detached: hostPlatform !== "win32",
719 shell: spawnCommand.shell,
720 env: {
721 ...input.environment,
722 ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),
723 // The value is set explicitly (rather than relying on inheritance) because
724 // `extendEnv` is false whenever `input.environment` is provided.
725 OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
726 },
727 extendEnv: input.environment === undefined,
728 }),
729 )
730 .pipe(
731 Effect.provideService(Scope.Scope, runtimeScope),
732 Effect.mapError(
733 (cause) =>
734 new OpenCodeRuntimeError({
735 operation: "startOpenCodeServerProcess",
736 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
737 cause,
738 }),
739 ),
740 );
741​
742 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
743 hostPlatform === "win32"
744 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
745 : Effect.sync(() => {
746 try {
747 signalProcessGroup(Number(child.pid), signal);
748 } catch {}
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 // Allow trailing diagnostics to drain, but descendants can keep pipes open.
804 const drained = yield* Fiber.joinAll([stdoutFiber, stderrFiber]).pipe(
805 Effect.timeoutOption(OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT),
806 );
807 if (Option.isNone(drained)) {
808 yield* Fiber.interruptAll([stdoutFiber, stderrFiber]);
809 }
810 const stdout = (yield* Ref.get(stdoutRef)) ?? "";
811 const stderr = (yield* Ref.get(stderrRef)) ?? "";
812 const exitCode = Number(code);
813 const reason = classifyStartupExit(stderr);
814 yield* Deferred.fail(
815 readyDeferred,
816 new OpenCodeRuntimeError({
817 operation: "startOpenCodeServerProcess",
818 ...(reason ? { reason } : {}),
819 detail: [
820 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
821 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
822 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
823 ]
824 .filter(Boolean)
825 .join("\n\n"),
826 cause: { exitCode, stdout, stderr },
827 }),
828 ).pipe(Effect.ignore);
829 }),
830 ),
831 Effect.ignore,
832 Effect.forkIn(runtimeScope),
833 );
834​
835 const readyExit = yield* Effect.exit(
836 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
837 );
838​
839 if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {
840 yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);
841 }
842​
843 if (Exit.isFailure(readyExit)) {
844 const squashed = Cause.squash(readyExit.cause);
845 return yield* ensureRuntimeError(
846 "startOpenCodeServerProcess",
847 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
848 squashed,
849 );
850 }
851​
852 const readyOption = readyExit.value;
853 if (Option.isNone(readyOption)) {
854 return yield* new OpenCodeRuntimeError({
855 operation: "startOpenCodeServerProcess",
856 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
857 });
858 }
859​
860 // Keep draining both pipes until the process scope closes. Stopping the
861 // readers can block OpenCode when its output buffers fill. Startup output
862 // is no longer needed, so discard later output instead of retaining it.
863 yield* Ref.set(stdoutRef, null);
864 yield* Ref.set(stderrRef, null);
865​
866 const url = readyOption.value;
867 const version = yield* (
868 input.verify?.(url) ??
869 verifyOpenCodeServerVersion(
870 createOpenCodeSdkClient({
871 baseUrl: url,
872 directory: input.directory,
873 ...(serverPassword !== undefined ? { serverPassword } : {}),
874 }),
875 )
876 );
877​
878 return {
879 url,
880 ...(serverPassword !== undefined ? { serverPassword } : {}),
881 version,
882 isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
883 exitCode: child.exitCode.pipe(
884 Effect.map(Number),
885 Effect.orElseSucceed(() => 0),
886 ),
887 } satisfies OpenCodeServerProcess;
888 });
889​
890 const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] =
891 Effect.fn("OpenCodeRuntime.startOpenCodeServerProcess")(function* (input) {
892 const ownerScope = yield* Scope.Scope;
893 const attempt = Effect.gen(function* () {
894 const attemptScope = yield* Scope.fork(ownerScope);
895 return yield* startServerAttempt(input).pipe(
896 Effect.provideService(Scope.Scope, attemptScope),
897 Effect.onExit((exit) =>
898 Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void,
899 ),
900 );
901 });
902 // OpenCode instances share opencode.db. Migration/WAL locks are transient;
903 // configuration and executable errors are not helped by launching again.
904 return yield* attempt.pipe(
905 Effect.retry({
906 times: 3,
907 schedule: Schedule.spaced("250 millis"),
908 while: (error) => error.reason === "databaseLocked",
909 }),
910 );
911 });
912​
913 const connectToOpenCodeServer: OpenCodeRuntime["Service"]["connectToOpenCodeServer"] = (
914 input,
915 ) => {
916 const serverUrl = input.serverUrl?.trim();
917 if (serverUrl) {
918 const serverPassword = resolveOpenCodeServerPassword({
919 external: true,
920 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
921 });
922 return verifyOpenCodeServerVersion(
923 createOpenCodeSdkClient({
924 baseUrl: serverUrl,
925 directory: input.directory,
926 ...(serverPassword !== undefined ? { serverPassword } : {}),
927 }),
928 ).pipe(
929 Effect.map((version) => ({
930 url: serverUrl,
931 ...(serverPassword !== undefined ? { serverPassword } : {}),
932 version,
933 exitCode: null,
934 external: true,
935 })),
936 );
937 }
938​
939 return startOpenCodeServerProcess({
940 binaryPath: input.binaryPath,
941 directory: input.directory,
942 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
943 ...(input.environment !== undefined ? { environment: input.environment } : {}),
944 ...(input.port !== undefined ? { port: input.port } : {}),
945 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
946 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
947 }).pipe(
948 Effect.map((server) => ({
949 url: server.url,
950 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
951 version: server.version,
952 exitCode: server.exitCode,
953 external: false,
954 })),
955 );
956 };
957​
958 const loadProviders = (client: OpencodeClient) =>
959 runOpenCodeSdk("provider.list", (signal) => client.provider.list(undefined, { signal })).pipe(
960 Effect.filterMapOrFail(
961 (list) =>
962 list.data
963 ? Result.succeed(list.data)
964 : Result.fail(
965 new OpenCodeRuntimeError({
966 operation: "provider.list",
967 detail: "OpenCode provider list was empty.",
968 }),
969 ),
970 (result) => result,
971 ),
972 );
973​
974 const loadAgents = (client: OpencodeClient) =>
975 runOpenCodeSdk("app.agents", (signal) => client.app.agents(undefined, { signal })).pipe(
976 Effect.map((result) => result.data ?? []),
977 Effect.orElseSucceed((): ReadonlyArray<Agent> => []),
978 );
979​
980 const loadOpenCodeSkills: OpenCodeRuntime["Service"]["loadOpenCodeSkills"] = (client) =>
981 runOpenCodeSdk("app.skills", (signal) => client.app.skills(undefined, { signal })).pipe(
982 Effect.map((result) =>
983 (result.data ?? []).map((skill) => ({
984 name: skill.name,
985 ...(skill.description === undefined ? {} : { description: skill.description }),
986 location: skill.location,
987 })),
988 ),
989 );
990 const loadSkills = (client: OpencodeClient) =>
991 loadOpenCodeSkills(client).pipe(Effect.orElseSucceed((): ReadonlyArray<OpenCodeSkill> => []));
992​
993 const loadOpenCodeInventory: OpenCodeRuntime["Service"]["loadOpenCodeInventory"] = (client) =>
994 Effect.all(
995 [
996 loadProviders(client),
997 loadAgents(client),
998 loadSkills(client),
999 loadOpenCodeCommands(client).pipe(Effect.orElseSucceed(() => [])),
1000 ],
1002 concurrency: "unbounded",
1003 },
1004 ).pipe(
1005 Effect.map(([providerList, agents, skills, commands]) => ({
1006 providerList,
1007 agents,
1008 skills,
1009 commands,
1010 })),
1011 );
1012​
1013 const loadInventoryFromCli: OpenCodeRuntime["Service"]["loadInventoryFromCli"] = Effect.fn(
1014 "OpenCodeRuntime.loadInventoryFromCli",
1015 )(function* (input) {
1016 const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
1017 const commandContext = { cwd: input.cwd, ...env };
1018​
1019 const runModelsCli = () =>
1020 runOpenCodeCommand({
1021 binaryPath: input.binaryPath,
1022 args: ["models", "--verbose"],
1023 ...commandContext,
1024 }).pipe(Effect.exit);
1025 const runAgentsCli = () =>
1026 runOpenCodeCommand({
1027 binaryPath: input.binaryPath,
1028 args: ["agent", "list"],
1029 ...commandContext,
1030 }).pipe(Effect.exit);
1031 const runSkillsCli = () =>
1032 runOpenCodeCommand({
1033 binaryPath: input.binaryPath,
1034 args: ["debug", "skill"],
1035 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
1036 ...commandContext,
1037 }).pipe(Effect.exit);
1038​
1039 // Every OpenCode CLI command opens the same shared SQLite database. Running them
1040 // concurrently causes "database is locked" failures, so run them one at a time.
1041 const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(
1042 [runModelsCli(), runAgentsCli(), runSkillsCli()],
1043 { concurrency: 1 },
1044 );
1045 let modelsResult = initialModelsResult;
1046 let agentsResult = initialAgentsResult;
1047 let skillsResult = initialSkillsResult;
1048​
1049 const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
1050 const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
1051 const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;
1052 if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {
1053 yield* Effect.sleep("1 second");
1054 const [m2, a2, s2] = yield* Effect.all(
1056 needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
1057 needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
1058 needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),
1059 ],
1060 { concurrency: 1 },
1061 );
1062 modelsResult = m2;
1063 agentsResult = a2;
1064 skillsResult = s2;
1066​
1067 if (modelsResult._tag === "Failure") {
1068 const cause = Cause.squash(modelsResult.cause);
1069 return yield* ensureRuntimeError(
1070 "loadInventoryFromCli",
1071 `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
1072 cause,
1073 );
1075 if (modelsResult.value.code !== 0) {
1076 return yield* new OpenCodeRuntimeError({
1077 operation: "loadInventoryFromCli",
1078 detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
1079 });
1081​
1082 const parsed = parseModelsCliOutput(modelsResult.value.stdout);
1083 const connected = [...parsed.connected];
1084 const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
1085 (provider) => ({
1086 id: provider.id,
1087 name: provider.name,
1088 source: "config" as const,
1089 env: [],
1090 options: {},
1091 models: provider.models,
1092 }),
1093 );
1094​
1095 let agents: ReadonlyArray<Agent> = [];
1096 if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
1097 agents = parseAgentListCliOutput(agentsResult.value.stdout);
1099 let skills: ReadonlyArray<OpenCodeSkill> = [];
1100 if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {
1101 skills = parseSkillsCliOutput(skillsResult.value.stdout);
1103​
1104 return {
1105 providerList: { all: allProviders, default: {}, connected },
1106 agents,
1107 skills,
1108 };
1109 });
1110​
1111 const loadSkillsFromCli: OpenCodeRuntime["Service"]["loadSkillsFromCli"] = (input) =>
1112 runOpenCodeCommand({
1113 binaryPath: input.binaryPath,
1114 args: ["debug", "skill"],
1115 cwd: input.cwd,
1116 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
1117 ...(input.environment !== undefined ? { environment: input.environment } : {}),
1118 }).pipe(
1119 Effect.flatMap((result) =>
1120 result.code === 0
1121 ? Effect.succeed(parseSkillsCliOutput(result.stdout))
1122 : Effect.fail(
1123 new OpenCodeRuntimeError({
1124 operation: "loadSkillsFromCli",
1125 detail: `OpenCode skills command exited with code ${result.code}.`,
1126 }),
1127 ),
1128 ),
1129 );
1130​
1131 return {
1132 startOpenCodeServerProcess,
1133 connectToOpenCodeServer,
1134 runOpenCodeCommand,
1135 createOpenCodeSdkClient,
1136 loadOpenCodeInventory,
1137 loadOpenCodeSkills,
1138 loadInventoryFromCli,
1139 loadSkillsFromCli,
1140 } satisfies OpenCodeRuntime["Service"];
1141});
1142​
1143export const layer = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
1144 Layer.provide(NetService.layer),