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

opencodeRuntime.ts

883 lines32.6 KB

1import * as NodeURL from "node:url";
2​
3import type { ChatAttachment, ProviderApprovalDecision, RuntimeMode } from "@t3tools/contracts";
4import { OpenCode } from "@opencode/client";
5import type {
6 AgentInfo,
7 CommandInfo,
8 ModelInfo,
9 PermissionRuleset,
10 ProviderInfo,
11 SkillInfo,
12 FormInfo,
13 FormInfo1,
14 FormAnswer,
15} from "@opencode/client";
16import * as Cause from "effect/Cause";
17import * as Context from "effect/Context";
18import * as Crypto from "effect/Crypto";
19import * as Data from "effect/Data";
20import * as Deferred from "effect/Deferred";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as Fiber from "effect/Fiber";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as P from "effect/Predicate";
27import * as Ref from "effect/Ref";
28import * as Scope from "effect/Scope";
29import * as Schema from "effect/Schema";
30import * as Stream from "effect/Stream";
31import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
32​
33import { isWindowsCommandNotFound } from "../processRunner.ts";
34import { collectStreamAsString } from "./providerSnapshot.ts";
35import * as NetService from "@t3tools/shared/Net";
36import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
37import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
38import { resolveSpawnCommand } from "@t3tools/shared/shell";
39const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
40export const MINIMUM_OPENCODE_VERSION = "2.0.12";
41const OPENCODE_HEALTH_TIMEOUT = "5 seconds";
42​
43const OpenCodeInfoSchema = Schema.Struct({ version: Schema.String });
44const decodeOpenCodeInfo = Schema.decodeUnknownEffect(OpenCodeInfoSchema);
45​
46export function resolveOpenCodeConfigContent(
47 inputEnvironment: Readonly<Record<string, string | undefined>> | undefined,
48 inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env,
49): string | undefined {
50 return (
51 inputEnvironment?.OPENCODE_CONFIG_CONTENT ??
52 inheritedEnvironment.OPENCODE_CONFIG_CONTENT
53 );
55​
56export function resolveOpenCodeServerPassword(
57 input: {
58 readonly external: boolean;
59 readonly serverPassword?: string;
60 readonly environment?: Readonly<Record<string, string | undefined>>;
61 },
62 inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env,
63): string | undefined {
64 if (input.serverPassword !== undefined) {
65 return input.serverPassword;
66 }
67 if (input.external) {
68 return undefined;
69 }
70 const environment = input.environment ?? inheritedEnvironment;
71 return environment.OPENCODE_PASSWORD ?? environment.OPENCODE_SERVER_PASSWORD;
73​
74const OPENCODE_SERVER_READY_PREFIX = "server listening";
75const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000;
76const DEFAULT_HOSTNAME = "127.0.0.1";
77const OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS = 64 * 1024;
78export interface OpenCodeServerProcess {
79 readonly url: string;
80 readonly serverPassword?: string;
81 readonly version: string;
82 readonly isRunning: Effect.Effect<boolean>;
83 readonly exitCode: Effect.Effect<number, never>;
85​
86export interface OpenCodeServerConnection {
87 readonly url: string;
88 readonly serverPassword?: string;
89 readonly version: string;
90 readonly exitCode: Effect.Effect<number, never> | null;
91 readonly external: boolean;
93​
94const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
95export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
96 readonly operation: string;
97 readonly cause?: unknown;
98 readonly detail: string;
99}> {
100 static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
101 P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
103​
104function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
105 const result = encodeUnknownJsonStringExit(input);
106 return Exit.isSuccess(result) ? result.value : undefined;
108​
109export function openCodeRuntimeErrorDetail(cause: unknown): string {
110 if (OpenCodeRuntimeError.is(cause)) return cause.detail;
111 if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
112 if (cause && typeof cause === "object") {
113 const anyCause = cause as Record<string, unknown>;
114 const status = (anyCause.response as { status?: number } | undefined)?.status;
115 const body = anyCause.error ?? anyCause.data ?? anyCause.body;
116 const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);
117 if (encodedBody) {
118 return `status=${status ?? "?"} body=${encodedBody}`;
119 }
120 }
121 return String(cause);
123​
124export const runOpenCodeSdk = <A>(
125 operation: string,
126 fn: (signal: AbortSignal) => Promise<A>,
127): Effect.Effect<A, OpenCodeRuntimeError> =>
128 Effect.tryPromise({
129 try: fn,
130 catch: (cause) =>
131 new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
132 }).pipe(Effect.withSpan(`opencode.${operation}`));
133​
134export type OpenCodeClient = ReturnType<typeof OpenCode.make>;
135​
136export const verifyOpenCodeServerVersion = Effect.fn("verifyOpenCodeServerVersion")(function* (
137 client: OpenCodeClient,
138) {
139 const healthOption = yield* runOpenCodeSdk("server.info", (signal) =>
140 client.server.info({ signal }),
141 ).pipe(Effect.timeoutOption(OPENCODE_HEALTH_TIMEOUT));
142 if (Option.isNone(healthOption)) {
143 return yield* new OpenCodeRuntimeError({
144 operation: "server.info",
145 detail: "Timed out while checking the OpenCode server version.",
146 });
147 }
148​
149 const health = yield* decodeOpenCodeInfo(healthOption.value).pipe(
150 Effect.mapError(
151 (cause) =>
152 new OpenCodeRuntimeError({
153 operation: "server.info",
154 detail: `OpenCode server returned an invalid health response. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
155 cause,
156 }),
157 ),
158 );
159 if (parseSemver(health.version) === null) {
160 return yield* new OpenCodeRuntimeError({
161 operation: "server.info",
162 detail: `OpenCode server returned an invalid version. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
163 });
164 }
165 if (compareSemverVersions(health.version, MINIMUM_OPENCODE_VERSION) < 0) {
166 return yield* new OpenCodeRuntimeError({
167 operation: "server.info",
168 detail: `OpenCode v${health.version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
169 });
170 }
171 return health.version;
172});
173​
174export interface OpenCodeCommandResult {
175 readonly stdout: string;
176 readonly stderr: string;
177 readonly code: number;
179​
180export interface OpenCodeInventory {
181 readonly providers: ReadonlyArray<ProviderInfo>;
182 readonly models: ReadonlyArray<ModelInfo>;
183 readonly agents: ReadonlyArray<AgentInfo>;
184 readonly skills: ReadonlyArray<SkillInfo>;
185 readonly commands: ReadonlyArray<CommandInfo>;
187​
188/** Command templates stay in OpenCode, which expands arguments and runs MCP prompts. */
189export const loadOpenCodeCommands = (client: OpenCodeClient, directory: string) =>
190 runOpenCodeSdk("command.list", (signal) =>
191 client.command.list({ location: { directory } }, { signal }),
192 ).pipe(Effect.map((result) => result.data));
193​
194export interface ParsedOpenCodeModelSlug {
195 readonly providerID: string;
196 readonly modelID: string;
198​
199export interface OpenCodeRuntimeShape {
200 /**
201 * Spawns a local OpenCode server process. Its lifetime is bound to the caller's
202 * `Scope.Scope` — the child is killed automatically when that scope closes.
203 * Consumers that want a long-lived server must create and hold a scope explicitly
204 * (see {@link Scope.make}) and close it when done.
205 */
206 readonly startOpenCodeServerProcess: (input: {
207 readonly binaryPath: string;
208 readonly directory: string;
209 readonly serverPassword?: string;
210 readonly environment?: NodeJS.ProcessEnv;
211 readonly port?: number;
212 readonly hostname?: string;
213 readonly timeoutMs?: number;
214 }) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
215 /**
216 * Returns a handle to either an externally-managed OpenCode server (when
217 * `serverUrl` is provided — no lifetime is attached to the caller's scope) or a
218 * freshly spawned local server whose lifetime is bound to the caller's scope.
219 */
220 readonly connectToOpenCodeServer: (input: {
221 readonly binaryPath: string;
222 readonly directory: string;
223 readonly serverUrl?: string | null;
224 readonly serverPassword?: string;
225 readonly environment?: NodeJS.ProcessEnv;
226 readonly port?: number;
227 readonly hostname?: string;
228 readonly timeoutMs?: number;
229 }) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
230 readonly runOpenCodeCommand: (input: {
231 readonly binaryPath: string;
232 readonly args: ReadonlyArray<string>;
233 readonly environment?: NodeJS.ProcessEnv;
234 readonly cwd?: string;
235 readonly maxOutputBytes?: number;
236 }) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
237 readonly createOpenCodeSdkClient: (input: {
238 readonly baseUrl: string;
239 readonly serverPassword?: string;
240 }) => OpenCodeClient;
241 readonly loadOpenCodeInventory: (
242 client: OpenCodeClient,
243 directory: string,
244 ) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
245 readonly loadOpenCodeSkills: (
246 client: OpenCodeClient,
247 directory: string,
248 ) => Effect.Effect<ReadonlyArray<SkillInfo>, OpenCodeRuntimeError>;
250​
251function parseServerUrlFromOutput(output: string): {
252 readonly url: string;
253 /** Whether the readiness line was newline-terminated (definitely complete). */
254 readonly terminated: boolean;
255} | null {
256 // Every line except the last is newline-terminated and therefore complete.
257 // The trailing fragment may be a complete readiness line that never got a
258 // newline, or a partial chunk of a line still in flight — the caller keeps
259 // a trailing candidate pending until the output settles instead of
260 // resolving with a truncated URL.
261 const lines = output.split("\n");
262 for (const line of lines.slice(0, -1)) {
263 if (!line.startsWith(OPENCODE_SERVER_READY_PREFIX)) {
264 continue;
265 }
266 const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
267 if (match?.[1]) {
268 return { url: match[1], terminated: true };
269 }
270 }
271 const trailing = lines[lines.length - 1] ?? "";
272 if (trailing.startsWith(OPENCODE_SERVER_READY_PREFIX)) {
273 const match = trailing.match(/on\s+(https?:\/\/[^\s]+)/);
274 if (match?.[1]) {
275 return { url: match[1], terminated: false };
276 }
277 }
278 return null;
280​
281export function parseOpenCodeModelSlug(
282 slug: string | null | undefined,
283): ParsedOpenCodeModelSlug | null {
284 if (typeof slug !== "string") {
285 return null;
286 }
287​
288 const trimmed = slug.trim();
289 const separator = trimmed.indexOf("/");
290 if (separator <= 0 || separator === trimmed.length - 1) {
291 return null;
292 }
293​
294 return {
295 providerID: trimmed.slice(0, separator),
296 modelID: trimmed.slice(separator + 1),
297 };
299​
300/**
301 * Attachments OpenCode can hand to a model as a native file part. Anything
302 * else (ZIP, binaries, image formats like BMP/AVIF/SVG that model APIs
303 * reject, or files over the direct-attachment size limit) would make the turn
304 * fail before it starts, so those ride only as the file path ProviderService
305 * puts in the prompt.
306 */
307const OPENCODE_NATIVE_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
308const OPENCODE_NATIVE_FILE_PART_MAX_BYTES = 20 * 1024 * 1024;
309​
310function isOpenCodeNativeFilePart(input: {
311 readonly mimeType: string;
312 readonly sizeBytes: number;
313}): boolean {
314 if (input.sizeBytes > OPENCODE_NATIVE_FILE_PART_MAX_BYTES) {
315 return false;
316 }
317 const normalized = input.mimeType.trim().toLowerCase();
318 return (
319 OPENCODE_NATIVE_IMAGE_MIMES.has(normalized) ||
320 normalized.startsWith("text/") ||
321 normalized === "application/pdf"
322 );
324​
325export function toOpenCodeFileParts(input: {
326 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
327 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
328}): Array<{ uri: string; name?: string }> {
329 const parts: Array<{ uri: string; name?: string }> = [];
330​
331 for (const attachment of input.attachments ?? []) {
332 if (
333 attachment.type === "file" &&
334 "source" in attachment &&
335 attachment.source?._tag === "pasted-text"
336 ) {
337 continue;
338 }
339 if (!isOpenCodeNativeFilePart(attachment)) {
340 continue;
341 }
342 const attachmentPath = input.resolveAttachmentPath(attachment);
343 if (!attachmentPath) {
344 continue;
345 }
346​
347 parts.push({
348 uri: NodeURL.pathToFileURL(attachmentPath).href,
349 name: attachment.name,
350 });
351 }
352​
353 return parts;
355​
356export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
357 if (runtimeMode === "full-access") {
358 return [
359 { action: "*", resource: "*", effect: "allow" },
360 { action: "external_directory", resource: "*", effect: "allow" },
361 ];
362 }
363​
364 // "Auto-accept edits" is documented as "auto-approve edits, ask before other
365 // actions", so prompting for every edit ignores the mode the user picked.
366 // "auto" is left asking on purpose: the docs say providers without an AI
367 // reviewer, OpenCode among them, fall back to Supervised for that mode.
368 const editAction = runtimeMode === "auto-accept-edits" ? "allow" : "ask";
369​
370 // Session rules override OpenCode's agent defaults. Allow reads and task
371 // updates, but keep its default approval rules for environment files.
372 return [
373 { action: "*", resource: "*", effect: "ask" },
374 { action: "read", resource: "*", effect: "allow" },
375 { action: "read", resource: "*.env", effect: "ask" },
376 { action: "read", resource: "*.env.*", effect: "ask" },
377 { action: "read", resource: "*.env.example", effect: "allow" },
378 { action: "glob", resource: "*", effect: "allow" },
379 { action: "grep", resource: "*", effect: "allow" },
380 { action: "lsp", resource: "*", effect: "allow" },
381 { action: "skill", resource: "*", effect: "allow" },
382 { action: "todowrite", resource: "*", effect: "allow" },
383 { action: "shell", resource: "*", effect: "ask" },
384 { action: "edit", resource: "*", effect: editAction },
385 { action: "webfetch", resource: "*", effect: "ask" },
386 { action: "websearch", resource: "*", effect: "ask" },
387 { action: "codesearch", resource: "*", effect: "ask" },
388 { action: "external_directory", resource: "*", effect: "ask" },
389 { action: "doom_loop", resource: "*", effect: "ask" },
390 { action: "question", resource: "*", effect: "allow" },
391 ];
393​
394export function toOpenCodePermissionReply(
395 decision: ProviderApprovalDecision,
396): "once" | "always" | "reject" {
397 switch (decision) {
398 case "accept":
399 return "once";
400 case "acceptForSession":
401 case "acceptAlways":
402 return "always";
403 case "decline":
404 case "cancel":
405 default:
406 return "reject";
407 }
409​
410export function toOpenCodeQuestionAnswers(
411 request: FormInfo | FormInfo1,
412 answers: Record<string, unknown>,
413): FormAnswer {
414 const result: FormAnswer = {};
415 for (const field of request.fields) {
416 if (field.type === "external") continue;
417 const raw = answers[field.key];
418 const values = Array.isArray(raw) ? raw : raw === undefined ? [] : [raw];
419 if (values.length === 0 && !field.required) continue;
420 const options = "options" in field ? field.options : undefined;
421 // Match the UI's submitted identifier: `normalizeOpenCodeForm` round-trips
422 // the native option `value` through `UserInputQuestionOption.value`, and
423 // the web client submits that value (`option.value ?? option.label`).
424 // Values win over labels across the whole option list so a duplicate
425 // label can never shadow another option's native value; labels remain a
426 // display fallback for answers authored by hand.
427 const value = (item: unknown) =>
428 options?.find((option) => option.value === item)?.value ??
429 options?.find((option) => option.label === item)?.value ??
430 item;
431 const first = value(values[0]);
432 if (field.type === "multiselect")
433 result[field.key] = values
434 .map(value)
435 .filter((item): item is string => typeof item === "string");
436 else if (field.type === "boolean") {
437 if (typeof first === "boolean") result[field.key] = first;
438 else if (first === "true" || first === "false") result[field.key] = first === "true";
439 } else if (field.type === "number" || field.type === "integer") {
440 const number =
441 typeof first === "number"
442 ? first
443 : typeof first === "string" && first.trim()
444 ? Number(first)
445 : Number.NaN;
446 if (Number.isFinite(number) && (field.type !== "integer" || Number.isInteger(number)))
447 result[field.key] = number;
448 } else if (typeof first === "string") result[field.key] = first;
449 }
450 return result;
452​
453function ensureRuntimeError(
454 operation: OpenCodeRuntimeError["operation"],
455 detail: string,
456 cause: unknown,
457): OpenCodeRuntimeError {
458 return OpenCodeRuntimeError.is(cause)
459 ? cause
460 : new OpenCodeRuntimeError({ operation, detail, cause });
462​
463const makeOpenCodeRuntime = Effect.gen(function* () {
464 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
465 const crypto = yield* Crypto.Crypto;
466 const netService = yield* NetService.NetService;
467 const hostPlatform = yield* HostProcessPlatform;
468 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
469 resolveSpawnCommand(command, args, env ? { env } : {});
470​
471 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
472 Effect.gen(function* () {
473 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
474 const child = yield* spawner.spawn(
475 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
476 detached: hostPlatform !== "win32",
477 shell: spawnCommand.shell,
478 ...(input.cwd ? { cwd: input.cwd } : {}),
479 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
480 }),
481 );
482 const terminateCommandGroup =
483 hostPlatform === "win32"
484 ? child.kill({ killSignal: "SIGKILL" }).pipe(Effect.asVoid)
485 : Effect.sync(() => {
486 try {
487 process.kill(-Number(child.pid), "SIGKILL");
488 } catch {
489 // The command and its process group may already have exited.
490 }
491 });
492 yield* Effect.addFinalizer(() => terminateCommandGroup.pipe(Effect.ignore));
493 const collectOptions =
494 input.maxOutputBytes === undefined ? undefined : { maxBytes: input.maxOutputBytes };
495 const [stdout, stderr, code] = yield* Effect.all(
496 [
497 collectStreamAsString(child.stdout, collectOptions),
498 collectStreamAsString(child.stderr, collectOptions),
499 child.exitCode,
500 ],
501 { concurrency: "unbounded" },
502 );
503 const exitCode = Number(code);
504 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
505 return yield* new OpenCodeRuntimeError({
506 operation: "runOpenCodeCommand",
507 detail: `spawn ${input.binaryPath} ENOENT`,
508 });
509 }
510 return {
511 stdout,
512 stderr,
513 code: exitCode,
514 } satisfies OpenCodeCommandResult;
515 }).pipe(
516 Effect.scoped,
517 Effect.mapError((cause) =>
518 ensureRuntimeError(
519 "runOpenCodeCommand",
520 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
521 cause,
522 ),
523 ),
524 );
525​
526 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
527 OpenCode.make({
528 baseUrl: input.baseUrl,
529 ...(input.serverPassword
530 ? {
531 headers: {
532 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
533 },
534 }
535 : {}),
536 });
537​
538 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
539 Effect.gen(function* () {
540 // Bind this server's lifetime to the caller's scope. When the caller's
541 // scope closes, the spawned child is killed and all associated fibers
542 // are interrupted automatically — no `close()` method needed.
543 const runtimeScope = yield* Scope.Scope;
544​
545 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
546 const port =
547 input.port ??
548 (yield* netService.findAvailablePort(0).pipe(
549 Effect.mapError(
550 (cause) =>
551 new OpenCodeRuntimeError({
552 operation: "startOpenCodeServerProcess",
553 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
554 cause,
555 }),
556 ),
557 ));
558 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
559 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
560 const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
561 const serverPassword =
562 resolveOpenCodeServerPassword({
563 external: false,
564 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
565 ...(input.environment !== undefined ? { environment: input.environment } : {}),
566 }) ||
567 (yield* crypto.randomUUIDv4.pipe(
568 Effect.mapError(
569 (cause) =>
570 new OpenCodeRuntimeError({
571 operation: "startOpenCodeServerProcess",
572 detail: "Failed to generate an OpenCode server password.",
573 cause,
574 }),
575 ),
576 ));
577​
578 const resolvedConfigContent = resolveOpenCodeConfigContent(input.environment);
579 const child = yield* spawner
580 .spawn(
581 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
582 detached: hostPlatform !== "win32",
583 shell: spawnCommand.shell,
584 env: {
585 ...input.environment,
586 OPENCODE_PASSWORD: serverPassword,
587 // Respect an OPENCODE_CONFIG_CONTENT provided by the caller or
588 // the inherited process environment. When neither is provided,
589 // do NOT set OPENCODE_CONFIG_CONTENT so OpenCode reads the user's
590 // default configuration (~/.config/opencode/opencode.json). Setting
591 // it unconditionally to "{}" previously clobbered the user's
592 // opencode config, hiding their providers/models.
593 ...(resolvedConfigContent !== undefined
594 ? { OPENCODE_CONFIG_CONTENT: resolvedConfigContent }
595 : {}),
596 },
597 extendEnv: input.environment === undefined,
598 }),
599 )
600 .pipe(
601 Effect.provideService(Scope.Scope, runtimeScope),
602 Effect.mapError(
603 (cause) =>
604 new OpenCodeRuntimeError({
605 operation: "startOpenCodeServerProcess",
606 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
607 cause,
608 }),
609 ),
610 );
611​
612 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
613 hostPlatform === "win32"
614 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
615 : Effect.sync(() => {
616 try {
617 process.kill(-Number(child.pid), signal);
618 } catch {
619 // The direct child may already have exited after starting the
620 // server; the process group kill is best-effort cleanup for
621 // any serve process left in that group.
622 }
623 });
624 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
625 Effect.andThen(Effect.sleep("1 second")),
626 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
627 Effect.ignore,
628 );
629 yield* Scope.addFinalizer(runtimeScope, terminateChild);
630​
631 const stdoutRef = yield* Ref.make<string | null>("");
632 const stderrRef = yield* Ref.make<string | null>("");
633 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
634​
635 const setReadyFromStdoutChunk = (chunk: string) =>
636 Ref.modify(stdoutRef, (stdout) => {
637 if (stdout === null) {
638 return [null, null] as const;
639 }
640 const nextStdout = `${stdout}${chunk}`;
641 return [
642 parseServerUrlFromOutput(nextStdout),
643 nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
644 ] as const;
645 }).pipe(
646 Effect.flatMap((parsed) =>
647 parsed === null
648 ? Effect.void
649 : parsed.terminated
650 ? Deferred.succeed(readyDeferred, parsed.url).pipe(Effect.ignore)
651 : confirmSettledReadyUrl(parsed.url).pipe(Effect.ignore),
652 ),
653 );
654​
655 // An unterminated readiness candidate may be a partial chunk of a line
656 // still in flight. Give the output a moment to settle: if it grows,
657 // re-parse (the next chunk's handler also runs, so this just avoids
658 // resolving with a truncated URL when no further chunk ever arrives).
659 const confirmSettledReadyUrl = (candidate: string): Effect.Effect<void> =>
660 Effect.gen(function* () {
661 if (yield* Deferred.isDone(readyDeferred)) {
662 return;
663 }
664 const before = yield* Ref.get(stdoutRef);
665 yield* Effect.sleep("300 millis");
666 if (yield* Deferred.isDone(readyDeferred)) {
667 return;
668 }
669 const after = yield* Ref.get(stdoutRef);
670 if (after === null || after === before) {
671 yield* Deferred.succeed(readyDeferred, candidate).pipe(Effect.ignore);
672 return;
673 }
674 const reparsed = parseServerUrlFromOutput(after);
675 if (reparsed === null) {
676 yield* Deferred.succeed(readyDeferred, candidate).pipe(Effect.ignore);
677 } else if (reparsed.terminated) {
678 yield* Deferred.succeed(readyDeferred, reparsed.url).pipe(Effect.ignore);
679 } else {
680 yield* confirmSettledReadyUrl(reparsed.url);
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 const stdout = ((yield* Ref.get(stdoutRef)) ?? "").replaceAll(
707 serverPassword,
708 "[redacted]",
709 );
710 const stderr = ((yield* Ref.get(stderrRef)) ?? "").replaceAll(
711 serverPassword,
712 "[redacted]",
713 );
714 const exitCode = Number(code);
715 yield* Deferred.fail(
716 readyDeferred,
717 new OpenCodeRuntimeError({
718 operation: "startOpenCodeServerProcess",
719 detail: [
720 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
721 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
722 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
723 ]
724 .filter(Boolean)
725 .join("\n\n"),
726 cause: { exitCode, stdout, stderr },
727 }),
728 ).pipe(Effect.ignore);
729 }),
730 ),
731 Effect.ignore,
732 Effect.forkIn(runtimeScope),
733 );
734​
735 const readyExit = yield* Effect.exit(
736 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
737 );
738​
739 if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {
740 yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);
741 }
742​
743 if (Exit.isFailure(readyExit)) {
744 const squashed = Cause.squash(readyExit.cause);
745 return yield* ensureRuntimeError(
746 "startOpenCodeServerProcess",
747 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
748 squashed,
749 );
750 }
751​
752 const readyOption = readyExit.value;
753 if (Option.isNone(readyOption)) {
754 return yield* new OpenCodeRuntimeError({
755 operation: "startOpenCodeServerProcess",
756 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
757 });
758 }
759​
760 // Keep draining both pipes until the process scope closes. Stopping the
761 // readers can block OpenCode when its output buffers fill. Startup output
762 // is no longer needed, so discard later output instead of retaining it.
763 yield* Ref.set(stdoutRef, null);
764 yield* Ref.set(stderrRef, null);
765​
766 const url = readyOption.value;
767 const version = yield* verifyOpenCodeServerVersion(
768 createOpenCodeSdkClient({
769 baseUrl: url,
770 ...(serverPassword !== undefined ? { serverPassword } : {}),
771 }),
772 );
773​
774 return {
775 url,
776 ...(serverPassword !== undefined ? { serverPassword } : {}),
777 version,
778 isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
779 exitCode: child.exitCode.pipe(
780 Effect.map(Number),
781 Effect.orElseSucceed(() => 0),
782 ),
783 } satisfies OpenCodeServerProcess;
784 });
785​
786 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
787 const serverUrl = input.serverUrl?.trim();
788 if (serverUrl) {
789 const serverPassword = resolveOpenCodeServerPassword({
790 external: true,
791 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
792 });
793 return verifyOpenCodeServerVersion(
794 createOpenCodeSdkClient({
795 baseUrl: serverUrl,
796 ...(serverPassword !== undefined ? { serverPassword } : {}),
797 }),
798 ).pipe(
799 Effect.map((version) => ({
800 url: serverUrl,
801 ...(serverPassword !== undefined ? { serverPassword } : {}),
802 version,
803 exitCode: null,
804 external: true,
805 })),
806 );
807 }
808​
809 return startOpenCodeServerProcess({
810 binaryPath: input.binaryPath,
811 directory: input.directory,
812 ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
813 ...(input.environment !== undefined ? { environment: input.environment } : {}),
814 ...(input.port !== undefined ? { port: input.port } : {}),
815 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
816 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
817 }).pipe(
818 Effect.map((server) => ({
819 url: server.url,
820 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
821 version: server.version,
822 exitCode: server.exitCode,
823 external: false,
824 })),
825 );
826 };
827​
828 const loadOpenCodeSkills: OpenCodeRuntimeShape["loadOpenCodeSkills"] = (client, directory) =>
829 runOpenCodeSdk("skill.list", (signal) =>
830 client.skill.list({ location: { directory } }, { signal }),
831 ).pipe(Effect.map((result) => result.data));
832​
833 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (
834 client,
835 directory,
836 ) =>
837 Effect.all(
838 [
839 runOpenCodeSdk("provider.list", (signal) =>
840 client.provider.list({ location: { directory } }, { signal }),
841 ).pipe(Effect.map((result) => result.data)),
842 runOpenCodeSdk("model.list", (signal) =>
843 client.model.list({ location: { directory } }, { signal }),
844 ).pipe(Effect.map((result) => result.data)),
845 runOpenCodeSdk("agent.list", (signal) =>
846 client.agent.list({ location: { directory } }, { signal }),
847 ).pipe(
848 Effect.map((result) => result.data),
849 Effect.orElseSucceed(() => []),
850 ),
851 loadOpenCodeSkills(client, directory).pipe(Effect.orElseSucceed(() => [])),
852 loadOpenCodeCommands(client, directory).pipe(Effect.orElseSucceed(() => [])),
853 ],
854 {
855 concurrency: "unbounded",
856 },
857 ).pipe(
858 Effect.map(([providers, models, agents, skills, commands]) => ({
859 providers,
860 models,
861 agents,
862 skills,
863 commands,
864 })),
865 );
866​
867 return {
868 startOpenCodeServerProcess,
869 connectToOpenCodeServer,
870 runOpenCodeCommand,
871 createOpenCodeSdkClient,
872 loadOpenCodeInventory,
873 loadOpenCodeSkills,
874 } satisfies OpenCodeRuntimeShape;
875});
876​
877export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
878 "t3/provider/opencodeRuntime",
879) {}
880​
881export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
882 Layer.provide(NetService.layer),
883);