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