Open History to see the last commit
1import * as NodeURL from "node:url";
2
3import type { ChatAttachment, ProviderApprovalDecision } from "@t3tools/contracts";
4import {
5 createOpencodeClient,
6 type Agent,
7 type Command,
8 type FilePartInput,
9 type OpencodeClient,
10 type ProviderListResponse,
11 type QuestionAnswer,
12 type QuestionRequest,
13} from "@opencode-ai/sdk/v2";
14import * as Cause from "effect/Cause";
15import * as Context from "effect/Context";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Fiber from "effect/Fiber";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as P from "effect/Predicate";
23import * as Ref from "effect/Ref";
24import * as Result from "effect/Result";
25import * as Scope from "effect/Scope";
26import * as Schema from "effect/Schema";
27import * as Schedule from "effect/Schedule";
28import * as Stream from "effect/Stream";
29import * as ChildProcess from "effect/process/ChildProcess";
30import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
31
32import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
33import { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe";
34import * as OpenCodeServerLedger from "./OpenCodeServerLedger.ts";
35import { collectStreamAsString } from "@t3tools/provider-core/server/snapshotProbe";
36import * as NetService from "@t3tools/shared/Net";
37import { AgentScope } from "@t3tools/shared/AgentScope";
38import * as HostProcess from "@t3tools/shared/HostProcess";
39import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
40import { resolveSpawnCommand } from "@t3tools/shared/shell";
41const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
42const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
43
44export const MINIMUM_OPENCODE_VERSION = "1.14.19";
45const OPENCODE_HEALTH_TIMEOUT = "5 seconds";
46
47const OpenCodeHealthSchema = Schema.Struct({
48 healthy: Schema.Literal(true),
49 version: Schema.String,
50});
51const decodeOpenCodeHealth = Schema.decodeUnknownEffect(OpenCodeHealthSchema);
52
53function resolveOpenCodeConfigContent(
54 inputEnvironment: Readonly<Record<string, string | undefined>> | undefined,
55 inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env,
56): string {
57 return (
58 inputEnvironment?.OPENCODE_CONFIG_CONTENT ??
59 inheritedEnvironment.OPENCODE_CONFIG_CONTENT ??
60 OPENCODE_EMPTY_CONFIG_CONTENT
61 );
62}
63
64export function resolveOpenCodeServerPassword(
65 input: {
66 readonly external: boolean;
67 readonly serverPassword?: string;
68 readonly environment?: Readonly<Record<string, string | undefined>>;
69 },
70 inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env,
71): string | undefined {
72 if (input.serverPassword !== undefined) {
73 return input.serverPassword;
74 }
75 if (input.external) {
76 return undefined;
77 }
78 return input.environment === undefined
79 ? inheritedEnvironment.OPENCODE_SERVER_PASSWORD
80 : input.environment.OPENCODE_SERVER_PASSWORD;
81}
82
83const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000;
84const DEFAULT_HOSTNAME = "127.0.0.1";
85const OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS = 64 * 1024;
86const OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT = "500 millis";
87export interface OpenCodeServerProcess {
88 readonly url: string;
89 readonly serverPassword?: string;
90 readonly version: string;
91 readonly isRunning: Effect.Effect<boolean>;
92 readonly exitCode: Effect.Effect<number, never>;
93}
94
95export interface OpenCodeServerConnection {
96 readonly url: string;
97 readonly serverPassword?: string;
98 readonly version: string;
99 readonly exitCode: Effect.Effect<number, never> | null;
100 readonly external: boolean;
101}
102
103const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
104const OpenCodeStartupFailureReason = Schema.Literal("databaseLocked");
105export type OpenCodeStartupFailureReason = typeof OpenCodeStartupFailureReason.Type;
106
107export class OpenCodeRuntimeError extends Schema.TaggedError<OpenCodeRuntimeError>()(
108 OPENCODE_RUNTIME_ERROR_TAG,
109 {
110 operation: Schema.String,
111 cause: Schema.optional(Schema.Defect()),
112 detail: Schema.String,
113 reason: Schema.optional(OpenCodeStartupFailureReason),
114 },
115) {}
116
117// Classify stderr database locks at exit so callers need not parse diagnostics.
118function classifyStartupExit(stderr: string): OpenCodeStartupFailureReason | undefined {
119 return /SQLITE_BUSY|database is locked/i.test(stderr) ? "databaseLocked" : undefined;
120}
121
122export const isOpenCodeRuntimeError = (u: unknown): u is OpenCodeRuntimeError =>
123 P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
124
125function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
126 const result = encodeUnknownJsonStringExit(input);
127 return Exit.isSuccess(result) ? result.value : undefined;
128}
129
130export function openCodeRuntimeErrorDetail(cause: unknown): string {
131 if (isOpenCodeRuntimeError(cause)) return cause.detail;
132 // Effect TimeoutError can have a non-string message.
133 if (cause instanceof Error) {
134 const message = cause.message;
135 if (typeof message === "string") {
136 const trimmedMessage = message.trim();
137 if (trimmedMessage.length > 0) return trimmedMessage;
138 }
139 }
140 if (cause && typeof cause === "object") {
141 // SDK v2 throws response/request/error envelopes.
142 const anyCause = cause as Record<string, unknown>;
143 const status = (anyCause.response as { status?: number } | undefined)?.status;
144 const body = anyCause.error ?? anyCause.data ?? anyCause.body;
145 const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);
146 if (encodedBody) {
147 return `status=${status ?? "?"} body=${encodedBody}`;
148 }
149 }
150 return String(cause);
151}
152
153export const runOpenCodeSdk = <A>(
154 operation: string,
155 fn: (signal: AbortSignal) => Promise<A>,
156): Effect.Effect<A, OpenCodeRuntimeError> =>
157 Effect.tryPromise({
158 try: fn,
159 catch: (cause) =>
160 new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
161 }).pipe(Effect.withSpan(`opencode.${operation}`));
162
163export const verifyOpenCodeServerVersion = Effect.fn("verifyOpenCodeServerVersion")(function* (
164 client: OpencodeClient,
165) {
166 const healthOption = yield* runOpenCodeSdk("global.health", (signal) =>
167 client.global.health({ signal }),
168 ).pipe(Effect.timeoutOption(OPENCODE_HEALTH_TIMEOUT));
169 if (Option.isNone(healthOption)) {
170 return yield* new OpenCodeRuntimeError({
171 operation: "global.health",
172 detail: "Timed out while checking the OpenCode server version.",
173 });
174 }
175
176 const health = yield* decodeOpenCodeHealth(healthOption.value.data).pipe(
177 Effect.mapError(
178 (cause) =>
179 new OpenCodeRuntimeError({
180 operation: "global.health",
181 detail: `OpenCode server returned an invalid health response. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
182 cause,
183 }),
184 ),
185 );
186 if (parseSemver(health.version) === null) {
187 return yield* new OpenCodeRuntimeError({
188 operation: "global.health",
189 detail: `OpenCode server returned an invalid version. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
190 });
191 }
192 if (compareSemverVersions(health.version, MINIMUM_OPENCODE_VERSION) < 0) {
193 return yield* new OpenCodeRuntimeError({
194 operation: "global.health",
195 detail: `OpenCode v${health.version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
196 });
197 }
198 return health.version;
199});
200
201export interface OpenCodeCommandResult {
202 readonly stdout: string;
203 readonly stderr: string;
204 readonly code: number;
205}
206
207export interface OpenCodeInventory {
208 readonly providerList: ProviderListResponse;
209 readonly agents: ReadonlyArray<Agent>;
210 readonly skills: ReadonlyArray<OpenCodeSkill>;
211 readonly commands?: ReadonlyArray<OpenCodeSlashCommand>;
212}
213
214export type OpenCodeSlashCommand = Pick<Command, "name" | "description" | "source" | "hints">;
215
216export const loadOpenCodeCommands = (client: OpencodeClient) =>
217 runOpenCodeSdk("command.list", (signal) => client.command.list(undefined, { signal })).pipe(
218 Effect.map((result): ReadonlyArray<OpenCodeSlashCommand> =>
219 (result.data ?? []).map(({ name, description, source, hints }) => ({
220 name,
221 ...(description === undefined ? {} : { description }),
222 ...(source === undefined ? {} : { source }),
223 hints,
224 })),
225 ),
226 );
227
228export interface ParsedOpenCodeModelSlug {
229 readonly providerID: string;
230 readonly modelID: string;
231}
232
233export interface OpenCodeSkill {
234 readonly name?: string | null;
235 readonly description?: string | null;
236 readonly location?: string | null;
237}
238
239export class OpenCodeRuntime extends Context.Service<
240 OpenCodeRuntime,
241 {
242 /** Closing the caller's scope kills the child. */
243 readonly startOpenCodeServerProcess: (input: {
244 readonly binaryPath: string;
245 readonly directory: string;
246 readonly serverPassword?: string;
247 readonly environment?: NodeJS.ProcessEnv;
248 readonly port?: number;
249 readonly hostname?: string;
250 readonly timeoutMs?: number;
251 readonly verify?: (url: string) => Effect.Effect<string, OpenCodeRuntimeError>;
252 }) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
253 readonly connectToOpenCodeServer: (input: {
254 readonly binaryPath: string;
255 readonly directory: string;
256 readonly serverUrl?: string | null;
257 readonly serverPassword?: string;
258 readonly environment?: NodeJS.ProcessEnv;
259 readonly port?: number;
260 readonly hostname?: string;
261 readonly timeoutMs?: number;
262 }) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
263 readonly runOpenCodeCommand: (input: {
264 readonly binaryPath: string;
265 readonly args: ReadonlyArray<string>;
266 readonly environment?: NodeJS.ProcessEnv;
267 readonly cwd?: string;
268 }) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
269 readonly createOpenCodeSdkClient: (input: {
270 readonly baseUrl: string;
271 readonly directory: string;
272 readonly serverPassword?: string;
273 }) => OpencodeClient;
274 readonly loadOpenCodeInventory: (
275 client: OpencodeClient,
276 ) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
277 readonly loadOpenCodeSkills: (
278 client: OpencodeClient,
279 ) => Effect.Effect<ReadonlyArray<OpenCodeSkill>, OpenCodeRuntimeError>;
280 }
281>()("@t3tools/provider-opencode/server/OpenCodeRuntime") {}
282
283function parseServerUrlFromOutput(output: string): string | null {
284 for (const line of output.split("\n")) {
285 const match = line.match(/server listening on\s+(https?:\/\/[^\s]+)/i);
286 if (match?.[1]) return match[1];
287 }
288 return null;
289}
290
291export function parseOpenCodeModelSlug(
292 slug: string | null | undefined,
293): ParsedOpenCodeModelSlug | null {
294 if (typeof slug !== "string") {
295 return null;
296 }
297
298 const trimmed = slug.trim();
299 const separator = trimmed.indexOf("/");
300 if (separator <= 0 || separator === trimmed.length - 1) {
301 return null;
302 }
303
304 return {
305 providerID: trimmed.slice(0, separator),
306 modelID: trimmed.slice(separator + 1),
307 };
308}
309
310export function openCodeQuestionId(
311 index: number,
312 question: QuestionRequest["questions"][number],
313): string {
314 const header = question.header
315 .trim()
316 .toLowerCase()
317 .replace(/[^a-z0-9_-]+/g, "-");
318 return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
319}
320
321// OpenCode inlines only text/plain; other text MIME parts reach APIs that reject them.
322const OPENCODE_NATIVE_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
323const OPENCODE_NATIVE_FILE_PART_MAX_BYTES = 20 * 1024 * 1024;
324
325function isOpenCodeNativeFilePart(input: {
326 readonly mimeType: string;
327 readonly sizeBytes: number;
328}): boolean {
329 if (input.sizeBytes > OPENCODE_NATIVE_FILE_PART_MAX_BYTES) {
330 return false;
331 }
332 const normalized = input.mimeType.trim().toLowerCase();
333 return (
334 OPENCODE_NATIVE_IMAGE_MIMES.has(normalized) ||
335 normalized === "text/plain" ||
336 normalized === "application/pdf"
337 );
338}
339
340export function toOpenCodeFileParts(input: {
341 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
342 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
343}): Array<FilePartInput> {
344 const parts: Array<FilePartInput> = [];
345
346 for (const attachment of input.attachments ?? []) {
347 if (
348 attachment.type === "file" &&
349 "source" in attachment &&
350 attachment.source?._tag === "pasted-text"
351 ) {
352 continue;
353 }
354 if (!isOpenCodeNativeFilePart(attachment)) {
355 continue;
356 }
357 const attachmentPath = input.resolveAttachmentPath(attachment);
358 if (!attachmentPath) {
359 continue;
360 }
361
362 parts.push({
363 type: "file",
364 mime: attachment.mimeType,
365 filename: attachment.name,
366 url: NodeURL.pathToFileURL(attachmentPath).href,
367 });
368 }
369
370 return parts;
371}
372
373export function toOpenCodePermissionReply(
374 decision: ProviderApprovalDecision,
375): "once" | "always" | "reject" {
376 switch (decision) {
377 case "accept":
378 return "once";
379 case "acceptForSession":
380 case "acceptAlways":
381 return "always";
382 case "decline":
383 case "cancel":
384 default:
385 return "reject";
386 }
387}
388
389export function toOpenCodeQuestionAnswers(
390 request: QuestionRequest,
391 answers: Record<string, unknown>,
392): Array<QuestionAnswer> {
393 return request.questions.map((question, index) => {
394 const raw =
395 answers[openCodeQuestionId(index, question)] ??
396 answers[question.header] ??
397 answers[question.question];
398 if (Array.isArray(raw)) {
399 return raw.filter((value): value is string => typeof value === "string");
400 }
401 if (typeof raw === "string") {
402 return raw.trim().length > 0 ? [raw] : [];
403 }
404 return [];
405 });
406}
407
408function ensureRuntimeError(
409 operation: OpenCodeRuntimeError["operation"],
410 detail: string,
411 cause: unknown,
412): OpenCodeRuntimeError {
413 return isOpenCodeRuntimeError(cause)
414 ? cause
415 : new OpenCodeRuntimeError({ operation, detail, cause });
416}
417
418const makeOpenCodeRuntime = Effect.gen(function* () {
419 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
420 const netService = yield* NetService.NetService;
421 const hostPlatform = yield* HostProcess.Platform;
422 const serverLedger = yield* OpenCodeServerLedger.OpenCodeServerLedger;
423 const agentScope = yield* AgentScope;
424 // npm's Windows shim lets the child escape libuv kill-on-close; run its executable directly.
425 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
426 resolveSpawnCommand(command, args, { ...(env ? { env } : {}), bypassNpmShim: true });
427
428 const runOpenCodeCommand: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = Effect.fn(
429 "OpenCodeRuntime.runOpenCodeCommand",
430 )(
431 function* (input) {
432 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
433 const child = yield* spawner.spawn(
434 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
435 detached: hostPlatform !== "win32",
436 shell: spawnCommand.shell,
437 ...(input.cwd ? { cwd: input.cwd } : {}),
438 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
439 }),
440 );
441 const terminateCommandGroup =
442 hostPlatform === "win32"
443 ? child.kill({ killSignal: "SIGKILL" }).pipe(Effect.asVoid)
444 : Effect.sync(() => {
445 try {
446 signalProcessGroup(Number(child.pid), "SIGKILL");
447 } catch {}
448 });
449 yield* Effect.addFinalizer(() => terminateCommandGroup.pipe(Effect.ignore));
450 const [stdout, stderr, code] = yield* Effect.all(
451 [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],
452 { concurrency: "unbounded" },
453 );
454 const exitCode = Number(code);
455 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
456 return yield* new OpenCodeRuntimeError({
457 operation: "runOpenCodeCommand",
458 detail: `spawn ${input.binaryPath} ENOENT`,
459 });
460 }
461 return {
462 stdout,
463 stderr,
464 code: exitCode,
465 } satisfies OpenCodeCommandResult;
466 },
467 (effect, input) =>
468 effect.pipe(
469 Effect.scoped,
470 Effect.mapError((cause) =>
471 ensureRuntimeError(
472 "runOpenCodeCommand",
473 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
474 cause,
475 ),
476 ),
477 ),
478 );
479
480 const createOpenCodeSdkClient: OpenCodeRuntime["Service"]["createOpenCodeSdkClient"] = (input) =>
481 createOpencodeClient({
482 baseUrl: input.baseUrl,
483 directory: input.directory,
484 ...(input.serverPassword
485 ? {
486 headers: {
487 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
488 },
489 }
490 : {}),
491 throwOnError: true,
492 });
493
494 const startServerAttempt: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = Effect.fn(
495 "OpenCodeRuntime.startServerAttempt",
496 )(function* (input) {
497 const runtimeScope = yield* Scope.Scope;
498
499 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
500 const port =
501 input.port ??
502 (yield* netService.findAvailablePort(0).pipe(
503 Effect.mapError(
504 (cause) =>
505 new OpenCodeRuntimeError({
506 operation: "startOpenCodeServerProcess",
507 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
508 cause,
509 }),
510 ),
511 ));
512 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
513 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
514 const launch = yield* agentScope.wrap({
515 command: input.binaryPath,
516 args,
517 name: "opencode",
518 env: input.environment,
519 shared: true,
520 });
521 const spawnCommand = yield* resolveCommand(launch.command, launch.args, input.environment);
522 const serverPassword = resolveOpenCodeServerPassword({
523 external: false,
524 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
525 ...(input.environment !== undefined ? { environment: input.environment } : {}),
526 });
527
528 // Scopes close in reverse order. Forking this before the group kill is
529 // registered forgets the ledger entry only once the group is stopped.
530 const ledgerScope = yield* Scope.fork(runtimeScope);
531 const child = yield* spawner
532 .spawn(
533 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
534 detached: hostPlatform !== "win32",
535 shell: spawnCommand.shell,
536 env: {
537 ...input.environment,
538 ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),
539 // The value is set explicitly (rather than relying on inheritance) because
540 // `extendEnv` is false whenever `input.environment` is provided.
541 OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
542 },
543 extendEnv: input.environment === undefined,
544 }),
545 )
546 .pipe(
547 Effect.provideService(Scope.Scope, runtimeScope),
548 Effect.mapError(
549 (cause) =>
550 new OpenCodeRuntimeError({
551 operation: "startOpenCodeServerProcess",
552 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
553 cause,
554 }),
555 ),
556 );
557
558 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
559 hostPlatform === "win32"
560 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
561 : Effect.sync(() => {
562 try {
563 signalProcessGroup(Number(child.pid), signal);
564 } catch {}
565 });
566 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
567 Effect.andThen(Effect.sleep("1 second")),
568 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
569 Effect.ignore,
570 );
571 // Registered before recording, so an interrupt while the ledger writes
572 // still stops the group.
573 yield* Scope.addFinalizer(runtimeScope, terminateChild);
574 const forgetServer = yield* serverLedger.track({ pid: Number(child.pid), port, args });
575 yield* Scope.addFinalizer(ledgerScope, forgetServer);
576
577 const stdoutRef = yield* Ref.make<string | null>("");
578 const stderrRef = yield* Ref.make<string | null>("");
579 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
580
581 const setReadyFromStdoutChunk = (chunk: string) =>
582 Ref.modify(stdoutRef, (stdout) => {
583 if (stdout === null) {
584 return [null, null] as const;
585 }
586 const nextStdout = `${stdout}${chunk}`;
587 return [
588 parseServerUrlFromOutput(nextStdout),
589 nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
590 ] as const;
591 }).pipe(
592 Effect.flatMap((parsed) =>
593 parsed ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) : Effect.void,
594 ),
595 );
596
597 const stdoutFiber = yield* child.stdout.pipe(
598 Stream.decodeText(),
599 Stream.runForEach(setReadyFromStdoutChunk),
600 Effect.ignore,
601 Effect.forkIn(runtimeScope),
602 );
603 const stderrFiber = yield* child.stderr.pipe(
604 Stream.decodeText(),
605 Stream.runForEach((chunk) =>
606 Ref.update(stderrRef, (stderr) =>
607 stderr === null
608 ? null
609 : `${stderr}${chunk}`.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
610 ),
611 ),
612 Effect.ignore,
613 Effect.forkIn(runtimeScope),
614 );
615
616 const exitFiber = yield* child.exitCode.pipe(
617 Effect.flatMap((code) =>
618 Effect.gen(function* () {
619 // Allow trailing diagnostics to drain, but descendants can keep pipes open.
620 const drained = yield* Fiber.joinAll([stdoutFiber, stderrFiber]).pipe(
621 Effect.timeoutOption(OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT),
622 );
623 if (Option.isNone(drained)) {
624 yield* Fiber.interruptAll([stdoutFiber, stderrFiber]);
625 }
626 const stdout = (yield* Ref.get(stdoutRef)) ?? "";
627 const stderr = (yield* Ref.get(stderrRef)) ?? "";
628 const exitCode = Number(code);
629 const reason = classifyStartupExit(stderr);
630 yield* Deferred.fail(
631 readyDeferred,
632 new OpenCodeRuntimeError({
633 operation: "startOpenCodeServerProcess",
634 ...(reason ? { reason } : {}),
635 detail: [
636 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
637 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
638 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
639 ]
640 .filter(Boolean)
641 .join("\n\n"),
642 cause: { exitCode, stdout, stderr },
643 }),
644 ).pipe(Effect.ignore);
645 }),
646 ),
647 Effect.ignore,
648 Effect.forkIn(runtimeScope),
649 );
650
651 const readyExit = yield* Effect.exit(
652 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
653 );
654
655 if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {
656 yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);
657 }
658
659 if (Exit.isFailure(readyExit)) {
660 const squashed = Cause.squash(readyExit.cause);
661 return yield* ensureRuntimeError(
662 "startOpenCodeServerProcess",
663 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
664 squashed,
665 );
666 }
667
668 const readyOption = readyExit.value;
669 if (Option.isNone(readyOption)) {
670 return yield* new OpenCodeRuntimeError({
671 operation: "startOpenCodeServerProcess",
672 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
673 });
674 }
675
676 // Keep draining both pipes until the process scope closes. Stopping the
677 // readers can block OpenCode when its output buffers fill. Startup output
678 // is no longer needed, so discard later output instead of retaining it.
679 yield* Ref.set(stdoutRef, null);
680 yield* Ref.set(stderrRef, null);
681
682 const url = readyOption.value;
683 const version = yield* (
684 input.verify?.(url) ??
685 verifyOpenCodeServerVersion(
686 createOpenCodeSdkClient({
687 baseUrl: url,
688 directory: input.directory,
689 ...(serverPassword !== undefined ? { serverPassword } : {}),
690 }),
691 )
692 );
693
694 return {
695 url,
696 ...(serverPassword !== undefined ? { serverPassword } : {}),
697 version,
698 isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
699 exitCode: child.exitCode.pipe(
700 Effect.map(Number),
701 Effect.orElseSucceed(() => 0),
702 ),
703 } satisfies OpenCodeServerProcess;
704 });
705
706 const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] =
707 Effect.fn("OpenCodeRuntime.startOpenCodeServerProcess")(function* (input) {
708 const ownerScope = yield* Scope.Scope;
709 const attempt = Effect.gen(function* () {
710 const attemptScope = yield* Scope.fork(ownerScope);
711 return yield* startServerAttempt(input).pipe(
712 Effect.provideService(Scope.Scope, attemptScope),
713 Effect.onExit((exit) =>
714 Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void,
715 ),
716 );
717 });
718 // Shared opencode.db locks are transient; retry those, not configuration/executable errors.
719 return yield* attempt.pipe(
720 Effect.retry({
721 times: 3,
722 schedule: Schedule.spaced("250 millis"),
723 while: (error) => error.reason === "databaseLocked",
724 }),
725 );
726 });
727
728 const connectToOpenCodeServer: OpenCodeRuntime["Service"]["connectToOpenCodeServer"] = (
729 input,
730 ) => {
731 const serverUrl = input.serverUrl?.trim();
732 if (serverUrl) {
733 const serverPassword = resolveOpenCodeServerPassword({
734 external: true,
735 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
736 });
737 return verifyOpenCodeServerVersion(
738 createOpenCodeSdkClient({
739 baseUrl: serverUrl,
740 directory: input.directory,
741 ...(serverPassword !== undefined ? { serverPassword } : {}),
742 }),
743 ).pipe(
744 Effect.map((version) => ({
745 url: serverUrl,
746 ...(serverPassword !== undefined ? { serverPassword } : {}),
747 version,
748 exitCode: null,
749 external: true,
750 })),
751 );
752 }
753
754 return startOpenCodeServerProcess({
755 binaryPath: input.binaryPath,
756 directory: input.directory,
757 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
758 ...(input.environment !== undefined ? { environment: input.environment } : {}),
759 ...(input.port !== undefined ? { port: input.port } : {}),
760 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
761 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
762 }).pipe(
763 Effect.map((server) => ({
764 url: server.url,
765 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
766 version: server.version,
767 exitCode: server.exitCode,
768 external: false,
769 })),
770 );
771 };
772
773 const loadProviders = (client: OpencodeClient) =>
774 runOpenCodeSdk("provider.list", (signal) => client.provider.list(undefined, { signal })).pipe(
775 Effect.filterMapOrFail(
776 (list) =>
777 list.data
778 ? Result.succeed(list.data)
779 : Result.fail(
780 new OpenCodeRuntimeError({
781 operation: "provider.list",
782 detail: "OpenCode provider list was empty.",
783 }),
784 ),
785 (result) => result,
786 ),
787 );
788
789 const loadAgents = (client: OpencodeClient) =>
790 runOpenCodeSdk("app.agents", (signal) => client.app.agents(undefined, { signal })).pipe(
791 Effect.map((result) => result.data ?? []),
792 Effect.orElseSucceed((): ReadonlyArray<Agent> => []),
793 );
794
795 const loadOpenCodeSkills: OpenCodeRuntime["Service"]["loadOpenCodeSkills"] = (client) =>
796 runOpenCodeSdk("app.skills", (signal) => client.app.skills(undefined, { signal })).pipe(
797 Effect.map((result) =>
798 (result.data ?? []).map((skill) => ({
799 name: skill.name,
800 ...(skill.description === undefined ? {} : { description: skill.description }),
801 location: skill.location,
802 })),
803 ),
804 );
805 const loadSkills = (client: OpencodeClient) =>
806 loadOpenCodeSkills(client).pipe(Effect.orElseSucceed((): ReadonlyArray<OpenCodeSkill> => []));
807
808 const loadOpenCodeInventory: OpenCodeRuntime["Service"]["loadOpenCodeInventory"] = (client) =>
809 Effect.all(
810 [
811 loadProviders(client),
812 loadAgents(client),
813 loadSkills(client),
814 loadOpenCodeCommands(client).pipe(Effect.orElseSucceed(() => [])),
815 ],
816 {
817 concurrency: "unbounded",
818 },
819 ).pipe(
820 Effect.map(([providerList, agents, skills, commands]) => ({
821 providerList,
822 agents,
823 skills,
824 commands,
825 })),
826 );
827
828 return {
829 startOpenCodeServerProcess,
830 connectToOpenCodeServer,
831 runOpenCodeCommand,
832 createOpenCodeSdkClient,
833 loadOpenCodeInventory,
834 loadOpenCodeSkills,
835 } satisfies OpenCodeRuntime["Service"];
836});
837
838export const layer = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
839 Layer.provide(NetService.layer),
840);