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