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

opencodeRuntime.ts

1,033 lines37.1 KB

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