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,502 @@
1
+ /**
2
+ * One live "background activity" card per session.
3
+ *
4
+ * Async work (monitors, backgrounded Bash, subagents, workflows)
5
+ * reports in from outside any user turn, so every arm, event and completion
6
+ * used to arrive as its own Telegram message — a monitor that fires ten times
7
+ * produced ten messages. This module folds all of it into a single message
8
+ * that is edited in place, the shape `ActionLogger` already gives a turn's
9
+ * tool output.
10
+ *
11
+ * Two things stop it from being a plain edit-forever accumulator:
12
+ *
13
+ * - Telegram raises no push notification for an edited message. A monitor
14
+ * exists to tell the user something happened, so a card that only ever
15
+ * edits goes silent on their phone.
16
+ * - Once anything else is posted the card is buried up-chat, and edits to a
17
+ * buried message are invisible.
18
+ *
19
+ * So the card *re-anchors*: it is sealed and re-posted fresh at the bottom
20
+ * when it goes stale (a turn ran) or when something notify-worthy lands and
21
+ * the current card has been on screen a while. Bursts collapse into one
22
+ * message; a genuinely new event still buzzes the phone. REANCHOR_FLOOR_MS is
23
+ * the knob trading notifications against message count.
24
+ *
25
+ * Nothing new may come in for a long while, though: a build in the background
26
+ * says nothing until it ends. So the card is also brought down when a turn
27
+ * closes or a command answers (bringCardDown), silently, as long as tasks run
28
+ * — the user is in the chat then, and a card above what they just read would
29
+ * leave them thinking nothing runs. A card that only listed running tasks is
30
+ * deleted once its successor is up, so the chat keeps one of them; a card
31
+ * with events on it stays where they happened.
32
+ */
33
+ import { GrammyError } from 'grammy';
34
+ import { EntityText, sliceMessage } from './entities.js';
35
+ import { sendFormatted, editFormatted } from './send.js';
36
+ import { parseSessionKey } from '../utils/session-key.js';
37
+ /**
38
+ * Minimum gap between edits of one card. Telegram tolerates roughly 20
39
+ * edits/minute per chat; 5s stays well clear while still reading as live.
40
+ */
41
+ const MIN_EDIT_INTERVAL_MS = 5_000;
42
+ /**
43
+ * How long a card must have been on screen before a notify-worthy event is
44
+ * allowed to re-anchor it. Under this, the event folds into the existing card
45
+ * — the user was pinged recently enough. Raise for a quieter chat, lower for
46
+ * more responsive notifications.
47
+ */
48
+ const REANCHOR_FLOOR_MS = 120_000;
49
+ /** Telegram refuses to edit messages older than 48h. Re-anchor well before. */
50
+ const MAX_CARD_AGE_MS = 24 * 60 * 60 * 1000;
51
+ /** Events kept on one card before the oldest scroll off. */
52
+ const MAX_EVENTS = 8;
53
+ const MAX_CARD_CHARS = 3800;
54
+ const MAX_DETAIL_CHARS = 400;
55
+ const MAX_TITLE_CHARS = 140;
56
+ const cards = new Map();
57
+ let botRef = null;
58
+ export function setBackgroundCardBot(bot) {
59
+ botRef = bot;
60
+ }
61
+ /** Register a newly armed background task so it shows as running on the card. */
62
+ export function noteTaskArmed(sessionKey, kind, description, toolUseId, startedAt = Date.now()) {
63
+ const state = getOrCreate(sessionKey);
64
+ if (!state)
65
+ return;
66
+ if (toolUseId) {
67
+ state.running.set(toolUseId, { kind, description, startedAt });
68
+ }
69
+ else {
70
+ // No tool_use_id means no terminal notification can ever be matched to
71
+ // it, so a running row would never clear. Record it as a one-off event
72
+ // instead of leaving a permanent ghost in the running list.
73
+ state.events.push({ at: Date.now(), icon: kindIcon(kind), title: `${kindLabel(kind)} started: ${description}` });
74
+ }
75
+ markDirty(state);
76
+ }
77
+ /** Retire a running task and record how it ended. */
78
+ export function noteTaskFinished(sessionKey, toolUseId, info, opts = {}) {
79
+ const state = getOrCreate(sessionKey);
80
+ if (!state)
81
+ return;
82
+ state.running.delete(toolUseId);
83
+ const verb = info.status === 'failed' ? 'failed'
84
+ : info.status === 'killed' || info.status === 'stopped' ? 'stopped'
85
+ : info.kind === 'monitor' ? 'ended' : 'done';
86
+ pushEvent(state, {
87
+ at: Date.now(),
88
+ icon: completionIcon(info.kind, info.status),
89
+ title: `${kindLabel(info.kind)} ${verb}: ${info.description} (${formatDuration(info.elapsedMs)})`,
90
+ }, opts);
91
+ }
92
+ /**
93
+ * Record a monitor firing. What Claude says about it is not the card's: the
94
+ * monitor relay sends that as a reply of its own, which a card could only
95
+ * hold cut short.
96
+ */
97
+ export function noteMonitorEvent(sessionKey, summary, detail, opts = {}) {
98
+ const state = getOrCreate(sessionKey);
99
+ if (!state)
100
+ return;
101
+ pushEvent(state, {
102
+ at: Date.now(),
103
+ icon: '📡',
104
+ title: summary ? `Monitor — ${summary}` : 'Monitor',
105
+ detail: detail || undefined,
106
+ }, opts);
107
+ }
108
+ /** Whether the session's card lists tasks still running. */
109
+ export function hasRunningTasks(sessionKey) {
110
+ return (cards.get(sessionKey)?.running.size ?? 0) > 0;
111
+ }
112
+ /**
113
+ * Post the card again at the bottom of the chat, silently, if tasks still run.
114
+ * Called after something was posted below it: a turn's reply, a command's.
115
+ * Returns whether there was a card to bring down.
116
+ */
117
+ export function bringCardDown(sessionKey, opts = {}) {
118
+ const state = cards.get(sessionKey);
119
+ if (!state || state.running.size === 0)
120
+ return false;
121
+ if (state.inFlight) {
122
+ state.bringDownPending = { withLog: opts.withLog || state.bringDownPending?.withLog };
123
+ return true;
124
+ }
125
+ if (state.flushTimer) {
126
+ clearTimeout(state.flushTimer);
127
+ state.flushTimer = null;
128
+ }
129
+ if (state.messageId !== null) {
130
+ // The live card moves as a whole, events and all.
131
+ state.retired.push(state.messageId);
132
+ state.messageId = null;
133
+ state.anchoredAt = 0;
134
+ }
135
+ else if (opts.withLog && state.sealedId !== null) {
136
+ state.events = [...state.sealedEvents, ...state.events].slice(-MAX_EVENTS);
137
+ state.retired.push(state.sealedId);
138
+ state.sealedId = null;
139
+ state.sealedEvents = [];
140
+ }
141
+ state.lastRendered = '';
142
+ state.silentNext = true;
143
+ markDirty(state);
144
+ return true;
145
+ }
146
+ /**
147
+ * Seal the current card and stop editing it. Called at turn boundaries: the
148
+ * turn pipeline is about to post (or has just posted) its own messages, which
149
+ * bury the card, so any later edit would land where nobody is looking.
150
+ *
151
+ * Running tasks survive into the next card; the event list does not — a fresh
152
+ * card is a fresh digest, not a replay of what is already in the scrollback.
153
+ */
154
+ export function sealCard(sessionKey) {
155
+ const state = cards.get(sessionKey);
156
+ if (!state)
157
+ return;
158
+ // Let the in-flight call finish and adopt its message id first; flush()
159
+ // re-enters here from its finally block.
160
+ if (state.inFlight) {
161
+ state.sealPending = true;
162
+ return;
163
+ }
164
+ if (state.flushTimer) {
165
+ clearTimeout(state.flushTimer);
166
+ state.flushTimer = null;
167
+ }
168
+ // Final edit so the sealed card is not left showing a stale intermediate
169
+ // state. Bypasses the throttle — turn boundaries are rare enough. A card
170
+ // with tasks still running gets it even when clean: its bottom line must
171
+ // stop saying they run here, since their end lands on the next card.
172
+ if (state.messageId !== null && (state.dirty || state.running.size > 0)) {
173
+ void editCard(state, state.messageId, renderCard(state, true));
174
+ }
175
+ if (state.messageId !== null) {
176
+ state.sealedId = state.messageId;
177
+ state.sealedEvents = state.events;
178
+ }
179
+ state.messageId = null;
180
+ state.anchoredAt = 0;
181
+ state.events = [];
182
+ state.lastRendered = '';
183
+ state.dirty = false;
184
+ }
185
+ /** Drop all card state for a session (teardown, /reset). */
186
+ export function clearCard(sessionKey) {
187
+ const state = cards.get(sessionKey);
188
+ if (!state)
189
+ return;
190
+ if (state.flushTimer)
191
+ clearTimeout(state.flushTimer);
192
+ state.epoch++;
193
+ cards.delete(sessionKey);
194
+ }
195
+ /** Test seam: read the live card state without exporting the map. */
196
+ export function _inspectCard(sessionKey) {
197
+ const state = cards.get(sessionKey);
198
+ if (!state)
199
+ return null;
200
+ return {
201
+ messageId: state.messageId,
202
+ running: state.running.size,
203
+ events: state.events.length,
204
+ text: renderCard(state).text,
205
+ };
206
+ }
207
+ function getOrCreate(sessionKey) {
208
+ const existing = cards.get(sessionKey);
209
+ if (existing)
210
+ return existing;
211
+ const { chatId, threadId } = parseSessionKey(sessionKey);
212
+ if (!Number.isFinite(chatId))
213
+ return null;
214
+ const state = {
215
+ sessionKey,
216
+ chatId,
217
+ threadId,
218
+ messageId: null,
219
+ anchoredAt: 0,
220
+ running: new Map(),
221
+ events: [],
222
+ lastEditAt: 0,
223
+ rateLimitedUntil: 0,
224
+ flushTimer: null,
225
+ dirty: false,
226
+ inFlight: false,
227
+ lastRendered: '',
228
+ epoch: 0,
229
+ sealPending: false,
230
+ bringDownPending: null,
231
+ sealedId: null,
232
+ sealedEvents: [],
233
+ retired: [],
234
+ silentNext: false,
235
+ };
236
+ cards.set(sessionKey, state);
237
+ return state;
238
+ }
239
+ function pushEvent(state, event, opts) {
240
+ // Re-anchor before appending so the new event lands on the fresh card
241
+ // rather than on the one about to be sealed.
242
+ if (opts.notify && shouldReanchor(state, opts.urgent === true))
243
+ sealCard(state.sessionKey);
244
+ // Something did happen: whatever posts the card next should buzz.
245
+ if (opts.notify)
246
+ state.silentNext = false;
247
+ state.events.push(event);
248
+ if (state.events.length > MAX_EVENTS)
249
+ state.events = state.events.slice(-MAX_EVENTS);
250
+ markDirty(state);
251
+ }
252
+ function shouldReanchor(state, urgent) {
253
+ // Nothing anchored yet — the next flush posts fresh (and notifies) anyway.
254
+ if (state.messageId === null)
255
+ return false;
256
+ if (urgent)
257
+ return true;
258
+ return Date.now() - state.anchoredAt >= REANCHOR_FLOOR_MS;
259
+ }
260
+ function markDirty(state) {
261
+ state.dirty = true;
262
+ scheduleFlush(state);
263
+ }
264
+ function scheduleFlush(state) {
265
+ if (state.flushTimer || state.inFlight)
266
+ return;
267
+ const now = Date.now();
268
+ // The first post of a card lands immediately; only edits are throttled.
269
+ const earliest = state.messageId === null
270
+ ? Math.max(now, state.rateLimitedUntil)
271
+ : Math.max(state.lastEditAt + MIN_EDIT_INTERVAL_MS, state.rateLimitedUntil);
272
+ const delay = Math.max(0, earliest - now);
273
+ if (delay === 0) {
274
+ void flush(state);
275
+ return;
276
+ }
277
+ state.flushTimer = setTimeout(() => {
278
+ state.flushTimer = null;
279
+ void flush(state);
280
+ }, delay);
281
+ // Never hold the process open for a pending cosmetic edit.
282
+ state.flushTimer.unref?.();
283
+ }
284
+ async function flush(state) {
285
+ if (!botRef || state.inFlight || !state.dirty)
286
+ return;
287
+ // Telegram rejects edits to messages past 48h outright; drop the anchor
288
+ // early so this turns into a fresh post instead of a guaranteed failure.
289
+ if (state.messageId !== null && Date.now() - state.anchoredAt > MAX_CARD_AGE_MS) {
290
+ state.messageId = null;
291
+ state.lastRendered = '';
292
+ }
293
+ const card = renderCard(state);
294
+ const text = card.text;
295
+ if (state.messageId !== null && text === state.lastRendered) {
296
+ state.dirty = false;
297
+ return;
298
+ }
299
+ const epoch = state.epoch;
300
+ state.inFlight = true;
301
+ state.dirty = false;
302
+ try {
303
+ if (state.messageId === null) {
304
+ const messageId = await sendCard(state, card, state.silentNext);
305
+ // Torn down while the send was in flight — the session is gone, so
306
+ // there is nothing left to adopt this message id.
307
+ if (epoch !== state.epoch)
308
+ return;
309
+ if (messageId !== null) {
310
+ state.messageId = messageId;
311
+ state.anchoredAt = Date.now();
312
+ state.lastEditAt = Date.now();
313
+ state.lastRendered = text;
314
+ state.silentNext = false;
315
+ retireReplaced(state);
316
+ }
317
+ }
318
+ else {
319
+ const ok = await editCard(state, state.messageId, card);
320
+ if (epoch !== state.epoch)
321
+ return;
322
+ state.lastEditAt = Date.now();
323
+ if (ok)
324
+ state.lastRendered = text;
325
+ }
326
+ }
327
+ finally {
328
+ state.inFlight = false;
329
+ const seal = state.sealPending;
330
+ const bringDown = state.bringDownPending;
331
+ state.sealPending = false;
332
+ state.bringDownPending = null;
333
+ if (seal)
334
+ sealCard(state.sessionKey);
335
+ if (bringDown && epoch === state.epoch) {
336
+ bringCardDown(state.sessionKey, bringDown);
337
+ }
338
+ else if (!seal && state.dirty && epoch === state.epoch) {
339
+ scheduleFlush(state);
340
+ }
341
+ }
342
+ }
343
+ /**
344
+ * Delete what the card just posted replaces: a card it moved down from, and
345
+ * the last sealed card if all that one held was the running list, which the
346
+ * new card shows as well.
347
+ */
348
+ function retireReplaced(state) {
349
+ const ids = [...state.retired];
350
+ if (state.sealedId !== null && state.sealedEvents.length === 0)
351
+ ids.push(state.sealedId);
352
+ state.retired = [];
353
+ state.sealedId = null;
354
+ state.sealedEvents = [];
355
+ const bot = botRef;
356
+ if (!bot)
357
+ return;
358
+ for (const id of ids) {
359
+ // Past 48h Telegram refuses, and the user may have deleted it already;
360
+ // either way it stays as it is, sealed.
361
+ Promise.resolve()
362
+ .then(() => bot.api.deleteMessage(state.chatId, id))
363
+ .catch((err) => console.debug('[BackgroundCard] delete failed:', describe(err)));
364
+ }
365
+ }
366
+ /**
367
+ * Post the card. A card whose formatting Telegram refuses goes out again as
368
+ * plain text (see ./send.ts).
369
+ */
370
+ async function sendCard(state, card, silent) {
371
+ if (!botRef)
372
+ return null;
373
+ const opts = {
374
+ ...(state.threadId !== undefined ? { message_thread_id: state.threadId } : {}),
375
+ ...(silent ? { disable_notification: true } : {}),
376
+ };
377
+ try {
378
+ const msg = await sendFormatted(botRef.api, state.chatId, card, opts);
379
+ return msg.message_id;
380
+ }
381
+ catch (err) {
382
+ if (noteRateLimit(state, err))
383
+ return null;
384
+ console.error('[BackgroundCard] send failed:', describe(err));
385
+ return null;
386
+ }
387
+ }
388
+ async function editCard(state, messageId, card) {
389
+ if (!botRef)
390
+ return false;
391
+ try {
392
+ await editFormatted(botRef.api, state.chatId, messageId, card);
393
+ return true;
394
+ }
395
+ catch (err) {
396
+ if (noteRateLimit(state, err))
397
+ return false;
398
+ const msg = describe(err).toLowerCase();
399
+ // Already showing this content — the render matched what is on screen.
400
+ if (msg.includes('not modified'))
401
+ return true;
402
+ // The card was deleted out from under us; drop the anchor so the next
403
+ // flush posts a fresh one rather than retrying a dead message id.
404
+ if (msg.includes('message to edit not found') || msg.includes('message_id_invalid')) {
405
+ state.messageId = null;
406
+ state.lastRendered = '';
407
+ return false;
408
+ }
409
+ console.error('[BackgroundCard] edit failed:', describe(err));
410
+ return false;
411
+ }
412
+ }
413
+ /** Record Telegram's retry_after so scheduleFlush backs off instead of hammering. */
414
+ function noteRateLimit(state, err) {
415
+ if (!(err instanceof GrammyError) || err.error_code !== 429)
416
+ return false;
417
+ const retryAfter = err.parameters.retry_after ?? 60;
418
+ state.rateLimitedUntil = Date.now() + retryAfter * 1000;
419
+ state.dirty = true;
420
+ console.warn(`[BackgroundCard] rate limited, backing off for ${retryAfter}s`);
421
+ return true;
422
+ }
423
+ function describe(err) {
424
+ return err instanceof Error ? err.message : String(err);
425
+ }
426
+ /**
427
+ * The card's bottom line, saying whether anything is still running. The card
428
+ * grows downward and the running list sits at its top, so on a long card the
429
+ * bottom is the only part on screen, and without this line a finished card
430
+ * looked the same as a busy one.
431
+ */
432
+ function statusLine(running, sealed, empty) {
433
+ if (running === 0)
434
+ return empty ? '✅ Nothing running' : '✅ All done';
435
+ const tasks = `${running} task${running === 1 ? '' : 's'}`;
436
+ return sealed ? `⏳ ${tasks} still running · updates continue below` : `⏳ ${tasks} running`;
437
+ }
438
+ function renderCard(state, sealed = false) {
439
+ for (let limit = state.events.length; limit >= 0; limit--) {
440
+ const card = renderCardAt(state, limit, sealed);
441
+ if (card.text.length <= MAX_CARD_CHARS)
442
+ return card;
443
+ }
444
+ return sliceMessage(renderCardAt(state, 0, sealed), 0, MAX_CARD_CHARS);
445
+ }
446
+ function renderCardAt(state, eventLimit, sealed) {
447
+ const b = new EntityText().add('📡 ').bold('Background activity');
448
+ const running = [...state.running.values()].sort((a, b) => a.startedAt - b.startedAt);
449
+ if (running.length > 0) {
450
+ b.newline();
451
+ const now = Date.now();
452
+ for (const task of running) {
453
+ const label = `${kindLabel(task.kind)}: ${truncate(task.description, MAX_TITLE_CHARS)}`;
454
+ b.newline().add(`${kindIcon(task.kind)} ${label} · `).italic(`running ${formatDuration(now - task.startedAt)}`);
455
+ }
456
+ }
457
+ const shown = eventLimit > 0 ? state.events.slice(-eventLimit) : [];
458
+ const dropped = state.events.length - shown.length;
459
+ if (dropped > 0) {
460
+ b.newline(2).italic(`… ${dropped} earlier event${dropped === 1 ? '' : 's'}`);
461
+ }
462
+ for (const event of shown) {
463
+ b.newline(2).add(`${event.icon} `).italic(clockTime(event.at)).add(` ${truncate(event.title, MAX_TITLE_CHARS)}`);
464
+ if (event.detail) {
465
+ b.newline().pre(truncate(event.detail, MAX_DETAIL_CHARS));
466
+ }
467
+ }
468
+ const empty = running.length === 0 && shown.length === 0 && dropped === 0;
469
+ b.newline(2).italic(statusLine(running.length, sealed, empty));
470
+ return b.build();
471
+ }
472
+ function kindIcon(kind) {
473
+ return kind === 'monitor' ? '📡'
474
+ : kind === 'bash_background' ? '⚙️'
475
+ : kind === 'workflow' ? '📋'
476
+ : '🤖';
477
+ }
478
+ function kindLabel(kind) {
479
+ return kind === 'monitor' ? 'Monitor'
480
+ : kind === 'bash_background' ? 'Backgrounded'
481
+ : kind === 'workflow' ? 'Workflow'
482
+ : 'Subagent';
483
+ }
484
+ function completionIcon(kind, status) {
485
+ if (status === 'failed')
486
+ return '❌';
487
+ if (status === 'killed' || status === 'stopped')
488
+ return '🛑';
489
+ return kind === 'monitor' ? '📡' : '✅';
490
+ }
491
+ export function formatDuration(elapsedMs) {
492
+ const seconds = Math.max(0, Math.round(elapsedMs / 1000));
493
+ return seconds >= 60 ? `${Math.floor(seconds / 60)}m ${seconds % 60}s` : `${seconds}s`;
494
+ }
495
+ function clockTime(at) {
496
+ return new Date(at).toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' });
497
+ }
498
+ function truncate(text, max) {
499
+ const trimmed = text.trim();
500
+ return trimmed.length > max ? trimmed.slice(0, max - 3) + '...' : trimmed;
501
+ }
502
+ //# sourceMappingURL=background-activity-card.js.map