telecoder 1.2.0 → 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 +142 -130
- package/CHANGELOG.md +683 -2
- package/README.md +36 -32
- package/dist/audio/transcribe.js +0 -9
- package/dist/bin/mcp-server.js +46 -61
- package/dist/bot/bot.js +162 -181
- package/dist/bot/command-catalog.js +263 -0
- package/dist/bot/deleted-threads.js +103 -0
- package/dist/bot/file-access.js +35 -26
- package/dist/bot/handlers/album.handler.js +128 -0
- package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
- package/dist/bot/handlers/command/access.js +1 -1
- package/dist/bot/handlers/command/admin.js +86 -110
- package/dist/bot/handlers/command/all-view.js +33 -0
- package/dist/bot/handlers/command/auto-approve.js +3 -3
- 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 +20 -69
- package/dist/bot/handlers/command/cleanup.js +329 -0
- package/dist/bot/handlers/command/model.js +40 -119
- package/dist/bot/handlers/command/prefs-scope.js +255 -90
- package/dist/bot/handlers/command/project.js +31 -109
- package/dist/bot/handlers/command/resume.js +8 -4
- package/dist/bot/handlers/command/session.js +74 -213
- package/dist/bot/handlers/command/settings.js +92 -447
- package/dist/bot/handlers/command/shared.js +32 -35
- package/dist/bot/handlers/command/tasks.js +263 -95
- package/dist/bot/handlers/command/thread.js +128 -0
- package/dist/bot/handlers/command/topic-store.js +14 -53
- package/dist/bot/handlers/command/topic.js +8 -61
- package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
- package/dist/bot/handlers/command-fallback.js +179 -0
- package/dist/bot/handlers/command.handler.js +96 -422
- package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
- package/dist/bot/handlers/media-fallback.js +12 -7
- package/dist/bot/handlers/message/replies.js +10 -87
- package/dist/bot/handlers/message/shared.js +9 -31
- package/dist/bot/handlers/message/turn-notify.js +15 -49
- package/dist/bot/handlers/message/turn-runner.js +18 -103
- package/dist/bot/handlers/message.handler.js +59 -52
- package/dist/bot/handlers/newbot.handler.js +13 -4
- package/dist/bot/handlers/photo.handler.js +88 -129
- package/dist/bot/handlers/prompts.handler.js +11 -11
- package/dist/bot/handlers/running-note.js +2 -2
- package/dist/bot/handlers/session-guard.js +4 -4
- package/dist/bot/handlers/suggestion.handler.js +2 -2
- package/dist/bot/handlers/tree.handler.js +20 -20
- package/dist/bot/handlers/voice.handler.js +23 -85
- package/dist/bot/kept-threads.js +51 -0
- package/dist/bot/middleware/album-collector.js +69 -0
- package/dist/bot/middleware/auth.middleware.js +1 -1
- package/dist/bot/middleware/group-mention.middleware.js +11 -5
- package/dist/bot/middleware/queued-messages.js +143 -32
- package/dist/bot/middleware/stale-filter.js +0 -22
- package/dist/build-info.json +5 -5
- package/dist/claude/ask-user-form.js +517 -0
- package/dist/claude/ask-user.js +94 -26
- package/dist/claude/auto-topic-haiku.js +17 -0
- package/dist/claude/available-commands.js +22 -19
- package/dist/claude/background-hint.js +91 -0
- package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
- package/dist/claude/carry-over.js +0 -2
- package/dist/claude/ccr-shim.js +12 -10
- package/dist/claude/claude-auth.js +6 -10
- package/dist/claude/command-parser.js +49 -43
- package/dist/claude/cost-overlay-scraper.js +7 -2
- package/dist/claude/effort-level.js +5 -0
- package/dist/claude/enabled-plugins.js +12 -16
- package/dist/claude/in-flight-tracker.js +21 -0
- package/dist/claude/mcp-bridge.js +86 -58
- package/dist/claude/memory-guard.js +400 -0
- package/dist/claude/message-offsets.js +5 -5
- package/dist/claude/modal-relay.js +401 -34
- package/dist/claude/model-catalog.js +20 -3
- package/dist/claude/monitor-relay.js +130 -15
- package/dist/claude/native-commands.js +40 -0
- package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
- package/dist/claude/permission-gate.js +11 -10
- package/dist/claude/permission-mode.js +19 -45
- package/dist/claude/prewarm.js +70 -0
- package/dist/claude/pty-idle-reaper.js +96 -0
- package/dist/claude/pty-provider.js +473 -188
- package/dist/claude/pty-spawn-config.js +79 -32
- package/dist/claude/pty-watch.js +201 -0
- package/dist/claude/request-queue.js +7 -35
- package/dist/claude/rewind.js +111 -0
- package/dist/claude/scheduled-runner.js +1 -3
- package/dist/claude/scheduler.js +6 -2
- package/dist/claude/scope-guard.js +8 -3
- package/dist/claude/screen-marks.js +83 -0
- package/dist/claude/screen-render.js +96 -0
- package/dist/claude/session-history.js +4 -2
- package/dist/claude/session-jsonl.js +162 -15
- package/dist/claude/session-manager.js +29 -8
- package/dist/claude/session-move.js +70 -0
- package/dist/claude/shell-mode-gate.js +60 -0
- package/dist/claude/side-question.js +20 -17
- package/dist/claude/stage-images.js +5 -5
- package/dist/claude/tasks-overlay-scraper.js +143 -20
- package/dist/claude/thread-judge-haiku.js +88 -0
- package/dist/claude/tip-scraper.js +3 -4
- package/dist/claude/tui-modal.js +272 -27
- package/dist/claude/tui-state.js +74 -2
- package/dist/claude/turn-end.js +15 -1
- package/dist/claude/turn-prose.js +1 -1
- package/dist/claude/typed-answer.js +104 -0
- package/dist/claude/update-banner-relay.js +1 -1
- package/dist/cli/commands/doctor.js +48 -15
- package/dist/cli/commands/help.js +11 -2
- package/dist/cli/commands/init.js +16 -13
- package/dist/cli/commands/service.js +40 -8
- package/dist/cli/commands/start.js +10 -0
- package/dist/cli/commands/watch.js +322 -0
- package/dist/cli/dispatch.js +5 -0
- package/dist/cli/init/env-file.js +1 -1
- package/dist/cli/init/flow.js +114 -47
- package/dist/cli/init/prompter.js +8 -0
- package/dist/cli/init/telegram.js +35 -9
- package/dist/cli/service/render.js +3 -3
- package/dist/config.js +156 -131
- package/dist/index.js +107 -31
- package/dist/launcher.js +34 -7
- package/dist/providers/ccr-introspect.js +1 -8
- package/dist/providers/ccr-provider.js +19 -20
- package/dist/providers/claude-provider.js +4 -57
- package/dist/providers/prefs-sync.js +16 -59
- package/dist/providers/provider-router.js +24 -23
- package/dist/providers/spawn-settings.js +45 -0
- package/dist/providers/user-preferences.js +127 -19
- package/dist/restart-when-idle.js +27 -7
- package/dist/startup/auto-continue.js +2 -2
- package/dist/startup/auto-resume.js +3 -15
- package/dist/startup/notices.js +1 -1
- package/dist/startup/verify-token.js +4 -4
- package/dist/telegram/action-logger.js +3 -165
- package/dist/telegram/background-activity-card.js +1 -1
- package/dist/telegram/botname-settings.js +71 -125
- package/dist/telegram/client-options.js +6 -7
- package/dist/telegram/force-reply-tracker.js +55 -16
- package/dist/telegram/message-sender.js +92 -360
- package/dist/telegram/prompt-label.js +11 -5
- package/dist/telegram/streaming-turn.js +5 -7
- package/dist/telegram/table-lists.js +56 -0
- package/dist/telegram/task-list.js +4 -4
- package/dist/telegram/task-tracker.js +45 -126
- package/dist/telegram/terminal-renderer.js +1 -5
- package/dist/telegram/thread-titles.js +74 -2
- package/dist/telegram/threads-setup.js +1 -1
- package/dist/utils/admins.js +2 -2
- package/dist/utils/bot-icon.js +248 -0
- package/dist/utils/bot-token.js +8 -5
- package/dist/utils/build-info.js +3 -3
- package/dist/utils/caffeinate.js +6 -3
- package/dist/utils/claude-env.js +0 -1
- package/dist/utils/claude-version.js +2 -2
- package/dist/utils/config-home.js +3 -3
- package/dist/utils/download.js +41 -15
- package/dist/utils/exit-codes.js +11 -0
- package/dist/utils/format.js +3 -6
- package/dist/utils/home-project.js +1 -1
- package/dist/utils/idle-restart.js +1 -1
- package/dist/utils/install-mode.js +1 -1
- package/dist/utils/instance-config.js +1 -1
- package/dist/utils/instances.js +1 -1
- package/dist/utils/keyed-settings.js +2 -2
- package/dist/utils/memory-pressure.js +60 -0
- package/dist/utils/npm-version.js +2 -2
- package/dist/utils/resolve-claude-bin.js +13 -24
- package/dist/utils/respawn-backoff.js +9 -0
- package/dist/utils/stale-launcher.js +1 -1
- package/dist/utils/systemd.js +8 -8
- package/dist/utils/telegram-proxy.js +72 -0
- package/dist/utils/uploads-dir.js +27 -0
- package/dist/utils/verbosity.js +8 -8
- package/dist/utils/version-check.js +5 -5
- package/package.json +3 -4
- package/dist/bot/handlers/command/media.js +0 -197
- package/dist/bot/handlers/command/streaming-mode.js +0 -16
- package/dist/bot/handlers/message/throttle.js +0 -49
- package/dist/claude/agent-watchdog.js +0 -162
- package/dist/claude/agent.js +0 -1458
- package/dist/claude/held-query.js +0 -190
- package/dist/claude/mcp-tools.js +0 -354
- package/dist/claude/sdk-permission-gate.js +0 -77
- package/dist/claude/session-cost.js +0 -41
- package/dist/claude/system-prompt.js +0 -162
- package/dist/providers/sdk-provider.js +0 -37
- package/dist/telegram/telegraph-settings.js +0 -31
- package/dist/telegram/telegraph.js +0 -453
- package/dist/telegram/terminal-settings.js +0 -25
- package/dist/tts/tts-settings.js +0 -62
- package/dist/tts/tts.js +0 -245
- package/dist/tts/voice-reply.js +0 -78
- package/dist/utils/debug-agent.js +0 -117
- package/dist/utils/debug-watchdog.js +0 -121
- package/dist/utils/project-data-dir.js +0 -33
- package/dist/utils/reasoning-summary.js +0 -12
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The /botname command: the name the bot shows in Telegram.
|
|
3
|
+
*
|
|
4
|
+
* `/botname <name>` saves the name per bot (it wins over `BOT_NAME`) and renames
|
|
5
|
+
* the bot on Telegram. Telegram throttles renames hard, so when it refuses the
|
|
6
|
+
* reply says so and the name is sent again as soon as the cooldown ends.
|
|
7
|
+
* `/botname reset` goes back to `BOT_NAME`; `/botname` alone shows the state.
|
|
8
|
+
*/
|
|
9
|
+
import { config, getBotNameSource, setStoredBotName } from '../../../config.js';
|
|
10
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
11
|
+
import { replyFormatted } from '../../../telegram/send.js';
|
|
12
|
+
import { pushBotName, getBotNameCooldownUntil, formatCooldownLeft, } from '../../../telegram/botname-settings.js';
|
|
13
|
+
/** Telegram's limit on a bot's name. */
|
|
14
|
+
const MAX_NAME_LENGTH = 64;
|
|
15
|
+
export async function handleBotName(ctx) {
|
|
16
|
+
const text = ctx.message?.text || '';
|
|
17
|
+
const arg = text.split(' ').slice(1).join(' ').trim();
|
|
18
|
+
if (!arg)
|
|
19
|
+
return showBotName(ctx);
|
|
20
|
+
const name = arg === 'reset' ? undefined : arg;
|
|
21
|
+
if (name && name.length > MAX_NAME_LENGTH) {
|
|
22
|
+
await replyFormatted(ctx, `❌ A bot name is at most ${MAX_NAME_LENGTH} characters; this one is ${name.length}.`);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
setStoredBotName(name);
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
await replyFormatted(ctx, `❌ Could not save the name: ${err instanceof Error ? err.message : String(err)}`);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const result = await pushBotName(ctx.api, config.BOT_NAME);
|
|
33
|
+
const msg = new EntityText().add('✅ Bot name: ').bold(config.BOT_NAME);
|
|
34
|
+
if (!name)
|
|
35
|
+
msg.add(' (back to ').code('BOT_NAME').add(')');
|
|
36
|
+
msg.newline().italic(describeResult(result));
|
|
37
|
+
await replyFormatted(ctx, msg.build());
|
|
38
|
+
}
|
|
39
|
+
function describeResult(result) {
|
|
40
|
+
switch (result.status) {
|
|
41
|
+
case 'sent':
|
|
42
|
+
case 'no_change':
|
|
43
|
+
return 'Telegram shows it now.';
|
|
44
|
+
case 'queued':
|
|
45
|
+
return 'Telegram shows it within a minute.';
|
|
46
|
+
case 'newly_blocked':
|
|
47
|
+
case 'still_blocked':
|
|
48
|
+
return `Telegram is rate-limiting renames and still shows the old name. `
|
|
49
|
+
+ `The new one is sent again in ${formatCooldownLeft(result.blockedUntilMs)}.`;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function showBotName(ctx) {
|
|
53
|
+
let live;
|
|
54
|
+
try {
|
|
55
|
+
live = (await ctx.api.getMyName()).name;
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
live = undefined;
|
|
59
|
+
}
|
|
60
|
+
const msg = new EntityText().add('✏️ ').bold('Bot name').newline(2);
|
|
61
|
+
msg.add('Telegram shows: ').bold(live ?? '(unknown)').newline();
|
|
62
|
+
const source = getBotNameSource();
|
|
63
|
+
if (source === 'default') {
|
|
64
|
+
msg.add('As chosen in BotFather; ').code('BOT_NAME').add(' is not set.');
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
msg.add(source === 'command' ? 'Set with /botname: ' : 'From BOT_NAME: ').bold(config.BOT_NAME);
|
|
68
|
+
const cooldownUntil = getBotNameCooldownUntil();
|
|
69
|
+
if (live !== undefined && live !== config.BOT_NAME && cooldownUntil !== undefined) {
|
|
70
|
+
msg.newline().add(`⏳ Telegram is rate-limiting renames; it gets this name in ${formatCooldownLeft(cooldownUntil)}.`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
msg.newline(2).italic('/botname <name> renames the bot, /botname reset goes back to BOT_NAME. Admins only.');
|
|
74
|
+
await replyFormatted(ctx, msg.build());
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=botname.js.map
|
|
@@ -6,11 +6,10 @@
|
|
|
6
6
|
* losing its place.
|
|
7
7
|
*/
|
|
8
8
|
import { sessionManager } from '../../../claude/session-manager.js';
|
|
9
|
-
import { getActiveQuery } from '../../../claude/request-queue.js';
|
|
10
9
|
import { askForkedSideQuestion } from '../../../claude/side-question.js';
|
|
11
10
|
import { messageSender } from '../../../telegram/message-sender.js';
|
|
12
11
|
import { getActiveProviderName } from '../../../providers/provider-router.js';
|
|
13
|
-
import {
|
|
12
|
+
import { getCcrShimPath } from '../../../claude/ccr-shim.js';
|
|
14
13
|
import { sanitizeError } from '../../../utils/sanitize.js';
|
|
15
14
|
import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
|
|
16
15
|
// ── /btw ─────────────────────────────────────────────────────────
|
|
@@ -33,39 +32,29 @@ export async function handleBtw(ctx) {
|
|
|
33
32
|
* context of the tap rather than of a typed command.
|
|
34
33
|
*/
|
|
35
34
|
export async function askBtw(ctx, sessionKey, question) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const usesPty = getActiveProviderName(sessionKey) === 'claude'
|
|
40
|
-
&& getActiveMethod(sessionKey) === 'pty';
|
|
41
|
-
if (usesPty) {
|
|
42
|
-
await handleBtwViaFork(ctx, sessionKey, question);
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
const activeQuery = getActiveQuery(sessionKey);
|
|
46
|
-
if (!activeQuery) {
|
|
47
|
-
// The query object only exists while a turn is in flight — this is not a
|
|
48
|
-
// statement about whether the conversation itself exists.
|
|
49
|
-
await ctx.reply('No turn is running right now, so there is nothing to ask alongside. Send your question as a regular message instead.');
|
|
50
|
-
return;
|
|
51
|
-
}
|
|
52
|
-
// askSideQuestion exists at runtime but isn't in the TypeScript types yet
|
|
53
|
-
const queryAny = activeQuery;
|
|
54
|
-
if (typeof queryAny.askSideQuestion !== 'function') {
|
|
55
|
-
await ctx.reply('Side questions are not supported by the current SDK version.');
|
|
35
|
+
const session = sessionManager.getSession(sessionKey);
|
|
36
|
+
if (!session?.claudeSessionId) {
|
|
37
|
+
await ctx.reply('No conversation to ask about yet. Send a message first, then /btw can answer alongside it.');
|
|
56
38
|
return;
|
|
57
39
|
}
|
|
58
|
-
|
|
59
|
-
// it's alive with a ticking elapsed — without it nothing appears until the
|
|
60
|
-
// whole answer lands.
|
|
40
|
+
const chatId = ctx.chat.id;
|
|
61
41
|
const headline = `💬 /btw — ${btwLabel(question)}`;
|
|
42
|
+
// Labelled ack: this sits alongside the main turn's live status message, so
|
|
43
|
+
// it has to be obvious which one belongs to the side question. It then
|
|
44
|
+
// doubles as the progress line, and finally as a one-line receipt.
|
|
62
45
|
const ack = await ctx.reply(`${headline}\nasking on the side… (main task keeps running)`);
|
|
63
|
-
const progress = new BtwProgressLine(ctx,
|
|
64
|
-
const startedAt = Date.now();
|
|
46
|
+
const progress = new BtwProgressLine(ctx, chatId, ack.message_id, headline);
|
|
65
47
|
try {
|
|
66
|
-
const result = await
|
|
67
|
-
|
|
68
|
-
|
|
48
|
+
const result = await askForkedSideQuestion({
|
|
49
|
+
question,
|
|
50
|
+
sessionId: session.claudeSessionId,
|
|
51
|
+
cwd: session.workingDirectory,
|
|
52
|
+
// A CCR session's thinking blocks only replay through CCR.
|
|
53
|
+
executable: getActiveProviderName(sessionKey) === 'ccr' ? getCcrShimPath() : undefined,
|
|
54
|
+
onProgress: (p) => progress.update(p),
|
|
55
|
+
});
|
|
56
|
+
await progress.finish(result.toolCount ?? 0, result.elapsedMs ?? 0);
|
|
57
|
+
if (!result.response) {
|
|
69
58
|
await ctx.reply("I don't have enough context to answer that.");
|
|
70
59
|
return;
|
|
71
60
|
}
|
|
@@ -73,7 +62,7 @@ export async function askBtw(ctx, sessionKey, question) {
|
|
|
73
62
|
}
|
|
74
63
|
catch (error) {
|
|
75
64
|
const msg = error instanceof Error ? error.message : 'Unknown error';
|
|
76
|
-
console.error('[btw]
|
|
65
|
+
console.error('[btw] Fork error:', sanitizeError(error));
|
|
77
66
|
await progress.fail();
|
|
78
67
|
await ctx.reply(`Failed to answer side question: ${msg}`);
|
|
79
68
|
}
|
|
@@ -97,44 +86,6 @@ export function btwLabel(question) {
|
|
|
97
86
|
export function formatSideAnswer(question, response) {
|
|
98
87
|
return `💬 **/btw** — _${btwLabel(question)}_\n\n${response}`;
|
|
99
88
|
}
|
|
100
|
-
/**
|
|
101
|
-
* PTY-mode `/btw`: shell out to a forked, non-persisted copy of the live
|
|
102
|
-
* claude session so the running turn is never interrupted or mutated.
|
|
103
|
-
*/
|
|
104
|
-
async function handleBtwViaFork(ctx, sessionKey, question) {
|
|
105
|
-
const session = sessionManager.getSession(sessionKey);
|
|
106
|
-
if (!session?.claudeSessionId) {
|
|
107
|
-
await ctx.reply('No conversation to ask about yet. Send a message first, then /btw can answer alongside it.');
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
const chatId = ctx.chat.id;
|
|
111
|
-
const headline = `💬 /btw — ${btwLabel(question)}`;
|
|
112
|
-
// Labelled ack: this sits alongside the main turn's live status message, so
|
|
113
|
-
// it has to be obvious which one belongs to the side question. It then
|
|
114
|
-
// doubles as the progress line, and finally as a one-line receipt.
|
|
115
|
-
const ack = await ctx.reply(`${headline}\nasking on the side… (main task keeps running)`);
|
|
116
|
-
const progress = new BtwProgressLine(ctx, chatId, ack.message_id, headline);
|
|
117
|
-
try {
|
|
118
|
-
const result = await askForkedSideQuestion({
|
|
119
|
-
question,
|
|
120
|
-
sessionId: session.claudeSessionId,
|
|
121
|
-
cwd: session.workingDirectory,
|
|
122
|
-
onProgress: (p) => progress.update(p),
|
|
123
|
-
});
|
|
124
|
-
await progress.finish(result.toolCount ?? 0, result.elapsedMs ?? 0);
|
|
125
|
-
if (!result.response) {
|
|
126
|
-
await ctx.reply("I don't have enough context to answer that.");
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
await messageSender.sendMessage(ctx, formatSideAnswer(question, result.response));
|
|
130
|
-
}
|
|
131
|
-
catch (error) {
|
|
132
|
-
const msg = error instanceof Error ? error.message : 'Unknown error';
|
|
133
|
-
console.error('[btw] Fork error:', sanitizeError(error));
|
|
134
|
-
await progress.fail();
|
|
135
|
-
await ctx.reply(`Failed to answer side question: ${msg}`);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
89
|
/** Minimum gap between /btw progress edits — Telegram rate-limits edits hard. */
|
|
139
90
|
const BTW_EDIT_INTERVAL_MS = 2000;
|
|
140
91
|
/** How often the elapsed counter ticks while a single slow tool runs. */
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /threadcleanup: delete the threads of a private chat that are done with, in one go.
|
|
3
|
+
*
|
|
4
|
+
* Telegram can't list a chat's threads to a bot, but the chat history has one
|
|
5
|
+
* entry per thread the bot has had a session in, with when it was last used.
|
|
6
|
+
* That's the list. A thread is left alone when deleting it could lose
|
|
7
|
+
* something: the thread /threadcleanup is sent in, a kept one (/threadkeep), one with a
|
|
8
|
+
* turn running, messages waiting or one set aside, a background task, a
|
|
9
|
+
* schedule, or one used more recently than the idle threshold (2 days, or
|
|
10
|
+
* what `/threadcleanup 7d` says).
|
|
11
|
+
*
|
|
12
|
+
* The rest are offered as a list of buttons to tick, and Haiku reads the end of
|
|
13
|
+
* each to guess which still have loose ends: those start unticked, marked ⚠️.
|
|
14
|
+
* Nothing goes until the Delete tap, and every thread is checked again then,
|
|
15
|
+
* since one may have come back to life in the meantime. Each is deleted the
|
|
16
|
+
* way /threaddelete does it; the transcripts stay on disk for /resume.
|
|
17
|
+
*
|
|
18
|
+
* Private chats only: a group's topics are everyone's, and go one at a time.
|
|
19
|
+
*/
|
|
20
|
+
import { randomBytes } from 'crypto';
|
|
21
|
+
import { sessionHistory } from '../../../claude/session-history.js';
|
|
22
|
+
import { scheduler } from '../../../claude/scheduler.js';
|
|
23
|
+
import { judgeThreads } from '../../../claude/thread-judge-haiku.js';
|
|
24
|
+
import { hasRunningTasks } from '../../../telegram/background-activity-card.js';
|
|
25
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
26
|
+
import { cutLabel } from '../../../telegram/prompt-label.js';
|
|
27
|
+
import { editCallbackMessage, editFormatted, replyFormatted } from '../../../telegram/send.js';
|
|
28
|
+
import { hasImplicitName, threadDisplayName, threadName } from '../../../telegram/thread-titles.js';
|
|
29
|
+
import { getSessionKeyFromCtx, parseSessionKey } from '../../../utils/session-key.js';
|
|
30
|
+
import { sanitizeError } from '../../../utils/sanitize.js';
|
|
31
|
+
import { isThreadForgotten } from '../../deleted-threads.js';
|
|
32
|
+
import { isThreadKept } from '../../kept-threads.js';
|
|
33
|
+
import { pendingWork } from '../../middleware/queued-messages.js';
|
|
34
|
+
import { deleteThread } from './thread.js';
|
|
35
|
+
import { parseCallback } from './shared.js';
|
|
36
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
37
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
38
|
+
export const DEFAULT_MIN_IDLE_MS = 2 * DAY_MS;
|
|
39
|
+
/** Thread buttons in one list; Telegram takes 100 buttons, and a phone screen far fewer. */
|
|
40
|
+
export const MAX_ROWS = 40;
|
|
41
|
+
/** Lines of "left alone" before the rest are only counted. */
|
|
42
|
+
const MAX_SKIPPED_LINES = 15;
|
|
43
|
+
const MAX_LABEL_CHARS = 30;
|
|
44
|
+
/** How long a list's buttons keep working. */
|
|
45
|
+
const VIEW_TTL_MS = HOUR_MS;
|
|
46
|
+
const UNITS = { h: HOUR_MS, d: DAY_MS, w: 7 * DAY_MS };
|
|
47
|
+
/** The idle threshold an argument asks for: undefined for one that isn't one. */
|
|
48
|
+
export function parseMinIdle(arg) {
|
|
49
|
+
const a = arg.trim().toLowerCase();
|
|
50
|
+
if (a === '')
|
|
51
|
+
return DEFAULT_MIN_IDLE_MS;
|
|
52
|
+
if (a === '0' || a === 'any' || a === 'all')
|
|
53
|
+
return 0;
|
|
54
|
+
const m = /^(\d+)\s*([hdw])$/.exec(a);
|
|
55
|
+
return m ? Number(m[1]) * UNITS[m[2]] : undefined;
|
|
56
|
+
}
|
|
57
|
+
/** A span the short way: 45m, 5h, 3d, 2w. */
|
|
58
|
+
export function formatSpan(ms) {
|
|
59
|
+
if (ms < HOUR_MS)
|
|
60
|
+
return `${Math.max(1, Math.floor(ms / 60000))}m`;
|
|
61
|
+
if (ms < DAY_MS)
|
|
62
|
+
return `${Math.floor(ms / HOUR_MS)}h`;
|
|
63
|
+
if (ms < 14 * DAY_MS)
|
|
64
|
+
return `${Math.floor(ms / DAY_MS)}d`;
|
|
65
|
+
return `${Math.floor(ms / (7 * DAY_MS))}w`;
|
|
66
|
+
}
|
|
67
|
+
function nameOf(sessionKey, entry) {
|
|
68
|
+
const shown = hasImplicitName(sessionKey) ? undefined : threadDisplayName(sessionKey);
|
|
69
|
+
return shown || threadName(entry.topic ?? '', '', entry.projectName) || entry.projectName;
|
|
70
|
+
}
|
|
71
|
+
/** Why deleting this thread now could lose something, apart from how recently it was used. */
|
|
72
|
+
export function busyReason(sessionKey) {
|
|
73
|
+
if (isThreadKept(sessionKey))
|
|
74
|
+
return 'kept';
|
|
75
|
+
const work = pendingWork(sessionKey);
|
|
76
|
+
if (work)
|
|
77
|
+
return work;
|
|
78
|
+
if (hasRunningTasks(sessionKey))
|
|
79
|
+
return 'background task running';
|
|
80
|
+
if (scheduler.listSchedules(sessionKey).some((s) => !s.disabled))
|
|
81
|
+
return 'has a schedule';
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
/** This chat's threads, split into the ones to offer (idle longest first) and the ones left alone. */
|
|
85
|
+
export function surveyThreads(chatId, currentKey, minIdleMs, now = Date.now()) {
|
|
86
|
+
const rows = [];
|
|
87
|
+
const skipped = [];
|
|
88
|
+
for (const [sessionKey, entry] of sessionHistory.getAllActiveSessions()) {
|
|
89
|
+
const key = parseSessionKey(sessionKey);
|
|
90
|
+
if (key.chatId !== chatId || key.threadId === undefined || isThreadForgotten(sessionKey))
|
|
91
|
+
continue;
|
|
92
|
+
const name = nameOf(sessionKey, entry);
|
|
93
|
+
const idleMs = now - new Date(entry.lastActivity).getTime();
|
|
94
|
+
const reason = sessionKey === currentKey ? 'this thread'
|
|
95
|
+
: busyReason(sessionKey) ?? (idleMs < minIdleMs ? `active ${formatSpan(idleMs)} ago` : undefined);
|
|
96
|
+
if (reason) {
|
|
97
|
+
skipped.push({ name, reason });
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
rows.push({
|
|
101
|
+
sessionKey,
|
|
102
|
+
name,
|
|
103
|
+
idleMs,
|
|
104
|
+
lastActivity: entry.lastActivity,
|
|
105
|
+
summary: { topic: entry.topic, lastUserMessage: entry.lastMessagePreview, lastReply: entry.lastAssistantPreview },
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
rows.sort((a, b) => b.idleMs - a.idleMs);
|
|
109
|
+
return { rows, skipped };
|
|
110
|
+
}
|
|
111
|
+
const views = new Map();
|
|
112
|
+
function pruneViews(now) {
|
|
113
|
+
for (const [id, view] of views)
|
|
114
|
+
if (view.expiresAt <= now)
|
|
115
|
+
views.delete(id);
|
|
116
|
+
}
|
|
117
|
+
/** A thread starts ticked unless Haiku saw loose ends in it. */
|
|
118
|
+
export function buildView(chatId, minIdleMs, survey, verdicts, now = Date.now()) {
|
|
119
|
+
const rows = survey.rows.slice(0, MAX_ROWS).map((row, i) => ({ ...row, verdict: verdicts?.[i] }));
|
|
120
|
+
return {
|
|
121
|
+
id: randomBytes(4).toString('hex'),
|
|
122
|
+
chatId,
|
|
123
|
+
minIdleMs,
|
|
124
|
+
rows,
|
|
125
|
+
ticked: new Set(rows.flatMap((row, i) => (row.verdict === 'open' ? [] : [i]))),
|
|
126
|
+
skipped: survey.skipped,
|
|
127
|
+
more: Math.max(0, survey.rows.length - MAX_ROWS),
|
|
128
|
+
judged: rows.length === 0 ? 'no' : verdicts ? 'yes' : 'failed',
|
|
129
|
+
expiresAt: now + VIEW_TTL_MS,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function addSkipped(text, skipped) {
|
|
133
|
+
if (skipped.length === 0)
|
|
134
|
+
return;
|
|
135
|
+
text.newline(2).bold(`Left alone (${skipped.length}):`);
|
|
136
|
+
for (const s of skipped.slice(0, MAX_SKIPPED_LINES)) {
|
|
137
|
+
text.newline().add(`${s.reason === 'kept' ? '📌' : '•'} ${cutLabel(s.name, 48)}: `).italic(s.reason);
|
|
138
|
+
}
|
|
139
|
+
if (skipped.length > MAX_SKIPPED_LINES)
|
|
140
|
+
text.newline().italic(`…and ${skipped.length - MAX_SKIPPED_LINES} more`);
|
|
141
|
+
}
|
|
142
|
+
export function renderView(view) {
|
|
143
|
+
const text = new EntityText().add('🧹 ').bold('Clean up threads');
|
|
144
|
+
if (view.rows.length === 0) {
|
|
145
|
+
text.newline(2).add(view.minIdleMs > 0
|
|
146
|
+
? `No threads idle for ${formatSpan(view.minIdleMs)} or more to clean up.`
|
|
147
|
+
: 'No threads to clean up.');
|
|
148
|
+
addSkipped(text, view.skipped);
|
|
149
|
+
if (view.minIdleMs > 0 && view.skipped.some((s) => s.reason.startsWith('active '))) {
|
|
150
|
+
text.newline(2).add('💡 ').code('/threadcleanup 12h').add(' offers threads idle for less long.');
|
|
151
|
+
}
|
|
152
|
+
return { text: text.build(), keyboard: [] };
|
|
153
|
+
}
|
|
154
|
+
text.newline(2).add('Delete the ticked threads? ')
|
|
155
|
+
.add('Telegram can\'t undo this, but the conversations stay on disk, so ').code('/resume').add(' can still pick them up.');
|
|
156
|
+
if (view.judged === 'failed') {
|
|
157
|
+
text.newline(2).add('⚠️ Haiku couldn\'t check these for loose ends, so look them over.');
|
|
158
|
+
}
|
|
159
|
+
else if (view.rows.some((r) => r.verdict === 'open')) {
|
|
160
|
+
text.newline(2).add('⚠️ marks a thread where Haiku saw loose ends. Those start unticked.');
|
|
161
|
+
}
|
|
162
|
+
if (view.more > 0) {
|
|
163
|
+
text.newline(2).italic(`Showing the ${view.rows.length} idle longest. ${view.more} more after these: send /threadcleanup again.`);
|
|
164
|
+
}
|
|
165
|
+
addSkipped(text, view.skipped);
|
|
166
|
+
text.newline(2).add('💡 ').code('/threadkeep').add(' in a thread keeps it out of cleanups.');
|
|
167
|
+
const keyboard = view.rows.map((row, i) => [{
|
|
168
|
+
text: `${view.ticked.has(i) ? '☑️' : '⬜'} ${row.verdict === 'open' ? '⚠️ ' : ''}${cutLabel(row.name, MAX_LABEL_CHARS)} · ${formatSpan(row.idleMs)}`,
|
|
169
|
+
callback_data: `threadcleanup:${view.id}:t:${i}`,
|
|
170
|
+
}]);
|
|
171
|
+
if (view.rows.length > 1) {
|
|
172
|
+
keyboard.push([
|
|
173
|
+
{ text: '☑️ All', callback_data: `threadcleanup:${view.id}:all` },
|
|
174
|
+
{ text: '⬜ None', callback_data: `threadcleanup:${view.id}:none` },
|
|
175
|
+
]);
|
|
176
|
+
}
|
|
177
|
+
const count = view.ticked.size;
|
|
178
|
+
keyboard.push([
|
|
179
|
+
...(count > 0 ? [{ text: `🗑️ Delete ${count}`, callback_data: `threadcleanup:${view.id}:go` }] : []),
|
|
180
|
+
{ text: '✗ Cancel', callback_data: `threadcleanup:${view.id}:x` },
|
|
181
|
+
]);
|
|
182
|
+
return { text: text.build(), keyboard };
|
|
183
|
+
}
|
|
184
|
+
// ── /threadcleanup ─────────────────────────────────────────────────────────────
|
|
185
|
+
export async function handleThreadCleanup(ctx) {
|
|
186
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
187
|
+
if (!keyInfo)
|
|
188
|
+
return;
|
|
189
|
+
const { chatId, sessionKey } = keyInfo;
|
|
190
|
+
if (ctx.chat?.type !== 'private') {
|
|
191
|
+
await replyFormatted(ctx, new EntityText()
|
|
192
|
+
.add('🧹 ').code('/threadcleanup').add(' works in private chats, where every thread is yours. ')
|
|
193
|
+
.add('In a group, delete topics one at a time with ').code('/threaddelete').add('.').build());
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const arg = (ctx.message?.text ?? '').split(' ').slice(1).join(' ');
|
|
197
|
+
const minIdleMs = parseMinIdle(arg);
|
|
198
|
+
if (minIdleMs === undefined) {
|
|
199
|
+
await replyFormatted(ctx, new EntityText()
|
|
200
|
+
.add('ℹ️ Usage: ').code('/threadcleanup').add(' offers threads idle for 2 days or more; ')
|
|
201
|
+
.code('/threadcleanup 12h').add(', ').code('/threadcleanup 7d').add(' or ').code('/threadcleanup 2w').add(' set the idle time, and ')
|
|
202
|
+
.code('/threadcleanup 0').add(' offers every idle thread.').build());
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const now = Date.now();
|
|
206
|
+
pruneViews(now);
|
|
207
|
+
const survey = surveyThreads(chatId, sessionKey, minIdleMs, now);
|
|
208
|
+
if (survey.rows.length === 0) {
|
|
209
|
+
await replyFormatted(ctx, renderView(buildView(chatId, minIdleMs, survey, undefined, now)).text);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const shown = Math.min(survey.rows.length, MAX_ROWS);
|
|
213
|
+
const status = await ctx.reply(`🧹 Looking through ${shown} idle thread${shown === 1 ? '' : 's'} for loose ends…`);
|
|
214
|
+
const verdicts = await judgeThreads(survey.rows.slice(0, MAX_ROWS).map((r) => r.summary));
|
|
215
|
+
const view = buildView(chatId, minIdleMs, survey, verdicts);
|
|
216
|
+
views.set(view.id, view);
|
|
217
|
+
const { text, keyboard } = renderView(view);
|
|
218
|
+
await editFormatted(ctx.api, chatId, status.message_id, text, { reply_markup: { inline_keyboard: keyboard } });
|
|
219
|
+
}
|
|
220
|
+
// ── The buttons ──────────────────────────────────────────────────────────
|
|
221
|
+
/** Delete what's ticked, checking each thread again first. The report. */
|
|
222
|
+
export async function deleteTicked(api, view) {
|
|
223
|
+
const deleted = [];
|
|
224
|
+
const kept = [];
|
|
225
|
+
const failed = [];
|
|
226
|
+
for (const i of [...view.ticked].sort((a, b) => a - b)) {
|
|
227
|
+
const row = view.rows[i];
|
|
228
|
+
if (!row)
|
|
229
|
+
continue;
|
|
230
|
+
// Deleted some other way since the list went up.
|
|
231
|
+
if (isThreadForgotten(row.sessionKey)) {
|
|
232
|
+
deleted.push(row.name);
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
// Used again since then, which moves its history entry on.
|
|
236
|
+
const entry = sessionHistory.getLastSession(row.sessionKey);
|
|
237
|
+
const usedSince = entry !== undefined && entry.lastActivity > row.lastActivity;
|
|
238
|
+
const reason = busyReason(row.sessionKey) ?? (usedSince ? 'used since the list went up' : undefined);
|
|
239
|
+
if (reason) {
|
|
240
|
+
kept.push({ name: row.name, reason });
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
const error = await deleteThread(api, row.sessionKey, '/threadcleanup');
|
|
245
|
+
if (error)
|
|
246
|
+
failed.push({ name: row.name, reason: error });
|
|
247
|
+
else
|
|
248
|
+
deleted.push(row.name);
|
|
249
|
+
}
|
|
250
|
+
catch (err) {
|
|
251
|
+
failed.push({ name: row.name, reason: sanitizeError(err) });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const text = new EntityText().add('🧹 ');
|
|
255
|
+
text.bold(deleted.length === 0 ? 'No threads deleted' : `Deleted ${deleted.length} thread${deleted.length === 1 ? '' : 's'}`);
|
|
256
|
+
for (const name of deleted.slice(0, MAX_ROWS))
|
|
257
|
+
text.newline().add(`• ${cutLabel(name, 48)}`);
|
|
258
|
+
if (kept.length > 0) {
|
|
259
|
+
text.newline(2).bold('Kept, since they changed:');
|
|
260
|
+
for (const s of kept)
|
|
261
|
+
text.newline().add(`• ${cutLabel(s.name, 48)}: `).italic(s.reason);
|
|
262
|
+
}
|
|
263
|
+
if (failed.length > 0) {
|
|
264
|
+
text.newline(2).bold('Couldn\'t delete:');
|
|
265
|
+
for (const s of failed)
|
|
266
|
+
text.newline().add(`• ${cutLabel(s.name, 48)}: `).italic(s.reason);
|
|
267
|
+
}
|
|
268
|
+
if (deleted.length > 0) {
|
|
269
|
+
text.newline(2).add('The conversations stay on disk: ').code('/resume').add(' picks any of them up again.');
|
|
270
|
+
}
|
|
271
|
+
return text.build();
|
|
272
|
+
}
|
|
273
|
+
export async function handleThreadCleanupCallback(ctx) {
|
|
274
|
+
const cb = parseCallback(ctx, 'threadcleanup:');
|
|
275
|
+
if (!cb)
|
|
276
|
+
return;
|
|
277
|
+
const m = /^threadcleanup:([0-9a-f]+):(t|all|none|go|x)(?::(\d+))?$/.exec(cb.data);
|
|
278
|
+
const view = m ? views.get(m[1]) : undefined;
|
|
279
|
+
if (!m || !view || view.chatId !== cb.chatId || view.expiresAt <= Date.now()) {
|
|
280
|
+
await ctx.answerCallbackQuery({ text: 'This list has expired. Send /threadcleanup again.' }).catch(() => { });
|
|
281
|
+
await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } }).catch(() => { });
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
const action = m[2];
|
|
285
|
+
if (action === 'x') {
|
|
286
|
+
views.delete(view.id);
|
|
287
|
+
await ctx.answerCallbackQuery({ text: 'Nothing deleted.' }).catch(() => { });
|
|
288
|
+
await editCallbackMessage(ctx, new EntityText().add('👍 Nothing deleted.').build()).catch(() => { });
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
if (action === 'go') {
|
|
292
|
+
// Gone before the first delete, so a second tap can't start a second run.
|
|
293
|
+
views.delete(view.id);
|
|
294
|
+
await ctx.answerCallbackQuery({ text: 'Deleting…' }).catch(() => { });
|
|
295
|
+
await editCallbackMessage(ctx, `🧹 Deleting ${view.ticked.size} thread${view.ticked.size === 1 ? '' : 's'}…`).catch(() => { });
|
|
296
|
+
const report = await deleteTicked(ctx.api, view);
|
|
297
|
+
await editCallbackMessage(ctx, report).catch((err) => {
|
|
298
|
+
console.error('[ThreadCleanup] Could not post the report:', sanitizeError(err));
|
|
299
|
+
});
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (action === 't') {
|
|
303
|
+
const i = Number(m[3]);
|
|
304
|
+
if (i >= 0 && i < view.rows.length) {
|
|
305
|
+
if (view.ticked.has(i))
|
|
306
|
+
view.ticked.delete(i);
|
|
307
|
+
else
|
|
308
|
+
view.ticked.add(i);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
else if (action === 'all') {
|
|
312
|
+
view.ticked = new Set(view.rows.map((_, i) => i));
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
view.ticked = new Set();
|
|
316
|
+
}
|
|
317
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
318
|
+
const { text, keyboard } = renderView(view);
|
|
319
|
+
await editCallbackMessage(ctx, text, { reply_markup: { inline_keyboard: keyboard } }).catch(() => { });
|
|
320
|
+
}
|
|
321
|
+
/** Test seam: forget every open list. */
|
|
322
|
+
export function resetCleanupViewsForTest() {
|
|
323
|
+
views.clear();
|
|
324
|
+
}
|
|
325
|
+
/** Test seam: an open list, by id. */
|
|
326
|
+
export function cleanupViewForTest(id) {
|
|
327
|
+
return views.get(id);
|
|
328
|
+
}
|
|
329
|
+
//# sourceMappingURL=cleanup.js.map
|