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

OpenCodeRuntime.ts

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