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