687
Oc
orc-code / files
orc-code / packages / types / src / helpers.ts
1.8 KB
1import type { AgentEvent, AgentProcess, AgentResult } from "./index.js"; 2 3export type LineParseFn = (raw: string) => AgentEvent[]; 4export type SessionIdExtractFn = (raw: string, events: AgentEvent[]) => string | null; 5 6/** 7 * Spawns a CLI process and streams its stdout through a line parser, 8 * yielding normalized AgentEvents. 9 */ 10export function spawnAgentProcess( 11 command: string, 12 args: string[], 13 parseLine: LineParseFn, 14 extractSessionId: SessionIdExtractFn, 15 cwd?: string, 16): AgentProcess { 17 const child = Bun.spawn([command, ...args], { 18 cwd: cwd ?? process.cwd(), 19 stdin: "ignore", 20 stdout: "pipe", 21 stderr: "pipe", 22 }); 23 24 let resolvedSessionId: string | null = null; 25 26 function processLine(line: string) { 27 const events = parseLine(line); 28 const sid = extractSessionId(line, events); 29 if (sid) resolvedSessionId = sid; 30 return events; 31 } 32 33 async function* streamEvents(): AsyncIterable<AgentEvent> { 34 const reader = child.stdout.getReader(); 35 const decoder = new TextDecoder(); 36 let buffer = ""; 37 38 while (true) { 39 const { done, value } = await reader.read(); 40 if (done) break; 41 buffer += decoder.decode(value, { stream: true }); 42 43 const lines = buffer.split("\n"); 44 buffer = lines.pop() ?? ""; 45 46 for (const line of lines) { 47 yield* processLine(line); 48 } 49 } 50 51 if (buffer.trim()) { 52 yield* processLine(buffer); 53 } 54 } 55 56 const result: Promise<AgentResult> = child.exited.then((exitCode) => ({ 57 sessionId: resolvedSessionId, 58 exitCode, 59 })); 60 61 return { 62 child, 63 events: streamEvents(), 64 result, 65 }; 66} 67 68/** Check if a command exists in $PATH */ 69export async function checkCommand(command: string): Promise<boolean> { 70 try { 71 const proc = Bun.spawn(["which", command], { 72 stdin: "ignore", 73 stdout: "ignore", 74 stderr: "ignore", 75 }); 76 const code = await proc.exited; 77 return code === 0; 78 } catch { 79 return false; 80 } 81}