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