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