687
Oc
orc-code / files
orc-code / packages / plugin-claude / src / parser.ts
2.4 KB
1import type { AgentEvent } from "@orc-code/types"; 2 3interface ClaudeContentBlock { 4 type: string; 5 text?: string; 6 name?: string; 7 input?: unknown; 8 thinking?: string; 9} 10 11interface ClaudeToolResultContent { 12 type: string; 13 tool_use_id?: string; 14 content?: string; 15 is_error?: boolean; 16} 17 18interface ClaudeLine { 19 type: string; 20 subtype?: string; 21 session_id?: string; 22 message?: { 23 content?: (ClaudeContentBlock | ClaudeToolResultContent)[]; 24 }; 25 is_error?: boolean; 26 result?: string; 27 total_cost_usd?: number; 28 usage?: { 29 input_tokens?: number; 30 output_tokens?: number; 31 cache_read_input_tokens?: number; 32 cache_creation_input_tokens?: number; 33 }; 34} 35 36export function parseLine(raw: string): AgentEvent[] { 37 const trimmed = raw.trim(); 38 if (trimmed === "") return []; 39 40 let line: ClaudeLine; 41 try { 42 line = JSON.parse(trimmed); 43 } catch { 44 return []; 45 } 46 47 const events: AgentEvent[] = []; 48 49 switch (line.type) { 50 case "system": 51 // init event — no user-facing output 52 break; 53 54 case "assistant": { 55 const blocks = line.message?.content ?? []; 56 for (const block of blocks) { 57 if (block.type === "text" && "text" in block && block.text) { 58 events.push({ type: "text", content: block.text }); 59 } else if (block.type === "tool_use" && "name" in block) { 60 events.push({ 61 type: "tool_use", 62 tool: (block as ClaudeContentBlock).name ?? "unknown", 63 args: (block as ClaudeContentBlock).input, 64 }); 65 } 66 // skip thinking blocks 67 } 68 break; 69 } 70 71 case "user": { 72 const blocks = line.message?.content ?? []; 73 for (const block of blocks) { 74 if (block.type === "tool_result") { 75 const tr = block as ClaudeToolResultContent; 76 events.push({ 77 type: "tool_result", 78 output: tr.content ?? "", 79 error: tr.is_error, 80 }); 81 } 82 } 83 break; 84 } 85 86 case "result": { 87 if (line.usage) { 88 events.push({ 89 type: "usage", 90 tokens: { 91 inputTokens: line.usage.input_tokens, 92 outputTokens: line.usage.output_tokens, 93 cacheReadTokens: line.usage.cache_read_input_tokens, 94 cacheWriteTokens: line.usage.cache_creation_input_tokens, 95 }, 96 }); 97 } 98 if (line.is_error) { 99 events.push({ 100 type: "error", 101 message: line.result ?? "Unknown error", 102 }); 103 } 104 events.push({ 105 type: "done", 106 sessionId: line.session_id ?? "", 107 }); 108 break; 109 } 110 111 // rate_limit_event etc — ignored 112 } 113 114 return events; 115}