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