@dreb/telegram 2.4.2 → 2.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/handlers/events.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAElC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,OAAO,EAAE,eAAe,EAAmB,MAAM,qBAAqB,CAAC;AAEvE,gFAA8E;AAC9E,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;AAE5D;;;;;GAKG;AACH,KAAK,QAAQ,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,CAAC;AAmErD,MAAM,WAAW,iBAAiB;IACjC,kCAAkC;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,6BAA6B;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,oDAAoD;IACpD,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,gDAAgD;IAChD,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,uBAAuB;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,+BAA+B;IAC/B,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,wBAAwB;IACxB,KAAK,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5D,wBAAwB;IACxB,gBAAgB,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAC5C,iCAAiC;IACjC,IAAI,EAAE,OAAO,CAAC;IACd,gCAAgC;IAChC,MAAM,EAAE,eAAe,CAAC;IACxB,wFAAsF;IACtF,eAAe,EAAE,OAAO,CAAC;IACzB,wGAAsG;IACtG,YAAY,EAAE,OAAO,CAAC;IACtB,+CAA+C;IAC/C,YAAY,EAAE,MAAM,CAAC;IACrB,yEAAuE;IACvE,eAAe,CAAC,EAAE,GAAG,CAAC;CACtB;AAaD;;GAEG;AACH,wBAAgB,kBAAkB,CACjC,GAAG,EAAE,GAAG,EACR,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,MAAM,GAAG,IAAI,GAC5B,iBAAiB,CAgBnB;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,GAAG,EACR,KAAK,EAAE,iBAAiB,EACxB,KAAK,EAAE,QAAQ,GACb,OAAO,CAAC,IAAI,CAAC,CA6Qf","sourcesContent":["/**\n * Event display — translates RPC agent events into Telegram messages.\n *\n * Manages an ephemeral status message that shows tool use, task lists,\n * and subagent activity. Text from the agent is sent as permanent messages.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { Api } from \"grammy\";\nimport { InputFile } from \"grammy\";\nimport type { TrackedAgent } from \"../types.js\";\nimport { extractSendFiles } from \"../util/files.js\";\nimport { DebouncedEditor, log, safeDelete } from \"../util/telegram.js\";\n\n/** Callback to queue a message for delivery — never blocks the event chain */\nexport type SendFn = (text: string, long?: boolean) => void;\n\n/**\n * RPC events include both core AgentEvent and session-specific events\n * (tasks_update, background_agent_*, auto_compaction_*).\n * We type loosely here since the RPC client types onEvent as AgentEvent\n * but actually forwards all AgentSessionEvent types.\n */\ntype RpcEvent = { type: string; [key: string]: any };\n\n// Tool emoji mapping (tool names are lowercase in definitions)\nconst TOOL_EMOJI: Record<string, string> = {\n\tbash: \"🔧\",\n\tread: \"📖\",\n\tedit: \"✏️\",\n\twrite: \"📝\",\n\tgrep: \"🔎\",\n\tfind: \"🔍\",\n\tls: \"📂\",\n\tweb_search: \"🌐\",\n\tweb_fetch: \"🌐\",\n\tsubagent: \"🤖\",\n\ttasks_update: \"📋\",\n\tskill: \"⚡\",\n};\n\nfunction toolEmoji(name: string): string {\n\treturn TOOL_EMOJI[name] || \"🔧\";\n}\n\n/** Format a tool call for display */\nfunction formatTool(name: string, args: Record<string, any>): string {\n\tconst emoji = toolEmoji(name);\n\tswitch (name) {\n\t\tcase \"bash\": {\n\t\t\tconst cmd = args.command || \"\";\n\t\t\treturn `${emoji} *bash*\\n\\`${cmd.slice(0, 500)}\\``;\n\t\t}\n\t\tcase \"read\":\n\t\t\treturn `${emoji} *read*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"edit\":\n\t\t\treturn `${emoji} *edit*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"write\":\n\t\t\treturn `${emoji} *write*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"grep\":\n\t\t\treturn `${emoji} *grep*: \\`${args.pattern || \"?\"}\\``;\n\t\tcase \"find\":\n\t\t\treturn `${emoji} *find*: \\`${args.pattern || \"?\"}\\``;\n\t\tcase \"ls\":\n\t\t\treturn `${emoji} *ls*: \\`${args.path || \".\"}\\``;\n\t\tcase \"web_search\":\n\t\t\treturn `${emoji} *web\\\\_search*: ${args.query || \"?\"}`;\n\t\tcase \"web_fetch\":\n\t\t\treturn `${emoji} *web\\\\_fetch*: ${(args.url || \"?\").slice(0, 80)}`;\n\t\tcase \"subagent\":\n\t\t\treturn `${emoji} *subagent* (${args.agent || \"?\"}): ${(args.task || args.tasks?.[0]?.task || \"?\").slice(0, 200)}`;\n\t\tcase \"skill\":\n\t\t\treturn `${emoji} *skill*: ${args.skill || \"?\"}`;\n\t\tdefault:\n\t\t\treturn `${emoji} *${name}*`;\n\t}\n}\n\n/** Format task list as checklist */\nfunction formatTaskList(tasks: Array<{ id: string; title: string; status: string }>): string {\n\tif (!tasks.length) return \"📋 *Tasks*: (empty)\";\n\tconst lines = [\"📋 *Tasks*:\"];\n\tfor (const task of tasks) {\n\t\tif (task.status === \"completed\") lines.push(` ✅ ${task.title}`);\n\t\telse if (task.status === \"in_progress\") lines.push(` 🔄 ${task.title}`);\n\t\telse lines.push(` ⬜ ${task.title}`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport interface EventDisplayState {\n\t/** Chat ID to send messages to */\n\tchatId: number;\n\t/** Message ID to reply to */\n\treplyToId: number;\n\t/** Ephemeral status message ID (edited in-place) */\n\tstatusMessageId: number | null;\n\t/** Tool messages accumulated since last text */\n\ttoolsSinceText: string[];\n\t/** Total tool count */\n\ttoolCount: number;\n\t/** All text blocks received */\n\ttextBlocks: string[];\n\t/** Current task list */\n\ttasks: Array<{ id: string; title: string; status: string }>;\n\t/** Background agents */\n\tbackgroundAgents: Map<string, TrackedAgent>;\n\t/** Whether agent has finished */\n\tdone: boolean;\n\t/** Debounced editor instance */\n\teditor: DebouncedEditor;\n\t/** Whether auto-retry is in progress (Layer 1: reactive — set by auto_retry_start) */\n\tretryInProgress: boolean;\n\t/** Whether a retry is expected (Layer 2: predictive — set by agent_end when error looks retryable) */\n\tpendingRetry: boolean;\n\t/** Current retry attempt number for display */\n\tretryAttempt: number;\n\t/** Buddy controller — receives agent events for context + reactions */\n\tbuddyController?: any;\n}\n\n/**\n * Check if an error message looks retryable (overloaded, rate limit, server errors).\n * Mirrors the core's _isRetryableError check as a defensive Layer 2.\n */\nconst RETRYABLE_ERROR_PATTERN =\n\t/overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|timed? out|timeout|terminated|retry delay/i;\n\nfunction isRetryableError(errorMessage: string): boolean {\n\treturn RETRYABLE_ERROR_PATTERN.test(errorMessage);\n}\n\n/**\n * Create a fresh event display state for a new agent run.\n */\nexport function createEventDisplay(\n\tapi: Api,\n\tchatId: number,\n\treplyToId: number,\n\tstatusMessageId: number | null,\n): EventDisplayState {\n\treturn {\n\t\tchatId,\n\t\treplyToId,\n\t\tstatusMessageId,\n\t\ttoolsSinceText: [],\n\t\ttoolCount: 0,\n\t\ttextBlocks: [],\n\t\ttasks: [],\n\t\tbackgroundAgents: new Map(),\n\t\tdone: false,\n\t\teditor: new DebouncedEditor(api),\n\t\tretryInProgress: false,\n\t\tpendingRetry: false,\n\t\tretryAttempt: 0,\n\t};\n}\n\n/**\n * Process an agent event and update the display.\n */\nexport async function handleAgentEvent(\n\tsend: SendFn,\n\tapi: Api,\n\tstate: EventDisplayState,\n\tevent: RpcEvent,\n): Promise<void> {\n\tswitch (event.type) {\n\t\tcase \"tool_execution_start\": {\n\t\t\tconst name = event.toolName || \"?\";\n\t\t\tconst args = event.args || {};\n\t\t\tstate.toolCount++;\n\n\t\t\t// tasks_update is shown via the separate tasks_update event — skip from tool summary\n\t\t\tif (name !== \"tasks_update\") {\n\t\t\t\tconst toolMsg = formatTool(name, args);\n\t\t\t\tstate.toolsSinceText.push(toolMsg);\n\t\t\t}\n\n\t\t\t// Update status with tool count and recent tools\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"tool_execution_end\": {\n\t\t\t// Feed event to buddy controller for context capture + error reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"message_end\": {\n\t\t\tconst msg = event.message;\n\n\t\t\t// Show subagent results — the parent agent references these but the\n\t\t\t// Telegram user can't see them otherwise. Send the full content.\n\t\t\tif (msg?.role === \"toolResult\" && msg?.toolName === \"subagent\") {\n\t\t\t\tconst content = msg?.content;\n\t\t\t\tif (content && Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (block.type === \"text\" && block.text?.trim()) {\n\t\t\t\t\t\t\tsend(`🤖 *Subagent result:*\\n${block.text.trim()}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Show background agent completion results — these arrive as user\n\t\t\t// messages injected by agent-session.ts via prompt()/steer() and\n\t\t\t// contain the actual subagent output the model sees.\n\t\t\tif (msg?.role === \"user\") {\n\t\t\t\tconst content = msg?.content;\n\t\t\t\tif (content && Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (block.type === \"text\" && block.text?.includes(\"<background-agent-complete>\")) {\n\t\t\t\t\t\t\t// Extract the content between the XML tags\n\t\t\t\t\t\t\tconst match = block.text.match(\n\t\t\t\t\t\t\t\t/<background-agent-complete>\\n?([\\s\\S]*?)\\n?<\\/background-agent-complete>/,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (match?.[1]?.trim()) {\n\t\t\t\t\t\t\t\tsend(`🤖 *Background agent complete:*\\n${match[1].trim()}`, true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Only display assistant messages — user messages are echoed back by RPC\n\t\t\tif (msg?.role !== \"assistant\") break;\n\t\t\tconst content = msg?.content;\n\t\t\tif (!content || !Array.isArray(content)) break;\n\n\t\t\tfor (const block of content) {\n\t\t\t\t// Display thinking blocks (collapsed summary)\n\t\t\t\tif (block.type === \"thinking\" && block.thinking?.trim() && !block.redacted) {\n\t\t\t\t\tconst thinking = block.thinking.trim();\n\t\t\t\t\tsend(`💭 _${thinking}_`, true);\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\" && block.text?.trim()) {\n\t\t\t\t\tconst text = block.text.trim();\n\n\t\t\t\t\t// Flush accumulated tools as permanent summary\n\t\t\t\t\tif (state.toolsSinceText.length > 0) {\n\t\t\t\t\t\tconst summary = `📋 *${state.toolsSinceText.length} tools*:\\n${state.toolsSinceText.join(\"\\n\")}`;\n\t\t\t\t\t\tsend(summary, true);\n\t\t\t\t\t\tstate.toolsSinceText = [];\n\t\t\t\t\t}\n\n\t\t\t\t\t// Send the text as a permanent message\n\t\t\t\t\tstate.textBlocks.push(text);\n\n\t\t\t\t\t// Check for file send markers\n\t\t\t\t\tconst [cleanText, filePaths] = extractSendFiles(text);\n\t\t\t\t\tif (cleanText) {\n\t\t\t\t\t\tsend(cleanText, true);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Send any requested files (silently skip non-existent paths —\n\t\t\t\t\t// the pattern may appear in explanatory text)\n\t\t\t\t\tfor (const filePath of filePaths) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (existsSync(filePath)) {\n\t\t\t\t\t\t\t\tawait api.sendDocument(state.chatId, new InputFile(filePath));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tlog(`[EVENTS] Failed to send file ${filePath}: ${e}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Feed event to buddy controller for context capture + reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"tasks_update\": {\n\t\t\tstate.tasks = (event as any).tasks || [];\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"background_agent_start\": {\n\t\t\tconst { agentId, agentType, taskSummary } = event as any;\n\t\t\tstate.backgroundAgents.set(agentId, {\n\t\t\t\tagentId,\n\t\t\t\tagentType,\n\t\t\t\ttaskSummary,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t});\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"background_agent_end\": {\n\t\t\tconst { agentId } = event as any;\n\t\t\tstate.backgroundAgents.delete(agentId);\n\t\t\t// Background agents completing does not end the parent's turn.\n\t\t\t// Only agent_end sets done — same as TUI behavior.\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_compaction_start\": {\n\t\t\tupdateStatusText(state, \"🗜 _Compacting context..._\");\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_compaction_end\": {\n\t\t\tconst result = (event as any).result;\n\t\t\tif (result) {\n\t\t\t\tconst before = result.tokensBefore || 0;\n\t\t\t\tconst msg = `🗜 Context compacted (was ${Math.round(before / 1000)}k tokens)`;\n\t\t\t\tsend(msg);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// =====================================================================\n\t\t// Auto-retry — prevents agent_end from marking done during retries\n\t\t// =====================================================================\n\n\t\tcase \"auto_retry_start\": {\n\t\t\tconst { attempt, maxAttempts, delayMs, errorMessage } = event as any;\n\t\t\tstate.retryInProgress = true;\n\t\t\tstate.pendingRetry = false; // Layer 1 has taken over from Layer 2\n\t\t\tstate.retryAttempt = attempt;\n\t\t\tconst delaySec = Math.round(delayMs / 1000);\n\t\t\tconst shortErr = errorMessage?.length > 80 ? `${errorMessage.slice(0, 80)}…` : errorMessage;\n\t\t\tupdateStatusText(state, `🔄 _Retrying (${attempt}/${maxAttempts}) in ${delaySec}s — ${shortErr || \"error\"}_`);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_retry_end\": {\n\t\t\tconst { success, attempt, finalError } = event as any;\n\t\t\tstate.retryInProgress = false;\n\t\t\tstate.retryAttempt = 0;\n\t\t\tif (!success && finalError) {\n\t\t\t\t// Max retries exhausted — show final error\n\t\t\t\tsend(`❌ _Retry failed (${attempt} attempts):_ ${finalError}`, true);\n\t\t\t}\n\t\t\t// On success, the retry's agent_start/agent_end cycle will handle display normally\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"agent_end\": {\n\t\t\t// Flush any remaining tools\n\t\t\tif (state.toolsSinceText.length > 0) {\n\t\t\t\tconst summary = `📋 *${state.toolsSinceText.length} tools*:\\n${state.toolsSinceText.join(\"\\n\")}`;\n\t\t\t\tsend(summary, true);\n\t\t\t\tstate.toolsSinceText = [];\n\t\t\t}\n\n\t\t\t// Check for error in agent_end messages\n\t\t\tconst errorMsg = (event.messages as any[])?.find(\n\t\t\t\t(m: any) => m.stopReason === \"error\" || m.stopReason === \"aborted\",\n\t\t\t);\n\n\t\t\t// Layer 2 (defensive): If this error looks retryable and we're not already\n\t\t\t// tracking a retry via Layer 1, don't mark done — the core will auto-retry\n\t\t\t// and emit a new agent_start/agent_end cycle.\n\t\t\tconst errorIsRetryable = errorMsg?.errorMessage && isRetryableError(errorMsg.errorMessage);\n\n\t\t\tif (errorMsg?.errorMessage) {\n\t\t\t\t// Suppress the scary error message during retry — user already saw the\n\t\t\t\t// auto_retry_start status. Only show the error if retry tracking missed it\n\t\t\t\t// (defensive: shouldn't happen, but better than silence).\n\t\t\t\tif (!state.retryInProgress && !errorIsRetryable) {\n\t\t\t\t\tconst provider = errorMsg.provider ? `${errorMsg.provider}/${errorMsg.model}` : \"\";\n\t\t\t\t\tconst prefix = provider ? `${provider}: ` : \"\";\n\t\t\t\t\tconst errLower = errorMsg.errorMessage.toLowerCase();\n\t\t\t\t\tconst hint =\n\t\t\t\t\t\terrLower.includes(\"connection\") || errLower.includes(\"timeout\") || errLower.includes(\"network\")\n\t\t\t\t\t\t\t? \"\\n_Provider may be down — try /model to switch._\"\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\tsend(`❌ ${prefix}${errorMsg.errorMessage}${hint}`, true);\n\t\t\t\t}\n\t\t\t} else if (state.textBlocks.length === 0 && state.backgroundAgents.size === 0) {\n\t\t\t\t// Only show \"(No response)\" when truly done — not between agent cycles\n\t\t\t\tif (!state.retryInProgress && !errorIsRetryable) {\n\t\t\t\t\tsend(\"(No response)\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Feed event to buddy controller for context capture + reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\n\t\t\t// Don't mark done if auto-retry is in progress (Layer 1) or the error\n\t\t\t// looks retryable (Layer 2 — defensive catch in case events were missed).\n\t\t\t// The core will emit a new agent_start/agent_end cycle for the retry.\n\t\t\tif (state.retryInProgress || errorIsRetryable) {\n\t\t\t\t// Signal that a retry is expected — the completion check in\n\t\t\t\t// ensureSubscribed needs this because it runs in the eventChain\n\t\t\t\t// BEFORE auto_retry_start has been processed.\n\t\t\t\tif (errorIsRetryable) state.pendingRetry = true;\n\t\t\t\t// Reset per-cycle state for the next agent loop\n\t\t\t\tstate.textBlocks = [];\n\t\t\t\tstate.toolCount = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// If background agents are still running, keep the subscription alive\n\t\t\t// and reset per-cycle state for the next agent loop\n\t\t\tif (state.backgroundAgents.size > 0) {\n\t\t\t\tstate.textBlocks = [];\n\t\t\t\tstate.toolCount = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Delete ephemeral status before signaling done\n\t\t\tif (state.statusMessageId) {\n\t\t\t\tawait state.editor.flush(state.chatId, state.statusMessageId);\n\t\t\t\tawait safeDelete(api, state.chatId, state.statusMessageId);\n\t\t\t\tstate.statusMessageId = null;\n\t\t\t}\n\n\t\t\t// Clean up editor\n\t\t\tstate.editor.clear();\n\n\t\t\t// Signal done AFTER cleanup — waitForCompletion checks this flag,\n\t\t\t// so setting it last ensures status message is deleted before DONE is sent\n\t\t\tstate.done = true;\n\t\t\tbreak;\n\t\t}\n\n\t\t// Handle error responses that leak through RPC (async prompt errors)\n\t\tcase \"response\": {\n\t\t\tconst resp = event as any;\n\t\t\tif (!resp.success && resp.error) {\n\t\t\t\tsend(`❌ ${resp.error}`, true);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Build and push a status update to the ephemeral message.\n */\nfunction updateStatus(state: EventDisplayState): void {\n\tif (!state.statusMessageId) return;\n\n\tconst parts: string[] = [];\n\n\t// Tool count header\n\tif (state.toolCount > 0) {\n\t\tparts.push(`🔧 *Tool ${state.toolCount}*`);\n\t}\n\n\t// Task list\n\tif (state.tasks.length > 0) {\n\t\tparts.push(formatTaskList(state.tasks));\n\t}\n\n\t// Background agents\n\tif (state.backgroundAgents.size > 0) {\n\t\tfor (const agent of state.backgroundAgents.values()) {\n\t\t\tparts.push(`🤖 *${agent.agentType}*: ${agent.taskSummary.slice(0, 200)}`);\n\t\t}\n\t}\n\n\t// Recent tools (last 5)\n\tif (state.toolsSinceText.length > 0) {\n\t\tconst recent = state.toolsSinceText.slice(-5);\n\t\tparts.push(recent.join(\"\\n\\n\"));\n\t}\n\n\tif (parts.length === 0) return;\n\n\tconst text = parts.join(\"\\n\\n\").slice(0, 4000);\n\tstate.editor.edit(state.chatId, state.statusMessageId, text);\n}\n\nfunction updateStatusText(state: EventDisplayState, text: string): void {\n\tif (!state.statusMessageId) return;\n\tstate.editor.edit(state.chatId, state.statusMessageId, text);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/handlers/events.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAElC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,OAAO,EAAE,eAAe,EAAmB,MAAM,qBAAqB,CAAC;AAEvE,gFAA8E;AAC9E,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;AAE5D;;;;;GAKG;AACH,KAAK,QAAQ,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,CAAC;AAmErD,MAAM,WAAW,iBAAiB;IACjC,kCAAkC;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,6BAA6B;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,oDAAoD;IACpD,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,gDAAgD;IAChD,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,uBAAuB;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,+BAA+B;IAC/B,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,wBAAwB;IACxB,KAAK,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5D,wBAAwB;IACxB,gBAAgB,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAC5C,iCAAiC;IACjC,IAAI,EAAE,OAAO,CAAC;IACd,gCAAgC;IAChC,MAAM,EAAE,eAAe,CAAC;IACxB,wFAAsF;IACtF,eAAe,EAAE,OAAO,CAAC;IACzB,wGAAsG;IACtG,YAAY,EAAE,OAAO,CAAC;IACtB,+CAA+C;IAC/C,YAAY,EAAE,MAAM,CAAC;IACrB,yEAAuE;IACvE,eAAe,CAAC,EAAE,GAAG,CAAC;CACtB;AAaD;;GAEG;AACH,wBAAgB,kBAAkB,CACjC,GAAG,EAAE,GAAG,EACR,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,MAAM,GAAG,IAAI,GAC5B,iBAAiB,CAgBnB;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,GAAG,EACR,KAAK,EAAE,iBAAiB,EACxB,KAAK,EAAE,QAAQ,GACb,OAAO,CAAC,IAAI,CAAC,CA6Qf","sourcesContent":["/**\n * Event display — translates RPC agent events into Telegram messages.\n *\n * Manages an ephemeral status message that shows tool use, task lists,\n * and subagent activity. Text from the agent is sent as permanent messages.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { Api } from \"grammy\";\nimport { InputFile } from \"grammy\";\nimport type { TrackedAgent } from \"../types.js\";\nimport { extractSendFiles } from \"../util/files.js\";\nimport { DebouncedEditor, log, safeDelete } from \"../util/telegram.js\";\n\n/** Callback to queue a message for delivery — never blocks the event chain */\nexport type SendFn = (text: string, long?: boolean) => void;\n\n/**\n * RPC events include both core AgentEvent and session-specific events\n * (tasks_update, background_agent_*, auto_compaction_*).\n * We type loosely here since the RPC client types onEvent as AgentEvent\n * but actually forwards all AgentSessionEvent types.\n */\ntype RpcEvent = { type: string; [key: string]: any };\n\n// Tool emoji mapping (tool names are lowercase in definitions)\nconst TOOL_EMOJI: Record<string, string> = {\n\tbash: \"🔧\",\n\tread: \"📖\",\n\tedit: \"✏️\",\n\twrite: \"📝\",\n\tgrep: \"🔎\",\n\tfind: \"🔍\",\n\tls: \"📂\",\n\tweb_search: \"🌐\",\n\tweb_fetch: \"🌐\",\n\tsubagent: \"🤖\",\n\ttasks_update: \"📋\",\n\tskill: \"⚡\",\n};\n\nfunction toolEmoji(name: string): string {\n\treturn TOOL_EMOJI[name] || \"🔧\";\n}\n\n/** Format a tool call for display */\nfunction formatTool(name: string, args: Record<string, any>): string {\n\tconst emoji = toolEmoji(name);\n\tswitch (name) {\n\t\tcase \"bash\": {\n\t\t\tconst cmd = args.command || \"\";\n\t\t\treturn `${emoji} *bash*\\n\\`${cmd.slice(0, 500)}\\``;\n\t\t}\n\t\tcase \"read\":\n\t\t\treturn `${emoji} *read*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"edit\":\n\t\t\treturn `${emoji} *edit*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"write\":\n\t\t\treturn `${emoji} *write*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"grep\":\n\t\t\treturn `${emoji} *grep*: \\`${args.pattern || \"?\"}\\``;\n\t\tcase \"find\":\n\t\t\treturn `${emoji} *find*: \\`${args.pattern || \"?\"}\\``;\n\t\tcase \"ls\":\n\t\t\treturn `${emoji} *ls*: \\`${args.path || \".\"}\\``;\n\t\tcase \"web_search\":\n\t\t\treturn `${emoji} *web\\\\_search*: ${args.query || \"?\"}`;\n\t\tcase \"web_fetch\":\n\t\t\treturn `${emoji} *web\\\\_fetch*: ${(args.url || \"?\").slice(0, 80)}`;\n\t\tcase \"subagent\":\n\t\t\treturn `${emoji} *subagent* (${args.agent || \"?\"}): ${(args.task || args.tasks?.[0]?.task || \"?\").slice(0, 200)}`;\n\t\tcase \"skill\":\n\t\t\treturn `${emoji} *skill*: ${args.skill || \"?\"}`;\n\t\tdefault:\n\t\t\treturn `${emoji} *${name}*`;\n\t}\n}\n\n/** Format task list as checklist */\nfunction formatTaskList(tasks: Array<{ id: string; title: string; status: string }>): string {\n\tif (!tasks.length) return \"📋 *Tasks*: (empty)\";\n\tconst lines = [\"📋 *Tasks*:\"];\n\tfor (const task of tasks) {\n\t\tif (task.status === \"completed\") lines.push(` ✅ ${task.title}`);\n\t\telse if (task.status === \"in_progress\") lines.push(` 🔄 ${task.title}`);\n\t\telse lines.push(` ⬜ ${task.title}`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport interface EventDisplayState {\n\t/** Chat ID to send messages to */\n\tchatId: number;\n\t/** Message ID to reply to */\n\treplyToId: number;\n\t/** Ephemeral status message ID (edited in-place) */\n\tstatusMessageId: number | null;\n\t/** Tool messages accumulated since last text */\n\ttoolsSinceText: string[];\n\t/** Total tool count */\n\ttoolCount: number;\n\t/** All text blocks received */\n\ttextBlocks: string[];\n\t/** Current task list */\n\ttasks: Array<{ id: string; title: string; status: string }>;\n\t/** Background agents */\n\tbackgroundAgents: Map<string, TrackedAgent>;\n\t/** Whether agent has finished */\n\tdone: boolean;\n\t/** Debounced editor instance */\n\teditor: DebouncedEditor;\n\t/** Whether auto-retry is in progress (Layer 1: reactive — set by auto_retry_start) */\n\tretryInProgress: boolean;\n\t/** Whether a retry is expected (Layer 2: predictive — set by agent_end when error looks retryable) */\n\tpendingRetry: boolean;\n\t/** Current retry attempt number for display */\n\tretryAttempt: number;\n\t/** Buddy controller — receives agent events for context + reactions */\n\tbuddyController?: any;\n}\n\n/**\n * Check if an error message looks retryable (overloaded, rate limit, server errors).\n * Mirrors the core's _isRetryableError check as a defensive Layer 2.\n */\nconst RETRYABLE_ERROR_PATTERN =\n\t/overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|other side closed|fetch failed|ended without|upstream.?connect|reset before headers|socket hang up|timed? out|timeout|terminated|retry delay/i;\n\nfunction isRetryableError(errorMessage: string): boolean {\n\treturn RETRYABLE_ERROR_PATTERN.test(errorMessage);\n}\n\n/**\n * Create a fresh event display state for a new agent run.\n */\nexport function createEventDisplay(\n\tapi: Api,\n\tchatId: number,\n\treplyToId: number,\n\tstatusMessageId: number | null,\n): EventDisplayState {\n\treturn {\n\t\tchatId,\n\t\treplyToId,\n\t\tstatusMessageId,\n\t\ttoolsSinceText: [],\n\t\ttoolCount: 0,\n\t\ttextBlocks: [],\n\t\ttasks: [],\n\t\tbackgroundAgents: new Map(),\n\t\tdone: false,\n\t\teditor: new DebouncedEditor(api),\n\t\tretryInProgress: false,\n\t\tpendingRetry: false,\n\t\tretryAttempt: 0,\n\t};\n}\n\n/**\n * Process an agent event and update the display.\n */\nexport async function handleAgentEvent(\n\tsend: SendFn,\n\tapi: Api,\n\tstate: EventDisplayState,\n\tevent: RpcEvent,\n): Promise<void> {\n\tswitch (event.type) {\n\t\tcase \"tool_execution_start\": {\n\t\t\tconst name = event.toolName || \"?\";\n\t\t\tconst args = event.args || {};\n\t\t\tstate.toolCount++;\n\n\t\t\t// tasks_update is shown via the separate tasks_update event — skip from tool summary\n\t\t\tif (name !== \"tasks_update\") {\n\t\t\t\tconst toolMsg = formatTool(name, args);\n\t\t\t\tstate.toolsSinceText.push(toolMsg);\n\t\t\t}\n\n\t\t\t// Update status with tool count and recent tools\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"tool_execution_end\": {\n\t\t\t// Feed event to buddy controller for context capture + error reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"message_end\": {\n\t\t\tconst msg = event.message;\n\n\t\t\t// Show subagent results — the parent agent references these but the\n\t\t\t// Telegram user can't see them otherwise. Send the full content.\n\t\t\tif (msg?.role === \"toolResult\" && msg?.toolName === \"subagent\") {\n\t\t\t\tconst content = msg?.content;\n\t\t\t\tif (content && Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (block.type === \"text\" && block.text?.trim()) {\n\t\t\t\t\t\t\tsend(`🤖 *Subagent result:*\\n${block.text.trim()}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Show background agent completion results — these arrive as user\n\t\t\t// messages injected by agent-session.ts via prompt()/steer() and\n\t\t\t// contain the actual subagent output the model sees.\n\t\t\tif (msg?.role === \"user\") {\n\t\t\t\tconst content = msg?.content;\n\t\t\t\tif (content && Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (block.type === \"text\" && block.text?.includes(\"<background-agent-complete>\")) {\n\t\t\t\t\t\t\t// Extract the content between the XML tags\n\t\t\t\t\t\t\tconst match = block.text.match(\n\t\t\t\t\t\t\t\t/<background-agent-complete>\\n?([\\s\\S]*?)\\n?<\\/background-agent-complete>/,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (match?.[1]?.trim()) {\n\t\t\t\t\t\t\t\tsend(`🤖 *Background agent complete:*\\n${match[1].trim()}`, true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Only display assistant messages — user messages are echoed back by RPC\n\t\t\tif (msg?.role !== \"assistant\") break;\n\t\t\tconst content = msg?.content;\n\t\t\tif (!content || !Array.isArray(content)) break;\n\n\t\t\tfor (const block of content) {\n\t\t\t\t// Display thinking blocks (collapsed summary)\n\t\t\t\tif (block.type === \"thinking\" && block.thinking?.trim() && !block.redacted) {\n\t\t\t\t\tconst thinking = block.thinking.trim();\n\t\t\t\t\tsend(`💭 _${thinking}_`, true);\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\" && block.text?.trim()) {\n\t\t\t\t\tconst text = block.text.trim();\n\n\t\t\t\t\t// Flush accumulated tools as permanent summary\n\t\t\t\t\tif (state.toolsSinceText.length > 0) {\n\t\t\t\t\t\tconst summary = `📋 *${state.toolsSinceText.length} tools*:\\n${state.toolsSinceText.join(\"\\n\")}`;\n\t\t\t\t\t\tsend(summary, true);\n\t\t\t\t\t\tstate.toolsSinceText = [];\n\t\t\t\t\t}\n\n\t\t\t\t\t// Send the text as a permanent message\n\t\t\t\t\tstate.textBlocks.push(text);\n\n\t\t\t\t\t// Check for file send markers\n\t\t\t\t\tconst [cleanText, filePaths] = extractSendFiles(text);\n\t\t\t\t\tif (cleanText) {\n\t\t\t\t\t\tsend(cleanText, true);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Send any requested files (silently skip non-existent paths —\n\t\t\t\t\t// the pattern may appear in explanatory text)\n\t\t\t\t\tfor (const filePath of filePaths) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (existsSync(filePath)) {\n\t\t\t\t\t\t\t\tawait api.sendDocument(state.chatId, new InputFile(filePath));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tlog(`[EVENTS] Failed to send file ${filePath}: ${e}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Feed event to buddy controller for context capture + reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"tasks_update\": {\n\t\t\tstate.tasks = (event as any).tasks || [];\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"background_agent_start\": {\n\t\t\tconst { agentId, agentType, taskSummary } = event as any;\n\t\t\tstate.backgroundAgents.set(agentId, {\n\t\t\t\tagentId,\n\t\t\t\tagentType,\n\t\t\t\ttaskSummary,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t});\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"background_agent_end\": {\n\t\t\tconst { agentId } = event as any;\n\t\t\tstate.backgroundAgents.delete(agentId);\n\t\t\t// Background agents completing does not end the parent's turn.\n\t\t\t// Only agent_end sets done — same as TUI behavior.\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_compaction_start\": {\n\t\t\tupdateStatusText(state, \"🗜 _Compacting context..._\");\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_compaction_end\": {\n\t\t\tconst result = (event as any).result;\n\t\t\tif (result) {\n\t\t\t\tconst before = result.tokensBefore || 0;\n\t\t\t\tconst msg = `🗜 Context compacted (was ${Math.round(before / 1000)}k tokens)`;\n\t\t\t\tsend(msg);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// =====================================================================\n\t\t// Auto-retry — prevents agent_end from marking done during retries\n\t\t// =====================================================================\n\n\t\tcase \"auto_retry_start\": {\n\t\t\tconst { attempt, maxAttempts, delayMs, errorMessage } = event as any;\n\t\t\tstate.retryInProgress = true;\n\t\t\tstate.pendingRetry = false; // Layer 1 has taken over from Layer 2\n\t\t\tstate.retryAttempt = attempt;\n\t\t\tconst delaySec = Math.round(delayMs / 1000);\n\t\t\tconst shortErr = errorMessage?.length > 80 ? `${errorMessage.slice(0, 80)}…` : errorMessage;\n\t\t\tupdateStatusText(state, `🔄 _Retrying (${attempt}/${maxAttempts}) in ${delaySec}s — ${shortErr || \"error\"}_`);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_retry_end\": {\n\t\t\tconst { success, attempt, finalError } = event as any;\n\t\t\tstate.retryInProgress = false;\n\t\t\tstate.retryAttempt = 0;\n\t\t\tif (!success && finalError) {\n\t\t\t\t// Max retries exhausted — show final error\n\t\t\t\tsend(`❌ _Retry failed (${attempt} attempts):_ ${finalError}`, true);\n\t\t\t}\n\t\t\t// On success, the retry's agent_start/agent_end cycle will handle display normally\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"agent_end\": {\n\t\t\t// Flush any remaining tools\n\t\t\tif (state.toolsSinceText.length > 0) {\n\t\t\t\tconst summary = `📋 *${state.toolsSinceText.length} tools*:\\n${state.toolsSinceText.join(\"\\n\")}`;\n\t\t\t\tsend(summary, true);\n\t\t\t\tstate.toolsSinceText = [];\n\t\t\t}\n\n\t\t\t// Check for error in agent_end messages\n\t\t\tconst errorMsg = (event.messages as any[])?.find(\n\t\t\t\t(m: any) => m.stopReason === \"error\" || m.stopReason === \"aborted\",\n\t\t\t);\n\n\t\t\t// Layer 2 (defensive): If this error looks retryable and we're not already\n\t\t\t// tracking a retry via Layer 1, don't mark done — the core will auto-retry\n\t\t\t// and emit a new agent_start/agent_end cycle.\n\t\t\tconst errorIsRetryable = errorMsg?.errorMessage && isRetryableError(errorMsg.errorMessage);\n\n\t\t\tif (errorMsg?.errorMessage) {\n\t\t\t\t// Suppress the scary error message during retry — user already saw the\n\t\t\t\t// auto_retry_start status. Only show the error if retry tracking missed it\n\t\t\t\t// (defensive: shouldn't happen, but better than silence).\n\t\t\t\tif (!state.retryInProgress && !errorIsRetryable) {\n\t\t\t\t\tconst provider = errorMsg.provider ? `${errorMsg.provider}/${errorMsg.model}` : \"\";\n\t\t\t\t\tconst prefix = provider ? `${provider}: ` : \"\";\n\t\t\t\t\tconst errLower = errorMsg.errorMessage.toLowerCase();\n\t\t\t\t\tconst hint =\n\t\t\t\t\t\terrLower.includes(\"connection\") || errLower.includes(\"timeout\") || errLower.includes(\"network\")\n\t\t\t\t\t\t\t? \"\\n_Provider may be down — try /model to switch._\"\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\tsend(`❌ ${prefix}${errorMsg.errorMessage}${hint}`, true);\n\t\t\t\t}\n\t\t\t} else if (state.textBlocks.length === 0 && state.backgroundAgents.size === 0) {\n\t\t\t\t// Only show \"(No response)\" when truly done — not between agent cycles\n\t\t\t\tif (!state.retryInProgress && !errorIsRetryable) {\n\t\t\t\t\tsend(\"(No response)\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Feed event to buddy controller for context capture + reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\n\t\t\t// Don't mark done if auto-retry is in progress (Layer 1) or the error\n\t\t\t// looks retryable (Layer 2 — defensive catch in case events were missed).\n\t\t\t// The core will emit a new agent_start/agent_end cycle for the retry.\n\t\t\tif (state.retryInProgress || errorIsRetryable) {\n\t\t\t\t// Signal that a retry is expected — the completion check in\n\t\t\t\t// ensureSubscribed needs this because it runs in the eventChain\n\t\t\t\t// BEFORE auto_retry_start has been processed.\n\t\t\t\tif (errorIsRetryable) state.pendingRetry = true;\n\t\t\t\t// Reset per-cycle state for the next agent loop\n\t\t\t\tstate.textBlocks = [];\n\t\t\t\tstate.toolCount = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// If background agents are still running, keep the subscription alive\n\t\t\t// and reset per-cycle state for the next agent loop\n\t\t\tif (state.backgroundAgents.size > 0) {\n\t\t\t\tstate.textBlocks = [];\n\t\t\t\tstate.toolCount = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Delete ephemeral status before signaling done\n\t\t\tif (state.statusMessageId) {\n\t\t\t\tawait state.editor.flush(state.chatId, state.statusMessageId);\n\t\t\t\tawait safeDelete(api, state.chatId, state.statusMessageId);\n\t\t\t\tstate.statusMessageId = null;\n\t\t\t}\n\n\t\t\t// Clean up editor\n\t\t\tstate.editor.clear();\n\n\t\t\t// Signal done AFTER cleanup — waitForCompletion checks this flag,\n\t\t\t// so setting it last ensures status message is deleted before DONE is sent\n\t\t\tstate.done = true;\n\t\t\tbreak;\n\t\t}\n\n\t\t// Handle error responses that leak through RPC (async prompt errors)\n\t\tcase \"response\": {\n\t\t\tconst resp = event as any;\n\t\t\tif (!resp.success && resp.error) {\n\t\t\t\tsend(`❌ ${resp.error}`, true);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Build and push a status update to the ephemeral message.\n */\nfunction updateStatus(state: EventDisplayState): void {\n\tif (!state.statusMessageId) return;\n\n\tconst parts: string[] = [];\n\n\t// Tool count header\n\tif (state.toolCount > 0) {\n\t\tparts.push(`🔧 *Tool ${state.toolCount}*`);\n\t}\n\n\t// Task list\n\tif (state.tasks.length > 0) {\n\t\tparts.push(formatTaskList(state.tasks));\n\t}\n\n\t// Background agents\n\tif (state.backgroundAgents.size > 0) {\n\t\tfor (const agent of state.backgroundAgents.values()) {\n\t\t\tparts.push(`🤖 *${agent.agentType}*: ${agent.taskSummary.slice(0, 200)}`);\n\t\t}\n\t}\n\n\t// Recent tools (last 5)\n\tif (state.toolsSinceText.length > 0) {\n\t\tconst recent = state.toolsSinceText.slice(-5);\n\t\tparts.push(recent.join(\"\\n\\n\"));\n\t}\n\n\tif (parts.length === 0) return;\n\n\tconst text = parts.join(\"\\n\\n\").slice(0, 4000);\n\tstate.editor.edit(state.chatId, state.statusMessageId, text);\n}\n\nfunction updateStatusText(state: EventDisplayState, text: string): void {\n\tif (!state.statusMessageId) return;\n\tstate.editor.edit(state.chatId, state.statusMessageId, text);\n}\n"]}
|
package/dist/handlers/events.js
CHANGED
|
@@ -77,7 +77,7 @@ function formatTaskList(tasks) {
|
|
|
77
77
|
* Check if an error message looks retryable (overloaded, rate limit, server errors).
|
|
78
78
|
* Mirrors the core's _isRetryableError check as a defensive Layer 2.
|
|
79
79
|
*/
|
|
80
|
-
const RETRYABLE_ERROR_PATTERN = /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|timed? out|timeout|terminated|retry delay/i;
|
|
80
|
+
const RETRYABLE_ERROR_PATTERN = /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|other side closed|fetch failed|ended without|upstream.?connect|reset before headers|socket hang up|timed? out|timeout|terminated|retry delay/i;
|
|
81
81
|
function isRetryableError(errorMessage) {
|
|
82
82
|
return RETRYABLE_ERROR_PATTERN.test(errorMessage);
|
|
83
83
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/handlers/events.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAEnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAavE,+DAA+D;AAC/D,MAAM,UAAU,GAA2B;IAC1C,IAAI,EAAE,MAAG;IACT,IAAI,EAAE,MAAG;IACT,IAAI,EAAE,QAAI;IACV,KAAK,EAAE,MAAG;IACV,IAAI,EAAE,MAAG;IACT,IAAI,EAAE,MAAG;IACT,EAAE,EAAE,MAAG;IACP,UAAU,EAAE,MAAG;IACf,SAAS,EAAE,MAAG;IACd,QAAQ,EAAE,MAAG;IACb,YAAY,EAAE,MAAG;IACjB,KAAK,EAAE,KAAG;CACV,CAAC;AAEF,SAAS,SAAS,CAAC,IAAY,EAAU;IACxC,OAAO,UAAU,CAAC,IAAI,CAAC,IAAI,MAAG,CAAC;AAAA,CAC/B;AAED,qCAAqC;AACrC,SAAS,UAAU,CAAC,IAAY,EAAE,IAAyB,EAAU;IACpE,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC9B,QAAQ,IAAI,EAAE,CAAC;QACd,KAAK,MAAM,EAAE,CAAC;YACb,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;YAC/B,OAAO,GAAG,KAAK,cAAc,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC;QACpD,C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AC,SAAS,MAAM,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;QAC1E,CAAC;IACF,CAAC;IAED,wBAAwB;IACxB,IAAI,KAAK,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrC,MAAM,MAAM,GAAG,KAAK,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9C,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IACjC,CAAC;IAED,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAE/B,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC/C,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;AAAA,CAC7D;AAED,SAAS,gBAAgB,CAAC,KAAwB,EAAE,IAAY,EAAQ;IACvE,IAAI,CAAC,KAAK,CAAC,eAAe;QAAE,OAAO;IACnC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;AAAA,CAC7D","sourcesContent":["/**\n * Event display — translates RPC agent events into Telegram messages.\n *\n * Manages an ephemeral status message that shows tool use, task lists,\n * and subagent activity. Text from the agent is sent as permanent messages.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { Api } from \"grammy\";\nimport { InputFile } from \"grammy\";\nimport type { TrackedAgent } from \"../types.js\";\nimport { extractSendFiles } from \"../util/files.js\";\nimport { DebouncedEditor, log, safeDelete } from \"../util/telegram.js\";\n\n/** Callback to queue a message for delivery — never blocks the event chain */\nexport type SendFn = (text: string, long?: boolean) => void;\n\n/**\n * RPC events include both core AgentEvent and session-specific events\n * (tasks_update, background_agent_*, auto_compaction_*).\n * We type loosely here since the RPC client types onEvent as AgentEvent\n * but actually forwards all AgentSessionEvent types.\n */\ntype RpcEvent = { type: string; [key: string]: any };\n\n// Tool emoji mapping (tool names are lowercase in definitions)\nconst TOOL_EMOJI: Record<string, string> = {\n\tbash: \"🔧\",\n\tread: \"📖\",\n\tedit: \"✏️\",\n\twrite: \"📝\",\n\tgrep: \"🔎\",\n\tfind: \"🔍\",\n\tls: \"📂\",\n\tweb_search: \"🌐\",\n\tweb_fetch: \"🌐\",\n\tsubagent: \"🤖\",\n\ttasks_update: \"📋\",\n\tskill: \"⚡\",\n};\n\nfunction toolEmoji(name: string): string {\n\treturn TOOL_EMOJI[name] || \"🔧\";\n}\n\n/** Format a tool call for display */\nfunction formatTool(name: string, args: Record<string, any>): string {\n\tconst emoji = toolEmoji(name);\n\tswitch (name) {\n\t\tcase \"bash\": {\n\t\t\tconst cmd = args.command || \"\";\n\t\t\treturn `${emoji} *bash*\\n\\`${cmd.slice(0, 500)}\\``;\n\t\t}\n\t\tcase \"read\":\n\t\t\treturn `${emoji} *read*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"edit\":\n\t\t\treturn `${emoji} *edit*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"write\":\n\t\t\treturn `${emoji} *write*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"grep\":\n\t\t\treturn `${emoji} *grep*: \\`${args.pattern || \"?\"}\\``;\n\t\tcase \"find\":\n\t\t\treturn `${emoji} *find*: \\`${args.pattern || \"?\"}\\``;\n\t\tcase \"ls\":\n\t\t\treturn `${emoji} *ls*: \\`${args.path || \".\"}\\``;\n\t\tcase \"web_search\":\n\t\t\treturn `${emoji} *web\\\\_search*: ${args.query || \"?\"}`;\n\t\tcase \"web_fetch\":\n\t\t\treturn `${emoji} *web\\\\_fetch*: ${(args.url || \"?\").slice(0, 80)}`;\n\t\tcase \"subagent\":\n\t\t\treturn `${emoji} *subagent* (${args.agent || \"?\"}): ${(args.task || args.tasks?.[0]?.task || \"?\").slice(0, 200)}`;\n\t\tcase \"skill\":\n\t\t\treturn `${emoji} *skill*: ${args.skill || \"?\"}`;\n\t\tdefault:\n\t\t\treturn `${emoji} *${name}*`;\n\t}\n}\n\n/** Format task list as checklist */\nfunction formatTaskList(tasks: Array<{ id: string; title: string; status: string }>): string {\n\tif (!tasks.length) return \"📋 *Tasks*: (empty)\";\n\tconst lines = [\"📋 *Tasks*:\"];\n\tfor (const task of tasks) {\n\t\tif (task.status === \"completed\") lines.push(` ✅ ${task.title}`);\n\t\telse if (task.status === \"in_progress\") lines.push(` 🔄 ${task.title}`);\n\t\telse lines.push(` ⬜ ${task.title}`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport interface EventDisplayState {\n\t/** Chat ID to send messages to */\n\tchatId: number;\n\t/** Message ID to reply to */\n\treplyToId: number;\n\t/** Ephemeral status message ID (edited in-place) */\n\tstatusMessageId: number | null;\n\t/** Tool messages accumulated since last text */\n\ttoolsSinceText: string[];\n\t/** Total tool count */\n\ttoolCount: number;\n\t/** All text blocks received */\n\ttextBlocks: string[];\n\t/** Current task list */\n\ttasks: Array<{ id: string; title: string; status: string }>;\n\t/** Background agents */\n\tbackgroundAgents: Map<string, TrackedAgent>;\n\t/** Whether agent has finished */\n\tdone: boolean;\n\t/** Debounced editor instance */\n\teditor: DebouncedEditor;\n\t/** Whether auto-retry is in progress (Layer 1: reactive — set by auto_retry_start) */\n\tretryInProgress: boolean;\n\t/** Whether a retry is expected (Layer 2: predictive — set by agent_end when error looks retryable) */\n\tpendingRetry: boolean;\n\t/** Current retry attempt number for display */\n\tretryAttempt: number;\n\t/** Buddy controller — receives agent events for context + reactions */\n\tbuddyController?: any;\n}\n\n/**\n * Check if an error message looks retryable (overloaded, rate limit, server errors).\n * Mirrors the core's _isRetryableError check as a defensive Layer 2.\n */\nconst RETRYABLE_ERROR_PATTERN =\n\t/overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|timed? out|timeout|terminated|retry delay/i;\n\nfunction isRetryableError(errorMessage: string): boolean {\n\treturn RETRYABLE_ERROR_PATTERN.test(errorMessage);\n}\n\n/**\n * Create a fresh event display state for a new agent run.\n */\nexport function createEventDisplay(\n\tapi: Api,\n\tchatId: number,\n\treplyToId: number,\n\tstatusMessageId: number | null,\n): EventDisplayState {\n\treturn {\n\t\tchatId,\n\t\treplyToId,\n\t\tstatusMessageId,\n\t\ttoolsSinceText: [],\n\t\ttoolCount: 0,\n\t\ttextBlocks: [],\n\t\ttasks: [],\n\t\tbackgroundAgents: new Map(),\n\t\tdone: false,\n\t\teditor: new DebouncedEditor(api),\n\t\tretryInProgress: false,\n\t\tpendingRetry: false,\n\t\tretryAttempt: 0,\n\t};\n}\n\n/**\n * Process an agent event and update the display.\n */\nexport async function handleAgentEvent(\n\tsend: SendFn,\n\tapi: Api,\n\tstate: EventDisplayState,\n\tevent: RpcEvent,\n): Promise<void> {\n\tswitch (event.type) {\n\t\tcase \"tool_execution_start\": {\n\t\t\tconst name = event.toolName || \"?\";\n\t\t\tconst args = event.args || {};\n\t\t\tstate.toolCount++;\n\n\t\t\t// tasks_update is shown via the separate tasks_update event — skip from tool summary\n\t\t\tif (name !== \"tasks_update\") {\n\t\t\t\tconst toolMsg = formatTool(name, args);\n\t\t\t\tstate.toolsSinceText.push(toolMsg);\n\t\t\t}\n\n\t\t\t// Update status with tool count and recent tools\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"tool_execution_end\": {\n\t\t\t// Feed event to buddy controller for context capture + error reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"message_end\": {\n\t\t\tconst msg = event.message;\n\n\t\t\t// Show subagent results — the parent agent references these but the\n\t\t\t// Telegram user can't see them otherwise. Send the full content.\n\t\t\tif (msg?.role === \"toolResult\" && msg?.toolName === \"subagent\") {\n\t\t\t\tconst content = msg?.content;\n\t\t\t\tif (content && Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (block.type === \"text\" && block.text?.trim()) {\n\t\t\t\t\t\t\tsend(`🤖 *Subagent result:*\\n${block.text.trim()}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Show background agent completion results — these arrive as user\n\t\t\t// messages injected by agent-session.ts via prompt()/steer() and\n\t\t\t// contain the actual subagent output the model sees.\n\t\t\tif (msg?.role === \"user\") {\n\t\t\t\tconst content = msg?.content;\n\t\t\t\tif (content && Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (block.type === \"text\" && block.text?.includes(\"<background-agent-complete>\")) {\n\t\t\t\t\t\t\t// Extract the content between the XML tags\n\t\t\t\t\t\t\tconst match = block.text.match(\n\t\t\t\t\t\t\t\t/<background-agent-complete>\\n?([\\s\\S]*?)\\n?<\\/background-agent-complete>/,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (match?.[1]?.trim()) {\n\t\t\t\t\t\t\t\tsend(`🤖 *Background agent complete:*\\n${match[1].trim()}`, true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Only display assistant messages — user messages are echoed back by RPC\n\t\t\tif (msg?.role !== \"assistant\") break;\n\t\t\tconst content = msg?.content;\n\t\t\tif (!content || !Array.isArray(content)) break;\n\n\t\t\tfor (const block of content) {\n\t\t\t\t// Display thinking blocks (collapsed summary)\n\t\t\t\tif (block.type === \"thinking\" && block.thinking?.trim() && !block.redacted) {\n\t\t\t\t\tconst thinking = block.thinking.trim();\n\t\t\t\t\tsend(`💭 _${thinking}_`, true);\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\" && block.text?.trim()) {\n\t\t\t\t\tconst text = block.text.trim();\n\n\t\t\t\t\t// Flush accumulated tools as permanent summary\n\t\t\t\t\tif (state.toolsSinceText.length > 0) {\n\t\t\t\t\t\tconst summary = `📋 *${state.toolsSinceText.length} tools*:\\n${state.toolsSinceText.join(\"\\n\")}`;\n\t\t\t\t\t\tsend(summary, true);\n\t\t\t\t\t\tstate.toolsSinceText = [];\n\t\t\t\t\t}\n\n\t\t\t\t\t// Send the text as a permanent message\n\t\t\t\t\tstate.textBlocks.push(text);\n\n\t\t\t\t\t// Check for file send markers\n\t\t\t\t\tconst [cleanText, filePaths] = extractSendFiles(text);\n\t\t\t\t\tif (cleanText) {\n\t\t\t\t\t\tsend(cleanText, true);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Send any requested files (silently skip non-existent paths —\n\t\t\t\t\t// the pattern may appear in explanatory text)\n\t\t\t\t\tfor (const filePath of filePaths) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (existsSync(filePath)) {\n\t\t\t\t\t\t\t\tawait api.sendDocument(state.chatId, new InputFile(filePath));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tlog(`[EVENTS] Failed to send file ${filePath}: ${e}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Feed event to buddy controller for context capture + reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"tasks_update\": {\n\t\t\tstate.tasks = (event as any).tasks || [];\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"background_agent_start\": {\n\t\t\tconst { agentId, agentType, taskSummary } = event as any;\n\t\t\tstate.backgroundAgents.set(agentId, {\n\t\t\t\tagentId,\n\t\t\t\tagentType,\n\t\t\t\ttaskSummary,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t});\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"background_agent_end\": {\n\t\t\tconst { agentId } = event as any;\n\t\t\tstate.backgroundAgents.delete(agentId);\n\t\t\t// Background agents completing does not end the parent's turn.\n\t\t\t// Only agent_end sets done — same as TUI behavior.\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_compaction_start\": {\n\t\t\tupdateStatusText(state, \"🗜 _Compacting context..._\");\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_compaction_end\": {\n\t\t\tconst result = (event as any).result;\n\t\t\tif (result) {\n\t\t\t\tconst before = result.tokensBefore || 0;\n\t\t\t\tconst msg = `🗜 Context compacted (was ${Math.round(before / 1000)}k tokens)`;\n\t\t\t\tsend(msg);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// =====================================================================\n\t\t// Auto-retry — prevents agent_end from marking done during retries\n\t\t// =====================================================================\n\n\t\tcase \"auto_retry_start\": {\n\t\t\tconst { attempt, maxAttempts, delayMs, errorMessage } = event as any;\n\t\t\tstate.retryInProgress = true;\n\t\t\tstate.pendingRetry = false; // Layer 1 has taken over from Layer 2\n\t\t\tstate.retryAttempt = attempt;\n\t\t\tconst delaySec = Math.round(delayMs / 1000);\n\t\t\tconst shortErr = errorMessage?.length > 80 ? `${errorMessage.slice(0, 80)}…` : errorMessage;\n\t\t\tupdateStatusText(state, `🔄 _Retrying (${attempt}/${maxAttempts}) in ${delaySec}s — ${shortErr || \"error\"}_`);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_retry_end\": {\n\t\t\tconst { success, attempt, finalError } = event as any;\n\t\t\tstate.retryInProgress = false;\n\t\t\tstate.retryAttempt = 0;\n\t\t\tif (!success && finalError) {\n\t\t\t\t// Max retries exhausted — show final error\n\t\t\t\tsend(`❌ _Retry failed (${attempt} attempts):_ ${finalError}`, true);\n\t\t\t}\n\t\t\t// On success, the retry's agent_start/agent_end cycle will handle display normally\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"agent_end\": {\n\t\t\t// Flush any remaining tools\n\t\t\tif (state.toolsSinceText.length > 0) {\n\t\t\t\tconst summary = `📋 *${state.toolsSinceText.length} tools*:\\n${state.toolsSinceText.join(\"\\n\")}`;\n\t\t\t\tsend(summary, true);\n\t\t\t\tstate.toolsSinceText = [];\n\t\t\t}\n\n\t\t\t// Check for error in agent_end messages\n\t\t\tconst errorMsg = (event.messages as any[])?.find(\n\t\t\t\t(m: any) => m.stopReason === \"error\" || m.stopReason === \"aborted\",\n\t\t\t);\n\n\t\t\t// Layer 2 (defensive): If this error looks retryable and we're not already\n\t\t\t// tracking a retry via Layer 1, don't mark done — the core will auto-retry\n\t\t\t// and emit a new agent_start/agent_end cycle.\n\t\t\tconst errorIsRetryable = errorMsg?.errorMessage && isRetryableError(errorMsg.errorMessage);\n\n\t\t\tif (errorMsg?.errorMessage) {\n\t\t\t\t// Suppress the scary error message during retry — user already saw the\n\t\t\t\t// auto_retry_start status. Only show the error if retry tracking missed it\n\t\t\t\t// (defensive: shouldn't happen, but better than silence).\n\t\t\t\tif (!state.retryInProgress && !errorIsRetryable) {\n\t\t\t\t\tconst provider = errorMsg.provider ? `${errorMsg.provider}/${errorMsg.model}` : \"\";\n\t\t\t\t\tconst prefix = provider ? `${provider}: ` : \"\";\n\t\t\t\t\tconst errLower = errorMsg.errorMessage.toLowerCase();\n\t\t\t\t\tconst hint =\n\t\t\t\t\t\terrLower.includes(\"connection\") || errLower.includes(\"timeout\") || errLower.includes(\"network\")\n\t\t\t\t\t\t\t? \"\\n_Provider may be down — try /model to switch._\"\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\tsend(`❌ ${prefix}${errorMsg.errorMessage}${hint}`, true);\n\t\t\t\t}\n\t\t\t} else if (state.textBlocks.length === 0 && state.backgroundAgents.size === 0) {\n\t\t\t\t// Only show \"(No response)\" when truly done — not between agent cycles\n\t\t\t\tif (!state.retryInProgress && !errorIsRetryable) {\n\t\t\t\t\tsend(\"(No response)\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Feed event to buddy controller for context capture + reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\n\t\t\t// Don't mark done if auto-retry is in progress (Layer 1) or the error\n\t\t\t// looks retryable (Layer 2 — defensive catch in case events were missed).\n\t\t\t// The core will emit a new agent_start/agent_end cycle for the retry.\n\t\t\tif (state.retryInProgress || errorIsRetryable) {\n\t\t\t\t// Signal that a retry is expected — the completion check in\n\t\t\t\t// ensureSubscribed needs this because it runs in the eventChain\n\t\t\t\t// BEFORE auto_retry_start has been processed.\n\t\t\t\tif (errorIsRetryable) state.pendingRetry = true;\n\t\t\t\t// Reset per-cycle state for the next agent loop\n\t\t\t\tstate.textBlocks = [];\n\t\t\t\tstate.toolCount = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// If background agents are still running, keep the subscription alive\n\t\t\t// and reset per-cycle state for the next agent loop\n\t\t\tif (state.backgroundAgents.size > 0) {\n\t\t\t\tstate.textBlocks = [];\n\t\t\t\tstate.toolCount = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Delete ephemeral status before signaling done\n\t\t\tif (state.statusMessageId) {\n\t\t\t\tawait state.editor.flush(state.chatId, state.statusMessageId);\n\t\t\t\tawait safeDelete(api, state.chatId, state.statusMessageId);\n\t\t\t\tstate.statusMessageId = null;\n\t\t\t}\n\n\t\t\t// Clean up editor\n\t\t\tstate.editor.clear();\n\n\t\t\t// Signal done AFTER cleanup — waitForCompletion checks this flag,\n\t\t\t// so setting it last ensures status message is deleted before DONE is sent\n\t\t\tstate.done = true;\n\t\t\tbreak;\n\t\t}\n\n\t\t// Handle error responses that leak through RPC (async prompt errors)\n\t\tcase \"response\": {\n\t\t\tconst resp = event as any;\n\t\t\tif (!resp.success && resp.error) {\n\t\t\t\tsend(`❌ ${resp.error}`, true);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Build and push a status update to the ephemeral message.\n */\nfunction updateStatus(state: EventDisplayState): void {\n\tif (!state.statusMessageId) return;\n\n\tconst parts: string[] = [];\n\n\t// Tool count header\n\tif (state.toolCount > 0) {\n\t\tparts.push(`🔧 *Tool ${state.toolCount}*`);\n\t}\n\n\t// Task list\n\tif (state.tasks.length > 0) {\n\t\tparts.push(formatTaskList(state.tasks));\n\t}\n\n\t// Background agents\n\tif (state.backgroundAgents.size > 0) {\n\t\tfor (const agent of state.backgroundAgents.values()) {\n\t\t\tparts.push(`🤖 *${agent.agentType}*: ${agent.taskSummary.slice(0, 200)}`);\n\t\t}\n\t}\n\n\t// Recent tools (last 5)\n\tif (state.toolsSinceText.length > 0) {\n\t\tconst recent = state.toolsSinceText.slice(-5);\n\t\tparts.push(recent.join(\"\\n\\n\"));\n\t}\n\n\tif (parts.length === 0) return;\n\n\tconst text = parts.join(\"\\n\\n\").slice(0, 4000);\n\tstate.editor.edit(state.chatId, state.statusMessageId, text);\n}\n\nfunction updateStatusText(state: EventDisplayState, text: string): void {\n\tif (!state.statusMessageId) return;\n\tstate.editor.edit(state.chatId, state.statusMessageId, text);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/handlers/events.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAEnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAavE,+DAA+D;AAC/D,MAAM,UAAU,GAA2B;IAC1C,IAAI,EAAE,MAAG;IACT,IAAI,EAAE,MAAG;IACT,IAAI,EAAE,QAAI;IACV,KAAK,EAAE,MAAG;IACV,IAAI,EAAE,MAAG;IACT,IAAI,EAAE,MAAG;IACT,EAAE,EA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7D;AAED,SAAS,gBAAgB,CAAC,KAAwB,EAAE,IAAY,EAAQ;IACvE,IAAI,CAAC,KAAK,CAAC,eAAe;QAAE,OAAO;IACnC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;AAAA,CAC7D","sourcesContent":["/**\n * Event display — translates RPC agent events into Telegram messages.\n *\n * Manages an ephemeral status message that shows tool use, task lists,\n * and subagent activity. Text from the agent is sent as permanent messages.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { Api } from \"grammy\";\nimport { InputFile } from \"grammy\";\nimport type { TrackedAgent } from \"../types.js\";\nimport { extractSendFiles } from \"../util/files.js\";\nimport { DebouncedEditor, log, safeDelete } from \"../util/telegram.js\";\n\n/** Callback to queue a message for delivery — never blocks the event chain */\nexport type SendFn = (text: string, long?: boolean) => void;\n\n/**\n * RPC events include both core AgentEvent and session-specific events\n * (tasks_update, background_agent_*, auto_compaction_*).\n * We type loosely here since the RPC client types onEvent as AgentEvent\n * but actually forwards all AgentSessionEvent types.\n */\ntype RpcEvent = { type: string; [key: string]: any };\n\n// Tool emoji mapping (tool names are lowercase in definitions)\nconst TOOL_EMOJI: Record<string, string> = {\n\tbash: \"🔧\",\n\tread: \"📖\",\n\tedit: \"✏️\",\n\twrite: \"📝\",\n\tgrep: \"🔎\",\n\tfind: \"🔍\",\n\tls: \"📂\",\n\tweb_search: \"🌐\",\n\tweb_fetch: \"🌐\",\n\tsubagent: \"🤖\",\n\ttasks_update: \"📋\",\n\tskill: \"⚡\",\n};\n\nfunction toolEmoji(name: string): string {\n\treturn TOOL_EMOJI[name] || \"🔧\";\n}\n\n/** Format a tool call for display */\nfunction formatTool(name: string, args: Record<string, any>): string {\n\tconst emoji = toolEmoji(name);\n\tswitch (name) {\n\t\tcase \"bash\": {\n\t\t\tconst cmd = args.command || \"\";\n\t\t\treturn `${emoji} *bash*\\n\\`${cmd.slice(0, 500)}\\``;\n\t\t}\n\t\tcase \"read\":\n\t\t\treturn `${emoji} *read*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"edit\":\n\t\t\treturn `${emoji} *edit*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"write\":\n\t\t\treturn `${emoji} *write*: \\`${args.path || \"?\"}\\``;\n\t\tcase \"grep\":\n\t\t\treturn `${emoji} *grep*: \\`${args.pattern || \"?\"}\\``;\n\t\tcase \"find\":\n\t\t\treturn `${emoji} *find*: \\`${args.pattern || \"?\"}\\``;\n\t\tcase \"ls\":\n\t\t\treturn `${emoji} *ls*: \\`${args.path || \".\"}\\``;\n\t\tcase \"web_search\":\n\t\t\treturn `${emoji} *web\\\\_search*: ${args.query || \"?\"}`;\n\t\tcase \"web_fetch\":\n\t\t\treturn `${emoji} *web\\\\_fetch*: ${(args.url || \"?\").slice(0, 80)}`;\n\t\tcase \"subagent\":\n\t\t\treturn `${emoji} *subagent* (${args.agent || \"?\"}): ${(args.task || args.tasks?.[0]?.task || \"?\").slice(0, 200)}`;\n\t\tcase \"skill\":\n\t\t\treturn `${emoji} *skill*: ${args.skill || \"?\"}`;\n\t\tdefault:\n\t\t\treturn `${emoji} *${name}*`;\n\t}\n}\n\n/** Format task list as checklist */\nfunction formatTaskList(tasks: Array<{ id: string; title: string; status: string }>): string {\n\tif (!tasks.length) return \"📋 *Tasks*: (empty)\";\n\tconst lines = [\"📋 *Tasks*:\"];\n\tfor (const task of tasks) {\n\t\tif (task.status === \"completed\") lines.push(` ✅ ${task.title}`);\n\t\telse if (task.status === \"in_progress\") lines.push(` 🔄 ${task.title}`);\n\t\telse lines.push(` ⬜ ${task.title}`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport interface EventDisplayState {\n\t/** Chat ID to send messages to */\n\tchatId: number;\n\t/** Message ID to reply to */\n\treplyToId: number;\n\t/** Ephemeral status message ID (edited in-place) */\n\tstatusMessageId: number | null;\n\t/** Tool messages accumulated since last text */\n\ttoolsSinceText: string[];\n\t/** Total tool count */\n\ttoolCount: number;\n\t/** All text blocks received */\n\ttextBlocks: string[];\n\t/** Current task list */\n\ttasks: Array<{ id: string; title: string; status: string }>;\n\t/** Background agents */\n\tbackgroundAgents: Map<string, TrackedAgent>;\n\t/** Whether agent has finished */\n\tdone: boolean;\n\t/** Debounced editor instance */\n\teditor: DebouncedEditor;\n\t/** Whether auto-retry is in progress (Layer 1: reactive — set by auto_retry_start) */\n\tretryInProgress: boolean;\n\t/** Whether a retry is expected (Layer 2: predictive — set by agent_end when error looks retryable) */\n\tpendingRetry: boolean;\n\t/** Current retry attempt number for display */\n\tretryAttempt: number;\n\t/** Buddy controller — receives agent events for context + reactions */\n\tbuddyController?: any;\n}\n\n/**\n * Check if an error message looks retryable (overloaded, rate limit, server errors).\n * Mirrors the core's _isRetryableError check as a defensive Layer 2.\n */\nconst RETRYABLE_ERROR_PATTERN =\n\t/overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|other side closed|fetch failed|ended without|upstream.?connect|reset before headers|socket hang up|timed? out|timeout|terminated|retry delay/i;\n\nfunction isRetryableError(errorMessage: string): boolean {\n\treturn RETRYABLE_ERROR_PATTERN.test(errorMessage);\n}\n\n/**\n * Create a fresh event display state for a new agent run.\n */\nexport function createEventDisplay(\n\tapi: Api,\n\tchatId: number,\n\treplyToId: number,\n\tstatusMessageId: number | null,\n): EventDisplayState {\n\treturn {\n\t\tchatId,\n\t\treplyToId,\n\t\tstatusMessageId,\n\t\ttoolsSinceText: [],\n\t\ttoolCount: 0,\n\t\ttextBlocks: [],\n\t\ttasks: [],\n\t\tbackgroundAgents: new Map(),\n\t\tdone: false,\n\t\teditor: new DebouncedEditor(api),\n\t\tretryInProgress: false,\n\t\tpendingRetry: false,\n\t\tretryAttempt: 0,\n\t};\n}\n\n/**\n * Process an agent event and update the display.\n */\nexport async function handleAgentEvent(\n\tsend: SendFn,\n\tapi: Api,\n\tstate: EventDisplayState,\n\tevent: RpcEvent,\n): Promise<void> {\n\tswitch (event.type) {\n\t\tcase \"tool_execution_start\": {\n\t\t\tconst name = event.toolName || \"?\";\n\t\t\tconst args = event.args || {};\n\t\t\tstate.toolCount++;\n\n\t\t\t// tasks_update is shown via the separate tasks_update event — skip from tool summary\n\t\t\tif (name !== \"tasks_update\") {\n\t\t\t\tconst toolMsg = formatTool(name, args);\n\t\t\t\tstate.toolsSinceText.push(toolMsg);\n\t\t\t}\n\n\t\t\t// Update status with tool count and recent tools\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"tool_execution_end\": {\n\t\t\t// Feed event to buddy controller for context capture + error reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"message_end\": {\n\t\t\tconst msg = event.message;\n\n\t\t\t// Show subagent results — the parent agent references these but the\n\t\t\t// Telegram user can't see them otherwise. Send the full content.\n\t\t\tif (msg?.role === \"toolResult\" && msg?.toolName === \"subagent\") {\n\t\t\t\tconst content = msg?.content;\n\t\t\t\tif (content && Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (block.type === \"text\" && block.text?.trim()) {\n\t\t\t\t\t\t\tsend(`🤖 *Subagent result:*\\n${block.text.trim()}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Show background agent completion results — these arrive as user\n\t\t\t// messages injected by agent-session.ts via prompt()/steer() and\n\t\t\t// contain the actual subagent output the model sees.\n\t\t\tif (msg?.role === \"user\") {\n\t\t\t\tconst content = msg?.content;\n\t\t\t\tif (content && Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (block.type === \"text\" && block.text?.includes(\"<background-agent-complete>\")) {\n\t\t\t\t\t\t\t// Extract the content between the XML tags\n\t\t\t\t\t\t\tconst match = block.text.match(\n\t\t\t\t\t\t\t\t/<background-agent-complete>\\n?([\\s\\S]*?)\\n?<\\/background-agent-complete>/,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (match?.[1]?.trim()) {\n\t\t\t\t\t\t\t\tsend(`🤖 *Background agent complete:*\\n${match[1].trim()}`, true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Only display assistant messages — user messages are echoed back by RPC\n\t\t\tif (msg?.role !== \"assistant\") break;\n\t\t\tconst content = msg?.content;\n\t\t\tif (!content || !Array.isArray(content)) break;\n\n\t\t\tfor (const block of content) {\n\t\t\t\t// Display thinking blocks (collapsed summary)\n\t\t\t\tif (block.type === \"thinking\" && block.thinking?.trim() && !block.redacted) {\n\t\t\t\t\tconst thinking = block.thinking.trim();\n\t\t\t\t\tsend(`💭 _${thinking}_`, true);\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\" && block.text?.trim()) {\n\t\t\t\t\tconst text = block.text.trim();\n\n\t\t\t\t\t// Flush accumulated tools as permanent summary\n\t\t\t\t\tif (state.toolsSinceText.length > 0) {\n\t\t\t\t\t\tconst summary = `📋 *${state.toolsSinceText.length} tools*:\\n${state.toolsSinceText.join(\"\\n\")}`;\n\t\t\t\t\t\tsend(summary, true);\n\t\t\t\t\t\tstate.toolsSinceText = [];\n\t\t\t\t\t}\n\n\t\t\t\t\t// Send the text as a permanent message\n\t\t\t\t\tstate.textBlocks.push(text);\n\n\t\t\t\t\t// Check for file send markers\n\t\t\t\t\tconst [cleanText, filePaths] = extractSendFiles(text);\n\t\t\t\t\tif (cleanText) {\n\t\t\t\t\t\tsend(cleanText, true);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Send any requested files (silently skip non-existent paths —\n\t\t\t\t\t// the pattern may appear in explanatory text)\n\t\t\t\t\tfor (const filePath of filePaths) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (existsSync(filePath)) {\n\t\t\t\t\t\t\t\tawait api.sendDocument(state.chatId, new InputFile(filePath));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tlog(`[EVENTS] Failed to send file ${filePath}: ${e}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Feed event to buddy controller for context capture + reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"tasks_update\": {\n\t\t\tstate.tasks = (event as any).tasks || [];\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"background_agent_start\": {\n\t\t\tconst { agentId, agentType, taskSummary } = event as any;\n\t\t\tstate.backgroundAgents.set(agentId, {\n\t\t\t\tagentId,\n\t\t\t\tagentType,\n\t\t\t\ttaskSummary,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t});\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"background_agent_end\": {\n\t\t\tconst { agentId } = event as any;\n\t\t\tstate.backgroundAgents.delete(agentId);\n\t\t\t// Background agents completing does not end the parent's turn.\n\t\t\t// Only agent_end sets done — same as TUI behavior.\n\t\t\tupdateStatus(state);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_compaction_start\": {\n\t\t\tupdateStatusText(state, \"🗜 _Compacting context..._\");\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_compaction_end\": {\n\t\t\tconst result = (event as any).result;\n\t\t\tif (result) {\n\t\t\t\tconst before = result.tokensBefore || 0;\n\t\t\t\tconst msg = `🗜 Context compacted (was ${Math.round(before / 1000)}k tokens)`;\n\t\t\t\tsend(msg);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// =====================================================================\n\t\t// Auto-retry — prevents agent_end from marking done during retries\n\t\t// =====================================================================\n\n\t\tcase \"auto_retry_start\": {\n\t\t\tconst { attempt, maxAttempts, delayMs, errorMessage } = event as any;\n\t\t\tstate.retryInProgress = true;\n\t\t\tstate.pendingRetry = false; // Layer 1 has taken over from Layer 2\n\t\t\tstate.retryAttempt = attempt;\n\t\t\tconst delaySec = Math.round(delayMs / 1000);\n\t\t\tconst shortErr = errorMessage?.length > 80 ? `${errorMessage.slice(0, 80)}…` : errorMessage;\n\t\t\tupdateStatusText(state, `🔄 _Retrying (${attempt}/${maxAttempts}) in ${delaySec}s — ${shortErr || \"error\"}_`);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"auto_retry_end\": {\n\t\t\tconst { success, attempt, finalError } = event as any;\n\t\t\tstate.retryInProgress = false;\n\t\t\tstate.retryAttempt = 0;\n\t\t\tif (!success && finalError) {\n\t\t\t\t// Max retries exhausted — show final error\n\t\t\t\tsend(`❌ _Retry failed (${attempt} attempts):_ ${finalError}`, true);\n\t\t\t}\n\t\t\t// On success, the retry's agent_start/agent_end cycle will handle display normally\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"agent_end\": {\n\t\t\t// Flush any remaining tools\n\t\t\tif (state.toolsSinceText.length > 0) {\n\t\t\t\tconst summary = `📋 *${state.toolsSinceText.length} tools*:\\n${state.toolsSinceText.join(\"\\n\")}`;\n\t\t\t\tsend(summary, true);\n\t\t\t\tstate.toolsSinceText = [];\n\t\t\t}\n\n\t\t\t// Check for error in agent_end messages\n\t\t\tconst errorMsg = (event.messages as any[])?.find(\n\t\t\t\t(m: any) => m.stopReason === \"error\" || m.stopReason === \"aborted\",\n\t\t\t);\n\n\t\t\t// Layer 2 (defensive): If this error looks retryable and we're not already\n\t\t\t// tracking a retry via Layer 1, don't mark done — the core will auto-retry\n\t\t\t// and emit a new agent_start/agent_end cycle.\n\t\t\tconst errorIsRetryable = errorMsg?.errorMessage && isRetryableError(errorMsg.errorMessage);\n\n\t\t\tif (errorMsg?.errorMessage) {\n\t\t\t\t// Suppress the scary error message during retry — user already saw the\n\t\t\t\t// auto_retry_start status. Only show the error if retry tracking missed it\n\t\t\t\t// (defensive: shouldn't happen, but better than silence).\n\t\t\t\tif (!state.retryInProgress && !errorIsRetryable) {\n\t\t\t\t\tconst provider = errorMsg.provider ? `${errorMsg.provider}/${errorMsg.model}` : \"\";\n\t\t\t\t\tconst prefix = provider ? `${provider}: ` : \"\";\n\t\t\t\t\tconst errLower = errorMsg.errorMessage.toLowerCase();\n\t\t\t\t\tconst hint =\n\t\t\t\t\t\terrLower.includes(\"connection\") || errLower.includes(\"timeout\") || errLower.includes(\"network\")\n\t\t\t\t\t\t\t? \"\\n_Provider may be down — try /model to switch._\"\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\tsend(`❌ ${prefix}${errorMsg.errorMessage}${hint}`, true);\n\t\t\t\t}\n\t\t\t} else if (state.textBlocks.length === 0 && state.backgroundAgents.size === 0) {\n\t\t\t\t// Only show \"(No response)\" when truly done — not between agent cycles\n\t\t\t\tif (!state.retryInProgress && !errorIsRetryable) {\n\t\t\t\t\tsend(\"(No response)\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Feed event to buddy controller for context capture + reactions\n\t\t\tstate.buddyController?.handleEvent(event);\n\n\t\t\t// Don't mark done if auto-retry is in progress (Layer 1) or the error\n\t\t\t// looks retryable (Layer 2 — defensive catch in case events were missed).\n\t\t\t// The core will emit a new agent_start/agent_end cycle for the retry.\n\t\t\tif (state.retryInProgress || errorIsRetryable) {\n\t\t\t\t// Signal that a retry is expected — the completion check in\n\t\t\t\t// ensureSubscribed needs this because it runs in the eventChain\n\t\t\t\t// BEFORE auto_retry_start has been processed.\n\t\t\t\tif (errorIsRetryable) state.pendingRetry = true;\n\t\t\t\t// Reset per-cycle state for the next agent loop\n\t\t\t\tstate.textBlocks = [];\n\t\t\t\tstate.toolCount = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// If background agents are still running, keep the subscription alive\n\t\t\t// and reset per-cycle state for the next agent loop\n\t\t\tif (state.backgroundAgents.size > 0) {\n\t\t\t\tstate.textBlocks = [];\n\t\t\t\tstate.toolCount = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Delete ephemeral status before signaling done\n\t\t\tif (state.statusMessageId) {\n\t\t\t\tawait state.editor.flush(state.chatId, state.statusMessageId);\n\t\t\t\tawait safeDelete(api, state.chatId, state.statusMessageId);\n\t\t\t\tstate.statusMessageId = null;\n\t\t\t}\n\n\t\t\t// Clean up editor\n\t\t\tstate.editor.clear();\n\n\t\t\t// Signal done AFTER cleanup — waitForCompletion checks this flag,\n\t\t\t// so setting it last ensures status message is deleted before DONE is sent\n\t\t\tstate.done = true;\n\t\t\tbreak;\n\t\t}\n\n\t\t// Handle error responses that leak through RPC (async prompt errors)\n\t\tcase \"response\": {\n\t\t\tconst resp = event as any;\n\t\t\tif (!resp.success && resp.error) {\n\t\t\t\tsend(`❌ ${resp.error}`, true);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Build and push a status update to the ephemeral message.\n */\nfunction updateStatus(state: EventDisplayState): void {\n\tif (!state.statusMessageId) return;\n\n\tconst parts: string[] = [];\n\n\t// Tool count header\n\tif (state.toolCount > 0) {\n\t\tparts.push(`🔧 *Tool ${state.toolCount}*`);\n\t}\n\n\t// Task list\n\tif (state.tasks.length > 0) {\n\t\tparts.push(formatTaskList(state.tasks));\n\t}\n\n\t// Background agents\n\tif (state.backgroundAgents.size > 0) {\n\t\tfor (const agent of state.backgroundAgents.values()) {\n\t\t\tparts.push(`🤖 *${agent.agentType}*: ${agent.taskSummary.slice(0, 200)}`);\n\t\t}\n\t}\n\n\t// Recent tools (last 5)\n\tif (state.toolsSinceText.length > 0) {\n\t\tconst recent = state.toolsSinceText.slice(-5);\n\t\tparts.push(recent.join(\"\\n\\n\"));\n\t}\n\n\tif (parts.length === 0) return;\n\n\tconst text = parts.join(\"\\n\\n\").slice(0, 4000);\n\tstate.editor.edit(state.chatId, state.statusMessageId, text);\n}\n\nfunction updateStatusText(state: EventDisplayState, text: string): void {\n\tif (!state.statusMessageId) return;\n\tstate.editor.edit(state.chatId, state.statusMessageId, text);\n}\n"]}
|