Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | import { createInterface } from "node:readline"; const colors = { reset: "\x1b[0m", bright: "\x1b[1m", dim: "\x1b[2m", red: "\x1b[31m", green: "\x1b[32m", yellow: "\x1b[33m", blue: "\x1b[34m", magenta: "\x1b[35m", cyan: "\x1b[36m", }; function getTypeColor(type: string): string { switch (type) { case "system": return colors.magenta; case "user": return colors.blue; case "assistant": return colors.green; case "tool_use": return colors.cyan; case "tool_result": return colors.yellow; case "message": return colors.dim; case "text": return colors.reset; default: return colors.reset; } } interface Todo { status: string; content: string; priority?: string; } function formatTodoList(todos: Todo[]): string { let output = `📋 ${colors.bright}${colors.cyan}Todo List Update${colors.reset}\n`; const statusColors = { completed: colors.dim + colors.green, in_progress: colors.bright + colors.yellow, pending: colors.reset, }; const statusIcons = { completed: "✅", in_progress: "🔄", pending: "⏸️", }; const priorityColors = { high: colors.red, medium: colors.yellow, low: colors.dim, }; todos.forEach((todo, index) => { const statusColor = statusColors[todo.status as keyof typeof statusColors] || colors.reset; const statusIcon = statusIcons[todo.status as keyof typeof statusIcons] || "❓"; const priorityColor = priorityColors[todo.priority as keyof typeof priorityColors] || colors.reset; const checkbox = todo.status === "completed" ? "☑️" : "☐"; output += ` ${checkbox} ${statusIcon} ${statusColor}${todo.content}${colors.reset}`; output += ` ${priorityColor}[${todo.priority}]${colors.reset}`; if (todo.status === "in_progress") { output += ` ${colors.bright}${colors.yellow}← ACTIVE${colors.reset}`; } output += "\n"; }); // Add summary stats const completed = todos.filter((t) => t.status === "completed").length; const inProgress = todos.filter((t) => t.status === "in_progress").length; const pending = todos.filter((t) => t.status === "pending").length; output += `\n ${colors.dim}📊 Progress: ${colors.green}${completed} completed${colors.reset}`; output += `${colors.dim}, ${colors.yellow}${inProgress} active${colors.reset}`; output += `${colors.dim}, ${colors.reset}${pending} pending${colors.reset}`; output += `${colors.dim} (${Math.round((completed / todos.length) * 100)}% done)${colors.reset}`; return output; } function formatConcise(json: any): string { const type = json.type || "unknown"; const typeColor = getTypeColor(type); let output = `⏺ ${typeColor}${type.charAt(0).toUpperCase() + type.slice(1)}${colors.reset}`; // Special handling for TodoWrite calls if ( type === "assistant" && json.message?.content?.[0]?.name === "TodoWrite" ) { const toolInput = json.message.content[0].input; if (toolInput?.todos && Array.isArray(toolInput.todos)) { return formatTodoList(toolInput.todos); } } // Add context based on type if (type === "assistant" && json.message?.content?.[0]?.name) { const toolName = json.message.content[0].name; const toolInput = json.message.content[0].input; // Format tool name with key arguments let toolDisplay = `${colors.cyan}${toolName}${colors.reset}`; if (toolInput) { const keyArgs = []; // Extract the most important argument for each tool type if (toolInput.file_path) keyArgs.push(toolInput.file_path); else if (toolInput.path) keyArgs.push(toolInput.path); else if (toolInput.pattern) keyArgs.push(`"${toolInput.pattern}"`); else if (toolInput.command) keyArgs.push(toolInput.command); else if (toolInput.cmd) keyArgs.push(toolInput.cmd); else if (toolInput.query) keyArgs.push(`"${toolInput.query}"`); else if (toolInput.description) keyArgs.push(toolInput.description); else if (toolInput.prompt) keyArgs.push(`"${toolInput.prompt.substring(0, 30)}..."`); else if (toolInput.url) keyArgs.push(toolInput.url); if (keyArgs.length > 0) { toolDisplay += `(${colors.green}${keyArgs[0]}${colors.reset})`; } } output = `⏺ ${toolDisplay}`; // Show additional arguments on next lines for complex tools if (toolInput) { const additionalArgs = []; if (toolName === "Bash" && toolInput.cwd) { additionalArgs.push(`cwd: ${toolInput.cwd}`); } if (toolInput.limit) additionalArgs.push(`limit: ${toolInput.limit}`); if (toolInput.offset) additionalArgs.push(`offset: ${toolInput.offset}`); if (toolInput.include) additionalArgs.push(`include: ${toolInput.include}`); if (toolInput.old_string && toolInput.new_string) { additionalArgs.push( `replace: "${toolInput.old_string.substring(0, 20)}..." → "${toolInput.new_string.substring(0, 20)}..."`, ); } if (toolInput.timeout) additionalArgs.push(`timeout: ${toolInput.timeout}ms`); if (additionalArgs.length > 0) { output += `\n ⎿ ${colors.dim}${additionalArgs.join(", ")}${colors.reset}`; } } } else if (type === "tool_result" && json.name) { output += `(${colors.cyan}${json.name}${colors.reset})`; } else if (type === "user" && json.message?.content?.[0]) { const content = json.message.content[0]; if (content.type === "tool_result") { // Override the type display for tool results output = `⏺ ${colors.yellow}Tool Result${colors.reset}`; // Show result summary and first 2 lines if (content.content) { const resultText = typeof content.content === "string" ? content.content : JSON.stringify(content.content); const lines = resultText.split("\n"); const chars = resultText.length; output += `\n ⎿ ${colors.dim}${lines.length} lines, ${chars} chars${colors.reset}`; if (content.is_error) { output += ` ${colors.red}ERROR${colors.reset}`; } // Show first 2 lines of content if (lines.length > 0 && lines[0].trim()) { output += `\n ⎿ ${colors.reset}${lines[0]}${colors.reset}`; } if (lines.length > 1 && lines[1].trim()) { output += `\n ${colors.dim}${lines[1]}${colors.reset}`; } } } else if (content.text) { const text = content.text.substring(0, 50); output += `: ${colors.dim}${text}${text.length === 50 ? "..." : ""}${colors.reset}`; } } else if (type === "system" && json.subtype) { output += `(${colors.dim}${json.subtype}${colors.reset})`; } // Show assistant message content if it exists if (type === "assistant" && json.message?.content) { const textContent = json.message.content.find( (c: any) => c.type === "text", ); if (textContent?.text) { const lines = textContent.text.split("\n").slice(0, 3); // Show first 3 lines output += `\n ⎿ ${colors.reset}${lines[0]}${colors.reset}`; if (lines.length > 1) { output += `\n ${colors.dim}${lines[1]}${colors.reset}`; } if (lines.length > 2) { output += `\n ${colors.dim}${lines[2]}${colors.reset}`; } if (textContent.text.split("\n").length > 3) { output += `\n ${colors.dim}...${colors.reset}`; } } } // Add summary line let summary = ""; if (json.message?.usage) { const usage = json.message.usage; summary = `${usage.input_tokens || 0}/${usage.output_tokens || 0} tokens`; } else if (json.output && typeof json.output === "string") { summary = `${json.output.length} chars output`; } else if (json.message?.content?.length) { summary = `${json.message.content.length} content items`; } else if (json.tools?.length) { summary = `${json.tools.length} tools available`; } if (summary) { output += `\n ⎿ ${colors.dim}${summary}${colors.reset}`; } return output; } function displayToolCallWithResult( toolCall: any, toolCallJson: any, toolResultJson: any, callTimestamp: string, resultTimestamp: string, ) { // Display the tool call header process.stdout.write(`${callTimestamp}${formatConcise(toolCallJson)}\n`); // Display the result const toolResult = toolResultJson.message.content[0]; const isError = toolResult.is_error; const resultIcon = isError ? "❌" : "✅"; const resultColor = isError ? colors.red : colors.green; process.stdout.write( ` ${resultTimestamp}${resultIcon} ${resultColor}Tool Result${colors.reset}`, ); if (toolResult.content) { const resultText = typeof toolResult.content === "string" ? toolResult.content : JSON.stringify(toolResult.content); const lines = resultText.split("\n"); const chars = resultText.length; process.stdout.write( ` ${colors.dim}(${lines.length} lines, ${chars} chars)${colors.reset}`, ); if (isError) { process.stdout.write(` ${colors.red}ERROR${colors.reset}`); } // Show first few lines of result const linesToShow = Math.min(3, lines.length); for (let i = 0; i < linesToShow; i++) { if (lines[i].trim()) { const lineColor = i === 0 ? colors.reset : colors.dim; process.stdout.write(`\n ⎿ ${lineColor}${lines[i]}${colors.reset}`); } } if (lines.length > linesToShow) { process.stdout.write( `\n ⎿ ${colors.dim}... ${lines.length - linesToShow} more lines${colors.reset}`, ); } } process.stdout.write("\n\n"); } export async function visualize( options: { debug?: boolean } = {}, ): Promise<void> { const rl = createInterface({ input: process.stdin, crlfDelay: Infinity, }); const debugMode = options.debug || process.argv.includes("--debug"); const toolCalls = new Map(); // Store tool calls by their ID const pendingResults = new Map(); // Store results waiting for their tool calls let lastLine: any = null; // Track the last line to detect final message let isLastAssistantMessage = false; rl.on("line", (line) => { if (line.trim()) { const timestamp = debugMode ? `${colors.dim}[${new Date().toISOString()}]${colors.reset} ` : ""; try { const json = JSON.parse(line); // Check if this is a tool call if (json.type === "assistant" && json.message?.content?.[0]?.id) { const toolCall = json.message.content[0]; const toolId = toolCall.id; // Store the tool call toolCalls.set(toolId, { toolCall: json, timestamp: timestamp, }); // Check if we have a pending result for this tool call if (pendingResults.has(toolId)) { const result = pendingResults.get(toolId); displayToolCallWithResult( toolCall, json, result.toolResult, result.timestamp, timestamp, ); pendingResults.delete(toolId); } else { // Display the tool call and mark it as pending process.stdout.write(`${timestamp + formatConcise(json)}\n`); process.stdout.write( `${colors.dim} ⎿ Waiting for result...${colors.reset}\n\n`, ); } } // Check if this is a tool result else if ( json.type === "user" && json.message?.content?.[0]?.type === "tool_result" ) { const toolResult = json.message.content[0]; const toolId = toolResult.tool_use_id; if (toolCalls.has(toolId)) { // We have the matching tool call, display them together const stored = toolCalls.get(toolId); displayToolCallWithResult( stored.toolCall.message.content[0], stored.toolCall, json, stored.timestamp, timestamp, ); toolCalls.delete(toolId); } else { // Store the result and wait for the tool call pendingResults.set(toolId, { toolResult: json, timestamp: timestamp, }); } } // Check if this is the result message and display full content else if (json.type === "result" && json.result) { process.stdout.write(`${timestamp + formatConcise(json)}\n\n`); process.stdout.write( `${colors.bright}${colors.green}=== Final Result ===${colors.reset}\n\n`, ); process.stdout.write(`${json.result}\n`); } // For all other message types, display normally else { process.stdout.write(`${timestamp + formatConcise(json)}\n\n`); } // Track if this might be the last assistant message lastLine = json; isLastAssistantMessage = json.type === "assistant" && !json.message?.content?.[0]?.id; } catch (_error) { process.stdout.write( `${timestamp}${colors.red}⏺ Parse Error${colors.reset}\n`, ); process.stdout.write( ` ⎿ ${colors.dim}${line.substring(0, 50)}...${colors.reset}\n\n`, ); } } }); rl.on("close", () => { // If the last message was an assistant message (not a tool call), display the full content if (isLastAssistantMessage && lastLine?.message?.content?.[0]?.text) { process.stdout.write( `\n${colors.bright}${colors.green}=== Final Assistant Message ===${colors.reset}\n\n`, ); process.stdout.write(`${lastLine.message.content[0].text}\n`); } }); } |