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

opencodeRuntime.ts

573 lines16.0 KB

1import { execFileSync, spawn, type ChildProcess } from "node:child_process";
2import * as FS from "node:fs";
3import { createServer, type AddressInfo } from "node:net";
4import * as OS from "node:os";
5import * as Path from "node:path";
6import { pathToFileURL } from "node:url";
7​
8import type {
9 ChatAttachment,
10 ModelCapabilities,
11 ProviderApprovalDecision,
12 RuntimeMode,
13 ServerProviderModel,
14} from "@workbench/contracts";
15import {
16 createOpencodeClient,
17 type Agent,
18 type FilePartInput,
19 type OpencodeClient,
20 type PermissionRuleset,
21 type ProviderListResponse,
22 type QuestionAnswer,
23 type QuestionRequest,
24} from "@opencode-ai/sdk/v2";
25​
26const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
27const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
28const DEFAULT_HOSTNAME = "127.0.0.1";
29​
30const OPENAI_VARIANTS = ["none", "minimal", "low", "medium", "high", "xhigh"];
31const ANTHROPIC_VARIANTS = ["high", "max"];
32const GOOGLE_VARIANTS = ["low", "high"];
33​
34export const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = {
35 reasoningEffortLevels: [],
36 supportsFastMode: false,
37 supportsThinkingToggle: false,
38 contextWindowOptions: [],
39 promptInjectedEffortLevels: [],
40};
41​
42export interface OpenCodeServerProcess {
43 readonly url: string;
44 readonly process: ChildProcess;
45 close(): void;
47​
48export interface OpenCodeServerConnection {
49 readonly url: string;
50 readonly process: ChildProcess | null;
51 readonly external: boolean;
52 close(): void;
54​
55function buildOpenCodeBasicAuthorizationHeader(password: string): string {
56 return `Basic ${Buffer.from(`opencode:${password}`, "utf8").toString("base64")}`;
58​
59export interface OpenCodeCommandResult {
60 readonly stdout: string;
61 readonly stderr: string;
62 readonly code: number;
64​
65export interface OpenCodeInventory {
66 readonly providerList: ProviderListResponse;
67 readonly agents: ReadonlyArray<Agent>;
69​
70export interface ParsedOpenCodeModelSlug {
71 readonly providerID: string;
72 readonly modelID: string;
74​
75function titleCaseSlug(value: string): string {
76 return value
77 .split(/[-_/]+/)
78 .filter((segment) => segment.length > 0)
79 .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
80 .join(" ");
82​
83function parseServerUrlFromOutput(output: string): string | null {
84 for (const line of output.split("\n")) {
85 if (!line.startsWith(OPENCODE_SERVER_READY_PREFIX)) {
86 continue;
87 }
88 const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
89 return match?.[1] ?? null;
90 }
91 return null;
93​
94function isPrimaryAgent(agent: Agent): boolean {
95 return !agent.hidden && (agent.mode === "primary" || agent.mode === "all");
97​
98function inferVariantValues(providerID: string): ReadonlyArray<string> {
99 if (providerID === "anthropic") {
100 return ANTHROPIC_VARIANTS;
101 }
102 if (providerID === "openai" || providerID === "opencode") {
103 return OPENAI_VARIANTS;
104 }
105 if (providerID.startsWith("google")) {
106 return GOOGLE_VARIANTS;
107 }
108 return [];
110​
111function inferDefaultVariant(
112 providerID: string,
113 variants: ReadonlyArray<string>,
114): string | undefined {
115 if (variants.length === 1) {
116 return variants[0];
117 }
118 if (providerID === "anthropic" || providerID.startsWith("google")) {
119 return variants.includes("high") ? "high" : undefined;
120 }
121 if (providerID === "openai" || providerID === "opencode") {
122 return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
123 }
124 return undefined;
126​
127function buildVariantOptions(
128 providerID: string,
129 model: ProviderListResponse["all"][number]["models"][string],
130) {
131 const variantValues = Object.keys(model.variants ?? {});
132 const resolvedValues =
133 variantValues.length > 0 ? variantValues : [...inferVariantValues(providerID)];
134 const defaultVariant = inferDefaultVariant(providerID, resolvedValues);
135​
136 return resolvedValues.map((value) => {
137 const option: { value: string; label: string; isDefault?: boolean } = {
138 value,
139 label: titleCaseSlug(value),
140 };
141 if (defaultVariant === value) {
142 option.isDefault = true;
143 }
144 return option;
145 });
147​
148function buildAgentOptions(agents: ReadonlyArray<Agent>) {
149 const primaryAgents = agents.filter(isPrimaryAgent);
150 const defaultAgent =
151 primaryAgents.find((agent) => agent.name === "build")?.name ??
152 primaryAgents[0]?.name ??
153 undefined;
154 return primaryAgents.map((agent) => {
155 const option: { value: string; label: string; isDefault?: boolean } = {
156 value: agent.name,
157 label: titleCaseSlug(agent.name),
158 };
159 if (defaultAgent === agent.name) {
160 option.isDefault = true;
161 }
162 return option;
163 });
165​
166function openCodeCapabilitiesForModel(input: {
167 readonly providerID: string;
168 readonly model: ProviderListResponse["all"][number]["models"][string];
169 readonly agents: ReadonlyArray<Agent>;
170}): ModelCapabilities {
171 const variantOptions = buildVariantOptions(input.providerID, input.model);
172 const agentOptions = buildAgentOptions(input.agents);
173 return {
174 ...DEFAULT_OPENCODE_MODEL_CAPABILITIES,
175 ...(variantOptions.length > 0 ? { variantOptions } : {}),
176 ...(agentOptions.length > 0 ? { agentOptions } : {}),
177 };
179​
180export function parseOpenCodeModelSlug(
181 slug: string | null | undefined,
182): ParsedOpenCodeModelSlug | null {
183 if (typeof slug !== "string") {
184 return null;
185 }
186​
187 const trimmed = slug.trim();
188 const separator = trimmed.indexOf("/");
189 if (separator <= 0 || separator === trimmed.length - 1) {
190 return null;
191 }
192​
193 return {
194 providerID: trimmed.slice(0, separator),
195 modelID: trimmed.slice(separator + 1),
196 };
198​
199export function toOpenCodeModelSlug(providerID: string, modelID: string): string {
200 return `${providerID}/${modelID}`;
202​
203export function openCodeQuestionId(
204 index: number,
205 question: QuestionRequest["questions"][number],
206): string {
207 const header = question.header
208 .trim()
209 .toLowerCase()
210 .replace(/[^a-z0-9_-]+/g, "-");
211 return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
213​
214export function toOpenCodeFileParts(input: {
215 readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
216 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
217}): Array<FilePartInput> {
218 const parts: Array<FilePartInput> = [];
219​
220 for (const attachment of input.attachments ?? []) {
221 const attachmentPath = input.resolveAttachmentPath(attachment);
222 if (!attachmentPath) {
223 continue;
224 }
225​
226 parts.push({
227 type: "file",
228 mime: attachment.mimeType,
229 filename: attachment.name,
230 url: pathToFileURL(attachmentPath).href,
231 });
232 }
233​
234 return parts;
236​
237export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
238 if (runtimeMode === "full-access") {
239 return [{ permission: "*", pattern: "*", action: "allow" }];
240 }
241​
242 return [
243 { permission: "*", pattern: "*", action: "ask" },
244 { permission: "bash", pattern: "*", action: "ask" },
245 { permission: "edit", pattern: "*", action: "ask" },
246 { permission: "webfetch", pattern: "*", action: "ask" },
247 { permission: "websearch", pattern: "*", action: "ask" },
248 { permission: "codesearch", pattern: "*", action: "ask" },
249 { permission: "external_directory", pattern: "*", action: "ask" },
250 { permission: "doom_loop", pattern: "*", action: "ask" },
251 { permission: "question", pattern: "*", action: "allow" },
252 ];
254​
255export function toOpenCodePermissionReply(
256 decision: ProviderApprovalDecision,
257): "once" | "always" | "reject" {
258 switch (decision) {
259 case "accept":
260 return "once";
261 case "acceptForSession":
262 return "always";
263 case "decline":
264 case "cancel":
265 default:
266 return "reject";
267 }
269​
270export function toOpenCodeQuestionAnswers(
271 request: QuestionRequest,
272 answers: Record<string, unknown>,
273): Array<QuestionAnswer> {
274 return request.questions.map((question, index) => {
275 const raw =
276 answers[openCodeQuestionId(index, question)] ??
277 answers[question.header] ??
278 answers[question.question];
279 if (Array.isArray(raw)) {
280 return raw.filter((value): value is string => typeof value === "string");
281 }
282 if (typeof raw === "string") {
283 return raw.trim().length > 0 ? [raw] : [];
284 }
285 return [];
286 });
288​
289export async function findAvailablePort(): Promise<number> {
290 const server = createServer();
291 await new Promise<void>((resolve, reject) => {
292 server.once("error", reject);
293 server.listen(0, DEFAULT_HOSTNAME, () => resolve());
294 });
295 const address = server.address() as AddressInfo;
296 const port = address.port;
297 await new Promise<void>((resolve, reject) => {
298 server.close((error) => (error ? reject(error) : resolve()));
299 });
300 return port;
302​
303export function resolveOpenCodeBinaryPath(binaryPath: string): string {
304 if (Path.isAbsolute(binaryPath)) {
305 return binaryPath;
306 }
307 return execFileSync("which", [binaryPath], {
308 encoding: "utf8",
309 timeout: 3_000,
310 }).trim();
312​
313export function detectMacosSigkillHint(binaryPath: string): string | null {
314 try {
315 // Check for quarantine xattr first.
316 const resolvedPath = resolveOpenCodeBinaryPath(binaryPath);
317 const xattr = execFileSync("xattr", ["-l", resolvedPath], {
318 encoding: "utf8",
319 timeout: 3_000,
320 });
321 if (xattr.includes("com.apple.quarantine")) {
322 return (
323 `macOS quarantine is blocking the OpenCode binary. ` +
324 `Run: xattr -d com.apple.quarantine ${resolvedPath}`
325 );
326 }
327​
328 // Look for a recent crash report with the termination reason.
329 const crashDir = Path.join(OS.homedir(), "Library/Logs/DiagnosticReports");
330 const binaryName = Path.basename(resolvedPath);
331 const recentReports = FS.readdirSync(crashDir)
332 .filter((f) => f.startsWith(binaryName) && f.endsWith(".ips"))
333 .toSorted()
334 .toReversed()
335 .slice(0, 1);
336​
337 for (const report of recentReports) {
338 const content = FS.readFileSync(Path.join(crashDir, report), "utf8");
339 if (content.includes('"namespace":"CODESIGNING"')) {
340 return (
341 "macOS killed the process due to an invalid code signature. " +
342 "The binary may be corrupted — try reinstalling OpenCode."
343 );
344 }
345 }
346 } catch {
347 // Best-effort detection — don't fail the original error path.
348 }
349 return null;
351​
352export async function startOpenCodeServerProcess(input: {
353 readonly binaryPath: string;
354 readonly port?: number;
355 readonly hostname?: string;
356 readonly timeoutMs?: number;
357}): Promise<OpenCodeServerProcess> {
358 const hostname = input.hostname ?? DEFAULT_HOSTNAME;
359 const port = input.port ?? (await findAvailablePort());
360 const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
361 const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
362 const child = spawn(input.binaryPath, args, {
363 stdio: ["ignore", "pipe", "pipe"],
364 env: {
365 ...process.env,
366 OPENCODE_CONFIG_CONTENT: JSON.stringify({}),
367 },
368 });
369​
370 child.stdout.setEncoding("utf8");
371 child.stderr.setEncoding("utf8");
372​
373 let stdout = "";
374 let stderr = "";
375 let closed = false;
376 const close = () => {
377 if (closed) {
378 return;
379 }
380 closed = true;
381 child.kill();
382 };
383​
384 const url = await new Promise<string>((resolve, reject) => {
385 const timeout = setTimeout(() => {
386 close();
387 reject(new Error(`Timed out waiting for OpenCode server start after ${timeoutMs}ms.`));
388 }, timeoutMs);
389​
390 const cleanup = () => {
391 clearTimeout(timeout);
392 child.stdout.off("data", onStdout);
393 child.stderr.off("data", onStderr);
394 child.off("error", onError);
395 child.off("close", onClose);
396 };
397​
398 const onStdout = (chunk: string) => {
399 stdout += chunk;
400 const parsed = parseServerUrlFromOutput(stdout);
401 if (!parsed) {
402 return;
403 }
404 cleanup();
405 resolve(parsed);
406 };
407​
408 const onStderr = (chunk: string) => {
409 stderr += chunk;
410 };
411​
412 const onError = (error: Error) => {
413 cleanup();
414 reject(error);
415 };
416​
417 const onClose = (code: number | null, signal: NodeJS.Signals | null) => {
418 cleanup();
419 const exitReason = signal ? `signal: ${signal}` : `code: ${code ?? "unknown"}`;
420 const hint =
421 signal === "SIGKILL" && process.platform === "darwin"
422 ? detectMacosSigkillHint(input.binaryPath)
423 : null;
424 reject(
425 new Error(
426 [
427 `OpenCode server exited before startup completed (${exitReason}).`,
428 hint,
429 stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
430 stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
431 ]
432 .filter(Boolean)
433 .join("\n\n"),
434 ),
435 );
436 };
437​
438 child.stdout.on("data", onStdout);
439 child.stderr.on("data", onStderr);
440 child.once("error", onError);
441 child.once("close", onClose);
442 });
443​
444 return {
445 url,
446 process: child,
447 close,
448 };
450​
451export async function connectToOpenCodeServer(input: {
452 readonly binaryPath: string;
453 readonly serverUrl?: string | null;
454 readonly port?: number;
455 readonly hostname?: string;
456 readonly timeoutMs?: number;
457}): Promise<OpenCodeServerConnection> {
458 const serverUrl = input.serverUrl?.trim();
459 if (serverUrl) {
460 return {
461 url: serverUrl,
462 process: null,
463 external: true,
464 close() {},
465 };
466 }
467​
468 const server = await startOpenCodeServerProcess({
469 binaryPath: input.binaryPath,
470 ...(input.port !== undefined ? { port: input.port } : {}),
471 ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
472 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
473 });
474​
475 return {
476 url: server.url,
477 process: server.process,
478 external: false,
479 close: () => server.close(),
480 };
482​
483export async function runOpenCodeCommand(input: {
484 readonly binaryPath: string;
485 readonly args: ReadonlyArray<string>;
486}): Promise<OpenCodeCommandResult> {
487 const child = spawn(input.binaryPath, [...input.args], {
488 stdio: ["ignore", "pipe", "pipe"],
489 shell: process.platform === "win32",
490 env: process.env,
491 });
492​
493 child.stdout?.setEncoding("utf8");
494 child.stderr?.setEncoding("utf8");
495​
496 const stdoutChunks: Array<string> = [];
497 const stderrChunks: Array<string> = [];
498​
499 child.stdout?.on("data", (chunk: string) => stdoutChunks.push(chunk));
500 child.stderr?.on("data", (chunk: string) => stderrChunks.push(chunk));
501​
502 const code = await new Promise<number>((resolve, reject) => {
503 child.once("error", reject);
504 child.once("exit", (exitCode) => resolve(exitCode ?? 0));
505 });
506​
507 return {
508 stdout: stdoutChunks.join(""),
509 stderr: stderrChunks.join(""),
510 code,
511 };
513​
514export function createOpenCodeSdkClient(input: {
515 readonly baseUrl: string;
516 readonly directory: string;
517 readonly serverPassword?: string;
518}): OpencodeClient {
519 return createOpencodeClient({
520 baseUrl: input.baseUrl,
521 directory: input.directory,
522 ...(input.serverPassword
523 ? {
524 headers: {
525 Authorization: buildOpenCodeBasicAuthorizationHeader(input.serverPassword),
526 },
527 }
528 : {}),
529 throwOnError: true,
530 });
532​
533export async function loadOpenCodeInventory(client: OpencodeClient): Promise<OpenCodeInventory> {
534 const [providerListResult, agentsResult] = await Promise.all([
535 client.provider.list(),
536 client.app.agents(),
537 ]);
538 if (!providerListResult.data) {
539 throw new Error("OpenCode provider inventory was empty.");
540 }
541 return {
542 providerList: providerListResult.data,
543 agents: agentsResult.data ?? [],
544 };
546​
547export function flattenOpenCodeModels(
548 input: OpenCodeInventory,
549): ReadonlyArray<ServerProviderModel> {
550 const connected = new Set(input.providerList.connected);
551 const models: Array<ServerProviderModel> = [];
552​
553 for (const provider of input.providerList.all) {
554 if (!connected.has(provider.id)) {
555 continue;
556 }
557​
558 for (const model of Object.values(provider.models)) {
559 models.push({
560 slug: toOpenCodeModelSlug(provider.id, model.id),
561 name: `${provider.name} · ${model.name}`,
562 isCustom: false,
563 capabilities: openCodeCapabilitiesForModel({
564 providerID: provider.id,
565 model,
566 agents: input.agents,
567 }),
568 });
569 }
570 }
571​
572 return models.toSorted((left, right) => left.name.localeCompare(right.name));