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

opencodeRuntime.ts

1,061 lines38.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";
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_SERVER_STARTUP_MAX_OUTPUT_CHARS = 64 * 1024;
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 = 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 = 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 result = decodeOpenCodeSkillsCliOutputExit(stdout);
400 return Exit.isSuccess(result) ? result.value : [];
402​
403export function parseOpenCodeModelSlug(
404 slug: string | null | undefined,
405): ParsedOpenCodeModelSlug | null {
406 if (typeof slug !== "string") {
407 return null;
408 }
409​
410 const trimmed = slug.trim();
411 const separator = trimmed.indexOf("/");
412 if (separator <= 0 || separator === trimmed.length - 1) {
413 return null;
414 }
415​
416 return {
417 providerID: trimmed.slice(0, separator),
418 modelID: trimmed.slice(separator + 1),
419 };
421​
422export function openCodeQuestionId(
423 index: number,
424 question: QuestionRequest["questions"][number],
425): string {
426 const header = question.header
427 .trim()
428 .toLowerCase()
429 .replace(/[^a-z0-9_-]+/g, "-");
430 return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
432​
433/**
434 * Attachments OpenCode can hand to a model as a native file part. Anything
435 * else (ZIP, binaries, image formats like BMP/AVIF/SVG that model APIs
436 * reject, or files over the direct-attachment size limit) would make the turn
437 * fail before it starts, so those ride only as the file path ProviderService
438 * puts in the prompt.
439 */
440const OPENCODE_NATIVE_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
441const OPENCODE_NATIVE_FILE_PART_MAX_BYTES = 20 * 1024 * 1024;
442​
443function isOpenCodeNativeFilePart(input: {
444 readonly mimeType: string;
445 readonly sizeBytes: number;
446}): boolean {
447 if (input.sizeBytes > OPENCODE_NATIVE_FILE_PART_MAX_BYTES) {
448 return false;
449 }
450 const normalized = input.mimeType.trim().toLowerCase();
451 return (
452 OPENCODE_NATIVE_IMAGE_MIMES.has(normalized) ||
453 normalized.startsWith("text/") ||
454 normalized === "application/pdf"
455 );
457​
458export function toOpenCodeFileParts(input: {
459 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
460 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
461}): Array<FilePartInput> {
462 const parts: Array<FilePartInput> = [];
463​
464 for (const attachment of input.attachments ?? []) {
465 if (!isOpenCodeNativeFilePart(attachment)) {
466 continue;
467 }
468 const attachmentPath = input.resolveAttachmentPath(attachment);
469 if (!attachmentPath) {
470 continue;
471 }
472​
473 parts.push({
474 type: "file",
475 mime: attachment.mimeType,
476 filename: attachment.name,
477 url: NodeURL.pathToFileURL(attachmentPath).href,
478 });
479 }
480​
481 return parts;
483​
484export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
485 if (runtimeMode === "full-access") {
486 return [
487 { permission: "*", pattern: "*", action: "allow" },
488 { permission: "external_directory", pattern: "*", action: "allow" },
489 ];
490 }
491​
492 // "Auto-accept edits" is documented as "auto-approve edits, ask before other
493 // actions", so prompting for every edit ignores the mode the user picked.
494 // "auto" is left asking on purpose: the docs say providers without an AI
495 // reviewer, OpenCode among them, fall back to Supervised for that mode.
496 const editAction = runtimeMode === "auto-accept-edits" ? "allow" : "ask";
497​
498 // Session rules override OpenCode's agent defaults. Allow reads and task
499 // updates, but keep its default approval rules for environment files.
500 return [
501 { permission: "*", pattern: "*", action: "ask" },
502 { permission: "read", pattern: "*", action: "allow" },
503 { permission: "read", pattern: "*.env", action: "ask" },
504 { permission: "read", pattern: "*.env.*", action: "ask" },
505 { permission: "read", pattern: "*.env.example", action: "allow" },
506 { permission: "glob", pattern: "*", action: "allow" },
507 { permission: "grep", pattern: "*", action: "allow" },
508 { permission: "lsp", pattern: "*", action: "allow" },
509 { permission: "skill", pattern: "*", action: "allow" },
510 { permission: "todowrite", pattern: "*", action: "allow" },
511 { permission: "bash", pattern: "*", action: "ask" },
512 { permission: "edit", pattern: "*", action: editAction },
513 { permission: "webfetch", pattern: "*", action: "ask" },
514 { permission: "websearch", pattern: "*", action: "ask" },
515 { permission: "codesearch", pattern: "*", action: "ask" },
516 { permission: "external_directory", pattern: "*", action: "ask" },
517 { permission: "doom_loop", pattern: "*", action: "ask" },
518 { permission: "question", pattern: "*", action: "allow" },
519 ];
521​
522export function toOpenCodePermissionReply(
523 decision: ProviderApprovalDecision,
524): "once" | "always" | "reject" {
525 switch (decision) {
526 case "accept":
527 return "once";
528 case "acceptForSession":
529 case "acceptAlways":
530 return "always";
531 case "decline":
532 case "cancel":
533 default:
534 return "reject";
535 }
537​
538export function toOpenCodeQuestionAnswers(
539 request: QuestionRequest,
540 answers: Record<string, unknown>,
541): Array<QuestionAnswer> {
542 return request.questions.map((question, index) => {
543 const raw =
544 answers[openCodeQuestionId(index, question)] ??
545 answers[question.header] ??
546 answers[question.question];
547 if (Array.isArray(raw)) {
548 return raw.filter((value): value is string => typeof value === "string");
549 }
550 if (typeof raw === "string") {
551 return raw.trim().length > 0 ? [raw] : [];
552 }
553 return [];
554 });
556​
557function ensureRuntimeError(
558 operation: OpenCodeRuntimeError["operation"],
559 detail: string,
560 cause: unknown,
561): OpenCodeRuntimeError {
562 return OpenCodeRuntimeError.is(cause)
563 ? cause
564 : new OpenCodeRuntimeError({ operation, detail, cause });
566​
567const makeOpenCodeRuntime = Effect.gen(function* () {
568 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
569 const netService = yield* NetService.NetService;
570 const hostPlatform = yield* HostProcessPlatform;
571 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
572 resolveSpawnCommand(command, args, env ? { env } : {});
573​
574 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
575 Effect.gen(function* () {
576 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
577 const child = yield* spawner.spawn(
578 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
579 detached: hostPlatform !== "win32",
580 shell: spawnCommand.shell,
581 ...(input.cwd ? { cwd: input.cwd } : {}),
582 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
583 }),
584 );
585 const terminateCommandGroup =
586 hostPlatform === "win32"
587 ? child.kill({ killSignal: "SIGKILL" }).pipe(Effect.asVoid)
588 : Effect.sync(() => {
589 try {
590 process.kill(-Number(child.pid), "SIGKILL");
591 } catch {
592 // The command and its process group may already have exited.
593 }
594 });
595 yield* Effect.addFinalizer(() => terminateCommandGroup.pipe(Effect.ignore));
596 const collectOptions =
597 input.maxOutputBytes === undefined ? undefined : { maxBytes: input.maxOutputBytes };
598 const [stdout, stderr, code] = yield* Effect.all(
599 [
600 collectStreamAsString(child.stdout, collectOptions),
601 collectStreamAsString(child.stderr, collectOptions),
602 child.exitCode,
603 ],
604 { concurrency: "unbounded" },
605 );
606 const exitCode = Number(code);
607 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
608 return yield* new OpenCodeRuntimeError({
609 operation: "runOpenCodeCommand",
610 detail: `spawn ${input.binaryPath} ENOENT`,
611 });
612 }
613 return {
614 stdout,
615 stderr,
616 code: exitCode,
617 } satisfies OpenCodeCommandResult;
618 }).pipe(
619 Effect.scoped,
620 Effect.mapError((cause) =>
621 ensureRuntimeError(
622 "runOpenCodeCommand",
623 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
624 cause,
625 ),
626 ),
627 );
628​
629 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
630 createOpencodeClient({
631 baseUrl: input.baseUrl,
632 directory: input.directory,
633 ...(input.serverPassword
634 ? {
635 headers: {
636 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
637 },
638 }
639 : {}),
640 throwOnError: true,
641 });
642​
643 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
644 Effect.gen(function* () {
645 // Bind this server's lifetime to the caller's scope. When the caller's
646 // scope closes, the spawned child is killed and all associated fibers
647 // are interrupted automatically — no `close()` method needed.
648 const runtimeScope = yield* Scope.Scope;
649​
650 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
651 const port =
652 input.port ??
653 (yield* netService.findAvailablePort(0).pipe(
654 Effect.mapError(
655 (cause) =>
656 new OpenCodeRuntimeError({
657 operation: "startOpenCodeServerProcess",
658 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
659 cause,
660 }),
661 ),
662 ));
663 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
664 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
665 const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
666 const serverPassword = resolveOpenCodeServerPassword({
667 external: false,
668 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
669 ...(input.environment !== undefined ? { environment: input.environment } : {}),
670 });
671​
672 const child = yield* spawner
673 .spawn(
674 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
675 detached: hostPlatform !== "win32",
676 shell: spawnCommand.shell,
677 env: {
678 ...input.environment,
679 ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),
680 // Respect an OPENCODE_CONFIG_CONTENT provided by the caller or
681 // the inherited process environment, only falling back to the
682 // empty config when neither is set. Setting it unconditionally
683 // previously clobbered the user's opencode config, hiding their
684 // providers/models. The value is set explicitly (rather than
685 // relying on inheritance) because `extendEnv` is false whenever
686 // `input.environment` is provided.
687 OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
688 },
689 extendEnv: input.environment === undefined,
690 }),
691 )
692 .pipe(
693 Effect.provideService(Scope.Scope, runtimeScope),
694 Effect.mapError(
695 (cause) =>
696 new OpenCodeRuntimeError({
697 operation: "startOpenCodeServerProcess",
698 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
699 cause,
700 }),
701 ),
702 );
703​
704 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
705 hostPlatform === "win32"
706 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
707 : Effect.sync(() => {
708 try {
709 process.kill(-Number(child.pid), signal);
710 } catch {
711 // The direct child may already have exited after starting the
712 // server; the process group kill is best-effort cleanup for
713 // any serve process left in that group.
714 }
715 });
716 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
717 Effect.andThen(Effect.sleep("1 second")),
718 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
719 Effect.ignore,
720 );
721 yield* Scope.addFinalizer(runtimeScope, terminateChild);
722​
723 const stdoutRef = yield* Ref.make<string | null>("");
724 const stderrRef = yield* Ref.make<string | null>("");
725 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
726​
727 const setReadyFromStdoutChunk = (chunk: string) =>
728 Ref.modify(stdoutRef, (stdout) => {
729 if (stdout === null) {
730 return [null, null] as const;
731 }
732 const nextStdout = `${stdout}${chunk}`;
733 return [
734 parseServerUrlFromOutput(nextStdout),
735 nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
736 ] as const;
737 }).pipe(
738 Effect.flatMap((parsed) =>
739 parsed ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) : Effect.void,
740 ),
741 );
742​
743 const stdoutFiber = yield* child.stdout.pipe(
744 Stream.decodeText(),
745 Stream.runForEach(setReadyFromStdoutChunk),
746 Effect.ignore,
747 Effect.forkIn(runtimeScope),
748 );
749 const stderrFiber = yield* child.stderr.pipe(
750 Stream.decodeText(),
751 Stream.runForEach((chunk) =>
752 Ref.update(stderrRef, (stderr) =>
753 stderr === null
754 ? null
755 : `${stderr}${chunk}`.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
756 ),
757 ),
758 Effect.ignore,
759 Effect.forkIn(runtimeScope),
760 );
761​
762 const exitFiber = yield* child.exitCode.pipe(
763 Effect.flatMap((code) =>
764 Effect.gen(function* () {
765 const stdout = (yield* Ref.get(stdoutRef)) ?? "";
766 const stderr = (yield* Ref.get(stderrRef)) ?? "";
767 const exitCode = Number(code);
768 yield* Deferred.fail(
769 readyDeferred,
770 new OpenCodeRuntimeError({
771 operation: "startOpenCodeServerProcess",
772 detail: [
773 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
774 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
775 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
776 ]
777 .filter(Boolean)
778 .join("\n\n"),
779 cause: { exitCode, stdout, stderr },
780 }),
781 ).pipe(Effect.ignore);
782 }),
783 ),
784 Effect.ignore,
785 Effect.forkIn(runtimeScope),
786 );
787​
788 const readyExit = yield* Effect.exit(
789 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
790 );
791​
792 if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {
793 yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);
794 }
795​
796 if (Exit.isFailure(readyExit)) {
797 const squashed = Cause.squash(readyExit.cause);
798 return yield* ensureRuntimeError(
799 "startOpenCodeServerProcess",
800 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
801 squashed,
802 );
803 }
804​
805 const readyOption = readyExit.value;
806 if (Option.isNone(readyOption)) {
807 return yield* new OpenCodeRuntimeError({
808 operation: "startOpenCodeServerProcess",
809 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
810 });
811 }
812​
813 // Keep draining both pipes until the process scope closes. Stopping the
814 // readers can block OpenCode when its output buffers fill. Startup output
815 // is no longer needed, so discard later output instead of retaining it.
816 yield* Ref.set(stdoutRef, null);
817 yield* Ref.set(stderrRef, null);
818​
819 const url = readyOption.value;
820 const version = yield* verifyOpenCodeServerVersion(
821 createOpenCodeSdkClient({
822 baseUrl: url,
823 directory: input.directory,
824 ...(serverPassword !== undefined ? { serverPassword } : {}),
825 }),
826 );
827​
828 return {
829 url,
830 ...(serverPassword !== undefined ? { serverPassword } : {}),
831 version,
832 isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
833 exitCode: child.exitCode.pipe(
834 Effect.map(Number),
835 Effect.orElseSucceed(() => 0),
836 ),
837 } satisfies OpenCodeServerProcess;
838 });
839​
840 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
841 const serverUrl = input.serverUrl?.trim();
842 if (serverUrl) {
843 const serverPassword = resolveOpenCodeServerPassword({
844 external: true,
845 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
846 });
847 return verifyOpenCodeServerVersion(
848 createOpenCodeSdkClient({
849 baseUrl: serverUrl,
850 directory: input.directory,
851 ...(serverPassword !== undefined ? { serverPassword } : {}),
852 }),
853 ).pipe(
854 Effect.map((version) => ({
855 url: serverUrl,
856 ...(serverPassword !== undefined ? { serverPassword } : {}),
857 version,
858 exitCode: null,
859 external: true,
860 })),
861 );
862 }
863​
864 return startOpenCodeServerProcess({
865 binaryPath: input.binaryPath,
866 directory: input.directory,
867 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
868 ...(input.environment !== undefined ? { environment: input.environment } : {}),
869 ...(input.port !== undefined ? { port: input.port } : {}),
870 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
871 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
872 }).pipe(
873 Effect.map((server) => ({
874 url: server.url,
875 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
876 version: server.version,
877 exitCode: server.exitCode,
878 external: false,
879 })),
880 );
881 };
882​
883 const loadProviders = (client: OpencodeClient) =>
884 runOpenCodeSdk("provider.list", (signal) => client.provider.list(undefined, { signal })).pipe(
885 Effect.filterMapOrFail(
886 (list) =>
887 list.data
888 ? Result.succeed(list.data)
889 : Result.fail(
890 new OpenCodeRuntimeError({
891 operation: "provider.list",
892 detail: "OpenCode provider list was empty.",
893 }),
894 ),
895 (result) => result,
896 ),
897 );
898​
899 const loadAgents = (client: OpencodeClient) =>
900 runOpenCodeSdk("app.agents", (signal) => client.app.agents(undefined, { signal })).pipe(
901 Effect.map((result) => result.data ?? []),
902 Effect.orElseSucceed((): ReadonlyArray<Agent> => []),
903 );
904​
905 const loadOpenCodeSkills: OpenCodeRuntimeShape["loadOpenCodeSkills"] = (client) =>
906 runOpenCodeSdk("app.skills", (signal) => client.app.skills(undefined, { signal })).pipe(
907 Effect.map((result) =>
908 (result.data ?? []).map((skill) => ({
909 name: skill.name,
910 ...(skill.description === undefined ? {} : { description: skill.description }),
911 location: skill.location,
912 })),
913 ),
914 );
915 const loadSkills = (client: OpencodeClient) =>
916 loadOpenCodeSkills(client).pipe(Effect.orElseSucceed((): ReadonlyArray<OpenCodeSkill> => []));
917​
918 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
919 Effect.all([loadProviders(client), loadAgents(client), loadSkills(client)], {
920 concurrency: "unbounded",
921 }).pipe(Effect.map(([providerList, agents, skills]) => ({ providerList, agents, skills })));
922​
923 const loadInventoryFromCli: OpenCodeRuntimeShape["loadInventoryFromCli"] = (input) =>
924 Effect.gen(function* () {
925 const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
926 const commandContext = { cwd: input.cwd, ...env };
927​
928 const runModelsCli = () =>
929 runOpenCodeCommand({
930 binaryPath: input.binaryPath,
931 args: ["models", "--verbose"],
932 ...commandContext,
933 }).pipe(Effect.exit);
934 const runAgentsCli = () =>
935 runOpenCodeCommand({
936 binaryPath: input.binaryPath,
937 args: ["agent", "list"],
938 ...commandContext,
939 }).pipe(Effect.exit);
940 const runSkillsCli = () =>
941 runOpenCodeCommand({
942 binaryPath: input.binaryPath,
943 args: ["debug", "skill"],
944 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
945 ...commandContext,
946 }).pipe(Effect.exit);
947​
948 // Every OpenCode CLI command opens the same shared SQLite database. Running them
949 // concurrently causes "database is locked" failures, so run them one at a time.
950 const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(
951 [runModelsCli(), runAgentsCli(), runSkillsCli()],
952 { concurrency: 1 },
953 );
954 let modelsResult = initialModelsResult;
955 let agentsResult = initialAgentsResult;
956 let skillsResult = initialSkillsResult;
957​
958 // Retry once after 1s on transient failures (e.g. SQLite "database is locked")
959 const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
960 const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
961 const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;
962 if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {
963 yield* Effect.sleep("1 second");
964 const [m2, a2, s2] = yield* Effect.all(
965 [
966 needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
967 needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
968 needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),
969 ],
970 { concurrency: 1 },
971 );
972 modelsResult = m2;
973 agentsResult = a2;
974 skillsResult = s2;
975 }
976​
977 if (modelsResult._tag === "Failure") {
978 const cause = Cause.squash(modelsResult.cause);
979 return yield* ensureRuntimeError(
980 "loadInventoryFromCli",
981 `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
982 cause,
983 );
984 }
985 if (modelsResult.value.code !== 0) {
986 return yield* new OpenCodeRuntimeError({
987 operation: "loadInventoryFromCli",
988 detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
989 });
990 }
991​
992 const parsed = parseModelsCliOutput(modelsResult.value.stdout);
993 const connected = [...parsed.connected];
994 const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
995 (provider) => ({
996 id: provider.id,
997 name: provider.name,
998 source: "config" as const,
999 env: [],
1000 options: {},
1001 models: provider.models,
1002 }),
1003 );
1004​
1005 // Agent and skill metadata enrich the provider snapshot but are not required
1006 // for an authoritative model inventory, so either may degrade to an empty list.
1007 let agents: ReadonlyArray<Agent> = [];
1008 if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
1009 agents = parseAgentListCliOutput(agentsResult.value.stdout);
1011 let skills: ReadonlyArray<OpenCodeSkill> = [];
1012 if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {
1013 skills = parseSkillsCliOutput(skillsResult.value.stdout);
1015​
1016 return {
1017 providerList: { all: allProviders, default: {}, connected },
1018 agents,
1019 skills,
1020 };
1021 });
1022​
1023 const loadSkillsFromCli: OpenCodeRuntimeShape["loadSkillsFromCli"] = (input) =>
1024 runOpenCodeCommand({
1025 binaryPath: input.binaryPath,
1026 args: ["debug", "skill"],
1027 cwd: input.cwd,
1028 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
1029 ...(input.environment !== undefined ? { environment: input.environment } : {}),
1030 }).pipe(
1031 Effect.flatMap((result) =>
1032 result.code === 0
1033 ? Effect.succeed(parseSkillsCliOutput(result.stdout))
1034 : Effect.fail(
1035 new OpenCodeRuntimeError({
1036 operation: "loadSkillsFromCli",
1037 detail: `OpenCode skills command exited with code ${result.code}.`,
1038 }),
1039 ),
1040 ),
1041 );
1042​
1043 return {
1044 startOpenCodeServerProcess,
1045 connectToOpenCodeServer,
1046 runOpenCodeCommand,
1047 createOpenCodeSdkClient,
1048 loadOpenCodeInventory,
1049 loadOpenCodeSkills,
1050 loadInventoryFromCli,
1051 loadSkillsFromCli,
1052 } satisfies OpenCodeRuntimeShape;
1053});
1054​
1055export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
1056 "t3/provider/opencodeRuntime",
1057) {}
1058​
1059export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
1060 Layer.provide(NetService.layer),