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

OpenCodeRuntime.ts

1,146 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 shared: true,
705 });
706 const spawnCommand = yield* resolveCommand(launch.command, launch.args, input.environment);
707 const serverPassword = resolveOpenCodeServerPassword({
708 external: false,
709 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
710 ...(input.environment !== undefined ? { environment: input.environment } : {}),
711 });
712​
713 // Scopes close in reverse order. Forking this before the group kill is
714 // registered forgets the ledger entry only once the group is stopped.
715 const ledgerScope = yield* Scope.fork(runtimeScope);
716 const child = yield* spawner
717 .spawn(
718 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
719 detached: hostPlatform !== "win32",
720 shell: spawnCommand.shell,
721 env: {
722 ...input.environment,
723 ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),
724 // The value is set explicitly (rather than relying on inheritance) because
725 // `extendEnv` is false whenever `input.environment` is provided.
726 OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
727 },
728 extendEnv: input.environment === undefined,
729 }),
730 )
731 .pipe(
732 Effect.provideService(Scope.Scope, runtimeScope),
733 Effect.mapError(
734 (cause) =>
735 new OpenCodeRuntimeError({
736 operation: "startOpenCodeServerProcess",
737 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
738 cause,
739 }),
740 ),
741 );
742​
743 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
744 hostPlatform === "win32"
745 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
746 : Effect.sync(() => {
747 try {
748 signalProcessGroup(Number(child.pid), signal);
749 } catch {}
750 });
751 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
752 Effect.andThen(Effect.sleep("1 second")),
753 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
754 Effect.ignore,
755 );
756 // Registered before recording, so an interrupt while the ledger writes
757 // still stops the group.
758 yield* Scope.addFinalizer(runtimeScope, terminateChild);
759 const forgetServer = yield* serverLedger.track({ pid: Number(child.pid), port, args });
760 yield* Scope.addFinalizer(ledgerScope, forgetServer);
761​
762 const stdoutRef = yield* Ref.make<string | null>("");
763 const stderrRef = yield* Ref.make<string | null>("");
764 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
765​
766 const setReadyFromStdoutChunk = (chunk: string) =>
767 Ref.modify(stdoutRef, (stdout) => {
768 if (stdout === null) {
769 return [null, null] as const;
770 }
771 const nextStdout = `${stdout}${chunk}`;
772 return [
773 parseServerUrlFromOutput(nextStdout),
774 nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
775 ] as const;
776 }).pipe(
777 Effect.flatMap((parsed) =>
778 parsed ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) : Effect.void,
779 ),
780 );
781​
782 const stdoutFiber = yield* child.stdout.pipe(
783 Stream.decodeText(),
784 Stream.runForEach(setReadyFromStdoutChunk),
785 Effect.ignore,
786 Effect.forkIn(runtimeScope),
787 );
788 const stderrFiber = yield* child.stderr.pipe(
789 Stream.decodeText(),
790 Stream.runForEach((chunk) =>
791 Ref.update(stderrRef, (stderr) =>
792 stderr === null
793 ? null
794 : `${stderr}${chunk}`.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
795 ),
796 ),
797 Effect.ignore,
798 Effect.forkIn(runtimeScope),
799 );
800​
801 const exitFiber = yield* child.exitCode.pipe(
802 Effect.flatMap((code) =>
803 Effect.gen(function* () {
804 // Allow trailing diagnostics to drain, but descendants can keep pipes open.
805 const drained = yield* Fiber.joinAll([stdoutFiber, stderrFiber]).pipe(
806 Effect.timeoutOption(OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT),
807 );
808 if (Option.isNone(drained)) {
809 yield* Fiber.interruptAll([stdoutFiber, stderrFiber]);
810 }
811 const stdout = (yield* Ref.get(stdoutRef)) ?? "";
812 const stderr = (yield* Ref.get(stderrRef)) ?? "";
813 const exitCode = Number(code);
814 const reason = classifyStartupExit(stderr);
815 yield* Deferred.fail(
816 readyDeferred,
817 new OpenCodeRuntimeError({
818 operation: "startOpenCodeServerProcess",
819 ...(reason ? { reason } : {}),
820 detail: [
821 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
822 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
823 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
824 ]
825 .filter(Boolean)
826 .join("\n\n"),
827 cause: { exitCode, stdout, stderr },
828 }),
829 ).pipe(Effect.ignore);
830 }),
831 ),
832 Effect.ignore,
833 Effect.forkIn(runtimeScope),
834 );
835​
836 const readyExit = yield* Effect.exit(
837 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
838 );
839​
840 if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {
841 yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);
842 }
843​
844 if (Exit.isFailure(readyExit)) {
845 const squashed = Cause.squash(readyExit.cause);
846 return yield* ensureRuntimeError(
847 "startOpenCodeServerProcess",
848 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
849 squashed,
850 );
851 }
852​
853 const readyOption = readyExit.value;
854 if (Option.isNone(readyOption)) {
855 return yield* new OpenCodeRuntimeError({
856 operation: "startOpenCodeServerProcess",
857 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
858 });
859 }
860​
861 // Keep draining both pipes until the process scope closes. Stopping the
862 // readers can block OpenCode when its output buffers fill. Startup output
863 // is no longer needed, so discard later output instead of retaining it.
864 yield* Ref.set(stdoutRef, null);
865 yield* Ref.set(stderrRef, null);
866​
867 const url = readyOption.value;
868 const version = yield* (
869 input.verify?.(url) ??
870 verifyOpenCodeServerVersion(
871 createOpenCodeSdkClient({
872 baseUrl: url,
873 directory: input.directory,
874 ...(serverPassword !== undefined ? { serverPassword } : {}),
875 }),
876 )
877 );
878​
879 return {
880 url,
881 ...(serverPassword !== undefined ? { serverPassword } : {}),
882 version,
883 isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
884 exitCode: child.exitCode.pipe(
885 Effect.map(Number),
886 Effect.orElseSucceed(() => 0),
887 ),
888 } satisfies OpenCodeServerProcess;
889 });
890​
891 const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] =
892 Effect.fn("OpenCodeRuntime.startOpenCodeServerProcess")(function* (input) {
893 const ownerScope = yield* Scope.Scope;
894 const attempt = Effect.gen(function* () {
895 const attemptScope = yield* Scope.fork(ownerScope);
896 return yield* startServerAttempt(input).pipe(
897 Effect.provideService(Scope.Scope, attemptScope),
898 Effect.onExit((exit) =>
899 Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void,
900 ),
901 );
902 });
903 // OpenCode instances share opencode.db. Migration/WAL locks are transient;
904 // configuration and executable errors are not helped by launching again.
905 return yield* attempt.pipe(
906 Effect.retry({
907 times: 3,
908 schedule: Schedule.spaced("250 millis"),
909 while: (error) => error.reason === "databaseLocked",
910 }),
911 );
912 });
913​
914 const connectToOpenCodeServer: OpenCodeRuntime["Service"]["connectToOpenCodeServer"] = (
915 input,
916 ) => {
917 const serverUrl = input.serverUrl?.trim();
918 if (serverUrl) {
919 const serverPassword = resolveOpenCodeServerPassword({
920 external: true,
921 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
922 });
923 return verifyOpenCodeServerVersion(
924 createOpenCodeSdkClient({
925 baseUrl: serverUrl,
926 directory: input.directory,
927 ...(serverPassword !== undefined ? { serverPassword } : {}),
928 }),
929 ).pipe(
930 Effect.map((version) => ({
931 url: serverUrl,
932 ...(serverPassword !== undefined ? { serverPassword } : {}),
933 version,
934 exitCode: null,
935 external: true,
936 })),
937 );
938 }
939​
940 return startOpenCodeServerProcess({
941 binaryPath: input.binaryPath,
942 directory: input.directory,
943 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
944 ...(input.environment !== undefined ? { environment: input.environment } : {}),
945 ...(input.port !== undefined ? { port: input.port } : {}),
946 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
947 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
948 }).pipe(
949 Effect.map((server) => ({
950 url: server.url,
951 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
952 version: server.version,
953 exitCode: server.exitCode,
954 external: false,
955 })),
956 );
957 };
958​
959 const loadProviders = (client: OpencodeClient) =>
960 runOpenCodeSdk("provider.list", (signal) => client.provider.list(undefined, { signal })).pipe(
961 Effect.filterMapOrFail(
962 (list) =>
963 list.data
964 ? Result.succeed(list.data)
965 : Result.fail(
966 new OpenCodeRuntimeError({
967 operation: "provider.list",
968 detail: "OpenCode provider list was empty.",
969 }),
970 ),
971 (result) => result,
972 ),
973 );
974​
975 const loadAgents = (client: OpencodeClient) =>
976 runOpenCodeSdk("app.agents", (signal) => client.app.agents(undefined, { signal })).pipe(
977 Effect.map((result) => result.data ?? []),
978 Effect.orElseSucceed((): ReadonlyArray<Agent> => []),
979 );
980​
981 const loadOpenCodeSkills: OpenCodeRuntime["Service"]["loadOpenCodeSkills"] = (client) =>
982 runOpenCodeSdk("app.skills", (signal) => client.app.skills(undefined, { signal })).pipe(
983 Effect.map((result) =>
984 (result.data ?? []).map((skill) => ({
985 name: skill.name,
986 ...(skill.description === undefined ? {} : { description: skill.description }),
987 location: skill.location,
988 })),
989 ),
990 );
991 const loadSkills = (client: OpencodeClient) =>
992 loadOpenCodeSkills(client).pipe(Effect.orElseSucceed((): ReadonlyArray<OpenCodeSkill> => []));
993​
994 const loadOpenCodeInventory: OpenCodeRuntime["Service"]["loadOpenCodeInventory"] = (client) =>
995 Effect.all(
996 [
997 loadProviders(client),
998 loadAgents(client),
999 loadSkills(client),
1000 loadOpenCodeCommands(client).pipe(Effect.orElseSucceed(() => [])),
1001 ],
1003 concurrency: "unbounded",
1004 },
1005 ).pipe(
1006 Effect.map(([providerList, agents, skills, commands]) => ({
1007 providerList,
1008 agents,
1009 skills,
1010 commands,
1011 })),
1012 );
1013​
1014 const loadInventoryFromCli: OpenCodeRuntime["Service"]["loadInventoryFromCli"] = Effect.fn(
1015 "OpenCodeRuntime.loadInventoryFromCli",
1016 )(function* (input) {
1017 const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
1018 const commandContext = { cwd: input.cwd, ...env };
1019​
1020 const runModelsCli = () =>
1021 runOpenCodeCommand({
1022 binaryPath: input.binaryPath,
1023 args: ["models", "--verbose"],
1024 ...commandContext,
1025 }).pipe(Effect.exit);
1026 const runAgentsCli = () =>
1027 runOpenCodeCommand({
1028 binaryPath: input.binaryPath,
1029 args: ["agent", "list"],
1030 ...commandContext,
1031 }).pipe(Effect.exit);
1032 const runSkillsCli = () =>
1033 runOpenCodeCommand({
1034 binaryPath: input.binaryPath,
1035 args: ["debug", "skill"],
1036 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
1037 ...commandContext,
1038 }).pipe(Effect.exit);
1039​
1040 // Every OpenCode CLI command opens the same shared SQLite database. Running them
1041 // concurrently causes "database is locked" failures, so run them one at a time.
1042 const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(
1043 [runModelsCli(), runAgentsCli(), runSkillsCli()],
1044 { concurrency: 1 },
1045 );
1046 let modelsResult = initialModelsResult;
1047 let agentsResult = initialAgentsResult;
1048 let skillsResult = initialSkillsResult;
1049​
1050 const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
1051 const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
1052 const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;
1053 if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {
1054 yield* Effect.sleep("1 second");
1055 const [m2, a2, s2] = yield* Effect.all(
1057 needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
1058 needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
1059 needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),
1060 ],
1061 { concurrency: 1 },
1062 );
1063 modelsResult = m2;
1064 agentsResult = a2;
1065 skillsResult = s2;
1067​
1068 if (modelsResult._tag === "Failure") {
1069 const cause = Cause.squash(modelsResult.cause);
1070 return yield* ensureRuntimeError(
1071 "loadInventoryFromCli",
1072 `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
1073 cause,
1074 );
1076 if (modelsResult.value.code !== 0) {
1077 return yield* new OpenCodeRuntimeError({
1078 operation: "loadInventoryFromCli",
1079 detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
1080 });
1082​
1083 const parsed = parseModelsCliOutput(modelsResult.value.stdout);
1084 const connected = [...parsed.connected];
1085 const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
1086 (provider) => ({
1087 id: provider.id,
1088 name: provider.name,
1089 source: "config" as const,
1090 env: [],
1091 options: {},
1092 models: provider.models,
1093 }),
1094 );
1095​
1096 let agents: ReadonlyArray<Agent> = [];
1097 if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
1098 agents = parseAgentListCliOutput(agentsResult.value.stdout);
1100 let skills: ReadonlyArray<OpenCodeSkill> = [];
1101 if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {
1102 skills = parseSkillsCliOutput(skillsResult.value.stdout);
1104​
1105 return {
1106 providerList: { all: allProviders, default: {}, connected },
1107 agents,
1108 skills,
1109 };
1110 });
1111​
1112 const loadSkillsFromCli: OpenCodeRuntime["Service"]["loadSkillsFromCli"] = (input) =>
1113 runOpenCodeCommand({
1114 binaryPath: input.binaryPath,
1115 args: ["debug", "skill"],
1116 cwd: input.cwd,
1117 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
1118 ...(input.environment !== undefined ? { environment: input.environment } : {}),
1119 }).pipe(
1120 Effect.flatMap((result) =>
1121 result.code === 0
1122 ? Effect.succeed(parseSkillsCliOutput(result.stdout))
1123 : Effect.fail(
1124 new OpenCodeRuntimeError({
1125 operation: "loadSkillsFromCli",
1126 detail: `OpenCode skills command exited with code ${result.code}.`,
1127 }),
1128 ),
1129 ),
1130 );
1131​
1132 return {
1133 startOpenCodeServerProcess,
1134 connectToOpenCodeServer,
1135 runOpenCodeCommand,
1136 createOpenCodeSdkClient,
1137 loadOpenCodeInventory,
1138 loadOpenCodeSkills,
1139 loadInventoryFromCli,
1140 loadSkillsFromCli,
1141 } satisfies OpenCodeRuntime["Service"];
1142});
1143​
1144export const layer = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
1145 Layer.provide(NetService.layer),