telecoder 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.env.example +142 -130
  2. package/CHANGELOG.md +683 -2
  3. package/README.md +36 -32
  4. package/dist/audio/transcribe.js +0 -9
  5. package/dist/bin/mcp-server.js +46 -61
  6. package/dist/bot/bot.js +162 -181
  7. package/dist/bot/command-catalog.js +263 -0
  8. package/dist/bot/deleted-threads.js +103 -0
  9. package/dist/bot/file-access.js +35 -26
  10. package/dist/bot/handlers/album.handler.js +128 -0
  11. package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
  12. package/dist/bot/handlers/command/access.js +1 -1
  13. package/dist/bot/handlers/command/admin.js +86 -110
  14. package/dist/bot/handlers/command/all-view.js +33 -0
  15. package/dist/bot/handlers/command/auto-approve.js +3 -3
  16. package/dist/bot/handlers/command/background.js +37 -0
  17. package/dist/bot/handlers/command/botname.js +76 -0
  18. package/dist/bot/handlers/command/btw.js +20 -69
  19. package/dist/bot/handlers/command/cleanup.js +329 -0
  20. package/dist/bot/handlers/command/model.js +40 -119
  21. package/dist/bot/handlers/command/prefs-scope.js +255 -90
  22. package/dist/bot/handlers/command/project.js +31 -109
  23. package/dist/bot/handlers/command/resume.js +8 -4
  24. package/dist/bot/handlers/command/session.js +74 -213
  25. package/dist/bot/handlers/command/settings.js +92 -447
  26. package/dist/bot/handlers/command/shared.js +32 -35
  27. package/dist/bot/handlers/command/tasks.js +263 -95
  28. package/dist/bot/handlers/command/thread.js +128 -0
  29. package/dist/bot/handlers/command/topic-store.js +14 -53
  30. package/dist/bot/handlers/command/topic.js +8 -61
  31. package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
  32. package/dist/bot/handlers/command-fallback.js +179 -0
  33. package/dist/bot/handlers/command.handler.js +96 -422
  34. package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
  35. package/dist/bot/handlers/media-fallback.js +12 -7
  36. package/dist/bot/handlers/message/replies.js +10 -87
  37. package/dist/bot/handlers/message/shared.js +9 -31
  38. package/dist/bot/handlers/message/turn-notify.js +15 -49
  39. package/dist/bot/handlers/message/turn-runner.js +18 -103
  40. package/dist/bot/handlers/message.handler.js +59 -52
  41. package/dist/bot/handlers/newbot.handler.js +13 -4
  42. package/dist/bot/handlers/photo.handler.js +88 -129
  43. package/dist/bot/handlers/prompts.handler.js +11 -11
  44. package/dist/bot/handlers/running-note.js +2 -2
  45. package/dist/bot/handlers/session-guard.js +4 -4
  46. package/dist/bot/handlers/suggestion.handler.js +2 -2
  47. package/dist/bot/handlers/tree.handler.js +20 -20
  48. package/dist/bot/handlers/voice.handler.js +23 -85
  49. package/dist/bot/kept-threads.js +51 -0
  50. package/dist/bot/middleware/album-collector.js +69 -0
  51. package/dist/bot/middleware/auth.middleware.js +1 -1
  52. package/dist/bot/middleware/group-mention.middleware.js +11 -5
  53. package/dist/bot/middleware/queued-messages.js +143 -32
  54. package/dist/bot/middleware/stale-filter.js +0 -22
  55. package/dist/build-info.json +5 -5
  56. package/dist/claude/ask-user-form.js +517 -0
  57. package/dist/claude/ask-user.js +94 -26
  58. package/dist/claude/auto-topic-haiku.js +17 -0
  59. package/dist/claude/available-commands.js +22 -19
  60. package/dist/claude/background-hint.js +91 -0
  61. package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
  62. package/dist/claude/carry-over.js +0 -2
  63. package/dist/claude/ccr-shim.js +12 -10
  64. package/dist/claude/claude-auth.js +6 -10
  65. package/dist/claude/command-parser.js +49 -43
  66. package/dist/claude/cost-overlay-scraper.js +7 -2
  67. package/dist/claude/effort-level.js +5 -0
  68. package/dist/claude/enabled-plugins.js +12 -16
  69. package/dist/claude/in-flight-tracker.js +21 -0
  70. package/dist/claude/mcp-bridge.js +86 -58
  71. package/dist/claude/memory-guard.js +400 -0
  72. package/dist/claude/message-offsets.js +5 -5
  73. package/dist/claude/modal-relay.js +401 -34
  74. package/dist/claude/model-catalog.js +20 -3
  75. package/dist/claude/monitor-relay.js +130 -15
  76. package/dist/claude/native-commands.js +40 -0
  77. package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
  78. package/dist/claude/permission-gate.js +11 -10
  79. package/dist/claude/permission-mode.js +19 -45
  80. package/dist/claude/prewarm.js +70 -0
  81. package/dist/claude/pty-idle-reaper.js +96 -0
  82. package/dist/claude/pty-provider.js +473 -188
  83. package/dist/claude/pty-spawn-config.js +79 -32
  84. package/dist/claude/pty-watch.js +201 -0
  85. package/dist/claude/request-queue.js +7 -35
  86. package/dist/claude/rewind.js +111 -0
  87. package/dist/claude/scheduled-runner.js +1 -3
  88. package/dist/claude/scheduler.js +6 -2
  89. package/dist/claude/scope-guard.js +8 -3
  90. package/dist/claude/screen-marks.js +83 -0
  91. package/dist/claude/screen-render.js +96 -0
  92. package/dist/claude/session-history.js +4 -2
  93. package/dist/claude/session-jsonl.js +162 -15
  94. package/dist/claude/session-manager.js +29 -8
  95. package/dist/claude/session-move.js +70 -0
  96. package/dist/claude/shell-mode-gate.js +60 -0
  97. package/dist/claude/side-question.js +20 -17
  98. package/dist/claude/stage-images.js +5 -5
  99. package/dist/claude/tasks-overlay-scraper.js +143 -20
  100. package/dist/claude/thread-judge-haiku.js +88 -0
  101. package/dist/claude/tip-scraper.js +3 -4
  102. package/dist/claude/tui-modal.js +272 -27
  103. package/dist/claude/tui-state.js +74 -2
  104. package/dist/claude/turn-end.js +15 -1
  105. package/dist/claude/turn-prose.js +1 -1
  106. package/dist/claude/typed-answer.js +104 -0
  107. package/dist/claude/update-banner-relay.js +1 -1
  108. package/dist/cli/commands/doctor.js +48 -15
  109. package/dist/cli/commands/help.js +11 -2
  110. package/dist/cli/commands/init.js +16 -13
  111. package/dist/cli/commands/service.js +40 -8
  112. package/dist/cli/commands/start.js +10 -0
  113. package/dist/cli/commands/watch.js +322 -0
  114. package/dist/cli/dispatch.js +5 -0
  115. package/dist/cli/init/env-file.js +1 -1
  116. package/dist/cli/init/flow.js +114 -47
  117. package/dist/cli/init/prompter.js +8 -0
  118. package/dist/cli/init/telegram.js +35 -9
  119. package/dist/cli/service/render.js +3 -3
  120. package/dist/config.js +156 -131
  121. package/dist/index.js +107 -31
  122. package/dist/launcher.js +34 -7
  123. package/dist/providers/ccr-introspect.js +1 -8
  124. package/dist/providers/ccr-provider.js +19 -20
  125. package/dist/providers/claude-provider.js +4 -57
  126. package/dist/providers/prefs-sync.js +16 -59
  127. package/dist/providers/provider-router.js +24 -23
  128. package/dist/providers/spawn-settings.js +45 -0
  129. package/dist/providers/user-preferences.js +127 -19
  130. package/dist/restart-when-idle.js +27 -7
  131. package/dist/startup/auto-continue.js +2 -2
  132. package/dist/startup/auto-resume.js +3 -15
  133. package/dist/startup/notices.js +1 -1
  134. package/dist/startup/verify-token.js +4 -4
  135. package/dist/telegram/action-logger.js +3 -165
  136. package/dist/telegram/background-activity-card.js +1 -1
  137. package/dist/telegram/botname-settings.js +71 -125
  138. package/dist/telegram/client-options.js +6 -7
  139. package/dist/telegram/force-reply-tracker.js +55 -16
  140. package/dist/telegram/message-sender.js +92 -360
  141. package/dist/telegram/prompt-label.js +11 -5
  142. package/dist/telegram/streaming-turn.js +5 -7
  143. package/dist/telegram/table-lists.js +56 -0
  144. package/dist/telegram/task-list.js +4 -4
  145. package/dist/telegram/task-tracker.js +45 -126
  146. package/dist/telegram/terminal-renderer.js +1 -5
  147. package/dist/telegram/thread-titles.js +74 -2
  148. package/dist/telegram/threads-setup.js +1 -1
  149. package/dist/utils/admins.js +2 -2
  150. package/dist/utils/bot-icon.js +248 -0
  151. package/dist/utils/bot-token.js +8 -5
  152. package/dist/utils/build-info.js +3 -3
  153. package/dist/utils/caffeinate.js +6 -3
  154. package/dist/utils/claude-env.js +0 -1
  155. package/dist/utils/claude-version.js +2 -2
  156. package/dist/utils/config-home.js +3 -3
  157. package/dist/utils/download.js +41 -15
  158. package/dist/utils/exit-codes.js +11 -0
  159. package/dist/utils/format.js +3 -6
  160. package/dist/utils/home-project.js +1 -1
  161. package/dist/utils/idle-restart.js +1 -1
  162. package/dist/utils/install-mode.js +1 -1
  163. package/dist/utils/instance-config.js +1 -1
  164. package/dist/utils/instances.js +1 -1
  165. package/dist/utils/keyed-settings.js +2 -2
  166. package/dist/utils/memory-pressure.js +60 -0
  167. package/dist/utils/npm-version.js +2 -2
  168. package/dist/utils/resolve-claude-bin.js +13 -24
  169. package/dist/utils/respawn-backoff.js +9 -0
  170. package/dist/utils/stale-launcher.js +1 -1
  171. package/dist/utils/systemd.js +8 -8
  172. package/dist/utils/telegram-proxy.js +72 -0
  173. package/dist/utils/uploads-dir.js +27 -0
  174. package/dist/utils/verbosity.js +8 -8
  175. package/dist/utils/version-check.js +5 -5
  176. package/package.json +3 -4
  177. package/dist/bot/handlers/command/media.js +0 -197
  178. package/dist/bot/handlers/command/streaming-mode.js +0 -16
  179. package/dist/bot/handlers/message/throttle.js +0 -49
  180. package/dist/claude/agent-watchdog.js +0 -162
  181. package/dist/claude/agent.js +0 -1458
  182. package/dist/claude/held-query.js +0 -190
  183. package/dist/claude/mcp-tools.js +0 -354
  184. package/dist/claude/sdk-permission-gate.js +0 -77
  185. package/dist/claude/session-cost.js +0 -41
  186. package/dist/claude/system-prompt.js +0 -162
  187. package/dist/providers/sdk-provider.js +0 -37
  188. package/dist/telegram/telegraph-settings.js +0 -31
  189. package/dist/telegram/telegraph.js +0 -453
  190. package/dist/telegram/terminal-settings.js +0 -25
  191. package/dist/tts/tts-settings.js +0 -62
  192. package/dist/tts/tts.js +0 -245
  193. package/dist/tts/voice-reply.js +0 -78
  194. package/dist/utils/debug-agent.js +0 -117
  195. package/dist/utils/debug-watchdog.js +0 -121
  196. package/dist/utils/project-data-dir.js +0 -33
  197. package/dist/utils/reasoning-summary.js +0 -12
