telecoder 0.0.0-stage → 1.2.0

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