telecoder 0.0.0-stage โ†’ 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
@@ -0,0 +1,684 @@
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 { createTelegraphPage, fitsTelegraphPage } from './telegraph.js';
24
+ import { editFormatted } from './send.js';
25
+ import { isTelegraphEnabled } from './telegraph-settings.js';
26
+ import { getSessionKeyFromCtx } from '../utils/session-key.js';
27
+ // Constants
28
+ const MIN_EDIT_INTERVAL_MS = 10000; // Minimum time between message edits (~5 edits/min safe zone)
29
+ // Telegram's cap on a message's text.
30
+ const MAX_MESSAGE_CHARS = 4096;
31
+ // The most actions the live log shows at once.
32
+ const LIVE_LOG_ENTRIES = 10;
33
+ // How much of an action's command and output the live log shows.
34
+ const LIVE_ENTRY_CHARS = 200;
35
+ // How long the turn's prompt can be before the live log shows only its start
36
+ // and its end: as long as the status line shows each of its prompts.
37
+ const LIVE_PROMPT_CHARS = 300;
38
+ // How long a log stays open once its turn has ended, so tool results still in
39
+ // flight land in it before it collapses.
40
+ const COLLAPSE_DELAY_MS = 5000;
41
+ // How long a log opened after an answer waits before it posts, so the bot's
42
+ // "โœ… You picked" message lands above it rather than under it.
43
+ const ANSWER_SETTLE_MS = 1500;
44
+ // `mcp__telecoder-tools__telecoder_send_file` โ†’ `telecoder_send_file`
45
+ function stripMcpServerPrefix(toolName) {
46
+ if (!toolName.startsWith('mcp__'))
47
+ return toolName;
48
+ const lastSep = toolName.lastIndexOf('__');
49
+ return lastSep > 0 ? toolName.slice(lastSep + 2) : toolName;
50
+ }
51
+ function cutForLiveLog(text) {
52
+ return text.length > LIVE_ENTRY_CHARS ? text.substring(0, LIVE_ENTRY_CHARS - 3) + '...' : text;
53
+ }
54
+ /**
55
+ * A time as the server's clock reads it, for the clients that can't show a
56
+ * `date_time` entity. The rest show it in the reader's timezone instead.
57
+ */
58
+ function serverClockTime(ms) {
59
+ return new Date(ms).toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' });
60
+ }
61
+ /**
62
+ * The turn's prompt as the live log shows it. promptLabel leaves a slash
63
+ * command out, not being a turn of the conversation, but here a skill like
64
+ * /code-review is what the turn is running, so it shows as typed.
65
+ */
66
+ function liveLogPrompt(prompt) {
67
+ const label = promptLabel(prompt) ?? prompt.replace(/\s+/g, ' ').trim();
68
+ return label ? cutLabel(label, LIVE_PROMPT_CHARS) : undefined;
69
+ }
70
+ /**
71
+ * Manages consolidated action logging for verbose mode. Instead of sending
72
+ * multiple separate messages for tool results, diffs, etc., maintains a single
73
+ * message that gets edited with accumulated actions.
74
+ */
75
+ export class ActionLogger {
76
+ logStates = new Map();
77
+ /**
78
+ * Initialize action logging for a session. Creates the state but doesn't send a message yet.
79
+ * `statusSource` is the turn's live status line, drawn at the bottom of the log while the turn runs,
80
+ * and `prompt` what the turn was sent, drawn under it.
81
+ */
82
+ async initialize(ctx, sessionKey, statusSource, prompt) {
83
+ const chatId = ctx.chat?.id;
84
+ if (chatId === undefined)
85
+ return;
86
+ // Resolve the thread the same way the streaming bubble does. A turn can
87
+ // start from a callback query (a tapped suggestion button), where
88
+ // `ctx.message` is undefined and the originating message hangs off
89
+ // `ctx.callbackQuery` instead โ€” reading `ctx.message` directly threw and
90
+ // took the whole turn down with it.
91
+ const threadId = getSessionKeyFromCtx(ctx)?.threadId;
92
+ // Just create the state, don't send a message yet
93
+ this.logStates.set(sessionKey, {
94
+ sessionKey,
95
+ api: ctx.api,
96
+ chatId,
97
+ threadId,
98
+ messageId: null, // Will be created when first action is added
99
+ entries: [],
100
+ lastUpdate: Date.now(),
101
+ rateLimitedUntil: 0,
102
+ notBefore: 0,
103
+ statusSource,
104
+ prompt: prompt === undefined ? undefined : liveLogPrompt(prompt),
105
+ ended: false,
106
+ finalized: false,
107
+ dirty: false,
108
+ drawTimer: null,
109
+ inFlight: false,
110
+ lastDrawn: '',
111
+ });
112
+ }
113
+ /**
114
+ * Add a tool result to the action log
115
+ */
116
+ async addToolResult(sessionKey, event, maxLines, maxChars) {
117
+ const state = this.logStates.get(sessionKey);
118
+ if (!state)
119
+ return;
120
+ const cleaned = stripAnsi(event.content).replace(/\s+$/u, '');
121
+ if (!cleaned && !event.isError)
122
+ return;
123
+ const icon = event.toolName ? getToolIcon(event.toolName) : '๐Ÿ”น';
124
+ const label = event.toolName ? stripMcpServerPrefix(event.toolName) : 'tool';
125
+ const status = event.isError ? 'error' : 'completed';
126
+ // Tail-biased for errors (failures land at the end), head-biased for
127
+ // success โ€” middle elided either way (see elideToolOutput).
128
+ const content = elideToolOutput(cleaned || '(no output)', maxLines, maxChars, { isError: event.isError });
129
+ const detail = event.toolName && event.input
130
+ ? extractToolDetail(event.toolName, event.input, true)
131
+ : undefined;
132
+ const subtitle = detail
133
+ ? `${event.toolName === 'Bash' ? '$ ' : ''}${detail}`
134
+ : undefined;
135
+ const entry = {
136
+ id: `tool-${Date.now()}-${Math.random()}`,
137
+ timestamp: Date.now(),
138
+ type: 'tool_result',
139
+ icon,
140
+ title: `${label} ${event.isError ? 'error' : 'result'}`,
141
+ subtitle,
142
+ content,
143
+ status
144
+ };
145
+ state.entries.push(entry);
146
+ await this.requestDraw(state);
147
+ }
148
+ /**
149
+ * Add an edit diff to the action log
150
+ */
151
+ async addEditDiff(sessionKey, event, maxLines) {
152
+ const state = this.logStates.get(sessionKey);
153
+ if (!state)
154
+ return;
155
+ const fileLabel = this.stripWorkingDir(event.filePath);
156
+ const headerIcon = event.toolName === 'Write' ? 'โœ๏ธ' : '๐Ÿ”ง';
157
+ const lines = [];
158
+ // Add old content (if any)
159
+ if (typeof event.oldString === 'string' && event.oldString.length > 0) {
160
+ const oldLines = event.oldString.split('\n');
161
+ const oldShown = oldLines.slice(0, maxLines).map((l) => `- ${l}`);
162
+ if (oldLines.length > maxLines) {
163
+ oldShown.push(`- [+${oldLines.length - maxLines} more lines]`);
164
+ }
165
+ lines.push(...oldShown);
166
+ }
167
+ // Add new content
168
+ const newLines = event.newString.split('\n');
169
+ const newShown = newLines.slice(0, maxLines).map((l) => `+ ${l}`);
170
+ if (newLines.length > maxLines) {
171
+ newShown.push(`+ [+${newLines.length - maxLines} more lines]`);
172
+ }
173
+ lines.push(...newShown);
174
+ const entry = {
175
+ id: `edit-${Date.now()}-${Math.random()}`,
176
+ timestamp: Date.now(),
177
+ type: 'edit_diff',
178
+ icon: headerIcon,
179
+ title: `${event.toolName} ${fileLabel}`,
180
+ content: lines.join('\n'),
181
+ status: 'completed'
182
+ };
183
+ state.entries.push(entry);
184
+ await this.requestDraw(state);
185
+ }
186
+ /**
187
+ * Add a monitor event to the action log
188
+ */
189
+ async addMonitorEvent(sessionKey, task, eventText) {
190
+ const state = this.logStates.get(sessionKey);
191
+ if (!state || task.skipTranscript)
192
+ return;
193
+ const cleaned = stripAnsi(eventText);
194
+ const truncated = cleaned.length > 500
195
+ ? cleaned.substring(0, 497) + '...'
196
+ : cleaned;
197
+ const entry = {
198
+ id: `monitor-${Date.now()}-${Math.random()}`,
199
+ timestamp: Date.now(),
200
+ type: 'monitor_event',
201
+ icon: '๐Ÿ“ก',
202
+ title: 'Monitor event',
203
+ content: truncated,
204
+ status: 'completed'
205
+ };
206
+ state.entries.push(entry);
207
+ await this.requestDraw(state);
208
+ }
209
+ /**
210
+ * Add a task completion to the action log
211
+ */
212
+ async addTaskCompletion(sessionKey, task) {
213
+ const state = this.logStates.get(sessionKey);
214
+ if (!state || task.skipTranscript || !task.isBackgrounded)
215
+ return;
216
+ const isMonitor = task.taskType === 'monitor_mcp';
217
+ const statusIcon = task.status === 'completed'
218
+ ? (isMonitor ? '๐Ÿ“ก' : 'โœ…')
219
+ : task.status === 'stopped' ? '๐Ÿ›‘' : 'โŒ';
220
+ const verb = task.status === 'completed'
221
+ ? (isMonitor ? 'stream ended' : 'completed')
222
+ : task.status === 'stopped' ? 'stopped' : 'failed';
223
+ const elapsedMs = (task.endedAt ?? Date.now()) - task.startedAt;
224
+ const seconds = Math.round(elapsedMs / 1000);
225
+ const duration = seconds >= 60
226
+ ? `${Math.floor(seconds / 60)}m ${seconds % 60}s`
227
+ : `${seconds}s`;
228
+ const description = task.description.length > 100
229
+ ? task.description.substring(0, 97) + '...'
230
+ : task.description;
231
+ const title = isMonitor
232
+ ? `Monitor "${description}" ${verb} after ${duration}`
233
+ : `Background task "${description}" ${verb} in ${duration}`;
234
+ const entry = {
235
+ id: `task-${Date.now()}-${Math.random()}`,
236
+ timestamp: Date.now(),
237
+ type: 'task_completion',
238
+ icon: statusIcon,
239
+ title,
240
+ content: task.error,
241
+ status: task.status === 'completed' ? 'completed' : 'error'
242
+ };
243
+ state.entries.push(entry);
244
+ await this.requestDraw(state);
245
+ }
246
+ /**
247
+ * Whether the turn's status line is showing at the bottom of the log: from
248
+ * the log's first post until its turn ends. MessageSender stops updating the
249
+ * status bubble meanwhile and points it at the log instead.
250
+ */
251
+ showsStatus(sessionKey) {
252
+ const state = this.logStates.get(sessionKey);
253
+ return state !== undefined && this.isShowingStatus(state);
254
+ }
255
+ /**
256
+ * Redraw the log for a new status line. Waits behind the edit throttle like
257
+ * any other change, unless `immediate` โ€” a question waiting on the user
258
+ * shouldn't go unannounced until the next slot.
259
+ */
260
+ async refreshStatus(sessionKey, immediate = false) {
261
+ const state = this.logStates.get(sessionKey);
262
+ if (!state || !this.isShowingStatus(state))
263
+ return;
264
+ await this.requestDraw(state, immediate);
265
+ }
266
+ isShowingStatus(state) {
267
+ return state.statusSource !== undefined && state.messageId !== null && !state.ended;
268
+ }
269
+ /**
270
+ * Draw the log now if the edit throttle allows, or as soon as it does.
271
+ *
272
+ * The first draw posts the message straight away; the edits after it are at
273
+ * least MIN_EDIT_INTERVAL_MS apart, and `immediate` skips that wait. A change
274
+ * that comes too soon waits for its slot instead of being dropped. Dropped,
275
+ * the newest actions stayed off the log until another one came in, which
276
+ * during a long build after a burst of quick reads was minutes.
277
+ */
278
+ async requestDraw(state, immediate = false) {
279
+ if (state.finalized)
280
+ return;
281
+ state.dirty = true;
282
+ // The draw in flight goes again when it lands, and picks this change up.
283
+ if (state.inFlight)
284
+ return;
285
+ const now = Date.now();
286
+ const due = Math.max(state.messageId === null || immediate ? now : state.lastUpdate + MIN_EDIT_INTERVAL_MS,
287
+ // Respect Telegram's retry_after backoff on 429
288
+ state.rateLimitedUntil, state.notBefore);
289
+ if (due <= now) {
290
+ this.cancelDraw(state);
291
+ await this.draw(state);
292
+ }
293
+ else if (!state.drawTimer) {
294
+ state.drawTimer = setTimeout(() => {
295
+ state.drawTimer = null;
296
+ void this.requestDraw(state);
297
+ }, due - now);
298
+ // Never hold the process open for a cosmetic edit.
299
+ state.drawTimer.unref?.();
300
+ }
301
+ }
302
+ cancelDraw(state) {
303
+ if (state.drawTimer) {
304
+ clearTimeout(state.drawTimer);
305
+ state.drawTimer = null;
306
+ }
307
+ }
308
+ async draw(state) {
309
+ if (state.finalized || state.inFlight || !state.dirty || state.entries.length === 0)
310
+ return;
311
+ state.inFlight = true;
312
+ state.dirty = false;
313
+ let drawn = '';
314
+ try {
315
+ const { text, entities } = this.renderLive(state);
316
+ drawn = JSON.stringify({ text, entities });
317
+ if (state.messageId === null) {
318
+ const sendOpts = state.threadId !== undefined ? { message_thread_id: state.threadId } : {};
319
+ const message = await state.api.sendMessage(state.chatId, text, { entities, ...sendOpts });
320
+ state.messageId = message.message_id;
321
+ }
322
+ else if (drawn !== state.lastDrawn) {
323
+ await state.api.editMessageText(state.chatId, state.messageId, text, { entities });
324
+ }
325
+ else {
326
+ return;
327
+ }
328
+ state.lastUpdate = Date.now();
329
+ state.lastDrawn = drawn;
330
+ }
331
+ catch (error) {
332
+ this.handleDrawError(state, error, drawn);
333
+ }
334
+ finally {
335
+ state.inFlight = false;
336
+ if (state.dirty)
337
+ void this.requestDraw(state);
338
+ }
339
+ }
340
+ handleDrawError(state, error, drawn) {
341
+ if (error instanceof GrammyError) {
342
+ if (error.error_code === 429) {
343
+ const retryAfter = error.parameters.retry_after ?? 60;
344
+ state.rateLimitedUntil = Date.now() + retryAfter * 1000;
345
+ // Draw it again once the backoff is over.
346
+ state.dirty = true;
347
+ console.warn(`[ActionLogger] Rate limited, backing off for ${retryAfter}s`);
348
+ return;
349
+ }
350
+ const msg = error.message.toLowerCase();
351
+ if (msg.includes('message is not modified')) {
352
+ state.lastDrawn = drawn;
353
+ return;
354
+ }
355
+ if (msg.includes('message_id_invalid') || msg.includes('message to edit not found')) {
356
+ // Message was deleted: let the log go, so the next action opens a new one.
357
+ state.finalized = true;
358
+ this.cancelDraw(state);
359
+ if (this.logStates.get(state.sessionKey) === state)
360
+ this.logStates.delete(state.sessionKey);
361
+ return;
362
+ }
363
+ }
364
+ console.error('[ActionLogger] Failed to draw the log:', error);
365
+ }
366
+ /** The log as it reads now: the newest entries that fit, under them the status line and prompt while the turn runs. */
367
+ renderLive(state) {
368
+ const view = {
369
+ live: !state.ended,
370
+ // Rendered once per draw. The thinking verb in it is picked at random,
371
+ // so a second call could come out longer than the fit was measured on.
372
+ status: state.ended ? undefined : state.statusSource?.(),
373
+ prompt: state.ended ? undefined : state.prompt,
374
+ drawnAt: state.ended ? undefined : Date.now(),
375
+ };
376
+ return this.renderActionLog(state.entries, this.entriesThatFit(state.entries, view), view);
377
+ }
378
+ /**
379
+ * How many of the newest entries the live log can show: ten, or fewer when
380
+ * ten would overflow a message.
381
+ *
382
+ * Ten entries with a command and a couple of hundred characters of output
383
+ * each come to more than a Telegram message holds. An edit that long fails
384
+ * with MESSAGE_TOO_LONG โ€” so a busy turn's live log froze partway through.
385
+ * Measured on the text as sent: the formatting goes out as entities rather
386
+ * than markup, so its length is what Telegram counts.
387
+ */
388
+ entriesThatFit(entries, view) {
389
+ let shown = Math.min(entries.length, LIVE_LOG_ENTRIES);
390
+ while (shown > 1 && this.renderActionLog(entries, shown, view).text.length > MAX_MESSAGE_CHARS)
391
+ shown--;
392
+ return shown;
393
+ }
394
+ /**
395
+ * Render the newest `shown` action log entries.
396
+ *
397
+ * Entities rather than MarkdownV2: commands and their output are the model's
398
+ * and the shell's own text, so they go out verbatim with nothing to escape.
399
+ *
400
+ * The header starts with โณ while the turn runs. The chat list previews a
401
+ * chat by the start of its newest message, which mid-turn is usually this
402
+ * one โ€” so that's where the list shows the agent is still at it.
403
+ *
404
+ * The prompt goes under the status line, so what the turn is for sits where
405
+ * the user is looking: by the time the log is this long, the message that
406
+ * started the turn is far above it.
407
+ *
408
+ * Under the prompt, the time of the draw. Telegram shows when a message was
409
+ * sent but not when it was last edited, so a log that has stopped moving
410
+ * looks the same as one that's still going. With the terminal UI on, the
411
+ * status line redraws the log every ten seconds, so a time that keeps up
412
+ * with the clock means the bot is alive however long the current step
413
+ * takes, and one that falls behind means it isn't. Without the status line
414
+ * nothing redraws it between actions, and it's the time of the newest one.
415
+ *
416
+ * The same line opens the log, under the header: see addProgressLine. A log
417
+ * that isn't running has no time to give, and says how much of it is
418
+ * showing on its own, at the top.
419
+ */
420
+ renderActionLog(entries, shown, view) {
421
+ const b = new EntityText();
422
+ b.add(view.live ? 'โณ ' : '๐Ÿ“‹ ').bold('Action Log');
423
+ if (view.drawnAt !== undefined) {
424
+ this.addProgressLine(b.newline(2), view.drawnAt, shown, entries.length);
425
+ }
426
+ else if (entries.length > shown) {
427
+ b.newline(2).italic(`Showing last ${shown} of ${entries.length} actions`);
428
+ }
429
+ for (const entry of entries.slice(-shown)) {
430
+ const statusEmoji = entry.status === 'completed' ? 'โœ…' :
431
+ entry.status === 'error' ? 'โŒ' : 'โณ';
432
+ b.newline(2).add(`${entry.icon} ${statusEmoji} [`)
433
+ .dateTime(serverClockTime(entry.timestamp), entry.timestamp)
434
+ .add(`] ${entry.title}`);
435
+ if (entry.subtitle)
436
+ b.newline().code(cutForLiveLog(entry.subtitle));
437
+ if (entry.content)
438
+ b.newline().pre(cutForLiveLog(entry.content));
439
+ }
440
+ if (view.status)
441
+ b.newline(2).append(view.status);
442
+ if (view.prompt)
443
+ b.newline(2).italic(`โ–ธ ${view.prompt}`);
444
+ if (view.drawnAt !== undefined) {
445
+ this.addProgressLine(b.newline(2), view.drawnAt, shown, entries.length);
446
+ }
447
+ return b.build();
448
+ }
449
+ /**
450
+ * The line a running log both opens and closes with: when it was drawn, and
451
+ * how much of it is showing when that isn't all of it.
452
+ *
453
+ * At both ends because the log is usually taller than a screen and either
454
+ * end can be the one on screen: the bottom while following along, the top
455
+ * on opening the chat or scrolling back to an earlier action. The count was
456
+ * only at the top and the time only at the bottom, and both change all the
457
+ * time, so reading either meant scrolling to the other end. From the top
458
+ * the log also looked frozen through a long step, the count being the only
459
+ * thing there that moves, and only when an action comes in.
460
+ *
461
+ * One line rather than two: a log that had the count at its top is no
462
+ * taller for it, and one with every action showing gains the time there.
463
+ * The time comes first, as the part that says the bot is alive.
464
+ */
465
+ addProgressLine(b, drawnAt, shown, total) {
466
+ b.add('๐Ÿ• Updated ').dateTime(serverClockTime(drawnAt), drawnAt);
467
+ if (total > shown)
468
+ b.add(` ยท last ${shown} of ${total} actions`);
469
+ }
470
+ /**
471
+ * Collapse the session's log once its turn is over, then let it go.
472
+ *
473
+ * Holds on to this turn's log rather than looking the session up again when
474
+ * the delay runs out. A message queued behind the turn starts the next one
475
+ * straight away, and that turn's initialize() replaces the session's log
476
+ * well inside the delay โ€” looked up by key, the timer collapsed the new
477
+ * turn's log mid-turn, or threw it away while it was still empty, and never
478
+ * collapsed this one.
479
+ *
480
+ * The live marker and status line go at once, so a draw in the meantime โ€”
481
+ * for a result still landing โ€” doesn't show the finished turn as running.
482
+ */
483
+ endTurn(sessionKey) {
484
+ const state = this.logStates.get(sessionKey);
485
+ if (!state)
486
+ return;
487
+ state.ended = true;
488
+ setTimeout(async () => {
489
+ try {
490
+ await this.finalize(state);
491
+ }
492
+ finally {
493
+ // Unless a newer turn's log has taken the session over since.
494
+ if (this.logStates.get(sessionKey) === state)
495
+ this.logStates.delete(sessionKey);
496
+ }
497
+ }, COLLAPSE_DELAY_MS);
498
+ }
499
+ /**
500
+ * Close the log where it stands and open a new one below, for a turn that
501
+ * carries on after the user answered something it asked.
502
+ *
503
+ * A question doesn't end the turn: the agent waits on the tool call, and
504
+ * once the answer comes back it carries on in the same turn โ€” and so in the
505
+ * same log, which was posted before the question went up. Its next actions
506
+ * landed above the question and the answer, out of sight, while the bottom
507
+ * of the chat looked like nothing was happening.
508
+ *
509
+ * The closed log collapses like a finished turn's. Its status line and
510
+ * prompt move to the new one, which is posted with the next action, as the
511
+ * first log of a turn is โ€” but not within ANSWER_SETTLE_MS, or the agent's
512
+ * first move, often the question's own result, posts it before the bot has
513
+ * sent the answer it follows. A log with nothing in it yet has nothing above the
514
+ * answer to move away from, and is left as it is.
515
+ */
516
+ startNewMessage(sessionKey) {
517
+ const state = this.logStates.get(sessionKey);
518
+ if (!state || state.ended || state.entries.length === 0)
519
+ return;
520
+ this.logStates.set(sessionKey, {
521
+ ...state,
522
+ messageId: null,
523
+ entries: [],
524
+ lastUpdate: Date.now(),
525
+ notBefore: Date.now() + ANSWER_SETTLE_MS,
526
+ dirty: false,
527
+ drawTimer: null,
528
+ inFlight: false,
529
+ lastDrawn: '',
530
+ });
531
+ state.ended = true;
532
+ this.finalize(state).catch((error) => {
533
+ console.error('[ActionLogger] Failed to close the log before an answer:', error);
534
+ });
535
+ }
536
+ /**
537
+ * Collapse the in-chat action log into a Telegraph link at the end of a turn.
538
+ * Renders all entries (no 10-entry cap) onto a Telegraph page, then edits
539
+ * the existing action-log message into a brief "๐Ÿ“‹ N actions ยท view full
540
+ * log" summary. If Telegraph is disabled or fails, the log is drawn one last
541
+ * time as it stands, without the live marker and status line.
542
+ */
543
+ async finalize(state) {
544
+ if (state.finalized)
545
+ return;
546
+ // No more live draws: whatever is drawn from here on is final.
547
+ state.finalized = true;
548
+ this.cancelDraw(state);
549
+ if (!state.messageId || state.entries.length === 0)
550
+ return;
551
+ // Telegraph creation can fail (rate limit, network); the full log then
552
+ // stays in the chat instead.
553
+ const pageUrl = isTelegraphEnabled(state.sessionKey)
554
+ ? await createTelegraphPage('Action log', this.renderTelegraphPage(state.entries))
555
+ : null;
556
+ try {
557
+ if (pageUrl) {
558
+ const summary = this.renderCollapsedSummary(state.entries, pageUrl);
559
+ await editFormatted(state.api, state.chatId, state.messageId, summary, {
560
+ link_preview_options: { is_disabled: true },
561
+ });
562
+ return;
563
+ }
564
+ const view = { live: false };
565
+ const { text, entities } = this.renderActionLog(state.entries, this.entriesThatFit(state.entries, view), view);
566
+ if (JSON.stringify({ text, entities }) === state.lastDrawn)
567
+ return;
568
+ await state.api.editMessageText(state.chatId, state.messageId, text, { entities });
569
+ }
570
+ catch (error) {
571
+ if (error instanceof GrammyError) {
572
+ const msg = error.message.toLowerCase();
573
+ if (msg.includes('message is not modified'))
574
+ return;
575
+ }
576
+ console.error('[ActionLogger] Failed to collapse message:', error);
577
+ }
578
+ }
579
+ /**
580
+ * The full action log as markdown for a Telegraph page, cut down until it
581
+ * fits on one.
582
+ *
583
+ * Telegraph refuses a page over 64 KB, and a long turn's log passes that
584
+ * easily โ€” 40 results at the verbose tier's 2,000 characters is 80 KB โ€” which
585
+ * left the live log standing uncollapsed. Output goes first: each pass
586
+ * halves how much of an entry's input and output the page keeps, so every
587
+ * action stays listed. Only once the title lines alone are too much do the
588
+ * oldest actions drop off.
589
+ */
590
+ renderTelegraphPage(entries) {
591
+ const longest = entries.reduce((max, e) => Math.max(max, e.subtitle?.length ?? 0, e.content?.length ?? 0), 0);
592
+ for (let cap = longest; cap > 0; cap = Math.floor(cap / 2)) {
593
+ const markdown = this.renderTelegraphMarkdown(entries, cap);
594
+ if (fitsTelegraphPage(markdown))
595
+ return markdown;
596
+ }
597
+ let keep = entries.length;
598
+ let markdown = this.renderTelegraphMarkdown(entries, 0);
599
+ while (keep > 1 && !fitsTelegraphPage(markdown)) {
600
+ keep = Math.ceil(keep / 2);
601
+ markdown = this.renderTelegraphMarkdown(entries, 0, entries.length - keep);
602
+ }
603
+ return markdown;
604
+ }
605
+ /**
606
+ * Render the action log as markdown for a Telegraph page, from the entries
607
+ * as captured โ€” no attempt to recover untruncated content. Each entry's
608
+ * input and output are cut to `bodyCap` characters, and left off at 0; the
609
+ * first `skip` entries are left off entirely.
610
+ */
611
+ renderTelegraphMarkdown(entries, bodyCap, skip = 0) {
612
+ const sections = [];
613
+ if (skip > 0) {
614
+ sections.push(`_${skip} earlier action${skip === 1 ? '' : 's'} left off to fit the page._`);
615
+ }
616
+ entries.slice(skip).forEach((entry, index) => {
617
+ const statusEmoji = entry.status === 'completed' ? 'โœ…' :
618
+ entry.status === 'error' ? 'โŒ' : 'โณ';
619
+ const time = new Date(entry.timestamp).toLocaleTimeString('en-US', {
620
+ hour12: false,
621
+ hour: '2-digit',
622
+ minute: '2-digit',
623
+ second: '2-digit',
624
+ });
625
+ const cut = (text) => text && bodyCap > 0
626
+ ? elideToolOutput(text, Infinity, bodyCap, { isError: entry.status === 'error' })
627
+ : undefined;
628
+ const subtitle = cut(entry.subtitle);
629
+ const content = cut(entry.content);
630
+ const headerLines = [];
631
+ headerLines.push(`## ${skip + index + 1}. ${entry.icon} ${statusEmoji} ${entry.title}`);
632
+ headerLines.push(`_${time}_`);
633
+ if (subtitle) {
634
+ headerLines.push('');
635
+ headerLines.push('```');
636
+ headerLines.push(subtitle);
637
+ headerLines.push('```');
638
+ }
639
+ if (content) {
640
+ headerLines.push('');
641
+ headerLines.push('```');
642
+ headerLines.push(content);
643
+ headerLines.push('```');
644
+ }
645
+ sections.push(headerLines.join('\n'));
646
+ });
647
+ return sections.join('\n\n---\n\n');
648
+ }
649
+ /**
650
+ * Render the collapsed in-chat summary line that replaces the live log.
651
+ */
652
+ renderCollapsedSummary(entries, pageUrl) {
653
+ const completed = entries.filter(e => e.status === 'completed').length;
654
+ const errors = entries.filter(e => e.status === 'error').length;
655
+ const counts = [`${entries.length} action${entries.length === 1 ? '' : 's'}`];
656
+ if (errors > 0)
657
+ counts.push(`${errors} error${errors === 1 ? '' : 's'}`);
658
+ else if (completed < entries.length)
659
+ counts.push(`${completed} completed`);
660
+ const summary = counts.join(' ยท ');
661
+ return new EntityText().add('๐Ÿ“‹ ').italic(summary).add(' ยท ').link('view full log', pageUrl).build();
662
+ }
663
+ /**
664
+ * Check if action logging is active for a session
665
+ */
666
+ isActive(sessionKey) {
667
+ return this.logStates.has(sessionKey);
668
+ }
669
+ /**
670
+ * Trim long absolute paths for display
671
+ */
672
+ stripWorkingDir(filePath) {
673
+ const cwd = process.cwd();
674
+ if (filePath.startsWith(cwd + '/'))
675
+ return filePath.slice(cwd.length + 1);
676
+ const home = process.env.HOME;
677
+ if (home && filePath.startsWith(home + '/'))
678
+ return '~/' + filePath.slice(home.length + 1);
679
+ return filePath;
680
+ }
681
+ }
682
+ // Export singleton instance
683
+ export const actionLogger = new ActionLogger();
684
+ //# sourceMappingURL=action-logger.js.map