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.
- package/.env.example +375 -0
- package/CHANGELOG.md +1867 -0
- package/LICENSE +22 -0
- package/README.md +130 -2
- package/dist/audio/transcribe.js +41 -0
- package/dist/bin/mcp-server.js +363 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +573 -0
- package/dist/bot/command-catalog.js +263 -0
- package/dist/bot/deleted-threads.js +103 -0
- package/dist/bot/file-access.js +150 -0
- package/dist/bot/handlers/album.handler.js +128 -0
- package/dist/bot/handlers/branch.handler.js +1096 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +803 -0
- package/dist/bot/handlers/command/all-view.js +33 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/background.js +37 -0
- package/dist/bot/handlers/command/botname.js +76 -0
- package/dist/bot/handlers/command/btw.js +175 -0
- package/dist/bot/handlers/command/cleanup.js +329 -0
- package/dist/bot/handlers/command/model.js +226 -0
- package/dist/bot/handlers/command/prefs-scope.js +362 -0
- package/dist/bot/handlers/command/project.js +458 -0
- package/dist/bot/handlers/command/resume.js +325 -0
- package/dist/bot/handlers/command/session.js +299 -0
- package/dist/bot/handlers/command/settings.js +657 -0
- package/dist/bot/handlers/command/shared.js +207 -0
- package/dist/bot/handlers/command/tasks.js +681 -0
- package/dist/bot/handlers/command/thread.js +128 -0
- package/dist/bot/handlers/command/topic-store.js +74 -0
- package/dist/bot/handlers/command/topic.js +27 -0
- package/dist/bot/handlers/command/usage.js +382 -0
- package/dist/bot/handlers/command-fallback.js +179 -0
- package/dist/bot/handlers/command.handler.js +446 -0
- package/dist/bot/handlers/loop.handler.js +389 -0
- package/dist/bot/handlers/media-fallback.js +126 -0
- package/dist/bot/handlers/message/replies.js +56 -0
- package/dist/bot/handlers/message/shared.js +95 -0
- package/dist/bot/handlers/message/turn-notify.js +135 -0
- package/dist/bot/handlers/message/turn-runner.js +56 -0
- package/dist/bot/handlers/message.handler.js +114 -0
- package/dist/bot/handlers/newbot.handler.js +230 -0
- package/dist/bot/handlers/photo.handler.js +286 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/session-guard.js +78 -0
- package/dist/bot/handlers/suggestion.handler.js +84 -0
- package/dist/bot/handlers/tree.handler.js +480 -0
- package/dist/bot/handlers/view.js +41 -0
- package/dist/bot/handlers/voice.handler.js +147 -0
- package/dist/bot/kept-threads.js +51 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/album-collector.js +69 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +145 -0
- package/dist/bot/middleware/group-role.middleware.js +75 -0
- package/dist/bot/middleware/message-batcher.js +87 -0
- package/dist/bot/middleware/queued-messages.js +1082 -0
- package/dist/bot/middleware/stale-filter.js +9 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/ask-user-form.js +517 -0
- package/dist/claude/ask-user.js +363 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +143 -0
- package/dist/claude/available-commands.js +156 -0
- package/dist/claude/background-hint.js +91 -0
- package/dist/claude/branch-tree.js +393 -0
- package/dist/claude/carry-over.js +25 -0
- package/dist/claude/ccr-shim.js +48 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +117 -0
- package/dist/claude/command-parser.js +206 -0
- package/dist/claude/cost-overlay-scraper.js +134 -0
- package/dist/claude/effort-level.js +5 -0
- package/dist/claude/enabled-plugins.js +52 -0
- package/dist/claude/in-flight-tracker.js +82 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +481 -0
- package/dist/claude/memory-guard.js +400 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +817 -0
- package/dist/claude/model-catalog.js +102 -0
- package/dist/claude/monitor-relay.js +712 -0
- package/dist/claude/native-commands.js +40 -0
- package/dist/claude/pending-branches.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +338 -0
- package/dist/claude/permission-mode.js +152 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/prewarm.js +70 -0
- package/dist/claude/project-commands.js +69 -0
- package/dist/claude/prompt-hold.js +124 -0
- package/dist/claude/prompt-suggestion-scraper.js +89 -0
- package/dist/claude/pty-idle-reaper.js +96 -0
- package/dist/claude/pty-provider.js +2499 -0
- package/dist/claude/pty-spawn-config.js +343 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/pty-watch.js +201 -0
- package/dist/claude/request-queue.js +107 -0
- package/dist/claude/rewind.js +111 -0
- package/dist/claude/scheduled-runner.js +89 -0
- package/dist/claude/scheduler.js +241 -0
- package/dist/claude/scope-guard.js +279 -0
- package/dist/claude/screen-marks.js +83 -0
- package/dist/claude/screen-render.js +96 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-history.js +288 -0
- package/dist/claude/session-jsonl.js +1067 -0
- package/dist/claude/session-manager.js +216 -0
- package/dist/claude/session-move.js +70 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/shell-mode-gate.js +60 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +252 -0
- package/dist/claude/stage-images.js +62 -0
- package/dist/claude/subagent-tools.js +12 -0
- package/dist/claude/synthetic-ctx.js +51 -0
- package/dist/claude/tasks-overlay-scraper.js +217 -0
- package/dist/claude/thread-judge-haiku.js +88 -0
- package/dist/claude/tip-scraper.js +77 -0
- package/dist/claude/tui-modal.js +746 -0
- package/dist/claude/tui-state.js +456 -0
- package/dist/claude/turn-end.js +105 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/typed-answer.js +104 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +338 -0
- package/dist/cli/commands/help.js +34 -0
- package/dist/cli/commands/init.js +126 -0
- package/dist/cli/commands/service.js +710 -0
- package/dist/cli/commands/start.js +63 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/commands/watch.js +322 -0
- package/dist/cli/dispatch.js +84 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +705 -0
- package/dist/cli/init/prompter.js +124 -0
- package/dist/cli/init/telegram.js +120 -0
- package/dist/cli/service/render.js +212 -0
- package/dist/cli.js +18 -0
- package/dist/config-report.js +107 -0
- package/dist/config.js +525 -0
- package/dist/index.js +443 -0
- package/dist/launcher.js +960 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +142 -0
- package/dist/providers/ccr-provider.js +59 -0
- package/dist/providers/claude-provider.js +10 -0
- package/dist/providers/prefs-sync.js +121 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +128 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/spawn-settings.js +45 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +322 -0
- package/dist/restart-when-idle.js +173 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +161 -0
- package/dist/startup/notices.js +120 -0
- package/dist/startup/shared.js +44 -0
- package/dist/startup/verify-token.js +31 -0
- package/dist/telegram/access-request.js +153 -0
- package/dist/telegram/action-logger.js +522 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +282 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +26 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +96 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1019 -0
- package/dist/telegram/prompt-label.js +148 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +103 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/table-lists.js +56 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +128 -0
- package/dist/telegram/terminal-renderer.js +667 -0
- package/dist/telegram/thread-titles.js +262 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/utils/admins.js +143 -0
- package/dist/utils/agent-timer.js +55 -0
- package/dist/utils/atomic-write.js +24 -0
- package/dist/utils/bot-icon.js +248 -0
- package/dist/utils/bot-token.js +77 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +53 -0
- package/dist/utils/claude-env.js +53 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/download.js +137 -0
- package/dist/utils/exit-codes.js +59 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +78 -0
- package/dist/utils/home-project.js +30 -0
- package/dist/utils/host-stall.js +51 -0
- package/dist/utils/id-list.js +44 -0
- package/dist/utils/idle-restart.js +92 -0
- package/dist/utils/install-mode.js +63 -0
- package/dist/utils/instance-config.js +148 -0
- package/dist/utils/instances.js +95 -0
- package/dist/utils/json-store.js +140 -0
- package/dist/utils/keyed-settings.js +62 -0
- package/dist/utils/legacy-env.js +35 -0
- package/dist/utils/memory-pressure.js +60 -0
- package/dist/utils/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +52 -0
- package/dist/utils/respawn-backoff.js +28 -0
- package/dist/utils/sanitize.js +91 -0
- package/dist/utils/session-key.js +37 -0
- package/dist/utils/stale-launcher.js +109 -0
- package/dist/utils/state-dir-migration.js +92 -0
- package/dist/utils/systemd.js +126 -0
- package/dist/utils/telegram-proxy.js +72 -0
- package/dist/utils/uploads-dir.js +27 -0
- package/dist/utils/user-roster.js +275 -0
- package/dist/utils/verbosity.js +118 -0
- package/dist/utils/version-check.js +166 -0
- package/dist/utils/workspace-guard.js +44 -0
- package/dist/worker-restart.js +141 -0
- package/instances.json.example +41 -0
- package/package.json +75 -4
|
@@ -0,0 +1,803 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bot lifecycle commands: /botupdate, /botstatus, /botversion, /botrestart, /botrebuild.
|
|
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 the reload marker and
|
|
6
|
+
* the build.
|
|
7
|
+
*/
|
|
8
|
+
import * as fs from 'fs';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
import { execFile } 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 { getPtyProvider } from '../../../providers/claude-provider.js';
|
|
15
|
+
import { readMemory } from '../../../utils/memory-pressure.js';
|
|
16
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
17
|
+
import { replyFormatted, replyParts } from '../../../telegram/send.js';
|
|
18
|
+
import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
|
|
19
|
+
import { PROJECT_ROOT } from './shared.js';
|
|
20
|
+
import { continueLastSession, handleClear } from './session.js';
|
|
21
|
+
import { handleResume } from './resume.js';
|
|
22
|
+
import { requestRestart, requestRestartAll, requestRestartAllWhenIdle, controlIdleRestart, requestSiblingRestart, launcherIsStale, } from '../../../worker-restart.js';
|
|
23
|
+
import { isSystemdService, getSystemdUnit, getRestartBehaviour, willRestartOnRequestedExit, manualRestartCommand, RESTART_EXIT_CODE, } from '../../../utils/systemd.js';
|
|
24
|
+
import { launcherRestartHint } from '../../../utils/stale-launcher.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('[BotRestart] 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 handleBotUpdate(ctx) {
|
|
94
|
+
// An npm install updates itself too; a checkout updates with git pull and
|
|
95
|
+
// /botrebuild, so there /botupdate 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: 'botupdate:confirm' },
|
|
109
|
+
{ text: '❌ Cancel', callback_data: 'botupdate:cancel' },
|
|
110
|
+
],
|
|
111
|
+
],
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
export async function handleBotUpdateCallback(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 === 'botupdate:cancel') {
|
|
128
|
+
await ctx.reply('❌ Update cancelled.');
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (data === 'botupdate:telecoder') {
|
|
132
|
+
await updateTeleCoder(ctx);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (data !== 'botupdate: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 /botupdate 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: 'botupdate:telecoder' }]
|
|
186
|
+
: [];
|
|
187
|
+
await ctx.reply(lines.join('\n'), {
|
|
188
|
+
reply_markup: {
|
|
189
|
+
inline_keyboard: [
|
|
190
|
+
[...telecoderButton, { text: '⬆️ Claude Code', callback_data: 'botupdate:confirm' }],
|
|
191
|
+
[{ text: '❌ Cancel', callback_data: 'botupdate: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: /botrestart.');
|
|
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 /botrestart.');
|
|
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 keyInfo = getSessionKeyFromCtx(ctx);
|
|
255
|
+
const model = keyInfo ? getModel(keyInfo.sessionKey) : 'opus';
|
|
256
|
+
const pid = process.pid;
|
|
257
|
+
const memMB = (process.memoryUsage.rss() / 1024 / 1024).toFixed(1);
|
|
258
|
+
// The uptime above is this worker's, and a worker that restarted an hour ago
|
|
259
|
+
// says nothing about the process it restarted inside.
|
|
260
|
+
const warning = await staleLauncherWarning();
|
|
261
|
+
const build = describeRunningBuild();
|
|
262
|
+
const msg = new EntityText().add('🟢 ').bold(`${config.BOT_NAME} is running`).newline(2);
|
|
263
|
+
/** A `Label: value` line; every one but the last ends in a newline. */
|
|
264
|
+
const field = (label, value) => msg.bold(`${label}:`).add(` ${value}`);
|
|
265
|
+
if (build)
|
|
266
|
+
field('Version', build).newline();
|
|
267
|
+
field('Uptime', uptimeStr).newline();
|
|
268
|
+
field('PID', String(pid)).newline();
|
|
269
|
+
field('Memory', `${memMB} MB`).newline();
|
|
270
|
+
const machine = readMemory();
|
|
271
|
+
if (machine) {
|
|
272
|
+
const swap = machine.swapTotalMB > 0 ? `, swap ${machine.swapUsedMB.toLocaleString('en-US')} MB in use` : '';
|
|
273
|
+
field('Machine', `${machine.availableMB.toLocaleString('en-US')} MB available of ${machine.totalMB.toLocaleString('en-US')} MB${swap}`).newline();
|
|
274
|
+
}
|
|
275
|
+
const claudes = getPtyProvider().describeSessions();
|
|
276
|
+
const generating = claudes.filter((s) => s.generating).length;
|
|
277
|
+
field('Claude processes', claudes.length === 0 ? 'none' : `${claudes.length} (${generating} generating)`).newline();
|
|
278
|
+
field('Model', model);
|
|
279
|
+
if (warning)
|
|
280
|
+
msg.newline(2).add(warning);
|
|
281
|
+
await replyFormatted(ctx, msg.build());
|
|
282
|
+
}
|
|
283
|
+
export async function handleBotVersion(ctx) {
|
|
284
|
+
if (!isCheckout()) {
|
|
285
|
+
await handlePackageVersion(ctx);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const [code, remote, warning] = await Promise.all([
|
|
289
|
+
checkCode(getRunningBuild(), getLatestBuild(), PROJECT_ROOT),
|
|
290
|
+
checkRemote(PROJECT_ROOT),
|
|
291
|
+
// A worker's stamp only speaks for that worker, not the launcher it runs in.
|
|
292
|
+
staleLauncherWarning(),
|
|
293
|
+
]);
|
|
294
|
+
const build = describeRunningBuild();
|
|
295
|
+
const answer = [build && `Running: ${build}`, describeCodeCheck(code), describeRemoteCheck(remote)]
|
|
296
|
+
.filter(Boolean)
|
|
297
|
+
.join('\n');
|
|
298
|
+
// Plain text: a commit subject goes out exactly as written.
|
|
299
|
+
await ctx.reply(warning ? `${answer}\n\n${warning}` : answer);
|
|
300
|
+
}
|
|
301
|
+
/** /botversion for a package install: the installed version against npm's latest. */
|
|
302
|
+
async function handlePackageVersion(ctx) {
|
|
303
|
+
const installed = getInstalledVersion();
|
|
304
|
+
const [latest, warning] = await Promise.all([getLatestVersion(), staleLauncherWarning()]);
|
|
305
|
+
const answer = [
|
|
306
|
+
`Running: TeleCoder v${installed ?? '?'}`,
|
|
307
|
+
describeNpmCheck(compareInstalled(installed, latest), detectPackageRunner()),
|
|
308
|
+
].join('\n');
|
|
309
|
+
await ctx.reply(warning ? `${answer}\n\n${warning}` : answer);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Work out how to restart, without doing anything yet.
|
|
313
|
+
*
|
|
314
|
+
* Separate from executing it so a restart is never *announced* before it is
|
|
315
|
+
* known to be possible. Announcing one that then fails is how the bot ends up
|
|
316
|
+
* silently dead with a "restarting..." message as its last word.
|
|
317
|
+
*
|
|
318
|
+
* Returns an error message when there is no way to come back, in which case
|
|
319
|
+
* the bot keeps running.
|
|
320
|
+
*/
|
|
321
|
+
async function planRestart() {
|
|
322
|
+
if (isSystemdService()) {
|
|
323
|
+
// Exiting and letting systemd restart us works only if the unit is set up
|
|
324
|
+
// to (see utils/systemd.ts).
|
|
325
|
+
const unit = getSystemdUnit();
|
|
326
|
+
if (!unit) {
|
|
327
|
+
return {
|
|
328
|
+
error: new EntityText()
|
|
329
|
+
.add('Running under systemd, but the unit name could not be read from ')
|
|
330
|
+
.code('/proc/self/cgroup')
|
|
331
|
+
.add('.')
|
|
332
|
+
.newline(2)
|
|
333
|
+
.add('Restart it by hand: ')
|
|
334
|
+
.code('systemctl --user restart telecoder')
|
|
335
|
+
.build(),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
const behaviour = await getRestartBehaviour(unit);
|
|
339
|
+
if (behaviour === null) {
|
|
340
|
+
return {
|
|
341
|
+
error: new EntityText()
|
|
342
|
+
.add('Running as ')
|
|
343
|
+
.bold(unit.name)
|
|
344
|
+
.add(', but ')
|
|
345
|
+
.code('systemctl show')
|
|
346
|
+
.add(' did not answer, so there is no way to confirm the bot would come back.')
|
|
347
|
+
.newline(2)
|
|
348
|
+
.add('Restart it by hand: ')
|
|
349
|
+
.code(manualRestartCommand(unit))
|
|
350
|
+
.build(),
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
if (!willRestartOnRequestedExit(behaviour)) {
|
|
354
|
+
return {
|
|
355
|
+
error: new EntityText()
|
|
356
|
+
.bold(unit.name)
|
|
357
|
+
.add(' has ')
|
|
358
|
+
.code(`Restart=${behaviour.policy}`)
|
|
359
|
+
.add(', so systemd would not start the bot again.')
|
|
360
|
+
.newline(2)
|
|
361
|
+
.add('Set ')
|
|
362
|
+
.code('Restart=always')
|
|
363
|
+
.add(' in the unit, or restart by hand: ')
|
|
364
|
+
.code(manualRestartCommand(unit))
|
|
365
|
+
.build(),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
return { plan: { kind: 'systemd', unit } };
|
|
369
|
+
}
|
|
370
|
+
// Anything else expects a supervisor (a launchd unit with KeepAlive, pm2,
|
|
371
|
+
// ...) that starts it again when it exits — and in a terminal there is none,
|
|
372
|
+
// so there it says so instead.
|
|
373
|
+
if (process.stdin.isTTY && process.stdout.isTTY) {
|
|
374
|
+
return {
|
|
375
|
+
error: new EntityText()
|
|
376
|
+
.add('This bot is running in a terminal, so nothing would start it again after it exits.')
|
|
377
|
+
.newline(2)
|
|
378
|
+
.add('Stop it there and run ')
|
|
379
|
+
.code(isCheckout() ? 'npm start' : 'telecoder start')
|
|
380
|
+
.add(' again, or run it as a service so restarts work from chat.')
|
|
381
|
+
.build(),
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
return { plan: { kind: 'exit' } };
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Act on a plan from `planRestart`. The systemd path does not come back — the
|
|
388
|
+
* process is on its way out by the time this returns.
|
|
389
|
+
*/
|
|
390
|
+
function executeRestart(plan) {
|
|
391
|
+
if (plan.kind === 'exit') {
|
|
392
|
+
// Same as the systemd path below: the exit is the restart, non-zero so a
|
|
393
|
+
// supervisor that only restarts on failure acts on it too.
|
|
394
|
+
console.log('[Restart] Exiting for the service manager to start the bot again');
|
|
395
|
+
process.exitCode = RESTART_EXIT_CODE;
|
|
396
|
+
process.kill(process.pid, 'SIGTERM');
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
// The exit *is* the restart. Non-zero so both Restart=always and
|
|
400
|
+
// Restart=on-failure act on it; SIGTERM rather than process.exit so the
|
|
401
|
+
// normal graceful shutdown still runs.
|
|
402
|
+
console.log(`[Restart] Exiting for systemd to restart ${plan.unit.name}`);
|
|
403
|
+
process.exitCode = RESTART_EXIT_CODE;
|
|
404
|
+
process.kill(process.pid, 'SIGTERM');
|
|
405
|
+
}
|
|
406
|
+
async function performRestart(ctx, scope) {
|
|
407
|
+
// Multi-instance mode (worker thread) — restart via launcher, not shell script
|
|
408
|
+
if (!isMainThread) {
|
|
409
|
+
// A restart can't make the launcher stale — only a build does that — but
|
|
410
|
+
// it is the moment someone concludes everything is running current code.
|
|
411
|
+
const warning = await staleLauncherWarning();
|
|
412
|
+
const note = warning ? `\n\n${warning}` : '';
|
|
413
|
+
if (scope === 'all') {
|
|
414
|
+
if (config.AUTO_RESTORE_SESSION) {
|
|
415
|
+
await ctx.reply(`🔁 Restarting all bot instances.\n\n⏳ Sessions will be restored automatically.${note}`);
|
|
416
|
+
}
|
|
417
|
+
else {
|
|
418
|
+
await ctx.reply(`🔁 Restarting all bot instances.\n\n⏳ Please wait ~10 seconds.${note}`);
|
|
419
|
+
await sendRestoreButtons(ctx);
|
|
420
|
+
}
|
|
421
|
+
// Marker writing for sibling bots happens in the launcher — it has the
|
|
422
|
+
// tokens to derive each bot's marker path. We can't write them here.
|
|
423
|
+
requestRestartAll(config.AUTO_RESTORE_SESSION);
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
if (config.AUTO_RESTORE_SESSION) {
|
|
427
|
+
await ctx.reply(`🔁 Restarting this bot instance.\n\n⏳ Session will be restored automatically.${note}`);
|
|
428
|
+
writeReloadMarker();
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
await ctx.reply(`🔁 Restarting this bot instance.\n\n⏳ Other bots will not be affected. Please wait ~10 seconds.${note}`);
|
|
432
|
+
await sendRestoreButtons(ctx);
|
|
433
|
+
}
|
|
434
|
+
requestRestart();
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
// Single-instance mode — the supervisor restarts us once we exit
|
|
438
|
+
const planned = await planRestart();
|
|
439
|
+
if ('error' in planned) {
|
|
440
|
+
await replyFormatted(ctx, new EntityText().add('❌ Cannot restart.').newline(2).append(planned.error).build());
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
if (config.AUTO_RESTORE_SESSION) {
|
|
444
|
+
await ctx.reply('🔁 Restarting bot.\n\n⏳ Session will be restored automatically.');
|
|
445
|
+
writeReloadMarker();
|
|
446
|
+
}
|
|
447
|
+
else {
|
|
448
|
+
await replyFormatted(ctx, new EntityText()
|
|
449
|
+
.add('🔁 Restarting bot.')
|
|
450
|
+
.newline(2)
|
|
451
|
+
.add('⏳ Please wait at least ')
|
|
452
|
+
.bold('10-15 seconds')
|
|
453
|
+
.add(' before checking status or resuming.')
|
|
454
|
+
.build());
|
|
455
|
+
await sendRestoreButtons(ctx);
|
|
456
|
+
}
|
|
457
|
+
executeRestart(planned.plan);
|
|
458
|
+
}
|
|
459
|
+
export async function handleBotRestart(ctx) {
|
|
460
|
+
const args = ctx.message?.text?.split(/\s+/).slice(1).join(' ').trim();
|
|
461
|
+
// Cross-bot restart: /botrestart <name> — direct, no menu
|
|
462
|
+
if (args && !isMainThread && args.toLowerCase() !== 'all' && args.toLowerCase() !== 'one' && args.toLowerCase() !== 'this') {
|
|
463
|
+
const result = await requestSiblingRestart(args, config.AUTO_RESTORE_SESSION);
|
|
464
|
+
if (result.success) {
|
|
465
|
+
await replyFormatted(ctx, new EntityText()
|
|
466
|
+
.add('🔁 Restarting ')
|
|
467
|
+
.bold(result.name ?? args)
|
|
468
|
+
.add('... it should be back in ~10 seconds.')
|
|
469
|
+
.build());
|
|
470
|
+
}
|
|
471
|
+
else {
|
|
472
|
+
await replyFormatted(ctx, new EntityText()
|
|
473
|
+
.add('❌ Could not restart ')
|
|
474
|
+
.bold(args)
|
|
475
|
+
.add(`: ${result.reason ?? 'unknown error'}`)
|
|
476
|
+
.build());
|
|
477
|
+
}
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
// Legacy direct invocations: /botrestart all | /botrestart one | /botrestart this
|
|
481
|
+
if (args?.toLowerCase() === 'all') {
|
|
482
|
+
await performRestart(ctx, 'all');
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
if (args?.toLowerCase() === 'one' || args?.toLowerCase() === 'this') {
|
|
486
|
+
await performRestart(ctx, 'one');
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
// Single-instance mode: only one process exists, so just confirm.
|
|
490
|
+
if (isMainThread) {
|
|
491
|
+
await ctx.reply('🔁 Restart the bot?', {
|
|
492
|
+
reply_markup: {
|
|
493
|
+
inline_keyboard: [
|
|
494
|
+
[
|
|
495
|
+
{ text: '✅ Restart', callback_data: 'botrestart:one' },
|
|
496
|
+
{ text: '❌ Cancel', callback_data: 'botrestart:cancel' },
|
|
497
|
+
],
|
|
498
|
+
],
|
|
499
|
+
},
|
|
500
|
+
});
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
// Multi-instance (worker) mode: offer this/all/cancel
|
|
504
|
+
await ctx.reply('🔁 Restart which?', {
|
|
505
|
+
reply_markup: {
|
|
506
|
+
inline_keyboard: [
|
|
507
|
+
[{ text: '🔧 This instance only', callback_data: 'botrestart:one' }],
|
|
508
|
+
[{ text: '🌐 All instances', callback_data: 'botrestart:all' }],
|
|
509
|
+
[{ text: '❌ Cancel', callback_data: 'botrestart:cancel' }],
|
|
510
|
+
],
|
|
511
|
+
},
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
export async function handleBotRestartCallback(ctx) {
|
|
515
|
+
const data = ctx.callbackQuery?.data;
|
|
516
|
+
if (!data)
|
|
517
|
+
return;
|
|
518
|
+
await ctx.answerCallbackQuery();
|
|
519
|
+
// Remove the menu keyboard so it can't be tapped twice
|
|
520
|
+
try {
|
|
521
|
+
await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } });
|
|
522
|
+
}
|
|
523
|
+
catch {
|
|
524
|
+
// ignore — message may have been edited or deleted
|
|
525
|
+
}
|
|
526
|
+
if (data === 'botrestart:cancel') {
|
|
527
|
+
await ctx.reply('❌ Restart cancelled.');
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
if (data === 'botrestart:all') {
|
|
531
|
+
await performRestart(ctx, 'all');
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
if (data === 'botrestart:one') {
|
|
535
|
+
await performRestart(ctx, 'one');
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
/** Run the build without blocking the event loop. execSync would freeze this
|
|
540
|
+
* worker for the whole build, and a worker that stops sending heartbeats for
|
|
541
|
+
* 90s gets force-restarted by the launcher mid-build. */
|
|
542
|
+
function runBuild() {
|
|
543
|
+
return new Promise((resolve, reject) => {
|
|
544
|
+
execFile('npm', ['run', 'build'], { cwd: PROJECT_ROOT, timeout: 120_000, maxBuffer: 4 * 1024 * 1024 }, (error, _stdout, stderr) => {
|
|
545
|
+
if (error) {
|
|
546
|
+
reject(new Error((stderr || error.message || 'Unknown build error').trim()));
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
resolve();
|
|
550
|
+
});
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Said wherever someone is about to believe their code is now current: the
|
|
555
|
+
* launcher is running what it loaded at startup, and neither a rebuild nor a
|
|
556
|
+
* restart of the instances reaches it.
|
|
557
|
+
*
|
|
558
|
+
* Note what this does not claim — that the build in hand is the one that
|
|
559
|
+
* changed the launcher. The fingerprint only knows the launcher differs from
|
|
560
|
+
* the copy this process started with, which stays true for every later build
|
|
561
|
+
* until someone restarts it.
|
|
562
|
+
*
|
|
563
|
+
* Empty whenever the launcher is current or can't be asked. Plain text, which
|
|
564
|
+
* callers append as it is.
|
|
565
|
+
*/
|
|
566
|
+
async function staleLauncherWarning() {
|
|
567
|
+
if (!await launcherIsStale())
|
|
568
|
+
return '';
|
|
569
|
+
return `⚠️ The launcher is still running the code it started with — a build since then replaced it `
|
|
570
|
+
+ `on disk, and restarting instances can't reload it. To pick that up, ${launcherRestartHint()}; `
|
|
571
|
+
+ `that drops every live session.`;
|
|
572
|
+
}
|
|
573
|
+
async function performRebuild(ctx, scope) {
|
|
574
|
+
// Only a launcher can wait on other instances; checked before building, so
|
|
575
|
+
// the answer isn't a build nobody restarts onto.
|
|
576
|
+
if (scope === 'idle' && isMainThread) {
|
|
577
|
+
await ctx.reply('⚠️ "When idle" restarts the instances of a multi-instance setup — this bot runs on its own. Use /botrebuild to rebuild and restart it now.');
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
// Step 1: Build
|
|
581
|
+
await ctx.reply('🔨 Building...');
|
|
582
|
+
try {
|
|
583
|
+
await runBuild();
|
|
584
|
+
}
|
|
585
|
+
catch (error) {
|
|
586
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
587
|
+
await ctx.reply(`❌ Build failed. Aborting reload.\n\n${message.slice(-500).slice(0, 400)}`);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
// Step 2: Restart. For 'all', the launcher writes markers for every sibling
|
|
591
|
+
// (we can't — markers live at per-bot paths keyed by each bot's token). For
|
|
592
|
+
// 'one' and single-instance, write the local marker now.
|
|
593
|
+
if (!isMainThread) {
|
|
594
|
+
// Asked before the restart is requested: this worker is about to exit, and
|
|
595
|
+
// a second message sent into that gap may never make it out.
|
|
596
|
+
const warning = await staleLauncherWarning();
|
|
597
|
+
const note = warning ? `\n\n${warning}` : '';
|
|
598
|
+
if (scope === 'idle') {
|
|
599
|
+
await restartAllWhenIdle(ctx, warning);
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
if (scope === 'all') {
|
|
603
|
+
await ctx.reply(`✅ Build succeeded. Restarting all instances...${note}`);
|
|
604
|
+
requestRestartAll(config.AUTO_RESTORE_SESSION);
|
|
605
|
+
}
|
|
606
|
+
else {
|
|
607
|
+
if (config.AUTO_RESTORE_SESSION)
|
|
608
|
+
writeReloadMarker();
|
|
609
|
+
await ctx.reply(`✅ Build succeeded. Restarting this instance...${note}`);
|
|
610
|
+
if (!config.AUTO_RESTORE_SESSION)
|
|
611
|
+
await sendRestoreButtons(ctx);
|
|
612
|
+
requestRestart();
|
|
613
|
+
}
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
// Single-instance mode (scope is moot — only one process). Planned before
|
|
617
|
+
// the build is reported, so a bot that cannot restart says so while it is
|
|
618
|
+
// still alive to say it.
|
|
619
|
+
const planned = await planRestart();
|
|
620
|
+
if ('error' in planned) {
|
|
621
|
+
await replyFormatted(ctx, new EntityText()
|
|
622
|
+
.add('✅ Build succeeded, but the bot cannot restart itself.')
|
|
623
|
+
.newline(2)
|
|
624
|
+
.append(planned.error)
|
|
625
|
+
.build());
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
if (config.AUTO_RESTORE_SESSION)
|
|
629
|
+
writeReloadMarker();
|
|
630
|
+
await ctx.reply('✅ Build succeeded. Restarting...');
|
|
631
|
+
if (!config.AUTO_RESTORE_SESSION)
|
|
632
|
+
await sendRestoreButtons(ctx);
|
|
633
|
+
executeRestart(planned.plan);
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Hand the restart to the launcher, to make as each instance runs out of work.
|
|
637
|
+
* The message posted here is the one the launcher keeps up to date.
|
|
638
|
+
*/
|
|
639
|
+
async function restartAllWhenIdle(ctx, warning) {
|
|
640
|
+
const chatId = ctx.chat?.id;
|
|
641
|
+
if (chatId === undefined)
|
|
642
|
+
return;
|
|
643
|
+
const status = await ctx.reply('✅ Build succeeded. Restarting each instance once it has nothing left to finish...');
|
|
644
|
+
const names = await requestRestartAllWhenIdle({
|
|
645
|
+
autoResume: config.AUTO_RESTORE_SESSION,
|
|
646
|
+
chatId,
|
|
647
|
+
messageId: status.message_id,
|
|
648
|
+
note: warning || undefined,
|
|
649
|
+
});
|
|
650
|
+
if (names !== null)
|
|
651
|
+
return;
|
|
652
|
+
// The launcher that never answers is the one that predates the request —
|
|
653
|
+
// which the stale check usually says outright.
|
|
654
|
+
const text = '✅ Build succeeded, but the launcher did not take the restart — it is running code from '
|
|
655
|
+
+ `before "when idle" existed, so nothing is restarting. To pick it up, ${launcherRestartHint()}; that drops `
|
|
656
|
+
+ 'every live session. /botrebuild all restarts the instances now instead.';
|
|
657
|
+
try {
|
|
658
|
+
await ctx.api.editMessageText(chatId, status.message_id, text);
|
|
659
|
+
}
|
|
660
|
+
catch {
|
|
661
|
+
await ctx.reply(text);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* /botrebuild needs the source to build, which only a checkout has. Says so,
|
|
666
|
+
* and returns true, when this isn't one.
|
|
667
|
+
*/
|
|
668
|
+
async function refuseRebuildOutsideCheckout(ctx) {
|
|
669
|
+
if (isCheckout())
|
|
670
|
+
return false;
|
|
671
|
+
await ctx.reply('⚠️ /botrebuild rebuilds a source checkout of TeleCoder, and this one was installed from npm — there is no source here to build. '
|
|
672
|
+
+ 'Use /botupdate to install a newer release, and /botrestart to restart.');
|
|
673
|
+
return true;
|
|
674
|
+
}
|
|
675
|
+
export async function handleBotRebuild(ctx) {
|
|
676
|
+
if (await refuseRebuildOutsideCheckout(ctx))
|
|
677
|
+
return;
|
|
678
|
+
const args = ctx.message?.text?.split(/\s+/).slice(1).join(' ').trim();
|
|
679
|
+
// Legacy direct invocation: /botrebuild all
|
|
680
|
+
if (args?.toLowerCase() === 'all') {
|
|
681
|
+
await performRebuild(ctx, 'all');
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
if (args?.toLowerCase() === 'one' || args?.toLowerCase() === 'this') {
|
|
685
|
+
await performRebuild(ctx, 'one');
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
if (args?.toLowerCase() === 'idle' || args?.toLowerCase() === 'all idle') {
|
|
689
|
+
await performRebuild(ctx, 'idle');
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
// Single-instance mode: only one process exists, so skip the this-vs-all
|
|
693
|
+
// distinction and just confirm.
|
|
694
|
+
if (isMainThread) {
|
|
695
|
+
await ctx.reply('🔄 Rebuild and restart the bot?', {
|
|
696
|
+
reply_markup: {
|
|
697
|
+
inline_keyboard: [
|
|
698
|
+
[
|
|
699
|
+
{ text: '✅ Rebuild', callback_data: 'botrebuild:one' },
|
|
700
|
+
{ text: '❌ Cancel', callback_data: 'botrebuild:cancel' },
|
|
701
|
+
],
|
|
702
|
+
],
|
|
703
|
+
},
|
|
704
|
+
});
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
// Multi-instance (worker) mode: offer this/all/cancel
|
|
708
|
+
await ctx.reply('🔄 Rebuild and restart which?', {
|
|
709
|
+
reply_markup: {
|
|
710
|
+
inline_keyboard: [
|
|
711
|
+
[{ text: '🔧 This instance only', callback_data: 'botrebuild:one' }],
|
|
712
|
+
[{ text: '🌐 All instances', callback_data: 'botrebuild:all' }],
|
|
713
|
+
[{ text: '⏳ All instances, each once it is idle', callback_data: 'botrebuild:idle' }],
|
|
714
|
+
[{ text: '❌ Cancel', callback_data: 'botrebuild:cancel' }],
|
|
715
|
+
],
|
|
716
|
+
},
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
export async function handleBotRebuildCallback(ctx) {
|
|
720
|
+
const data = ctx.callbackQuery?.data;
|
|
721
|
+
if (!data)
|
|
722
|
+
return;
|
|
723
|
+
await ctx.answerCallbackQuery();
|
|
724
|
+
// Remove the menu keyboard so it can't be tapped twice
|
|
725
|
+
try {
|
|
726
|
+
await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } });
|
|
727
|
+
}
|
|
728
|
+
catch {
|
|
729
|
+
// ignore — message may have been edited or deleted
|
|
730
|
+
}
|
|
731
|
+
if (data === 'botrebuild:cancel') {
|
|
732
|
+
await ctx.reply('❌ Rebuild cancelled.');
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
if (await refuseRebuildOutsideCheckout(ctx))
|
|
736
|
+
return;
|
|
737
|
+
if (data === 'botrebuild:all') {
|
|
738
|
+
await performRebuild(ctx, 'all');
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
if (data === 'botrebuild:one') {
|
|
742
|
+
await performRebuild(ctx, 'one');
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (data === 'botrebuild:idle') {
|
|
746
|
+
await performRebuild(ctx, 'idle');
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
// The buttons on the "when idle" status message. The launcher redraws that
|
|
750
|
+
// message itself, buttons and all, so a tap only needs an answer when there
|
|
751
|
+
// was nothing left to act on.
|
|
752
|
+
if (data === 'botrebuild:idle_force' || data === 'botrebuild:idle_cancel') {
|
|
753
|
+
const found = await controlIdleRestart(data === 'botrebuild:idle_force' ? 'force' : 'cancel');
|
|
754
|
+
if (!found)
|
|
755
|
+
await ctx.reply('Nothing is waiting to restart any more.');
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
export async function handleRestartCallback(ctx) {
|
|
760
|
+
const data = ctx.callbackQuery?.data;
|
|
761
|
+
if (!data)
|
|
762
|
+
return;
|
|
763
|
+
if (data === 'restart:continue') {
|
|
764
|
+
await ctx.answerCallbackQuery();
|
|
765
|
+
await continueLastSession(ctx);
|
|
766
|
+
}
|
|
767
|
+
else if (data === 'restart:resume') {
|
|
768
|
+
await ctx.answerCallbackQuery();
|
|
769
|
+
await handleResume(ctx);
|
|
770
|
+
}
|
|
771
|
+
else {
|
|
772
|
+
await ctx.answerCallbackQuery();
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Taps on a "Continue where you left off, or start fresh?" prompt. Startup
|
|
777
|
+
* doesn't ask any more — a restart just carries on — but the prompts it already
|
|
778
|
+
* posted still sit in chats with live buttons.
|
|
779
|
+
*/
|
|
780
|
+
export async function handleStartupCallback(ctx) {
|
|
781
|
+
const data = ctx.callbackQuery?.data;
|
|
782
|
+
if (!data)
|
|
783
|
+
return;
|
|
784
|
+
await ctx.answerCallbackQuery();
|
|
785
|
+
// Remove the inline keyboard so the buttons can't be tapped twice.
|
|
786
|
+
try {
|
|
787
|
+
await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } });
|
|
788
|
+
}
|
|
789
|
+
catch {
|
|
790
|
+
// ignore — message may have been edited or deleted
|
|
791
|
+
}
|
|
792
|
+
if (data === 'startup:continue') {
|
|
793
|
+
await continueLastSession(ctx);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
if (data === 'startup:fresh') {
|
|
797
|
+
// Startup has put the old conversation back by now, so leaving it alone no
|
|
798
|
+
// longer starts anything fresh — clear it the way /clear does.
|
|
799
|
+
await handleClear(ctx);
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
//# sourceMappingURL=admin.js.map
|