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

opencodeRuntime.ts

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