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,522 @@
1
+ /**
2
+ * ActionLogger consolidates verbose mode action messages into a single editable
3
+ * message instead of posting many separate messages. This provides a more
4
+ * UI-like experience where actions are accumulated and displayed together.
5
+ *
6
+ * While its turn runs, the log also carries the turn's live status line at its
7
+ * bottom, under that the prompt the turn is running, and last the time it was
8
+ * drawn. The log is posted below the prompt and the status bubble, and is
9
+ * usually tall enough to push both off screen, so the bottom of the log is
10
+ * where the user is looking.
11
+ *
12
+ * It is usually taller than a screen itself, so the time it was drawn, and how
13
+ * much of the log is showing, stand at its top as well as its bottom: whichever
14
+ * end is on screen says whether the log is still moving.
15
+ *
16
+ * Times go out as `date_time` entities, so they read in the user's own
17
+ * timezone rather than the server's.
18
+ */
19
+ import { GrammyError } from 'grammy';
20
+ import { EntityText } from './entities.js';
21
+ import { promptLabel, cutLabel } from './prompt-label.js';
22
+ import { getToolIcon, extractToolDetail, elideToolOutput, stripAnsi } from './terminal-renderer.js';
23
+ import { getSessionKeyFromCtx } from '../utils/session-key.js';
24
+ // Constants
25
+ const MIN_EDIT_INTERVAL_MS = 10000; // Minimum time between message edits (~5 edits/min safe zone)
26
+ // Telegram's cap on a message's text.
27
+ const MAX_MESSAGE_CHARS = 4096;
28
+ // The most actions the live log shows at once.
29
+ const LIVE_LOG_ENTRIES = 10;
30
+ // How much of an action's command and output the live log shows.
31
+ const LIVE_ENTRY_CHARS = 200;
32
+ // How long the turn's prompt can be before the live log shows only its start
33
+ // and its end: as long as the status line shows each of its prompts.
34
+ const LIVE_PROMPT_CHARS = 300;
35
+ // How long a log stays open once its turn has ended, so tool results still in
36
+ // flight land in it before it collapses.
37
+ const COLLAPSE_DELAY_MS = 5000;
38
+ // How long a log opened after an answer waits before it posts, so the bot's
39
+ // "✅ You picked" message lands above it rather than under it.
40
+ const ANSWER_SETTLE_MS = 1500;
41
+ // `mcp__telecoder-tools__telecoder_send_file` → `telecoder_send_file`
42
+ function stripMcpServerPrefix(toolName) {
43
+ if (!toolName.startsWith('mcp__'))
44
+ return toolName;
45
+ const lastSep = toolName.lastIndexOf('__');
46
+ return lastSep > 0 ? toolName.slice(lastSep + 2) : toolName;
47
+ }
48
+ function cutForLiveLog(text) {
49
+ return text.length > LIVE_ENTRY_CHARS ? text.substring(0, LIVE_ENTRY_CHARS - 3) + '...' : text;
50
+ }
51
+ /**
52
+ * A time as the server's clock reads it, for the clients that can't show a
53
+ * `date_time` entity. The rest show it in the reader's timezone instead.
54
+ */
55
+ function serverClockTime(ms) {
56
+ return new Date(ms).toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' });
57
+ }
58
+ /**
59
+ * The turn's prompt as the live log shows it. promptLabel leaves a slash
60
+ * command out, not being a turn of the conversation, but here a skill like
61
+ * /code-review is what the turn is running, so it shows as typed.
62
+ */
63
+ function liveLogPrompt(prompt) {
64
+ const label = promptLabel(prompt) ?? prompt.replace(/\s+/g, ' ').trim();
65
+ return label ? cutLabel(label, LIVE_PROMPT_CHARS) : undefined;
66
+ }
67
+ /**
68
+ * Manages consolidated action logging for verbose mode. Instead of sending
69
+ * multiple separate messages for tool results, diffs, etc., maintains a single
70
+ * message that gets edited with accumulated actions.
71
+ */
72
+ export class ActionLogger {
73
+ logStates = new Map();
74
+ /**
75
+ * Initialize action logging for a session. Creates the state but doesn't send a message yet.
76
+ * `statusSource` is the turn's live status line, drawn at the bottom of the log while the turn runs,
77
+ * and `prompt` what the turn was sent, drawn under it.
78
+ */
79
+ async initialize(ctx, sessionKey, statusSource, prompt) {
80
+ const chatId = ctx.chat?.id;
81
+ if (chatId === undefined)
82
+ return;
83
+ // Resolve the thread the same way the streaming bubble does. A turn can
84
+ // start from a callback query (a tapped suggestion button), where
85
+ // `ctx.message` is undefined and the originating message hangs off
86
+ // `ctx.callbackQuery` instead — reading `ctx.message` directly threw and
87
+ // took the whole turn down with it.
88
+ const threadId = getSessionKeyFromCtx(ctx)?.threadId;
89
+ // Just create the state, don't send a message yet
90
+ this.logStates.set(sessionKey, {
91
+ sessionKey,
92
+ api: ctx.api,
93
+ chatId,
94
+ threadId,
95
+ messageId: null, // Will be created when first action is added
96
+ entries: [],
97
+ lastUpdate: Date.now(),
98
+ rateLimitedUntil: 0,
99
+ notBefore: 0,
100
+ statusSource,
101
+ prompt: prompt === undefined ? undefined : liveLogPrompt(prompt),
102
+ ended: false,
103
+ finalized: false,
104
+ dirty: false,
105
+ drawTimer: null,
106
+ inFlight: false,
107
+ lastDrawn: '',
108
+ });
109
+ }
110
+ /**
111
+ * Add a tool result to the action log
112
+ */
113
+ async addToolResult(sessionKey, event, maxLines, maxChars) {
114
+ const state = this.logStates.get(sessionKey);
115
+ if (!state)
116
+ return;
117
+ const cleaned = stripAnsi(event.content).replace(/\s+$/u, '');
118
+ if (!cleaned && !event.isError)
119
+ return;
120
+ const icon = event.toolName ? getToolIcon(event.toolName) : '🔹';
121
+ const label = event.toolName ? stripMcpServerPrefix(event.toolName) : 'tool';
122
+ const status = event.isError ? 'error' : 'completed';
123
+ // Tail-biased for errors (failures land at the end), head-biased for
124
+ // success — middle elided either way (see elideToolOutput).
125
+ const content = elideToolOutput(cleaned || '(no output)', maxLines, maxChars, { isError: event.isError });
126
+ const detail = event.toolName && event.input
127
+ ? extractToolDetail(event.toolName, event.input, true)
128
+ : undefined;
129
+ const subtitle = detail
130
+ ? `${event.toolName === 'Bash' ? '$ ' : ''}${detail}`
131
+ : undefined;
132
+ const entry = {
133
+ id: `tool-${Date.now()}-${Math.random()}`,
134
+ timestamp: Date.now(),
135
+ type: 'tool_result',
136
+ icon,
137
+ title: `${label} ${event.isError ? 'error' : 'result'}`,
138
+ subtitle,
139
+ content,
140
+ status
141
+ };
142
+ state.entries.push(entry);
143
+ await this.requestDraw(state);
144
+ }
145
+ /**
146
+ * Add an edit diff to the action log
147
+ */
148
+ async addEditDiff(sessionKey, event, maxLines) {
149
+ const state = this.logStates.get(sessionKey);
150
+ if (!state)
151
+ return;
152
+ const fileLabel = this.stripWorkingDir(event.filePath);
153
+ const headerIcon = event.toolName === 'Write' ? '✏️' : '🔧';
154
+ const lines = [];
155
+ // Add old content (if any)
156
+ if (typeof event.oldString === 'string' && event.oldString.length > 0) {
157
+ const oldLines = event.oldString.split('\n');
158
+ const oldShown = oldLines.slice(0, maxLines).map((l) => `- ${l}`);
159
+ if (oldLines.length > maxLines) {
160
+ oldShown.push(`- [+${oldLines.length - maxLines} more lines]`);
161
+ }
162
+ lines.push(...oldShown);
163
+ }
164
+ // Add new content
165
+ const newLines = event.newString.split('\n');
166
+ const newShown = newLines.slice(0, maxLines).map((l) => `+ ${l}`);
167
+ if (newLines.length > maxLines) {
168
+ newShown.push(`+ [+${newLines.length - maxLines} more lines]`);
169
+ }
170
+ lines.push(...newShown);
171
+ const entry = {
172
+ id: `edit-${Date.now()}-${Math.random()}`,
173
+ timestamp: Date.now(),
174
+ type: 'edit_diff',
175
+ icon: headerIcon,
176
+ title: `${event.toolName} ${fileLabel}`,
177
+ content: lines.join('\n'),
178
+ status: 'completed'
179
+ };
180
+ state.entries.push(entry);
181
+ await this.requestDraw(state);
182
+ }
183
+ /**
184
+ * Whether the turn's status line is showing at the bottom of the log: from
185
+ * the log's first post until its turn ends. MessageSender stops updating the
186
+ * status bubble meanwhile and points it at the log instead.
187
+ */
188
+ showsStatus(sessionKey) {
189
+ const state = this.logStates.get(sessionKey);
190
+ return state !== undefined && this.isShowingStatus(state);
191
+ }
192
+ /**
193
+ * Redraw the log for a new status line. Waits behind the edit throttle like
194
+ * any other change, unless `immediate` — a question waiting on the user
195
+ * shouldn't go unannounced until the next slot.
196
+ */
197
+ async refreshStatus(sessionKey, immediate = false) {
198
+ const state = this.logStates.get(sessionKey);
199
+ if (!state || !this.isShowingStatus(state))
200
+ return;
201
+ await this.requestDraw(state, immediate);
202
+ }
203
+ isShowingStatus(state) {
204
+ return state.statusSource !== undefined && state.messageId !== null && !state.ended;
205
+ }
206
+ /**
207
+ * Draw the log now if the edit throttle allows, or as soon as it does.
208
+ *
209
+ * The first draw posts the message straight away; the edits after it are at
210
+ * least MIN_EDIT_INTERVAL_MS apart, and `immediate` skips that wait. A change
211
+ * that comes too soon waits for its slot instead of being dropped. Dropped,
212
+ * the newest actions stayed off the log until another one came in, which
213
+ * during a long build after a burst of quick reads was minutes.
214
+ */
215
+ async requestDraw(state, immediate = false) {
216
+ if (state.finalized)
217
+ return;
218
+ state.dirty = true;
219
+ // The draw in flight goes again when it lands, and picks this change up.
220
+ if (state.inFlight)
221
+ return;
222
+ const now = Date.now();
223
+ const due = Math.max(state.messageId === null || immediate ? now : state.lastUpdate + MIN_EDIT_INTERVAL_MS,
224
+ // Respect Telegram's retry_after backoff on 429
225
+ state.rateLimitedUntil, state.notBefore);
226
+ if (due <= now) {
227
+ this.cancelDraw(state);
228
+ await this.draw(state);
229
+ }
230
+ else if (!state.drawTimer) {
231
+ state.drawTimer = setTimeout(() => {
232
+ state.drawTimer = null;
233
+ void this.requestDraw(state);
234
+ }, due - now);
235
+ // Never hold the process open for a cosmetic edit.
236
+ state.drawTimer.unref?.();
237
+ }
238
+ }
239
+ cancelDraw(state) {
240
+ if (state.drawTimer) {
241
+ clearTimeout(state.drawTimer);
242
+ state.drawTimer = null;
243
+ }
244
+ }
245
+ async draw(state) {
246
+ if (state.finalized || state.inFlight || !state.dirty || state.entries.length === 0)
247
+ return;
248
+ state.inFlight = true;
249
+ state.dirty = false;
250
+ let drawn = '';
251
+ try {
252
+ const { text, entities } = this.renderLive(state);
253
+ drawn = JSON.stringify({ text, entities });
254
+ if (state.messageId === null) {
255
+ const sendOpts = state.threadId !== undefined ? { message_thread_id: state.threadId } : {};
256
+ const message = await state.api.sendMessage(state.chatId, text, { entities, ...sendOpts });
257
+ state.messageId = message.message_id;
258
+ }
259
+ else if (drawn !== state.lastDrawn) {
260
+ await state.api.editMessageText(state.chatId, state.messageId, text, { entities });
261
+ }
262
+ else {
263
+ return;
264
+ }
265
+ state.lastUpdate = Date.now();
266
+ state.lastDrawn = drawn;
267
+ }
268
+ catch (error) {
269
+ this.handleDrawError(state, error, drawn);
270
+ }
271
+ finally {
272
+ state.inFlight = false;
273
+ if (state.dirty)
274
+ void this.requestDraw(state);
275
+ }
276
+ }
277
+ handleDrawError(state, error, drawn) {
278
+ if (error instanceof GrammyError) {
279
+ if (error.error_code === 429) {
280
+ const retryAfter = error.parameters.retry_after ?? 60;
281
+ state.rateLimitedUntil = Date.now() + retryAfter * 1000;
282
+ // Draw it again once the backoff is over.
283
+ state.dirty = true;
284
+ console.warn(`[ActionLogger] Rate limited, backing off for ${retryAfter}s`);
285
+ return;
286
+ }
287
+ const msg = error.message.toLowerCase();
288
+ if (msg.includes('message is not modified')) {
289
+ state.lastDrawn = drawn;
290
+ return;
291
+ }
292
+ if (msg.includes('message_id_invalid') || msg.includes('message to edit not found')) {
293
+ // Message was deleted: let the log go, so the next action opens a new one.
294
+ state.finalized = true;
295
+ this.cancelDraw(state);
296
+ if (this.logStates.get(state.sessionKey) === state)
297
+ this.logStates.delete(state.sessionKey);
298
+ return;
299
+ }
300
+ }
301
+ console.error('[ActionLogger] Failed to draw the log:', error);
302
+ }
303
+ /** The log as it reads now: the newest entries that fit, under them the status line and prompt while the turn runs. */
304
+ renderLive(state) {
305
+ const view = {
306
+ live: !state.ended,
307
+ // Rendered once per draw. The thinking verb in it is picked at random,
308
+ // so a second call could come out longer than the fit was measured on.
309
+ status: state.ended ? undefined : state.statusSource?.(),
310
+ prompt: state.ended ? undefined : state.prompt,
311
+ drawnAt: state.ended ? undefined : Date.now(),
312
+ };
313
+ return this.renderActionLog(state.entries, this.entriesThatFit(state.entries, view), view);
314
+ }
315
+ /**
316
+ * How many of the newest entries the live log can show: ten, or fewer when
317
+ * ten would overflow a message.
318
+ *
319
+ * Ten entries with a command and a couple of hundred characters of output
320
+ * each come to more than a Telegram message holds. An edit that long fails
321
+ * with MESSAGE_TOO_LONG — so a busy turn's live log froze partway through.
322
+ * Measured on the text as sent: the formatting goes out as entities rather
323
+ * than markup, so its length is what Telegram counts.
324
+ */
325
+ entriesThatFit(entries, view) {
326
+ let shown = Math.min(entries.length, LIVE_LOG_ENTRIES);
327
+ while (shown > 1 && this.renderActionLog(entries, shown, view).text.length > MAX_MESSAGE_CHARS)
328
+ shown--;
329
+ return shown;
330
+ }
331
+ /**
332
+ * Render the newest `shown` action log entries.
333
+ *
334
+ * Entities rather than MarkdownV2: commands and their output are the model's
335
+ * and the shell's own text, so they go out verbatim with nothing to escape.
336
+ *
337
+ * The header starts with ⏳ while the turn runs. The chat list previews a
338
+ * chat by the start of its newest message, which mid-turn is usually this
339
+ * one — so that's where the list shows the agent is still at it.
340
+ *
341
+ * The prompt goes under the status line, so what the turn is for sits where
342
+ * the user is looking: by the time the log is this long, the message that
343
+ * started the turn is far above it.
344
+ *
345
+ * Under the prompt, the time of the draw. Telegram shows when a message was
346
+ * sent but not when it was last edited, so a log that has stopped moving
347
+ * looks the same as one that's still going. With the terminal UI on, the
348
+ * status line redraws the log every ten seconds, so a time that keeps up
349
+ * with the clock means the bot is alive however long the current step
350
+ * takes, and one that falls behind means it isn't. Without the status line
351
+ * nothing redraws it between actions, and it's the time of the newest one.
352
+ *
353
+ * The same line opens the log, under the header: see addProgressLine. A log
354
+ * that isn't running has no time to give, and says how much of it is
355
+ * showing on its own, at the top.
356
+ */
357
+ renderActionLog(entries, shown, view) {
358
+ const b = new EntityText();
359
+ b.add(view.live ? '⏳ ' : '📋 ').bold('Action Log');
360
+ if (view.drawnAt !== undefined) {
361
+ this.addProgressLine(b.newline(2), view.drawnAt, shown, entries.length);
362
+ }
363
+ else if (entries.length > shown) {
364
+ b.newline(2).italic(`Showing last ${shown} of ${entries.length} actions`);
365
+ }
366
+ for (const entry of entries.slice(-shown)) {
367
+ const statusEmoji = entry.status === 'completed' ? '✅' :
368
+ entry.status === 'error' ? '❌' : '⏳';
369
+ b.newline(2).add(`${entry.icon} ${statusEmoji} [`)
370
+ .dateTime(serverClockTime(entry.timestamp), entry.timestamp)
371
+ .add(`] ${entry.title}`);
372
+ if (entry.subtitle)
373
+ b.newline().code(cutForLiveLog(entry.subtitle));
374
+ if (entry.content)
375
+ b.newline().pre(cutForLiveLog(entry.content));
376
+ }
377
+ if (view.status)
378
+ b.newline(2).append(view.status);
379
+ if (view.prompt)
380
+ b.newline(2).italic(`▸ ${view.prompt}`);
381
+ if (view.drawnAt !== undefined) {
382
+ this.addProgressLine(b.newline(2), view.drawnAt, shown, entries.length);
383
+ }
384
+ return b.build();
385
+ }
386
+ /**
387
+ * The line a running log both opens and closes with: when it was drawn, and
388
+ * how much of it is showing when that isn't all of it.
389
+ *
390
+ * At both ends because the log is usually taller than a screen and either
391
+ * end can be the one on screen: the bottom while following along, the top
392
+ * on opening the chat or scrolling back to an earlier action. The count was
393
+ * only at the top and the time only at the bottom, and both change all the
394
+ * time, so reading either meant scrolling to the other end. From the top
395
+ * the log also looked frozen through a long step, the count being the only
396
+ * thing there that moves, and only when an action comes in.
397
+ *
398
+ * One line rather than two: a log that had the count at its top is no
399
+ * taller for it, and one with every action showing gains the time there.
400
+ * The time comes first, as the part that says the bot is alive.
401
+ */
402
+ addProgressLine(b, drawnAt, shown, total) {
403
+ b.add('🕐 Updated ').dateTime(serverClockTime(drawnAt), drawnAt);
404
+ if (total > shown)
405
+ b.add(` · last ${shown} of ${total} actions`);
406
+ }
407
+ /**
408
+ * Collapse the session's log once its turn is over, then let it go.
409
+ *
410
+ * Holds on to this turn's log rather than looking the session up again when
411
+ * the delay runs out. A message queued behind the turn starts the next one
412
+ * straight away, and that turn's initialize() replaces the session's log
413
+ * well inside the delay — looked up by key, the timer collapsed the new
414
+ * turn's log mid-turn, or threw it away while it was still empty, and never
415
+ * collapsed this one.
416
+ *
417
+ * The live marker and status line go at once, so a draw in the meantime —
418
+ * for a result still landing — doesn't show the finished turn as running.
419
+ */
420
+ endTurn(sessionKey) {
421
+ const state = this.logStates.get(sessionKey);
422
+ if (!state)
423
+ return;
424
+ state.ended = true;
425
+ setTimeout(async () => {
426
+ try {
427
+ await this.finalize(state);
428
+ }
429
+ finally {
430
+ // Unless a newer turn's log has taken the session over since.
431
+ if (this.logStates.get(sessionKey) === state)
432
+ this.logStates.delete(sessionKey);
433
+ }
434
+ }, COLLAPSE_DELAY_MS);
435
+ }
436
+ /**
437
+ * Close the log where it stands and open a new one below, for a turn that
438
+ * carries on after the user answered something it asked.
439
+ *
440
+ * A question doesn't end the turn: the agent waits on the tool call, and
441
+ * once the answer comes back it carries on in the same turn — and so in the
442
+ * same log, which was posted before the question went up. Its next actions
443
+ * landed above the question and the answer, out of sight, while the bottom
444
+ * of the chat looked like nothing was happening.
445
+ *
446
+ * The closed log collapses like a finished turn's. Its status line and
447
+ * prompt move to the new one, which is posted with the next action, as the
448
+ * first log of a turn is — but not within ANSWER_SETTLE_MS, or the agent's
449
+ * first move, often the question's own result, posts it before the bot has
450
+ * sent the answer it follows. A log with nothing in it yet has nothing above the
451
+ * answer to move away from, and is left as it is.
452
+ */
453
+ startNewMessage(sessionKey) {
454
+ const state = this.logStates.get(sessionKey);
455
+ if (!state || state.ended || state.entries.length === 0)
456
+ return;
457
+ this.logStates.set(sessionKey, {
458
+ ...state,
459
+ messageId: null,
460
+ entries: [],
461
+ lastUpdate: Date.now(),
462
+ notBefore: Date.now() + ANSWER_SETTLE_MS,
463
+ dirty: false,
464
+ drawTimer: null,
465
+ inFlight: false,
466
+ lastDrawn: '',
467
+ });
468
+ state.ended = true;
469
+ this.finalize(state).catch((error) => {
470
+ console.error('[ActionLogger] Failed to close the log before an answer:', error);
471
+ });
472
+ }
473
+ /**
474
+ * Close the in-chat action log at the end of a turn: draw it one last time
475
+ * as it stands, without the live marker and status line.
476
+ */
477
+ async finalize(state) {
478
+ if (state.finalized)
479
+ return;
480
+ // No more live draws: whatever is drawn from here on is final.
481
+ state.finalized = true;
482
+ this.cancelDraw(state);
483
+ if (!state.messageId || state.entries.length === 0)
484
+ return;
485
+ try {
486
+ const view = { live: false };
487
+ const { text, entities } = this.renderActionLog(state.entries, this.entriesThatFit(state.entries, view), view);
488
+ if (JSON.stringify({ text, entities }) === state.lastDrawn)
489
+ return;
490
+ await state.api.editMessageText(state.chatId, state.messageId, text, { entities });
491
+ }
492
+ catch (error) {
493
+ if (error instanceof GrammyError) {
494
+ const msg = error.message.toLowerCase();
495
+ if (msg.includes('message is not modified'))
496
+ return;
497
+ }
498
+ console.error('[ActionLogger] Failed to close the log:', error);
499
+ }
500
+ }
501
+ /**
502
+ * Check if action logging is active for a session
503
+ */
504
+ isActive(sessionKey) {
505
+ return this.logStates.has(sessionKey);
506
+ }
507
+ /**
508
+ * Trim long absolute paths for display
509
+ */
510
+ stripWorkingDir(filePath) {
511
+ const cwd = process.cwd();
512
+ if (filePath.startsWith(cwd + '/'))
513
+ return filePath.slice(cwd.length + 1);
514
+ const home = process.env.HOME;
515
+ if (home && filePath.startsWith(home + '/'))
516
+ return '~/' + filePath.slice(home.length + 1);
517
+ return filePath;
518
+ }
519
+ }
520
+ // Export singleton instance
521
+ export const actionLogger = new ActionLogger();
522
+ //# sourceMappingURL=action-logger.js.map
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Naming a prompt's approvers in a chat.
3
+ *
4
+ * An approval prompt is only as good as the notification it raises: if the
5
+ * people who can answer it have the group muted — and anyone sharing a bot with
6
+ * friends will mute that group — a prompt that does not mention them is a
7
+ * prompt that is answered ten minutes later by the timeout. So the gate
8
+ * mentions them by numeric id, which pings them whether or not they have a
9
+ * @username.
10
+ *
11
+ * Who that is varies per prompt: admins always, plus any approver who is not
12
+ * the person who asked. So the roster is passed in rather than read here.
13
+ *
14
+ * Rendering a mention needs a display name, and an id alone does not carry one.
15
+ * `getChatMember` does, so it is asked once per (chat, admin) pair and the
16
+ * answer is kept for the life of the process — display names change far more
17
+ * slowly than permission prompts arrive, and a stale label on a working mention
18
+ * is a much smaller problem than an API round-trip on every prompt.
19
+ */
20
+ import { getAdminIds, isApprover } from '../utils/admins.js';
21
+ const nameCache = new Map();
22
+ /**
23
+ * How long a failed lookup sticks. A miss is usually "not a member yet", and
24
+ * that changes the moment the admin joins the group — so misses expire, while
25
+ * a resolved name is kept for the life of the process.
26
+ */
27
+ const MISS_TTL_MS = 10 * 60 * 1000;
28
+ function cacheKey(chatId, userId) {
29
+ return `${chatId}:${userId}`;
30
+ }
31
+ /**
32
+ * Look up these users' display names in this chat. Anyone the lookup cannot
33
+ * resolve — not a member, or the API call failed — is dropped rather than
34
+ * rendered with a placeholder: a mention of someone who is not in the chat
35
+ * notifies nobody, and listing them would suggest an approver who cannot see
36
+ * the prompt.
37
+ *
38
+ * Defaults to the admin roster, which is what every caller wanted before
39
+ * approvers existed.
40
+ */
41
+ export async function resolveApproversInChat(api, chatId, ids = getAdminIds()) {
42
+ const resolved = [];
43
+ for (const id of ids) {
44
+ const key = cacheKey(chatId, id);
45
+ const cached = nameCache.get(key);
46
+ if (cached && (cached.expiresAt === undefined || cached.expiresAt > Date.now())) {
47
+ if (cached.name)
48
+ resolved.push({ id, name: cached.name });
49
+ continue;
50
+ }
51
+ try {
52
+ const member = await api.getChatMember(chatId, id);
53
+ const user = member.user;
54
+ const name = [user.first_name, user.last_name].filter(Boolean).join(' ') || user.username || `approver ${id}`;
55
+ nameCache.set(key, { name });
56
+ resolved.push({ id, name });
57
+ }
58
+ catch {
59
+ // Not a member of this chat, or a transient API failure. Cache the miss
60
+ // briefly so a burst of prompts doesn't re-ask on every one, but let it
61
+ // expire so an admin who joins later starts getting mentioned.
62
+ nameCache.set(key, { name: '', expiresAt: Date.now() + MISS_TTL_MS });
63
+ }
64
+ }
65
+ return resolved;
66
+ }
67
+ /**
68
+ * Append "Only X can approve." to a prompt, with each admin as a real mention.
69
+ * Falls back to a countless phrasing when no admin could be resolved, so the
70
+ * sentence still reads correctly rather than trailing off.
71
+ */
72
+ export function appendApproverLine(builder, admins) {
73
+ if (admins.length === 0) {
74
+ return builder.add('Only an admin can approve this.');
75
+ }
76
+ builder.add('Only ');
77
+ admins.forEach((admin, index) => {
78
+ if (index > 0)
79
+ builder.add(index === admins.length - 1 ? ' or ' : ', ');
80
+ builder.mention(admin.name, admin.id);
81
+ });
82
+ return builder.add(' can approve this.');
83
+ }
84
+ /**
85
+ * The toast shown when someone taps an approval button that isn't theirs.
86
+ *
87
+ * An approver who taps their own request is the one case worth naming exactly.
88
+ * "Only a bot admin can answer that one" is wrong for them and reads as though
89
+ * their approver rights had not taken effect, when the truth is narrower and
90
+ * they will hit it every time: they can answer anyone's prompt but this one.
91
+ */
92
+ export function describeResponderRefusal(allowedResponderIds, userId) {
93
+ const count = allowedResponderIds?.length ?? 0;
94
+ if (count === 0)
95
+ return 'You cannot answer this question.';
96
+ if (isApprover(userId)) {
97
+ return 'You can’t approve your own request — someone else has to.';
98
+ }
99
+ return count === 1
100
+ ? 'Only this bot’s admin can answer that one.'
101
+ : 'Only an admin or approver can answer that one.';
102
+ }
103
+ /** Test seam — production keeps the cache for the life of the process. */
104
+ export function resetAdminNameCache() {
105
+ nameCache.clear();
106
+ }
107
+ //# sourceMappingURL=admin-mention.js.map