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

OpenCodeRuntime.ts

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