Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCodeRuntime.ts

915 lines31.9 KB

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