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

OpenCodeRuntime.ts

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