@@ -1,30 +1,38 @@
1
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.
2
+ * Session lifecycle: /clear, /history, /resend and /terminal, and the
3
+ * ▶️ Continue button under a restart notice. /prompts, which branches as well
4
+ * as lists, lives beside /tree in prompts.handler.ts.
5
5
  *
6
6
  * All of these move a chat between conversations — starting a fresh one,
7
7
  * picking an older one back up, or summarising what a previous one did — so
8
8
  * they share the session history, the JSONL reader and the topic restore.
9
9
  */
10
- import * as fs from 'fs';
11
10
  import * as path from 'path';
12
11
  import { config } from '../../../config.js';
13
12
  import { sessionManager } from '../../../claude/session-manager.js';
14
13
  import { sessionHistory } from '../../../claude/session-history.js';
15
14
  import { clearConversation, getCachedUsage } from '../../../providers/provider-router.js';
15
+ import { prewarmClaude } from '../../../claude/prewarm.js';
16
16
  import { messageSender } from '../../../telegram/message-sender.js';
17
17
  import { EntityText } from '../../../telegram/entities.js';
18
18
  import { replyFormatted, editCallbackMessage, replyMarkdown } from '../../../telegram/send.js';
19
19
  import { taskListDisplay } from '../../../telegram/task-list.js';
