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

opencodeRuntime.ts

1,021 lines36.6 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 shell: spawnCommand.shell,
567 ...(input.cwd ? { cwd: input.cwd } : {}),
568 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
569 }),
570 );
571 const collectOptions =
572 input.maxOutputBytes === undefined ? undefined : { maxBytes: input.maxOutputBytes };
573 const [stdout, stderr, code] = yield* Effect.all(
574 [
575 collectStreamAsString(child.stdout, collectOptions),
576 collectStreamAsString(child.stderr, collectOptions),
577 child.exitCode,
578 ],
579 { concurrency: "unbounded" },
580 );
581 const exitCode = Number(code);
582 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
583 return yield* new OpenCodeRuntimeError({
584 operation: "runOpenCodeCommand",
585 detail: `spawn ${input.binaryPath} ENOENT`,
586 });
587 }
588 return {
589 stdout,
590 stderr,
591 code: exitCode,
592 } satisfies OpenCodeCommandResult;
593 }).pipe(
594 Effect.scoped,
595 Effect.mapError((cause) =>
596 ensureRuntimeError(
597 "runOpenCodeCommand",
598 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
599 cause,
600 ),
601 ),
602 );
603​
604 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
605 createOpencodeClient({
606 baseUrl: input.baseUrl,
607 directory: input.directory,
608 ...(input.serverPassword
609 ? {
610 headers: {
611 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
612 },
613 }
614 : {}),
615 throwOnError: true,
616 });
617​
618 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
619 Effect.gen(function* () {
620 // Bind this server's lifetime to the caller's scope. When the caller's
621 // scope closes, the spawned child is killed and all associated fibers
622 // are interrupted automatically — no `close()` method needed.
623 const runtimeScope = yield* Scope.Scope;
624​
625 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
626 const port =
627 input.port ??
628 (yield* netService.findAvailablePort(0).pipe(
629 Effect.mapError(
630 (cause) =>
631 new OpenCodeRuntimeError({
632 operation: "startOpenCodeServerProcess",
633 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
634 cause,
635 }),
636 ),
637 ));
638 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
639 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
640 const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
641 const serverPassword = resolveOpenCodeServerPassword({
642 external: false,
643 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
644 ...(input.environment !== undefined ? { environment: input.environment } : {}),
645 });
646​
647 const child = yield* spawner
648 .spawn(
649 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
650 detached: hostPlatform !== "win32",
651 shell: spawnCommand.shell,
652 env: {
653 ...input.environment,
654 ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),
655 // Respect an OPENCODE_CONFIG_CONTENT provided by the caller or
656 // the inherited process environment, only falling back to the
657 // empty config when neither is set. Setting it unconditionally
658 // previously clobbered the user's opencode config, hiding their
659 // providers/models. The value is set explicitly (rather than
660 // relying on inheritance) because `extendEnv` is false whenever
661 // `input.environment` is provided.
662 OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
663 },
664 extendEnv: input.environment === undefined,
665 }),
666 )
667 .pipe(
668 Effect.provideService(Scope.Scope, runtimeScope),
669 Effect.mapError(
670 (cause) =>
671 new OpenCodeRuntimeError({
672 operation: "startOpenCodeServerProcess",
673 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
674 cause,
675 }),
676 ),
677 );
678​
679 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
680 hostPlatform === "win32"
681 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
682 : Effect.sync(() => {
683 try {
684 process.kill(-Number(child.pid), signal);
685 } catch {
686 // The direct child may already have exited after starting the
687 // server; the process group kill is best-effort cleanup for
688 // any serve process left in that group.
689 }
690 });
691 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
692 Effect.andThen(Effect.sleep("1 second")),
693 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
694 Effect.ignore,
695 );
696 yield* Scope.addFinalizer(runtimeScope, terminateChild);
697​
698 const stdoutRef = yield* Ref.make("");
699 const stderrRef = yield* Ref.make("");
700 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
701​
702 const setReadyFromStdoutChunk = (chunk: string) =>
703 Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(
704 Effect.flatMap((nextStdout) => {
705 const parsed = parseServerUrlFromOutput(nextStdout);
706 return parsed
707 ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)
708 : Effect.void;
709 }),
710 );
711​
712 const stdoutFiber = yield* child.stdout.pipe(
713 Stream.decodeText(),
714 Stream.runForEach(setReadyFromStdoutChunk),
715 Effect.ignore,
716 Effect.forkIn(runtimeScope),
717 );
718 const stderrFiber = yield* child.stderr.pipe(
719 Stream.decodeText(),
720 Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),
721 Effect.ignore,
722 Effect.forkIn(runtimeScope),
723 );
724​
725 const exitFiber = yield* child.exitCode.pipe(
726 Effect.flatMap((code) =>
727 Effect.gen(function* () {
728 const stdout = yield* Ref.get(stdoutRef);
729 const stderr = yield* Ref.get(stderrRef);
730 const exitCode = Number(code);
731 yield* Deferred.fail(
732 readyDeferred,
733 new OpenCodeRuntimeError({
734 operation: "startOpenCodeServerProcess",
735 detail: [
736 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
737 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
738 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
739 ]
740 .filter(Boolean)
741 .join("\n\n"),
742 cause: { exitCode, stdout, stderr },
743 }),
744 ).pipe(Effect.ignore);
745 }),
746 ),
747 Effect.ignore,
748 Effect.forkIn(runtimeScope),
749 );
750​
751 const readyExit = yield* Effect.exit(
752 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
753 );
754​
755 // Startup-time fibers are no longer needed once ready has resolved (either
756 // way). The exit fiber is only interrupted on failure; on success it keeps
757 // the caller's `exitCode` effect observable until the scope closes.
758 yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);
759 yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);
760​
761 if (Exit.isFailure(readyExit)) {
762 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
763 const squashed = Cause.squash(readyExit.cause);
764 return yield* ensureRuntimeError(
765 "startOpenCodeServerProcess",
766 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
767 squashed,
768 );
769 }
770​
771 const readyOption = readyExit.value;
772 if (Option.isNone(readyOption)) {
773 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
774 return yield* new OpenCodeRuntimeError({
775 operation: "startOpenCodeServerProcess",
776 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
777 });
778 }
779​
780 const url = readyOption.value;
781 const version = yield* verifyOpenCodeServerVersion(
782 createOpenCodeSdkClient({
783 baseUrl: url,
784 directory: input.directory,
785 ...(serverPassword !== undefined ? { serverPassword } : {}),
786 }),
787 );
788​
789 return {
790 url,
791 ...(serverPassword !== undefined ? { serverPassword } : {}),
792 version,
793 isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
794 exitCode: child.exitCode.pipe(
795 Effect.map(Number),
796 Effect.orElseSucceed(() => 0),
797 ),
798 } satisfies OpenCodeServerProcess;
799 });
800​
801 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
802 const serverUrl = input.serverUrl?.trim();
803 if (serverUrl) {
804 const serverPassword = resolveOpenCodeServerPassword({
805 external: true,
806 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
807 });
808 return verifyOpenCodeServerVersion(
809 createOpenCodeSdkClient({
810 baseUrl: serverUrl,
811 directory: input.directory,
812 ...(serverPassword !== undefined ? { serverPassword } : {}),
813 }),
814 ).pipe(
815 Effect.map((version) => ({
816 url: serverUrl,
817 ...(serverPassword !== undefined ? { serverPassword } : {}),
818 version,
819 exitCode: null,
820 external: true,
821 })),
822 );
823 }
824​
825 return startOpenCodeServerProcess({
826 binaryPath: input.binaryPath,
827 directory: input.directory,
828 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
829 ...(input.environment !== undefined ? { environment: input.environment } : {}),
830 ...(input.port !== undefined ? { port: input.port } : {}),
831 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
832 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
833 }).pipe(
834 Effect.map((server) => ({
835 url: server.url,
836 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
837 version: server.version,
838 exitCode: server.exitCode,
839 external: false,
840 })),
841 );
842 };
843​
844 const loadProviders = (client: OpencodeClient) =>
845 runOpenCodeSdk("provider.list", () => client.provider.list()).pipe(
846 Effect.filterMapOrFail(
847 (list) =>
848 list.data
849 ? Result.succeed(list.data)
850 : Result.fail(
851 new OpenCodeRuntimeError({
852 operation: "provider.list",
853 detail: "OpenCode provider list was empty.",
854 }),
855 ),
856 (result) => result,
857 ),
858 );
859​
860 const loadAgents = (client: OpencodeClient) =>
861 runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
862 Effect.map((result) => result.data ?? []),
863 Effect.orElseSucceed((): ReadonlyArray<Agent> => []),
864 );
865​
866 const loadOpenCodeSkills: OpenCodeRuntimeShape["loadOpenCodeSkills"] = (client) =>
867 runOpenCodeSdk("app.skills", (signal) => client.app.skills(undefined, { signal })).pipe(
868 Effect.map((result) =>
869 (result.data ?? []).map((skill) => ({
870 name: skill.name,
871 ...(skill.description === undefined ? {} : { description: skill.description }),
872 location: skill.location,
873 })),
874 ),
875 );
876 const loadSkills = (client: OpencodeClient) =>
877 loadOpenCodeSkills(client).pipe(Effect.orElseSucceed((): ReadonlyArray<OpenCodeSkill> => []));
878​
879 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
880 Effect.all([loadProviders(client), loadAgents(client), loadSkills(client)], {
881 concurrency: "unbounded",
882 }).pipe(Effect.map(([providerList, agents, skills]) => ({ providerList, agents, skills })));
883​
884 const loadInventoryFromCli: OpenCodeRuntimeShape["loadInventoryFromCli"] = (input) =>
885 Effect.gen(function* () {
886 const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
887 const commandContext = { cwd: input.cwd, ...env };
888​
889 const runModelsCli = () =>
890 runOpenCodeCommand({
891 binaryPath: input.binaryPath,
892 args: ["models", "--verbose"],
893 ...commandContext,
894 }).pipe(Effect.exit);
895 const runAgentsCli = () =>
896 runOpenCodeCommand({
897 binaryPath: input.binaryPath,
898 args: ["agent", "list"],
899 ...commandContext,
900 }).pipe(Effect.exit);
901 const runSkillsCli = () =>
902 runOpenCodeCommand({
903 binaryPath: input.binaryPath,
904 args: ["debug", "skill"],
905 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
906 ...commandContext,
907 }).pipe(Effect.exit);
908​
909 // First attempt — run all inventory commands in parallel.
910 const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(
911 [runModelsCli(), runAgentsCli(), runSkillsCli()],
912 { concurrency: "unbounded" },
913 );
914 let modelsResult = initialModelsResult;
915 let agentsResult = initialAgentsResult;
916 let skillsResult = initialSkillsResult;
917​
918 // Retry once after 1s on transient failures (e.g. SQLite "database is locked")
919 const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
920 const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
921 const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;
922 if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {
923 yield* Effect.sleep("1 second");
924 const [m2, a2, s2] = yield* Effect.all(
925 [
926 needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
927 needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
928 needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),
929 ],
930 { concurrency: "unbounded" },
931 );
932 modelsResult = m2;
933 agentsResult = a2;
934 skillsResult = s2;
935 }
936​
937 if (modelsResult._tag === "Failure") {
938 const cause = Cause.squash(modelsResult.cause);
939 return yield* ensureRuntimeError(
940 "loadInventoryFromCli",
941 `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
942 cause,
943 );
944 }
945 if (modelsResult.value.code !== 0) {
946 return yield* new OpenCodeRuntimeError({
947 operation: "loadInventoryFromCli",
948 detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
949 });
950 }
951​
952 const parsed = parseModelsCliOutput(modelsResult.value.stdout);
953 const connected = [...parsed.connected];
954 const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
955 (provider) => ({
956 id: provider.id,
957 name: provider.name,
958 source: "config" as const,
959 env: [],
960 options: {},
961 models: provider.models,
962 }),
963 );
964​
965 // Agent and skill metadata enrich the provider snapshot but are not required
966 // for an authoritative model inventory, so either may degrade to an empty list.
967 let agents: ReadonlyArray<Agent> = [];
968 if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
969 agents = parseAgentListCliOutput(agentsResult.value.stdout);
970 }
971 let skills: ReadonlyArray<OpenCodeSkill> = [];
972 if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {
973 skills = parseSkillsCliOutput(skillsResult.value.stdout);
974 }
975​
976 return {
977 providerList: { all: allProviders, default: {}, connected },
978 agents,
979 skills,
980 };
981 });
982​
983 const loadSkillsFromCli: OpenCodeRuntimeShape["loadSkillsFromCli"] = (input) =>
984 runOpenCodeCommand({
985 binaryPath: input.binaryPath,
986 args: ["debug", "skill"],
987 cwd: input.cwd,
988 maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
989 ...(input.environment !== undefined ? { environment: input.environment } : {}),
990 }).pipe(
991 Effect.flatMap((result) =>
992 result.code === 0
993 ? Effect.succeed(parseSkillsCliOutput(result.stdout))
994 : Effect.fail(
995 new OpenCodeRuntimeError({
996 operation: "loadSkillsFromCli",
997 detail: `OpenCode skills command exited with code ${result.code}.`,
998 }),
999 ),
1000 ),
1001 );
1002​
1003 return {
1004 startOpenCodeServerProcess,
1005 connectToOpenCodeServer,
1006 runOpenCodeCommand,
1007 createOpenCodeSdkClient,
1008 loadOpenCodeInventory,
1009 loadOpenCodeSkills,
1010 loadInventoryFromCli,
1011 loadSkillsFromCli,
1012 } satisfies OpenCodeRuntimeShape;
1013});
1014​
1015export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
1016 "t3/provider/opencodeRuntime",
1017) {}
1018​
1019export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
1020 Layer.provide(NetService.layer),