telecoder 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,216 @@
1
+ import * as fs from 'fs';
2
+ import * as os from 'os';
3
+ import { sessionHistory } from './session-history.js';
4
+ /**
5
+ * How long a chat can go quiet and still be put back in its conversation after
6
+ * a restart — eagerly at startup, or by its next message. Inside it a restart
7
+ * changes nothing; whoever wants a clean slate sends /clear.
8
+ */
9
+ export const RESTORE_MAX_IDLE_MS = 7 * 24 * 60 * 60 * 1000; // 7d
10
+ /**
11
+ * Resolve a stored working directory to a valid path on this system.
12
+ * Handles cross-OS portability (e.g. /Users/x saved on macOS, running on Linux).
13
+ */
14
+ function resolveWorkingDirectory(storedPath) {
15
+ // If it exists, use as-is
16
+ if (fs.existsSync(storedPath))
17
+ return storedPath;
18
+ // Try remapping: replace the stored home prefix with the current $HOME
19
+ // e.g. /Users/player3vsgpt/foo → /home/player3vsgpt/foo
20
+ const home = os.homedir();
21
+ const homePrefixes = ['/Users/', '/home/'];
22
+ for (const prefix of homePrefixes) {
23
+ if (storedPath.startsWith(prefix)) {
24
+ // Extract everything after the username segment
25
+ const rest = storedPath.slice(prefix.length);
26
+ const slashIdx = rest.indexOf('/');
27
+ const remapped = slashIdx === -1 ? home : `${home}${rest.slice(slashIdx)}`;
28
+ if (fs.existsSync(remapped))
29
+ return remapped;
30
+ }
31
+ }
32
+ // Last resort: fall back to $HOME
33
+ return home;
34
+ }
35
+ class SessionManager {
36
+ sessions = new Map();
37
+ // Tracks the last assistant text we successfully relayed to Telegram per
38
+ // sessionKey. Compared against the JSONL's latest assistant turn to detect
39
+ // gaps introduced by extractor edge cases (pure tool-call turns, lossy
40
+ // screen-scrape fallback, early end-of-turn before JSONL flush). In-memory
41
+ // only — after a restart we assume "caught up to nothing" so /resend will
42
+ // surface the most recent turn, which is the safer default.
43
+ lastRelayedAssistantText = new Map();
44
+ getSession(sessionKey) {
45
+ return this.sessions.get(sessionKey);
46
+ }
47
+ getLastRelayedAssistantText(sessionKey) {
48
+ return this.lastRelayedAssistantText.get(sessionKey) ?? '';
49
+ }
50
+ setLastRelayedAssistantText(sessionKey, text) {
51
+ this.lastRelayedAssistantText.set(sessionKey, text);
52
+ }
53
+ createSession(sessionKey, workingDirectory, conversationId) {
54
+ const resolved = resolveWorkingDirectory(workingDirectory);
55
+ const session = {
56
+ conversationId: conversationId || this.generateConversationId(),
57
+ claudeSessionId: undefined,
58
+ workingDirectory: resolved,
59
+ createdAt: new Date(),
60
+ lastActivity: new Date(),
61
+ };
62
+ this.sessions.set(sessionKey, session);
63
+ // Persist to history
64
+ sessionHistory.saveSession(sessionKey, session.conversationId, resolved, '', session.claudeSessionId);
65
+ return session;
66
+ }
67
+ updateActivity(sessionKey, messagePreview) {
68
+ const session = this.sessions.get(sessionKey);
69
+ if (session) {
70
+ session.lastActivity = new Date();
71
+ // Update history with last message preview
72
+ if (messagePreview) {
73
+ sessionHistory.updateLastMessage(sessionKey, session.conversationId, messagePreview);
74
+ }
75
+ }
76
+ }
77
+ updateLastAssistantMessage(sessionKey, preview) {
78
+ const session = this.sessions.get(sessionKey);
79
+ if (session) {
80
+ sessionHistory.updateLastAssistantMessage(sessionKey, session.conversationId, preview);
81
+ }
82
+ }
83
+ clearLastAssistantPreview(sessionKey) {
84
+ const session = this.sessions.get(sessionKey);
85
+ if (session) {
86
+ sessionHistory.clearLastAssistantPreview(sessionKey, session.conversationId);
87
+ }
88
+ }
89
+ setWorkingDirectory(sessionKey, directory) {
90
+ const existing = this.sessions.get(sessionKey);
91
+ if (existing) {
92
+ if (existing.workingDirectory === directory) {
93
+ existing.lastActivity = new Date();
94
+ sessionHistory.saveSession(sessionKey, existing.conversationId, directory, '', existing.claudeSessionId);
95
+ return existing;
96
+ }
97
+ // Different directory: start a new conversation. The Claude Code session
98
+ // is bound to the original cwd, so we mint a fresh conversationId and
99
+ // leave the prior history entry intact for "back to previous project".
100
+ return this.createSession(sessionKey, directory);
101
+ }
102
+ return this.createSession(sessionKey, directory);
103
+ }
104
+ /**
105
+ * The same conversation, now under `directory`: Claude Code's /cd moved the
106
+ * session there (session-move.ts). Unlike setWorkingDirectory, which starts
107
+ * a new conversation in another project, nothing else changes.
108
+ */
109
+ moveSession(sessionKey, directory) {
110
+ const existing = this.sessions.get(sessionKey);
111
+ if (!existing)
112
+ return undefined;
113
+ existing.workingDirectory = directory;
114
+ const entry = sessionHistory.getSessionByConversationId(sessionKey, existing.conversationId);
115
+ sessionHistory.saveSession(sessionKey, existing.conversationId, directory, entry?.lastMessagePreview ?? '', existing.claudeSessionId, existing.ownerProvider, { touch: false });
116
+ return existing;
117
+ }
118
+ clearSession(sessionKey) {
119
+ this.sessions.delete(sessionKey);
120
+ this.lastRelayedAssistantText.delete(sessionKey);
121
+ // Note: We don't clear history here - history is for resuming past sessions
122
+ }
123
+ /**
124
+ * Make a conversation in history the thread's live one again. `touch: false`
125
+ * restores it without counting as use, so its last-activity time stays put:
126
+ * restarts and the restore before a message do that, while going back to a
127
+ * conversation with /resume moves it on.
128
+ */
129
+ resumeSession(sessionKey, conversationId, { touch = true } = {}) {
130
+ const historyEntry = sessionHistory.getSessionByConversationId(sessionKey, conversationId);
131
+ if (!historyEntry) {
132
+ return undefined;
133
+ }
134
+ const resolvedPath = resolveWorkingDirectory(historyEntry.projectPath);
135
+ const session = {
136
+ conversationId: historyEntry.conversationId,
137
+ claudeSessionId: historyEntry.claudeSessionId,
138
+ ownerProvider: historyEntry.ownerProvider,
139
+ workingDirectory: resolvedPath,
140
+ createdAt: new Date(historyEntry.createdAt),
141
+ lastActivity: new Date(),
142
+ };
143
+ this.sessions.set(sessionKey, session);
144
+ // Moves it to the front of the history, with the resolved path.
145
+ sessionHistory.saveSession(sessionKey, conversationId, resolvedPath, historyEntry.lastMessagePreview, historyEntry.claudeSessionId, undefined, { touch });
146
+ return session;
147
+ }
148
+ /** Restore the thread's most recent conversation, without counting that as use. */
149
+ resumeLastSession(sessionKey) {
150
+ const lastEntry = sessionHistory.getLastSession(sessionKey);
151
+ if (!lastEntry) {
152
+ return undefined;
153
+ }
154
+ return this.resumeSession(sessionKey, lastEntry.conversationId, { touch: false });
155
+ }
156
+ /** Return the in-memory session if present; otherwise transparently restore
157
+ * the last session from disk if it's recent enough. Lets handlers recover
158
+ * from unplanned restarts without forcing the user to type /resume. */
159
+ getOrRestoreSession(sessionKey, maxAgeMs = RESTORE_MAX_IDLE_MS) {
160
+ const existing = this.sessions.get(sessionKey);
161
+ if (existing)
162
+ return { session: existing, restored: false };
163
+ const lastEntry = sessionHistory.getLastSession(sessionKey);
164
+ if (!lastEntry)
165
+ return { session: undefined, restored: false };
166
+ const age = Date.now() - new Date(lastEntry.lastActivity).getTime();
167
+ if (age < 0 || age > maxAgeMs)
168
+ return { session: undefined, restored: false };
169
+ const session = this.resumeLastSession(sessionKey);
170
+ return { session, restored: !!session };
171
+ }
172
+ getSessionHistory(sessionKey, limit = 5) {
173
+ return sessionHistory.getHistory(sessionKey, limit);
174
+ }
175
+ setClaudeSessionId(sessionKey, claudeSessionId, ownerProvider) {
176
+ const session = this.sessions.get(sessionKey);
177
+ if (!session)
178
+ return;
179
+ session.claudeSessionId = claudeSessionId;
180
+ // Pin ownership the first time a session id is established. Don't overwrite
181
+ // a known owner on subsequent turns of the same session.
182
+ if (ownerProvider && !session.ownerProvider) {
183
+ session.ownerProvider = ownerProvider;
184
+ }
185
+ session.lastActivity = new Date();
186
+ sessionHistory.updateClaudeSessionId(sessionKey, session.conversationId, claudeSessionId, session.ownerProvider);
187
+ }
188
+ /**
189
+ * Start a fresh conversation in the same project, preserving the prior
190
+ * entry in session history so the user can return to it. Used by /clear,
191
+ * which must actually sever the Claude session — the existing
192
+ * `claudeSessionId` would otherwise be re-used on the next message and the
193
+ * Anthropic-side conversation history would persist server-side.
194
+ */
195
+ startNewConversation(sessionKey) {
196
+ const existing = this.sessions.get(sessionKey);
197
+ if (!existing)
198
+ return undefined;
199
+ const fresh = {
200
+ conversationId: this.generateConversationId(),
201
+ claudeSessionId: undefined,
202
+ workingDirectory: existing.workingDirectory,
203
+ createdAt: new Date(),
204
+ lastActivity: new Date(),
205
+ };
206
+ this.sessions.set(sessionKey, fresh);
207
+ this.lastRelayedAssistantText.delete(sessionKey);
208
+ sessionHistory.saveSession(sessionKey, fresh.conversationId, fresh.workingDirectory, '', undefined);
209
+ return fresh;
210
+ }
211
+ generateConversationId() {
212
+ return `conv_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
213
+ }
214
+ }
215
+ export const sessionManager = new SessionManager();
216
+ //# sourceMappingURL=session-manager.js.map
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Claude Code's /cd, followed: when a chat's session moves to another working
3
+ * directory, the bot moves with it.
4
+ *
5
+ * /cd (Claude Code's own; it reaches the pty like any command the bot doesn't
6
+ * have) keeps the conversation and relocates its transcript to the new
7
+ * directory's project slot under ~/.claude/projects. Left alone, the bot
8
+ * would go on reading the transcript where it was — /branch, /history,
9
+ * /resend, /tree, the background relay — and its next respawn would
10
+ * `claude --resume` in the old directory, where the session no longer is.
11
+ *
12
+ * Claude Code runs the CwdChanged hook with old_cwd and new_cwd. That hook may
13
+ * fire for a working-directory change that moves nothing, so the bot follows
14
+ * only once the transcript is in the new directory's slot, and the move is
15
+ * then what the transcript says, not what the hook does.
16
+ */
17
+ import * as path from 'path';
18
+ import { registerIpcHandler } from './ipc-server.js';
19
+ import { sessionManager } from './session-manager.js';
20
+ import { claudeSessionFileExists } from './session-jsonl.js';
21
+ import { onSessionMoved as moveMonitorWatcher } from './monitor-relay.js';
22
+ import { getSessionTopic, setSessionTopic } from '../bot/handlers/command/topic-store.js';
23
+ const listeners = new Set();
24
+ /** Have `listener` told of every move this module follows. The pty provider keeps its live pty's directory this way. */
25
+ export function onSessionMove(listener) {
26
+ listeners.add(listener);
27
+ }
28
+ /** How long, and how often, to look for the transcript in its new slot after the hook. */
29
+ const LOOK_FOR_MS = 5_000;
30
+ const LOOK_EVERY_MS = 250;
31
+ /**
32
+ * Follow `claudeSessionId` to `newCwd` if it is the chat's session, the move
33
+ * is new, and its transcript is there (now, or within LOOK_FOR_MS: the hook
34
+ * and the relocation aren't ordered). Resolves to whether it followed.
35
+ */
36
+ export async function followSessionMove(sessionKey, claudeSessionId, newCwd, { lookForMs = LOOK_FOR_MS, lookEveryMs = LOOK_EVERY_MS } = {}) {
37
+ const deadline = Date.now() + lookForMs;
38
+ for (;;) {
39
+ const session = sessionManager.getSession(sessionKey);
40
+ if (!session || session.claudeSessionId !== claudeSessionId)
41
+ return false;
42
+ if (session.workingDirectory === newCwd)
43
+ return false;
44
+ if (claudeSessionFileExists(newCwd, claudeSessionId))
45
+ break;
46
+ if (Date.now() >= deadline)
47
+ return false;
48
+ await new Promise((resolve) => setTimeout(resolve, lookEveryMs));
49
+ }
50
+ sessionManager.moveSession(sessionKey, newCwd);
51
+ moveMonitorWatcher(sessionKey, newCwd);
52
+ for (const listener of listeners)
53
+ listener(sessionKey, newCwd);
54
+ // The thread's name carries the project: setting the topic again renames it.
55
+ setSessionTopic(sessionKey, getSessionTopic(sessionKey) ?? '');
56
+ console.log(`[SessionMove] ${sessionKey} followed /cd to ${path.basename(newCwd)}`);
57
+ return true;
58
+ }
59
+ registerIpcHandler('/hook/cwdChanged', (turn, body) => {
60
+ const claudeSessionId = typeof body.session_id === 'string' ? body.session_id : undefined;
61
+ const newCwd = typeof body.new_cwd === 'string' ? body.new_cwd : undefined;
62
+ if (claudeSessionId && newCwd) {
63
+ // Not awaited: the hook only reports, and claude shouldn't wait on the look.
64
+ void followSessionMove(turn.sessionKey, claudeSessionId, newCwd).catch((err) => {
65
+ console.error('[SessionMove] failed:', err instanceof Error ? err.message : err);
66
+ });
67
+ }
68
+ return { ok: true };
69
+ }, { betweenTurns: true });
70
+ //# sourceMappingURL=session-move.js.map
@@ -0,0 +1,270 @@
1
+ /**
2
+ * The conversations Claude Code has on disk, listed the way its own /resume
3
+ * picker lists them — so a session started in a terminal, in another bot or
4
+ * in a PTY this chat no longer remembers can be picked up from Telegram too.
5
+ *
6
+ * Claude Code writes one transcript per session under
7
+ * ~/.claude/projects/<encoded cwd>/<id>.jsonl. Its picker leaves out the ones
8
+ * the SDK wrote (`entrypoint` sdk-ts/sdk-py/sdk-cli) and its daemon sessions;
9
+ * we do the same, except that a TeleCoder chat's own SDK conversations stay
10
+ * in — the caller says which ids those are.
11
+ *
12
+ * Only the head and tail of a transcript are read: the head has the
13
+ * entrypoint, the cwd and the first prompt, the tail the latest title and
14
+ * reply. A transcript only grows, so what was read is cached per file until
15
+ * its size or mtime changes.
16
+ */
17
+ import * as fs from 'fs';
18
+ import * as path from 'path';
19
+ import { extractText, isSyntheticUserRecord, sessionJsonlPath, userTextKind } from './session-jsonl.js';
20
+ /** How much of each end of a transcript to read. Claude Code's own listing reads 64KB too. */
21
+ const CHUNK_BYTES = 64 * 1024;
22
+ const SDK_ENTRYPOINTS = new Set(['sdk-ts', 'sdk-py', 'sdk-cli']);
23
+ const DAEMON_KINDS = new Set(['daemon', 'daemon-worker']);
24
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
25
+ /** ~/.claude/projects, found the way the rest of TeleCoder finds transcripts. */
26
+ function projectsRoot() {
27
+ return path.dirname(path.dirname(sessionJsonlPath('/', 'x')));
28
+ }
29
+ /** Where Claude Code keeps `projectPath`'s transcripts. */
30
+ function dirFor(projectPath) {
31
+ return path.dirname(sessionJsonlPath(projectPath, 'x'));
32
+ }
33
+ export function isSessionId(text) {
34
+ return UUID_RE.test(text);
35
+ }
36
+ // ── Reading one transcript ───────────────────────────────────────────────
37
+ const scanCache = new Map();
38
+ /** Whole lines of `buf`, dropping the partial first (`fromMiddle`) and last ones. */
39
+ function wholeLines(buf, fromMiddle, toEnd) {
40
+ const lines = buf.split('\n');
41
+ if (fromMiddle)
42
+ lines.shift();
43
+ if (!toEnd)
44
+ lines.pop();
45
+ return lines;
46
+ }
47
+ function parse(line) {
48
+ if (!line.trim())
49
+ return undefined;
50
+ try {
51
+ return JSON.parse(line);
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ }
57
+ function readChunk(fd, start, length) {
58
+ const buf = Buffer.alloc(length);
59
+ const read = fs.readSync(fd, buf, 0, length, start);
60
+ return buf.subarray(0, read).toString('utf-8');
61
+ }
62
+ function firstPromptOf(rec) {
63
+ if (rec.type !== 'user' || rec.isSidechain || rec.isMeta || isSyntheticUserRecord(rec))
64
+ return undefined;
65
+ const text = extractText(rec.message?.content).trim();
66
+ return text && userTextKind(text) === 'prompt' ? text : undefined;
67
+ }
68
+ /** Read what the picker needs from one transcript, or null if it isn't a session file. */
69
+ export function scanTranscript(file) {
70
+ let stat;
71
+ try {
72
+ stat = fs.statSync(file);
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ const cached = scanCache.get(file);
78
+ if (cached && cached.size === stat.size && cached.mtimeMs === stat.mtimeMs)
79
+ return cached.scanned;
80
+ const sessionId = path.basename(file, '.jsonl');
81
+ let scanned = null;
82
+ if (isSessionId(sessionId)) {
83
+ let fd;
84
+ try {
85
+ fd = fs.openSync(file, 'r');
86
+ const whole = stat.size <= 2 * CHUNK_BYTES;
87
+ const head = wholeLines(readChunk(fd, 0, whole ? stat.size : CHUNK_BYTES), false, whole);
88
+ const tail = whole ? [] : wholeLines(readChunk(fd, stat.size - CHUNK_BYTES, CHUNK_BYTES), true, true);
89
+ scanned = summarize(sessionId, file, stat.mtimeMs, head, tail);
90
+ }
91
+ catch {
92
+ scanned = null;
93
+ }
94
+ finally {
95
+ if (fd !== undefined)
96
+ fs.closeSync(fd);
97
+ }
98
+ }
99
+ scanCache.set(file, { size: stat.size, mtimeMs: stat.mtimeMs, scanned });
100
+ return scanned;
101
+ }
102
+ function summarize(sessionId, file, mtimeMs, head, tail) {
103
+ const out = { sessionId, file, mtimeMs };
104
+ // Titles and the model are rewritten as the session goes on, so the last
105
+ // one in the file wins: head first, then the tail over it.
106
+ for (const line of [...head, ...tail]) {
107
+ const rec = parse(line);
108
+ if (!rec)
109
+ continue;
110
+ if (out.entrypoint === undefined && typeof rec.entrypoint === 'string')
111
+ out.entrypoint = rec.entrypoint;
112
+ if (out.sessionKind === undefined && typeof rec.sessionKind === 'string')
113
+ out.sessionKind = rec.sessionKind;
114
+ if (out.projectPath === undefined && typeof rec.cwd === 'string')
115
+ out.projectPath = rec.cwd;
116
+ if (rec.type === 'custom-title' && typeof rec.customTitle === 'string' && rec.customTitle.trim()) {
117
+ out.customTitle = rec.customTitle.trim();
118
+ }
119
+ else if (rec.type === 'ai-title' && typeof rec.aiTitle === 'string' && rec.aiTitle.trim()) {
120
+ out.aiTitle = rec.aiTitle.trim();
121
+ }
122
+ else if (rec.type === 'assistant') {
123
+ const model = rec.message?.model;
124
+ if (typeof model === 'string' && model !== '<synthetic>')
125
+ out.lastModel = model;
126
+ }
127
+ else if (out.firstPrompt === undefined) {
128
+ out.firstPrompt = firstPromptOf(rec);
129
+ }
130
+ }
131
+ if (!out.projectPath)
132
+ return null;
133
+ return out;
134
+ }
135
+ // ── Listing ──────────────────────────────────────────────────────────────
136
+ /**
137
+ * Whether the picker offers this session: not an SDK or daemon run unless
138
+ * TeleCoder knows it as one of its chats, and something the user said in it.
139
+ */
140
+ export function isListable(s, knownIds) {
141
+ if (!knownIds.has(s.sessionId)) {
142
+ if (s.entrypoint && SDK_ENTRYPOINTS.has(s.entrypoint))
143
+ return false;
144
+ if (s.sessionKind && DAEMON_KINDS.has(s.sessionKind))
145
+ return false;
146
+ }
147
+ return Boolean(s.customTitle || s.aiTitle || s.firstPrompt);
148
+ }
149
+ function transcriptsIn(dir) {
150
+ let names;
151
+ try {
152
+ names = fs.readdirSync(dir);
153
+ }
154
+ catch {
155
+ return [];
156
+ }
157
+ const out = [];
158
+ for (const name of names) {
159
+ if (!name.endsWith('.jsonl'))
160
+ continue;
161
+ const file = path.join(dir, name);
162
+ try {
163
+ out.push({ file, mtimeMs: fs.statSync(file).mtimeMs });
164
+ }
165
+ catch {
166
+ // Gone between the listing and the stat.
167
+ }
168
+ }
169
+ return out;
170
+ }
171
+ function allTranscriptDirs() {
172
+ try {
173
+ return fs.readdirSync(projectsRoot()).map((name) => path.join(projectsRoot(), name));
174
+ }
175
+ catch {
176
+ return [];
177
+ }
178
+ }
179
+ /**
180
+ * The listable sessions, newest first, from `offset`, at most `limit` of them,
181
+ * and whether there are more after those. Reads transcripts newest-first and
182
+ * stops once the page is full, so a long history costs only what it shows.
183
+ */
184
+ export function listSessions(opts) {
185
+ const dirs = opts.projectPath ? [dirFor(opts.projectPath)] : allTranscriptDirs();
186
+ const candidates = dirs.flatMap(transcriptsIn).sort((a, b) => b.mtimeMs - a.mtimeMs);
187
+ const sessions = [];
188
+ let skipped = 0;
189
+ for (const { file } of candidates) {
190
+ const s = scanTranscript(file);
191
+ if (!s || !isListable(s, opts.knownIds))
192
+ continue;
193
+ if (opts.match && !opts.match(s))
194
+ continue;
195
+ // A transcript of a project in a different directory only shows up in
196
+ // the all-projects list, never as this project's.
197
+ if (opts.projectPath && s.projectPath !== opts.projectPath)
198
+ continue;
199
+ if (skipped < opts.offset) {
200
+ skipped++;
201
+ continue;
202
+ }
203
+ if (sessions.length === opts.limit)
204
+ return { sessions, more: true };
205
+ sessions.push(s);
206
+ }
207
+ return { sessions, more: false };
208
+ }
209
+ /** Find a session's transcript by id: `projectPath`'s first, then every project's. */
210
+ export function findSession(sessionId, projectPath) {
211
+ if (!isSessionId(sessionId))
212
+ return null;
213
+ const dirs = projectPath ? [dirFor(projectPath), ...allTranscriptDirs()] : allTranscriptDirs();
214
+ for (const dir of dirs) {
215
+ const file = path.join(dir, `${sessionId}.jsonl`);
216
+ if (fs.existsSync(file))
217
+ return scanTranscript(file);
218
+ }
219
+ return null;
220
+ }
221
+ /** True if every word of `query` is in the session's titles, its first prompt or `alsoCalled`. */
222
+ export function matchesQuery(s, query, alsoCalled) {
223
+ const hay = [s.customTitle, s.aiTitle, alsoCalled, s.firstPrompt, s.sessionId].filter(Boolean).join('\n').toLowerCase();
224
+ return query.toLowerCase().split(/\s+/).filter(Boolean).every((word) => hay.includes(word));
225
+ }
226
+ // ── Open elsewhere ───────────────────────────────────────────────────────
227
+ function processAlive(pid) {
228
+ try {
229
+ process.kill(pid, 0);
230
+ return true;
231
+ }
232
+ catch (err) {
233
+ // EPERM: alive, just not ours to signal.
234
+ return err.code === 'EPERM';
235
+ }
236
+ }
237
+ /**
238
+ * Whether a running Claude Code process has `sessionId` open. Every claude
239
+ * process — a terminal, a PTY of any TeleCoder bot, an SDK turn in flight —
240
+ * registers itself in ~/.claude/sessions/<pid>.json with the session it is
241
+ * on; this is the registry Claude Code itself checks before resuming one.
242
+ */
243
+ export function isSessionOpenElsewhere(sessionId) {
244
+ const dir = path.join(path.dirname(projectsRoot()), 'sessions');
245
+ let names;
246
+ try {
247
+ names = fs.readdirSync(dir);
248
+ }
249
+ catch {
250
+ return false;
251
+ }
252
+ const wanted = sessionId.toLowerCase();
253
+ for (const name of names) {
254
+ if (!name.endsWith('.json'))
255
+ continue;
256
+ let entry;
257
+ try {
258
+ entry = JSON.parse(fs.readFileSync(path.join(dir, name), 'utf-8'));
259
+ }
260
+ catch {
261
+ continue;
262
+ }
263
+ if (typeof entry.sessionId !== 'string' || entry.sessionId.toLowerCase() !== wanted)
264
+ continue;
265
+ if (typeof entry.pid === 'number' && entry.pid !== process.pid && processAlive(entry.pid))
266
+ return true;
267
+ }
268
+ return false;
269
+ }
270
+ //# sourceMappingURL=session-scan.js.map