telecoder 0.0.0-stage → 1.2.0

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.
Files changed (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
@@ -0,0 +1,1287 @@
1
+ import { InputFile, GrammyError } from 'grammy';
2
+ import { config } from '../config.js';
3
+ import { formatMarkdown, markdownToEntities, splitEntityMessage, MAX_MESSAGE_LENGTH } from './markdown.js';
4
+ import { editFormatted, replyFormatted } from './send.js';
5
+ import { stripReasoningSummary } from '../utils/reasoning-summary.js';
6
+ import { shouldPublishTelegraph, createTelegraphPage, createTelegraphFromFile } from './telegraph.js';
7
+ import { isTerminalUIEnabled } from './terminal-settings.js';
8
+ import { getSpinnerFrame, getThinkingVerb, getToolIcon, getToolAction, renderStatusLine, renderBackgroundFooter, extractToolDetail, formatBashCommandBlock, elideToolOutput, stripAnsi, TOOL_ICONS, } from './terminal-renderer.js';
9
+ import { taskTracker } from './task-tracker.js';
10
+ import { taskListDisplay } from './task-list.js';
11
+ import { EntityText, clip, plain } from './entities.js';
12
+ import { getSessionKeyFromCtx, parseSessionKey } from '../utils/session-key.js';
13
+ import { resolveVerbosityFlags } from '../utils/verbosity.js';
14
+ import { actionLogger } from './action-logger.js';
15
+ import { sessionManager } from '../claude/session-manager.js';
16
+ import { sessionJsonlPath } from '../claude/session-jsonl.js';
17
+ import { messageOffsets, countJsonlLines } from '../claude/message-offsets.js';
18
+ import { storeSuggestion } from '../claude/pending-suggestions.js';
19
+ import { SUGGESTION_CARD_BUTTON, buildSuggestionCardText, flattenSuggestion, formatSuggestionLabel, suggestionFitsOnButton, } from './prompt-suggestion.js';
20
+ import { hasPendingQuestionForSession } from '../claude/ask-user.js';
21
+ import { PREMIUM_MODEL_ICON } from '../claude/model-catalog.js';
22
+ import { getPremiumModel } from '../providers/provider-router.js';
23
+ import * as fs from 'fs';
24
+ import * as path from 'path';
25
+ import { isClaudeAuthError } from '../claude/claude-auth.js';
26
+ export const FORK_KEYBOARD = { inline_keyboard: [[{ text: '🍴 Fork', callback_data: 'fork:pick' }]] };
27
+ /**
28
+ * The buttons on the banner where a chat switched conversations: fork that
29
+ * point again, or open the tree of branches it belongs to.
30
+ */
31
+ export const BRANCH_MARKER_KEYBOARD = {
32
+ inline_keyboard: [[
33
+ { text: '🍴 Fork', callback_data: 'fork:pick' },
34
+ { text: '🌳 Tree', callback_data: 'tree:show' },
35
+ ]],
36
+ };
37
+ /**
38
+ * Status-bubble text shown while an ask_user question is waiting on a tap.
39
+ * Replaces the spinner: the watchdog is deliberately paused during a pending
40
+ * question, so nothing else stops the bubble animating "Thinking…" at a turn
41
+ * that is actually parked on the user.
42
+ */
43
+ const AWAITING_ANSWER_LINE = '⏸️ Waiting for your answer — see the question below ↓';
44
+ /**
45
+ * Status-bubble text once the action log has taken the live status line over.
46
+ * The log is posted below the bubble and is usually tall enough to push it off
47
+ * screen, so the status line moves to the bottom of the log, where the user is
48
+ * looking.
49
+ */
50
+ const LOG_POINTER_LINE = '⏳ Working — live log below ↓';
51
+ /**
52
+ * Cap on a tool's detail in the status line under the action log. Verbose mode
53
+ * shows paths and patterns whole, and the line shares its message with up to
54
+ * ten actions.
55
+ */
56
+ const LOG_STATUS_DETAIL_CHARS = 200;
57
+ /**
58
+ * Register a suggestion in the pending-suggestions store and decide how it
59
+ * reaches the user: on a button when it fits there whole, otherwise on a card
60
+ * of its own. Returns null when there is no suggestion for this turn (the
61
+ * caller still gets its fork button).
62
+ */
63
+ function planSuggestion(sessionKey, suggestion) {
64
+ const text = flattenSuggestion(suggestion ?? '');
65
+ if (!text)
66
+ return null;
67
+ const onButton = suggestionFitsOnButton(text);
68
+ const id = storeSuggestion(sessionKey, text, onButton ? 'button' : 'card');
69
+ return { id, text, onButton };
70
+ }
71
+ const TYPING_INTERVAL_MS = 4000; // Send typing every 4 seconds
72
+ const MIN_EDIT_INTERVAL_MS = 10000; // Minimum time between status-only edits (~5 edits/min safe zone)
73
+ /**
74
+ * Minimum time between edits that show more of the reply. Telegram allows a
75
+ * bot about one message a second in a private chat and twenty a minute in a
76
+ * group, edits included, and the status line and action log draw on the same
77
+ * allowance. A 429 doubles the gap, up to {@link MAX_STREAM_EDIT_INTERVAL_MS}.
78
+ */
79
+ const STREAM_EDIT_INTERVAL_MS = 1500;
80
+ const GROUP_STREAM_EDIT_INTERVAL_MS = 3500;
81
+ const MAX_STREAM_EDIT_INTERVAL_MS = 15000;
82
+ /** How long after new text the status line keeps saying "Writing". */
83
+ const WRITING_WINDOW_MS = 4000;
84
+ /**
85
+ * Under a reply that is still being written, where the status line would be
86
+ * without the terminal UI: the text above it isn't final yet.
87
+ */
88
+ const STREAMING_INDICATOR = '✍️ Writing…';
89
+ /**
90
+ * Tacked onto the status line's first line while a premium model is on, so a
91
+ * fable picked for one task doesn't go on quietly spending the plan's limits
92
+ * on the next ten.
93
+ */
94
+ function premiumBadge(model) {
95
+ return model ? ` · ${PREMIUM_MODEL_ICON} ${model}` : '';
96
+ }
97
+ const MONITOR_TASK_TYPE = 'monitor_mcp';
98
+ /**
99
+ * How a background task is named in its start line and the completion that
100
+ * replaces it, by the SDK's task_type. The same icons as the PTY card's.
101
+ */
102
+ function taskKind(taskType) {
103
+ switch (taskType) {
104
+ case MONITOR_TASK_TYPE: return { icon: '📡', label: 'Monitor' };
105
+ case 'local_bash': return { icon: '⚙️', label: 'Command' };
106
+ case 'local_agent': return { icon: '🤖', label: 'Subagent' };
107
+ case 'local_workflow': return { icon: '📋', label: 'Workflow' };
108
+ default: return { icon: '⚙️', label: 'Task' };
109
+ }
110
+ }
111
+ function shortDescription(description) {
112
+ return description.length > 100 ? description.substring(0, 97) + '...' : description;
113
+ }
114
+ /**
115
+ * Publish a long reply as an Instant View page and return the footer line that
116
+ * points at it, or null when the chat hasn't asked for pages, the reply is
117
+ * short, or telegra.ph is unreachable.
118
+ *
119
+ * Every failure path returns null rather than throwing. The page is decoration
120
+ * on an answer that is about to be delivered in full either way, so a Telegraph
121
+ * outage must never cost the user the reply — which is exactly what the old
122
+ * publish-or-nothing flow did when it swapped the text out for a 200-character
123
+ * stub and the link then failed to render.
124
+ */
125
+ async function publishTelegraphFooter(text, sessionKey) {
126
+ if (!shouldPublishTelegraph(text, sessionKey))
127
+ return null;
128
+ try {
129
+ const pageUrl = await createTelegraphPage('Claude Response', text);
130
+ if (!pageUrl)
131
+ return null;
132
+ return new EntityText().add('📄 ').link('Open in Instant View', pageUrl).build();
133
+ }
134
+ catch (error) {
135
+ console.error('[Telegraph] Failed to publish page:', error instanceof Error ? error.message : error);
136
+ return null;
137
+ }
138
+ }
139
+ /**
140
+ * Hang `footer` under the last chunk of a reply, or give it a chunk of its own
141
+ * when appending would push that message past Telegram's limit.
142
+ *
143
+ * Exported for tests: the boundary is the whole point of the function, and it
144
+ * is the one place a bug would silently cost a chunk.
145
+ */
146
+ export function withTelegraphFooter(parts, footer) {
147
+ if (!footer)
148
+ return parts;
149
+ const last = parts[parts.length - 1];
150
+ if (last !== undefined && last.text.length + 2 + footer.text.length <= config.MAX_MESSAGE_LENGTH) {
151
+ return [...parts.slice(0, -1), new EntityText().append(last).newline(2).append(footer).build()];
152
+ }
153
+ return [...parts, footer];
154
+ }
155
+ // `mcp__telecoder-tools__telecoder_send_file` → `telecoder_send_file`
156
+ function stripMcpServerPrefix(toolName) {
157
+ if (!toolName.startsWith('mcp__'))
158
+ return toolName;
159
+ const lastSep = toolName.lastIndexOf('__');
160
+ return lastSep > 0 ? toolName.slice(lastSep + 2) : toolName;
161
+ }
162
+ /**
163
+ * Trim long absolute paths so a diff header reads `src/foo.ts` rather than
164
+ * `/home/rik/dev/telecoder/src/foo.ts`. Falls back to the full path if no
165
+ * prefix matches.
166
+ */
167
+ function stripWorkingDir(filePath) {
168
+ const cwd = process.cwd();
169
+ if (filePath.startsWith(cwd + '/'))
170
+ return filePath.slice(cwd.length + 1);
171
+ const home = process.env.HOME;
172
+ if (home && filePath.startsWith(home + '/'))
173
+ return '~/' + filePath.slice(home.length + 1);
174
+ return filePath;
175
+ }
176
+ /**
177
+ * Lay out the live status bubble.
178
+ *
179
+ * A running Bash command goes in a `bash` code block, the way the permission
180
+ * prompt shows one: monospace keeps a long one-liner's pipes and `$(...)`
181
+ * legible, and the block's copy button hands back the bare command.
182
+ *
183
+ * Entities rather than MarkdownV2: the command is the model's own text, and an
184
+ * underscore or backtick in it would break the parse and fail the edit.
185
+ *
186
+ * Exported for tests.
187
+ */
188
+ export function renderStatusBubble(view) {
189
+ const b = new EntityText();
190
+ const { operation } = view;
191
+ if (view.awaitingAnswer) {
192
+ // A pending ask_user question outranks the tool/thinking status: the turn
193
+ // is blocked on a button tap, and a spinner here reads as work still in
194
+ // progress, which is exactly the cue that makes a question easy to miss.
195
+ b.add(AWAITING_ANSWER_LINE);
196
+ }
197
+ else if (operation) {
198
+ b.add(renderStatusLine(view.spinnerIndex, getToolIcon(operation.name), getToolAction(operation.name), operation.detail?.trim(), view.elapsedMs, view.pausedMs) + premiumBadge(view.premiumModel));
199
+ // Bash commands render their (possibly multi-line) command in a separate
200
+ // block below the header so the timer stays on a clean single line.
201
+ if (operation.commandBlock)
202
+ b.newline().pre(operation.commandBlock, 'bash');
203
+ }
204
+ else if (view.writing) {
205
+ b.add(`${getSpinnerFrame(view.spinnerIndex)} ${STREAMING_INDICATOR}${premiumBadge(view.premiumModel)}`);
206
+ }
207
+ else {
208
+ b.add(`${getSpinnerFrame(view.spinnerIndex)} ${TOOL_ICONS.thinking} ${getThinkingVerb()}...${premiumBadge(view.premiumModel)}`);
209
+ }
210
+ // Mirror Claude Code's live spinner tip under the status line, as the TUI
211
+ // shows it. Suppressed while a question is pending — the tip is whatever was
212
+ // on screen when the model blocked, and it dilutes the one line that matters.
213
+ if (view.tip && !view.awaitingAnswer)
214
+ b.newline().add(` ⎿ 💡 ${view.tip}`);
215
+ if (view.footer)
216
+ b.newline(2).append(view.footer);
217
+ return b.build();
218
+ }
219
+ /** A message's text and formatting as one comparable string. */
220
+ function messageKey(message) {
221
+ return `${message.text}\u0000${JSON.stringify(message.entities)}`;
222
+ }
223
+ export class MessageSender {
224
+ streamStates = new Map();
225
+ // Per-stream counter of new chat messages posted during the turn (task
226
+ // list first render, monitor armed/events, sub-turn echoes, backgrounded task
227
+ // completions). Drives two behaviors when > 0:
228
+ // - finishStreaming posts the final response as a fresh bottom message
229
+ // and reduces the original "Processing..." bubble to a pointer, so the
230
+ // final answer isn't buried above the intervening messages.
231
+ // - sendCompletionNotification suppresses the generic "✅ Done" ping —
232
+ // the bottom-posted final message is itself a notification.
233
+ // Reset on startStreaming.
234
+ interveningPostsThisStream = new Map();
235
+ constructor() {
236
+ // A task-list card is posted by a timer as often as by a tool call, so it
237
+ // is counted where it is posted rather than where it was asked for.
238
+ taskListDisplay.onPost((sessionKey) => this.noteInterveningPost(sessionKey));
239
+ }
240
+ noteInterveningPost(sessionKey) {
241
+ if (!sessionKey)
242
+ return;
243
+ const prev = this.interveningPostsThisStream.get(sessionKey) ?? 0;
244
+ this.interveningPostsThisStream.set(sessionKey, prev + 1);
245
+ }
246
+ /**
247
+ * Send markdown — the model's own text, usually — as however many messages
248
+ * it takes, with an Instant View link under the last when the reply is long
249
+ * enough to be worth a page. The text always goes out in full: the page is a
250
+ * second way to read it, not a replacement for it.
251
+ *
252
+ * Returns the message_id of the last Telegram message posted, or null if
253
+ * nothing was sent (every attempt failed). Callers that want to attach the
254
+ * /fork button use this to know which message to anchor onto.
255
+ */
256
+ async sendMessage(ctx, text) {
257
+ const keyInfo = getSessionKeyFromCtx(ctx);
258
+ const parts = withTelegraphFooter(formatMarkdown(text, config.MAX_MESSAGE_LENGTH), await publishTelegraphFooter(text, keyInfo?.sessionKey));
259
+ return this.sendParts(ctx, parts);
260
+ }
261
+ /** Post `parts` in order; the id of the last one that went out. */
262
+ async sendParts(ctx, parts) {
263
+ let lastMessageId = null;
264
+ for (const part of parts) {
265
+ try {
266
+ lastMessageId = (await replyFormatted(ctx, part)).message_id;
267
+ }
268
+ catch (error) {
269
+ console.error('[Send] Failed to send part:', error instanceof Error ? error.message : error);
270
+ try {
271
+ lastMessageId = (await ctx.reply('⚠️ Message formatting error')).message_id;
272
+ }
273
+ catch { /* give up */ }
274
+ }
275
+ }
276
+ return lastMessageId;
277
+ }
278
+ /**
279
+ * Attach a "🍴 Fork" button to a past assistant message and record the
280
+ * JSONL truncation point that corresponds to it. Idempotent: calling this
281
+ * twice on the same message just re-records the offset (Telegram returns
282
+ * "message is not modified" on the second edit, which we swallow).
283
+ *
284
+ * Safe to call when there's no active claudeSessionId or JSONL yet — we
285
+ * silently skip in that case so the assistant turn isn't blocked by a
286
+ * fork-tracking edge case.
287
+ */
288
+ async attachForkButton(ctx, sessionKey, messageId, suggestion = null) {
289
+ if (!messageId)
290
+ return;
291
+ const session = sessionManager.getSession(sessionKey);
292
+ if (!session?.claudeSessionId)
293
+ return;
294
+ const jsonlPath = sessionJsonlPath(session.workingDirectory, session.claudeSessionId);
295
+ const lineCount = countJsonlLines(jsonlPath);
296
+ if (lineCount === 0)
297
+ return;
298
+ messageOffsets.record(sessionKey, messageId, {
299
+ claudeSessionId: session.claudeSessionId,
300
+ projectPath: session.workingDirectory,
301
+ lineCount,
302
+ conversationId: session.conversationId,
303
+ });
304
+ // A suggestion short enough to read on a button goes on a row above the
305
+ // fork button, so it is the primary call-to-action and fork stays as the
306
+ // secondary affordance. A longer one is not put here at all — it would
307
+ // arrive clipped — and {@link sendSuggestionCard} gives it its own
308
+ // message instead.
309
+ const rows = [];
310
+ if (suggestion?.onButton) {
311
+ rows.push([{
312
+ text: formatSuggestionLabel(suggestion.text),
313
+ callback_data: `sgt:${suggestion.id}`,
314
+ }]);
315
+ }
316
+ rows.push([{ text: '🍴 Fork', callback_data: 'fork:pick' }]);
317
+ const replyMarkup = rows.length === 1 ? FORK_KEYBOARD : { inline_keyboard: rows };
318
+ try {
319
+ await ctx.api.editMessageReplyMarkup(ctx.chat.id, messageId, { reply_markup: replyMarkup });
320
+ }
321
+ catch (err) {
322
+ // "message is not modified" or "message to edit not found" — non-fatal.
323
+ const msg = err instanceof Error ? err.message.toLowerCase() : '';
324
+ if (!msg.includes('not modified') && !msg.includes('not found') && !msg.includes('message_id_invalid')) {
325
+ console.debug('[Fork] attachForkButton edit failed:', err instanceof Error ? err.message : err);
326
+ }
327
+ }
328
+ }
329
+ /**
330
+ * Post a suggestion that is too wide for a button as its own message: the
331
+ * full prompt in the body, a fixed short label on the button below it.
332
+ *
333
+ * Sent silently — the response it follows has already raised a notification,
334
+ * and a second ping for an optional suggestion is not worth a buzz. No-ops
335
+ * for a suggestion that rode on its button, and for a turn that had none.
336
+ */
337
+ async sendSuggestionCard(ctx, suggestion) {
338
+ if (!suggestion || suggestion.onButton)
339
+ return;
340
+ const reply_markup = {
341
+ inline_keyboard: [[{ text: SUGGESTION_CARD_BUTTON, callback_data: `sgt:${suggestion.id}` }]],
342
+ };
343
+ try {
344
+ await replyFormatted(ctx, buildSuggestionCardText(suggestion.text), {
345
+ reply_markup,
346
+ disable_notification: true,
347
+ });
348
+ }
349
+ catch (err) {
350
+ // The answer itself already landed; a missing suggestion is cosmetic.
351
+ console.debug('[Suggestion] card send failed:', err instanceof Error ? err.message : err);
352
+ }
353
+ }
354
+ /**
355
+ * Send a file as a document attachment
356
+ */
357
+ async sendDocument(ctx, filePath, caption) {
358
+ try {
359
+ if (!fs.existsSync(filePath)) {
360
+ console.error('[Document] File not found:', filePath);
361
+ return false;
362
+ }
363
+ const fileName = path.basename(filePath);
364
+ const fileBuffer = fs.readFileSync(filePath);
365
+ const inputFile = new InputFile(fileBuffer, fileName);
366
+ await ctx.replyWithDocument(inputFile, { caption });
367
+ return true;
368
+ }
369
+ catch (error) {
370
+ console.error('[Document] Failed to send:', error);
371
+ return false;
372
+ }
373
+ }
374
+ /**
375
+ * Send a markdown file with Telegraph preview option
376
+ */
377
+ async sendMarkdownFile(ctx, filePath, options = {}) {
378
+ const { useTelegraph = true, sendAsDocument = false } = options;
379
+ try {
380
+ if (!fs.existsSync(filePath)) {
381
+ console.error('[Markdown] File not found:', filePath);
382
+ return false;
383
+ }
384
+ const fileName = path.basename(filePath);
385
+ const content = fs.readFileSync(filePath, 'utf-8');
386
+ // Option 1: Telegraph (Instant View)
387
+ if (useTelegraph) {
388
+ const pageUrl = await createTelegraphFromFile(filePath);
389
+ if (pageUrl) {
390
+ const message = new EntityText()
391
+ .add('📄 ').bold(fileName).newline(2)
392
+ .link('Open in Instant View', pageUrl)
393
+ .build();
394
+ await replyFormatted(ctx, message);
395
+ // Also send as document if requested
396
+ if (sendAsDocument) {
397
+ await this.sendDocument(ctx, filePath, 'Download file');
398
+ }
399
+ return true;
400
+ }
401
+ }
402
+ // Option 2: Send as document
403
+ if (sendAsDocument) {
404
+ return await this.sendDocument(ctx, filePath, `📎 ${fileName}`);
405
+ }
406
+ // Option 3: Send content inline
407
+ await this.sendMessage(ctx, content);
408
+ return true;
409
+ }
410
+ catch (error) {
411
+ console.error('[Markdown] Failed to send:', error);
412
+ return false;
413
+ }
414
+ }
415
+ async startStreaming(ctx, prompt) {
416
+ const keyInfo = getSessionKeyFromCtx(ctx);
417
+ if (!keyInfo)
418
+ return;
419
+ const { chatId, threadId, sessionKey } = keyInfo;
420
+ const terminalMode = isTerminalUIEnabled(sessionKey);
421
+ const verbosityFlags = resolveVerbosityFlags(chatId);
422
+ const actionLogEnabled = verbosityFlags.useActionLog && (verbosityFlags.showToolResults || verbosityFlags.showDiffs);
423
+ const premiumModel = getPremiumModel(sessionKey);
424
+ const initialText = `${getSpinnerFrame(0)} ${TOOL_ICONS.thinking} ${getThinkingVerb()}...${premiumBadge(premiumModel)}`;
425
+ const message = await ctx.reply(initialText);
426
+ // "typing…" only for a turn with no live status line. Terminal mode has
427
+ // one — in the bubble, then at the bottom of the action log — and Telegram
428
+ // Desktop draws the typing animation on the CPU for as long as it is up,
429
+ // which renewed every few seconds is the whole turn.
430
+ const typingInterval = terminalMode ? null : this.startTypingIndicator(ctx.api, chatId, threadId);
431
+ const now = Date.now();
432
+ const state = {
433
+ chatId,
434
+ threadId,
435
+ sessionKey,
436
+ messageId: message.message_id,
437
+ content: '',
438
+ contentChangedAt: 0,
439
+ shownContent: '',
440
+ shown: [],
441
+ overflowIds: [],
442
+ flushTimer: null,
443
+ liveEdits: new Set(),
444
+ ended: false,
445
+ streamIntervalMs: ctx.chat?.type === 'private' ? STREAM_EDIT_INTERVAL_MS : GROUP_STREAM_EDIT_INTERVAL_MS,
446
+ lastUpdate: now,
447
+ typingInterval,
448
+ // Terminal UI mode
449
+ terminalMode,
450
+ spinnerIndex: 0,
451
+ spinnerInterval: null,
452
+ currentOperation: null,
453
+ operationStartTime: now,
454
+ rateLimitedUntil: 0,
455
+ lastRateLimitDurationMs: 0,
456
+ tip: null,
457
+ actionLogEnabled,
458
+ prompt,
459
+ premiumModel,
460
+ };
461
+ // Register before anything else can throw. The typing indicator and the
462
+ // thinking bubble are already live at this point, and the only handle on
463
+ // them is `state` — if we bail out before registering, finish/cancel can't
464
+ // find the stream and the "typing…" interval ticks forever.
465
+ this.streamStates.set(sessionKey, state);
466
+ this.interveningPostsThisStream.set(sessionKey, 0);
467
+ // The task list's next change posts a fresh card, under this turn's prompt.
468
+ taskListDisplay.startTurn(sessionKey);
469
+ // Initialize action logging if enabled. Cosmetic, so a failure here
470
+ // degrades to a turn without an action log rather than no turn at all.
471
+ if (actionLogEnabled) {
472
+ try {
473
+ await actionLogger.initialize(ctx, sessionKey, this.logStatusSource(state), state.prompt);
474
+ }
475
+ catch (error) {
476
+ console.error('[ActionLog] initialize failed, continuing without it:', error);
477
+ }
478
+ }
479
+ // Periodic refresh so the elapsed timer and spinner update even during long tool runs
480
+ if (terminalMode) {
481
+ state.spinnerInterval = setInterval(() => {
482
+ state.spinnerIndex += 1;
483
+ if (ctx) {
484
+ this.flushLive(ctx, state).catch(() => { });
485
+ }
486
+ }, MIN_EDIT_INTERVAL_MS);
487
+ }
488
+ }
489
+ stopSpinnerAnimation(state) {
490
+ if (state.spinnerInterval) {
491
+ clearInterval(state.spinnerInterval);
492
+ state.spinnerInterval = null;
493
+ }
494
+ if (state.flushTimer) {
495
+ clearTimeout(state.flushTimer);
496
+ state.flushTimer = null;
497
+ }
498
+ }
499
+ startTypingIndicator(api, chatId, threadId) {
500
+ const opts = threadId !== undefined ? { message_thread_id: threadId } : {};
501
+ // Send typing immediately
502
+ api.sendChatAction(chatId, 'typing', opts).catch(() => { });
503
+ // Then send every TYPING_INTERVAL_MS
504
+ return setInterval(() => {
505
+ api.sendChatAction(chatId, 'typing', opts).catch(() => { });
506
+ }, TYPING_INTERVAL_MS);
507
+ }
508
+ stopTypingIndicator(state) {
509
+ if (state.typingInterval) {
510
+ clearInterval(state.typingInterval);
511
+ state.typingInterval = null;
512
+ }
513
+ }
514
+ stopTypingInterval(interval) {
515
+ clearInterval(interval);
516
+ }
517
+ /**
518
+ * Update the current tool operation (terminal UI mode).
519
+ * Event-driven: triggers a status message edit on each tool change.
520
+ */
521
+ updateToolOperation(sessionKey, toolName, input, ctx) {
522
+ const state = this.streamStates.get(sessionKey);
523
+ if (!state)
524
+ return;
525
+ // TaskCreate and TaskUpdate change the task list on disk; its card is
526
+ // redrawn from there once the write has landed.
527
+ if (ctx) {
528
+ taskListDisplay.noteToolStart(ctx.api, sessionKey, toolName, sessionManager.getSession(sessionKey)?.claudeSessionId);
529
+ }
530
+ if (!state.terminalMode)
531
+ return;
532
+ const { chatId } = parseSessionKey(sessionKey);
533
+ const verbose = resolveVerbosityFlags(chatId).terminalUiVerbose;
534
+ if (toolName === 'Bash') {
535
+ // Show the full command in a block beneath the header (capped per the
536
+ // verbose flag) instead of just its first line on the `→` row — a leading
537
+ // `cd` otherwise hides the slow work the timer is actually counting.
538
+ const command = typeof input?.command === 'string' ? input.command : undefined;
539
+ state.currentOperation = { name: toolName, commandBlock: formatBashCommandBlock(command, verbose) };
540
+ }
541
+ else {
542
+ const detail = input ? extractToolDetail(toolName, input, verbose) : undefined;
543
+ state.currentOperation = { name: toolName, detail };
544
+ }
545
+ state.operationStartTime = Date.now();
546
+ state.spinnerIndex += 1;
547
+ if (ctx) {
548
+ this.flushLive(ctx, state).catch(() => { });
549
+ }
550
+ }
551
+ /**
552
+ * Clear the current tool operation (terminal UI mode)
553
+ */
554
+ clearToolOperation(sessionKey) {
555
+ taskListDisplay.noteToolEnd(sessionKey);
556
+ const state = this.streamStates.get(sessionKey);
557
+ if (!state)
558
+ return;
559
+ state.currentOperation = null;
560
+ }
561
+ /**
562
+ * Apply an SDK task lifecycle event. Updates the per-session task tracker,
563
+ * posts a line when a backgrounded task starts (edited in place when it
564
+ * ends), surfaces Monitor events as their own chat messages, and refreshes
565
+ * the streaming UI footer.
566
+ */
567
+ async notifyTaskEvent(ctx, sessionKey, event) {
568
+ const wasBackgrounded = event.type === 'updated'
569
+ ? taskTracker.getTask(sessionKey, event.taskId)?.isBackgrounded
570
+ : undefined;
571
+ const state = taskTracker.handleEvent(sessionKey, event);
572
+ const isMonitor = state?.taskType === MONITOR_TASK_TYPE;
573
+ if (event.type === 'started' && state?.isBackgrounded) {
574
+ await this.postTaskStarted(ctx, state);
575
+ }
576
+ else if (event.type === 'updated' && state?.isBackgrounded && wasBackgrounded === false
577
+ && state.status === 'running') {
578
+ // A shell moved to the background partway through says so only here.
579
+ await this.postTaskStarted(ctx, state);
580
+ }
581
+ else if (event.type === 'progress' && state && isMonitor) {
582
+ const eventText = event.summary ?? event.description;
583
+ if (eventText)
584
+ await this.postMonitorEvent(ctx, state, eventText);
585
+ }
586
+ else if (event.type === 'notification' && state) {
587
+ await this.postTaskCompletion(ctx, state);
588
+ taskTracker.remove(sessionKey, event.taskId);
589
+ }
590
+ const streamState = this.streamStates.get(sessionKey);
591
+ if (streamState && streamState.terminalMode) {
592
+ streamState.spinnerIndex += 1;
593
+ this.flushLive(ctx, streamState).catch(() => { });
594
+ }
595
+ }
596
+ /**
597
+ * Say in the chat what just started in the background, rather than leave it
598
+ * to the footer's count. Silent: the user is in the chat, mid-turn. The
599
+ * line is kept by id so the completion can replace it.
600
+ */
601
+ async postTaskStarted(ctx, task) {
602
+ if (task.skipTranscript || task.armedMessageId !== undefined)
603
+ return;
604
+ const { icon, label } = taskKind(task.taskType);
605
+ const description = shortDescription(task.description);
606
+ const text = task.taskType === MONITOR_TASK_TYPE
607
+ ? `${icon} ${label} "${description}" armed`
608
+ : `${icon} ${label} "${description}" running in background`;
609
+ try {
610
+ const posted = await replyFormatted(ctx, text, { disable_notification: true });
611
+ task.armedMessageId = posted.message_id;
612
+ this.noteInterveningPost(getSessionKeyFromCtx(ctx)?.sessionKey);
613
+ }
614
+ catch (error) {
615
+ console.error('[Task] Failed to post task start:', error instanceof Error ? error.message : error);
616
+ }
617
+ }
618
+ async postMonitorEvent(ctx, task, eventText) {
619
+ if (task.skipTranscript)
620
+ return;
621
+ // Use action logging if enabled
622
+ const keyInfo = getSessionKeyFromCtx(ctx);
623
+ const sessionKey = keyInfo?.sessionKey;
624
+ if (sessionKey && actionLogger.isActive(sessionKey)) {
625
+ await actionLogger.addMonitorEvent(sessionKey, task, eventText);
626
+ return;
627
+ }
628
+ // Fall back to original behavior
629
+ const truncated = eventText.length > 1000
630
+ ? eventText.substring(0, 997) + '...'
631
+ : eventText;
632
+ try {
633
+ await replyFormatted(ctx, `📡 Monitor event: ${truncated}`);
634
+ this.noteInterveningPost(sessionKey);
635
+ }
636
+ catch (error) {
637
+ console.error('[Task] Failed to post monitor event:', error instanceof Error ? error.message : error);
638
+ }
639
+ }
640
+ /**
641
+ * Post the "🔔 Scheduled: …" header that precedes a scheduled-task fire.
642
+ * The scheduled prompt itself is then enqueued through the normal turn
643
+ * pipeline; this header just makes the unprompted message obvious so the
644
+ * user understands why a turn appeared with no input from them.
645
+ */
646
+ async postScheduledFire(ctx, label, prompt) {
647
+ const preview = prompt.length > 100 ? prompt.substring(0, 97) + '...' : prompt;
648
+ const b = new EntityText().add('🔔 ');
649
+ if (label)
650
+ b.bold('Scheduled').add(` — ${label}`);
651
+ else
652
+ b.bold('Scheduled fire');
653
+ b.newline().code(preview);
654
+ try {
655
+ await replyFormatted(ctx, b.build());
656
+ }
657
+ catch (error) {
658
+ console.error('[Schedule] Failed to post scheduled header:', error instanceof Error ? error.message : error);
659
+ }
660
+ this.noteInterveningPost(getSessionKeyFromCtx(ctx)?.sessionKey);
661
+ }
662
+ /**
663
+ * Post the model's text response from an SDK-driven sub-turn (monitor
664
+ * event echoes, post-task_notification commentary) as its own Telegram
665
+ * message, its markdown rendered as for any reply.
666
+ */
667
+ async postSubTurnResponse(ctx, text) {
668
+ const trimmed = text.trim();
669
+ if (!trimmed)
670
+ return;
671
+ await this.sendParts(ctx, formatMarkdown(trimmed, config.MAX_MESSAGE_LENGTH));
672
+ this.noteInterveningPost(getSessionKeyFromCtx(ctx)?.sessionKey);
673
+ }
674
+ /**
675
+ * If action-log mode is on for this chat AND the verbosity tier shows tool
676
+ * output, lazily initialize the logger and hand off to `forward`. Returns
677
+ * true when the action log took the message — callers fall through to the
678
+ * direct-post path when it returns false.
679
+ */
680
+ async routeToActionLog(ctx, forward) {
681
+ const chatId = ctx.chat?.id;
682
+ if (chatId === undefined)
683
+ return false;
684
+ const flags = resolveVerbosityFlags(chatId);
685
+ if (!flags.useActionLog || !(flags.showToolResults || flags.showDiffs))
686
+ return false;
687
+ const sessionKey = getSessionKeyFromCtx(ctx)?.sessionKey;
688
+ if (!sessionKey)
689
+ return false;
690
+ if (!actionLogger.isActive(sessionKey)) {
691
+ // No log for this session. Only open one if a turn is actually
692
+ // streaming — otherwise this is a straggler arriving after the turn
693
+ // ended and the log was collapsed and cleaned up (5s after finishStream),
694
+ // and initializing here would start a *second*, live-looking action log
695
+ // below the collapsed summary. Stragglers post as their own message
696
+ // instead, matching what postMonitorEvent already does.
697
+ const stream = this.streamStates.get(sessionKey);
698
+ if (!stream) {
699
+ console.debug(`[ActionLog] Straggler for ${sessionKey} after log cleanup — posting directly instead of opening a new log`);
700
+ return false;
701
+ }
702
+ await actionLogger.initialize(ctx, sessionKey, this.logStatusSource(stream), stream.prompt);
703
+ }
704
+ await forward(sessionKey);
705
+ return true;
706
+ }
707
+ /**
708
+ * Post a truncated preview of a tool's result. In action log mode, adds to
709
+ * the consolidated log; otherwise sends as its own Telegram message.
710
+ * Sent only when the chat's verbosity tier resolves `showToolResults: true`
711
+ * (caller is responsible for the gate). Plain text: tool output is shown as
712
+ * it came. The streaming bubble is pushed below via `noteInterveningPost`.
713
+ */
714
+ async postToolResult(ctx, event, maxLines, maxChars) {
715
+ if (await this.routeToActionLog(ctx, (sk) => actionLogger.addToolResult(sk, event, maxLines, maxChars))) {
716
+ return;
717
+ }
718
+ // Fall back to original behavior
719
+ const cleaned = stripAnsi(event.content).replace(/\s+$/u, '');
720
+ if (!cleaned && !event.isError)
721
+ return;
722
+ const icon = event.toolName ? getToolIcon(event.toolName) : '🔹';
723
+ const label = event.toolName ? stripMcpServerPrefix(event.toolName) : 'tool';
724
+ const verb = event.isError ? 'error' : 'result';
725
+ // Tail-biased for errors (failures land at the end), head-biased for
726
+ // success — middle elided either way (see elideToolOutput).
727
+ const body = elideToolOutput(cleaned || '(no output)', maxLines, maxChars, { isError: event.isError });
728
+ const detail = event.toolName && event.input
729
+ ? extractToolDetail(event.toolName, event.input, true)
730
+ : undefined;
731
+ const detailLine = detail
732
+ ? `${event.toolName === 'Bash' ? '$ ' : ''}${detail}\n`
733
+ : '';
734
+ const text = `${icon} ${label} ${verb}\n${detailLine}${body}`;
735
+ try {
736
+ await replyFormatted(ctx, text);
737
+ this.noteInterveningPost(getSessionKeyFromCtx(ctx)?.sessionKey);
738
+ }
739
+ catch (err) {
740
+ console.error('[ToolResult] Failed to post:', err instanceof Error ? err.message : err);
741
+ }
742
+ }
743
+ /**
744
+ * Post a before/after preview for a successful Edit or Write call. In action
745
+ * log mode, adds to the consolidated log; otherwise sends as its own message.
746
+ * Each side is independently capped at `maxLines` and prefixed with `-`/`+`.
747
+ * Write (new file) skips the `-` side. Plain text, shown as it came.
748
+ */
749
+ async postEditDiff(ctx, event, maxLines) {
750
+ if (await this.routeToActionLog(ctx, (sk) => actionLogger.addEditDiff(sk, event, maxLines))) {
751
+ return;
752
+ }
753
+ // Fall back to original behavior
754
+ const fileLabel = stripWorkingDir(event.filePath);
755
+ const headerIcon = event.toolName === 'Write' ? '✏️' : '🔧';
756
+ const lines = [`${headerIcon} ${event.toolName} ${fileLabel}`];
757
+ if (typeof event.oldString === 'string' && event.oldString.length > 0) {
758
+ const oldLines = event.oldString.split('\n');
759
+ const oldShown = oldLines.slice(0, maxLines).map((l) => `- ${l}`);
760
+ if (oldLines.length > maxLines) {
761
+ oldShown.push(`- [+${oldLines.length - maxLines} more lines]`);
762
+ }
763
+ lines.push(...oldShown);
764
+ }
765
+ const newLines = event.newString.split('\n');
766
+ const newShown = newLines.slice(0, maxLines).map((l) => `+ ${l}`);
767
+ if (newLines.length > maxLines) {
768
+ newShown.push(`+ [+${newLines.length - maxLines} more lines]`);
769
+ }
770
+ lines.push(...newShown);
771
+ const text = lines.join('\n');
772
+ try {
773
+ await replyFormatted(ctx, text);
774
+ this.noteInterveningPost(getSessionKeyFromCtx(ctx)?.sessionKey);
775
+ }
776
+ catch (err) {
777
+ console.error('[EditDiff] Failed to post:', err instanceof Error ? err.message : err);
778
+ }
779
+ }
780
+ async postTaskCompletion(ctx, task) {
781
+ // Skip ambient/housekeeping tasks and foreground subagents — only
782
+ // backgrounded tasks deserve a separate notification message.
783
+ if (task.skipTranscript)
784
+ return;
785
+ if (!task.isBackgrounded)
786
+ return;
787
+ // Without a start line to replace, an action log takes the completion.
788
+ // With one, the start line is where it goes, so it can't sit on
789
+ // "running" after the task ended.
790
+ const keyInfo = getSessionKeyFromCtx(ctx);
791
+ const sessionKey = keyInfo?.sessionKey;
792
+ if (task.armedMessageId === undefined && sessionKey && actionLogger.isActive(sessionKey)) {
793
+ await actionLogger.addTaskCompletion(sessionKey, task);
794
+ return;
795
+ }
796
+ const isMonitor = task.taskType === MONITOR_TASK_TYPE;
797
+ const { label } = taskKind(task.taskType);
798
+ const statusIcon = task.status === 'completed'
799
+ ? (isMonitor ? '📡' : '✅')
800
+ : task.status === 'stopped' ? '🛑' : '❌';
801
+ const verb = task.status === 'completed'
802
+ ? (isMonitor ? 'stream ended' : 'completed')
803
+ : task.status === 'stopped' ? 'stopped' : 'failed';
804
+ const elapsedMs = (task.endedAt ?? Date.now()) - task.startedAt;
805
+ const seconds = Math.round(elapsedMs / 1000);
806
+ const duration = seconds >= 60
807
+ ? `${Math.floor(seconds / 60)}m ${seconds % 60}s`
808
+ : `${seconds}s`;
809
+ const description = shortDescription(task.description);
810
+ // Single-line format matching Claude Code's TUI:
811
+ // ✅ Subagent "<description>" completed in 54s
812
+ // 📡 Monitor "<description>" stream ended after 12s
813
+ const body = isMonitor
814
+ ? `${statusIcon} Monitor "${description}" ${verb} after ${duration}`
815
+ : `${statusIcon} ${label} "${description}" ${verb} in ${duration}`;
816
+ const text = task.error ? `${body}\n⚠️ ${task.error}` : body;
817
+ // If we still know the armed-message id, edit it in place so the chat
818
+ // doesn't keep showing a stale "armed" line. Only post a fresh message
819
+ // (which triggers a Telegram notification and lands at the bottom of the
820
+ // chat) when the task ran long enough that the user likely walked away —
821
+ // matching sendCompletionNotification's threshold — or when there's an
822
+ // error the user needs to see.
823
+ const chatId = ctx.chat?.id;
824
+ const longRunning = elapsedMs >= config.NOTIFICATION_THRESHOLD_SECONDS * 1000;
825
+ const shouldEdit = task.armedMessageId !== undefined && chatId !== undefined;
826
+ const shouldPostFresh = !shouldEdit || longRunning || !!task.error;
827
+ if (shouldEdit) {
828
+ try {
829
+ await editFormatted(ctx.api, chatId, task.armedMessageId, text);
830
+ }
831
+ catch (error) {
832
+ const msg = error instanceof Error ? error.message : String(error);
833
+ // "message is not modified" is benign; anything else still leaves the
834
+ // fresh post below to tell the user, when posting is called for.
835
+ if (!/not modified/i.test(msg))
836
+ console.error('[Task] Failed to edit armed message:', msg);
837
+ }
838
+ }
839
+ if (!shouldPostFresh)
840
+ return;
841
+ try {
842
+ await replyFormatted(ctx, text);
843
+ this.noteInterveningPost(getSessionKeyFromCtx(ctx)?.sessionKey);
844
+ }
845
+ catch (error) {
846
+ console.error('[Task] Failed to post completion message:', error instanceof Error ? error.message : error);
847
+ }
848
+ }
849
+ /** What the status line shows right now. */
850
+ statusView(state) {
851
+ return {
852
+ awaitingAnswer: hasPendingQuestionForSession(state.sessionKey),
853
+ operation: state.currentOperation,
854
+ spinnerIndex: state.spinnerIndex,
855
+ elapsedMs: Date.now() - state.operationStartTime,
856
+ pausedMs: state.lastRateLimitDurationMs > 0 ? state.lastRateLimitDurationMs : undefined,
857
+ tip: state.tip,
858
+ footer: renderBackgroundFooter(taskTracker.getBackgroundedTasks(state.sessionKey)),
859
+ writing: Date.now() - state.contentChangedAt < WRITING_WINDOW_MS,
860
+ premiumModel: state.premiumModel,
861
+ };
862
+ }
863
+ /**
864
+ * The status line as the action log draws it at its bottom, or undefined for
865
+ * a turn without one (terminal UI off).
866
+ *
867
+ * It shares a message with up to ten actions, so a long command is clipped
868
+ * as compact mode clips it — verbose mode allows 3,500 characters — and a
869
+ * long detail is cut short. The bubble's rate-limit note is left off: it is
870
+ * about the bubble's own edits, which have stopped.
871
+ */
872
+ logStatusSource(state) {
873
+ if (!state.terminalMode)
874
+ return undefined;
875
+ return () => {
876
+ const view = this.statusView(state);
877
+ const operation = view.operation && {
878
+ ...view.operation,
879
+ detail: view.operation.detail && clip(view.operation.detail, LOG_STATUS_DETAIL_CHARS),
880
+ commandBlock: formatBashCommandBlock(view.operation.commandBlock, false),
881
+ };
882
+ return renderStatusBubble({ ...view, operation, pausedMs: undefined });
883
+ };
884
+ }
885
+ /**
886
+ * The line under the live reply that says it isn't final: the status line
887
+ * with the terminal UI on, a pointer down to the action log once that
888
+ * carries the status line, or a plain "Writing" otherwise.
889
+ */
890
+ liveFooter(state) {
891
+ if (state.terminalMode) {
892
+ if (actionLogger.showsStatus(state.sessionKey))
893
+ return plain(LOG_POINTER_LINE);
894
+ return renderStatusBubble(this.statusView(state));
895
+ }
896
+ if (hasPendingQuestionForSession(state.sessionKey))
897
+ return plain(AWAITING_ANSWER_LINE);
898
+ if (!state.content.trim()) {
899
+ return plain(`${getSpinnerFrame(state.spinnerIndex)} ${TOOL_ICONS.thinking} ${getThinkingVerb()}...${premiumBadge(state.premiumModel)}`);
900
+ }
901
+ return new EntityText().italic(STREAMING_INDICATOR).add(premiumBadge(state.premiumModel)).build();
902
+ }
903
+ /**
904
+ * The live messages: the reply so far, split where it outgrows one message,
905
+ * with `footer` under the last. The bubble shows the first; the rest
906
+ * overflow into messages of their own below it.
907
+ */
908
+ liveMessages(state, footer) {
909
+ const prose = stripReasoningSummary(state.content).trim();
910
+ if (!prose)
911
+ return [footer];
912
+ const room = MAX_MESSAGE_LENGTH - footer.text.length - 2;
913
+ const parts = splitEntityMessage(markdownToEntities(prose), room, { markers: false });
914
+ if (parts.length === 0)
915
+ return [footer];
916
+ const last = parts.length - 1;
917
+ return parts.map((part, i) => (i === last ? new EntityText().append(part).newline(2).append(footer).build() : part));
918
+ }
919
+ /**
920
+ * Bring the live messages up to date: the bubble, and any it overflowed
921
+ * into. An edit that only moves the status line waits
922
+ * {@link MIN_EDIT_INTERVAL_MS} since the last; one that shows more of the
923
+ * reply waits the much shorter stream interval, and is scheduled for when
924
+ * that has passed rather than dropped. `immediate` skips the wait, for a
925
+ * change the user has to see now.
926
+ */
927
+ async flushLive(ctx, state, immediate = false) {
928
+ // Verify state is still active
929
+ const currentState = this.streamStates.get(state.sessionKey);
930
+ if (!currentState || currentState !== state || state.ended || !state.messageId)
931
+ return;
932
+ // Once the action log is in the chat it carries the status line, which it
933
+ // redraws on its own throttle. The bubble's footer just points down at it.
934
+ if (state.terminalMode && actionLogger.showsStatus(state.sessionKey)) {
935
+ await actionLogger.refreshStatus(state.sessionKey, immediate);
936
+ // The turn may have ended while the log was drawn.
937
+ if (state.ended)
938
+ return;
939
+ }
940
+ const now = Date.now();
941
+ const newText = state.content !== state.shownContent;
942
+ const interval = newText ? state.streamIntervalMs : MIN_EDIT_INTERVAL_MS;
943
+ const wait = Math.max(state.rateLimitedUntil - now, immediate ? 0 : state.lastUpdate + interval - now);
944
+ if (wait > 0) {
945
+ // New text is worth coming back for; a status-only change is picked up
946
+ // by the next spinner tick.
947
+ if (newText)
948
+ this.scheduleFlush(ctx, state, wait);
949
+ return;
950
+ }
951
+ const content = state.content;
952
+ state.lastUpdate = now;
953
+ const edit = this.showLive(ctx, state, this.liveMessages(state, this.liveFooter(state)));
954
+ state.liveEdits.add(edit);
955
+ const shown = await edit.finally(() => state.liveEdits.delete(edit));
956
+ if (state.ended)
957
+ return;
958
+ if (shown) {
959
+ state.shownContent = content;
960
+ // Successful edit — clear any rate-limit annotation after it's been shown once
961
+ state.lastRateLimitDurationMs = 0;
962
+ }
963
+ else if (newText && state.rateLimitedUntil > Date.now()) {
964
+ // The reply may have stopped growing, so nothing else would bring the
965
+ // text that was refused back once the backoff is over.
966
+ this.scheduleFlush(ctx, state, state.rateLimitedUntil - Date.now());
967
+ }
968
+ }
969
+ scheduleFlush(ctx, state, wait) {
970
+ if (state.flushTimer)
971
+ return;
972
+ state.flushTimer = setTimeout(() => {
973
+ state.flushTimer = null;
974
+ this.flushLive(ctx, state).catch(() => { });
975
+ }, wait);
976
+ }
977
+ /**
978
+ * Edit the bubble and its overflow messages to `messages`, posting overflow
979
+ * messages that don't exist yet and deleting ones no longer needed. False if
980
+ * Telegram rate-limited us; the throttle is widened and a retry scheduled
981
+ * by the caller's next refresh.
982
+ */
983
+ async showLive(ctx, state, messages) {
984
+ try {
985
+ for (let i = 0; i < messages.length; i++) {
986
+ const key = messageKey(messages[i]);
987
+ if (state.shown[i] === key)
988
+ continue;
989
+ const id = i === 0 ? state.messageId : state.overflowIds[i - 1];
990
+ if (id) {
991
+ await this.editLive(ctx, state.chatId, id, messages[i]);
992
+ }
993
+ else {
994
+ // Silent: the bubble above already raised the turn's notification,
995
+ // and the final reply raises its own.
996
+ const sent = await replyFormatted(ctx, messages[i], { disable_notification: true });
997
+ state.overflowIds[i - 1] = sent.message_id;
998
+ }
999
+ state.shown[i] = key;
1000
+ }
1001
+ await this.dropOverflow(ctx, state, messages.length - 1);
1002
+ return true;
1003
+ }
1004
+ catch (error) {
1005
+ if (error instanceof GrammyError && error.error_code === 429) {
1006
+ const retryAfter = error.parameters.retry_after ?? 60;
1007
+ state.rateLimitedUntil = Date.now() + retryAfter * 1000;
1008
+ state.lastRateLimitDurationMs = retryAfter * 1000;
1009
+ state.streamIntervalMs = Math.min(state.streamIntervalMs * 2, MAX_STREAM_EDIT_INTERVAL_MS);
1010
+ console.warn(`[Stream] Rate limited, backing off for ${retryAfter}s (session:${state.sessionKey})`);
1011
+ return false;
1012
+ }
1013
+ // The bubble was deleted, or the turn ended under us: cosmetic either way.
1014
+ const msg = error instanceof Error ? error.message.toLowerCase() : '';
1015
+ if (!msg.includes('message to edit not found') && !msg.includes('message_id_invalid')) {
1016
+ console.error('[Stream] Error updating live message:', error);
1017
+ }
1018
+ return false;
1019
+ }
1020
+ }
1021
+ /**
1022
+ * Stop live edits and wait out the ones already sent, so the turn's last
1023
+ * edit is the one the bubble keeps. Edits land in the order Telegram gets
1024
+ * them, and an edit autoRetry is holding after a 429 gets there late.
1025
+ */
1026
+ async endLiveEdits(state) {
1027
+ state.ended = true;
1028
+ await Promise.allSettled([...state.liveEdits]);
1029
+ }
1030
+ /** Edit one message, treating "message is not modified" as done. */
1031
+ async editLive(ctx, chatId, messageId, message) {
1032
+ try {
1033
+ await editFormatted(ctx.api, chatId, messageId, message);
1034
+ }
1035
+ catch (error) {
1036
+ if (error instanceof Error && error.message.includes('message is not modified'))
1037
+ return;
1038
+ throw error;
1039
+ }
1040
+ }
1041
+ /** Delete the overflow messages past the first `keep`. */
1042
+ async dropOverflow(ctx, state, keep) {
1043
+ while (state.overflowIds.length > keep) {
1044
+ const id = state.overflowIds.pop();
1045
+ state.shown.length = Math.min(state.shown.length, state.overflowIds.length + 1);
1046
+ try {
1047
+ await ctx.api.deleteMessage(state.chatId, id);
1048
+ }
1049
+ catch { /* already gone */ }
1050
+ }
1051
+ }
1052
+ /**
1053
+ * The reply so far — the whole of it, every text block of the turn in
1054
+ * markdown — shown live in the bubble above the status line, and updated as
1055
+ * it grows until {@link finishStreaming} puts the final text in its place.
1056
+ */
1057
+ updateStream(ctx, content) {
1058
+ const keyInfo = getSessionKeyFromCtx(ctx);
1059
+ if (!keyInfo)
1060
+ return;
1061
+ const state = this.streamStates.get(keyInfo.sessionKey);
1062
+ if (!state || !state.messageId || content === state.content)
1063
+ return;
1064
+ state.content = content;
1065
+ state.contentChangedAt = Date.now();
1066
+ this.flushLive(ctx, state).catch(() => { });
1067
+ }
1068
+ /**
1069
+ * Mirror Claude Code's live spinner tip (PTY mode) under the status line.
1070
+ * Pass null to clear it. Attempts an immediate flush so the tip appears
1071
+ * promptly; the flush respects the normal edit throttle, and the periodic
1072
+ * spinner refresh picks it up otherwise.
1073
+ */
1074
+ updateTip(ctx, tip) {
1075
+ const keyInfo = getSessionKeyFromCtx(ctx);
1076
+ if (!keyInfo)
1077
+ return;
1078
+ const state = this.streamStates.get(keyInfo.sessionKey);
1079
+ if (!state || !state.messageId || !state.terminalMode)
1080
+ return;
1081
+ if (state.tip === tip)
1082
+ return;
1083
+ state.tip = tip;
1084
+ this.flushLive(ctx, state).catch(() => { });
1085
+ }
1086
+ /**
1087
+ * An ask_user question has just been posted to the chat.
1088
+ *
1089
+ * Counts it as an intervening post so finishStreaming publishes the final
1090
+ * answer as a fresh message at the bottom. Without this the counter stays at
1091
+ * 0 and the answer is edited into the status bubble — which sits *above* the
1092
+ * question — and a Telegram edit neither notifies nor re-orders, so the
1093
+ * question remains the last thing in the chat while the answer lands
1094
+ * silently upstream where it is easy to never see.
1095
+ *
1096
+ * Also repoints the status bubble at the user; see {@link AWAITING_ANSWER_LINE}.
1097
+ */
1098
+ async noteQuestionPosted(ctx, sessionKey) {
1099
+ this.noteInterveningPost(sessionKey);
1100
+ await this.refreshQuestionStatus(sessionKey, ctx);
1101
+ }
1102
+ /**
1103
+ * Counterpart to {@link noteQuestionPosted}, called once the question is
1104
+ * resolved — by a tap or by timing out — so the bubble drops the waiting
1105
+ * notice and goes back to reporting progress.
1106
+ *
1107
+ * What the turn does next goes in a new action log, under the question and
1108
+ * the answer: see {@link ActionLogger.startNewMessage}.
1109
+ */
1110
+ async noteQuestionAnswered(ctx, sessionKey) {
1111
+ actionLogger.startNewMessage(sessionKey);
1112
+ await this.refreshQuestionStatus(sessionKey, ctx);
1113
+ }
1114
+ /**
1115
+ * Re-render the bubble to match the session's current pending-question
1116
+ * state. Reads the registry rather than tracking a flag of its own, so the
1117
+ * bubble cannot disagree with it — overlapping asks and timeouts both land
1118
+ * on the right text without extra bookkeeping.
1119
+ */
1120
+ async refreshQuestionStatus(sessionKey, ctx) {
1121
+ const state = this.streamStates.get(sessionKey);
1122
+ if (!state || !state.messageId)
1123
+ return;
1124
+ // Bypass the edit throttle: the point of the notice is that it lands
1125
+ // now, not up to MIN_EDIT_INTERVAL_MS later on the next spinner tick.
1126
+ await this.flushLive(ctx, state, true).catch(() => { });
1127
+ }
1128
+ async finishStreaming(ctx, finalContent, options = {}) {
1129
+ const keyInfo = getSessionKeyFromCtx(ctx);
1130
+ if (!keyInfo)
1131
+ return;
1132
+ const { chatId, sessionKey } = keyInfo;
1133
+ const state = this.streamStates.get(sessionKey);
1134
+ if (!state)
1135
+ return;
1136
+ // Stop typing indicator, spinner and any held-back refresh
1137
+ this.stopTypingIndicator(state);
1138
+ this.stopSpinnerAnimation(state);
1139
+ state.currentOperation = null;
1140
+ await this.endLiveEdits(state);
1141
+ // Track the last Telegram message we posted in this turn so the /fork
1142
+ // button can be anchored to the final user-visible message (so a tap
1143
+ // forks AT that point, not at some earlier chunk).
1144
+ let lastMessageId = state.messageId;
1145
+ // Registered once, past the early returns above: an entry planned for a
1146
+ // turn that never renders would sit in the store until its TTL with no
1147
+ // button pointing at it.
1148
+ const suggestion = planSuggestion(sessionKey, options.nextPromptSuggestion);
1149
+ // A card posted at the very end of the turn still counts as an intervening post.
1150
+ await taskListDisplay.flush(sessionKey);
1151
+ if (state.messageId) {
1152
+ const hasInterveningPosts = (this.interveningPostsThisStream.get(sessionKey) ?? 0) > 0;
1153
+ const actionLogWasActive = actionLogger.isActive(sessionKey);
1154
+ // If the action log was used OR other messages interrupted the flow,
1155
+ // post the final answer as a new message for better visibility.
1156
+ if (hasInterveningPosts || actionLogWasActive) {
1157
+ const trimmedFinal = finalContent.trim();
1158
+ await this.dropOverflow(ctx, state, 0);
1159
+ try {
1160
+ await editFormatted(ctx.api, chatId, state.messageId, trimmedFinal ? '✅ Done — full response below ↓' : '✅ Done');
1161
+ }
1162
+ catch (err) {
1163
+ console.debug('[Stream] Pointer edit failed:', err instanceof Error ? err.message : err);
1164
+ }
1165
+ if (trimmedFinal) {
1166
+ const sentId = await this.sendMessage(ctx, finalContent);
1167
+ if (sentId)
1168
+ lastMessageId = sentId;
1169
+ }
1170
+ }
1171
+ else {
1172
+ // No intervening posts: the live messages become the answer, edited in place.
1173
+ let parts = withTelegraphFooter(formatMarkdown(finalContent, config.MAX_MESSAGE_LENGTH), await publishTelegraphFooter(finalContent, sessionKey));
1174
+ if (parts.length === 0)
1175
+ parts = [plain('Done.')];
1176
+ try {
1177
+ const ids = [state.messageId, ...state.overflowIds];
1178
+ for (let i = 0; i < parts.length; i++) {
1179
+ if (i < ids.length) {
1180
+ await this.editLive(ctx, chatId, ids[i], parts[i]);
1181
+ lastMessageId = ids[i];
1182
+ }
1183
+ else {
1184
+ lastMessageId = (await replyFormatted(ctx, parts[i])).message_id;
1185
+ }
1186
+ }
1187
+ await this.dropOverflow(ctx, state, parts.length - 1);
1188
+ }
1189
+ catch (error) {
1190
+ console.error('[Stream] Final edit failed, sending the answer fresh:', error);
1191
+ await this.dropOverflow(ctx, state, 0);
1192
+ try {
1193
+ await ctx.api.deleteMessage(chatId, state.messageId);
1194
+ }
1195
+ catch { /* ignore */ }
1196
+ lastMessageId = await this.sendMessage(ctx, finalContent);
1197
+ }
1198
+ }
1199
+ }
1200
+ await this.attachForkButton(ctx, sessionKey, lastMessageId, suggestion);
1201
+ await this.sendSuggestionCard(ctx, suggestion);
1202
+ this.streamStates.delete(sessionKey);
1203
+ // Collapse the live log into a Telegraph link once any remaining tool
1204
+ // results have landed.
1205
+ actionLogger.endTurn(sessionKey);
1206
+ }
1207
+ /**
1208
+ * Put a cancel/error banner where the status line was, under whatever of the
1209
+ * reply had been written, and tear down the per-turn streaming state.
1210
+ * `reason` is either an explicit banner string or the Error that ended the
1211
+ * turn; an Error whose `name` is `ClaudeApiError` gets a distinct banner so
1212
+ * users can tell a Claude Code API failure apart from a /stop they initiated
1213
+ * themselves.
1214
+ */
1215
+ async cancelStreaming(ctx, reason = '⚠️ Request cancelled') {
1216
+ const banner = typeof reason === 'string'
1217
+ ? reason
1218
+ : isClaudeAuthError(reason?.message) || reason?.name === 'ClaudeNotLoggedInError'
1219
+ ? "🔑 Claude Code isn't logged in — turn aborted"
1220
+ : (reason?.name === 'ClaudeApiError' ? '⚠️ Claude API error — turn aborted' : '⚠️ Request cancelled');
1221
+ const keyInfo = getSessionKeyFromCtx(ctx);
1222
+ if (!keyInfo)
1223
+ return;
1224
+ const { sessionKey } = keyInfo;
1225
+ const state = this.streamStates.get(sessionKey);
1226
+ if (state) {
1227
+ // Stop typing indicator and spinner
1228
+ this.stopTypingIndicator(state);
1229
+ this.stopSpinnerAnimation(state);
1230
+ await this.endLiveEdits(state);
1231
+ if (state.messageId) {
1232
+ // Shown in full, unthrottled: this is the last edit the turn makes.
1233
+ state.shown = [];
1234
+ await this.showLive(ctx, state, this.liveMessages(state, plain(banner)));
1235
+ }
1236
+ }
1237
+ this.streamStates.delete(sessionKey);
1238
+ // Collapse the live log into a Telegraph link once any remaining tool
1239
+ // results have landed.
1240
+ actionLogger.endTurn(sessionKey);
1241
+ }
1242
+ /**
1243
+ * Send a brief new message to trigger a push notification after a long task.
1244
+ * Telegram only notifies on new messages, not edits — so streaming mode
1245
+ * needs this to alert the user when a long task finishes.
1246
+ *
1247
+ * Suppressed when at least one backgrounded-task completion message was
1248
+ * already posted during this stream — that message is itself a new chat
1249
+ * message, which triggers a notification on its own.
1250
+ */
1251
+ async sendCompletionNotification(ctx, elapsedMs) {
1252
+ if (!config.NOTIFICATION_ENABLED)
1253
+ return;
1254
+ if (elapsedMs < config.NOTIFICATION_THRESHOLD_SECONDS * 1000)
1255
+ return;
1256
+ const chatId = ctx.chat?.id;
1257
+ if (chatId !== undefined && !resolveVerbosityFlags(chatId).sendCompletionPing)
1258
+ return;
1259
+ const sessionKey = getSessionKeyFromCtx(ctx)?.sessionKey;
1260
+ if (sessionKey) {
1261
+ const intervening = this.interveningPostsThisStream.get(sessionKey) ?? 0;
1262
+ if (intervening > 0)
1263
+ return;
1264
+ }
1265
+ try {
1266
+ const seconds = Math.round(elapsedMs / 1000);
1267
+ const duration = seconds >= 60
1268
+ ? `${Math.floor(seconds / 60)}m ${seconds % 60}s`
1269
+ : `${seconds}s`;
1270
+ await ctx.reply(`✅ Done (${duration})`);
1271
+ }
1272
+ catch (error) {
1273
+ console.error('[Notification] Failed to send completion notification:', error);
1274
+ }
1275
+ }
1276
+ // Send typing indicator for a specific chat (useful for long operations)
1277
+ async sendTyping(ctx) {
1278
+ try {
1279
+ await ctx.api.sendChatAction(ctx.chat.id, 'typing');
1280
+ }
1281
+ catch (error) {
1282
+ console.error('Error sending typing:', error);
1283
+ }
1284
+ }
1285
+ }
1286
+ export const messageSender = new MessageSender();
1287
+ //# sourceMappingURL=message-sender.js.map