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