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