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

opencodeRuntime.ts

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