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