20
20
  import { summarizeUserPrompt, unwrapPaste, cutLabel } from '../../../telegram/prompt-label.js';
21
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';
22
+ import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
23
+ import { replyMd, projectStatusSuffix, resumeCommandMessage, withBackToPrevious, } from './shared.js';
24
+ import { clearTopic, restoreTopic, setSessionTopic, } from './topic.js';
26
25
  import { sendStatusLine } from './settings.js';
27
- import { ensureProjectDataDir } from '../../../utils/project-data-dir.js';
26
+ /** What `-y` and its spellings were for: skipping a confirmation /clear no longer asks. */
27
+ const OLD_SKIP_FLAGS = new Set(['-y', '--yes', 'yes', 'force']);
28
+ /**
29
+ * /clear [name] (and /reset, /new, Claude Code's names for it): a new
30
+ * conversation in the same project, at once, as in Claude Code. Nothing is
31
+ * lost: the previous conversation stays on disk, behind the ↩️ Back button and
32
+ * in /resume. A name starts the new one under that topic, which names the
33
+ * thread as /topic does; Claude Code's `/clear <name>` titles the new session
34
+ * the same way. `-y` from when /clear asked first is accepted and ignored.
35
+ */
28
36
  export async function handleClear(ctx) {
29
37
  const keyInfo = getSessionKeyFromCtx(ctx);
30
38
  if (!keyInfo)
@@ -32,76 +40,37 @@ export async function handleClear(ctx) {
32
40
  const { sessionKey } = keyInfo;
33
41
  // After a bot restart the in-memory session map is empty; without this
34
42
  // pull-from-disk, startNewConversation silently no-ops and the project is
35
- // dropped, forcing the user to /project again. The default auto-restore
43
+ // dropped, forcing the user to /dir again. The default auto-restore
36
44
  // age cap doesn't apply here — the user is explicitly invoking /clear, so
37
45
  // any restorable project on disk should come back.
38
46
  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
- }
47
+ const arg = (ctx.message?.text ?? '').replace(/^\/\S*\s*/, '').trim();
48
+ const name = OLD_SKIP_FLAGS.has(arg.toLowerCase()) ? '' : arg;
49
+ // Preserve the working directory (project) — only the conversation is new,
50
+ // matching Claude Code's /clear.
51
+ clearConversation(sessionKey);
52
+ sessionManager.startNewConversation(sessionKey);
53
+ if (name)
54
+ setSessionTopic(sessionKey, name);
55
+ else
56
+ clearTopic(sessionKey);
52
57
  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
- });
58
+ const projectName = session ? path.basename(session.workingDirectory) : null;
59
+ const back = withBackToPrevious(clearedMessage(projectName, name), sessionKey, session?.conversationId);
60
+ await replyFormatted(ctx, back.text, back.options);
61
+ void prewarmClaude(ctx, sessionKey);
71
62
  }
