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,195 @@
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 /sync 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 Agent SDK 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
+ clearSession(sessionKey) {
105
+ this.sessions.delete(sessionKey);
106
+ this.lastRelayedAssistantText.delete(sessionKey);
107
+ // Note: We don't clear history here - history is for resuming past sessions
108
+ }
109
+ resumeSession(sessionKey, conversationId) {
110
+ const historyEntry = sessionHistory.getSessionByConversationId(sessionKey, conversationId);
111
+ if (!historyEntry) {
112
+ return undefined;
113
+ }
114
+ const resolvedPath = resolveWorkingDirectory(historyEntry.projectPath);
115
+ const session = {
116
+ conversationId: historyEntry.conversationId,
117
+ claudeSessionId: historyEntry.claudeSessionId,
118
+ ownerProvider: historyEntry.ownerProvider,
119
+ workingDirectory: resolvedPath,
120
+ createdAt: new Date(historyEntry.createdAt),
121
+ lastActivity: new Date(),
122
+ };
123
+ this.sessions.set(sessionKey, session);
124
+ // Update history activity (with resolved path)
125
+ sessionHistory.saveSession(sessionKey, conversationId, resolvedPath, historyEntry.lastMessagePreview, historyEntry.claudeSessionId);
126
+ return session;
127
+ }
128
+ resumeLastSession(sessionKey) {
129
+ const lastEntry = sessionHistory.getLastSession(sessionKey);
130
+ if (!lastEntry) {
131
+ return undefined;
132
+ }
133
+ return this.resumeSession(sessionKey, lastEntry.conversationId);
134
+ }
135
+ /** Return the in-memory session if present; otherwise transparently restore
136
+ * the last session from disk if it's recent enough. Lets handlers recover
137
+ * from unplanned restarts without forcing the user to type /continue. */
138
+ getOrRestoreSession(sessionKey, maxAgeMs = RESTORE_MAX_IDLE_MS) {
139
+ const existing = this.sessions.get(sessionKey);
140
+ if (existing)
141
+ return { session: existing, restored: false };
142
+ const lastEntry = sessionHistory.getLastSession(sessionKey);
143
+ if (!lastEntry)
144
+ return { session: undefined, restored: false };
145
+ const age = Date.now() - new Date(lastEntry.lastActivity).getTime();
146
+ if (age < 0 || age > maxAgeMs)
147
+ return { session: undefined, restored: false };
148
+ const session = this.resumeLastSession(sessionKey);
149
+ return { session, restored: !!session };
150
+ }
151
+ getSessionHistory(sessionKey, limit = 5) {
152
+ return sessionHistory.getHistory(sessionKey, limit);
153
+ }
154
+ setClaudeSessionId(sessionKey, claudeSessionId, ownerProvider) {
155
+ const session = this.sessions.get(sessionKey);
156
+ if (!session)
157
+ return;
158
+ session.claudeSessionId = claudeSessionId;
159
+ // Pin ownership the first time a session id is established. Don't overwrite
160
+ // a known owner on subsequent turns of the same session.
161
+ if (ownerProvider && !session.ownerProvider) {
162
+ session.ownerProvider = ownerProvider;
163
+ }
164
+ session.lastActivity = new Date();
165
+ sessionHistory.updateClaudeSessionId(sessionKey, session.conversationId, claudeSessionId, session.ownerProvider);
166
+ }
167
+ /**
168
+ * Start a fresh conversation in the same project, preserving the prior
169
+ * entry in session history so the user can return to it. Used by /clear,
170
+ * which must actually sever the SDK session — the existing
171
+ * `claudeSessionId` would otherwise be re-used on the next message and the
172
+ * Anthropic-side conversation history would persist server-side.
173
+ */
174
+ startNewConversation(sessionKey) {
175
+ const existing = this.sessions.get(sessionKey);
176
+ if (!existing)
177
+ return undefined;
178
+ const fresh = {
179
+ conversationId: this.generateConversationId(),
180
+ claudeSessionId: undefined,
181
+ workingDirectory: existing.workingDirectory,
182
+ createdAt: new Date(),
183
+ lastActivity: new Date(),
184
+ };
185
+ this.sessions.set(sessionKey, fresh);
186
+ this.lastRelayedAssistantText.delete(sessionKey);
187
+ sessionHistory.saveSession(sessionKey, fresh.conversationId, fresh.workingDirectory, '', undefined);
188
+ return fresh;
189
+ }
190
+ generateConversationId() {
191
+ return `conv_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
192
+ }
193
+ }
194
+ export const sessionManager = new SessionManager();
195
+ //# sourceMappingURL=session-manager.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