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,400 @@
1
+ /**
2
+ * Not starting a claude the machine has no room for.
3
+ *
4
+ * Every chat keeps its own `claude`, a few hundred MB each, and nothing
5
+ * about a typed message says whether it will reuse one or start one. On a box
6
+ * that is already in swap, the one that starts is the one that takes the
7
+ * machine down — bot, every other claude and all.
8
+ *
9
+ * So before a message starts a new claude, the kernel's MemAvailable is read.
10
+ * Under MEMORY_GUARD_MIN_AVAILABLE_MB the idle claudes are reaped first, with
11
+ * a window far shorter than the hourly reaper's; a chat so reaped loses a few
12
+ * seconds of resume on its next message and nothing else. Only when that
13
+ * doesn't free enough is the chat asked — start anyway, end the longest-idle
14
+ * claude first, check again, wait for room, or drop the message — because a
15
+ * plain yes/no on every prompt is tapped "yes" every time and so protects
16
+ * nothing. Waiting polls the machine and starts the moment it fits; what it
17
+ * is really waiting for is the other claudes to cross the reap window.
18
+ *
19
+ * A message to a chat whose claude is already running never asks: it starts
20
+ * nothing new.
21
+ *
22
+ * A claude that was let through a moment ago hasn't taken its memory yet: it
23
+ * allocates over its first seconds, and MemAvailable doesn't move until it
24
+ * does. Two threads started together would both read the same number and both
25
+ * pass, which is how a box with room for one more ended up with two. So every
26
+ * spawn the guard lets through is counted as a few hundred MB already spent
27
+ * until it has had time to show up in the kernel's figure.
28
+ */
29
+ import { config } from '../config.js';
30
+ import { readMemory } from '../utils/memory-pressure.js';
31
+ import { getPtyProvider } from '../providers/claude-provider.js';
32
+ import { endIdlePtySessions, sessionHasWork } from './pty-idle-reaper.js';
33
+ import { closeExpiredQuestion, createPendingQuestion, questionTimeoutMs, withdrawPendingQuestion } from './ask-user.js';
34
+ import { getAdminIds } from '../utils/admins.js';
35
+ import { parseSessionKey } from '../utils/session-key.js';
36
+ import { EntityText } from '../telegram/entities.js';
37
+ const PROCEED = { proceed: true, message: '' };
38
+ /** What a fresh claude takes within its first seconds, before any work: measured 160–470 MB, with its MCP servers. */
39
+ export const SPAWN_RESERVE_MB = 350;
40
+ /** How long a let-through spawn is counted before MemAvailable is trusted to include it. */
41
+ const SPAWN_RESERVE_MS = 30_000;
42
+ /** The spawns let through recently, by session key, with when each stops counting. */
43
+ const startingClaudes = new Map();
44
+ /** The floor 'auto' resolves to: a quarter of RAM, at least 1 GB. Exported for tests. */
45
+ export function resolveMinAvailableMB(totalMB) {
46
+ const setting = config.MEMORY_GUARD_MIN_AVAILABLE_MB;
47
+ if (setting !== 'auto')
48
+ return setting;
49
+ return Math.max(1024, Math.round(totalMB / 4));
50
+ }
51
+ /** How many claudes the guard let through in the last half minute, other than `exceptKey`'s. */
52
+ function countStarting(exceptKey) {
53
+ const now = Date.now();
54
+ let n = 0;
55
+ for (const [key, until] of startingClaudes) {
56
+ if (until <= now)
57
+ startingClaudes.delete(key);
58
+ else if (key !== exceptKey)
59
+ n++;
60
+ }
61
+ return n;
62
+ }
63
+ function noteSpawn(sessionKey) {
64
+ startingClaudes.set(sessionKey, Date.now() + SPAWN_RESERVE_MS);
65
+ return PROCEED;
66
+ }
67
+ /** Forget the spawns being counted. For tests. */
68
+ export function clearStartingClaudes() {
69
+ startingClaudes.clear();
70
+ }
71
+ const START = '▶️ Start anyway';
72
+ const END_IDLE = '♻️ End the longest-idle claude first';
73
+ const CHECK = '🔄 Check again';
74
+ const WAIT = '⏳ Wait for room';
75
+ const DROP = '✗ Drop this message';
76
+ /** How often a chat that chose to wait has the machine checked again. Exported for tests. */
77
+ export const WAIT_POLL_MS = 30_000;
78
+ export function isMemoryGuardEnabled() {
79
+ return config.MEMORY_GUARD_MIN_AVAILABLE_MB !== 0;
80
+ }
81
+ function swapOverLimit(mem) {
82
+ const limit = config.MEMORY_GUARD_MAX_SWAP_USED_MB;
83
+ return limit > 0 && mem.swapUsedMB > limit;
84
+ }
85
+ /** Tight when what's left, after the claudes still starting take theirs, is under the floor — or swap is past its limit. */
86
+ function isTight(mem, starting) {
87
+ if (mem === null)
88
+ return false;
89
+ return mem.availableMB - starting * SPAWN_RESERVE_MB < resolveMinAvailableMB(mem.totalMB) || swapOverLimit(mem);
90
+ }
91
+ const fmtMB = (mb) => `${mb.toLocaleString('en-US')} MB`;
92
+ export function formatIdle(ms) {
93
+ const s = Math.round(ms / 1000);
94
+ if (s < 60)
95
+ return `${s} s`;
96
+ const m = Math.round(s / 60);
97
+ if (m < 60)
98
+ return `${m} min`;
99
+ const h = Math.floor(m / 60);
100
+ const rest = m % 60;
101
+ return rest ? `${h} h ${rest} min` : `${h} h`;
102
+ }
103
+ /**
104
+ * Check the machine before `sessionKey`'s next turn, and ask the chat when it
105
+ * can't be made to fit. Returns at once for a chat with a claude already
106
+ * running, or a guard turned off.
107
+ */
108
+ export async function guardSpawn(ctx, sessionKey) {
109
+ if (!isMemoryGuardEnabled())
110
+ return PROCEED;
111
+ const pty = getPtyProvider();
112
+ if (pty.hasLiveSession(sessionKey))
113
+ return PROCEED;
114
+ const starting = countStarting(sessionKey); // also drops the expired entries
115
+ // Let through a moment ago and not yet live: that is this chat's own spawn.
116
+ if (startingClaudes.has(sessionKey))
117
+ return PROCEED;
118
+ const mem = readMemory();
119
+ if (!isTight(mem, starting))
120
+ return noteSpawn(sessionKey);
121
+ const room = await roomAfterReap(sessionKey, mem);
122
+ if (room.fits)
123
+ return noteSpawn(sessionKey);
124
+ if (!ctx?.api)
125
+ return noteSpawn(sessionKey); // nobody to ask; a scheduled run goes ahead
126
+ return askChat(ctx, sessionKey, room.mem, room.starting);
127
+ }
128
+ /**
129
+ * Make room the cheap way and read the machine again. Idle claudes go first:
130
+ * the chat they belonged to resumes from its transcript next time, which is
131
+ * all the hourly reaper does anyway. Run before the chat is asked, on every
132
+ * "Check again", and on every tick of a wait — so a claude that was busy when
133
+ * the question went up is ended as soon as it has sat idle long enough.
134
+ */
135
+ async function roomAfterReap(sessionKey, before) {
136
+ const reaped = endIdlePtySessions(config.MEMORY_GUARD_REAP_IDLE_MS);
137
+ if (reaped.length > 0) {
138
+ console.log(`[MemoryGuard] ${fmtMB(before.availableMB)} available; ended ${reaped.length} idle claude(s) before starting ${sessionKey}: ${reaped.join(', ')}`);
139
+ // Freed pages take a moment to show in MemAvailable; give it a tick.
140
+ await new Promise((r) => setTimeout(r, 300));
141
+ }
142
+ const starting = countStarting(sessionKey);
143
+ const mem = readMemory();
144
+ return isTight(mem, starting) ? { fits: false, mem, starting } : { fits: true };
145
+ }
146
+ /**
147
+ * Whether a claude may be started for `sessionKey` before anyone has sent it
148
+ * anything (see prewarm.ts). An early start is a convenience, so it gets the
149
+ * same floor and none of the remedies: nothing is reaped for it and nobody is
150
+ * asked. Under the floor it just doesn't happen, and the first message goes
151
+ * through {@link guardSpawn} as it would have. One that is allowed is counted
152
+ * like any other spawn.
153
+ */
154
+ export function allowPrewarm(sessionKey) {
155
+ if (!isMemoryGuardEnabled())
156
+ return true;
157
+ const starting = countStarting(sessionKey);
158
+ if (isTight(readMemory(), starting))
159
+ return false;
160
+ noteSpawn(sessionKey);
161
+ return true;
162
+ }
163
+ function surveyOthers() {
164
+ const idle = [];
165
+ let busy = 0;
166
+ for (const s of getPtyProvider().describeSessions()) {
167
+ if (s.generating || sessionHasWork(s.sessionKey, s.pid))
168
+ busy++;
169
+ else
170
+ idle.push({ sessionKey: s.sessionKey, idleMs: s.idleMs });
171
+ }
172
+ idle.sort((a, b) => b.idleMs - a.idleMs);
173
+ return { busy, idle };
174
+ }
175
+ /**
176
+ * Put the question to the chat and act on the answer. One Telegram message
177
+ * carries the whole exchange: "Check again" and a wait that runs out re-post
178
+ * the question over it with fresh numbers, so a chat that asks three times
179
+ * doesn't get three questions. The question is registered with `ownerCloses`,
180
+ * so a tap only resolves it and the message stays this function's to edit.
181
+ */
182
+ async function askChat(ctx, sessionKey, mem, starting) {
183
+ const { chatId, threadId } = parseSessionKey(sessionKey);
184
+ const api = ctx.api;
185
+ const timeoutMs = questionTimeoutMs();
186
+ const timeoutMin = Math.round(timeoutMs / 60000);
187
+ // The sender and the admins; in a group, a bystander's tap shouldn't start it.
188
+ const responders = [...new Set([ctx.from?.id, ...getAdminIds()].filter((id) => typeof id === 'number'))];
189
+ const swapLimitMB = config.MEMORY_GUARD_MAX_SWAP_USED_MB;
190
+ let sent;
191
+ let waitedOut = false; // the last wait ran out; the re-ask says so
192
+ for (;;) {
193
+ const others = surveyOthers();
194
+ const labels = others.idle.length > 0 ? [START, END_IDLE, CHECK, WAIT, DROP] : [START, CHECK, WAIT, DROP];
195
+ const { id, promise } = createPendingQuestion(labels, timeoutMs, sessionKey, responders, { ownerCloses: true });
196
+ let shown = buildMemoryGuardMessage({ mem, others, starting, timeoutMin, swapLimitMB, ...(waitedOut ? { waitedMin: timeoutMin } : {}) });
197
+ const keyboard = keyboardFor(labels, id);
198
+ if (!sent) {
199
+ try {
200
+ sent = await api.sendMessage(chatId, shown.text, {
201
+ entities: shown.entities,
202
+ reply_markup: { inline_keyboard: keyboard },
203
+ ...(threadId !== undefined ? { message_thread_id: threadId } : {}),
204
+ });
205
+ }
206
+ catch (err) {
207
+ withdrawPendingQuestion(id);
208
+ console.error('[MemoryGuard] failed to post the question:', err instanceof Error ? err.message : err);
209
+ return noteSpawn(sessionKey); // better one claude too many than a message silently lost
210
+ }
211
+ console.log(`[MemoryGuard] ${fmtMB(mem.availableMB)} available, asking ${sessionKey} before starting a claude`);
212
+ }
213
+ else {
214
+ await showQuestion(api, sent, shown, keyboard);
215
+ }
216
+ const answer = await promise;
217
+ if (answer === null) {
218
+ await closeExpiredQuestion(api, sent, shown.text, `No answer within ${timeoutMin} min, so the message was dropped.`, shown.entities);
219
+ return { proceed: false, message: `🧠 Memory was tight and nobody answered in ${timeoutMin} min, so that message was dropped. Send it again to start Claude anyway.` };
220
+ }
221
+ let chosen = labels[answer.index];
222
+ if (chosen === CHECK) {
223
+ const room = await roomAfterReap(sessionKey, mem);
224
+ if (room.fits) {
225
+ await closeQuestion(api, sent, shown, '✅ Checked again: it fits now, so Claude is starting.');
226
+ return noteSpawn(sessionKey);
227
+ }
228
+ ({ mem, starting } = room);
229
+ waitedOut = false;
230
+ continue;
231
+ }
232
+ if (chosen === WAIT) {
233
+ console.log(`[MemoryGuard] ${sessionKey} waits for room`);
234
+ const waited = await waitForRoom(api, sent, sessionKey, responders, timeoutMs, mem, starting, others.idle.length > 0);
235
+ shown = waited.shown;
236
+ if (waited.kind === 'fits') {
237
+ console.log(`[MemoryGuard] room came free after ${formatIdle(waited.waitedMs)}; starting ${sessionKey}`);
238
+ await closeQuestion(api, sent, shown, `✅ Room came free after ${formatIdle(waited.waitedMs)}, so Claude is starting.`);
239
+ return noteSpawn(sessionKey);
240
+ }
241
+ if (waited.kind === 'timeout') {
242
+ ({ mem, starting } = waited);
243
+ waitedOut = true;
244
+ continue; // ask again rather than drop: the chat said it wanted this message
245
+ }
246
+ chosen = waited.label;
247
+ }
248
+ if (chosen === START) {
249
+ await closeQuestion(api, sent, shown, `✅ Answered: ${START}`);
250
+ return noteSpawn(sessionKey);
251
+ }
252
+ if (chosen === END_IDLE) {
253
+ await closeQuestion(api, sent, shown, `✅ Answered: ${END_IDLE}`);
254
+ const ended = getPtyProvider().endLongestIdleSession(sessionHasWork);
255
+ if (ended) {
256
+ console.log(`[MemoryGuard] ended ${ended} on request before starting ${sessionKey}`);
257
+ return noteSpawn(sessionKey);
258
+ }
259
+ // Everything went busy while the question was open; the tap still meant "go".
260
+ console.log(`[MemoryGuard] nothing idle left to end; starting ${sessionKey} anyway`);
261
+ return noteSpawn(sessionKey);
262
+ }
263
+ await closeQuestion(api, sent, shown, `✅ Answered: ${DROP}`);
264
+ return { proceed: false, message: '🧠 Dropped. Send it again when you want Claude started anyway.' };
265
+ }
266
+ }
267
+ /**
268
+ * Check the machine every {@link WAIT_POLL_MS} until the claude fits, the
269
+ * question's timeout runs out, or the chat taps one of the buttons that stay
270
+ * up meanwhile (start anyway, end the longest-idle one, drop). Each tick reaps
271
+ * and re-reads like the first check did, and the message shows the latest
272
+ * figure. A tap and a tick that both land are settled by whichever came
273
+ * first; the question is withdrawn either way.
274
+ */
275
+ async function waitForRoom(api, sent, sessionKey, responders, timeoutMs, mem, starting, hasIdle) {
276
+ const labels = hasIdle ? [START, END_IDLE, DROP] : [START, DROP];
277
+ const { id, promise } = createPendingQuestion(labels, timeoutMs, sessionKey, responders, { ownerCloses: true });
278
+ const keyboard = keyboardFor(labels, id);
279
+ const timeoutMin = Math.round(timeoutMs / 60000);
280
+ const startedAt = Date.now();
281
+ const render = () => buildWaitingMessage({ mem, starting, waitedMs: Date.now() - startedAt, timeoutMin });
282
+ let shown = render();
283
+ await showQuestion(api, sent, shown, keyboard);
284
+ let settled = false;
285
+ let timer;
286
+ const poll = new Promise((resolve) => {
287
+ const tick = async () => {
288
+ const room = await roomAfterReap(sessionKey, mem);
289
+ if (settled)
290
+ return;
291
+ if (room.fits) {
292
+ resolve({ kind: 'fits', waitedMs: Date.now() - startedAt });
293
+ return;
294
+ }
295
+ ({ mem, starting } = room);
296
+ shown = render();
297
+ await showQuestion(api, sent, shown, keyboard);
298
+ if (!settled)
299
+ timer = setTimeout(tick, WAIT_POLL_MS);
300
+ };
301
+ timer = setTimeout(tick, WAIT_POLL_MS);
302
+ });
303
+ const tapped = promise.then((a) => (a === null ? { kind: 'timeout', mem, starting } : { kind: 'answer', label: labels[a.index] }));
304
+ const outcome = await Promise.race([poll, tapped]);
305
+ settled = true;
306
+ if (timer)
307
+ clearTimeout(timer);
308
+ withdrawPendingQuestion(id); // a no-op when a tap already resolved it
309
+ return { ...outcome, shown };
310
+ }
311
+ function keyboardFor(labels, id) {
312
+ return labels.map((label, idx) => [{ text: label, callback_data: `q:${id}:${idx}` }]);
313
+ }
314
+ /** Re-post the question over its own message. Best-effort: the question is live either way, and the old text still answers. */
315
+ async function showQuestion(api, sent, shown, keyboard) {
316
+ try {
317
+ await api.editMessageText(sent.chat.id, sent.message_id, shown.text, {
318
+ entities: shown.entities,
319
+ reply_markup: { inline_keyboard: keyboard },
320
+ });
321
+ }
322
+ catch (err) {
323
+ console.warn('[MemoryGuard] could not update the question:', err instanceof Error ? err.message : err);
324
+ }
325
+ }
326
+ /** Close the exchange: the footer says how it ended, and the keyboard comes down. Same fallbacks as ask-user's closeExpiredQuestion. */
327
+ async function closeQuestion(api, sent, shown, footer) {
328
+ try {
329
+ await api.editMessageText(sent.chat.id, sent.message_id, `${shown.text}\n\n${footer}`, { entities: shown.entities });
330
+ return;
331
+ }
332
+ catch {
333
+ // Losing the footer is cosmetic; a live keyboard on a closed question is not.
334
+ }
335
+ try {
336
+ await api.editMessageReplyMarkup(sent.chat.id, sent.message_id);
337
+ }
338
+ catch (err) {
339
+ console.warn('[MemoryGuard] could not close the question:', err instanceof Error ? err.message : err);
340
+ }
341
+ }
342
+ /** What the message says while the chat waits for room. Exported for tests. */
343
+ export function buildWaitingMessage(parts) {
344
+ const { mem, starting } = parts;
345
+ const need = resolveMinAvailableMB(mem.totalMB) + starting * SPAWN_RESERVE_MB;
346
+ const b = new EntityText();
347
+ b.add('🧠 ').bold('Waiting for room').newline();
348
+ b.add(`${fmtMB(mem.availableMB)} available of ${fmtMB(mem.totalMB)}; this chat's Claude starts at ${fmtMB(need)}.`);
349
+ if (parts.waitedMs >= 60_000)
350
+ b.add(` Waited ${formatIdle(parts.waitedMs)} so far.`);
351
+ b.newline().newline();
352
+ b.add(`Checked every ${Math.round(WAIT_POLL_MS / 1000)} s; claudes that go idle meanwhile are ended as they pass ${formatIdle(config.MEMORY_GUARD_REAP_IDLE_MS)}. `);
353
+ b.add('The buttons still work while it waits.');
354
+ b.newline().newline();
355
+ b.italic(`Gives up in ${parts.timeoutMin} min → asks again.`);
356
+ return b.build();
357
+ }
358
+ /** Lay out the question. Exported for tests — the wording is the product. */
359
+ export function buildMemoryGuardMessage(parts) {
360
+ const { mem, others } = parts;
361
+ const b = new EntityText();
362
+ b.add('🧠 ').bold('Memory is tight').newline();
363
+ b.add(`${fmtMB(mem.availableMB)} available of ${fmtMB(mem.totalMB)}`);
364
+ if (mem.swapTotalMB > 0)
365
+ b.add(`, swap ${fmtMB(mem.swapUsedMB)} in use`);
366
+ b.add('.');
367
+ const swapLimit = parts.swapLimitMB ?? 0;
368
+ if (swapLimit > 0 && mem.swapUsedMB > swapLimit)
369
+ b.add(` Swap is past the ${fmtMB(swapLimit)} limit.`);
370
+ const starting = parts.starting ?? 0;
371
+ if (starting > 0) {
372
+ b.add(starting === 1
373
+ ? ` 1 more Claude was started just now and isn't in that figure yet.`
374
+ : ` ${starting} more Claudes were started just now and aren't in that figure yet.`);
375
+ }
376
+ if (parts.waitedMin)
377
+ b.add(` Waited ${parts.waitedMin} min for room and it didn't come.`);
378
+ b.newline().newline();
379
+ b.add('This message starts a new Claude for this chat, which takes a few hundred MB more. ');
380
+ const total = others.busy + others.idle.length;
381
+ if (total === 0) {
382
+ b.add('No other Claude is running here; something else has the memory.');
383
+ }
384
+ else {
385
+ const parts = [];
386
+ if (others.busy > 0)
387
+ parts.push(`${others.busy} busy`);
388
+ if (others.idle.length > 0) {
389
+ const longest = others.idle[0];
390
+ parts.push(others.idle.length === 1
391
+ ? `1 idle for ${formatIdle(longest.idleMs)}`
392
+ : `${others.idle.length} idle, the longest for ${formatIdle(longest.idleMs)}`);
393
+ }
394
+ b.add(`${total} other Claude${total === 1 ? ' is' : 's are'} running: ${parts.join(', ')}.`);
395
+ }
396
+ b.newline().newline();
397
+ b.italic(`Ending an idle one costs its chat a few seconds of resume next time. Waiting checks every ${Math.round(WAIT_POLL_MS / 1000)} s and starts Claude when it fits. Times out in ${parts.timeoutMin} min → dropped.`);
398
+ return b.build();
399
+ }
400
+ //# sourceMappingURL=memory-guard.js.map
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Index from a Telegram assistant message_id → the JSONL truncation point
3
+ * that recreates the conversation state at the moment that message was sent.
4
+ *
5
+ * Used by /branch: the user taps a "🌱 Branch" button on a past assistant message,
6
+ * we look up the recorded {claudeSessionId, lineCount, projectPath} for that
7
+ * message, and slice the source JSONL to lineCount to build the truncated
8
+ * transcript that gets handed off to the target bot.
9
+ *
10
+ * File-backed (~/.telecoder/message-offsets-<botId>.json) so a restart
11
+ * doesn't invalidate branch buttons that were posted before the restart.
12
+ * Bounded per sessionKey to keep the file from growing forever — old
13
+ * entries simply lose their branch button (the button still exists in chat
14
+ * history; on tap we report "branch point no longer available").
15
+ */
16
+ import * as fs from 'fs';
17
+ import * as path from 'path';
18
+ import { z } from 'zod';
19
+ import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
20
+ import { BOT_ID } from '../config.js';
21
+ const HISTORY_DIR = getStateDir();
22
+ const entrySchema = z.object({
23
+ claudeSessionId: z.string(),
24
+ projectPath: z.string(),
25
+ lineCount: z.number().int().nonnegative(),
26
+ topic: z.string().optional(),
27
+ conversationId: z.string().optional(),
28
+ ts: z.string(),
29
+ });
30
+ const fileSchema = z.object({
31
+ sessions: z.record(z.string(), z.record(z.string(), entrySchema)),
32
+ });
33
+ const MAX_OFFSETS_PER_SESSION = 200;
34
+ class MessageOffsetStore {
35
+ data = { sessions: {} };
36
+ filePath;
37
+ constructor() {
38
+ this.filePath = path.join(HISTORY_DIR, `message-offsets-${BOT_ID}.json`);
39
+ ensureStateDir(HISTORY_DIR, 'MessageOffsets');
40
+ this.load();
41
+ }
42
+ load() {
43
+ const loaded = readJsonFile(this.filePath, fileSchema, 'MessageOffsets');
44
+ if (loaded)
45
+ this.data = loaded;
46
+ }
47
+ save() {
48
+ writeJsonFile(this.filePath, this.data, 'MessageOffsets');
49
+ }
50
+ record(sessionKey, telegramMessageId, entry) {
51
+ const bucket = this.data.sessions[sessionKey] ?? {};
52
+ bucket[String(telegramMessageId)] = { ...entry, ts: new Date().toISOString() };
53
+ // Trim oldest entries beyond the cap (by ts ascending).
54
+ const keys = Object.keys(bucket);
55
+ if (keys.length > MAX_OFFSETS_PER_SESSION) {
56
+ const sorted = keys.sort((a, b) => bucket[a].ts.localeCompare(bucket[b].ts));
57
+ const excess = sorted.slice(0, keys.length - MAX_OFFSETS_PER_SESSION);
58
+ for (const k of excess)
59
+ delete bucket[k];
60
+ }
61
+ this.data.sessions[sessionKey] = bucket;
62
+ this.save();
63
+ }
64
+ lookup(sessionKey, telegramMessageId) {
65
+ return this.data.sessions[sessionKey]?.[String(telegramMessageId)];
66
+ }
67
+ }
68
+ export const messageOffsets = new MessageOffsetStore();
69
+ /**
70
+ * Count current JSONL lines for a session. Used at "turn finished" time to
71
+ * record the truncation boundary for the Branch button.
72
+ */
73
+ export function countJsonlLines(filePath) {
74
+ try {
75
+ const raw = fs.readFileSync(filePath, 'utf-8');
76
+ if (!raw)
77
+ return 0;
78
+ // JSONL is line-delimited; trailing newline shouldn't count as a record.
79
+ const lines = raw.split('\n');
80
+ if (lines[lines.length - 1] === '')
81
+ lines.pop();
82
+ return lines.length;
83
+ }
84
+ catch {
85
+ return 0;
86
+ }
87
+ }
88
+ //# sourceMappingURL=message-offsets.js.map