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