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
|
@@ -1,32 +1,30 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* /
|
|
2
|
+
* /branch — hand off a conversation from this bot to a sibling bot at a chosen
|
|
3
3
|
* past assistant message.
|
|
4
4
|
*
|
|
5
5
|
* Tap flow:
|
|
6
|
-
* 1. "
|
|
6
|
+
* 1. "🌱 Branch" button on a past bot message → branch:pick
|
|
7
7
|
* ↳ shows picker of sibling bots
|
|
8
|
-
* 2. Tap target bot →
|
|
8
|
+
* 2. Tap target bot → branch:to:<botId>:<msgId>
|
|
9
9
|
* ↳ shows confirmation
|
|
10
|
-
* 3. Tap Confirm →
|
|
11
|
-
* ↳ truncates source JSONL, writes pending
|
|
10
|
+
* 3. Tap Confirm → branch:confirm:<botId>:<msgId>
|
|
11
|
+
* ↳ truncates source JSONL, writes pending branch to target's file
|
|
12
12
|
*
|
|
13
|
-
* On a bot with threads none of that is asked: the
|
|
14
|
-
* new thread at once with createForumTopic, the
|
|
15
|
-
* thread's session, and this one carries on.
|
|
16
|
-
* carry `fork:to:thread:<msgId>`, which goes the same way through the
|
|
17
|
-
* confirmation.
|
|
13
|
+
* On a bot with threads none of that is asked: the 🌱 tap (or /branch) opens a
|
|
14
|
+
* new thread at once with createForumTopic, the branch goes into the new
|
|
15
|
+
* thread's session, and this one carries on.
|
|
18
16
|
*
|
|
19
17
|
* Target-side pickup (in message.handler):
|
|
20
|
-
* user sends any message → bot sees pending
|
|
21
|
-
* Accept →
|
|
22
|
-
* Decline →
|
|
18
|
+
* user sends any message → bot sees pending branch → shows accept/decline
|
|
19
|
+
* Accept → branch:accept (loads transcript, switches project if needed)
|
|
20
|
+
* Decline → branch:decline (discards pending branch)
|
|
23
21
|
*
|
|
24
|
-
* Both confirmations keep a
|
|
25
|
-
* "
|
|
26
|
-
* — so the same point can be
|
|
22
|
+
* Both confirmations keep a 🌱 Branch button anchored at the branch point — the
|
|
23
|
+
* "Branched to" message here and the loaded branch's in the bot that received it
|
|
24
|
+
* — so the same point can be branched again from either chat without scrolling
|
|
27
25
|
* back to the message it was taken from.
|
|
28
26
|
*
|
|
29
|
-
* /
|
|
27
|
+
* /branchaccept and /branchdecline slash commands behave the same as the buttons, in
|
|
30
28
|
* case the inline keyboard isn't accessible.
|
|
31
29
|
*/
|
|
32
30
|
import * as fs from 'fs';
|
|
@@ -35,18 +33,18 @@ import * as crypto from 'crypto';
|
|
|
35
33
|
import { BOT_ID, config } from '../../config.js';
|
|
36
34
|
import { buildSessionKey, getSessionKeyFromCtx } from '../../utils/session-key.js';
|
|
37
35
|
import { messageOffsets, countJsonlLines } from '../../claude/message-offsets.js';
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
36
|
+
import { BRANCH_KEYBOARD, BRANCH_MARKER_KEYBOARD } from '../../telegram/message-sender.js';
|
|
37
|
+
import { getPendingBranch, putPendingBranch, removePendingBranch, markBranchOffered, listPendingBranches, pendingBranchesPathFor, } from '../../claude/pending-branches.js';
|
|
40
38
|
import { listSiblingBots, findBotById } from '../../utils/instances.js';
|
|
41
39
|
import { buildLetteredKeyboard, letteredOptionLines } from '../../telegram/lettered-options.js';
|
|
42
|
-
import { sessionJsonlPath, lastAssistantTurnText, lastExchangeIn, rewriteJsonlSessionId,
|
|
40
|
+
import { sessionJsonlPath, lastAssistantTurnText, lastExchangeIn, rewriteJsonlSessionId, branchPastRunningTurn, } from '../../claude/session-jsonl.js';
|
|
43
41
|
import { sessionManager } from '../../claude/session-manager.js';
|
|
44
42
|
import { clearConversation } from '../../providers/provider-router.js';
|
|
45
43
|
import { isAllowedUser } from '../../utils/user-roster.js';
|
|
46
44
|
import { EntityText, joinMessages, plain } from '../../telegram/entities.js';
|
|
47
45
|
import { editCallbackMessage, replyFormatted, sendFormatted } from '../../telegram/send.js';
|
|
48
46
|
import { cutLabel, promptLabel } from '../../telegram/prompt-label.js';
|
|
49
|
-
import {
|
|
47
|
+
import { restoreTopic } from './command.handler.js';
|
|
50
48
|
import { getSessionTopic } from './command.handler.js';
|
|
51
49
|
import { sessionDisplayName } from './command/shared.js';
|
|
52
50
|
import { adoptThread, threadName } from '../../telegram/thread-titles.js';
|
|
@@ -56,28 +54,22 @@ import { buildSyntheticCtx } from '../../claude/synthetic-ctx.js';
|
|
|
56
54
|
import { replayIntoThread } from '../middleware/queued-messages.js';
|
|
57
55
|
import { sanitizeError } from '../../utils/sanitize.js';
|
|
58
56
|
import { summarizeTopicWithHaiku } from '../../claude/auto-topic-haiku.js';
|
|
59
|
-
|
|
57
|
+
/** In front of a branched thread's name, so it reads apart from the one it came from. */
|
|
58
|
+
const BRANCH_THREAD_PREFIX = '🌱 ';
|
|
60
59
|
/**
|
|
61
|
-
*
|
|
62
|
-
* a new thread. The picker no longer offers it, but pickers already in a chat do.
|
|
63
|
-
*/
|
|
64
|
-
const THREAD_TARGET = 'thread';
|
|
65
|
-
/** In front of a forked thread's name, so it reads apart from the one it came from. */
|
|
66
|
-
const FORK_THREAD_PREFIX = '🍴 ';
|
|
67
|
-
/**
|
|
68
|
-
* Whether a fork can open a thread of its own here: a private chat with a bot
|
|
60
|
+
* Whether a branch can open a thread of its own here: a private chat with a bot
|
|
69
61
|
* that has threads turned on. Groups have forum topics, but people name and
|
|
70
|
-
* order those for each other, so a
|
|
62
|
+
* order those for each other, so a branch doesn't add to them.
|
|
71
63
|
*
|
|
72
|
-
* Where it can, that's where every
|
|
64
|
+
* Where it can, that's where every branch goes, without a picker: a new thread
|
|
73
65
|
* keeps both conversations open side by side, which a branch here or a
|
|
74
66
|
* sibling bot only approximates, and someone who turned threads on wants them.
|
|
75
67
|
*/
|
|
76
|
-
function
|
|
68
|
+
function canBranchToThread(ctx) {
|
|
77
69
|
return ctx.chat?.type === 'private' && ctx.me?.has_topics_enabled === true;
|
|
78
70
|
}
|
|
79
71
|
/**
|
|
80
|
-
* Build the
|
|
72
|
+
* Build the branch-target picker: this bot itself (a fresh branch of the current
|
|
81
73
|
* conversation) first, then every sibling bot, then Cancel. Self is always
|
|
82
74
|
* offered so you can branch a thread without needing a second bot.
|
|
83
75
|
*
|
|
@@ -96,38 +88,38 @@ export function buildTargetPicker(anchorMsgId) {
|
|
|
96
88
|
// parenthesising it on the label costs the whole keyboard its labels.
|
|
97
89
|
{
|
|
98
90
|
label: '🌱 New branch here',
|
|
99
|
-
description: BOT_NAME,
|
|
100
|
-
callbackData: `
|
|
91
|
+
description: config.BOT_NAME,
|
|
92
|
+
callbackData: `branch:to:${BOT_ID}:${anchorMsgId}`,
|
|
101
93
|
},
|
|
102
94
|
...listSiblingBots(BOT_ID).map((b) => ({
|
|
103
95
|
label: b.name,
|
|
104
|
-
callbackData: `
|
|
96
|
+
callbackData: `branch:to:${b.botId}:${anchorMsgId}`,
|
|
105
97
|
})),
|
|
106
98
|
];
|
|
107
99
|
return {
|
|
108
100
|
lines: letteredOptionLines(targets),
|
|
109
101
|
keyboard: [
|
|
110
102
|
...buildLetteredKeyboard(targets),
|
|
111
|
-
[{ text: 'Cancel', callback_data: '
|
|
103
|
+
[{ text: 'Cancel', callback_data: 'branch:cancel' }],
|
|
112
104
|
],
|
|
113
105
|
};
|
|
114
106
|
}
|
|
115
107
|
/**
|
|
116
|
-
* Compose the "
|
|
108
|
+
* Compose the "branch received" message + inline keyboard. Shared between the
|
|
117
109
|
* lazy in-message path (reply in current chat) and the proactive watcher
|
|
118
110
|
* (DMs the user without waiting for them to type).
|
|
119
111
|
*/
|
|
120
|
-
function
|
|
121
|
-
const projectLabel = path.basename(
|
|
112
|
+
function buildBranchOffer(branch, mode) {
|
|
113
|
+
const projectLabel = path.basename(branch.projectPath);
|
|
122
114
|
const text = new EntityText()
|
|
123
|
-
.add('📦 ').bold(`
|
|
115
|
+
.add('📦 ').bold(`Branch received from ${branch.fromBotName}`).newline(2)
|
|
124
116
|
.add('Project: ').bold(projectLabel);
|
|
125
|
-
if (
|
|
126
|
-
text.newline().bold('Topic:').add(` ${
|
|
127
|
-
if (
|
|
128
|
-
text.newline(2).italic('Last assistant message:').newline().add(
|
|
117
|
+
if (branch.topic)
|
|
118
|
+
text.newline().bold('Topic:').add(` ${branch.topic}`);
|
|
119
|
+
if (branch.assistantPreview) {
|
|
120
|
+
text.newline(2).italic('Last assistant message:').newline().add(branch.assistantPreview.substring(0, 200));
|
|
129
121
|
}
|
|
130
|
-
text.newline(2).add("Accepting will replace this bot's current conversation (saved to /resume history). Decline to discard the
|
|
122
|
+
text.newline(2).add("Accepting will replace this bot's current conversation (saved to /resume history). Decline to discard the branch.");
|
|
131
123
|
if (mode === 'lazy') {
|
|
132
124
|
text.newline(2).italic("Your message was held back so it doesn't get attached to the wrong context. Re-send it after deciding.");
|
|
133
125
|
}
|
|
@@ -136,14 +128,14 @@ function buildForkOffer(fork, mode) {
|
|
|
136
128
|
keyboard: {
|
|
137
129
|
inline_keyboard: [
|
|
138
130
|
[
|
|
139
|
-
{ text: '✅ Accept
|
|
140
|
-
{ text: '❌ Decline', callback_data: '
|
|
131
|
+
{ text: '✅ Accept branch', callback_data: 'branch:accept' },
|
|
132
|
+
{ text: '❌ Decline', callback_data: 'branch:decline' },
|
|
141
133
|
],
|
|
142
134
|
],
|
|
143
135
|
},
|
|
144
136
|
};
|
|
145
137
|
}
|
|
146
|
-
export async function
|
|
138
|
+
export async function handleBranchCallback(ctx) {
|
|
147
139
|
const data = ctx.callbackQuery?.data;
|
|
148
140
|
if (!data)
|
|
149
141
|
return;
|
|
@@ -169,13 +161,13 @@ export async function handleForkCallback(ctx) {
|
|
|
169
161
|
await onDecline(ctx);
|
|
170
162
|
}
|
|
171
163
|
else {
|
|
172
|
-
await ctx.answerCallbackQuery({ text: 'Unknown
|
|
164
|
+
await ctx.answerCallbackQuery({ text: 'Unknown branch action.' });
|
|
173
165
|
}
|
|
174
166
|
}
|
|
175
167
|
catch (err) {
|
|
176
|
-
console.error('[
|
|
168
|
+
console.error('[Branch] callback failed:', err instanceof Error ? err.message : err);
|
|
177
169
|
try {
|
|
178
|
-
await ctx.answerCallbackQuery({ text: '
|
|
170
|
+
await ctx.answerCallbackQuery({ text: 'Branch failed — see bot logs.' });
|
|
179
171
|
}
|
|
180
172
|
catch { /* ignore */ }
|
|
181
173
|
}
|
|
@@ -189,18 +181,18 @@ async function onPick(ctx) {
|
|
|
189
181
|
}
|
|
190
182
|
const offset = messageOffsets.lookup(keyInfo.sessionKey, msgId);
|
|
191
183
|
if (!offset) {
|
|
192
|
-
await ctx.answerCallbackQuery({ text: '
|
|
184
|
+
await ctx.answerCallbackQuery({ text: 'Branch point no longer available for this message.' });
|
|
193
185
|
return;
|
|
194
186
|
}
|
|
195
|
-
if (
|
|
196
|
-
await
|
|
187
|
+
if (canBranchToThread(ctx)) {
|
|
188
|
+
await branchIntoThread(ctx, keyInfo.sessionKey, offset, msgId);
|
|
197
189
|
return;
|
|
198
190
|
}
|
|
199
191
|
await ctx.answerCallbackQuery();
|
|
200
192
|
const projectLabel = path.basename(offset.projectPath);
|
|
201
193
|
const picker = buildTargetPicker(msgId);
|
|
202
194
|
await replyFormatted(ctx, new EntityText()
|
|
203
|
-
.add('
|
|
195
|
+
.add('🌱 ').bold('Branch conversation').newline(2)
|
|
204
196
|
.add('From this point in ').bold(projectLabel).add(' — pick where to branch it:').newline(2)
|
|
205
197
|
.add(picker.lines.join('\n'))
|
|
206
198
|
.build(), {
|
|
@@ -211,17 +203,16 @@ async function onPick(ctx) {
|
|
|
211
203
|
async function onTo(ctx, targetBotId, sourceMsgId) {
|
|
212
204
|
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
213
205
|
if (!keyInfo || Number.isNaN(sourceMsgId)) {
|
|
214
|
-
await ctx.answerCallbackQuery({ text: 'Invalid
|
|
206
|
+
await ctx.answerCallbackQuery({ text: 'Invalid branch target.' });
|
|
215
207
|
return;
|
|
216
208
|
}
|
|
217
209
|
const offset = messageOffsets.lookup(keyInfo.sessionKey, sourceMsgId);
|
|
218
210
|
if (!offset) {
|
|
219
|
-
await ctx.answerCallbackQuery({ text: '
|
|
211
|
+
await ctx.answerCallbackQuery({ text: 'Branch point no longer available.' });
|
|
220
212
|
return;
|
|
221
213
|
}
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
if (!toThread && !target) {
|
|
214
|
+
const target = findBotById(targetBotId);
|
|
215
|
+
if (!target) {
|
|
225
216
|
await ctx.answerCallbackQuery({ text: 'Target bot not found.' });
|
|
226
217
|
return;
|
|
227
218
|
}
|
|
@@ -229,113 +220,103 @@ async function onTo(ctx, targetBotId, sourceMsgId) {
|
|
|
229
220
|
const projectLabel = path.basename(offset.projectPath);
|
|
230
221
|
const isSelf = targetBotId === BOT_ID;
|
|
231
222
|
const text = new EntityText();
|
|
232
|
-
if (
|
|
233
|
-
text.add('
|
|
234
|
-
.add('This copies ').bold(projectLabel)
|
|
235
|
-
.add(" up to that point into a new thread, with this thread's settings. This thread carries on unchanged.");
|
|
236
|
-
}
|
|
237
|
-
else if (isSelf) {
|
|
238
|
-
text.add('🍴 ').bold('Branch into a new conversation?').newline(2)
|
|
223
|
+
if (isSelf) {
|
|
224
|
+
text.add('🌱 ').bold('Branch into a new conversation?').newline(2)
|
|
239
225
|
.add('This copies ').bold(projectLabel)
|
|
240
226
|
.add(' up to that point into a fresh conversation on this bot. '
|
|
241
227
|
+ 'Your current conversation is saved to /resume history, and you continue from the branch point.');
|
|
242
228
|
}
|
|
243
229
|
else {
|
|
244
230
|
const name = target.name;
|
|
245
|
-
text.add('
|
|
231
|
+
text.add('🌱 ').bold(`Branch to ${name}?`).newline(2)
|
|
246
232
|
.add('This will copy the conversation in ').bold(projectLabel)
|
|
247
233
|
.add(' up to that point and hand it off to ').bold(name).add('.').newline(2)
|
|
248
|
-
.add('When you open ').bold(name).add(" and send any message, you'll get a prompt to accept the
|
|
234
|
+
.add('When you open ').bold(name).add(" and send any message, you'll get a prompt to accept the branch. ")
|
|
249
235
|
.add('Accepting replaces ').bold(name).add("'s current conversation (saved to its /resume history).");
|
|
250
236
|
}
|
|
251
237
|
try {
|
|
252
238
|
await editCallbackMessage(ctx, text.build(), {
|
|
253
239
|
reply_markup: {
|
|
254
240
|
inline_keyboard: [
|
|
255
|
-
[{ text: '✅ Confirm
|
|
256
|
-
[{ text: 'Cancel', callback_data: '
|
|
241
|
+
[{ text: '✅ Confirm branch', callback_data: `branch:confirm:${targetBotId}:${sourceMsgId}` }],
|
|
242
|
+
[{ text: 'Cancel', callback_data: 'branch:cancel' }],
|
|
257
243
|
],
|
|
258
244
|
},
|
|
259
245
|
});
|
|
260
246
|
}
|
|
261
247
|
catch (err) {
|
|
262
|
-
console.debug('[
|
|
248
|
+
console.debug('[Branch] onTo edit failed:', err instanceof Error ? err.message : err);
|
|
263
249
|
}
|
|
264
250
|
}
|
|
265
251
|
async function onConfirm(ctx, targetBotId, sourceMsgId) {
|
|
266
252
|
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
267
253
|
if (!keyInfo || Number.isNaN(sourceMsgId)) {
|
|
268
|
-
await ctx.answerCallbackQuery({ text: 'Invalid
|
|
254
|
+
await ctx.answerCallbackQuery({ text: 'Invalid branch target.' });
|
|
269
255
|
return;
|
|
270
256
|
}
|
|
271
257
|
const offset = messageOffsets.lookup(keyInfo.sessionKey, sourceMsgId);
|
|
272
258
|
if (!offset) {
|
|
273
|
-
await ctx.answerCallbackQuery({ text: '
|
|
259
|
+
await ctx.answerCallbackQuery({ text: 'Branch point no longer available.' });
|
|
274
260
|
return;
|
|
275
261
|
}
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
if (!toThread && !target) {
|
|
262
|
+
const target = findBotById(targetBotId);
|
|
263
|
+
if (!target) {
|
|
279
264
|
await ctx.answerCallbackQuery({ text: 'Target bot not found.' });
|
|
280
265
|
return;
|
|
281
266
|
}
|
|
282
|
-
const cut =
|
|
267
|
+
const cut = cutBranch(ctx, keyInfo.sessionKey, offset, takeTypedName(keyInfo.sessionKey, sourceMsgId));
|
|
283
268
|
if ('error' in cut) {
|
|
284
269
|
await ctx.answerCallbackQuery({ text: cut.error });
|
|
285
270
|
return;
|
|
286
271
|
}
|
|
287
|
-
const {
|
|
272
|
+
const { branch } = cut;
|
|
288
273
|
const userId = ctx.from?.id;
|
|
289
274
|
if (!userId) {
|
|
290
275
|
await ctx.answerCallbackQuery({ text: 'Could not identify user.' });
|
|
291
276
|
return;
|
|
292
277
|
}
|
|
293
|
-
// Self-
|
|
278
|
+
// Self-branch: branch within this same bot/chat. The pending-branch handoff
|
|
294
279
|
// (and its accept/decline prompt) only exists to cross bots — here the
|
|
295
280
|
// source and target are the same conversation, so load the branch right
|
|
296
|
-
// now.
|
|
281
|
+
// now. loadBranch saves the current conversation to /resume history first.
|
|
297
282
|
if (targetBotId === BOT_ID) {
|
|
298
|
-
await
|
|
283
|
+
await loadBranch(ctx, keyInfo.sessionKey, branch);
|
|
299
284
|
await ctx.answerCallbackQuery({ text: 'Branched.' });
|
|
300
285
|
return;
|
|
301
286
|
}
|
|
302
|
-
|
|
303
|
-
await forkIntoThread(ctx, keyInfo.sessionKey, fork, offset);
|
|
304
|
-
return;
|
|
305
|
-
}
|
|
306
|
-
// Key the pending fork by Telegram user id, not sessionKey: each bot has
|
|
287
|
+
// Key the pending branch by Telegram user id, not sessionKey: each bot has
|
|
307
288
|
// its own DM with the user with a different chatId, so the target bot
|
|
308
|
-
// can't find the
|
|
289
|
+
// can't find the branch by chatId-based key. User id is constant across
|
|
309
290
|
// bots; the offer will land in whichever chat the user next messages
|
|
310
291
|
// the target bot in.
|
|
311
|
-
|
|
312
|
-
await ctx.answerCallbackQuery({ text: '
|
|
292
|
+
putPendingBranch(target.botId, userId, branch);
|
|
293
|
+
await ctx.answerCallbackQuery({ text: 'Branched.' });
|
|
313
294
|
const projectLabel = path.basename(offset.projectPath);
|
|
314
295
|
try {
|
|
315
296
|
await editCallbackMessage(ctx, new EntityText()
|
|
316
|
-
.add('✅ ').bold(`
|
|
297
|
+
.add('✅ ').bold(`Branched to ${target.name}`).newline(2)
|
|
317
298
|
.add('Open ').bold(target.name)
|
|
318
|
-
.add(` and send any message — you'll get the option to accept the
|
|
299
|
+
.add(` and send any message — you'll get the option to accept the branched conversation (${projectLabel}).`)
|
|
319
300
|
.newline(2)
|
|
320
301
|
.italic('This conversation carries on here unchanged.')
|
|
321
|
-
.build(), { reply_markup:
|
|
322
|
-
// This confirmation stands for the same point as the message the
|
|
302
|
+
.build(), { reply_markup: BRANCH_KEYBOARD });
|
|
303
|
+
// This confirmation stands for the same point as the message the branch was
|
|
323
304
|
// taken from, and it's the one at the bottom of the chat — so it gets that
|
|
324
|
-
// message's
|
|
305
|
+
// message's branch point, and sending the point on to another bot, or
|
|
325
306
|
// branching it here, doesn't mean scrolling back up to find it.
|
|
326
307
|
const anchorId = ctx.callbackQuery?.message?.message_id;
|
|
327
308
|
if (anchorId)
|
|
328
309
|
messageOffsets.record(keyInfo.sessionKey, anchorId, offset);
|
|
329
310
|
}
|
|
330
311
|
catch (err) {
|
|
331
|
-
console.debug('[
|
|
312
|
+
console.debug('[Branch] onConfirm edit failed:', err instanceof Error ? err.message : err);
|
|
332
313
|
}
|
|
333
314
|
}
|
|
334
315
|
/**
|
|
335
|
-
* The conversation as it stood at a
|
|
316
|
+
* The conversation as it stood at a branch point: the source transcript cut to
|
|
336
317
|
* the recorded line count, with what the receiving side shows about it.
|
|
337
318
|
*/
|
|
338
|
-
function
|
|
319
|
+
function cutBranch(ctx, sessionKey, offset, name) {
|
|
339
320
|
const sourceJsonl = sessionJsonlPath(offset.projectPath, offset.claudeSessionId);
|
|
340
321
|
if (!fs.existsSync(sourceJsonl))
|
|
341
322
|
return { error: 'Source transcript no longer on disk.' };
|
|
@@ -349,40 +330,27 @@ function cutFork(ctx, sessionKey, offset) {
|
|
|
349
330
|
truncated = sliced.join('\n') + (sliced.length > 0 ? '\n' : '');
|
|
350
331
|
}
|
|
351
332
|
catch (err) {
|
|
352
|
-
console.error('[
|
|
333
|
+
console.error('[Branch] Failed to read source JSONL:', err);
|
|
353
334
|
return { error: 'Could not read source transcript.' };
|
|
354
335
|
}
|
|
355
336
|
return {
|
|
356
|
-
|
|
357
|
-
fromBotName: BOT_NAME,
|
|
337
|
+
branch: {
|
|
338
|
+
fromBotName: config.BOT_NAME,
|
|
358
339
|
fromBotId: BOT_ID,
|
|
359
340
|
fromChatId: ctx.chat?.id,
|
|
360
341
|
projectPath: offset.projectPath,
|
|
361
342
|
jsonl: truncated,
|
|
362
|
-
topic
|
|
363
|
-
|
|
364
|
-
//
|
|
343
|
+
// A name given with /branch <name> is the branch's topic, and so its thread's name.
|
|
344
|
+
topic: name || getSessionTopic(sessionKey),
|
|
345
|
+
// The reply the branch was taken from, read out of the cut transcript. The
|
|
346
|
+
// chat's stored preview is its latest reply, which a branch taken from any
|
|
365
347
|
// earlier message doesn't contain.
|
|
366
348
|
assistantPreview: lastAssistantTurnText(truncated)?.substring(0, 200),
|
|
367
349
|
createdAt: new Date().toISOString(),
|
|
368
350
|
},
|
|
369
351
|
};
|
|
370
352
|
}
|
|
371
|
-
/**
|
|
372
|
-
* A fork on a bot with threads: straight into a new thread, with no picker
|
|
373
|
-
* and no confirmation. Nothing here changes, and a thread you didn't want is
|
|
374
|
-
* deleted as easily as a confirmation is cancelled. The result is a reply to
|
|
375
|
-
* `replyTo`, the message the fork was taken from, which stays as it is.
|
|
376
|
-
*/
|
|
377
|
-
async function forkStraightIntoThread(ctx, sessionKey, offset, replyTo) {
|
|
378
|
-
const cut = cutFork(ctx, sessionKey, offset);
|
|
379
|
-
if ('error' in cut) {
|
|
380
|
-
await tell(ctx, cut.error);
|
|
381
|
-
return;
|
|
382
|
-
}
|
|
383
|
-
await forkIntoThread(ctx, sessionKey, cut.fork, offset, { replyTo });
|
|
384
|
-
}
|
|
385
|
-
/** A short notice: the tapped button's toast, or a reply when /fork was typed. */
|
|
353
|
+
/** A short notice: the tapped button's toast, or a reply when /branch was typed. */
|
|
386
354
|
async function tell(ctx, text) {
|
|
387
355
|
if (ctx.callbackQuery)
|
|
388
356
|
await ctx.answerCallbackQuery({ text });
|
|
@@ -390,29 +358,36 @@ async function tell(ctx, text) {
|
|
|
390
358
|
await ctx.reply(text);
|
|
391
359
|
}
|
|
392
360
|
/**
|
|
393
|
-
*
|
|
361
|
+
* A branch on a bot with threads: straight into a new thread, with no picker
|
|
362
|
+
* and no confirmation. Nothing here changes, and a thread you didn't want is
|
|
363
|
+
* deleted as easily as a confirmation is cancelled.
|
|
394
364
|
*
|
|
395
365
|
* The new thread starts with the settings this one chose for itself (model,
|
|
396
366
|
* effort, transport…), since it carries on the same conversation, and a name
|
|
397
|
-
* from the same topic with
|
|
398
|
-
* so the two stay apart in the list. The
|
|
399
|
-
* thread; here,
|
|
400
|
-
*
|
|
401
|
-
* message keeps the fork point.
|
|
367
|
+
* from the same topic with 🌱 in front, which it keeps through later renames
|
|
368
|
+
* so the two stay apart in the list. The branch's banner goes into the new
|
|
369
|
+
* thread; here, a reply to `replyTo`, the message the branch was taken from,
|
|
370
|
+
* says where it went and keeps the branch point. That message stays as it is.
|
|
402
371
|
*/
|
|
403
|
-
async function
|
|
404
|
-
const
|
|
405
|
-
|
|
372
|
+
async function branchIntoThread(ctx, sessionKey, offset, replyTo, typedName) {
|
|
373
|
+
const cut = cutBranch(ctx, sessionKey, offset, typedName);
|
|
374
|
+
if ('error' in cut) {
|
|
375
|
+
await tell(ctx, cut.error);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const { branch } = cut;
|
|
379
|
+
const opened = await openBranchThread(ctx, sessionKey, branch, {
|
|
380
|
+
above: 'The conversation it was branched from carries on in its own thread.',
|
|
406
381
|
});
|
|
407
382
|
if ('error' in opened) {
|
|
408
383
|
await tell(ctx, opened.error);
|
|
409
384
|
return;
|
|
410
385
|
}
|
|
411
386
|
if (ctx.callbackQuery)
|
|
412
|
-
await ctx.answerCallbackQuery({ text: '
|
|
387
|
+
await ctx.answerCallbackQuery({ text: 'Branched into a new thread.' });
|
|
413
388
|
const { name, link } = opened;
|
|
414
|
-
const projectLabel = path.basename(
|
|
415
|
-
const b = new EntityText().add('✅ ').bold('
|
|
389
|
+
const projectLabel = path.basename(branch.projectPath);
|
|
390
|
+
const b = new EntityText().add('✅ ').bold('Branched into a new thread').newline(2);
|
|
416
391
|
if (link)
|
|
417
392
|
b.link(name, link);
|
|
418
393
|
else
|
|
@@ -421,58 +396,55 @@ async function forkIntoThread(ctx, sessionKey, fork, offset, opts = {}) {
|
|
|
421
396
|
.italic('This thread carries on here unchanged.');
|
|
422
397
|
const text = b.build();
|
|
423
398
|
try {
|
|
424
|
-
const anchorId =
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
ctx.callbackQuery?.message?.message_id);
|
|
431
|
-
// Same as a fork to another bot: this message stands for the point the
|
|
432
|
-
// fork was taken from, so it can be forked again from here.
|
|
399
|
+
const anchorId = (await replyFormatted(ctx, text, {
|
|
400
|
+
reply_markup: BRANCH_KEYBOARD,
|
|
401
|
+
reply_parameters: { message_id: replyTo },
|
|
402
|
+
})).message_id;
|
|
403
|
+
// Same as a branch to another bot: this message stands for the point the
|
|
404
|
+
// branch was taken from, so it can be branched again from here.
|
|
433
405
|
if (anchorId)
|
|
434
406
|
messageOffsets.record(sessionKey, anchorId, offset);
|
|
435
407
|
}
|
|
436
408
|
catch (err) {
|
|
437
|
-
console.debug('[
|
|
409
|
+
console.debug('[Branch] branchIntoThread reply failed:', err instanceof Error ? err.message : err);
|
|
438
410
|
}
|
|
439
411
|
}
|
|
440
412
|
/**
|
|
441
413
|
* Open a new thread named after the conversation, with this thread's
|
|
442
|
-
* settings, and load the
|
|
414
|
+
* settings, and load the branch into it with its banner. Nothing is said here.
|
|
443
415
|
*/
|
|
444
|
-
async function
|
|
416
|
+
async function openBranchThread(ctx, sessionKey, branch, marker) {
|
|
445
417
|
const chatId = ctx.chat?.id;
|
|
446
418
|
if (!chatId)
|
|
447
419
|
return { error: 'Cannot identify this chat.' };
|
|
448
|
-
const projectLabel = path.basename(
|
|
449
|
-
const name = threadName(
|
|
450
|
-
|| `${
|
|
420
|
+
const projectLabel = path.basename(branch.projectPath);
|
|
421
|
+
const name = threadName(branch.topic ?? '', BRANCH_THREAD_PREFIX, isHomeProject(branch.projectPath) ? '' : projectLabel)
|
|
422
|
+
|| `${BRANCH_THREAD_PREFIX}${projectLabel}`;
|
|
451
423
|
let threadId;
|
|
452
424
|
try {
|
|
453
425
|
threadId = (await ctx.api.createForumTopic(chatId, name)).message_thread_id;
|
|
454
426
|
}
|
|
455
427
|
catch (err) {
|
|
456
|
-
console.error('[
|
|
428
|
+
console.error('[Branch] createForumTopic failed:', err instanceof Error ? err.message : err);
|
|
457
429
|
return { error: 'Could not open a new thread.' };
|
|
458
430
|
}
|
|
459
431
|
const threadKey = buildSessionKey(chatId, threadId);
|
|
460
|
-
adoptThread(threadKey, name,
|
|
432
|
+
adoptThread(threadKey, name, BRANCH_THREAD_PREFIX);
|
|
461
433
|
userPreferences.copyScope(sessionKey, threadKey);
|
|
462
434
|
const threadCtx = buildSyntheticCtx({ api: ctx.api, sessionKey: threadKey, syntheticText: '' });
|
|
463
|
-
await
|
|
435
|
+
await loadBranch(threadCtx, threadKey, branch, marker);
|
|
464
436
|
const link = ctx.me?.username ? `https://t.me/${ctx.me.username}/${threadId}` : undefined;
|
|
465
437
|
return { threadId, threadKey, name, link };
|
|
466
438
|
}
|
|
467
439
|
/**
|
|
468
|
-
* What a
|
|
440
|
+
* What a branch taken while a turn is running has Claude say about that turn.
|
|
469
441
|
* In Claude's voice, because it stands as Claude's reply to the prompt.
|
|
470
442
|
*/
|
|
471
|
-
export const STILL_RUNNING_NOTE = 'TeleCoder
|
|
443
|
+
export const STILL_RUNNING_NOTE = 'TeleCoder branched this conversation while the original was still working on the '
|
|
472
444
|
+ 'message above, so none of that work happened here. The original is still on it, in the same working '
|
|
473
|
-
+ "directory, so files may change while this
|
|
445
|
+
+ "directory, so files may change while this branch runs. I won't redo or undo that work, and I'll check a "
|
|
474
446
|
+ "file's current state before relying on it.";
|
|
475
|
-
/** What one sent while a turn was running says, on one line, for the `You:` line in the
|
|
447
|
+
/** What one sent while a turn was running says, on one line, for the `You:` line in the branch. */
|
|
476
448
|
function describeMessage(message) {
|
|
477
449
|
const words = message.text ?? message.caption;
|
|
478
450
|
if (words?.trim())
|
|
@@ -480,27 +452,27 @@ function describeMessage(message) {
|
|
|
480
452
|
return message.voice ? '🎤 voice note' : message.photo ? '🖼 photo' : message.document ? '📎 file' : 'message';
|
|
481
453
|
}
|
|
482
454
|
/**
|
|
483
|
-
* The conversation as it stands, for a
|
|
455
|
+
* The conversation as it stands, for a branch taken whether or not a turn is
|
|
484
456
|
* running: up to the last turn that ended, with the running one's prompt and
|
|
485
|
-
* STILL_RUNNING_NOTE after it when there is one (see
|
|
457
|
+
* STILL_RUNNING_NOTE after it when there is one (see branchPastRunningTurn).
|
|
486
458
|
*/
|
|
487
|
-
function
|
|
459
|
+
function branchOfLatest(ctx, sessionKey) {
|
|
488
460
|
const session = sessionManager.getSession(sessionKey);
|
|
489
461
|
if (!session?.claudeSessionId)
|
|
490
|
-
return { error: 'No conversation to
|
|
462
|
+
return { error: 'No conversation to branch yet.' };
|
|
491
463
|
const sourceJsonl = sessionJsonlPath(session.workingDirectory, session.claudeSessionId);
|
|
492
464
|
let raw;
|
|
493
465
|
try {
|
|
494
466
|
raw = fs.readFileSync(sourceJsonl, 'utf-8');
|
|
495
467
|
}
|
|
496
468
|
catch {
|
|
497
|
-
return { error: 'No transcript on disk to
|
|
469
|
+
return { error: 'No transcript on disk to branch.' };
|
|
498
470
|
}
|
|
499
|
-
const { jsonl, noted } =
|
|
471
|
+
const { jsonl, noted } = branchPastRunningTurn(raw, STILL_RUNNING_NOTE);
|
|
500
472
|
return {
|
|
501
473
|
noted,
|
|
502
|
-
|
|
503
|
-
fromBotName: BOT_NAME,
|
|
474
|
+
branch: {
|
|
475
|
+
fromBotName: config.BOT_NAME,
|
|
504
476
|
fromBotId: BOT_ID,
|
|
505
477
|
fromChatId: ctx.chat?.id,
|
|
506
478
|
projectPath: session.workingDirectory,
|
|
@@ -512,24 +484,24 @@ function forkOfLatest(ctx, sessionKey) {
|
|
|
512
484
|
};
|
|
513
485
|
}
|
|
514
486
|
/**
|
|
515
|
-
* "Ask in a
|
|
487
|
+
* "Ask in a branch" on a message waiting behind a running turn: the conversation
|
|
516
488
|
* as it stood before that turn goes into a new thread, with the running prompt
|
|
517
489
|
* and a reply saying it's still being worked on elsewhere (see
|
|
518
|
-
*
|
|
490
|
+
* branchPastRunningTurn), and a `You:` line showing what's about to be asked
|
|
519
491
|
* there. Sending the message itself is the caller's: it's the queue that holds
|
|
520
492
|
* the update.
|
|
521
493
|
*/
|
|
522
|
-
export async function
|
|
523
|
-
if (!
|
|
524
|
-
return { error: '
|
|
525
|
-
const latest =
|
|
494
|
+
export async function branchPastRunningTurnIntoThread(ctx, sessionKey, message) {
|
|
495
|
+
if (!canBranchToThread(ctx))
|
|
496
|
+
return { error: 'Branches need threads, which are off for this bot.' };
|
|
497
|
+
const latest = branchOfLatest(ctx, sessionKey);
|
|
526
498
|
if ('error' in latest)
|
|
527
499
|
return latest;
|
|
528
|
-
const {
|
|
500
|
+
const { branch, noted } = latest;
|
|
529
501
|
if (!noted)
|
|
530
|
-
console.warn(`[
|
|
531
|
-
const opened = await
|
|
532
|
-
above: 'The conversation it was
|
|
502
|
+
console.warn(`[Branch] ${sessionKey}: running turn not on disk yet, branching without the note`);
|
|
503
|
+
const opened = await openBranchThread(ctx, sessionKey, branch, {
|
|
504
|
+
above: 'The conversation it was branched from carries on in its own thread, still working on that prompt.',
|
|
533
505
|
});
|
|
534
506
|
if ('error' in opened)
|
|
535
507
|
return opened;
|
|
@@ -537,34 +509,34 @@ export async function forkPastRunningTurnIntoThread(ctx, sessionKey, message) {
|
|
|
537
509
|
await sendFormatted(ctx.api, ctx.chat.id, youLine(describeMessage(message), MARKER_PROMPT_LEN), { message_thread_id: opened.threadId });
|
|
538
510
|
}
|
|
539
511
|
catch (err) {
|
|
540
|
-
console.warn('[
|
|
512
|
+
console.warn('[Branch] Could not post the You line:', err instanceof Error ? err.message : err);
|
|
541
513
|
}
|
|
542
514
|
return { threadId: opened.threadId, name: opened.name, link: opened.link };
|
|
543
515
|
}
|
|
544
516
|
async function onCancel(ctx) {
|
|
545
517
|
await ctx.answerCallbackQuery({ text: 'Cancelled.' });
|
|
546
518
|
try {
|
|
547
|
-
await ctx.editMessageText('
|
|
519
|
+
await ctx.editMessageText('🌱 Branch cancelled.');
|
|
548
520
|
}
|
|
549
521
|
catch { /* ignore */ }
|
|
550
522
|
}
|
|
551
523
|
// ── Target-side accept / decline ─────────────────────────────────────────
|
|
552
524
|
/**
|
|
553
|
-
* Show the "
|
|
525
|
+
* Show the "branch received" prompt in the target bot when a pending branch
|
|
554
526
|
* exists for this user. Called from message.handler before normal message
|
|
555
|
-
* handling. Returns true if a
|
|
527
|
+
* handling. Returns true if a branch was offered (and the caller should drop
|
|
556
528
|
* the incoming message), false otherwise.
|
|
557
529
|
*/
|
|
558
|
-
export async function
|
|
530
|
+
export async function offerPendingBranchIfAny(ctx) {
|
|
559
531
|
const userId = ctx.from?.id;
|
|
560
532
|
if (!userId)
|
|
561
533
|
return false;
|
|
562
|
-
const
|
|
563
|
-
if (!
|
|
534
|
+
const branch = getPendingBranch(BOT_ID, userId);
|
|
535
|
+
if (!branch)
|
|
564
536
|
return false;
|
|
565
|
-
const offer =
|
|
537
|
+
const offer = buildBranchOffer(branch, 'lazy');
|
|
566
538
|
await replyFormatted(ctx, offer.text, { reply_markup: offer.keyboard });
|
|
567
|
-
|
|
539
|
+
markBranchOffered(BOT_ID, userId);
|
|
568
540
|
return true;
|
|
569
541
|
}
|
|
570
542
|
async function onAccept(ctx) {
|
|
@@ -574,18 +546,18 @@ async function onAccept(ctx) {
|
|
|
574
546
|
await ctx.answerCallbackQuery({ text: 'No active chat.' });
|
|
575
547
|
return;
|
|
576
548
|
}
|
|
577
|
-
const
|
|
578
|
-
if (!
|
|
579
|
-
await ctx.answerCallbackQuery({ text: 'No pending
|
|
549
|
+
const branch = getPendingBranch(BOT_ID, userId);
|
|
550
|
+
if (!branch) {
|
|
551
|
+
await ctx.answerCallbackQuery({ text: 'No pending branch.' });
|
|
580
552
|
try {
|
|
581
|
-
await ctx.editMessageText('No pending
|
|
553
|
+
await ctx.editMessageText('No pending branch to accept.');
|
|
582
554
|
}
|
|
583
555
|
catch { /* ignore */ }
|
|
584
556
|
return;
|
|
585
557
|
}
|
|
586
|
-
await
|
|
587
|
-
|
|
588
|
-
await ctx.answerCallbackQuery({ text: '
|
|
558
|
+
await loadBranch(ctx, keyInfo.sessionKey, branch);
|
|
559
|
+
removePendingBranch(BOT_ID, userId);
|
|
560
|
+
await ctx.answerCallbackQuery({ text: 'Branch loaded.' });
|
|
589
561
|
}
|
|
590
562
|
async function onDecline(ctx) {
|
|
591
563
|
const userId = ctx.from?.id;
|
|
@@ -593,10 +565,10 @@ async function onDecline(ctx) {
|
|
|
593
565
|
await ctx.answerCallbackQuery({ text: 'No active chat.' });
|
|
594
566
|
return;
|
|
595
567
|
}
|
|
596
|
-
|
|
597
|
-
await ctx.answerCallbackQuery({ text: '
|
|
568
|
+
removePendingBranch(BOT_ID, userId);
|
|
569
|
+
await ctx.answerCallbackQuery({ text: 'Branch discarded.' });
|
|
598
570
|
try {
|
|
599
|
-
await ctx.editMessageText('❌
|
|
571
|
+
await ctx.editMessageText('❌ Branch discarded. Send a message to continue your current conversation.');
|
|
600
572
|
}
|
|
601
573
|
catch { /* ignore */ }
|
|
602
574
|
}
|
|
@@ -606,22 +578,37 @@ async function onDecline(ctx) {
|
|
|
606
578
|
* users who'd rather type. Both shape the response the same as the buttons.
|
|
607
579
|
*/
|
|
608
580
|
/**
|
|
609
|
-
*
|
|
610
|
-
*
|
|
611
|
-
*
|
|
581
|
+
* Names typed with /branch <name> on a bot without threads, waiting for the
|
|
582
|
+
* picker's tap, keyed by session and the /branch message the picker anchors on.
|
|
583
|
+
* In memory only: a picker that outlives a restart branches under the topic.
|
|
584
|
+
*/
|
|
585
|
+
const typedNames = new Map();
|
|
586
|
+
/** The name typed with the /branch a picker came from, if any, taken once. */
|
|
587
|
+
function takeTypedName(sessionKey, anchorMsgId) {
|
|
588
|
+
const key = `${sessionKey}:${anchorMsgId}`;
|
|
589
|
+
const name = typedNames.get(key);
|
|
590
|
+
typedNames.delete(key);
|
|
591
|
+
return name;
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* /branch [name] — alternative to tapping the 🌱 Branch button. Branches from
|
|
595
|
+
* the current session state (the latest JSONL line): on a bot with threads
|
|
596
|
+
* straight into a new thread, otherwise through the target picker. A name is
|
|
597
|
+
* the branch's topic, so it names the thread, as Claude Code's `/branch <name>`
|
|
598
|
+
* names its branch; without one the branch keeps this conversation's topic.
|
|
612
599
|
*/
|
|
613
|
-
export async function
|
|
600
|
+
export async function handleBranchCommand(ctx) {
|
|
614
601
|
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
615
602
|
if (!keyInfo)
|
|
616
603
|
return;
|
|
617
604
|
const session = sessionManager.getSession(keyInfo.sessionKey);
|
|
618
605
|
if (!session?.claudeSessionId) {
|
|
619
|
-
await ctx.reply('No active conversation to
|
|
606
|
+
await ctx.reply('No active conversation to branch. Send at least one message in this session first.');
|
|
620
607
|
return;
|
|
621
608
|
}
|
|
622
609
|
const jsonlPath = sessionJsonlPath(session.workingDirectory, session.claudeSessionId);
|
|
623
610
|
if (!fs.existsSync(jsonlPath)) {
|
|
624
|
-
await ctx.reply('No transcript on disk yet — finish an assistant turn before
|
|
611
|
+
await ctx.reply('No transcript on disk yet — finish an assistant turn before branching.');
|
|
625
612
|
return;
|
|
626
613
|
}
|
|
627
614
|
const raw = fs.readFileSync(jsonlPath, 'utf-8');
|
|
@@ -630,15 +617,15 @@ export async function handleForkCommand(ctx) {
|
|
|
630
617
|
lines.pop();
|
|
631
618
|
const lineCount = lines.length;
|
|
632
619
|
if (lineCount === 0) {
|
|
633
|
-
await ctx.reply('Transcript is empty — nothing to
|
|
620
|
+
await ctx.reply('Transcript is empty — nothing to branch.');
|
|
634
621
|
return;
|
|
635
622
|
}
|
|
636
|
-
// Record a synthetic offset against the user's /
|
|
623
|
+
// Record a synthetic offset against the user's /branch message so the rest
|
|
637
624
|
// of the flow can reuse the inline-button machinery unchanged. The
|
|
638
|
-
// /
|
|
625
|
+
// /branch command itself is the anchor message.
|
|
639
626
|
const anchorMsgId = ctx.message?.message_id;
|
|
640
627
|
if (!anchorMsgId) {
|
|
641
|
-
await ctx.reply('Could not anchor
|
|
628
|
+
await ctx.reply('Could not anchor branch — try the 🌱 button on a bot message instead.');
|
|
642
629
|
return;
|
|
643
630
|
}
|
|
644
631
|
messageOffsets.record(keyInfo.sessionKey, anchorMsgId, {
|
|
@@ -648,14 +635,17 @@ export async function handleForkCommand(ctx) {
|
|
|
648
635
|
conversationId: session.conversationId,
|
|
649
636
|
});
|
|
650
637
|
const offset = messageOffsets.lookup(keyInfo.sessionKey, anchorMsgId);
|
|
651
|
-
|
|
652
|
-
|
|
638
|
+
const name = (ctx.message?.text ?? '').replace(/^\/\S*\s*/, '').trim() || undefined;
|
|
639
|
+
if (offset && canBranchToThread(ctx)) {
|
|
640
|
+
await branchIntoThread(ctx, keyInfo.sessionKey, offset, anchorMsgId, name);
|
|
653
641
|
return;
|
|
654
642
|
}
|
|
643
|
+
if (name)
|
|
644
|
+
typedNames.set(`${keyInfo.sessionKey}:${anchorMsgId}`, name);
|
|
655
645
|
const projectLabel = path.basename(session.workingDirectory);
|
|
656
646
|
const picker = buildTargetPicker(anchorMsgId);
|
|
657
647
|
await replyFormatted(ctx, new EntityText()
|
|
658
|
-
.add('
|
|
648
|
+
.add('🌱 ').bold('Branch conversation').newline(2)
|
|
659
649
|
.add('From the current state of ').bold(projectLabel).add(' — pick where to branch it:').newline(2)
|
|
660
650
|
.add(picker.lines.join('\n'))
|
|
661
651
|
.build(), { reply_markup: { inline_keyboard: picker.keyboard } });
|
|
@@ -673,18 +663,18 @@ export function spinoffCompactFocus(task) {
|
|
|
673
663
|
}
|
|
674
664
|
/**
|
|
675
665
|
* /spinoff <task> — split one task off into a conversation of its own. The
|
|
676
|
-
* conversation as it stands (past a running turn, as "Ask in a
|
|
666
|
+
* conversation as it stands (past a running turn, as "Ask in a branch" takes
|
|
677
667
|
* it) goes into a new thread, is compacted there around the task, and the
|
|
678
668
|
* task goes in as the first prompt. This thread carries on unchanged, so it
|
|
679
669
|
* works mid-turn: it's registered ahead of sequentialize, and the new thread
|
|
680
670
|
* has a queue of its own.
|
|
681
671
|
*
|
|
682
|
-
* Unlike a /
|
|
672
|
+
* Unlike a /branch, which takes the whole conversation along, the spinoff
|
|
683
673
|
* starts with only what its task needs, and starts on it without waiting for
|
|
684
674
|
* another message.
|
|
685
675
|
*
|
|
686
676
|
* Sent as a reply to one of the bot's messages, it spins off from that point
|
|
687
|
-
* instead, the way that message's
|
|
677
|
+
* instead, the way that message's 🌱 button branches: for a task planned before
|
|
688
678
|
* a tangent the spinoff has no need of.
|
|
689
679
|
*
|
|
690
680
|
* The thread is named after the task, not the conversation it came from. A
|
|
@@ -705,29 +695,29 @@ export async function handleSpinoffCommand(ctx) {
|
|
|
705
695
|
+ 'This thread carries on as it is. Send it as a reply to one of my messages to spin off from that point.');
|
|
706
696
|
return;
|
|
707
697
|
}
|
|
708
|
-
if (!
|
|
698
|
+
if (!canBranchToThread(ctx)) {
|
|
709
699
|
await ctx.reply('A spinoff opens a new thread, and threads are off for this bot.');
|
|
710
700
|
return;
|
|
711
701
|
}
|
|
712
702
|
// In a thread, a message that isn't a reply still carries the thread's
|
|
713
|
-
// opening service message as its reply_to_message; that isn't a
|
|
703
|
+
// opening service message as its reply_to_message; that isn't a branch point.
|
|
714
704
|
const repliedTo = message.reply_to_message?.forum_topic_created ? undefined : message.reply_to_message;
|
|
715
705
|
const offset = repliedTo && messageOffsets.lookup(keyInfo.sessionKey, repliedTo.message_id);
|
|
716
706
|
if (repliedTo && !offset) {
|
|
717
|
-
await ctx.reply("There's no
|
|
707
|
+
await ctx.reply("There's no branch point on that message. Reply to one of my replies to spin off from there, "
|
|
718
708
|
+ 'or send /spinoff without replying to spin off from where the conversation is now.');
|
|
719
709
|
return;
|
|
720
710
|
}
|
|
721
|
-
const cut = offset ?
|
|
711
|
+
const cut = offset ? cutBranch(ctx, keyInfo.sessionKey, offset) : branchOfLatest(ctx, keyInfo.sessionKey);
|
|
722
712
|
if ('error' in cut) {
|
|
723
713
|
await ctx.reply(cut.error);
|
|
724
714
|
return;
|
|
725
715
|
}
|
|
726
|
-
const {
|
|
716
|
+
const { branch } = cut;
|
|
727
717
|
if (config.AUTO_TOPIC_HAIKU) {
|
|
728
|
-
|
|
718
|
+
branch.topic = await summarizeTopicWithHaiku(task, undefined, path.basename(branch.projectPath)) ?? branch.topic;
|
|
729
719
|
}
|
|
730
|
-
const opened = await
|
|
720
|
+
const opened = await openBranchThread(ctx, keyInfo.sessionKey, branch, {
|
|
731
721
|
above: 'The conversation it was spun off from carries on in its own thread. '
|
|
732
722
|
+ 'This one is compacted around the task below first, then starts on it.',
|
|
733
723
|
});
|
|
@@ -744,7 +734,7 @@ export async function handleSpinoffCommand(ctx) {
|
|
|
744
734
|
catch (err) {
|
|
745
735
|
console.warn('[Spinoff] Could not post the You line:', sanitizeError(err));
|
|
746
736
|
}
|
|
747
|
-
const b = new EntityText().add('
|
|
737
|
+
const b = new EntityText().add('🌱 ').bold('Spun off into ');
|
|
748
738
|
if (opened.link)
|
|
749
739
|
b.link(opened.name, opened.link);
|
|
750
740
|
else
|
|
@@ -782,111 +772,108 @@ export async function handleSpinoffCommand(ctx) {
|
|
|
782
772
|
console.error(`[Spinoff] Starting the spinoff in thread ${opened.threadId} failed:`, sanitizeError(err));
|
|
783
773
|
});
|
|
784
774
|
}
|
|
785
|
-
export async function
|
|
775
|
+
export async function handleBranchAcceptCommand(ctx) {
|
|
786
776
|
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
787
777
|
const userId = ctx.from?.id;
|
|
788
778
|
if (!keyInfo || !userId)
|
|
789
779
|
return;
|
|
790
|
-
const
|
|
791
|
-
if (!
|
|
792
|
-
await ctx.reply('There is no pending
|
|
780
|
+
const branch = getPendingBranch(BOT_ID, userId);
|
|
781
|
+
if (!branch) {
|
|
782
|
+
await ctx.reply('There is no pending branch to accept.');
|
|
793
783
|
return;
|
|
794
784
|
}
|
|
795
|
-
await
|
|
796
|
-
|
|
785
|
+
await loadBranch(ctx, keyInfo.sessionKey, branch);
|
|
786
|
+
removePendingBranch(BOT_ID, userId);
|
|
797
787
|
}
|
|
798
|
-
export async function
|
|
788
|
+
export async function handleBranchDeclineCommand(ctx) {
|
|
799
789
|
const userId = ctx.from?.id;
|
|
800
790
|
if (!userId)
|
|
801
791
|
return;
|
|
802
|
-
if (!
|
|
803
|
-
await ctx.reply('There is no pending
|
|
792
|
+
if (!getPendingBranch(BOT_ID, userId)) {
|
|
793
|
+
await ctx.reply('There is no pending branch to decline.');
|
|
804
794
|
return;
|
|
805
795
|
}
|
|
806
|
-
|
|
807
|
-
await ctx.reply('❌
|
|
796
|
+
removePendingBranch(BOT_ID, userId);
|
|
797
|
+
await ctx.reply('❌ Branch discarded.');
|
|
808
798
|
}
|
|
809
799
|
/**
|
|
810
|
-
* Take a pending
|
|
800
|
+
* Take a pending branch, write the truncated JSONL to a fresh session file in
|
|
811
801
|
* the source project's Claude Code dir, and point this bot's session at it.
|
|
812
|
-
* If the project we're
|
|
802
|
+
* If the project we're branching into is different from the current one, the
|
|
813
803
|
* session-manager call mints a fresh conversation in the new cwd; if it's
|
|
814
804
|
* the same project, we still want a fresh conversation so we don't tack the
|
|
815
805
|
* old transcript onto whatever's already loaded.
|
|
816
806
|
*
|
|
817
|
-
* `marker` rewords the banner for a caller whose
|
|
807
|
+
* `marker` rewords the banner for a caller whose branch doesn't come from the
|
|
818
808
|
* chat above it — /tree branches from any point, not the message you tapped.
|
|
819
809
|
*/
|
|
820
|
-
export async function
|
|
810
|
+
export async function loadBranch(ctx, sessionKey, branch, marker) {
|
|
821
811
|
// Generate a fresh sessionId for this bot's copy of the transcript. We
|
|
822
812
|
// rewrite the `sessionId` field in each record so the file is internally
|
|
823
813
|
// consistent — Claude Code stamps the original session's id into every
|
|
824
814
|
// record, and a resume can get confused if the filename and contents
|
|
825
815
|
// disagree.
|
|
826
816
|
const newSessionId = crypto.randomUUID();
|
|
827
|
-
const rewritten = rewriteJsonlSessionId(
|
|
828
|
-
const targetPath = sessionJsonlPath(
|
|
817
|
+
const rewritten = rewriteJsonlSessionId(branch.jsonl, newSessionId);
|
|
818
|
+
const targetPath = sessionJsonlPath(branch.projectPath, newSessionId);
|
|
829
819
|
try {
|
|
830
820
|
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
|
|
831
821
|
fs.writeFileSync(targetPath, rewritten, { mode: 0o600 });
|
|
832
822
|
}
|
|
833
823
|
catch (err) {
|
|
834
|
-
console.error('[
|
|
835
|
-
await ctx.reply('❌ Failed to load
|
|
824
|
+
console.error('[Branch] Failed to write target JSONL:', err);
|
|
825
|
+
await ctx.reply('❌ Failed to load branch: could not write transcript to disk.');
|
|
836
826
|
return;
|
|
837
827
|
}
|
|
838
|
-
// The branch point, for the
|
|
828
|
+
// The branch point, for the 🌱 Branch button on the done message below.
|
|
839
829
|
// Counted before the session points at the file: from then on the next
|
|
840
830
|
// turn appends to it.
|
|
841
831
|
const loadedLineCount = countJsonlLines(targetPath);
|
|
842
|
-
// Reset this bot's session to the
|
|
832
|
+
// Reset this bot's session to the branched project + transcript. Calling
|
|
843
833
|
// setWorkingDirectory mints a fresh conversation; if the project matches
|
|
844
834
|
// an existing session, we still want a clean slate, so we follow up with
|
|
845
835
|
// startNewConversation when needed.
|
|
846
836
|
const existing = sessionManager.getSession(sessionKey);
|
|
847
|
-
if (existing && existing.workingDirectory ===
|
|
837
|
+
if (existing && existing.workingDirectory === branch.projectPath) {
|
|
848
838
|
sessionManager.startNewConversation(sessionKey);
|
|
849
839
|
}
|
|
850
840
|
else {
|
|
851
|
-
sessionManager.setWorkingDirectory(sessionKey,
|
|
841
|
+
sessionManager.setWorkingDirectory(sessionKey, branch.projectPath);
|
|
852
842
|
}
|
|
853
843
|
sessionManager.setClaudeSessionId(sessionKey, newSessionId);
|
|
854
|
-
// Sever any live process bound to the old session.
|
|
844
|
+
// Sever any live process bound to the old session. A long-lived
|
|
855
845
|
// `claude` process is reused as long as its cwd is unchanged (see
|
|
856
|
-
// PtyProvider._getOrCreateSession) — so a same-project
|
|
857
|
-
// keep serving the pre-
|
|
846
|
+
// PtyProvider._getOrCreateSession) — so a same-project branch would otherwise
|
|
847
|
+
// keep serving the pre-branch session and silently ignore the branch we just
|
|
858
848
|
// loaded. Tearing it down (exactly what /clear does) forces the next turn to
|
|
859
|
-
// respawn with `--resume <newSessionId>` onto the
|
|
849
|
+
// respawn with `--resume <newSessionId>` onto the branched transcript. Order
|
|
860
850
|
// matters: this must run AFTER setClaudeSessionId, since clearConversation
|
|
861
851
|
// leaves sessionManager's session id untouched — only the live process and
|
|
862
852
|
// in-memory provider state are dropped.
|
|
863
853
|
clearConversation(sessionKey);
|
|
864
|
-
// Restore the source topic
|
|
865
|
-
// a change of project shows in the bot name on the next message.
|
|
866
|
-
// restoreTopicAndRefreshBotName handles both the topic write and the
|
|
867
|
-
// rate-limited setMyName call internally.
|
|
854
|
+
// Restore the source topic, for the status line and the thread name.
|
|
868
855
|
//
|
|
869
856
|
// Even with no topic to restore: the one in memory is the conversation this
|
|
870
|
-
// chat just left, and a
|
|
857
|
+
// chat just left, and a branch that arrives without a topic — from a chat
|
|
871
858
|
// that had none, or from /tree, where no history may name the point — would
|
|
872
859
|
// otherwise carry it on. Restoring none falls back to the title Claude Code
|
|
873
860
|
// gave the transcript.
|
|
874
|
-
|
|
875
|
-
await postMarker(ctx, sessionKey,
|
|
861
|
+
restoreTopic(sessionKey, branch.topic);
|
|
862
|
+
await postMarker(ctx, sessionKey, buildBranchMarker(branch, marker), {
|
|
876
863
|
claudeSessionId: newSessionId,
|
|
877
|
-
projectPath:
|
|
864
|
+
projectPath: branch.projectPath,
|
|
878
865
|
lineCount: loadedLineCount,
|
|
879
866
|
});
|
|
880
867
|
}
|
|
881
868
|
/**
|
|
882
869
|
* Put a banner where the chat switched conversations — over the message whose
|
|
883
870
|
* button made the switch, or as a reply to the command that did — and anchor
|
|
884
|
-
* its
|
|
871
|
+
* its 🌱 Branch button at `point`.
|
|
885
872
|
*
|
|
886
|
-
* The banner is where the new conversation starts in this chat, so it
|
|
873
|
+
* The banner is where the new conversation starts in this chat, so it branches
|
|
887
874
|
* that point: sending it to another bot, or branching it again here, doesn't
|
|
888
875
|
* mean scrolling back to the message it was first taken from. Like that
|
|
889
|
-
* message's button, it
|
|
876
|
+
* message's button, it branches the transcript as it was at that point, whatever
|
|
890
877
|
* the conversation has done since. Its 🌳 button opens the tree the
|
|
891
878
|
* conversation is part of.
|
|
892
879
|
*
|
|
@@ -917,20 +904,20 @@ export async function postMarker(ctx, sessionKey, marker, point) {
|
|
|
917
904
|
/** A line heavy enough to read as a break in the chat, short enough for a phone. */
|
|
918
905
|
const MARKER_RULE = '━'.repeat(16);
|
|
919
906
|
/**
|
|
920
|
-
* How long the prompt a
|
|
907
|
+
* How long the prompt a branch picks up after can run before the banner shows
|
|
921
908
|
* only its start and its end: as long as /prompts and the status line let one
|
|
922
909
|
* run. The longest reply a banner holds still fits in the message with it.
|
|
923
910
|
*/
|
|
924
911
|
const MARKER_PROMPT_LEN = 300;
|
|
925
912
|
/**
|
|
926
|
-
* How much of the reply a
|
|
913
|
+
* How much of the reply a branch picks up after its marker holds. Telegram caps
|
|
927
914
|
* a message at 4096 characters, and the rest of the banner has to fit too.
|
|
928
915
|
*/
|
|
929
916
|
const MARKER_REPLY_LEN = 3000;
|
|
930
917
|
/** What a switch left above the banner, when it wasn't the conversation branched from. */
|
|
931
918
|
export const LEFT_ABOVE = "What's above is the conversation you were in — it's in /resume.";
|
|
932
919
|
/**
|
|
933
|
-
* The message a loaded
|
|
920
|
+
* The message a loaded branch leaves in its chat: a banner where
|
|
934
921
|
* one conversation ends and another begins.
|
|
935
922
|
*
|
|
936
923
|
* Scrolled back through, the messages on either side of it would otherwise
|
|
@@ -939,18 +926,18 @@ export const LEFT_ABOVE = "What's above is the conversation you were in — it's
|
|
|
939
926
|
* outright that a new conversation starts here, shows the exchange it picks
|
|
940
927
|
* up after, and says where the conversation above went.
|
|
941
928
|
*
|
|
942
|
-
* The reply goes in whole, collapsed. A
|
|
929
|
+
* The reply goes in whole, collapsed. A branch to another bot would otherwise
|
|
943
930
|
* leave it in the other bot's chat, and a branch taken here would leave the
|
|
944
931
|
* last reply above your next message one the branch never had.
|
|
945
932
|
*/
|
|
946
|
-
export function
|
|
947
|
-
const isBranch =
|
|
933
|
+
export function buildBranchMarker(branch, opts = {}) {
|
|
934
|
+
const isBranch = branch.fromBotId === BOT_ID;
|
|
948
935
|
return buildMarker({
|
|
949
|
-
title: isBranch ? '🌱 New branch' :
|
|
950
|
-
name: sessionDisplayName({ projectName: path.basename(
|
|
936
|
+
title: isBranch ? '🌱 New branch' : `🌱 Branched from ${branch.fromBotName}`,
|
|
937
|
+
name: sessionDisplayName({ projectName: path.basename(branch.projectPath), topic: branch.topic }),
|
|
951
938
|
lead: 'A new conversation starts here.',
|
|
952
939
|
after: 'It picks up after:',
|
|
953
|
-
exchange: lastExchangeIn(
|
|
940
|
+
exchange: lastExchangeIn(branch.jsonl),
|
|
954
941
|
above: opts.above ?? (isBranch
|
|
955
942
|
? "What's above is the conversation you branched from — it's in /resume."
|
|
956
943
|
: "What's above is this bot's previous conversation — it's in /resume."),
|
|
@@ -958,7 +945,7 @@ export function buildForkMarker(fork, opts = {}) {
|
|
|
958
945
|
}
|
|
959
946
|
/**
|
|
960
947
|
* The banner for going back to a branch that already exists: the same break
|
|
961
|
-
* in the chat as a
|
|
948
|
+
* in the chat as a branch's, except the conversation below it isn't new — it
|
|
962
949
|
* carries on from the exchange shown.
|
|
963
950
|
*/
|
|
964
951
|
export function buildBackOnBranchMarker(branch) {
|
|
@@ -1016,10 +1003,10 @@ function sliceWhole(text, end) {
|
|
|
1016
1003
|
* The reply as a collapsed quote. A quote holds plain text only, so markdown
|
|
1017
1004
|
* markers go rather than show up as stray asterisks, backticks and hashes. A
|
|
1018
1005
|
* reply longer than `max` is cut at a line or word, followed by `rest` — by
|
|
1019
|
-
* default, naming /
|
|
1006
|
+
* default, naming /history, which shows the reply whole, formatted. One message
|
|
1020
1007
|
* per line of the result.
|
|
1021
1008
|
*/
|
|
1022
|
-
export function replyQuote(reply, max = MARKER_REPLY_LEN, rest = 'The rest of the reply is in /
|
|
1009
|
+
export function replyQuote(reply, max = MARKER_REPLY_LEN, rest = 'The rest of the reply is in /history.') {
|
|
1023
1010
|
const text = reply
|
|
1024
1011
|
.replace(/^\s*```.*$/gm, '')
|
|
1025
1012
|
.replace(/^#{1,6}\s+/gm, '')
|
|
@@ -1037,10 +1024,10 @@ export function replyQuote(reply, max = MARKER_REPLY_LEN, rest = 'The rest of th
|
|
|
1037
1024
|
];
|
|
1038
1025
|
}
|
|
1039
1026
|
/**
|
|
1040
|
-
* Proactively DM the
|
|
1027
|
+
* Proactively DM the branch offer to the user as soon as it lands, without
|
|
1041
1028
|
* waiting for them to type something into the target bot.
|
|
1042
1029
|
*
|
|
1043
|
-
* Implementation: poll the mtime of pending-
|
|
1030
|
+
* Implementation: poll the mtime of pending-branches-<botId>.json every few
|
|
1044
1031
|
* seconds. On change (and once at startup), scan for entries where
|
|
1045
1032
|
* `offered` is unset and the userId is allowed (`.env` or the roster). For each, try
|
|
1046
1033
|
* bot.api.sendMessage(userId, …) — in a Telegram DM, chat_id == user_id,
|
|
@@ -1051,8 +1038,8 @@ export function replyQuote(reply, max = MARKER_REPLY_LEN, rest = 'The rest of th
|
|
|
1051
1038
|
* leave the entry unoffered and let the lazy in-message path handle it
|
|
1052
1039
|
* whenever the user does message the bot.
|
|
1053
1040
|
*/
|
|
1054
|
-
export function
|
|
1055
|
-
const filePath =
|
|
1041
|
+
export function startPendingBranchWatcher(bot) {
|
|
1042
|
+
const filePath = pendingBranchesPathFor(BOT_ID);
|
|
1056
1043
|
let lastMtimeMs = 0;
|
|
1057
1044
|
let scanInFlight = false;
|
|
1058
1045
|
const tick = async () => {
|
|
@@ -1076,34 +1063,34 @@ export function startPendingForkWatcher(bot) {
|
|
|
1076
1063
|
scanInFlight = false;
|
|
1077
1064
|
}
|
|
1078
1065
|
};
|
|
1079
|
-
// Startup scan: there may already be unoffered
|
|
1080
|
-
// crash/restart while a
|
|
1066
|
+
// Startup scan: there may already be unoffered branches waiting from a
|
|
1067
|
+
// crash/restart while a branch was sitting unsent.
|
|
1081
1068
|
void tick();
|
|
1082
1069
|
setInterval(() => { void tick(); }, 2_000).unref();
|
|
1083
1070
|
}
|
|
1084
1071
|
async function scanAndOffer(bot) {
|
|
1085
|
-
const entries =
|
|
1086
|
-
for (const [userIdStr,
|
|
1087
|
-
if (
|
|
1072
|
+
const entries = listPendingBranches(BOT_ID);
|
|
1073
|
+
for (const [userIdStr, branch] of Object.entries(entries)) {
|
|
1074
|
+
if (branch.offered)
|
|
1088
1075
|
continue;
|
|
1089
1076
|
const userId = Number.parseInt(userIdStr, 10);
|
|
1090
1077
|
if (!Number.isFinite(userId))
|
|
1091
1078
|
continue;
|
|
1092
1079
|
if (!isAllowedUser(userId))
|
|
1093
1080
|
continue;
|
|
1094
|
-
const offer =
|
|
1081
|
+
const offer = buildBranchOffer(branch, 'proactive');
|
|
1095
1082
|
try {
|
|
1096
1083
|
await sendFormatted(bot.api, userId, offer.text, { reply_markup: offer.keyboard });
|
|
1097
|
-
|
|
1084
|
+
markBranchOffered(BOT_ID, userId);
|
|
1098
1085
|
}
|
|
1099
1086
|
catch (err) {
|
|
1100
1087
|
// 403 "bot can't initiate conversation with a user" / "chat not found"
|
|
1101
|
-
// is expected when the user has never DM'd this bot. Leave the
|
|
1088
|
+
// is expected when the user has never DM'd this bot. Leave the branch
|
|
1102
1089
|
// unoffered so the lazy in-message path picks it up next time the
|
|
1103
1090
|
// user messages this bot.
|
|
1104
1091
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1105
|
-
console.debug(`[
|
|
1092
|
+
console.debug(`[Branch] Proactive offer to ${userIdStr} failed (will retry via lazy path): ${msg}`);
|
|
1106
1093
|
}
|
|
1107
1094
|
}
|
|
1108
1095
|
}
|
|
1109
|
-
//# sourceMappingURL=
|
|
1096
|
+
//# sourceMappingURL=branch.handler.js.map
|