telecoder 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,1096 @@
1
+ /**
2
+ * /branch — hand off a conversation from this bot to a sibling bot at a chosen
3
+ * past assistant message.
4
+ *
5
+ * Tap flow:
6
+ * 1. "🌱 Branch" button on a past bot message → branch:pick
7
+ * ↳ shows picker of sibling bots
8
+ * 2. Tap target bot → branch:to:<botId>:<msgId>
9
+ * ↳ shows confirmation
10
+ * 3. Tap Confirm → branch:confirm:<botId>:<msgId>
11
+ * ↳ truncates source JSONL, writes pending branch to target's file
12
+ *
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.
16
+ *
17
+ * Target-side pickup (in message.handler):
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)
21
+ *
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
25
+ * back to the message it was taken from.
26
+ *
27
+ * /branchaccept and /branchdecline slash commands behave the same as the buttons, in
28
+ * case the inline keyboard isn't accessible.
29
+ */
30
+ import * as fs from 'fs';
31
+ import * as path from 'path';
32
+ import * as crypto from 'crypto';
33
+ import { BOT_ID, config } from '../../config.js';
34
+ import { buildSessionKey, getSessionKeyFromCtx } from '../../utils/session-key.js';
35
+ import { messageOffsets, countJsonlLines } from '../../claude/message-offsets.js';
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';
38
+ import { listSiblingBots, findBotById } from '../../utils/instances.js';
39
+ import { buildLetteredKeyboard, letteredOptionLines } from '../../telegram/lettered-options.js';
40
+ import { sessionJsonlPath, lastAssistantTurnText, lastExchangeIn, rewriteJsonlSessionId, branchPastRunningTurn, } from '../../claude/session-jsonl.js';
41
+ import { sessionManager } from '../../claude/session-manager.js';
42
+ import { clearConversation } from '../../providers/provider-router.js';
43
+ import { isAllowedUser } from '../../utils/user-roster.js';
44
+ import { EntityText, joinMessages, plain } from '../../telegram/entities.js';
45
+ import { editCallbackMessage, replyFormatted, sendFormatted } from '../../telegram/send.js';
46
+ import { cutLabel, promptLabel } from '../../telegram/prompt-label.js';
47
+ import { restoreTopic } from './command.handler.js';
48
+ import { getSessionTopic } from './command.handler.js';
49
+ import { sessionDisplayName } from './command/shared.js';
50
+ import { adoptThread, threadName } from '../../telegram/thread-titles.js';
51
+ import { isHomeProject } from '../../utils/home-project.js';
52
+ import { userPreferences } from '../../providers/user-preferences.js';
53
+ import { buildSyntheticCtx } from '../../claude/synthetic-ctx.js';
54
+ import { replayIntoThread } from '../middleware/queued-messages.js';
55
+ import { sanitizeError } from '../../utils/sanitize.js';
56
+ import { summarizeTopicWithHaiku } from '../../claude/auto-topic-haiku.js';
57
+ /** In front of a branched thread's name, so it reads apart from the one it came from. */
58
+ const BRANCH_THREAD_PREFIX = '🌱 ';
59
+ /**
60
+ * Whether a branch can open a thread of its own here: a private chat with a bot
61
+ * that has threads turned on. Groups have forum topics, but people name and
62
+ * order those for each other, so a branch doesn't add to them.
63
+ *
64
+ * Where it can, that's where every branch goes, without a picker: a new thread
65
+ * keeps both conversations open side by side, which a branch here or a
66
+ * sibling bot only approximates, and someone who turned threads on wants them.
67
+ */
68
+ function canBranchToThread(ctx) {
69
+ return ctx.chat?.type === 'private' && ctx.me?.has_topics_enabled === true;
70
+ }
71
+ /**
72
+ * Build the branch-target picker: this bot itself (a fresh branch of the current
73
+ * conversation) first, then every sibling bot, then Cancel. Self is always
74
+ * offered so you can branch a thread without needing a second bot.
75
+ *
76
+ * Returns the body lines as well as the rows. A sibling's name is whatever the
77
+ * operator wrote in the instances config, and on a button anything past the
78
+ * width Telegram renders is ellipsised away with no way to read it — two bots
79
+ * sharing a prefix would arrive as the same clipped line. So the targets are
80
+ * written out in the message keyed A/B/C and the same letter keys the button,
81
+ * the way /resume and `telecoder_ask_user` list their options. Cancel keeps
82
+ * its own row and no letter: it is the way out, not one of the targets.
83
+ */
84
+ export function buildTargetPicker(anchorMsgId) {
85
+ const targets = [
86
+ // Which bot "here" is goes in the description rather than the label: it
87
+ // is the one sending the message, so it is context, not the choice — and
88
+ // parenthesising it on the label costs the whole keyboard its labels.
89
+ {
90
+ label: '🌱 New branch here',
91
+ description: config.BOT_NAME,
92
+ callbackData: `branch:to:${BOT_ID}:${anchorMsgId}`,
93
+ },
94
+ ...listSiblingBots(BOT_ID).map((b) => ({
95
+ label: b.name,
96
+ callbackData: `branch:to:${b.botId}:${anchorMsgId}`,
97
+ })),
98
+ ];
99
+ return {
100
+ lines: letteredOptionLines(targets),
101
+ keyboard: [
102
+ ...buildLetteredKeyboard(targets),
103
+ [{ text: 'Cancel', callback_data: 'branch:cancel' }],
104
+ ],
105
+ };
106
+ }
107
+ /**
108
+ * Compose the "branch received" message + inline keyboard. Shared between the
109
+ * lazy in-message path (reply in current chat) and the proactive watcher
110
+ * (DMs the user without waiting for them to type).
111
+ */
112
+ function buildBranchOffer(branch, mode) {
113
+ const projectLabel = path.basename(branch.projectPath);
114
+ const text = new EntityText()
115
+ .add('📦 ').bold(`Branch received from ${branch.fromBotName}`).newline(2)
116
+ .add('Project: ').bold(projectLabel);
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));
121
+ }
122
+ text.newline(2).add("Accepting will replace this bot's current conversation (saved to /resume history). Decline to discard the branch.");
123
+ if (mode === 'lazy') {
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.");
125
+ }
126
+ return {
127
+ text: text.build(),
128
+ keyboard: {
129
+ inline_keyboard: [
130
+ [
131
+ { text: '✅ Accept branch', callback_data: 'branch:accept' },
132
+ { text: '❌ Decline', callback_data: 'branch:decline' },
133
+ ],
134
+ ],
135
+ },
136
+ };
137
+ }
138
+ export async function handleBranchCallback(ctx) {
139
+ const data = ctx.callbackQuery?.data;
140
+ if (!data)
141
+ return;
142
+ const parts = data.split(':');
143
+ const action = parts[1];
144
+ try {
145
+ if (action === 'pick') {
146
+ await onPick(ctx);
147
+ }
148
+ else if (action === 'to') {
149
+ await onTo(ctx, parts[2], parseInt(parts[3], 10));
150
+ }
151
+ else if (action === 'confirm') {
152
+ await onConfirm(ctx, parts[2], parseInt(parts[3], 10));
153
+ }
154
+ else if (action === 'cancel') {
155
+ await onCancel(ctx);
156
+ }
157
+ else if (action === 'accept') {
158
+ await onAccept(ctx);
159
+ }
160
+ else if (action === 'decline') {
161
+ await onDecline(ctx);
162
+ }
163
+ else {
164
+ await ctx.answerCallbackQuery({ text: 'Unknown branch action.' });
165
+ }
166
+ }
167
+ catch (err) {
168
+ console.error('[Branch] callback failed:', err instanceof Error ? err.message : err);
169
+ try {
170
+ await ctx.answerCallbackQuery({ text: 'Branch failed — see bot logs.' });
171
+ }
172
+ catch { /* ignore */ }
173
+ }
174
+ }
175
+ async function onPick(ctx) {
176
+ const keyInfo = getSessionKeyFromCtx(ctx);
177
+ const msgId = ctx.callbackQuery?.message?.message_id;
178
+ if (!keyInfo || !msgId) {
179
+ await ctx.answerCallbackQuery({ text: 'Cannot identify this message.' });
180
+ return;
181
+ }
182
+ const offset = messageOffsets.lookup(keyInfo.sessionKey, msgId);
183
+ if (!offset) {
184
+ await ctx.answerCallbackQuery({ text: 'Branch point no longer available for this message.' });
185
+ return;
186
+ }
187
+ if (canBranchToThread(ctx)) {
188
+ await branchIntoThread(ctx, keyInfo.sessionKey, offset, msgId);
189
+ return;
190
+ }
191
+ await ctx.answerCallbackQuery();
192
+ const projectLabel = path.basename(offset.projectPath);
193
+ const picker = buildTargetPicker(msgId);
194
+ await replyFormatted(ctx, new EntityText()
195
+ .add('🌱 ').bold('Branch conversation').newline(2)
196
+ .add('From this point in ').bold(projectLabel).add(' — pick where to branch it:').newline(2)
197
+ .add(picker.lines.join('\n'))
198
+ .build(), {
199
+ reply_parameters: { message_id: msgId },
200
+ reply_markup: { inline_keyboard: picker.keyboard },
201
+ });
202
+ }
203
+ async function onTo(ctx, targetBotId, sourceMsgId) {
204
+ const keyInfo = getSessionKeyFromCtx(ctx);
205
+ if (!keyInfo || Number.isNaN(sourceMsgId)) {
206
+ await ctx.answerCallbackQuery({ text: 'Invalid branch target.' });
207
+ return;
208
+ }
209
+ const offset = messageOffsets.lookup(keyInfo.sessionKey, sourceMsgId);
210
+ if (!offset) {
211
+ await ctx.answerCallbackQuery({ text: 'Branch point no longer available.' });
212
+ return;
213
+ }
214
+ const target = findBotById(targetBotId);
215
+ if (!target) {
216
+ await ctx.answerCallbackQuery({ text: 'Target bot not found.' });
217
+ return;
218
+ }
219
+ await ctx.answerCallbackQuery();
220
+ const projectLabel = path.basename(offset.projectPath);
221
+ const isSelf = targetBotId === BOT_ID;
222
+ const text = new EntityText();
223
+ if (isSelf) {
224
+ text.add('🌱 ').bold('Branch into a new conversation?').newline(2)
225
+ .add('This copies ').bold(projectLabel)
226
+ .add(' up to that point into a fresh conversation on this bot. '
227
+ + 'Your current conversation is saved to /resume history, and you continue from the branch point.');
228
+ }
229
+ else {
230
+ const name = target.name;
231
+ text.add('🌱 ').bold(`Branch to ${name}?`).newline(2)
232
+ .add('This will copy the conversation in ').bold(projectLabel)
233
+ .add(' up to that point and hand it off to ').bold(name).add('.').newline(2)
234
+ .add('When you open ').bold(name).add(" and send any message, you'll get a prompt to accept the branch. ")
235
+ .add('Accepting replaces ').bold(name).add("'s current conversation (saved to its /resume history).");
236
+ }
237
+ try {
238
+ await editCallbackMessage(ctx, text.build(), {
239
+ reply_markup: {
240
+ inline_keyboard: [
241
+ [{ text: '✅ Confirm branch', callback_data: `branch:confirm:${targetBotId}:${sourceMsgId}` }],
242
+ [{ text: 'Cancel', callback_data: 'branch:cancel' }],
243
+ ],
244
+ },
245
+ });
246
+ }
247
+ catch (err) {
248
+ console.debug('[Branch] onTo edit failed:', err instanceof Error ? err.message : err);
249
+ }
250
+ }
251
+ async function onConfirm(ctx, targetBotId, sourceMsgId) {
252
+ const keyInfo = getSessionKeyFromCtx(ctx);
253
+ if (!keyInfo || Number.isNaN(sourceMsgId)) {
254
+ await ctx.answerCallbackQuery({ text: 'Invalid branch target.' });
255
+ return;
256
+ }
257
+ const offset = messageOffsets.lookup(keyInfo.sessionKey, sourceMsgId);
258
+ if (!offset) {
259
+ await ctx.answerCallbackQuery({ text: 'Branch point no longer available.' });
260
+ return;
261
+ }
262
+ const target = findBotById(targetBotId);
263
+ if (!target) {
264
+ await ctx.answerCallbackQuery({ text: 'Target bot not found.' });
265
+ return;
266
+ }
267
+ const cut = cutBranch(ctx, keyInfo.sessionKey, offset, takeTypedName(keyInfo.sessionKey, sourceMsgId));
268
+ if ('error' in cut) {
269
+ await ctx.answerCallbackQuery({ text: cut.error });
270
+ return;
271
+ }
272
+ const { branch } = cut;
273
+ const userId = ctx.from?.id;
274
+ if (!userId) {
275
+ await ctx.answerCallbackQuery({ text: 'Could not identify user.' });
276
+ return;
277
+ }
278
+ // Self-branch: branch within this same bot/chat. The pending-branch handoff
279
+ // (and its accept/decline prompt) only exists to cross bots — here the
280
+ // source and target are the same conversation, so load the branch right
281
+ // now. loadBranch saves the current conversation to /resume history first.
282
+ if (targetBotId === BOT_ID) {
283
+ await loadBranch(ctx, keyInfo.sessionKey, branch);
284
+ await ctx.answerCallbackQuery({ text: 'Branched.' });
285
+ return;
286
+ }
287
+ // Key the pending branch by Telegram user id, not sessionKey: each bot has
288
+ // its own DM with the user with a different chatId, so the target bot
289
+ // can't find the branch by chatId-based key. User id is constant across
290
+ // bots; the offer will land in whichever chat the user next messages
291
+ // the target bot in.
292
+ putPendingBranch(target.botId, userId, branch);
293
+ await ctx.answerCallbackQuery({ text: 'Branched.' });
294
+ const projectLabel = path.basename(offset.projectPath);
295
+ try {
296
+ await editCallbackMessage(ctx, new EntityText()
297
+ .add('✅ ').bold(`Branched to ${target.name}`).newline(2)
298
+ .add('Open ').bold(target.name)
299
+ .add(` and send any message — you'll get the option to accept the branched conversation (${projectLabel}).`)
300
+ .newline(2)
301
+ .italic('This conversation carries on here unchanged.')
302
+ .build(), { reply_markup: BRANCH_KEYBOARD });
303
+ // This confirmation stands for the same point as the message the branch was
304
+ // taken from, and it's the one at the bottom of the chat — so it gets that
305
+ // message's branch point, and sending the point on to another bot, or
306
+ // branching it here, doesn't mean scrolling back up to find it.
307
+ const anchorId = ctx.callbackQuery?.message?.message_id;
308
+ if (anchorId)
309
+ messageOffsets.record(keyInfo.sessionKey, anchorId, offset);
310
+ }
311
+ catch (err) {
312
+ console.debug('[Branch] onConfirm edit failed:', err instanceof Error ? err.message : err);
313
+ }
314
+ }
315
+ /**
316
+ * The conversation as it stood at a branch point: the source transcript cut to
317
+ * the recorded line count, with what the receiving side shows about it.
318
+ */
319
+ function cutBranch(ctx, sessionKey, offset, name) {
320
+ const sourceJsonl = sessionJsonlPath(offset.projectPath, offset.claudeSessionId);
321
+ if (!fs.existsSync(sourceJsonl))
322
+ return { error: 'Source transcript no longer on disk.' };
323
+ let truncated;
324
+ try {
325
+ const raw = fs.readFileSync(sourceJsonl, 'utf-8');
326
+ const lines = raw.split('\n');
327
+ if (lines[lines.length - 1] === '')
328
+ lines.pop();
329
+ const sliced = lines.slice(0, offset.lineCount);
330
+ truncated = sliced.join('\n') + (sliced.length > 0 ? '\n' : '');
331
+ }
332
+ catch (err) {
333
+ console.error('[Branch] Failed to read source JSONL:', err);
334
+ return { error: 'Could not read source transcript.' };
335
+ }
336
+ return {
337
+ branch: {
338
+ fromBotName: config.BOT_NAME,
339
+ fromBotId: BOT_ID,
340
+ fromChatId: ctx.chat?.id,
341
+ projectPath: offset.projectPath,
342
+ jsonl: truncated,
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
347
+ // earlier message doesn't contain.
348
+ assistantPreview: lastAssistantTurnText(truncated)?.substring(0, 200),
349
+ createdAt: new Date().toISOString(),
350
+ },
351
+ };
352
+ }
353
+ /** A short notice: the tapped button's toast, or a reply when /branch was typed. */
354
+ async function tell(ctx, text) {
355
+ if (ctx.callbackQuery)
356
+ await ctx.answerCallbackQuery({ text });
357
+ else
358
+ await ctx.reply(text);
359
+ }
360
+ /**
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.
364
+ *
365
+ * The new thread starts with the settings this one chose for itself (model,
366
+ * effort, transport…), since it carries on the same conversation, and a name
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.
371
+ */
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.',
381
+ });
382
+ if ('error' in opened) {
383
+ await tell(ctx, opened.error);
384
+ return;
385
+ }
386
+ if (ctx.callbackQuery)
387
+ await ctx.answerCallbackQuery({ text: 'Branched into a new thread.' });
388
+ const { name, link } = opened;
389
+ const projectLabel = path.basename(branch.projectPath);
390
+ const b = new EntityText().add('✅ ').bold('Branched into a new thread').newline(2);
391
+ if (link)
392
+ b.link(name, link);
393
+ else
394
+ b.bold(name);
395
+ b.add(' carries on from that point in ').bold(projectLabel).add('.').newline(2)
396
+ .italic('This thread carries on here unchanged.');
397
+ const text = b.build();
398
+ try {
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.
405
+ if (anchorId)
406
+ messageOffsets.record(sessionKey, anchorId, offset);
407
+ }
408
+ catch (err) {
409
+ console.debug('[Branch] branchIntoThread reply failed:', err instanceof Error ? err.message : err);
410
+ }
411
+ }
412
+ /**
413
+ * Open a new thread named after the conversation, with this thread's
414
+ * settings, and load the branch into it with its banner. Nothing is said here.
415
+ */
416
+ async function openBranchThread(ctx, sessionKey, branch, marker) {
417
+ const chatId = ctx.chat?.id;
418
+ if (!chatId)
419
+ return { error: 'Cannot identify this chat.' };
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}`;
423
+ let threadId;
424
+ try {
425
+ threadId = (await ctx.api.createForumTopic(chatId, name)).message_thread_id;
426
+ }
427
+ catch (err) {
428
+ console.error('[Branch] createForumTopic failed:', err instanceof Error ? err.message : err);
429
+ return { error: 'Could not open a new thread.' };
430
+ }
431
+ const threadKey = buildSessionKey(chatId, threadId);
432
+ adoptThread(threadKey, name, BRANCH_THREAD_PREFIX);
433
+ userPreferences.copyScope(sessionKey, threadKey);
434
+ const threadCtx = buildSyntheticCtx({ api: ctx.api, sessionKey: threadKey, syntheticText: '' });
435
+ await loadBranch(threadCtx, threadKey, branch, marker);
436
+ const link = ctx.me?.username ? `https://t.me/${ctx.me.username}/${threadId}` : undefined;
437
+ return { threadId, threadKey, name, link };
438
+ }
439
+ /**
440
+ * What a branch taken while a turn is running has Claude say about that turn.
441
+ * In Claude's voice, because it stands as Claude's reply to the prompt.
442
+ */
443
+ export const STILL_RUNNING_NOTE = 'TeleCoder branched this conversation while the original was still working on the '
444
+ + 'message above, so none of that work happened here. The original is still on it, in the same working '
445
+ + "directory, so files may change while this branch runs. I won't redo or undo that work, and I'll check a "
446
+ + "file's current state before relying on it.";
447
+ /** What one sent while a turn was running says, on one line, for the `You:` line in the branch. */
448
+ function describeMessage(message) {
449
+ const words = message.text ?? message.caption;
450
+ if (words?.trim())
451
+ return words;
452
+ return message.voice ? '🎤 voice note' : message.photo ? '🖼 photo' : message.document ? '📎 file' : 'message';
453
+ }
454
+ /**
455
+ * The conversation as it stands, for a branch taken whether or not a turn is
456
+ * running: up to the last turn that ended, with the running one's prompt and
457
+ * STILL_RUNNING_NOTE after it when there is one (see branchPastRunningTurn).
458
+ */
459
+ function branchOfLatest(ctx, sessionKey) {
460
+ const session = sessionManager.getSession(sessionKey);
461
+ if (!session?.claudeSessionId)
462
+ return { error: 'No conversation to branch yet.' };
463
+ const sourceJsonl = sessionJsonlPath(session.workingDirectory, session.claudeSessionId);
464
+ let raw;
465
+ try {
466
+ raw = fs.readFileSync(sourceJsonl, 'utf-8');
467
+ }
468
+ catch {
469
+ return { error: 'No transcript on disk to branch.' };
470
+ }
471
+ const { jsonl, noted } = branchPastRunningTurn(raw, STILL_RUNNING_NOTE);
472
+ return {
473
+ noted,
474
+ branch: {
475
+ fromBotName: config.BOT_NAME,
476
+ fromBotId: BOT_ID,
477
+ fromChatId: ctx.chat?.id,
478
+ projectPath: session.workingDirectory,
479
+ jsonl,
480
+ topic: getSessionTopic(sessionKey),
481
+ assistantPreview: lastAssistantTurnText(jsonl)?.substring(0, 200),
482
+ createdAt: new Date().toISOString(),
483
+ },
484
+ };
485
+ }
486
+ /**
487
+ * "Ask in a branch" on a message waiting behind a running turn: the conversation
488
+ * as it stood before that turn goes into a new thread, with the running prompt
489
+ * and a reply saying it's still being worked on elsewhere (see
490
+ * branchPastRunningTurn), and a `You:` line showing what's about to be asked
491
+ * there. Sending the message itself is the caller's: it's the queue that holds
492
+ * the update.
493
+ */
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);
498
+ if ('error' in latest)
499
+ return latest;
500
+ const { branch, noted } = latest;
501
+ if (!noted)
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.',
505
+ });
506
+ if ('error' in opened)
507
+ return opened;
508
+ try {
509
+ await sendFormatted(ctx.api, ctx.chat.id, youLine(describeMessage(message), MARKER_PROMPT_LEN), { message_thread_id: opened.threadId });
510
+ }
511
+ catch (err) {
512
+ console.warn('[Branch] Could not post the You line:', err instanceof Error ? err.message : err);
513
+ }
514
+ return { threadId: opened.threadId, name: opened.name, link: opened.link };
515
+ }
516
+ async function onCancel(ctx) {
517
+ await ctx.answerCallbackQuery({ text: 'Cancelled.' });
518
+ try {
519
+ await ctx.editMessageText('🌱 Branch cancelled.');
520
+ }
521
+ catch { /* ignore */ }
522
+ }
523
+ // ── Target-side accept / decline ─────────────────────────────────────────
524
+ /**
525
+ * Show the "branch received" prompt in the target bot when a pending branch
526
+ * exists for this user. Called from message.handler before normal message
527
+ * handling. Returns true if a branch was offered (and the caller should drop
528
+ * the incoming message), false otherwise.
529
+ */
530
+ export async function offerPendingBranchIfAny(ctx) {
531
+ const userId = ctx.from?.id;
532
+ if (!userId)
533
+ return false;
534
+ const branch = getPendingBranch(BOT_ID, userId);
535
+ if (!branch)
536
+ return false;
537
+ const offer = buildBranchOffer(branch, 'lazy');
538
+ await replyFormatted(ctx, offer.text, { reply_markup: offer.keyboard });
539
+ markBranchOffered(BOT_ID, userId);
540
+ return true;
541
+ }
542
+ async function onAccept(ctx) {
543
+ const keyInfo = getSessionKeyFromCtx(ctx);
544
+ const userId = ctx.from?.id;
545
+ if (!keyInfo || !userId) {
546
+ await ctx.answerCallbackQuery({ text: 'No active chat.' });
547
+ return;
548
+ }
549
+ const branch = getPendingBranch(BOT_ID, userId);
550
+ if (!branch) {
551
+ await ctx.answerCallbackQuery({ text: 'No pending branch.' });
552
+ try {
553
+ await ctx.editMessageText('No pending branch to accept.');
554
+ }
555
+ catch { /* ignore */ }
556
+ return;
557
+ }
558
+ await loadBranch(ctx, keyInfo.sessionKey, branch);
559
+ removePendingBranch(BOT_ID, userId);
560
+ await ctx.answerCallbackQuery({ text: 'Branch loaded.' });
561
+ }
562
+ async function onDecline(ctx) {
563
+ const userId = ctx.from?.id;
564
+ if (!userId) {
565
+ await ctx.answerCallbackQuery({ text: 'No active chat.' });
566
+ return;
567
+ }
568
+ removePendingBranch(BOT_ID, userId);
569
+ await ctx.answerCallbackQuery({ text: 'Branch discarded.' });
570
+ try {
571
+ await ctx.editMessageText('❌ Branch discarded. Send a message to continue your current conversation.');
572
+ }
573
+ catch { /* ignore */ }
574
+ }
575
+ /**
576
+ * Slash-command equivalents of the inline buttons. Useful if the inline
577
+ * keyboard is missing (e.g. user scrolled away in a busy chat) or for power
578
+ * users who'd rather type. Both shape the response the same as the buttons.
579
+ */
580
+ /**
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.
599
+ */
600
+ export async function handleBranchCommand(ctx) {
601
+ const keyInfo = getSessionKeyFromCtx(ctx);
602
+ if (!keyInfo)
603
+ return;
604
+ const session = sessionManager.getSession(keyInfo.sessionKey);
605
+ if (!session?.claudeSessionId) {
606
+ await ctx.reply('No active conversation to branch. Send at least one message in this session first.');
607
+ return;
608
+ }
609
+ const jsonlPath = sessionJsonlPath(session.workingDirectory, session.claudeSessionId);
610
+ if (!fs.existsSync(jsonlPath)) {
611
+ await ctx.reply('No transcript on disk yet — finish an assistant turn before branching.');
612
+ return;
613
+ }
614
+ const raw = fs.readFileSync(jsonlPath, 'utf-8');
615
+ const lines = raw.split('\n');
616
+ if (lines[lines.length - 1] === '')
617
+ lines.pop();
618
+ const lineCount = lines.length;
619
+ if (lineCount === 0) {
620
+ await ctx.reply('Transcript is empty — nothing to branch.');
621
+ return;
622
+ }
623
+ // Record a synthetic offset against the user's /branch message so the rest
624
+ // of the flow can reuse the inline-button machinery unchanged. The
625
+ // /branch command itself is the anchor message.
626
+ const anchorMsgId = ctx.message?.message_id;
627
+ if (!anchorMsgId) {
628
+ await ctx.reply('Could not anchor branch — try the 🌱 button on a bot message instead.');
629
+ return;
630
+ }
631
+ messageOffsets.record(keyInfo.sessionKey, anchorMsgId, {
632
+ claudeSessionId: session.claudeSessionId,
633
+ projectPath: session.workingDirectory,
634
+ lineCount,
635
+ conversationId: session.conversationId,
636
+ });
637
+ const offset = messageOffsets.lookup(keyInfo.sessionKey, anchorMsgId);
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);
641
+ return;
642
+ }
643
+ if (name)
644
+ typedNames.set(`${keyInfo.sessionKey}:${anchorMsgId}`, name);
645
+ const projectLabel = path.basename(session.workingDirectory);
646
+ const picker = buildTargetPicker(anchorMsgId);
647
+ await replyFormatted(ctx, new EntityText()
648
+ .add('🌱 ').bold('Branch conversation').newline(2)
649
+ .add('From the current state of ').bold(projectLabel).add(' — pick where to branch it:').newline(2)
650
+ .add(picker.lines.join('\n'))
651
+ .build(), { reply_markup: { inline_keyboard: picker.keyboard } });
652
+ }
653
+ /**
654
+ * What the spun-off conversation is compacted around: the task, and that the
655
+ * rest of the work stays with the conversation it came from.
656
+ */
657
+ export function spinoffCompactFocus(task) {
658
+ return 'This conversation is being spun off into a new session for one task, which is the next message. '
659
+ + 'Keep what that task needs: the decisions, constraints and knowledge of the code that bear on it. '
660
+ + 'The original conversation carries on separately in the same working directory, with its own work '
661
+ + 'and background tasks; mention those only as far as they affect this task, and as belonging to the '
662
+ + `other session, not this one. The task: ${task}`;
663
+ }
664
+ /**
665
+ * /spinoff <task> — split one task off into a conversation of its own. The
666
+ * conversation as it stands (past a running turn, as "Ask in a branch" takes
667
+ * it) goes into a new thread, is compacted there around the task, and the
668
+ * task goes in as the first prompt. This thread carries on unchanged, so it
669
+ * works mid-turn: it's registered ahead of sequentialize, and the new thread
670
+ * has a queue of its own.
671
+ *
672
+ * Unlike a /branch, which takes the whole conversation along, the spinoff
673
+ * starts with only what its task needs, and starts on it without waiting for
674
+ * another message.
675
+ *
676
+ * Sent as a reply to one of the bot's messages, it spins off from that point
677
+ * instead, the way that message's 🌱 button branches: for a task planned before
678
+ * a tangent the spinoff has no need of.
679
+ *
680
+ * The thread is named after the task, not the conversation it came from. A
681
+ * thread's name is its topic's general half, which the topic summarizer keeps
682
+ * from one message to the next, so the source's topic would name the thread
683
+ * for good. Asked with no previous topic, it names the task's own area.
684
+ */
685
+ export async function handleSpinoffCommand(ctx) {
686
+ const keyInfo = getSessionKeyFromCtx(ctx);
687
+ const message = ctx.message;
688
+ if (!keyInfo || !message?.text)
689
+ return;
690
+ const argStart = message.text.match(/^\/spinoff(?:@\w+)?\s*/i)?.[0].length ?? message.text.length;
691
+ const task = message.text.slice(argStart).trim();
692
+ if (!task) {
693
+ await ctx.reply('Usage: /spinoff <task>\n\n'
694
+ + 'Opens a new thread with this conversation compacted around the task, and starts on it there. '
695
+ + 'This thread carries on as it is. Send it as a reply to one of my messages to spin off from that point.');
696
+ return;
697
+ }
698
+ if (!canBranchToThread(ctx)) {
699
+ await ctx.reply('A spinoff opens a new thread, and threads are off for this bot.');
700
+ return;
701
+ }
702
+ // In a thread, a message that isn't a reply still carries the thread's
703
+ // opening service message as its reply_to_message; that isn't a branch point.
704
+ const repliedTo = message.reply_to_message?.forum_topic_created ? undefined : message.reply_to_message;
705
+ const offset = repliedTo && messageOffsets.lookup(keyInfo.sessionKey, repliedTo.message_id);
706
+ if (repliedTo && !offset) {
707
+ await ctx.reply("There's no branch point on that message. Reply to one of my replies to spin off from there, "
708
+ + 'or send /spinoff without replying to spin off from where the conversation is now.');
709
+ return;
710
+ }
711
+ const cut = offset ? cutBranch(ctx, keyInfo.sessionKey, offset) : branchOfLatest(ctx, keyInfo.sessionKey);
712
+ if ('error' in cut) {
713
+ await ctx.reply(cut.error);
714
+ return;
715
+ }
716
+ const { branch } = cut;
717
+ if (config.AUTO_TOPIC_HAIKU) {
718
+ branch.topic = await summarizeTopicWithHaiku(task, undefined, path.basename(branch.projectPath)) ?? branch.topic;
719
+ }
720
+ const opened = await openBranchThread(ctx, keyInfo.sessionKey, branch, {
721
+ above: 'The conversation it was spun off from carries on in its own thread. '
722
+ + 'This one is compacted around the task below first, then starts on it.',
723
+ });
724
+ if ('error' in opened) {
725
+ await ctx.reply(opened.error);
726
+ return;
727
+ }
728
+ let taskLineId;
729
+ try {
730
+ taskLineId = (await sendFormatted(ctx.api, message.chat.id, youLine(task, MARKER_PROMPT_LEN), {
731
+ message_thread_id: opened.threadId,
732
+ })).message_id;
733
+ }
734
+ catch (err) {
735
+ console.warn('[Spinoff] Could not post the You line:', sanitizeError(err));
736
+ }
737
+ const b = new EntityText().add('🌱 ').bold('Spun off into ');
738
+ if (opened.link)
739
+ b.link(opened.name, opened.link);
740
+ else
741
+ b.bold(opened.name);
742
+ b.newline(2).italic('It compacts this conversation around the task, then starts on it. This thread carries on unchanged.');
743
+ try {
744
+ await replyFormatted(ctx, b.build(), {
745
+ reply_parameters: { message_id: message.message_id },
746
+ ...(opened.link ? { reply_markup: { inline_keyboard: [[{ text: `Open ${opened.name}`, url: opened.link }]] } } : {}),
747
+ });
748
+ }
749
+ catch (err) {
750
+ console.warn('[Spinoff] Could not confirm:', sanitizeError(err));
751
+ }
752
+ // The compact and then the task, each as if typed in the new thread. Each
753
+ // replay settles once its turn is over, so the task waits for the compact.
754
+ // Their own ids, or the message handler would take the second for a retry
755
+ // of the first: the /spinoff's for the compact (the handler never saw it),
756
+ // the You line's for the task.
757
+ const compact = `/compact ${spinoffCompactFocus(task)}`;
758
+ const taskEntities = message.entities
759
+ ?.filter((e) => e.offset >= argStart && e.type !== 'bot_command')
760
+ .map((e) => ({ ...e, offset: e.offset - argStart }));
761
+ void (async () => {
762
+ await replayIntoThread(ctx.update, opened.threadId, {
763
+ text: compact,
764
+ entities: [{ type: 'bot_command', offset: 0, length: '/compact'.length }],
765
+ });
766
+ await replayIntoThread(ctx.update, opened.threadId, {
767
+ text: task,
768
+ entities: taskEntities?.length ? taskEntities : undefined,
769
+ ...(taskLineId ? { message_id: taskLineId } : {}),
770
+ });
771
+ })().catch((err) => {
772
+ console.error(`[Spinoff] Starting the spinoff in thread ${opened.threadId} failed:`, sanitizeError(err));
773
+ });
774
+ }
775
+ export async function handleBranchAcceptCommand(ctx) {
776
+ const keyInfo = getSessionKeyFromCtx(ctx);
777
+ const userId = ctx.from?.id;
778
+ if (!keyInfo || !userId)
779
+ return;
780
+ const branch = getPendingBranch(BOT_ID, userId);
781
+ if (!branch) {
782
+ await ctx.reply('There is no pending branch to accept.');
783
+ return;
784
+ }
785
+ await loadBranch(ctx, keyInfo.sessionKey, branch);
786
+ removePendingBranch(BOT_ID, userId);
787
+ }
788
+ export async function handleBranchDeclineCommand(ctx) {
789
+ const userId = ctx.from?.id;
790
+ if (!userId)
791
+ return;
792
+ if (!getPendingBranch(BOT_ID, userId)) {
793
+ await ctx.reply('There is no pending branch to decline.');
794
+ return;
795
+ }
796
+ removePendingBranch(BOT_ID, userId);
797
+ await ctx.reply('❌ Branch discarded.');
798
+ }
799
+ /**
800
+ * Take a pending branch, write the truncated JSONL to a fresh session file in
801
+ * the source project's Claude Code dir, and point this bot's session at it.
802
+ * If the project we're branching into is different from the current one, the
803
+ * session-manager call mints a fresh conversation in the new cwd; if it's
804
+ * the same project, we still want a fresh conversation so we don't tack the
805
+ * old transcript onto whatever's already loaded.
806
+ *
807
+ * `marker` rewords the banner for a caller whose branch doesn't come from the
808
+ * chat above it — /tree branches from any point, not the message you tapped.
809
+ */
810
+ export async function loadBranch(ctx, sessionKey, branch, marker) {
811
+ // Generate a fresh sessionId for this bot's copy of the transcript. We
812
+ // rewrite the `sessionId` field in each record so the file is internally
813
+ // consistent — Claude Code stamps the original session's id into every
814
+ // record, and a resume can get confused if the filename and contents
815
+ // disagree.
816
+ const newSessionId = crypto.randomUUID();
817
+ const rewritten = rewriteJsonlSessionId(branch.jsonl, newSessionId);
818
+ const targetPath = sessionJsonlPath(branch.projectPath, newSessionId);
819
+ try {
820
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
821
+ fs.writeFileSync(targetPath, rewritten, { mode: 0o600 });
822
+ }
823
+ catch (err) {
824
+ console.error('[Branch] Failed to write target JSONL:', err);
825
+ await ctx.reply('❌ Failed to load branch: could not write transcript to disk.');
826
+ return;
827
+ }
828
+ // The branch point, for the 🌱 Branch button on the done message below.
829
+ // Counted before the session points at the file: from then on the next
830
+ // turn appends to it.
831
+ const loadedLineCount = countJsonlLines(targetPath);
832
+ // Reset this bot's session to the branched project + transcript. Calling
833
+ // setWorkingDirectory mints a fresh conversation; if the project matches
834
+ // an existing session, we still want a clean slate, so we follow up with
835
+ // startNewConversation when needed.
836
+ const existing = sessionManager.getSession(sessionKey);
837
+ if (existing && existing.workingDirectory === branch.projectPath) {
838
+ sessionManager.startNewConversation(sessionKey);
839
+ }
840
+ else {
841
+ sessionManager.setWorkingDirectory(sessionKey, branch.projectPath);
842
+ }
843
+ sessionManager.setClaudeSessionId(sessionKey, newSessionId);
844
+ // Sever any live process bound to the old session. A long-lived
845
+ // `claude` process is reused as long as its cwd is unchanged (see
846
+ // PtyProvider._getOrCreateSession) — so a same-project branch would otherwise
847
+ // keep serving the pre-branch session and silently ignore the branch we just
848
+ // loaded. Tearing it down (exactly what /clear does) forces the next turn to
849
+ // respawn with `--resume <newSessionId>` onto the branched transcript. Order
850
+ // matters: this must run AFTER setClaudeSessionId, since clearConversation
851
+ // leaves sessionManager's session id untouched — only the live process and
852
+ // in-memory provider state are dropped.
853
+ clearConversation(sessionKey);
854
+ // Restore the source topic, for the status line and the thread name.
855
+ //
856
+ // Even with no topic to restore: the one in memory is the conversation this
857
+ // chat just left, and a branch that arrives without a topic — from a chat
858
+ // that had none, or from /tree, where no history may name the point — would
859
+ // otherwise carry it on. Restoring none falls back to the title Claude Code
860
+ // gave the transcript.
861
+ restoreTopic(sessionKey, branch.topic);
862
+ await postMarker(ctx, sessionKey, buildBranchMarker(branch, marker), {
863
+ claudeSessionId: newSessionId,
864
+ projectPath: branch.projectPath,
865
+ lineCount: loadedLineCount,
866
+ });
867
+ }
868
+ /**
869
+ * Put a banner where the chat switched conversations — over the message whose
870
+ * button made the switch, or as a reply to the command that did — and anchor
871
+ * its 🌱 Branch button at `point`.
872
+ *
873
+ * The banner is where the new conversation starts in this chat, so it branches
874
+ * that point: sending it to another bot, or branching it again here, doesn't
875
+ * mean scrolling back to the message it was first taken from. Like that
876
+ * message's button, it branches the transcript as it was at that point, whatever
877
+ * the conversation has done since. Its 🌳 button opens the tree the
878
+ * conversation is part of.
879
+ *
880
+ * A marker Telegram won't format still has to land in plain text: left
881
+ * unedited, the message would go on offering the buttons that made the switch.
882
+ * The send helpers retry it unformatted.
883
+ */
884
+ export async function postMarker(ctx, sessionKey, marker, point) {
885
+ try {
886
+ let anchorId;
887
+ if (ctx.callbackQuery) {
888
+ await editCallbackMessage(ctx, marker, { reply_markup: BRANCH_MARKER_KEYBOARD });
889
+ anchorId = ctx.callbackQuery.message?.message_id;
890
+ }
891
+ else {
892
+ const sent = await replyFormatted(ctx, marker, { reply_markup: BRANCH_MARKER_KEYBOARD });
893
+ anchorId = sent.message_id;
894
+ }
895
+ if (anchorId) {
896
+ messageOffsets.record(sessionKey, anchorId, {
897
+ ...point,
898
+ conversationId: sessionManager.getSession(sessionKey)?.conversationId,
899
+ });
900
+ }
901
+ }
902
+ catch { /* ignore */ }
903
+ }
904
+ /** A line heavy enough to read as a break in the chat, short enough for a phone. */
905
+ const MARKER_RULE = '━'.repeat(16);
906
+ /**
907
+ * How long the prompt a branch picks up after can run before the banner shows
908
+ * only its start and its end: as long as /prompts and the status line let one
909
+ * run. The longest reply a banner holds still fits in the message with it.
910
+ */
911
+ const MARKER_PROMPT_LEN = 300;
912
+ /**
913
+ * How much of the reply a branch picks up after its marker holds. Telegram caps
914
+ * a message at 4096 characters, and the rest of the banner has to fit too.
915
+ */
916
+ const MARKER_REPLY_LEN = 3000;
917
+ /** What a switch left above the banner, when it wasn't the conversation branched from. */
918
+ export const LEFT_ABOVE = "What's above is the conversation you were in — it's in /resume.";
919
+ /**
920
+ * The message a loaded branch leaves in its chat: a banner where
921
+ * one conversation ends and another begins.
922
+ *
923
+ * Scrolled back through, the messages on either side of it would otherwise
924
+ * read as one thread — and for a branch taken in the same chat, the messages
925
+ * just above even carry on past the point the branch starts from. So it says
926
+ * outright that a new conversation starts here, shows the exchange it picks
927
+ * up after, and says where the conversation above went.
928
+ *
929
+ * The reply goes in whole, collapsed. A branch to another bot would otherwise
930
+ * leave it in the other bot's chat, and a branch taken here would leave the
931
+ * last reply above your next message one the branch never had.
932
+ */
933
+ export function buildBranchMarker(branch, opts = {}) {
934
+ const isBranch = branch.fromBotId === BOT_ID;
935
+ return buildMarker({
936
+ title: isBranch ? '🌱 New branch' : `🌱 Branched from ${branch.fromBotName}`,
937
+ name: sessionDisplayName({ projectName: path.basename(branch.projectPath), topic: branch.topic }),
938
+ lead: 'A new conversation starts here.',
939
+ after: 'It picks up after:',
940
+ exchange: lastExchangeIn(branch.jsonl),
941
+ above: opts.above ?? (isBranch
942
+ ? "What's above is the conversation you branched from — it's in /resume."
943
+ : "What's above is this bot's previous conversation — it's in /resume."),
944
+ });
945
+ }
946
+ /**
947
+ * The banner for going back to a branch that already exists: the same break
948
+ * in the chat as a branch's, except the conversation below it isn't new — it
949
+ * carries on from the exchange shown.
950
+ */
951
+ export function buildBackOnBranchMarker(branch) {
952
+ return buildMarker({
953
+ title: '↪️ Back on a branch',
954
+ name: sessionDisplayName({ projectName: path.basename(branch.projectPath), topic: branch.topic }),
955
+ lead: "You're back on an earlier branch.",
956
+ after: 'It carries on from:',
957
+ exchange: lastExchangeIn(branch.jsonl),
958
+ above: LEFT_ABOVE,
959
+ });
960
+ }
961
+ function buildMarker(parts) {
962
+ const { title, name, lead, after, exchange, above } = parts;
963
+ return joinMessages([
964
+ plain(MARKER_RULE),
965
+ new EntityText().bold(title).build(),
966
+ plain(MARKER_RULE),
967
+ plain(name),
968
+ plain(''),
969
+ ...(exchange
970
+ ? [
971
+ plain(`${lead} ${after}`),
972
+ youLine(exchange.user, MARKER_PROMPT_LEN),
973
+ ...replyQuote(exchange.assistant),
974
+ ]
975
+ : [plain(lead)]),
976
+ plain(''),
977
+ new EntityText().italic(above).build(),
978
+ ], '\n');
979
+ }
980
+ /** `You: <prompt>`, the prompt on one line: how a banner or a node names what was asked. */
981
+ export function youLine(user, max) {
982
+ return new EntityText().bold('You:').add(` ${promptLine(user, max)}`).build();
983
+ }
984
+ /**
985
+ * The prompt of an exchange, on one line: cleaned the way promptLabel cleans
986
+ * one — a paste's text without its tags, an upload's caption, the words
987
+ * written under a quote — or as the log has it when it was a command. Whole
988
+ * up to `max` characters, past that by its start and its end.
989
+ */
990
+ export function promptLine(user, max) {
991
+ return cutLabel(promptLabel(user) ?? user.replace(/\s+/g, ' ').trim(), max);
992
+ }
993
+ /**
994
+ * The first `end` UTF-16 units of `text`, one fewer when the cut would fall
995
+ * inside an emoji. Half a surrogate pair is not valid text, and Telegram
996
+ * rejects a message carrying one.
997
+ */
998
+ function sliceWhole(text, end) {
999
+ const last = text.charCodeAt(end - 1);
1000
+ return text.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end);
1001
+ }
1002
+ /**
1003
+ * The reply as a collapsed quote. A quote holds plain text only, so markdown
1004
+ * markers go rather than show up as stray asterisks, backticks and hashes. A
1005
+ * reply longer than `max` is cut at a line or word, followed by `rest` — by
1006
+ * default, naming /history, which shows the reply whole, formatted. One message
1007
+ * per line of the result.
1008
+ */
1009
+ export function replyQuote(reply, max = MARKER_REPLY_LEN, rest = 'The rest of the reply is in /history.') {
1010
+ const text = reply
1011
+ .replace(/^\s*```.*$/gm, '')
1012
+ .replace(/^#{1,6}\s+/gm, '')
1013
+ .replace(/\*\*|__|`/g, '')
1014
+ .replace(/\n{3,}/g, '\n\n')
1015
+ .trim();
1016
+ const collapsed = (body) => new EntityText().quote(body, true).build();
1017
+ if (text.length <= max)
1018
+ return [collapsed(text)];
1019
+ const cut = sliceWhole(text, max);
1020
+ const end = Math.max(cut.lastIndexOf('\n'), cut.lastIndexOf(' '));
1021
+ return [
1022
+ collapsed(`${(end > 0 ? cut.slice(0, end) : cut).trimEnd()} …`),
1023
+ ...(rest ? [plain(rest)] : []),
1024
+ ];
1025
+ }
1026
+ /**
1027
+ * Proactively DM the branch offer to the user as soon as it lands, without
1028
+ * waiting for them to type something into the target bot.
1029
+ *
1030
+ * Implementation: poll the mtime of pending-branches-<botId>.json every few
1031
+ * seconds. On change (and once at startup), scan for entries where
1032
+ * `offered` is unset and the userId is allowed (`.env` or the roster). For each, try
1033
+ * bot.api.sendMessage(userId, …) — in a Telegram DM, chat_id == user_id,
1034
+ * so this hits the user's existing conversation with this bot. On success,
1035
+ * stamp `offered: true` so we don't re-send on the next file change.
1036
+ *
1037
+ * If the send fails (user has never DM'd this bot — "chat not found"),
1038
+ * leave the entry unoffered and let the lazy in-message path handle it
1039
+ * whenever the user does message the bot.
1040
+ */
1041
+ export function startPendingBranchWatcher(bot) {
1042
+ const filePath = pendingBranchesPathFor(BOT_ID);
1043
+ let lastMtimeMs = 0;
1044
+ let scanInFlight = false;
1045
+ const tick = async () => {
1046
+ if (scanInFlight)
1047
+ return;
1048
+ let mtimeMs = 0;
1049
+ try {
1050
+ mtimeMs = fs.statSync(filePath).mtimeMs;
1051
+ }
1052
+ catch {
1053
+ return; // file doesn't exist yet — nothing to do
1054
+ }
1055
+ if (mtimeMs === lastMtimeMs)
1056
+ return;
1057
+ lastMtimeMs = mtimeMs;
1058
+ scanInFlight = true;
1059
+ try {
1060
+ await scanAndOffer(bot);
1061
+ }
1062
+ finally {
1063
+ scanInFlight = false;
1064
+ }
1065
+ };
1066
+ // Startup scan: there may already be unoffered branches waiting from a
1067
+ // crash/restart while a branch was sitting unsent.
1068
+ void tick();
1069
+ setInterval(() => { void tick(); }, 2_000).unref();
1070
+ }
1071
+ async function scanAndOffer(bot) {
1072
+ const entries = listPendingBranches(BOT_ID);
1073
+ for (const [userIdStr, branch] of Object.entries(entries)) {
1074
+ if (branch.offered)
1075
+ continue;
1076
+ const userId = Number.parseInt(userIdStr, 10);
1077
+ if (!Number.isFinite(userId))
1078
+ continue;
1079
+ if (!isAllowedUser(userId))
1080
+ continue;
1081
+ const offer = buildBranchOffer(branch, 'proactive');
1082
+ try {
1083
+ await sendFormatted(bot.api, userId, offer.text, { reply_markup: offer.keyboard });
1084
+ markBranchOffered(BOT_ID, userId);
1085
+ }
1086
+ catch (err) {
1087
+ // 403 "bot can't initiate conversation with a user" / "chat not found"
1088
+ // is expected when the user has never DM'd this bot. Leave the branch
1089
+ // unoffered so the lazy in-message path picks it up next time the
1090
+ // user messages this bot.
1091
+ const msg = err instanceof Error ? err.message : String(err);
1092
+ console.debug(`[Branch] Proactive offer to ${userIdStr} failed (will retry via lazy path): ${msg}`);
1093
+ }
1094
+ }
1095
+ }
1096
+ //# sourceMappingURL=branch.handler.js.map