72
- /** The confirmation once a conversation is cleared, naming the project kept. */
73
- function clearedMessage(projectName) {
74
- const msg = new EntityText().add('🔄 Conversation cleared.');
63
+ /** The note once a conversation is cleared: the project kept, the topic given, where the old one went. */
64
+ function clearedMessage(projectName, name = '') {
65
+ const msg = new EntityText().add('🔄 New conversation');
66
+ if (name)
67
+ msg.add(': ').bold(name);
68
+ msg.add('.');
75
69
  if (projectName)
76
70
  msg.add(' Project ').bold(projectName).add(' is still selected.');
71
+ msg.add(' The previous conversation stays in /resume.');
77
72
  return msg.build();
78
73
  }
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
74
  /**
106
75
  * Go back to a conversation from this chat's history — what the ↩️ Back
107
76
  * button does (`resume:<conversationId>`), and what the history-based /resume
@@ -115,7 +84,7 @@ export async function resumeHistoryEntry(ctx, sessionKey, conversationId) {
115
84
  }
116
85
  clearConversation(sessionKey);
117
86
  const entry = sessionHistory.getSessionByConversationId(sessionKey, conversationId);
118
- await restoreTopicAndRefreshBotName(ctx, sessionKey, entry?.topic);
87
+ restoreTopic(sessionKey, entry?.topic);
119
88
  await ctx.answerCallbackQuery({ text: 'Session resumed!' });
120
89
  await editCallbackMessage(ctx, sessionRestoredMessage('✅ Resumed session for ', session.workingDirectory, sessionKey));
121
90
  // Send session ID as separate message for easy copying
@@ -124,6 +93,7 @@ export async function resumeHistoryEntry(ctx, sessionKey, conversationId) {
124
93
  }
125
94
  await taskListDisplay.showRestored(ctx.api, sessionKey, session.claudeSessionId);
126
95
  await sendRecapHint(ctx, sessionKey);
96
+ void prewarmClaude(ctx, sessionKey);
127
97
  }
128
98
  /** "<lead><project>", the working directory and the project status block. */
129
99
  function sessionRestoredMessage(lead, workingDirectory, sessionKey) {
@@ -133,19 +103,24 @@ function sessionRestoredMessage(lead, workingDirectory, sessionKey) {
133
103
  .append(projectStatusSuffix(sessionKey))
134
104
  .build();
135
105
  }
136
- export async function handleContinue(ctx) {
106
+ /**
107
+ * Pick the chat's most recent session back up: what the ▶️ Continue button
108
+ * under a restart notice does. Startup continues a chat by itself these days
109
+ * (startup/auto-continue.ts); this is the manual path for one it left alone.
110
+ */
111
+ export async function continueLastSession(ctx) {
137
112
  const keyInfo = getSessionKeyFromCtx(ctx);
138
113
  if (!keyInfo)
139
114
  return;
140
115
  const { sessionKey } = keyInfo;
141
116
  const session = sessionManager.resumeLastSession(sessionKey);
142
117
  if (!session) {
143
- await replyMd(ctx, 'ℹ️ No previous session to continue.\n\nUse `/project <name>` to start a new session.');
118
+ await replyMd(ctx, 'ℹ️ No previous session to continue.\n\nUse `/resume` to pick one, or `/dir <name>` to start a new session.');
144
119
  return;
145
120
  }
146
121
  clearConversation(sessionKey);
147
122
  const entry = sessionHistory.getLastSession(sessionKey);
148
- await restoreTopicAndRefreshBotName(ctx, sessionKey, entry?.topic);
123
+ restoreTopic(sessionKey, entry?.topic);
149
124
  await replyFormatted(ctx, sessionRestoredMessage('✅ Continuing ', session.workingDirectory, sessionKey));
150
125
  // Send session ID as separate message for easy copying
151
126
  if (session.claudeSessionId) {
@@ -153,6 +128,7 @@ export async function handleContinue(ctx) {
153
128
  }
154
129
  await taskListDisplay.showRestored(ctx.api, sessionKey, session.claudeSessionId);
155
130
  await sendRecapHint(ctx, sessionKey);
131
+ void prewarmClaude(ctx, sessionKey);
156
132
  }
157
133
  // Cap for the user-prompt blockquote — long pasted prompts shouldn't dominate
158
134
  // the recap. Assistant replies are NOT truncated: they go through the same
@@ -190,7 +166,7 @@ async function sendRecap(ctx, exchanges) {
190
166
  }
191
167
  }
192
168
  }
193
- /** Post a one-line tip pointing the user at /recap. Used after explicit restore. */
169
+ /** Post a one-line tip pointing the user at /history. Used after explicit restore. */
194
170
  export async function sendRecapHint(ctx, sessionKey) {
195
171
  const session = sessionManager.getSession(sessionKey);
196
172
  if (!session?.claudeSessionId)
@@ -198,9 +174,9 @@ export async function sendRecapHint(ctx, sessionKey) {
198
174
  const exchanges = readRecentExchanges(session.workingDirectory, session.claudeSessionId, 1);
199
175
  if (exchanges.length === 0)
200
176
  return;
201
- await replyMd(ctx, '💡 Tip: use `/recap` to see your last messages from this session.');
177
+ await replyMd(ctx, '💡 Tip: use `/history` to see your last messages from this session.');
202
178
  }
203
- export async function handleRecap(ctx) {
179
+ export async function handleHistory(ctx) {
204
180
  const keyInfo = getSessionKeyFromCtx(ctx);
205
181
  if (!keyInfo)
206
182
  return;
@@ -211,14 +187,14 @@ export async function handleRecap(ctx) {
211
187
  if (arg) {
212
188
  const parsed = parseInt(arg, 10);
213
189
  if (Number.isNaN(parsed) || parsed < 1) {
214
- await replyMd(ctx, '⚠️ Usage: `/recap [N]` where N is the number of exchanges (default 3, max 10).');
190
+ await replyMd(ctx, '⚠️ Usage: `/history [N]` where N is the number of exchanges (default 3, max 10).');
215
191
  return;
216
192
  }
217
193
  n = Math.min(parsed, RECAP_MAX_N);
218
194
  }
219
195
  const session = sessionManager.getSession(sessionKey);
220
196
  if (!session) {
221
- await replyMd(ctx, '⚠️ No active session. Use `/continue` or `/resume` first.');
197
+ await replyMd(ctx, '⚠️ No active session. Use `/resume` first.');
222
198
  return;
223
199
  }
224
200
  if (!session.claudeSessionId) {
@@ -232,115 +208,28 @@ export async function handleRecap(ctx) {
232
208
  }
233
209
  await sendRecap(ctx, exchanges);
234
210
  // 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
211
+ // prompt it answers scrolled away, and after a jump to a branch or an earlier
236
212
  // point the context is no longer the figure last shown.
237
213
  const usage = getCachedUsage(sessionKey);
238
214
  await sendStatusLine(ctx, chatId, sessionKey, usage, exchanges[exchanges.length - 1].user);
239
215
  }
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
216
  /**
328
217
  * Manual safety net for the PTY → Telegram translation. Reads the canonical
329
218
  * latest assistant turn from Claude Code's session JSONL and posts whatever
330
219
  * 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
220
+ * each turn (relayCatchUpIfMissed in message.handler.ts); /resend exists for
332
221
  * cases where the user suspects a miss outside that automatic window — e.g.
333
222
  * a quietly-failed catch-up, or after a bot restart that wiped the relayed
334
223
  * tracker.
335
224
  */
336
- export async function handleSync(ctx) {
225
+ export async function handleResend(ctx) {
337
226
  const keyInfo = getSessionKeyFromCtx(ctx);
338
227
  if (!keyInfo)
339
228
  return;
340
229
  const { sessionKey } = keyInfo;
341
230
  const session = sessionManager.getSession(sessionKey);
342
231
  if (!session) {
343
- await replyMd(ctx, '⚠️ No active session. Use `/continue` or `/resume` first.');
232
+ await replyMd(ctx, '⚠️ No active session. Use `/resume` first.');
344
233
  return;
345
234
  }
346
235
  if (!session.claudeSessionId) {
@@ -370,68 +259,40 @@ export async function handleSync(ctx) {
370
259
  await messageSender.sendMessage(ctx, missing);
371
260
  sessionManager.setLastRelayedAssistantText(sessionKey, jsonlText);
372
261
  }
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) {
262
+ /**
263
+ * /terminal: the command line that carries this session on in a terminal, as
264
+ * a fork. It was /teleport until Claude Code had a /teleport of its own (send
265
+ * a session to the cloud, or resume one from claude.ai), which the bot's
266
+ * command of that name kept anyone from reaching.
267
+ */
268
+ export async function handleTerminal(ctx) {
410
269
  const keyInfo = getSessionKeyFromCtx(ctx);
411
270
  if (!keyInfo)
412
271
  return;
413
272
  const { sessionKey } = keyInfo;
414
- const { chatId } = parseSessionKey(sessionKey);
415
273
  const session = sessionManager.getSession(sessionKey);
416
274
  if (!session) {
417
- await replyMd(ctx, 'ℹ️ No active session to teleport.\n\nStart a conversation first with `/project <name>`.');
275
+ await replyMd(ctx, 'ℹ️ No active session to continue in a terminal.\n\nStart a conversation first with `/dir <name>`.');
418
276
  return;
419
277
  }
420
278
  if (!session.claudeSessionId) {
421
- await replyMd(ctx, 'ℹ️ No Claude session available yet.\n\nSend a message first to start a session, then use `/teleport`.');
279
+ await replyMd(ctx, 'ℹ️ No Claude session available yet.\n\nSend a message first to start a session, then use `/terminal`.');
422
280
  return;
423
281
  }
424
282
  const projectName = path.basename(session.workingDirectory);
425
283
  const claudeBin = config.CLAUDE_EXECUTABLE_PATH ?? 'claude';
426
- const command = `cd "${session.workingDirectory}" && ${claudeBin} --resume ${session.claudeSessionId}`;
284
+ // --fork-session: the chat's own claude still has this session open, and a
285
+ // plain --resume would have two processes appending to one log. The fork
286
+ // starts with the whole conversation under an id of its own.
287
+ const command = `cd "${session.workingDirectory}" && ${claudeBin} --resume ${session.claudeSessionId} --fork-session`;
427
288
  const message = new EntityText()
428
- .add('🚀 ').bold('Teleport to Terminal')
289
+ .add('💻 ').bold('Continue in a terminal')
429
290
  .add('\n\n').bold('Project:').add(' ').code(projectName)
430
291
  .newline().bold('Session:').add(' ').code(`${session.claudeSessionId.substring(0, 8)}...`)
431
292
  .add('\n\nCopy and run in your terminal:\n\n')
432
293
  .pre(command)
433
294
  .add('\n\n')
434
- .italic('Both Telegram and terminal can continue independently (forked session).')
295
+ .italic('The terminal gets a copy of the conversation as a new session, so this chat and the terminal can each carry on.')
435
296
  .build();
436
297
  await replyFormatted(ctx, message);
437
298
  }