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,827 @@
1
+ /**
2
+ * Bot lifecycle commands: /update, /botstatus, /version, /restartbot, /rebuildbot.
3
+ *
4
+ * These are the handlers that act on the bot process itself rather than on a
5
+ * conversation, so they are the only ones that touch botctl, the reload marker
6
+ * and the build.
7
+ */
8
+ import * as fs from 'fs';
9
+ import * as path from 'path';
10
+ import { execFile, spawn } from 'child_process';
11
+ import { isMainThread } from 'worker_threads';
12
+ import { config, getReloadMarkerPath } from '../../../config.js';
13
+ import { getModel } from '../../../providers/provider-router.js';
14
+ import { EntityText } from '../../../telegram/entities.js';
15
+ import { replyFormatted, replyParts } from '../../../telegram/send.js';
16
+ import { sanitizeError } from '../../../utils/sanitize.js';
17
+ import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
18
+ import { botctlExists, PROJECT_ROOT, BOTCTL_PATH } from './shared.js';
19
+ import { handleContinue, handleClear } from './session.js';
20
+ import { handleResume } from './resume.js';
21
+ import { requestRestart, requestRestartAll, requestRestartAllWhenIdle, controlIdleRestart, requestSiblingRestart, launcherIsStale, } from '../../../worker-restart.js';
22
+ import { isSystemdService, getSystemdUnit, getRestartBehaviour, willRestartOnRequestedExit, manualRestartCommand, RESTART_EXIT_CODE, } from '../../../utils/systemd.js';
23
+ import { launcherRestartHint } from '../../../utils/stale-launcher.js';
24
+ import { getServiceManager } from '../../../utils/exit-codes.js';
25
+ import { describeRunningBuild, getLatestBuild, getRunningBuild } from '../../../utils/build-info.js';
26
+ import { checkCode, checkRemote, describeCodeCheck, describeRemoteCheck } from '../../../utils/version-check.js';
27
+ import { isCheckout, detectPackageRunner, getInstalledVersion } from '../../../utils/install-mode.js';
28
+ import { compareInstalled, describeNpmCheck, getLatestVersion, installLatestGlobally, updateCommand, } from '../../../utils/npm-version.js';
29
+ /** Write the reload marker so autoResumeAfterReload picks up sessions on restart. */
30
+ export function writeReloadMarker() {
31
+ try {
32
+ const markerDir = path.dirname(getReloadMarkerPath());
33
+ if (!fs.existsSync(markerDir)) {
34
+ fs.mkdirSync(markerDir, { recursive: true, mode: 0o700 });
35
+ }
36
+ fs.writeFileSync(getReloadMarkerPath(), JSON.stringify({ timestamp: new Date().toISOString() }), { mode: 0o600 });
37
+ }
38
+ catch (err) {
39
+ console.error('[ReloadMarker] Failed to write marker file:', err);
40
+ }
41
+ }
42
+ /** Send Continue/Resume inline buttons for manual session restore. */
43
+ export async function sendRestoreButtons(ctx) {
44
+ const chatId = ctx.chat?.id;
45
+ if (!chatId)
46
+ return;
47
+ try {
48
+ await ctx.api.sendMessage(chatId, '👇 Restore your session after restart:', {
49
+ reply_markup: {
50
+ inline_keyboard: [
51
+ [
52
+ { text: '▶️ Continue', callback_data: 'restart:continue' },
53
+ { text: '📜 Resume', callback_data: 'restart:resume' },
54
+ ],
55
+ ],
56
+ },
57
+ });
58
+ }
59
+ catch (e) {
60
+ console.debug('[RestartBot] Failed to send restore buttons:', e instanceof Error ? e.message : e);
61
+ }
62
+ }
63
+ async function getClaudeVersion() {
64
+ return new Promise((resolve) => {
65
+ execFile(config.CLAUDE_EXECUTABLE_PATH, ['--version'], { timeout: 10_000, maxBuffer: 64 * 1024, env: process.env }, (error, stdout, stderr) => {
66
+ if (error) {
67
+ resolve(null);
68
+ return;
69
+ }
70
+ const line = (stdout || stderr || '').trim().split('\n')[0]?.trim() ?? '';
71
+ const match = line.match(/\d+\.\d+\.\d+\S*/);
72
+ resolve(match ? match[0] : line || null);
73
+ });
74
+ });
75
+ }
76
+ async function runClaudeUpdate() {
77
+ return new Promise((resolve, reject) => {
78
+ execFile(config.CLAUDE_EXECUTABLE_PATH, ['update'], {
79
+ // `claude update` may download and install a new binary — give it room.
80
+ timeout: 180_000,
81
+ maxBuffer: 2 * 1024 * 1024,
82
+ env: process.env,
83
+ }, (error, stdout, stderr) => {
84
+ if (error) {
85
+ const message = (stderr || error.message).trim();
86
+ reject(new Error(message || 'Failed to run claude update'));
87
+ return;
88
+ }
89
+ resolve((stdout || stderr || '').trim());
90
+ });
91
+ });
92
+ }
93
+ export async function handleUpdate(ctx) {
94
+ // An npm install updates itself too; a checkout updates with git pull and
95
+ // /rebuildbot, so there /update stays about Claude Code alone.
96
+ if (!isCheckout()) {
97
+ await offerPackageUpdate(ctx);
98
+ return;
99
+ }
100
+ const version = await getClaudeVersion();
101
+ const prompt = version
102
+ ? `⬆️ Update Claude Code? (currently ${version})`
103
+ : '⬆️ Update Claude Code?';
104
+ await ctx.reply(prompt, {
105
+ reply_markup: {
106
+ inline_keyboard: [
107
+ [
108
+ { text: '✅ Update', callback_data: 'update:confirm' },
109
+ { text: '❌ Cancel', callback_data: 'update:cancel' },
110
+ ],
111
+ ],
112
+ },
113
+ });
114
+ }
115
+ export async function handleUpdateCallback(ctx) {
116
+ const data = ctx.callbackQuery?.data;
117
+ if (!data)
118
+ return;
119
+ await ctx.answerCallbackQuery();
120
+ // Remove the menu keyboard so it can't be tapped twice
121
+ try {
122
+ await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } });
123
+ }
124
+ catch {
125
+ // ignore — message may have been edited or deleted
126
+ }
127
+ if (data === 'update:cancel') {
128
+ await ctx.reply('❌ Update cancelled.');
129
+ return;
130
+ }
131
+ if (data === 'update:telecoder') {
132
+ await updateTeleCoder(ctx);
133
+ return;
134
+ }
135
+ if (data !== 'update:confirm')
136
+ return;
137
+ const chatId = ctx.chat?.id;
138
+ const ack = await ctx.reply('⬆️ Updating Claude Code…');
139
+ try {
140
+ const raw = await runClaudeUpdate();
141
+ const body = raw || 'Update finished — no output.';
142
+ await replyParts(ctx, new EntityText().bold('⬆️ Claude Code Update').newline(2).pre(body).build());
143
+ }
144
+ catch (error) {
145
+ const message = error instanceof Error ? error.message : 'Unknown error';
146
+ const b = new EntityText().add('❌ Update failed:').newline(2).pre(message);
147
+ if (/not found|enoent/i.test(message)) {
148
+ b.newline(2)
149
+ .add('The ')
150
+ .code('claude')
151
+ .add(' executable could not be found on PATH. Check ')
152
+ .code('CLAUDE_EXECUTABLE_PATH')
153
+ .add('.');
154
+ }
155
+ else if (/npm|installed via/i.test(message)) {
156
+ b.newline(2).add('This install may be managed by npm — update it there instead.');
157
+ }
158
+ await replyParts(ctx, b.build());
159
+ }
160
+ finally {
161
+ if (chatId !== undefined) {
162
+ try {
163
+ await ctx.api.deleteMessage(chatId, ack.message_id);
164
+ }
165
+ catch {
166
+ // ignore cleanup errors
167
+ }
168
+ }
169
+ }
170
+ }
171
+ /** The /update menu of a package install: TeleCoder itself, or Claude Code. */
172
+ async function offerPackageUpdate(ctx) {
173
+ const [claudeVersion, latest] = await Promise.all([getClaudeVersion(), getLatestVersion()]);
174
+ const check = compareInstalled(getInstalledVersion(), latest);
175
+ const runner = detectPackageRunner();
176
+ const lines = [
177
+ '⬆️ What should be updated?',
178
+ '',
179
+ `TeleCoder: ${describeNpmCheck(check, runner)}`,
180
+ `Claude Code: ${claudeVersion ? `currently ${claudeVersion}` : 'version unknown'}`,
181
+ ];
182
+ // Only a global install can replace itself: npx and a local install are
183
+ // updated from wherever they were started.
184
+ const telecoderButton = runner === 'global'
185
+ ? [{ text: '⬆️ TeleCoder', callback_data: 'update:telecoder' }]
186
+ : [];
187
+ await ctx.reply(lines.join('\n'), {
188
+ reply_markup: {
189
+ inline_keyboard: [
190
+ [...telecoderButton, { text: '⬆️ Claude Code', callback_data: 'update:confirm' }],
191
+ [{ text: '❌ Cancel', callback_data: 'update:cancel' }],
192
+ ],
193
+ },
194
+ });
195
+ }
196
+ /** `npm install -g telecoder@latest`, then say how to start running it. */
197
+ async function updateTeleCoder(ctx) {
198
+ const runner = detectPackageRunner();
199
+ if (runner !== 'global') {
200
+ await replyFormatted(ctx, new EntityText()
201
+ .add('This TeleCoder was not installed with ')
202
+ .code('npm install -g')
203
+ .add(", so it can't replace itself. Update it with ")
204
+ .code(updateCommand(runner))
205
+ .add(' and restart it.')
206
+ .build());
207
+ return;
208
+ }
209
+ const chatId = ctx.chat?.id;
210
+ const ack = await ctx.reply('⬆️ Updating TeleCoder…');
211
+ try {
212
+ const raw = await installLatestGlobally();
213
+ // Read back from disk: npm replaced the package directory this runs from.
214
+ const installed = getInstalledVersion();
215
+ const b = new EntityText().bold('⬆️ TeleCoder Update').newline(2);
216
+ if (raw)
217
+ b.pre(raw.slice(-1500)).newline(2);
218
+ b.add(installed ? `v${installed} is installed. ` : 'Installed. ')
219
+ .add('It runs from the next restart: /restartbot.');
220
+ await replyParts(ctx, b.build());
221
+ }
222
+ catch (error) {
223
+ const message = error instanceof Error ? error.message : 'Unknown error';
224
+ const b = new EntityText().add('❌ Update failed:').newline(2).pre(message.slice(-1500));
225
+ if (/EACCES|permission denied/i.test(message)) {
226
+ b.newline(2)
227
+ .add("npm can't write to its global directory as this user. Run ")
228
+ .code(updateCommand('global'))
229
+ .add(' yourself (with the rights it needs), then /restartbot.');
230
+ }
231
+ await replyParts(ctx, b.build());
232
+ }
233
+ finally {
234
+ if (chatId !== undefined) {
235
+ try {
236
+ await ctx.api.deleteMessage(chatId, ack.message_id);
237
+ }
238
+ catch {
239
+ // ignore cleanup errors
240
+ }
241
+ }
242
+ }
243
+ }
244
+ export async function handleBotStatus(ctx) {
245
+ const uptimeSec = process.uptime();
246
+ const hours = Math.floor(uptimeSec / 3600);
247
+ const minutes = Math.floor((uptimeSec % 3600) / 60);
248
+ const seconds = Math.floor(uptimeSec % 60);
249
+ const uptimeStr = hours > 0
250
+ ? `${hours}h ${minutes}m ${seconds}s`
251
+ : minutes > 0
252
+ ? `${minutes}m ${seconds}s`
253
+ : `${seconds}s`;
254
+ const mode = config.BOT_MODE === 'prod' ? 'Production' : 'Development';
255
+ const keyInfo = getSessionKeyFromCtx(ctx);
256
+ const model = keyInfo ? getModel(keyInfo.sessionKey) : 'opus';
257
+ const streaming = config.STREAMING_MODE || 'streaming';
258
+ const pid = process.pid;
259
+ const memMB = (process.memoryUsage.rss() / 1024 / 1024).toFixed(1);
260
+ // The uptime above is this worker's, and a worker that restarted an hour ago
261
+ // says nothing about the process it restarted inside.
262
+ const warning = await staleLauncherWarning();
263
+ const build = describeRunningBuild();
264
+ const msg = new EntityText().add('🟢 ').bold(`${config.BOT_NAME} is running`).newline(2);
265
+ /** A `Label: value` line; every one but the last ends in a newline. */
266
+ const field = (label, value) => msg.bold(`${label}:`).add(` ${value}`);
267
+ field('Mode', mode).newline();
268
+ if (build)
269
+ field('Version', build).newline();
270
+ field('Uptime', uptimeStr).newline();
271
+ field('PID', String(pid)).newline();
272
+ field('Memory', `${memMB} MB`).newline();
273
+ field('Model', model).newline();
274
+ field('Streaming', streaming);
275
+ if (warning)
276
+ msg.newline(2).add(warning);
277
+ await replyFormatted(ctx, msg.build());
278
+ }
279
+ export async function handleVersion(ctx) {
280
+ if (!isCheckout()) {
281
+ await handlePackageVersion(ctx);
282
+ return;
283
+ }
284
+ const [code, remote, warning] = await Promise.all([
285
+ checkCode(getRunningBuild(), getLatestBuild(), PROJECT_ROOT),
286
+ checkRemote(PROJECT_ROOT),
287
+ // A worker's stamp only speaks for that worker, not the launcher it runs in.
288
+ staleLauncherWarning(),
289
+ ]);
290
+ const build = describeRunningBuild();
291
+ const answer = [build && `Running: ${build}`, describeCodeCheck(code), describeRemoteCheck(remote)]
292
+ .filter(Boolean)
293
+ .join('\n');
294
+ // Plain text: a commit subject goes out exactly as written.
295
+ await ctx.reply(warning ? `${answer}\n\n${warning}` : answer);
296
+ }
297
+ /** /version for a package install: the installed version against npm's latest. */
298
+ async function handlePackageVersion(ctx) {
299
+ const installed = getInstalledVersion();
300
+ const [latest, warning] = await Promise.all([getLatestVersion(), staleLauncherWarning()]);
301
+ const answer = [
302
+ `Running: TeleCoder v${installed ?? '?'}`,
303
+ describeNpmCheck(compareInstalled(installed, latest), detectPackageRunner()),
304
+ ].join('\n');
305
+ await ctx.reply(warning ? `${answer}\n\n${warning}` : answer);
306
+ }
307
+ /**
308
+ * Work out how to restart, without doing anything yet.
309
+ *
310
+ * Separate from executing it so a restart is never *announced* before it is
311
+ * known to be possible. Announcing one that then fails is how the bot ends up
312
+ * silently dead with a "restarting..." message as its last word.
313
+ *
314
+ * Returns an error message when there is no way to come back, in which case
315
+ * the bot keeps running.
316
+ */
317
+ async function planRestart() {
318
+ if (isSystemdService()) {
319
+ // botctl is not an option here: it would be reaped with us (see
320
+ // utils/systemd.ts). Exiting and letting systemd restart us is, but only
321
+ // if the unit is set up to.
322
+ const unit = getSystemdUnit();
323
+ if (!unit) {
324
+ return {
325
+ error: new EntityText()
326
+ .add('Running under systemd, but the unit name could not be read from ')
327
+ .code('/proc/self/cgroup')
328
+ .add('.')
329
+ .newline(2)
330
+ .add('Restart it by hand: ')
331
+ .code('systemctl --user restart telecoder')
332
+ .build(),
333
+ };
334
+ }
335
+ const behaviour = await getRestartBehaviour(unit);
336
+ if (behaviour === null) {
337
+ return {
338
+ error: new EntityText()
339
+ .add('Running as ')
340
+ .bold(unit.name)
341
+ .add(', but ')
342
+ .code('systemctl show')
343
+ .add(' did not answer, so there is no way to confirm the bot would come back.')
344
+ .newline(2)
345
+ .add('Restart it by hand: ')
346
+ .code(manualRestartCommand(unit))
347
+ .build(),
348
+ };
349
+ }
350
+ if (!willRestartOnRequestedExit(behaviour)) {
351
+ return {
352
+ error: new EntityText()
353
+ .bold(unit.name)
354
+ .add(' has ')
355
+ .code(`Restart=${behaviour.policy}`)
356
+ .add(', so systemd would not start the bot again.')
357
+ .newline(2)
358
+ .add('Set ')
359
+ .code('Restart=always')
360
+ .add(' in the unit, or restart by hand: ')
361
+ .code(manualRestartCommand(unit))
362
+ .build(),
363
+ };
364
+ }
365
+ return { plan: { kind: 'systemd', unit } };
366
+ }
367
+ // A checkout under the launchd agent `telecoder service install
368
+ // --from-checkout` writes takes this path too: botctl would start a second
369
+ // copy beside the one launchd is about to bring back.
370
+ if (!isCheckout() || getServiceManager() === 'launchd') {
371
+ // A package install has no botctl. It expects a supervisor (a systemd or
372
+ // launchd unit with Restart=always, pm2, ...) that starts it again when it
373
+ // exits — and in a terminal there is none, so there it says so instead.
374
+ if (process.stdin.isTTY && process.stdout.isTTY) {
375
+ return {
376
+ error: new EntityText()
377
+ .add('This bot is running in a terminal, so nothing would start it again after it exits.')
378
+ .newline(2)
379
+ .add('Stop it there and run ')
380
+ .code('telecoder start')
381
+ .add(' again, or run it as a service so restarts work from chat.')
382
+ .build(),
383
+ };
384
+ }
385
+ return { plan: { kind: 'exit' } };
386
+ }
387
+ if (!botctlExists()) {
388
+ return {
389
+ error: new EntityText()
390
+ .add('Bot control script not found.')
391
+ .newline(2)
392
+ .add('Expected at ')
393
+ .code('scripts/telecoder-botctl.sh')
394
+ .add('.')
395
+ .build(),
396
+ };
397
+ }
398
+ return { plan: { kind: 'botctl' } };
399
+ }
400
+ /**
401
+ * Act on a plan from `planRestart`. The systemd path does not come back — the
402
+ * process is on its way out by the time this returns.
403
+ */
404
+ function executeRestart(plan) {
405
+ if (plan.kind === 'exit') {
406
+ // Same as the systemd path below: the exit is the restart, non-zero so a
407
+ // supervisor that only restarts on failure acts on it too.
408
+ console.log('[Restart] Exiting for the service manager to start the bot again');
409
+ process.exitCode = RESTART_EXIT_CODE;
410
+ process.kill(process.pid, 'SIGTERM');
411
+ return;
412
+ }
413
+ if (plan.kind === 'systemd') {
414
+ // The exit *is* the restart. Non-zero so both Restart=always and
415
+ // Restart=on-failure act on it; SIGTERM rather than process.exit so the
416
+ // normal graceful shutdown still runs.
417
+ console.log(`[Restart] Exiting for systemd to restart ${plan.unit.name}`);
418
+ process.exitCode = RESTART_EXIT_CODE;
419
+ process.kill(process.pid, 'SIGTERM');
420
+ return;
421
+ }
422
+ try {
423
+ const child = spawn(BOTCTL_PATH, ['recover'], { cwd: PROJECT_ROOT, detached: true, stdio: 'ignore', env: { ...process.env, MODE: config.BOT_MODE } });
424
+ child.unref();
425
+ }
426
+ catch (error) {
427
+ console.error('[BotCtl] Failed to restart:', sanitizeError(error));
428
+ }
429
+ }
430
+ async function performRestart(ctx, scope) {
431
+ // Multi-instance mode (worker thread) — restart via launcher, not shell script
432
+ if (!isMainThread) {
433
+ // A restart can't make the launcher stale — only a build does that — but
434
+ // it is the moment someone concludes everything is running current code.
435
+ const warning = await staleLauncherWarning();
436
+ const note = warning ? `\n\n${warning}` : '';
437
+ if (scope === 'all') {
438
+ if (config.AUTO_RESTORE_SESSION) {
439
+ await ctx.reply(`🔁 Restarting all bot instances.\n\n⏳ Sessions will be restored automatically.${note}`);
440
+ }
441
+ else {
442
+ await ctx.reply(`🔁 Restarting all bot instances.\n\n⏳ Please wait ~10 seconds.${note}`);
443
+ await sendRestoreButtons(ctx);
444
+ }
445
+ // Marker writing for sibling bots happens in the launcher — it has the
446
+ // tokens to derive each bot's marker path. We can't write them here.
447
+ requestRestartAll(config.AUTO_RESTORE_SESSION);
448
+ return;
449
+ }
450
+ if (config.AUTO_RESTORE_SESSION) {
451
+ await ctx.reply(`🔁 Restarting this bot instance.\n\n⏳ Session will be restored automatically.${note}`);
452
+ writeReloadMarker();
453
+ }
454
+ else {
455
+ await ctx.reply(`🔁 Restarting this bot instance.\n\n⏳ Other bots will not be affected. Please wait ~10 seconds.${note}`);
456
+ await sendRestoreButtons(ctx);
457
+ }
458
+ requestRestart();
459
+ return;
460
+ }
461
+ // Single-instance mode — systemd restarts us, or botctl starts a successor
462
+ const planned = await planRestart();
463
+ if ('error' in planned) {
464
+ await replyFormatted(ctx, new EntityText().add('❌ Cannot restart.').newline(2).append(planned.error).build());
465
+ return;
466
+ }
467
+ if (config.AUTO_RESTORE_SESSION) {
468
+ await ctx.reply('🔁 Restarting bot.\n\n⏳ Session will be restored automatically.');
469
+ writeReloadMarker();
470
+ }
471
+ else {
472
+ await replyFormatted(ctx, new EntityText()
473
+ .add('🔁 Restarting bot.')
474
+ .newline(2)
475
+ .add('⏳ Please wait at least ')
476
+ .bold('10-15 seconds')
477
+ .add(' before checking status or resuming.')
478
+ .build());
479
+ await sendRestoreButtons(ctx);
480
+ }
481
+ executeRestart(planned.plan);
482
+ }
483
+ export async function handleRestartBot(ctx) {
484
+ const args = ctx.message?.text?.split(/\s+/).slice(1).join(' ').trim();
485
+ // Cross-bot restart: /restartbot <name> — direct, no menu
486
+ if (args && !isMainThread && args.toLowerCase() !== 'all' && args.toLowerCase() !== 'one' && args.toLowerCase() !== 'this') {
487
+ const result = await requestSiblingRestart(args, config.AUTO_RESTORE_SESSION);
488
+ if (result.success) {
489
+ await replyFormatted(ctx, new EntityText()
490
+ .add('🔁 Restarting ')
491
+ .bold(result.name ?? args)
492
+ .add('... it should be back in ~10 seconds.')
493
+ .build());
494
+ }
495
+ else {
496
+ await replyFormatted(ctx, new EntityText()
497
+ .add('❌ Could not restart ')
498
+ .bold(args)
499
+ .add(`: ${result.reason ?? 'unknown error'}`)
500
+ .build());
501
+ }
502
+ return;
503
+ }
504
+ // Legacy direct invocations: /restartbot all | /restartbot one | /restartbot this
505
+ if (args?.toLowerCase() === 'all') {
506
+ await performRestart(ctx, 'all');
507
+ return;
508
+ }
509
+ if (args?.toLowerCase() === 'one' || args?.toLowerCase() === 'this') {
510
+ await performRestart(ctx, 'one');
511
+ return;
512
+ }
513
+ // Single-instance mode: only one process exists, so just confirm.
514
+ if (isMainThread) {
515
+ await ctx.reply('🔁 Restart the bot?', {
516
+ reply_markup: {
517
+ inline_keyboard: [
518
+ [
519
+ { text: '✅ Restart', callback_data: 'restartbot:one' },
520
+ { text: '❌ Cancel', callback_data: 'restartbot:cancel' },
521
+ ],
522
+ ],
523
+ },
524
+ });
525
+ return;
526
+ }
527
+ // Multi-instance (worker) mode: offer this/all/cancel
528
+ await ctx.reply('🔁 Restart which?', {
529
+ reply_markup: {
530
+ inline_keyboard: [
531
+ [{ text: '🔧 This instance only', callback_data: 'restartbot:one' }],
532
+ [{ text: '🌐 All instances', callback_data: 'restartbot:all' }],
533
+ [{ text: '❌ Cancel', callback_data: 'restartbot:cancel' }],
534
+ ],
535
+ },
536
+ });
537
+ }
538
+ export async function handleRestartBotCallback(ctx) {
539
+ const data = ctx.callbackQuery?.data;
540
+ if (!data)
541
+ return;
542
+ await ctx.answerCallbackQuery();
543
+ // Remove the menu keyboard so it can't be tapped twice
544
+ try {
545
+ await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } });
546
+ }
547
+ catch {
548
+ // ignore — message may have been edited or deleted
549
+ }
550
+ if (data === 'restartbot:cancel') {
551
+ await ctx.reply('❌ Restart cancelled.');
552
+ return;
553
+ }
554
+ if (data === 'restartbot:all') {
555
+ await performRestart(ctx, 'all');
556
+ return;
557
+ }
558
+ if (data === 'restartbot:one') {
559
+ await performRestart(ctx, 'one');
560
+ return;
561
+ }
562
+ }
563
+ /** Run the build without blocking the event loop. execSync would freeze this
564
+ * worker for the whole build, and a worker that stops sending heartbeats for
565
+ * 90s gets force-restarted by the launcher mid-build. */
566
+ function runBuild() {
567
+ return new Promise((resolve, reject) => {
568
+ execFile('npm', ['run', 'build'], { cwd: PROJECT_ROOT, timeout: 120_000, maxBuffer: 4 * 1024 * 1024 }, (error, _stdout, stderr) => {
569
+ if (error) {
570
+ reject(new Error((stderr || error.message || 'Unknown build error').trim()));
571
+ return;
572
+ }
573
+ resolve();
574
+ });
575
+ });
576
+ }
577
+ /**
578
+ * Said wherever someone is about to believe their code is now current: the
579
+ * launcher is running what it loaded at startup, and neither a rebuild nor a
580
+ * restart of the instances reaches it.
581
+ *
582
+ * Note what this does not claim — that the build in hand is the one that
583
+ * changed the launcher. The fingerprint only knows the launcher differs from
584
+ * the copy this process started with, which stays true for every later build
585
+ * until someone restarts it.
586
+ *
587
+ * Empty whenever the launcher is current or can't be asked. Plain text, which
588
+ * callers append as it is.
589
+ */
590
+ async function staleLauncherWarning() {
591
+ if (!await launcherIsStale())
592
+ return '';
593
+ return `⚠️ The launcher is still running the code it started with — a build since then replaced it `
594
+ + `on disk, and restarting instances can't reload it. To pick that up, ${launcherRestartHint()}; `
595
+ + `that drops every live session.`;
596
+ }
597
+ async function performRebuild(ctx, scope) {
598
+ // Only a launcher can wait on other instances; checked before building, so
599
+ // the answer isn't a build nobody restarts onto.
600
+ if (scope === 'idle' && isMainThread) {
601
+ await ctx.reply('⚠️ "When idle" restarts the instances of a multi-instance setup — this bot runs on its own. Use /rebuildbot to rebuild and restart it now.');
602
+ return;
603
+ }
604
+ // Step 1: Build
605
+ await ctx.reply('🔨 Building...');
606
+ try {
607
+ await runBuild();
608
+ }
609
+ catch (error) {
610
+ const message = error instanceof Error ? error.message : String(error);
611
+ await ctx.reply(`❌ Build failed. Aborting reload.\n\n${message.slice(-500).slice(0, 400)}`);
612
+ return;
613
+ }
614
+ // Step 2: Restart. For 'all', the launcher writes markers for every sibling
615
+ // (we can't — markers live at per-bot paths keyed by each bot's token). For
616
+ // 'one' and single-instance, write the local marker now.
617
+ if (!isMainThread) {
618
+ // Asked before the restart is requested: this worker is about to exit, and
619
+ // a second message sent into that gap may never make it out.
620
+ const warning = await staleLauncherWarning();
621
+ const note = warning ? `\n\n${warning}` : '';
622
+ if (scope === 'idle') {
623
+ await restartAllWhenIdle(ctx, warning);
624
+ return;
625
+ }
626
+ if (scope === 'all') {
627
+ await ctx.reply(`✅ Build succeeded. Restarting all instances...${note}`);
628
+ requestRestartAll(config.AUTO_RESTORE_SESSION);
629
+ }
630
+ else {
631
+ if (config.AUTO_RESTORE_SESSION)
632
+ writeReloadMarker();
633
+ await ctx.reply(`✅ Build succeeded. Restarting this instance...${note}`);
634
+ if (!config.AUTO_RESTORE_SESSION)
635
+ await sendRestoreButtons(ctx);
636
+ requestRestart();
637
+ }
638
+ return;
639
+ }
640
+ // Single-instance mode (scope is moot — only one process). Planned before
641
+ // the build is reported, so a bot that cannot restart says so while it is
642
+ // still alive to say it.
643
+ const planned = await planRestart();
644
+ if ('error' in planned) {
645
+ await replyFormatted(ctx, new EntityText()
646
+ .add('✅ Build succeeded, but the bot cannot restart itself.')
647
+ .newline(2)
648
+ .append(planned.error)
649
+ .build());
650
+ return;
651
+ }
652
+ if (config.AUTO_RESTORE_SESSION)
653
+ writeReloadMarker();
654
+ await ctx.reply('✅ Build succeeded. Restarting...');
655
+ if (!config.AUTO_RESTORE_SESSION)
656
+ await sendRestoreButtons(ctx);
657
+ executeRestart(planned.plan);
658
+ }
659
+ /**
660
+ * Hand the restart to the launcher, to make as each instance runs out of work.
661
+ * The message posted here is the one the launcher keeps up to date.
662
+ */
663
+ async function restartAllWhenIdle(ctx, warning) {
664
+ const chatId = ctx.chat?.id;
665
+ if (chatId === undefined)
666
+ return;
667
+ const status = await ctx.reply('✅ Build succeeded. Restarting each instance once it has nothing left to finish...');
668
+ const names = await requestRestartAllWhenIdle({
669
+ autoResume: config.AUTO_RESTORE_SESSION,
670
+ chatId,
671
+ messageId: status.message_id,
672
+ note: warning || undefined,
673
+ });
674
+ if (names !== null)
675
+ return;
676
+ // The launcher that never answers is the one that predates the request —
677
+ // which the stale check usually says outright.
678
+ const text = '✅ Build succeeded, but the launcher did not take the restart — it is running code from '
679
+ + `before "when idle" existed, so nothing is restarting. To pick it up, ${launcherRestartHint()}; that drops `
680
+ + 'every live session. /rebuildbot all restarts the instances now instead.';
681
+ try {
682
+ await ctx.api.editMessageText(chatId, status.message_id, text);
683
+ }
684
+ catch {
685
+ await ctx.reply(text);
686
+ }
687
+ }
688
+ /**
689
+ * /rebuildbot needs the source to build, which only a checkout has. Says so,
690
+ * and returns true, when this isn't one.
691
+ */
692
+ async function refuseRebuildOutsideCheckout(ctx) {
693
+ if (isCheckout())
694
+ return false;
695
+ await ctx.reply('⚠️ /rebuildbot rebuilds a source checkout of TeleCoder, and this one was installed from npm — there is no source here to build. '
696
+ + 'Use /update to install a newer release, and /restartbot to restart.');
697
+ return true;
698
+ }
699
+ export async function handleRebuild(ctx) {
700
+ if (await refuseRebuildOutsideCheckout(ctx))
701
+ return;
702
+ const args = ctx.message?.text?.split(/\s+/).slice(1).join(' ').trim();
703
+ // Legacy direct invocation: /rebuildbot all
704
+ if (args?.toLowerCase() === 'all') {
705
+ await performRebuild(ctx, 'all');
706
+ return;
707
+ }
708
+ if (args?.toLowerCase() === 'one' || args?.toLowerCase() === 'this') {
709
+ await performRebuild(ctx, 'one');
710
+ return;
711
+ }
712
+ if (args?.toLowerCase() === 'idle' || args?.toLowerCase() === 'all idle') {
713
+ await performRebuild(ctx, 'idle');
714
+ return;
715
+ }
716
+ // Single-instance mode: only one process exists, so skip the this-vs-all
717
+ // distinction and just confirm.
718
+ if (isMainThread) {
719
+ await ctx.reply('🔄 Rebuild and restart the bot?', {
720
+ reply_markup: {
721
+ inline_keyboard: [
722
+ [
723
+ { text: '✅ Rebuild', callback_data: 'rebuild:one' },
724
+ { text: '❌ Cancel', callback_data: 'rebuild:cancel' },
725
+ ],
726
+ ],
727
+ },
728
+ });
729
+ return;
730
+ }
731
+ // Multi-instance (worker) mode: offer this/all/cancel
732
+ await ctx.reply('🔄 Rebuild and restart which?', {
733
+ reply_markup: {
734
+ inline_keyboard: [
735
+ [{ text: '🔧 This instance only', callback_data: 'rebuild:one' }],
736
+ [{ text: '🌐 All instances', callback_data: 'rebuild:all' }],
737
+ [{ text: '⏳ All instances, each once it is idle', callback_data: 'rebuild:idle' }],
738
+ [{ text: '❌ Cancel', callback_data: 'rebuild:cancel' }],
739
+ ],
740
+ },
741
+ });
742
+ }
743
+ export async function handleRebuildCallback(ctx) {
744
+ const data = ctx.callbackQuery?.data;
745
+ if (!data)
746
+ return;
747
+ await ctx.answerCallbackQuery();
748
+ // Remove the menu keyboard so it can't be tapped twice
749
+ try {
750
+ await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } });
751
+ }
752
+ catch {
753
+ // ignore — message may have been edited or deleted
754
+ }
755
+ if (data === 'rebuild:cancel') {
756
+ await ctx.reply('❌ Rebuild cancelled.');
757
+ return;
758
+ }
759
+ if (await refuseRebuildOutsideCheckout(ctx))
760
+ return;
761
+ if (data === 'rebuild:all') {
762
+ await performRebuild(ctx, 'all');
763
+ return;
764
+ }
765
+ if (data === 'rebuild:one') {
766
+ await performRebuild(ctx, 'one');
767
+ return;
768
+ }
769
+ if (data === 'rebuild:idle') {
770
+ await performRebuild(ctx, 'idle');
771
+ return;
772
+ }
773
+ // The buttons on the "when idle" status message. The launcher redraws that
774
+ // message itself, buttons and all, so a tap only needs an answer when there
775
+ // was nothing left to act on.
776
+ if (data === 'rebuild:idle_force' || data === 'rebuild:idle_cancel') {
777
+ const found = await controlIdleRestart(data === 'rebuild:idle_force' ? 'force' : 'cancel');
778
+ if (!found)
779
+ await ctx.reply('Nothing is waiting to restart any more.');
780
+ return;
781
+ }
782
+ }
783
+ export async function handleRestartCallback(ctx) {
784
+ const data = ctx.callbackQuery?.data;
785
+ if (!data)
786
+ return;
787
+ if (data === 'restart:continue') {
788
+ await ctx.answerCallbackQuery();
789
+ await handleContinue(ctx);
790
+ }
791
+ else if (data === 'restart:resume') {
792
+ await ctx.answerCallbackQuery();
793
+ await handleResume(ctx);
794
+ }
795
+ else {
796
+ await ctx.answerCallbackQuery();
797
+ }
798
+ }
799
+ /**
800
+ * Taps on a "Continue where you left off, or start fresh?" prompt. Startup
801
+ * doesn't ask any more — a restart just carries on — but the prompts it already
802
+ * posted still sit in chats with live buttons.
803
+ */
804
+ export async function handleStartupCallback(ctx) {
805
+ const data = ctx.callbackQuery?.data;
806
+ if (!data)
807
+ return;
808
+ await ctx.answerCallbackQuery();
809
+ // Remove the inline keyboard so the buttons can't be tapped twice.
810
+ try {
811
+ await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } });
812
+ }
813
+ catch {
814
+ // ignore — message may have been edited or deleted
815
+ }
816
+ if (data === 'startup:continue') {
817
+ await handleContinue(ctx);
818
+ return;
819
+ }
820
+ if (data === 'startup:fresh') {
821
+ // Startup has put the old conversation back by now, so leaving it alone no
822
+ // longer starts anything fresh — clear it the way /clear does.
823
+ await handleClear(ctx);
824
+ return;
825
+ }
826
+ }
827
+ //# sourceMappingURL=admin.js.map