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

opencodeRuntime.ts

560 lines19.4 KB

1import { pathToFileURL } from "node:url";
2​
3import type { ChatAttachment, ProviderApprovalDecision, RuntimeMode } from "@t3tools/contracts";
4import {
5 createOpencodeClient,
6 type Agent,
7 type FilePartInput,
8 type OpencodeClient,
9 type PermissionRuleset,
10 type ProviderListResponse,
11 type QuestionAnswer,
12 type QuestionRequest,
13} from "@opencode-ai/sdk/v2";
14import * as Cause from "effect/Cause";
15import * as Context from "effect/Context";
16import * as Data from "effect/Data";
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 Stream from "effect/Stream";
29import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
30​
31import { isWindowsCommandNotFound } from "../processRunner.ts";
32import { collectStreamAsString } from "./providerSnapshot.ts";
33import * as NetService from "@t3tools/shared/Net";
34import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
35import { resolveSpawnCommand } from "@t3tools/shared/shell";
36const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
37const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
38​
39const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
40const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
41const DEFAULT_HOSTNAME = "127.0.0.1";
42export interface OpenCodeServerProcess {
43 readonly url: string;
44 readonly exitCode: Effect.Effect<number, never>;
46​
47export interface OpenCodeServerConnection {
48 readonly url: string;
49 readonly exitCode: Effect.Effect<number, never> | null;
50 readonly external: boolean;
52​
53const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
54export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
55 readonly operation: string;
56 readonly cause?: unknown;
57 readonly detail: string;
58}> {
59 static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
60 P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
62​
63function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
64 const result = encodeUnknownJsonStringExit(input);
65 return Exit.isSuccess(result) ? result.value : undefined;
67​
68export function openCodeRuntimeErrorDetail(cause: unknown): string {
69 if (OpenCodeRuntimeError.is(cause)) return cause.detail;
70 if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
71 if (cause && typeof cause === "object") {
72 // SDK v2 throws { response, request, error? } shapes — extract what's useful
73 const anyCause = cause as Record<string, unknown>;
74 const status = (anyCause.response as { status?: number } | undefined)?.status;
75 const body = anyCause.error ?? anyCause.data ?? anyCause.body;
76 const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);
77 if (encodedBody) {
78 return `status=${status ?? "?"} body=${encodedBody}`;
79 }
80 }
81 return String(cause);
83​
84export const runOpenCodeSdk = <A>(
85 operation: string,
86 fn: () => Promise<A>,
87): Effect.Effect<A, OpenCodeRuntimeError> =>
88 Effect.tryPromise({
89 try: fn,
90 catch: (cause) =>
91 new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
92 }).pipe(Effect.withSpan(`opencode.${operation}`));
93​
94export interface OpenCodeCommandResult {
95 readonly stdout: string;
96 readonly stderr: string;
97 readonly code: number;
99​
100export interface OpenCodeInventory {
101 readonly providerList: ProviderListResponse;
102 readonly agents: ReadonlyArray<Agent>;
104​
105export interface ParsedOpenCodeModelSlug {
106 readonly providerID: string;
107 readonly modelID: string;
109​
110export interface OpenCodeRuntimeShape {
111 /**
112 * Spawns a local OpenCode server process. Its lifetime is bound to the caller's
113 * `Scope.Scope` — the child is killed automatically when that scope closes.
114 * Consumers that want a long-lived server must create and hold a scope explicitly
115 * (see {@link Scope.make}) and close it when done.
116 */
117 readonly startOpenCodeServerProcess: (input: {
118 readonly binaryPath: string;
119 readonly environment?: NodeJS.ProcessEnv;
120 readonly port?: number;
121 readonly hostname?: string;
122 readonly timeoutMs?: number;
123 }) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
124 /**
125 * Returns a handle to either an externally-managed OpenCode server (when
126 * `serverUrl` is provided — no lifetime is attached to the caller's scope) or a
127 * freshly spawned local server whose lifetime is bound to the caller's scope.
128 */
129 readonly connectToOpenCodeServer: (input: {
130 readonly binaryPath: string;
131 readonly serverUrl?: string | null;
132 readonly environment?: NodeJS.ProcessEnv;
133 readonly port?: number;
134 readonly hostname?: string;
135 readonly timeoutMs?: number;
136 }) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
137 readonly runOpenCodeCommand: (input: {
138 readonly binaryPath: string;
139 readonly args: ReadonlyArray<string>;
140 readonly environment?: NodeJS.ProcessEnv;
141 }) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
142 readonly createOpenCodeSdkClient: (input: {
143 readonly baseUrl: string;
144 readonly directory: string;
145 readonly serverPassword?: string;
146 }) => OpencodeClient;
147 readonly loadOpenCodeInventory: (
148 client: OpencodeClient,
149 ) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
151​
152function parseServerUrlFromOutput(output: string): string | null {
153 for (const line of output.split("\n")) {
154 if (!line.startsWith(OPENCODE_SERVER_READY_PREFIX)) {
155 continue;
156 }
157 const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
158 return match?.[1] ?? null;
159 }
160 return null;
162​
163export function parseOpenCodeModelSlug(
164 slug: string | null | undefined,
165): ParsedOpenCodeModelSlug | null {
166 if (typeof slug !== "string") {
167 return null;
168 }
169​
170 const trimmed = slug.trim();
171 const separator = trimmed.indexOf("/");
172 if (separator <= 0 || separator === trimmed.length - 1) {
173 return null;
174 }
175​
176 return {
177 providerID: trimmed.slice(0, separator),
178 modelID: trimmed.slice(separator + 1),
179 };
181​
182export function openCodeQuestionId(
183 index: number,
184 question: QuestionRequest["questions"][number],
185): string {
186 const header = question.header
187 .trim()
188 .toLowerCase()
189 .replace(/[^a-z0-9_-]+/g, "-");
190 return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
192​
193export function toOpenCodeFileParts(input: {
194 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
195 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
196}): Array<FilePartInput> {
197 const parts: Array<FilePartInput> = [];
198​
199 for (const attachment of input.attachments ?? []) {
200 const attachmentPath = input.resolveAttachmentPath(attachment);
201 if (!attachmentPath) {
202 continue;
203 }
204​
205 parts.push({
206 type: "file",
207 mime: attachment.mimeType,
208 filename: attachment.name,
209 url: pathToFileURL(attachmentPath).href,
210 });
211 }
212​
213 return parts;
215​
216export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
217 if (runtimeMode === "full-access") {
218 return [{ permission: "*", pattern: "*", action: "allow" }];
219 }
220​
221 return [
222 { permission: "*", pattern: "*", action: "ask" },
223 { permission: "bash", pattern: "*", action: "ask" },
224 { permission: "edit", pattern: "*", action: "ask" },
225 { permission: "webfetch", pattern: "*", action: "ask" },
226 { permission: "websearch", pattern: "*", action: "ask" },
227 { permission: "codesearch", pattern: "*", action: "ask" },
228 { permission: "external_directory", pattern: "*", action: "ask" },
229 { permission: "doom_loop", pattern: "*", action: "ask" },
230 { permission: "question", pattern: "*", action: "allow" },
231 ];
233​
234export function toOpenCodePermissionReply(
235 decision: ProviderApprovalDecision,
236): "once" | "always" | "reject" {
237 switch (decision) {
238 case "accept":
239 return "once";
240 case "acceptForSession":
241 return "always";
242 case "decline":
243 case "cancel":
244 default:
245 return "reject";
246 }
248​
249export function toOpenCodeQuestionAnswers(
250 request: QuestionRequest,
251 answers: Record<string, unknown>,
252): Array<QuestionAnswer> {
253 return request.questions.map((question, index) => {
254 const raw =
255 answers[openCodeQuestionId(index, question)] ??
256 answers[question.header] ??
257 answers[question.question];
258 if (Array.isArray(raw)) {
259 return raw.filter((value): value is string => typeof value === "string");
260 }
261 if (typeof raw === "string") {
262 return raw.trim().length > 0 ? [raw] : [];
263 }
264 return [];
265 });
267​
268function ensureRuntimeError(
269 operation: OpenCodeRuntimeError["operation"],
270 detail: string,
271 cause: unknown,
272): OpenCodeRuntimeError {
273 return OpenCodeRuntimeError.is(cause)
274 ? cause
275 : new OpenCodeRuntimeError({ operation, detail, cause });
277​
278const makeOpenCodeRuntime = Effect.gen(function* () {
279 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
280 const netService = yield* NetService.NetService;
281 const hostPlatform = yield* HostProcessPlatform;
282 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
283 resolveSpawnCommand(command, args, env ? { env } : {});
284​
285 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
286 Effect.gen(function* () {
287 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
288 const child = yield* spawner.spawn(
289 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
290 shell: spawnCommand.shell,
291 ...(input.environment ? { env: input.environment } : { extendEnv: true }),
292 }),
293 );
294 const [stdout, stderr, code] = yield* Effect.all(
295 [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],
296 { concurrency: "unbounded" },
297 );
298 const exitCode = Number(code);
299 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
300 return yield* new OpenCodeRuntimeError({
301 operation: "runOpenCodeCommand",
302 detail: `spawn ${input.binaryPath} ENOENT`,
303 });
304 }
305 return {
306 stdout,
307 stderr,
308 code: exitCode,
309 } satisfies OpenCodeCommandResult;
310 }).pipe(
311 Effect.scoped,
312 Effect.mapError((cause) =>
313 ensureRuntimeError(
314 "runOpenCodeCommand",
315 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
316 cause,
317 ),
318 ),
319 );
320​
321 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
322 Effect.gen(function* () {
323 // Bind this server's lifetime to the caller's scope. When the caller's
324 // scope closes, the spawned child is killed and all associated fibers
325 // are interrupted automatically — no `close()` method needed.
326 const runtimeScope = yield* Scope.Scope;
327​
328 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
329 const port =
330 input.port ??
331 (yield* netService.findAvailablePort(0).pipe(
332 Effect.mapError(
333 (cause) =>
334 new OpenCodeRuntimeError({
335 operation: "startOpenCodeServerProcess",
336 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
337 cause,
338 }),
339 ),
340 ));
341 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
342 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
343 const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
344​
345 const child = yield* spawner
346 .spawn(
347 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
348 detached: hostPlatform !== "win32",
349 shell: spawnCommand.shell,
350 env: {
351 ...input.environment,
352 OPENCODE_CONFIG_CONTENT: OPENCODE_EMPTY_CONFIG_CONTENT,
353 },
354 extendEnv: input.environment === undefined,
355 }),
356 )
357 .pipe(
358 Effect.provideService(Scope.Scope, runtimeScope),
359 Effect.mapError(
360 (cause) =>
361 new OpenCodeRuntimeError({
362 operation: "startOpenCodeServerProcess",
363 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
364 cause,
365 }),
366 ),
367 );
368​
369 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
370 hostPlatform === "win32"
371 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
372 : Effect.sync(() => {
373 try {
374 process.kill(-Number(child.pid), signal);
375 } catch {
376 // The direct child may already have exited after starting the
377 // server; the process group kill is best-effort cleanup for
378 // any serve process left in that group.
379 }
380 });
381 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
382 Effect.andThen(Effect.sleep("1 second")),
383 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
384 Effect.ignore,
385 );
386 yield* Scope.addFinalizer(runtimeScope, terminateChild);
387​
388 const stdoutRef = yield* Ref.make("");
389 const stderrRef = yield* Ref.make("");
390 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
391​
392 const setReadyFromStdoutChunk = (chunk: string) =>
393 Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(
394 Effect.flatMap((nextStdout) => {
395 const parsed = parseServerUrlFromOutput(nextStdout);
396 return parsed
397 ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)
398 : Effect.void;
399 }),
400 );
401​
402 const stdoutFiber = yield* child.stdout.pipe(
403 Stream.decodeText(),
404 Stream.runForEach(setReadyFromStdoutChunk),
405 Effect.ignore,
406 Effect.forkIn(runtimeScope),
407 );
408 const stderrFiber = yield* child.stderr.pipe(
409 Stream.decodeText(),
410 Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),
411 Effect.ignore,
412 Effect.forkIn(runtimeScope),
413 );
414​
415 const exitFiber = yield* child.exitCode.pipe(
416 Effect.flatMap((code) =>
417 Effect.gen(function* () {
418 const stdout = yield* Ref.get(stdoutRef);
419 const stderr = yield* Ref.get(stderrRef);
420 const exitCode = Number(code);
421 yield* Deferred.fail(
422 readyDeferred,
423 new OpenCodeRuntimeError({
424 operation: "startOpenCodeServerProcess",
425 detail: [
426 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
427 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
428 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
429 ]
430 .filter(Boolean)
431 .join("\n\n"),
432 cause: { exitCode, stdout, stderr },
433 }),
434 ).pipe(Effect.ignore);
435 }),
436 ),
437 Effect.ignore,
438 Effect.forkIn(runtimeScope),
439 );
440​
441 const readyExit = yield* Effect.exit(
442 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
443 );
444​
445 // Startup-time fibers are no longer needed once ready has resolved (either
446 // way). The exit fiber is only interrupted on failure; on success it keeps
447 // the caller's `exitCode` effect observable until the scope closes.
448 yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);
449 yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);
450​
451 if (Exit.isFailure(readyExit)) {
452 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
453 const squashed = Cause.squash(readyExit.cause);
454 return yield* ensureRuntimeError(
455 "startOpenCodeServerProcess",
456 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
457 squashed,
458 );
459 }
460​
461 const readyOption = readyExit.value;
462 if (Option.isNone(readyOption)) {
463 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
464 return yield* new OpenCodeRuntimeError({
465 operation: "startOpenCodeServerProcess",
466 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
467 });
468 }
469​
470 return {
471 url: readyOption.value,
472 exitCode: child.exitCode.pipe(
473 Effect.map(Number),
474 Effect.orElseSucceed(() => 0),
475 ),
476 } satisfies OpenCodeServerProcess;
477 });
478​
479 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
480 const serverUrl = input.serverUrl?.trim();
481 if (serverUrl) {
482 // We don't own externally-configured servers — no scope interaction.
483 return Effect.succeed({
484 url: serverUrl,
485 exitCode: null,
486 external: true,
487 });
488 }
489​
490 return startOpenCodeServerProcess({
491 binaryPath: input.binaryPath,
492 ...(input.environment !== undefined ? { environment: input.environment } : {}),
493 ...(input.port !== undefined ? { port: input.port } : {}),
494 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
495 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
496 }).pipe(
497 Effect.map((server) => ({
498 url: server.url,
499 exitCode: server.exitCode,
500 external: false,
501 })),
502 );
503 };
504​
505 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
506 createOpencodeClient({
507 baseUrl: input.baseUrl,
508 directory: input.directory,
509 ...(input.serverPassword
510 ? {
511 headers: {
512 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
513 },
514 }
515 : {}),
516 throwOnError: true,
517 });
518​
519 const loadProviders = (client: OpencodeClient) =>
520 runOpenCodeSdk("provider.list", () => client.provider.list()).pipe(
521 Effect.filterMapOrFail(
522 (list) =>
523 list.data
524 ? Result.succeed(list.data)
525 : Result.fail(
526 new OpenCodeRuntimeError({
527 operation: "provider.list",
528 detail: "OpenCode provider list was empty.",
529 }),
530 ),
531 (result) => result,
532 ),
533 );
534​
535 const loadAgents = (client: OpencodeClient) =>
536 runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
537 Effect.map((result) => result.data ?? []),
538 );
539​
540 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
541 Effect.all([loadProviders(client), loadAgents(client)], { concurrency: "unbounded" }).pipe(
542 Effect.map(([providerList, agents]) => ({ providerList, agents })),
543 );
544​
545 return {
546 startOpenCodeServerProcess,
547 connectToOpenCodeServer,
548 runOpenCodeCommand,
549 createOpenCodeSdkClient,
550 loadOpenCodeInventory,
551 } satisfies OpenCodeRuntimeShape;
552});
553​
554export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
555 "t3/provider/opencodeRuntime",
556) {}
557​
558export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
559 Layer.provide(NetService.layer),
560);