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

opencodeRuntime.ts

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