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