687
Oc
orc-code / files
orc-code / packages / plugin-codex / src / parser.ts
2.0 KB
1import type { AgentEvent } from "@orc-code/types"; 2 3interface CodexItem { 4 id?: string; 5 type?: string; 6 text?: string; 7 command?: string; 8 aggregated_output?: string; 9 exit_code?: number | null; 10 status?: string; 11} 12 13interface CodexLine { 14 type: string; 15 thread_id?: string; 16 item?: CodexItem; 17 usage?: { 18 input_tokens?: number; 19 cached_input_tokens?: number; 20 output_tokens?: number; 21 }; 22} 23 24export function parseLine(raw: string): AgentEvent[] { 25 const trimmed = raw.trim(); 26 if (trimmed === "") return []; 27 28 let line: CodexLine; 29 try { 30 line = JSON.parse(trimmed); 31 } catch { 32 return []; 33 } 34 35 const events: AgentEvent[] = []; 36 37 switch (line.type) { 38 case "item.completed": { 39 const item = line.item; 40 if (!item) break; 41 42 if (item.type === "agent_message" && item.text) { 43 events.push({ type: "text", content: item.text }); 44 } else if (item.type === "command_execution") { 45 events.push({ 46 type: "tool_result", 47 output: item.aggregated_output ?? "", 48 error: item.exit_code !== null && item.exit_code !== undefined && item.exit_code !== 0, 49 }); 50 } 51 break; 52 } 53 54 case "item.started": { 55 const item = line.item; 56 if (!item) break; 57 58 if (item.type === "command_execution" && item.command) { 59 events.push({ 60 type: "tool_use", 61 tool: "command_execution", 62 args: item.command, 63 }); 64 } 65 break; 66 } 67 68 case "turn.completed": { 69 if (line.usage) { 70 events.push({ 71 type: "usage", 72 tokens: { 73 inputTokens: line.usage.input_tokens, 74 outputTokens: line.usage.output_tokens, 75 cacheReadTokens: line.usage.cached_input_tokens, 76 }, 77 }); 78 } 79 break; 80 } 81 82 // thread.started, turn.started — no user-facing output 83 } 84 85 return events; 86} 87 88export function extractThreadId(raw: string): string | null { 89 const trimmed = raw.trim(); 90 if (trimmed === "") return null; 91 92 try { 93 const line = JSON.parse(trimmed) as CodexLine; 94 if (line.type === "thread.started" && line.thread_id) { 95 return line.thread_id; 96 } 97 } catch { 98 // ignore 99 } 100 return null; 101}