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

opencodeRuntime.ts

556 lines19.0 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 readonly sseMaxRetryAttempts?: number;
145 }) => OpencodeClient;
146 readonly loadOpenCodeInventory: (
147 client: OpencodeClient,
148 ) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
150​
151function parseServerUrlFromOutput(output: string): string | null {
152 for (const line of output.split("\n")) {
153 if (!line.startsWith(OPENCODE_SERVER_READY_PREFIX)) {
154 continue;
155 }
156 const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
157 return match?.[1] ?? null;
158 }
159 return null;
161​
162export function parseOpenCodeModelSlug(
163 slug: string | null | undefined,
164): ParsedOpenCodeModelSlug | null {
165 if (typeof slug !== "string") {
166 return null;
167 }
168​
169 const trimmed = slug.trim();
170 const separator = trimmed.indexOf("/");
171 if (separator <= 0 || separator === trimmed.length - 1) {
172 return null;
173 }
174​
175 return {
176 providerID: trimmed.slice(0, separator),
177 modelID: trimmed.slice(separator + 1),
178 };
180​
181export function openCodeQuestionId(
182 index: number,
183 question: QuestionRequest["questions"][number],
184): string {
185 const header = question.header
186 .trim()
187 .toLowerCase()
188 .replace(/[^a-z0-9_-]+/g, "-");
189 return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
191​
192export function toOpenCodeFileParts(input: {
193 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
194 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
195}): Array<FilePartInput> {
196 const parts: Array<FilePartInput> = [];
197​
198 for (const attachment of input.attachments ?? []) {
199 const attachmentPath = input.resolveAttachmentPath(attachment);
200 if (!attachmentPath) {
201 continue;
202 }
203​
204 parts.push({
205 type: "file",
206 mime: attachment.mimeType,
207 filename: attachment.name,
208 url: pathToFileURL(attachmentPath).href,
209 });
210 }
211​
212 return parts;
214​
215export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
216 if (runtimeMode === "full-access") {
217 return [{ permission: "*", pattern: "*", action: "allow" }];
218 }
219​
220 return [
221 { permission: "*", pattern: "*", action: "ask" },
222 { permission: "bash", pattern: "*", action: "ask" },
223 { permission: "edit", pattern: "*", action: "ask" },
224 { permission: "webfetch", pattern: "*", action: "ask" },
225 { permission: "websearch", pattern: "*", action: "ask" },
226 { permission: "codesearch", pattern: "*", action: "ask" },
227 { permission: "external_directory", pattern: "*", action: "ask" },
228 { permission: "doom_loop", pattern: "*", action: "ask" },
229 { permission: "question", pattern: "*", action: "allow" },
230 ];
232​
233export function toOpenCodePermissionReply(
234 decision: ProviderApprovalDecision,
235): "once" | "always" | "reject" {
236 switch (decision) {
237 case "accept":
238 return "once";
239 case "acceptForSession":
240 return "always";
241 case "decline":
242 case "cancel":
243 default:
244 return "reject";
245 }
247​
248export function toOpenCodeQuestionAnswers(
249 request: QuestionRequest,
250 answers: Record<string, unknown>,
251): Array<QuestionAnswer> {
252 return request.questions.map((question, index) => {
253 const raw =
254 answers[openCodeQuestionId(index, question)] ??
255 answers[question.header] ??
256 answers[question.question];
257 if (Array.isArray(raw)) {
258 return raw.filter((value): value is string => typeof value === "string");
259 }
260 if (typeof raw === "string") {
261 return raw.trim().length > 0 ? [raw] : [];
262 }
263 return [];
264 });
266​
267function ensureRuntimeError(
268 operation: OpenCodeRuntimeError["operation"],
269 detail: string,
270 cause: unknown,
271): OpenCodeRuntimeError {
272 return OpenCodeRuntimeError.is(cause)
273 ? cause
274 : new OpenCodeRuntimeError({ operation, detail, cause });
276​
277const makeOpenCodeRuntime = Effect.gen(function* () {
278 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
279 const netService = yield* NetService.NetService;
280​
281 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
282 Effect.gen(function* () {
283 const child = yield* spawner.spawn(
284 ChildProcess.make(input.binaryPath, [...input.args], {
285 shell: process.platform === "win32",
286 env: input.environment ?? process.env,
287 }),
288 );
289 const [stdout, stderr, code] = yield* Effect.all(
290 [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],
291 { concurrency: "unbounded" },
292 );
293 const exitCode = Number(code);
294 if (isWindowsCommandNotFound(exitCode, stderr)) {
295 return yield* new OpenCodeRuntimeError({
296 operation: "runOpenCodeCommand",
297 detail: `spawn ${input.binaryPath} ENOENT`,
298 });
299 }
300 return {
301 stdout,
302 stderr,
303 code: exitCode,
304 } satisfies OpenCodeCommandResult;
305 }).pipe(
306 Effect.scoped,
307 Effect.mapError((cause) =>
308 ensureRuntimeError(
309 "runOpenCodeCommand",
310 `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
311 cause,
312 ),
313 ),
314 );
315​
316 const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
317 Effect.gen(function* () {
318 // Bind this server's lifetime to the caller's scope. When the caller's
319 // scope closes, the spawned child is killed and all associated fibers
320 // are interrupted automatically — no `close()` method needed.
321 const runtimeScope = yield* Scope.Scope;
322​
323 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
324 const port =
325 input.port ??
326 (yield* netService.findAvailablePort(0).pipe(
327 Effect.mapError(
328 (cause) =>
329 new OpenCodeRuntimeError({
330 operation: "startOpenCodeServerProcess",
331 detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
332 cause,
333 }),
334 ),
335 ));
336 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
337 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
338​
339 const child = yield* spawner
340 .spawn(
341 ChildProcess.make(input.binaryPath, args, {
342 detached: process.platform !== "win32",
343 shell: process.platform === "win32",
344 env: {
345 ...(input.environment ?? process.env),
346 OPENCODE_CONFIG_CONTENT: OPENCODE_EMPTY_CONFIG_CONTENT,
347 },
348 }),
349 )
350 .pipe(
351 Effect.provideService(Scope.Scope, runtimeScope),
352 Effect.mapError(
353 (cause) =>
354 new OpenCodeRuntimeError({
355 operation: "startOpenCodeServerProcess",
356 detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
357 cause,
358 }),
359 ),
360 );
361​
362 const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
363 process.platform === "win32"
364 ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
365 : Effect.sync(() => {
366 try {
367 process.kill(-Number(child.pid), signal);
368 } catch {
369 // The direct child may already have exited after starting the
370 // server; the process group kill is best-effort cleanup for
371 // any serve process left in that group.
372 }
373 });
374 const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
375 Effect.andThen(Effect.sleep("1 second")),
376 Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
377 Effect.ignore,
378 );
379 yield* Scope.addFinalizer(runtimeScope, terminateChild);
380​
381 const stdoutRef = yield* Ref.make("");
382 const stderrRef = yield* Ref.make("");
383 const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
384​
385 const setReadyFromStdoutChunk = (chunk: string) =>
386 Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(
387 Effect.flatMap((nextStdout) => {
388 const parsed = parseServerUrlFromOutput(nextStdout);
389 return parsed
390 ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)
391 : Effect.void;
392 }),
393 );
394​
395 const stdoutFiber = yield* child.stdout.pipe(
396 Stream.decodeText(),
397 Stream.runForEach(setReadyFromStdoutChunk),
398 Effect.ignore,
399 Effect.forkIn(runtimeScope),
400 );
401 const stderrFiber = yield* child.stderr.pipe(
402 Stream.decodeText(),
403 Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),
404 Effect.ignore,
405 Effect.forkIn(runtimeScope),
406 );
407​
408 const exitFiber = yield* child.exitCode.pipe(
409 Effect.flatMap((code) =>
410 Effect.gen(function* () {
411 const stdout = yield* Ref.get(stdoutRef);
412 const stderr = yield* Ref.get(stderrRef);
413 const exitCode = Number(code);
414 yield* Deferred.fail(
415 readyDeferred,
416 new OpenCodeRuntimeError({
417 operation: "startOpenCodeServerProcess",
418 detail: [
419 `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
420 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
421 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
422 ]
423 .filter(Boolean)
424 .join("\n\n"),
425 cause: { exitCode, stdout, stderr },
426 }),
427 ).pipe(Effect.ignore);
428 }),
429 ),
430 Effect.ignore,
431 Effect.forkIn(runtimeScope),
432 );
433​
434 const readyExit = yield* Effect.exit(
435 Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
436 );
437​
438 // Startup-time fibers are no longer needed once ready has resolved (either
439 // way). The exit fiber is only interrupted on failure; on success it keeps
440 // the caller's `exitCode` effect observable until the scope closes.
441 yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);
442 yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);
443​
444 if (Exit.isFailure(readyExit)) {
445 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
446 const squashed = Cause.squash(readyExit.cause);
447 return yield* ensureRuntimeError(
448 "startOpenCodeServerProcess",
449 `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
450 squashed,
451 );
452 }
453​
454 const readyOption = readyExit.value;
455 if (Option.isNone(readyOption)) {
456 yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
457 return yield* new OpenCodeRuntimeError({
458 operation: "startOpenCodeServerProcess",
459 detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
460 });
461 }
462​
463 return {
464 url: readyOption.value,
465 exitCode: child.exitCode.pipe(
466 Effect.map(Number),
467 Effect.orElseSucceed(() => 0),
468 ),
469 } satisfies OpenCodeServerProcess;
470 });
471​
472 const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
473 const serverUrl = input.serverUrl?.trim();
474 if (serverUrl) {
475 // We don't own externally-configured servers — no scope interaction.
476 return Effect.succeed({
477 url: serverUrl,
478 exitCode: null,
479 external: true,
480 });
481 }
482​
483 return startOpenCodeServerProcess({
484 binaryPath: input.binaryPath,
485 ...(input.environment !== undefined ? { environment: input.environment } : {}),
486 ...(input.port !== undefined ? { port: input.port } : {}),
487 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
488 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
489 }).pipe(
490 Effect.map((server) => ({
491 url: server.url,
492 exitCode: server.exitCode,
493 external: false,
494 })),
495 );
496 };
497​
498 const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
499 createOpencodeClient({
500 baseUrl: input.baseUrl,
501 directory: input.directory,
502 ...(input.serverPassword
503 ? {
504 headers: {
505 Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
506 },
507 }
508 : {}),
509 ...(input.sseMaxRetryAttempts !== undefined
510 ? { sseMaxRetryAttempts: input.sseMaxRetryAttempts }
511 : {}),
512 throwOnError: true,
513 });
514​
515 const loadProviders = (client: OpencodeClient) =>
516 runOpenCodeSdk("provider.list", () => client.provider.list()).pipe(
517 Effect.filterMapOrFail(
518 (list) =>
519 list.data
520 ? Result.succeed(list.data)
521 : Result.fail(
522 new OpenCodeRuntimeError({
523 operation: "provider.list",
524 detail: "OpenCode provider list was empty.",
525 }),
526 ),
527 (result) => result,
528 ),
529 );
530​
531 const loadAgents = (client: OpencodeClient) =>
532 runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
533 Effect.map((result) => result.data ?? []),
534 );
535​
536 const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
537 Effect.all([loadProviders(client), loadAgents(client)], { concurrency: "unbounded" }).pipe(
538 Effect.map(([providerList, agents]) => ({ providerList, agents })),
539 );
540​
541 return {
542 startOpenCodeServerProcess,
543 connectToOpenCodeServer,
544 runOpenCodeCommand,
545 createOpenCodeSdkClient,
546 loadOpenCodeInventory,
547 } satisfies OpenCodeRuntimeShape;
548});
549​
550export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
551 "t3/provider/opencodeRuntime",
552) {}
553​
554export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
555 Layer.provide(NetService.layer),
556);