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