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,67 @@
1
+ /**
2
+ * Cold-start auto-continue.
3
+ *
4
+ * Unlike auto-resume this runs on every startup, marker or not, and it never
5
+ * says a word: a restart shouldn't change which conversation a chat is in, so
6
+ * every chat used within the restore window carries straight on where it left
7
+ * off. Whoever wants a clean slate sends /clear. Auto-resume only covers
8
+ * sessions idle under an hour, and only after /botrebuild or /botrestart —
9
+ * this is what brings back everything else.
10
+ */
11
+ import { sessionManager, RESTORE_MAX_IDLE_MS } from '../claude/session-manager.js';
12
+ import { sessionHistory } from '../claude/session-history.js';
13
+ import { parseSessionKey } from '../utils/session-key.js';
14
+ import { allowedChatIds } from './shared.js';
15
+ /**
16
+ * Cold-start auto-continue. For every chat with a prior session belonging to
17
+ * this instance:
18
+ * - idle ≤ 7d → silently restore in memory (no chat noise)
19
+ * - idle > 7d → skip (the chat can /resume it)
20
+ *
21
+ * Sessions already live in memory are skipped — that covers both the ones
22
+ * autoResumeAfterReload just restored (they got the fuller "Reloaded and
23
+ * session restored" recap) and the ones notifyInterruptedSessions revived.
24
+ */
25
+ export function autoContinueOnStartup() {
26
+ const activeSessions = sessionHistory.getAllActiveSessions();
27
+ const allowedIds = allowedChatIds();
28
+ let restored = 0;
29
+ const skipped = { notAllowed: 0, alreadyLive: 0, noClaudeSessionId: 0, tooOld: 0, threw: 0 };
30
+ for (const [sessionKey, entry] of activeSessions) {
31
+ const { chatId } = parseSessionKey(sessionKey);
32
+ if (!allowedIds.has(chatId)) {
33
+ skipped.notAllowed++;
34
+ continue;
35
+ }
36
+ if (sessionManager.getSession(sessionKey)) {
37
+ skipped.alreadyLive++;
38
+ continue;
39
+ }
40
+ // Nothing said in it yet: the chat's next message brings the project back
41
+ // on its own, through the same restore window.
42
+ if (!entry.claudeSessionId) {
43
+ skipped.noClaudeSessionId++;
44
+ continue;
45
+ }
46
+ const idleMs = Date.now() - new Date(entry.lastActivity).getTime();
47
+ if (idleMs < 0 || idleMs > RESTORE_MAX_IDLE_MS) {
48
+ skipped.tooOld++;
49
+ continue;
50
+ }
51
+ try {
52
+ sessionManager.resumeLastSession(sessionKey);
53
+ restored++;
54
+ }
55
+ catch (err) {
56
+ console.error(`[AutoContinue] Restore failed for ${sessionKey}:`, err);
57
+ skipped.threw++;
58
+ }
59
+ }
60
+ const skipSummary = Object.entries(skipped)
61
+ .filter(([, n]) => n > 0)
62
+ .map(([k, n]) => `${k}=${n}`)
63
+ .join(', ');
64
+ console.log(`[AutoContinue] restored=${restored}, total=${activeSessions.size}` +
65
+ (skipSummary ? `, skipped(${skipSummary})` : ''));
66
+ }
67
+ //# sourceMappingURL=auto-continue.js.map
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Auto-resume after /botrebuild or /botrestart.
3
+ *
4
+ * The restarting worker (or the launcher, for a restart-all) leaves a reload
5
+ * marker on disk. Finding a *fresh* one here is what distinguishes a
6
+ * user-initiated restart from a crash respawn or a plain pm2 restart, so only
7
+ * this path posts the "Reloaded and session restored" recap.
8
+ */
9
+ import * as fs from 'fs';
10
+ import * as path from 'path';
11
+ import { getReloadMarkerPath } from '../config.js';
12
+ import { sessionManager } from '../claude/session-manager.js';
13
+ import { sessionHistory } from '../claude/session-history.js';
14
+ import { clearConversation } from '../providers/provider-router.js';
15
+ import { parseSessionKey } from '../utils/session-key.js';
16
+ import { describeRunningBuild } from '../utils/build-info.js';
17
+ import { setSessionTopic } from '../bot/handlers/command/topic-store.js';
18
+ import { getEffortLabel } from '../bot/handlers/command.handler.js';
19
+ import { sendParts } from '../telegram/send.js';
20
+ import { taskListDisplay } from '../telegram/task-list.js';
21
+ import { allowedChatIds, threadOpts, sendBlockWithPlainFallback } from './shared.js';
22
+ const RELOAD_MARKER_MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes
23
+ /**
24
+ * Restore sessions flagged by a fresh reload marker.
25
+ *
26
+ * Returns whether a fresh marker was found and consumed — the caller uses that
27
+ * to decide whether the restart itself warrants a confirmation message.
28
+ */
29
+ export async function autoResumeAfterReload(bot, notified) {
30
+ const markerFile = getReloadMarkerPath();
31
+ if (!fs.existsSync(markerFile)) {
32
+ console.log(`[AutoResume] No reload marker at ${markerFile} — skipping auto-resume`);
33
+ return false;
34
+ }
35
+ let marker;
36
+ try {
37
+ const raw = fs.readFileSync(markerFile, 'utf-8');
38
+ marker = JSON.parse(raw);
39
+ }
40
+ catch (err) {
41
+ console.warn(`[AutoResume] Marker file ${markerFile} is unreadable, deleting:`, err instanceof Error ? err.message : err);
42
+ try {
43
+ fs.unlinkSync(markerFile);
44
+ }
45
+ catch { }
46
+ return false;
47
+ }
48
+ // Validate timestamp freshness
49
+ const age = Date.now() - new Date(marker.timestamp).getTime();
50
+ if (age > RELOAD_MARKER_MAX_AGE_MS || age < 0) {
51
+ console.log(`[AutoResume] Stale marker (age=${age}ms, max=${RELOAD_MARKER_MAX_AGE_MS}ms), ignoring`);
52
+ try {
53
+ fs.unlinkSync(markerFile);
54
+ }
55
+ catch { }
56
+ return false;
57
+ }
58
+ console.log(`[AutoResume] Found fresh marker (age=${Math.round(age / 1000)}s), evaluating sessions for restore`);
59
+ // Delete marker immediately to prevent double-processing or crash loops
60
+ try {
61
+ fs.unlinkSync(markerFile);
62
+ }
63
+ catch { }
64
+ // Resume all recent active sessions that belong to this instance
65
+ const activeSessions = sessionHistory.getAllActiveSessions();
66
+ const allowedIds = allowedChatIds();
67
+ console.log(`[AutoResume] ${activeSessions.size} candidate session(s) in history; allowlist size=${allowedIds.size}`);
68
+ let resumed = 0;
69
+ const skipped = { notAllowed: 0, idle: 0, noClaudeSessionId: 0, resumeReturnedUndefined: 0, threw: 0 };
70
+ for (const [sessionKey, newest] of activeSessions) {
71
+ const { chatId, threadId } = parseSessionKey(sessionKey);
72
+ // Only resume sessions belonging to this bot instance
73
+ if (!allowedIds.has(chatId)) {
74
+ console.log(`[AutoResume] skip ${sessionKey}: chatId ${chatId} not in this bot's allowlist`);
75
+ skipped.notAllowed++;
76
+ continue;
77
+ }
78
+ // Resume the most recent entry that actually carries a claudeSessionId. The
79
+ // newest entry can be a stub from a conversation that never finished init
80
+ // (a query interrupted by the rebuild itself, an aborted /clear) — falling
81
+ // back past it restores the healthy session sitting one slot back instead
82
+ // of going silent on the whole chat.
83
+ const entry = sessionHistory.getLastResumableSession(sessionKey);
84
+ if (!entry) {
85
+ console.log(`[AutoResume] skip ${sessionKey}: no history entry has a claudeSessionId (newest conversationId=${newest.conversationId}, project=${newest.projectName}) — no completed session to resume`);
86
+ skipped.noClaudeSessionId++;
87
+ continue;
88
+ }
89
+ // Only resume sessions with recent activity (within last hour). Measured
90
+ // against the resumable entry, not a fresher stub, so we don't revive a
91
+ // long-stale conversation just because an aborted one touched the chat.
92
+ const lastActivity = new Date(entry.lastActivity).getTime();
93
+ const idleMs = Date.now() - lastActivity;
94
+ if (idleMs > 60 * 60 * 1000) {
95
+ console.log(`[AutoResume] skip ${sessionKey}: idle for ${Math.round(idleMs / 60000)}min (cutoff=60min, lastActivity=${entry.lastActivity})`);
96
+ skipped.idle++;
97
+ continue;
98
+ }
99
+ try {
100
+ const session = sessionManager.resumeSession(sessionKey, entry.conversationId);
101
+ if (!session) {
102
+ console.warn(`[AutoResume] skip ${sessionKey}: sessionManager.resumeSession returned undefined (history entry exists with claudeSessionId=${entry.claudeSessionId})`);
103
+ skipped.resumeReturnedUndefined++;
104
+ continue;
105
+ }
106
+ console.log(`[AutoResume] resuming ${sessionKey}: project=${entry.projectName}, claudeSessionId=${entry.claudeSessionId}, idle=${Math.round(idleMs / 1000)}s`);
107
+ clearConversation(sessionKey);
108
+ // Restore the topic in memory, for the status line and the thread name.
109
+ setSessionTopic(sessionKey, entry.topic || '');
110
+ const projectName = path.basename(session.workingDirectory);
111
+ const opts = threadOpts(threadId);
112
+ // Header: plain status text, sent without formatting so topic/project
113
+ // names go out verbatim. Kept compact (no prompt body) so a long stored
114
+ // prompt doesn't blow past the 4096-char limit; the prompt is delivered
115
+ // in its own chunked block below.
116
+ let header = `✅ Reloaded and session restored: ${projectName}`;
117
+ if (entry.topic) {
118
+ header += ` (topic: ${entry.topic})`;
119
+ }
120
+ const effortLabel = getEffortLabel(sessionKey);
121
+ if (effortLabel) {
122
+ header += `\nEffort: ${effortLabel}`;
123
+ }
124
+ const build = describeRunningBuild();
125
+ if (build) {
126
+ header += `\nVersion: ${build}`;
127
+ }
128
+ await sendParts(bot.api, chatId, header, opts);
129
+ // Last prompt: deliver the full stored prompt as its own message
130
+ // (chunked if long). User input is treated as literal text — sent
131
+ // plain rather than rendered as markdown so a literal `*` or `_` doesn't
132
+ // become formatting noise.
133
+ if (entry.lastMessagePreview) {
134
+ await bot.api.sendMessage(chatId, '📝 Last prompt:', opts);
135
+ await sendBlockWithPlainFallback(bot, chatId, opts, entry.lastMessagePreview, 'AutoResume');
136
+ }
137
+ // Assistant preview: re-render the markdown as entities (mirrors
138
+ // how messageSender.sendMessage delivers normal responses) so bold/code/
139
+ // links survive the resume.
140
+ if (entry.lastAssistantPreview) {
141
+ await bot.api.sendMessage(chatId, '💬 Last response:', opts);
142
+ await sendBlockWithPlainFallback(bot, chatId, opts, entry.lastAssistantPreview, 'AutoResume', 'render');
143
+ }
144
+ await taskListDisplay.showRestored(bot.api, sessionKey, session.claudeSessionId);
145
+ resumed++;
146
+ notified.add(sessionKey);
147
+ }
148
+ catch (err) {
149
+ console.error(`[AutoResume] Failed to resume ${sessionKey}:`, err);
150
+ skipped.threw++;
151
+ }
152
+ }
153
+ const skipSummary = Object.entries(skipped)
154
+ .filter(([, n]) => n > 0)
155
+ .map(([k, n]) => `${k}=${n}`)
156
+ .join(', ');
157
+ console.log(`[AutoResume] Done: restored=${resumed}/${activeSessions.size}` +
158
+ (skipSummary ? `, skipped(${skipSummary})` : ''));
159
+ return true;
160
+ }
161
+ //# sourceMappingURL=auto-resume.js.map
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The two startup messages that aren't about restoring a session: warning a
3
+ * chat that its task was cut off mid-run, and confirming a user-initiated
4
+ * restart actually landed.
5
+ *
6
+ * Both consult the `notified` set the session-restore paths fill in, so a chat
7
+ * that already heard from us this startup doesn't get piled on.
8
+ */
9
+ import { config } from '../config.js';
10
+ import { sessionManager } from '../claude/session-manager.js';
11
+ import { sessionHistory } from '../claude/session-history.js';
12
+ import { consumeAllInFlight } from '../claude/in-flight-tracker.js';
13
+ import { parseSessionKey } from '../utils/session-key.js';
14
+ import { describeRunningBuild } from '../utils/build-info.js';
15
+ import { taskListDisplay } from '../telegram/task-list.js';
16
+ import { allowedChatIds, threadOpts, sendBlockWithPlainFallback } from './shared.js';
17
+ /**
18
+ * If a task was running when the bot exited (clean or crash), surface that
19
+ * to the affected chat so the user knows their last prompt may not have
20
+ * completed. Also ensures the session is restored in memory so the next
21
+ * message arrives at a live session.
22
+ */
23
+ export async function notifyInterruptedSessions(bot, notified) {
24
+ const interrupted = consumeAllInFlight();
25
+ if (interrupted.length === 0)
26
+ return;
27
+ const allowedIds = allowedChatIds();
28
+ for (const entry of interrupted) {
29
+ const { chatId, threadId } = parseSessionKey(entry.sessionKey);
30
+ if (!allowedIds.has(chatId))
31
+ continue;
32
+ // Auto-resume already showed this session's task list with its recap.
33
+ const listShown = notified.has(entry.sessionKey);
34
+ // Make sure the session is live in memory so the user can immediately reply.
35
+ if (!sessionManager.getSession(entry.sessionKey)) {
36
+ sessionManager.resumeLastSession(entry.sessionKey);
37
+ }
38
+ const opts = threadOpts(threadId);
39
+ const text = '⚠️ I was interrupted while running a task. The last action may not have completed.';
40
+ try {
41
+ await bot.api.sendMessage(chatId, text, opts);
42
+ notified.add(entry.sessionKey);
43
+ }
44
+ catch (err) {
45
+ console.error(`[InFlight] Failed to notify ${entry.sessionKey}:`, err);
46
+ }
47
+ // Deliver the interrupted prompt as its own chunked block so long prompts
48
+ // survive intact rather than getting clipped into the header.
49
+ if (entry.messagePreview) {
50
+ try {
51
+ await bot.api.sendMessage(chatId, '📝 Last prompt:', opts);
52
+ await sendBlockWithPlainFallback(bot, chatId, opts, entry.messagePreview, 'InFlight');
53
+ }
54
+ catch (err) {
55
+ console.error(`[InFlight] Failed to deliver prompt for ${entry.sessionKey}:`, err);
56
+ }
57
+ }
58
+ if (!listShown) {
59
+ const claudeSessionId = sessionManager.getSession(entry.sessionKey)?.claudeSessionId;
60
+ await taskListDisplay.showRestored(bot.api, entry.sessionKey, claudeSessionId);
61
+ }
62
+ }
63
+ }
64
+ /**
65
+ * Confirm a user-initiated restart in Telegram.
66
+ *
67
+ * Apart from this, only the resume recap and the interrupted-task warning speak
68
+ * on startup, and the recap only for a session idle under an hour — a chat that
69
+ * carries on silently, or one quiet for longer than the restore window, hears
70
+ * nothing. After an explicit /botrebuild or /botrestart that reads as "did my
71
+ * restart even land?", especially for `all`, where five sibling instances
72
+ * restart with no visible sign either way. Like the recap, it says which build
73
+ * came back, since landing on the wrong one reads just the same.
74
+ *
75
+ * Sends to the most recently active chat this instance serves, and only when
76
+ * that chat heard nothing else this startup — so a chat that already got the
77
+ * resume recap or the interrupted-task warning doesn't get a redundant second
78
+ * message.
79
+ *
80
+ * Gated on the caller having seen a fresh reload marker, so crash-loop
81
+ * respawns and plain pm2 restarts stay quiet.
82
+ */
83
+ export async function notifyRestartComplete(bot, notified) {
84
+ const allowedIds = allowedChatIds();
85
+ // getAllActiveSessions is keyed in insertion order, not recency — pick the
86
+ // genuinely most-recent chat, since that's the one the user most plausibly
87
+ // ran the command from.
88
+ let target;
89
+ let newest = -Infinity;
90
+ for (const [sessionKey, entry] of sessionHistory.getAllActiveSessions()) {
91
+ const { chatId } = parseSessionKey(sessionKey);
92
+ if (!allowedIds.has(chatId))
93
+ continue;
94
+ const lastActivity = new Date(entry.lastActivity).getTime();
95
+ if (!Number.isFinite(lastActivity) || lastActivity <= newest)
96
+ continue;
97
+ newest = lastActivity;
98
+ target = sessionKey;
99
+ }
100
+ if (!target) {
101
+ console.log('[Restart] No active chat to notify — skipping restart confirmation');
102
+ return;
103
+ }
104
+ if (notified.has(target)) {
105
+ console.log(`[Restart] ${target} already heard from us this startup — skipping restart confirmation`);
106
+ return;
107
+ }
108
+ const { chatId, threadId } = parseSessionKey(target);
109
+ const opts = threadOpts(threadId);
110
+ const build = describeRunningBuild();
111
+ try {
112
+ // Plain text, no formatting to carry.
113
+ await bot.api.sendMessage(chatId, `✅ ${config.BOT_NAME} restarted and is ready.` + (build ? `\nVersion: ${build}` : ''), opts);
114
+ console.log(`[Restart] Confirmed restart to ${target}`);
115
+ }
116
+ catch (err) {
117
+ console.error(`[Restart] Failed to confirm restart to ${target}:`, err);
118
+ }
119
+ }
120
+ //# sourceMappingURL=notices.js.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Helpers shared by the startup routines that speak to Telegram.
3
+ *
4
+ * Each of auto-resume, auto-continue, the interrupted-task notice and the
5
+ * restart confirmation had its own copy of the allowlist set and the
6
+ * thread-options object, and three of them repeated the same chunked
7
+ * delivery loop.
8
+ */
9
+ import { config } from '../config.js';
10
+ import { sendParts, sendMarkdown } from '../telegram/send.js';
11
+ /** Chat ids this instance is allowed to talk to — users and groups combined. */
12
+ export function allowedChatIds() {
13
+ return new Set([
14
+ ...config.ALLOWED_USER_IDS,
15
+ ...config.ALLOWED_GROUP_IDS,
16
+ ]);
17
+ }
18
+ /** Thread-scoping options for a send, empty when the chat has no thread. */
19
+ export function threadOpts(threadId) {
20
+ return threadId !== undefined ? { message_thread_id: threadId } : {};
21
+ }
22
+ /**
23
+ * Deliver a possibly-long block of text, split into as many messages as it
24
+ * needs.
25
+ *
26
+ * `mode` picks how the text is formatted: 'escape' treats it as literal user
27
+ * input (so a stray `*` stays a `*`), 'render' runs it through the same
28
+ * markdown-to-entities conversion normal assistant responses use, preserving
29
+ * bold/code/links. A part whose formatting Telegram refuses goes out again as
30
+ * plain text (see ../telegram/send.ts).
31
+ */
32
+ export async function sendBlockWithPlainFallback(bot, chatId, opts, text, label, mode = 'escape') {
33
+ try {
34
+ if (mode === 'render')
35
+ await sendMarkdown(bot.api, chatId, text, opts);
36
+ else
37
+ await sendParts(bot.api, chatId, text, opts);
38
+ }
39
+ catch (error) {
40
+ console.error(`[${label}] Failed to deliver block:`, error);
41
+ throw error;
42
+ }
43
+ }
44
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Ask Telegram who we are before anything else starts.
3
+ *
4
+ * A token with the right shape can still be revoked, or belong to a bot that
5
+ * was deleted. That used to surface from `bot.init()` as a grammY stack trace,
6
+ * after the IPC server was already listening. Checking first means a bad
7
+ * token stops the bot with one sentence and nothing to clean up, and the
8
+ * answer is handed to createBot so the check costs no extra request.
9
+ */
10
+ import { Api } from 'grammy';
11
+ import { config } from '../config.js';
12
+ import { telegramClientOptions, telegramProxyUrl } from '../telegram/client-options.js';
13
+ import { describeTokenCheckFailure } from '../utils/bot-token.js';
14
+ import { EXIT_TELEGRAM_UNAVAILABLE, exitForConfigError } from '../utils/exit-codes.js';
15
+ /** getMe with the bot's own token and proxy, or exit with a plain-language reason. */
16
+ export async function verifyBotTokenOrExit() {
17
+ const api = new Api(config.TELEGRAM_BOT_TOKEN, { ...telegramClientOptions(), timeoutSeconds: 30 });
18
+ try {
19
+ return await api.getMe();
20
+ }
21
+ catch (err) {
22
+ const failure = describeTokenCheckFailure(err, telegramProxyUrl());
23
+ console.error(`❌ ${failure.message}`);
24
+ // A rejected token stays rejected; a network failure or a Telegram error
25
+ // might not, so it exits for whatever restarts the bot to try again.
26
+ if (failure.fatal)
27
+ exitForConfigError();
28
+ process.exit(EXIT_TELEGRAM_UNAVAILABLE);
29
+ }
30
+ }
31
+ //# sourceMappingURL=verify-token.js.map
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The card an admin taps to let someone in.
3
+ *
4
+ * A stranger who speaks in the shared group is, on a bot shared with friends,
5
+ * almost always someone who was just added to it. Answering them with nothing
6
+ * but "⛔ You are not authorized" leaves the admin to notice, ask for their
7
+ * numeric id, edit `.env` and restart — four steps, three of them off Telegram,
8
+ * for what is socially a nod.
9
+ *
10
+ * So the denial carries an approval card instead: who they are, where they
11
+ * turned up, and two buttons. It mentions its admins by numeric id for the same
12
+ * reason the permission gate does — the group is muted, and a card nobody is
13
+ * notified about is a card answered tomorrow.
14
+ *
15
+ * The card is only ever posted in an allow-listed group. A stranger who finds
16
+ * the bot in a private chat gets the flat denial and no card: an approval
17
+ * request that only its subject can see is not a request, and posting one per
18
+ * unknown DM is a way to have strangers ring the admin's phone.
19
+ */
20
+ import { config } from '../config.js';
21
+ import { getAdminIds } from '../utils/admins.js';
22
+ import { describeUser, noteSeenUser } from '../utils/user-roster.js';
23
+ import { BoundedMap } from '../utils/bounded-map.js';
24
+ import { sanitizeError } from '../utils/sanitize.js';
25
+ import { resolveApproversInChat, appendApproverLine } from './admin-mention.js';
26
+ import { EntityText, clip } from './entities.js';
27
+ /** Callback data prefix for the card's buttons. Matched in bot.ts. */
28
+ export const ACCESS_CALLBACK_PREFIX = 'access';
29
+ /**
30
+ * How long before a stranger who keeps talking earns a second card. Long
31
+ * enough that a burst of messages posts one card, short enough that an admin
32
+ * who scrolled past the first still gets another within the hour.
33
+ */
34
+ const RE_ASK_MS = 30 * 60 * 1000;
35
+ /**
36
+ * Bounded because the keys are (chat, stranger) pairs and a stranger is
37
+ * whoever turns up — an unbounded map here would be a slow leak driven by
38
+ * people the bot has already turned away.
39
+ */
40
+ const lastAsked = new BoundedMap(500);
41
+ function askKey(chatId, userId) {
42
+ return `${chatId}:${userId}`;
43
+ }
44
+ /** Longest display name the card will render before clipping. */
45
+ const MAX_NAME_CHARS = 64;
46
+ /**
47
+ * Lay out the card. Exported for tests — the wording and the entity offsets are
48
+ * the whole product, and both are worth pinning down.
49
+ */
50
+ export function buildAccessRequestMessage(parts) {
51
+ const b = new EntityText();
52
+ const { user } = parts;
53
+ b.add('👋 ').bold('Access requested').newline();
54
+ const name = user.name ? clip(user.name, MAX_NAME_CHARS) : undefined;
55
+ if (name) {
56
+ // A text_mention rather than plain text: it renders as a link to their
57
+ // profile, which is how an admin tells two people with the same first name
58
+ // apart before deciding.
59
+ b.mention(name, user.id);
60
+ if (user.username)
61
+ b.add(` (@${user.username})`);
62
+ }
63
+ else if (user.username) {
64
+ b.add(`@${user.username}`);
65
+ }
66
+ else {
67
+ b.add('Someone');
68
+ }
69
+ b.add(' wants to use this bot.').newline();
70
+ b.add('User id: ').code(String(user.id)).newline(2);
71
+ appendApproverLine(b, parts.admins);
72
+ return b.build();
73
+ }
74
+ /** The two buttons, as grammy's inline keyboard shape. */
75
+ export function accessKeyboard(userId) {
76
+ return [[
77
+ { text: '✅ Allow', callback_data: `${ACCESS_CALLBACK_PREFIX}:${userId}:y` },
78
+ { text: '🚫 Ignore', callback_data: `${ACCESS_CALLBACK_PREFIX}:${userId}:n` },
79
+ ]];
80
+ }
81
+ /**
82
+ * Post the card for an unknown user, if this chat is one where that makes
83
+ * sense.
84
+ *
85
+ * Every failure path is swallowed: this runs inside the auth middleware's
86
+ * denial, and a bot that crashes on an unauthorised message is a bot anyone can
87
+ * take down by messaging it.
88
+ */
89
+ export async function requestAccess(ctx, user) {
90
+ const chatId = ctx.chat?.id;
91
+ if (chatId === undefined)
92
+ return 'not-asked';
93
+ // Only in the groups the operator has already named. See the module note.
94
+ if (!config.ALLOWED_GROUP_IDS.includes(chatId))
95
+ return 'not-asked';
96
+ // Nobody to ask.
97
+ if (getAdminIds().length === 0)
98
+ return 'not-asked';
99
+ const key = askKey(chatId, user.id);
100
+ const asked = lastAsked.get(key);
101
+ if (asked !== undefined && Date.now() - asked < RE_ASK_MS)
102
+ return 'pending';
103
+ lastAsked.set(key, Date.now());
104
+ try {
105
+ // Record them first: if the send fails, `/allow @them` should still work.
106
+ noteSeenUser(user, chatId);
107
+ // Admins only: letting a stranger in is an owner decision, not an approver's.
108
+ const admins = await resolveApproversInChat(ctx.api, chatId);
109
+ const { text, entities } = buildAccessRequestMessage({ user, admins });
110
+ const threadId = ctx.message?.message_thread_id;
111
+ const threadOpts = threadId !== undefined ? { message_thread_id: threadId } : {};
112
+ await ctx.api.sendMessage(chatId, text, {
113
+ entities,
114
+ reply_markup: { inline_keyboard: accessKeyboard(user.id) },
115
+ ...threadOpts,
116
+ });
117
+ console.log(`[access] requested for ${describeUser(user)} in chat:${chatId}`);
118
+ return 'pending';
119
+ }
120
+ catch (error) {
121
+ // A text_mention Telegram won't render here is the likely cause, and the
122
+ // card is worth more unstyled than not at all.
123
+ console.error('[access] card send failed:', sanitizeError(error));
124
+ try {
125
+ const { text } = buildAccessRequestMessage({ user, admins: [] });
126
+ await ctx.api.sendMessage(chatId, text, {
127
+ reply_markup: { inline_keyboard: accessKeyboard(user.id) },
128
+ });
129
+ return 'pending';
130
+ }
131
+ catch (retryError) {
132
+ console.error('[access] card retry failed:', sanitizeError(retryError));
133
+ // Let the next message try again rather than staying silent for 30 min.
134
+ lastAsked.delete(key);
135
+ return 'not-asked';
136
+ }
137
+ }
138
+ }
139
+ /**
140
+ * Forget the cooldown for a user, so a decision taken on one card does not
141
+ * suppress a fresh card if they are later revoked.
142
+ */
143
+ export function clearAccessCooldown(userId) {
144
+ for (const key of [...lastAsked.keys()]) {
145
+ if (key.endsWith(`:${userId}`))
146
+ lastAsked.delete(key);
147
+ }
148
+ }
149
+ /** Test seam — production keeps the cooldowns for the life of the process. */
150
+ export function resetAccessCooldowns() {
151
+ lastAsked.clear();
152
+ }
153
+ //# sourceMappingURL=access-request.js.map