// Runs OpenCode for one profile and returns its final visible text. import process from "node:process"; import { chunks, writeChunk } from "./command.ts"; import { agentCommand } from "./isolation.ts"; import { collectOpenCodeOutput, openCodeArgs, openCodeError, parseOpenCodeEvents, } from "./opencode.ts"; import { agentEnvironment } from "./profiles.ts"; import { PROCESS_ENV, WORKSPACE } from "./run-context.ts"; import type { RuntimeProfile } from "./runtime.ts"; export async function runOpenCode( profile: RuntimeProfile, token: string, prompt: string, ): Promise { const child = agentCommand(profile, "opencode", openCodeArgs(profile.model, prompt), { cwd: WORKSPACE, env: agentEnvironment(PROCESS_ENV, profile, token), clearEnv: true, stdout: "piped", stderr: "piped", }).spawn(); const collected = collectOpenCodeOutput( chunks(child.stdout), chunks(child.stderr), async (chunk) => { await writeChunk(process.stdout, chunk); }, async (chunk) => { await writeChunk(process.stderr, chunk); }, ); const [status, streams] = await Promise.all([child.status, collected]); const error = streams.stderr.trim(); if (!status.success) { throw ( openCodeError(streams.stdout) ?? new Error(error || `opencode exited with ${status.code}`) ); } return parseOpenCodeEvents(streams.stdout); }