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

opencodeRuntime.ts

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