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,438 @@
1
+ /**
2
+ * Session lifecycle: /clear, /continue, /recap, /handoff, /sync,
3
+ * /sessions and /teleport. /prompts, which branches as well as lists, lives
4
+ * beside /tree in prompts.handler.ts.
5
+ *
6
+ * All of these move a chat between conversations — starting a fresh one,
7
+ * picking an older one back up, or summarising what a previous one did — so
8
+ * they share the session history, the JSONL reader and the topic restore.
9
+ */
10
+ import * as fs from 'fs';
11
+ import * as path from 'path';
12
+ import { config } from '../../../config.js';
13
+ import { sessionManager } from '../../../claude/session-manager.js';
14
+ import { sessionHistory } from '../../../claude/session-history.js';
15
+ import { clearConversation, getCachedUsage } from '../../../providers/provider-router.js';
16
+ import { messageSender } from '../../../telegram/message-sender.js';
17
+ import { EntityText } from '../../../telegram/entities.js';
18
+ import { replyFormatted, editCallbackMessage, replyMarkdown } from '../../../telegram/send.js';
19
+ import { taskListDisplay } from '../../../telegram/task-list.js';
20
+ import { summarizeUserPrompt, unwrapPaste, cutLabel } from '../../../telegram/prompt-label.js';
21
+ import { readRecentExchanges, readLastAssistantTurnText, } from '../../../claude/session-jsonl.js';
22
+ import { getSessionKeyFromCtx, parseSessionKey } from '../../../utils/session-key.js';
23
+ import { isTelegraphEnabled } from '../../../telegram/telegraph-settings.js';
24
+ import { replyMd, parseCallback, projectStatusSuffix, resumeCommandMessage, formatTimeAgo, withBackToPrevious, } from './shared.js';
25
+ import { getSessionTopic, clearTopicAndRefreshBotName, restoreTopicAndRefreshBotName, } from './topic.js';
26
+ import { sendStatusLine } from './settings.js';
27
+ import { ensureProjectDataDir } from '../../../utils/project-data-dir.js';
28
+ export async function handleClear(ctx) {
29
+ const keyInfo = getSessionKeyFromCtx(ctx);
30
+ if (!keyInfo)
31
+ return;
32
+ const { sessionKey } = keyInfo;
33
+ // After a bot restart the in-memory session map is empty; without this
34
+ // pull-from-disk, startNewConversation silently no-ops and the project is
35
+ // dropped, forcing the user to /project again. The default auto-restore
36
+ // age cap doesn't apply here — the user is explicitly invoking /clear, so
37
+ // any restorable project on disk should come back.
38
+ sessionManager.getOrRestoreSession(sessionKey, Number.MAX_SAFE_INTEGER);
39
+ const text = ctx.message?.text || '';
40
+ const arg = text.split(' ').slice(1).join(' ').trim().toLowerCase();
41
+ const skipConfirm = arg === '-y' || arg === '--yes' || arg === 'yes' || arg === 'force';
42
+ if (skipConfirm) {
43
+ clearConversation(sessionKey);
44
+ sessionManager.startNewConversation(sessionKey);
45
+ await clearTopicAndRefreshBotName(ctx, sessionKey);
46
+ const session = sessionManager.getSession(sessionKey);
47
+ const projectName = session ? path.basename(session.workingDirectory) : null;
48
+ const back = withBackToPrevious(clearedMessage(projectName), sessionKey, session?.conversationId);
49
+ await replyFormatted(ctx, back.text, back.options);
50
+ return;
51
+ }
52
+ const session = sessionManager.getSession(sessionKey);
53
+ const projectName = session ? path.basename(session.workingDirectory) : 'current session';
54
+ const confirm = new EntityText()
55
+ .add('⚠️ ').bold('Clear conversation?')
56
+ .add('\n\nThis wipes the conversation history for ').bold(projectName)
57
+ .add('. The project stays selected.\n\n')
58
+ .italic('This cannot be undone.')
59
+ .add('\n\n💡 Tip: ').code('/clear -y').add(' skips this confirmation.')
60
+ .build();
61
+ await replyFormatted(ctx, confirm, {
62
+ reply_markup: {
63
+ inline_keyboard: [
64
+ [
65
+ { text: '✓ Yes, clear it', callback_data: 'clear:confirm' },
66
+ { text: '✗ Cancel', callback_data: 'clear:cancel' },
67
+ ],
68
+ ],
69
+ },
70
+ });
71
+ }
72
+ /** The confirmation once a conversation is cleared, naming the project kept. */
73
+ function clearedMessage(projectName) {
74
+ const msg = new EntityText().add('🔄 Conversation cleared.');
75
+ if (projectName)
76
+ msg.add(' Project ').bold(projectName).add(' is still selected.');
77
+ return msg.build();
78
+ }
79
+ export async function handleClearCallback(ctx) {
80
+ const cb = parseCallback(ctx, 'clear:');
81
+ if (!cb)
82
+ return;
83
+ const { sessionKey, data } = cb;
84
+ const action = data.replace('clear:', '');
85
+ if (action === 'confirm') {
86
+ // Same restore-from-disk guard as handleClear: a bot restart between the
87
+ // confirm prompt and the tap would otherwise drop the project on confirm.
88
+ sessionManager.getOrRestoreSession(sessionKey, Number.MAX_SAFE_INTEGER);
89
+ // Preserve the working directory (project) — only wipe the conversation,
90
+ // matching Claude Code's /clear semantics.
91
+ clearConversation(sessionKey);
92
+ sessionManager.startNewConversation(sessionKey);
93
+ await clearTopicAndRefreshBotName(ctx, sessionKey);
94
+ const session = sessionManager.getSession(sessionKey);
95
+ const projectName = session ? path.basename(session.workingDirectory) : null;
96
+ await ctx.answerCallbackQuery({ text: 'Conversation cleared!' });
97
+ const back = withBackToPrevious(clearedMessage(projectName), sessionKey, session?.conversationId);
98
+ await editCallbackMessage(ctx, back.text, back.options);
99
+ }
100
+ else {
101
+ await ctx.answerCallbackQuery({ text: 'Cancelled' });
102
+ await editCallbackMessage(ctx, '👍 Clear cancelled. Your session is intact.');
103
+ }
104
+ }
105
+ /**
106
+ * Go back to a conversation from this chat's history — what the ↩️ Back
107
+ * button does (`resume:<conversationId>`), and what the history-based /resume
108
+ * picker did before /resume read Claude Code's transcripts (resume.ts).
109
+ */
110
+ export async function resumeHistoryEntry(ctx, sessionKey, conversationId) {
111
+ const session = sessionManager.resumeSession(sessionKey, conversationId);
112
+ if (!session) {
113
+ await ctx.answerCallbackQuery({ text: 'Session not found' });
114
+ return;
115
+ }
116
+ clearConversation(sessionKey);
117
+ const entry = sessionHistory.getSessionByConversationId(sessionKey, conversationId);
118
+ await restoreTopicAndRefreshBotName(ctx, sessionKey, entry?.topic);
119
+ await ctx.answerCallbackQuery({ text: 'Session resumed!' });
120
+ await editCallbackMessage(ctx, sessionRestoredMessage('✅ Resumed session for ', session.workingDirectory, sessionKey));
121
+ // Send session ID as separate message for easy copying
122
+ if (session.claudeSessionId) {
123
+ await replyFormatted(ctx, resumeCommandMessage(session.claudeSessionId));
124
+ }
125
+ await taskListDisplay.showRestored(ctx.api, sessionKey, session.claudeSessionId);
126
+ await sendRecapHint(ctx, sessionKey);
127
+ }
128
+ /** "<lead><project>", the working directory and the project status block. */
129
+ function sessionRestoredMessage(lead, workingDirectory, sessionKey) {
130
+ return new EntityText()
131
+ .add(lead).bold(path.basename(workingDirectory))
132
+ .add('\n\nWorking directory: ').code(workingDirectory)
133
+ .append(projectStatusSuffix(sessionKey))
134
+ .build();
135
+ }
136
+ export async function handleContinue(ctx) {
137
+ const keyInfo = getSessionKeyFromCtx(ctx);
138
+ if (!keyInfo)
139
+ return;
140
+ const { sessionKey } = keyInfo;
141
+ const session = sessionManager.resumeLastSession(sessionKey);
142
+ if (!session) {
143
+ await replyMd(ctx, 'ℹ️ No previous session to continue.\n\nUse `/project <name>` to start a new session.');
144
+ return;
145
+ }
146
+ clearConversation(sessionKey);
147
+ const entry = sessionHistory.getLastSession(sessionKey);
148
+ await restoreTopicAndRefreshBotName(ctx, sessionKey, entry?.topic);
149
+ await replyFormatted(ctx, sessionRestoredMessage('✅ Continuing ', session.workingDirectory, sessionKey));
150
+ // Send session ID as separate message for easy copying
151
+ if (session.claudeSessionId) {
152
+ await replyFormatted(ctx, resumeCommandMessage(session.claudeSessionId));
153
+ }
154
+ await taskListDisplay.showRestored(ctx.api, sessionKey, session.claudeSessionId);
155
+ await sendRecapHint(ctx, sessionKey);
156
+ }
157
+ // Cap for the user-prompt blockquote — long pasted prompts shouldn't dominate
158
+ // the recap. Assistant replies are NOT truncated: they go through the same
159
+ // markdown-to-entities converter and splitter as the original delivery, so
160
+ // their markdown renders (bold, code, lists) instead of showing raw marks.
161
+ const RECAP_USER_MAX_CHARS = 500;
162
+ const RECAP_DEFAULT_N = 3;
163
+ const RECAP_MAX_N = 10;
164
+ function truncateUserPrompt(text, max = RECAP_USER_MAX_CHARS) {
165
+ return cutLabel(summarizeUserPrompt(unwrapPaste(text)).replace(/\s+/g, ' ').trim(), max);
166
+ }
167
+ /**
168
+ * Post the recap as a sequence of messages: a header, then for each exchange
169
+ * the user prompt as a blockquote followed by the assistant reply rendered
170
+ * with its original markdown intact. This mirrors how the assistant text
171
+ * looked on first delivery, instead of cramming everything into one
172
+ * blockquote where `**bold**` / backticks / lists show as raw characters.
173
+ */
174
+ async function sendRecap(ctx, exchanges) {
175
+ await replyFormatted(ctx, new EntityText()
176
+ .add('📋 ').bold('Recap')
177
+ .add(` — last ${exchanges.length} exchange${exchanges.length === 1 ? '' : 's'}`)
178
+ .build());
179
+ for (const ex of exchanges) {
180
+ const userText = truncateUserPrompt(ex.user);
181
+ await replyFormatted(ctx, new EntityText().wrap('blockquote', (b) => b.bold('You:').add(` ${userText}`)).build());
182
+ // replyMarkdown already falls back to plain text when Telegram refuses the
183
+ // formatting; this only keeps one undeliverable reply from ending the
184
+ // whole recap.
185
+ try {
186
+ await replyMarkdown(ctx, ex.assistant);
187
+ }
188
+ catch (error) {
189
+ console.error('[Recap] Failed to send an assistant reply:', error);
190
+ }
191
+ }
192
+ }
193
+ /** Post a one-line tip pointing the user at /recap. Used after explicit restore. */
194
+ export async function sendRecapHint(ctx, sessionKey) {
195
+ const session = sessionManager.getSession(sessionKey);
196
+ if (!session?.claudeSessionId)
197
+ return;
198
+ const exchanges = readRecentExchanges(session.workingDirectory, session.claudeSessionId, 1);
199
+ if (exchanges.length === 0)
200
+ return;
201
+ await replyMd(ctx, '💡 Tip: use `/recap` to see your last messages from this session.');
202
+ }
203
+ export async function handleRecap(ctx) {
204
+ const keyInfo = getSessionKeyFromCtx(ctx);
205
+ if (!keyInfo)
206
+ return;
207
+ const { chatId, sessionKey } = keyInfo;
208
+ const text = ctx.message?.text || '';
209
+ const arg = text.split(' ').slice(1).join(' ').trim();
210
+ let n = RECAP_DEFAULT_N;
211
+ if (arg) {
212
+ const parsed = parseInt(arg, 10);
213
+ if (Number.isNaN(parsed) || parsed < 1) {
214
+ await replyMd(ctx, '⚠️ Usage: `/recap [N]` where N is the number of exchanges (default 3, max 10).');
215
+ return;
216
+ }
217
+ n = Math.min(parsed, RECAP_MAX_N);
218
+ }
219
+ const session = sessionManager.getSession(sessionKey);
220
+ if (!session) {
221
+ await replyMd(ctx, '⚠️ No active session. Use `/continue` or `/resume` first.');
222
+ return;
223
+ }
224
+ if (!session.claudeSessionId) {
225
+ await replyMd(ctx, 'ℹ️ This session has no recorded messages yet.');
226
+ return;
227
+ }
228
+ const exchanges = readRecentExchanges(session.workingDirectory, session.claudeSessionId, n);
229
+ if (exchanges.length === 0) {
230
+ await replyMd(ctx, 'ℹ️ No recoverable exchanges found in this session.');
231
+ return;
232
+ }
233
+ await sendRecap(ctx, exchanges);
234
+ // End the way a turn ends. A long reply leaves the chat on its tail, with the
235
+ // prompt it answers scrolled away, and after a jump to a fork or an earlier
236
+ // point the context is no longer the figure last shown.
237
+ const usage = getCachedUsage(sessionKey);
238
+ await sendStatusLine(ctx, chatId, sessionKey, usage, exchanges[exchanges.length - 1].user);
239
+ }
240
+ /**
241
+ * Dump the current session's conversation to a markdown file and deliver
242
+ * via Telegram (Telegraph link + downloadable file). Useful before switching
243
+ * projects, clearing context, or handing off to a teammate. Captures all
244
+ * exchanges (capped at 200) plus session metadata.
245
+ */
246
+ export async function handleHandoff(ctx) {
247
+ const keyInfo = getSessionKeyFromCtx(ctx);
248
+ if (!keyInfo)
249
+ return;
250
+ const { sessionKey } = keyInfo;
251
+ const session = sessionManager.getSession(sessionKey);
252
+ if (!session) {
253
+ await replyMd(ctx, '⚠️ No active session. Use `/continue` or `/resume` first.');
254
+ return;
255
+ }
256
+ if (!session.claudeSessionId) {
257
+ await replyMd(ctx, 'ℹ️ This session has no recorded messages yet.');
258
+ return;
259
+ }
260
+ const exchanges = readRecentExchanges(session.workingDirectory, session.claudeSessionId, 200);
261
+ if (exchanges.length === 0) {
262
+ await replyMd(ctx, 'ℹ️ No recoverable exchanges in this session.');
263
+ return;
264
+ }
265
+ const projectName = path.basename(session.workingDirectory);
266
+ const topic = getSessionTopic(sessionKey);
267
+ const ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
268
+ const headerLines = [
269
+ `# Session handoff — ${projectName}`,
270
+ '',
271
+ `**Project:** \`${session.workingDirectory}\` `,
272
+ `**Session id:** \`${session.claudeSessionId}\` `,
273
+ `**Conversation id:** \`${session.conversationId}\` `,
274
+ `**Exported:** ${new Date().toLocaleString()} `,
275
+ topic ? `**Topic:** ${topic} ` : '',
276
+ `**Exchanges:** ${exchanges.length}`,
277
+ '',
278
+ `Resume with: \`claude --resume ${session.claudeSessionId}\``,
279
+ '',
280
+ '---',
281
+ '',
282
+ ].filter(Boolean);
283
+ const bodyLines = [];
284
+ exchanges.forEach((ex, i) => {
285
+ bodyLines.push(`## Exchange ${i + 1}`);
286
+ bodyLines.push('');
287
+ bodyLines.push('### User');
288
+ bodyLines.push('');
289
+ bodyLines.push(unwrapPaste(ex.user));
290
+ bodyLines.push('');
291
+ bodyLines.push('### Assistant');
292
+ bodyLines.push('');
293
+ bodyLines.push(ex.assistant.trim());
294
+ bodyLines.push('');
295
+ bodyLines.push('---');
296
+ bodyLines.push('');
297
+ });
298
+ const md = [...headerLines, ...bodyLines].join('\n');
299
+ let outDir;
300
+ try {
301
+ outDir = ensureProjectDataDir(session.workingDirectory, 'handoffs');
302
+ }
303
+ catch (err) {
304
+ await replyFormatted(ctx, `❌ Couldn't create handoff dir: ${err instanceof Error ? err.message : String(err)}`);
305
+ return;
306
+ }
307
+ const filePath = path.join(outDir, `handoff-${ts}.md`);
308
+ try {
309
+ fs.writeFileSync(filePath, md, { mode: 0o600 });
310
+ }
311
+ catch (err) {
312
+ await replyFormatted(ctx, `❌ Couldn't write handoff: ${err instanceof Error ? err.message : String(err)}`);
313
+ return;
314
+ }
315
+ await replyFormatted(ctx, new EntityText()
316
+ .add('📦 ').bold('Handoff written')
317
+ .add(' — ').code(path.relative(session.workingDirectory, filePath))
318
+ .add(`\n${exchanges.length} exchange${exchanges.length === 1 ? '' : 's'} captured.`)
319
+ .build());
320
+ // Telegraph preview + downloadable file (mirrors /telegraph). The page is
321
+ // public, so only when this chat has Telegraph on — otherwise just the file.
322
+ await messageSender.sendMarkdownFile(ctx, filePath, {
323
+ useTelegraph: isTelegraphEnabled(sessionKey),
324
+ sendAsDocument: true,
325
+ });
326
+ }
327
+ /**
328
+ * Manual safety net for the PTY → Telegram translation. Reads the canonical
329
+ * latest assistant turn from Claude Code's session JSONL and posts whatever
330
+ * the user hasn't seen yet. Mirrors the proactive catch-up that runs after
331
+ * each turn (relayCatchUpIfMissed in message.handler.ts); /sync exists for
332
+ * cases where the user suspects a miss outside that automatic window — e.g.
333
+ * a quietly-failed catch-up, or after a bot restart that wiped the relayed
334
+ * tracker.
335
+ */
336
+ export async function handleSync(ctx) {
337
+ const keyInfo = getSessionKeyFromCtx(ctx);
338
+ if (!keyInfo)
339
+ return;
340
+ const { sessionKey } = keyInfo;
341
+ const session = sessionManager.getSession(sessionKey);
342
+ if (!session) {
343
+ await replyMd(ctx, '⚠️ No active session. Use `/continue` or `/resume` first.');
344
+ return;
345
+ }
346
+ if (!session.claudeSessionId) {
347
+ await replyMd(ctx, 'ℹ️ This session has no recorded messages yet.');
348
+ return;
349
+ }
350
+ const jsonlText = readLastAssistantTurnText(session.workingDirectory, session.claudeSessionId);
351
+ if (!jsonlText) {
352
+ await replyMd(ctx, 'ℹ️ No assistant reply found for the current turn.');
353
+ return;
354
+ }
355
+ const relayed = sessionManager.getLastRelayedAssistantText(sessionKey);
356
+ // Same 20-char slack as the proactive check — trim/whitespace deltas don't
357
+ // count as a real miss.
358
+ if (jsonlText.length <= relayed.length + 20) {
359
+ await replyMd(ctx, "✅ You're caught up — nothing new in the session log.");
360
+ return;
361
+ }
362
+ const missing = jsonlText.startsWith(relayed) && relayed.length > 0
363
+ ? jsonlText.slice(relayed.length).trim()
364
+ : jsonlText;
365
+ if (!missing) {
366
+ await replyMd(ctx, "✅ You're caught up — nothing new in the session log.");
367
+ return;
368
+ }
369
+ await replyMd(ctx, '📨 **Sync** — from session log');
370
+ await messageSender.sendMessage(ctx, missing);
371
+ sessionManager.setLastRelayedAssistantText(sessionKey, jsonlText);
372
+ }
373
+ export async function handleSessions(ctx) {
374
+ const keyInfo = getSessionKeyFromCtx(ctx);
375
+ if (!keyInfo)
376
+ return;
377
+ const { sessionKey } = keyInfo;
378
+ const history = sessionManager.getSessionHistory(sessionKey, 10);
379
+ const currentSession = sessionManager.getSession(sessionKey);
380
+ if (history.length === 0 && !currentSession) {
381
+ await replyMd(ctx, 'ℹ️ No sessions found.\n\nUse `/project <name>` to start a new session.');
382
+ return;
383
+ }
384
+ const message = new EntityText().add('📋 ').bold('Sessions').add('\n\n');
385
+ if (currentSession) {
386
+ message
387
+ .bold('Active:')
388
+ .add('\n• ').code(path.basename(currentSession.workingDirectory))
389
+ .add(` (${formatTimeAgo(currentSession.lastActivity)})\n\n`);
390
+ }
391
+ if (history.length > 0) {
392
+ message.bold('Recent:').newline();
393
+ for (const entry of history) {
394
+ const isActive = currentSession && currentSession.conversationId === entry.conversationId;
395
+ const marker = isActive ? '→ ' : '• ';
396
+ const date = new Date(entry.lastActivity);
397
+ message.add(marker).code(entry.projectName).add(` (${formatTimeAgo(date)})`);
398
+ if (entry.topic)
399
+ message.add(' — ').italic(entry.topic);
400
+ message.newline();
401
+ }
402
+ }
403
+ message.newline().wrap('italic', (b) => b
404
+ .add('Use ').code('/resume')
405
+ .add(' to switch sessions or ').code('/continue')
406
+ .add(' to resume the last one.'));
407
+ await replyFormatted(ctx, message.build());
408
+ }
409
+ export async function handleTeleport(ctx) {
410
+ const keyInfo = getSessionKeyFromCtx(ctx);
411
+ if (!keyInfo)
412
+ return;
413
+ const { sessionKey } = keyInfo;
414
+ const { chatId } = parseSessionKey(sessionKey);
415
+ const session = sessionManager.getSession(sessionKey);
416
+ if (!session) {
417
+ await replyMd(ctx, 'ℹ️ No active session to teleport.\n\nStart a conversation first with `/project <name>`.');
418
+ return;
419
+ }
420
+ if (!session.claudeSessionId) {
421
+ await replyMd(ctx, 'ℹ️ No Claude session available yet.\n\nSend a message first to start a session, then use `/teleport`.');
422
+ return;
423
+ }
424
+ const projectName = path.basename(session.workingDirectory);
425
+ const claudeBin = config.CLAUDE_EXECUTABLE_PATH ?? 'claude';
426
+ const command = `cd "${session.workingDirectory}" && ${claudeBin} --resume ${session.claudeSessionId}`;
427
+ const message = new EntityText()
428
+ .add('🚀 ').bold('Teleport to Terminal')
429
+ .add('\n\n').bold('Project:').add(' ').code(projectName)
430
+ .newline().bold('Session:').add(' ').code(`${session.claudeSessionId.substring(0, 8)}...`)
431
+ .add('\n\nCopy and run in your terminal:\n\n')
432
+ .pre(command)
433
+ .add('\n\n')
434
+ .italic('Both Telegram and terminal can continue independently (forked session).')
435
+ .build();
436
+ await replyFormatted(ctx, message);
437
+ }
438
+ //# sourceMappingURL=session.js.map