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

OpenCodeRuntime.ts

878 lines30.6 KB

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