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