telecoder 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.env.example +142 -130
  2. package/CHANGELOG.md +683 -2
  3. package/README.md +36 -32
  4. package/dist/audio/transcribe.js +0 -9
  5. package/dist/bin/mcp-server.js +46 -61
  6. package/dist/bot/bot.js +162 -181
  7. package/dist/bot/command-catalog.js +263 -0
  8. package/dist/bot/deleted-threads.js +103 -0
  9. package/dist/bot/file-access.js +35 -26
  10. package/dist/bot/handlers/album.handler.js +128 -0
  11. package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
  12. package/dist/bot/handlers/command/access.js +1 -1
  13. package/dist/bot/handlers/command/admin.js +86 -110
  14. package/dist/bot/handlers/command/all-view.js +33 -0
  15. package/dist/bot/handlers/command/auto-approve.js +3 -3
  16. package/dist/bot/handlers/command/background.js +37 -0
  17. package/dist/bot/handlers/command/botname.js +76 -0
  18. package/dist/bot/handlers/command/btw.js +20 -69
  19. package/dist/bot/handlers/command/cleanup.js +329 -0
  20. package/dist/bot/handlers/command/model.js +40 -119
  21. package/dist/bot/handlers/command/prefs-scope.js +255 -90
  22. package/dist/bot/handlers/command/project.js +31 -109
  23. package/dist/bot/handlers/command/resume.js +8 -4
  24. package/dist/bot/handlers/command/session.js +74 -213
  25. package/dist/bot/handlers/command/settings.js +92 -447
  26. package/dist/bot/handlers/command/shared.js +32 -35
  27. package/dist/bot/handlers/command/tasks.js +263 -95
  28. package/dist/bot/handlers/command/thread.js +128 -0
  29. package/dist/bot/handlers/command/topic-store.js +14 -53
  30. package/dist/bot/handlers/command/topic.js +8 -61
  31. package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
  32. package/dist/bot/handlers/command-fallback.js +179 -0
  33. package/dist/bot/handlers/command.handler.js +96 -422
  34. package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
  35. package/dist/bot/handlers/media-fallback.js +12 -7
  36. package/dist/bot/handlers/message/replies.js +10 -87
  37. package/dist/bot/handlers/message/shared.js +9 -31
  38. package/dist/bot/handlers/message/turn-notify.js +15 -49
  39. package/dist/bot/handlers/message/turn-runner.js +18 -103
  40. package/dist/bot/handlers/message.handler.js +59 -52
  41. package/dist/bot/handlers/newbot.handler.js +13 -4
  42. package/dist/bot/handlers/photo.handler.js +88 -129
  43. package/dist/bot/handlers/prompts.handler.js +11 -11
  44. package/dist/bot/handlers/running-note.js +2 -2
  45. package/dist/bot/handlers/session-guard.js +4 -4
  46. package/dist/bot/handlers/suggestion.handler.js +2 -2
  47. package/dist/bot/handlers/tree.handler.js +20 -20
  48. package/dist/bot/handlers/voice.handler.js +23 -85
  49. package/dist/bot/kept-threads.js +51 -0
  50. package/dist/bot/middleware/album-collector.js +69 -0
  51. package/dist/bot/middleware/auth.middleware.js +1 -1
  52. package/dist/bot/middleware/group-mention.middleware.js +11 -5
  53. package/dist/bot/middleware/queued-messages.js +143 -32
  54. package/dist/bot/middleware/stale-filter.js +0 -22
  55. package/dist/build-info.json +5 -5
  56. package/dist/claude/ask-user-form.js +517 -0
  57. package/dist/claude/ask-user.js +94 -26
  58. package/dist/claude/auto-topic-haiku.js +17 -0
  59. package/dist/claude/available-commands.js +22 -19
  60. package/dist/claude/background-hint.js +91 -0
  61. package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
  62. package/dist/claude/carry-over.js +0 -2
  63. package/dist/claude/ccr-shim.js +12 -10
  64. package/dist/claude/claude-auth.js +6 -10
  65. package/dist/claude/command-parser.js +49 -43
  66. package/dist/claude/cost-overlay-scraper.js +7 -2
  67. package/dist/claude/effort-level.js +5 -0
  68. package/dist/claude/enabled-plugins.js +12 -16
  69. package/dist/claude/in-flight-tracker.js +21 -0
  70. package/dist/claude/mcp-bridge.js +86 -58
  71. package/dist/claude/memory-guard.js +400 -0
  72. package/dist/claude/message-offsets.js +5 -5
  73. package/dist/claude/modal-relay.js +401 -34
  74. package/dist/claude/model-catalog.js +20 -3
  75. package/dist/claude/monitor-relay.js +130 -15
  76. package/dist/claude/native-commands.js +40 -0
  77. package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
  78. package/dist/claude/permission-gate.js +11 -10
  79. package/dist/claude/permission-mode.js +19 -45
  80. package/dist/claude/prewarm.js +70 -0
  81. package/dist/claude/pty-idle-reaper.js +96 -0
  82. package/dist/claude/pty-provider.js +473 -188
  83. package/dist/claude/pty-spawn-config.js +79 -32
  84. package/dist/claude/pty-watch.js +201 -0
  85. package/dist/claude/request-queue.js +7 -35
  86. package/dist/claude/rewind.js +111 -0
  87. package/dist/claude/scheduled-runner.js +1 -3
  88. package/dist/claude/scheduler.js +6 -2
  89. package/dist/claude/scope-guard.js +8 -3
  90. package/dist/claude/screen-marks.js +83 -0
  91. package/dist/claude/screen-render.js +96 -0
  92. package/dist/claude/session-history.js +4 -2
  93. package/dist/claude/session-jsonl.js +162 -15
  94. package/dist/claude/session-manager.js +29 -8
  95. package/dist/claude/session-move.js +70 -0
  96. package/dist/claude/shell-mode-gate.js +60 -0
  97. package/dist/claude/side-question.js +20 -17
  98. package/dist/claude/stage-images.js +5 -5
  99. package/dist/claude/tasks-overlay-scraper.js +143 -20
  100. package/dist/claude/thread-judge-haiku.js +88 -0
  101. package/dist/claude/tip-scraper.js +3 -4
  102. package/dist/claude/tui-modal.js +272 -27
  103. package/dist/claude/tui-state.js +74 -2
  104. package/dist/claude/turn-end.js +15 -1
  105. package/dist/claude/turn-prose.js +1 -1
  106. package/dist/claude/typed-answer.js +104 -0
  107. package/dist/claude/update-banner-relay.js +1 -1
  108. package/dist/cli/commands/doctor.js +48 -15
  109. package/dist/cli/commands/help.js +11 -2
  110. package/dist/cli/commands/init.js +16 -13
  111. package/dist/cli/commands/service.js +40 -8
  112. package/dist/cli/commands/start.js +10 -0
  113. package/dist/cli/commands/watch.js +322 -0
  114. package/dist/cli/dispatch.js +5 -0
  115. package/dist/cli/init/env-file.js +1 -1
  116. package/dist/cli/init/flow.js +114 -47
  117. package/dist/cli/init/prompter.js +8 -0
  118. package/dist/cli/init/telegram.js +35 -9
  119. package/dist/cli/service/render.js +3 -3
  120. package/dist/config.js +156 -131
  121. package/dist/index.js +107 -31
  122. package/dist/launcher.js +34 -7
  123. package/dist/providers/ccr-introspect.js +1 -8
  124. package/dist/providers/ccr-provider.js +19 -20
  125. package/dist/providers/claude-provider.js +4 -57
  126. package/dist/providers/prefs-sync.js +16 -59
  127. package/dist/providers/provider-router.js +24 -23
  128. package/dist/providers/spawn-settings.js +45 -0
  129. package/dist/providers/user-preferences.js +127 -19
  130. package/dist/restart-when-idle.js +27 -7
  131. package/dist/startup/auto-continue.js +2 -2
  132. package/dist/startup/auto-resume.js +3 -15
  133. package/dist/startup/notices.js +1 -1
  134. package/dist/startup/verify-token.js +4 -4
  135. package/dist/telegram/action-logger.js +3 -165
  136. package/dist/telegram/background-activity-card.js +1 -1
  137. package/dist/telegram/botname-settings.js +71 -125
  138. package/dist/telegram/client-options.js +6 -7
  139. package/dist/telegram/force-reply-tracker.js +55 -16
  140. package/dist/telegram/message-sender.js +92 -360
  141. package/dist/telegram/prompt-label.js +11 -5
  142. package/dist/telegram/streaming-turn.js +5 -7
  143. package/dist/telegram/table-lists.js +56 -0
  144. package/dist/telegram/task-list.js +4 -4
  145. package/dist/telegram/task-tracker.js +45 -126
  146. package/dist/telegram/terminal-renderer.js +1 -5
  147. package/dist/telegram/thread-titles.js +74 -2
  148. package/dist/telegram/threads-setup.js +1 -1
  149. package/dist/utils/admins.js +2 -2
  150. package/dist/utils/bot-icon.js +248 -0
  151. package/dist/utils/bot-token.js +8 -5
  152. package/dist/utils/build-info.js +3 -3
  153. package/dist/utils/caffeinate.js +6 -3
  154. package/dist/utils/claude-env.js +0 -1
  155. package/dist/utils/claude-version.js +2 -2
  156. package/dist/utils/config-home.js +3 -3
  157. package/dist/utils/download.js +41 -15
  158. package/dist/utils/exit-codes.js +11 -0
  159. package/dist/utils/format.js +3 -6
  160. package/dist/utils/home-project.js +1 -1
  161. package/dist/utils/idle-restart.js +1 -1
  162. package/dist/utils/install-mode.js +1 -1
  163. package/dist/utils/instance-config.js +1 -1
  164. package/dist/utils/instances.js +1 -1
  165. package/dist/utils/keyed-settings.js +2 -2
  166. package/dist/utils/memory-pressure.js +60 -0
  167. package/dist/utils/npm-version.js +2 -2
  168. package/dist/utils/resolve-claude-bin.js +13 -24
  169. package/dist/utils/respawn-backoff.js +9 -0
  170. package/dist/utils/stale-launcher.js +1 -1
  171. package/dist/utils/systemd.js +8 -8
  172. package/dist/utils/telegram-proxy.js +72 -0
  173. package/dist/utils/uploads-dir.js +27 -0
  174. package/dist/utils/verbosity.js +8 -8
  175. package/dist/utils/version-check.js +5 -5
  176. package/package.json +3 -4
  177. package/dist/bot/handlers/command/media.js +0 -197
  178. package/dist/bot/handlers/command/streaming-mode.js +0 -16
  179. package/dist/bot/handlers/message/throttle.js +0 -49
  180. package/dist/claude/agent-watchdog.js +0 -162
  181. package/dist/claude/agent.js +0 -1458
  182. package/dist/claude/held-query.js +0 -190
  183. package/dist/claude/mcp-tools.js +0 -354
  184. package/dist/claude/sdk-permission-gate.js +0 -77
  185. package/dist/claude/session-cost.js +0 -41
  186. package/dist/claude/system-prompt.js +0 -162
  187. package/dist/providers/sdk-provider.js +0 -37
  188. package/dist/telegram/telegraph-settings.js +0 -31
  189. package/dist/telegram/telegraph.js +0 -453
  190. package/dist/telegram/terminal-settings.js +0 -25
  191. package/dist/tts/tts-settings.js +0 -62
  192. package/dist/tts/tts.js +0 -245
  193. package/dist/tts/voice-reply.js +0 -78
  194. package/dist/utils/debug-agent.js +0 -117
  195. package/dist/utils/debug-watchdog.js +0 -121
  196. package/dist/utils/project-data-dir.js +0 -33
  197. package/dist/utils/reasoning-summary.js +0 -12
@@ -1,5 +1,5 @@
1
1
  /**
2
- * A prompt as TeleCoder shows it back: in /prompts, /recap and /handoff, on
2
+ * A prompt as TeleCoder shows it back: in /prompts and /history, on
3
3
  * the branches /tree draws, in the status line under an answer, and at the
4
4
  * bottom of the live action log.
5
5
  *
@@ -21,12 +21,15 @@ import { userTextKind } from '../claude/session-jsonl.js';
21
21
  // an `[Image #N]` chip, leaving `Saved at:` and ` 1.` pointing at nothing.
22
22
  //
23
23
  // Collapse those notes back to what the upload was: kind, name, caption.
24
+ // Both wordings are matched: the one the handlers write, and the one they
25
+ // wrote while uploads went to the project, which old transcripts still carry.
24
26
  const UPLOAD_CHIPS = /^(?:\[(?:Image|Pasted text) #\d+(?: \+\d+ lines)?\]\s*)+/;
25
- const IMAGE_NOTE = 'User uploaded an image to the project.';
26
- const FILE_NOTE = /^User uploaded a file: (.+)$/;
27
+ const IMAGE_NOTE = /^User (?:sent an image\.|uploaded an image to the project\.)$/;
28
+ const FILE_NOTE = /^User (?:sent|uploaded) a file: (.+)$/;
29
+ const ALBUM_NOTE = /^User sent (\d+) files together\.$/;
27
30
  // The line each handler puts directly after the caption — the caption itself
28
31
  // is a user-supplied string that may run over several lines.
29
- const AFTER_CAPTION = /^(?:The image is attached as a vision input|Use the Read tool to read its contents)/;
32
+ const AFTER_CAPTION = /^(?:The images? (?:is|are) attached as (?:a )?vision input|Use the Read tool to read (?:its|their) contents)/;
30
33
  function uploadCaption(lines) {
31
34
  const start = lines.findIndex((l) => l.startsWith('Caption: '));
32
35
  if (start === -1)
@@ -52,13 +55,16 @@ export function summarizeUserPrompt(text) {
52
55
  const lines = text.replace(UPLOAD_CHIPS, '').split('\n');
53
56
  const first = lines[0]?.trim() ?? '';
54
57
  let label;
55
- if (first === IMAGE_NOTE) {
58
+ if (IMAGE_NOTE.test(first)) {
56
59
  label = '📷 Image';
57
60
  }
58
61
  else {
59
62
  const named = FILE_NOTE.exec(first);
63
+ const album = ALBUM_NOTE.exec(first);
60
64
  if (named)
61
65
  label = `📎 ${named[1].trim()}`;
66
+ else if (album)
67
+ label = `📎 ${album[1]} files`;
62
68
  }
63
69
  if (!label)
64
70
  return text;
@@ -42,9 +42,7 @@ export function makeEditDiffHandler(ctx) {
42
42
  }
43
43
  /**
44
44
  * Callbacks that render a turn's progress into the streaming message. Shared
45
- * by every streaming entry point, including /loop — which takes only these,
46
- * since `sendLoopToAgent` reports iteration progress rather than individual
47
- * tool calls.
45
+ * by every entry point that starts a turn.
48
46
  */
49
47
  export function progressCallbacks(ctx) {
50
48
  return {
@@ -54,14 +52,16 @@ export function progressCallbacks(ctx) {
54
52
  onTip: (tip) => {
55
53
  messageSender.updateTip(ctx, tip);
56
54
  },
55
+ onBackgroundHint: (offered) => {
56
+ messageSender.updateBackgroundHint(ctx, offered);
57
+ },
57
58
  onToolResult: makeToolResultHandler(ctx),
58
59
  onEditDiff: makeEditDiffHandler(ctx),
59
60
  };
60
61
  }
61
62
  /**
62
63
  * Per-tool telemetry on top of `progressCallbacks`, for the `sendToAgent`
63
- * paths that surface the running tool in the stream header and relay
64
- * sub-agent output.
64
+ * paths that surface the running tool in the stream header.
65
65
  */
66
66
  export function toolCallbacks(ctx, sessionKey) {
67
67
  return {
@@ -71,8 +71,6 @@ export function toolCallbacks(ctx, sessionKey) {
71
71
  onToolEnd: () => {
72
72
  messageSender.clearToolOperation(sessionKey);
73
73
  },
74
- onTaskEvent: (event) => messageSender.notifyTaskEvent(ctx, sessionKey, event),
75
- onSubTurnResponse: (text) => messageSender.postSubTurnResponse(ctx, text),
76
74
  };
77
75
  }
78
76
  /**
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Markdown tables rewritten as bullet lists, for a report made of narrow
3
+ * label-and-number tables.
4
+ *
5
+ * Telegram has no tables, so markdown.ts draws each row as a block of
6
+ * `Header: cell` lines. That suits the prose tables Claude writes in a reply,
7
+ * but Claude Code's `/context` report is three tables of short rows, and drawn
8
+ * that way it runs past a hundred lines. Here each row is one line, its first
9
+ * cell in bold and the rest after it, and the other column headers go above
10
+ * the list in italics so the numbers keep their names:
11
+ *
12
+ * _Tokens · Percentage_
13
+ * - **System prompt:** 3.8k · 0.4%
14
+ *
15
+ * Everything that isn't a table passes through unchanged.
16
+ */
17
+ export function tablesToLists(markdown) {
18
+ const lines = markdown.split('\n');
19
+ const out = [];
20
+ let i = 0;
21
+ while (i < lines.length) {
22
+ const header = cells(lines[i]);
23
+ if (!header || !SEPARATOR_RE.test(lines[i + 1] ?? '')) {
24
+ out.push(lines[i]);
25
+ i++;
26
+ continue;
27
+ }
28
+ i += 2;
29
+ const names = header.slice(1).filter(Boolean);
30
+ if (names.length > 0)
31
+ out.push(`_${names.join(' · ')}_`);
32
+ for (let row = cells(lines[i] ?? ''); row; row = cells(lines[++i] ?? '')) {
33
+ const [first, ...rest] = row;
34
+ const values = rest.filter(Boolean).join(' · ');
35
+ if (first && values)
36
+ out.push(`- **${first}:** ${values}`);
37
+ else if (first || values)
38
+ out.push(`- ${first || values}`);
39
+ }
40
+ }
41
+ return out.join('\n');
42
+ }
43
+ /** A table's header rule: `|---|:--:|---|`, outer pipes optional. */
44
+ const SEPARATOR_RE = /^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)*\|?\s*$/;
45
+ /** A table row's cells, trimmed, or null when the line isn't a row. */
46
+ function cells(line) {
47
+ const t = line.trim();
48
+ if (!t.startsWith('|'))
49
+ return null;
50
+ return t
51
+ .replace(/^\|/, '')
52
+ .replace(/(?<!\\)\|$/, '')
53
+ .split(/(?<!\\)\|/)
54
+ .map((cell) => cell.trim());
55
+ }
56
+ //# sourceMappingURL=table-lists.js.map
@@ -5,8 +5,8 @@
5
5
  * it, TaskList and TaskGet read it. None of their inputs carries the whole list
6
6
  * (TodoWrite, which they replaced, sent the complete array on every call), so
7
7
  * the list is read from where Claude Code stores it: one JSON file per task in
8
- * `~/.claude/tasks/<session id>/`. That works the same for both transports, and
9
- * it is also what lets a restored session show the list it left off with.
8
+ * `~/.claude/tasks/<session id>/`. That is also what lets a restored session
9
+ * show the list it left off with.
10
10
  *
11
11
  * The rendering copies the CLI's own task panel (2.1.322, the component that
12
12
  * draws `N tasks (X done, Y in progress, Z open)`):
@@ -164,8 +164,8 @@ export function renderSessionTaskList(claudeSessionId) {
164
164
  }
165
165
  // After a TaskCreate/TaskUpdate starts, look at the files this long after —
166
166
  // again and again while nothing has changed, since the write lands some time
167
- // after the tool starts and the SDK transport's tool-end signal is not sent
168
- // for every call. A list that renders the same costs a directory read.
167
+ // after the tool starts and a tool-end signal can't be counted on for every
168
+ // call. A list that renders the same costs a directory read.
169
169
  const DIRTY_RECHECK_MS = [300, 1000, 2500, 5000];
170
170
  // A file caught mid-write is read again after this long, this many times;
171
171
  // after that it is taken to be broken for good and left out.
@@ -1,10 +1,12 @@
1
1
  /**
2
- * Tracks Claude Agent SDK background tasks per session.
2
+ * Tracks the work each session has running in the background: monitors,
3
+ * backgrounded shells, subagents and workflows.
3
4
  *
4
- * Tasks survive across streaming turns: a task started in turn 1 may emit
5
- * its `task_notification` in turn 2 or later (e.g. when the model calls
6
- * `TaskOutput` to wait for completion). Cleared explicitly via clear() on
7
- * /reset or session teardown.
5
+ * The monitor relay (claude/monitor-relay.ts) feeds it. It records a task when
6
+ * claude starts one and removes it when the task's notification comes back,
7
+ * which may be turns later. So a task in here is one still running in the
8
+ * background, and there is no status to keep. Cleared with the session's
9
+ * relay state.
8
10
  */
9
11
  /** Updates kept per task: the footer shares the status bubble, so only the latest few. */
10
12
  const MAX_TASK_UPDATES = 3;
@@ -18,100 +20,19 @@ class TaskTracker {
18
20
  }
19
21
  return tasks;
20
22
  }
21
- /**
22
- * Apply an SDK task event to the per-session task map.
23
- * Returns the resulting TaskState (or undefined if the event referenced
24
- * an unknown task on a non-started subtype).
25
- */
26
- handleEvent(sessionKey, event) {
27
- const tasks = this.getOrCreateMap(sessionKey);
28
- switch (event.type) {
29
- case 'started': {
30
- // Monitors are inherently long-running streaming subscriptions —
31
- // treat them as backgrounded even if the launching tool didn't set
32
- // run_in_background:true.
33
- const isMonitor = event.taskType === 'monitor_mcp';
34
- const state = {
35
- id: event.taskId,
36
- description: event.description,
37
- taskType: event.taskType,
38
- workflowName: event.workflowName,
39
- toolUseId: event.toolUseId,
40
- status: 'running',
41
- isBackgrounded: event.isBackgrounded ?? isMonitor,
42
- skipTranscript: event.skipTranscript ?? false,
43
- startedAt: event.startedAt ?? Date.now(),
44
- lastActivityAt: Date.now(),
45
- };
46
- tasks.set(event.taskId, state);
47
- return state;
48
- }
49
- case 'progress': {
50
- const existing = tasks.get(event.taskId);
51
- if (!existing)
52
- return undefined;
53
- // Note: event.description on progress events conveys the *current
54
- // activity*, not the task's description — keep the original.
55
- existing.lastActivityAt = Date.now();
56
- existing.lastProgress = {
57
- summary: event.summary,
58
- lastToolName: event.lastToolName,
59
- usage: event.usage,
60
- };
61
- const text = existing.taskType === 'monitor_mcp'
62
- ? event.summary ?? event.description
63
- : [event.lastToolName, event.description].filter(Boolean).join(' · ');
64
- if (text)
65
- pushUpdate(existing, text);
66
- return existing;
67
- }
68
- case 'updated': {
69
- const existing = tasks.get(event.taskId);
70
- if (!existing)
71
- return undefined;
72
- existing.lastActivityAt = Date.now();
73
- if (event.status)
74
- existing.status = event.status;
75
- if (event.isBackgrounded !== undefined)
76
- existing.isBackgrounded = event.isBackgrounded;
77
- if (event.error !== undefined)
78
- existing.error = event.error;
79
- if (event.endTime !== undefined)
80
- existing.endedAt = event.endTime;
81
- return existing;
82
- }
83
- case 'notification': {
84
- const existing = tasks.get(event.taskId);
85
- if (!existing) {
86
- // Notification for an unknown task — synthesise a minimal record
87
- const synthetic = {
88
- id: event.taskId,
89
- description: '(unknown task)',
90
- status: event.status,
91
- isBackgrounded: false,
92
- skipTranscript: false,
93
- startedAt: Date.now(),
94
- lastActivityAt: Date.now(),
95
- endedAt: Date.now(),
96
- outputFile: event.outputFile,
97
- finalSummary: event.summary,
98
- };
99
- tasks.set(event.taskId, synthetic);
100
- return synthetic;
101
- }
102
- existing.status = event.status;
103
- existing.outputFile = event.outputFile;
104
- existing.finalSummary = event.summary;
105
- existing.endedAt = existing.endedAt ?? Date.now();
106
- if (event.usage) {
107
- existing.lastProgress = {
108
- ...existing.lastProgress,
109
- usage: event.usage,
110
- };
111
- }
112
- return existing;
113
- }
114
- }
23
+ /** Record a task claude has just started. */
24
+ start(sessionKey, task) {
25
+ const state = {
26
+ id: task.taskId,
27
+ description: task.description,
28
+ ...(task.command !== undefined ? { command: task.command } : {}),
29
+ taskType: task.taskType,
30
+ toolUseId: task.toolUseId,
31
+ startedAt: task.startedAt ?? Date.now(),
32
+ lastActivityAt: Date.now(),
33
+ };
34
+ this.getOrCreateMap(sessionKey).set(task.taskId, state);
35
+ return state;
115
36
  }
116
37
  /**
117
38
  * Remove a finished task from the tracker. Call once the completion
@@ -126,10 +47,7 @@ class TaskTracker {
126
47
  this.sessionTasks.delete(sessionKey);
127
48
  }
128
49
  }
129
- /**
130
- * Record something a task did that arrived outside an SDK progress event:
131
- * a PTY monitor firing. Unknown tasks are ignored.
132
- */
50
+ /** Record something a task reported: a monitor firing. Unknown tasks are ignored. */
133
51
  noteUpdate(sessionKey, taskId, text, at = Date.now()) {
134
52
  const task = this.sessionTasks.get(sessionKey)?.get(taskId);
135
53
  if (!task)
@@ -137,32 +55,35 @@ class TaskTracker {
137
55
  task.lastActivityAt = at;
138
56
  pushUpdate(task, text, at);
139
57
  }
140
- getTask(sessionKey, taskId) {
141
- return this.sessionTasks.get(sessionKey)?.get(taskId);
58
+ /** Record claude's own id for a task, once the launching call has returned it. */
59
+ setClaudeTaskId(sessionKey, taskId, claudeTaskId) {
60
+ const task = this.sessionTasks.get(sessionKey)?.get(taskId);
61
+ if (task)
62
+ task.claudeTaskId = claudeTaskId;
142
63
  }
143
- getTasks(sessionKey) {
64
+ /** The task claude knows by `claudeTaskId`, if its launching call reported it. */
65
+ findByClaudeTaskId(sessionKey, claudeTaskId) {
144
66
  const tasks = this.sessionTasks.get(sessionKey);
145
- return tasks ? Array.from(tasks.values()) : [];
67
+ if (!tasks)
68
+ return undefined;
69
+ for (const task of tasks.values())
70
+ if (task.claudeTaskId === claudeTaskId)
71
+ return task;
72
+ return undefined;
73
+ }
74
+ getTask(sessionKey, taskId) {
75
+ return this.sessionTasks.get(sessionKey)?.get(taskId);
146
76
  }
147
77
  /**
148
- * Tasks currently running in the background
149
- * (is_backgrounded=true, status not in a terminal state).
150
- * Drives the streaming UI's "in background" footer.
78
+ * The session's tasks running in the background, oldest first. Drives
79
+ * `/tasks` and the streaming UI's "in background" footer.
151
80
  */
152
- getBackgroundedTasks(sessionKey) {
81
+ getTasks(sessionKey) {
153
82
  const tasks = this.sessionTasks.get(sessionKey);
154
- if (!tasks)
155
- return [];
156
- const result = [];
157
- for (const task of tasks.values()) {
158
- if (task.isBackgrounded && (task.status === 'running' || task.status === 'pending')) {
159
- result.push(task);
160
- }
161
- }
162
- return result;
83
+ return tasks ? Array.from(tasks.values()) : [];
163
84
  }
164
85
  getBackgroundedCount(sessionKey) {
165
- return this.getBackgroundedTasks(sessionKey).length;
86
+ return this.sessionTasks.get(sessionKey)?.size ?? 0;
166
87
  }
167
88
  /** Background tasks still running across every session. */
168
89
  getBackgroundedTotal() {
@@ -172,18 +93,16 @@ class TaskTracker {
172
93
  return total;
173
94
  }
174
95
  /**
175
- * True when at least one Monitor task is currently running. Used to detect
176
- * SDK sub-turns that are triggered by monitor events so the bot can surface
177
- * the model's echoed event line as its own Telegram message.
96
+ * True when at least one Monitor task is currently running. The idle reaper
97
+ * asks: a pty with a monitor armed isn't idle, however quiet it is.
178
98
  */
179
99
  hasActiveMonitor(sessionKey) {
180
100
  const tasks = this.sessionTasks.get(sessionKey);
181
101
  if (!tasks)
182
102
  return false;
183
103
  for (const task of tasks.values()) {
184
- if (task.taskType === 'monitor_mcp' && (task.status === 'running' || task.status === 'pending')) {
104
+ if (task.taskType === 'monitor_mcp')
185
105
  return true;
186
- }
187
106
  }
188
107
  return false;
189
108
  }
@@ -27,7 +27,7 @@ export const TOOL_ICONS = {
27
27
  WebSearch: '🔎',
28
28
  // Notebook
29
29
  NotebookEdit: '📓',
30
- // TeleCoder MCP tools — keys are the SDK-reported full names so
30
+ // TeleCoder MCP tools — keys are the full names Claude Code reports so
31
31
  // updateToolOperation/getToolIcon match without any extra normalization.
32
32
  'mcp__telecoder-tools__telecoder_ask_user': '❓',
33
33
  'mcp__telecoder-tools__telecoder_set_topic': '🏷️',
@@ -35,7 +35,6 @@ export const TOOL_ICONS = {
35
35
  'mcp__telecoder-tools__telecoder_list_projects': '📂',
36
36
  'mcp__telecoder-tools__telecoder_switch_project': '🔀',
37
37
  'mcp__telecoder-tools__telecoder_create_bot': '🤖',
38
- 'mcp__telecoder-tools__telecoder_publish_telegraph': '📄',
39
38
  // Status indicators
40
39
  thinking: '💭',
41
40
  complete: '✅',
@@ -345,7 +344,6 @@ export function getToolAction(toolName) {
345
344
  'mcp__telecoder-tools__telecoder_list_projects': 'Listing projects',
346
345
  'mcp__telecoder-tools__telecoder_switch_project': 'Switching project',
347
346
  'mcp__telecoder-tools__telecoder_create_bot': 'Creating bot',
348
- 'mcp__telecoder-tools__telecoder_publish_telegraph': 'Publishing Telegraph',
349
347
  };
350
348
  if (actions[toolName])
351
349
  return actions[toolName];
@@ -401,8 +399,6 @@ export function extractToolDetail(toolName, input, verbose) {
401
399
  case 'mcp__telecoder-tools__telecoder_switch_project':
402
400
  case 'mcp__telecoder-tools__telecoder_create_bot':
403
401
  return str('project_name');
404
- case 'mcp__telecoder-tools__telecoder_publish_telegraph':
405
- return str('title');
406
402
  default:
407
403
  return undefined;
408
404
  }
@@ -35,7 +35,7 @@ const titleSchema = z.object({
35
35
  /** 'user' names are never touched; 'implicit' and 'bot' ones are ours to replace. */
36
36
  owner: z.enum(['implicit', 'bot', 'user']),
37
37
  name: z.string().optional(),
38
- /** Goes in front of every name we give the thread, e.g. 🍴 for a fork's. */
38
+ /** Goes in front of every name we give the thread, e.g. 🌱 for a branch's. */
39
39
  prefix: z.string().optional(),
40
40
  });
41
41
  const fileSchema = z.object({ threads: z.record(z.string(), titleSchema) });
@@ -45,6 +45,8 @@ let threads;
45
45
  let api;
46
46
  const lastRenameAt = new Map();
47
47
  const pending = new Map();
48
+ /** editForumTopic calls not yet answered. */
49
+ let renamesInFlight = 0;
48
50
  function state() {
49
51
  if (!threads) {
50
52
  ensureStateDir(STATE_DIR, 'ThreadTitles');
@@ -129,13 +131,26 @@ async function rename(sessionKey, name) {
129
131
  return;
130
132
  const { chatId, threadId } = parseSessionKey(sessionKey);
131
133
  lastRenameAt.set(sessionKey, Date.now());
134
+ renamesInFlight++;
132
135
  try {
133
136
  await api.editForumTopic(chatId, threadId, { name });
134
- record(sessionKey, { owner: 'bot', name, ...(current?.prefix ? { prefix: current.prefix } : {}) });
137
+ // Read again: the prefix may have changed while the call was out.
138
+ const prefix = state()[sessionKey]?.prefix;
139
+ record(sessionKey, { owner: 'bot', name, ...(prefix ? { prefix } : {}) });
135
140
  }
136
141
  catch (err) {
137
142
  console.debug(`[ThreadTitles] Failed to rename ${sessionKey}:`, err instanceof Error ? err.message : err);
138
143
  }
144
+ finally {
145
+ renamesInFlight--;
146
+ }
147
+ }
148
+ /**
149
+ * Renames still to make: held for the cooldown, or on their way to Telegram.
150
+ * For /botrebuild's "when idle", which would otherwise restart over them.
151
+ */
152
+ export function renamesOutstanding() {
153
+ return pending.size + renamesInFlight;
139
154
  }
140
155
  /**
141
156
  * Pass a new session topic on to the thread's name. A no-op outside private
@@ -165,6 +180,62 @@ export function syncThreadTitle(sessionKey, topic, project) {
165
180
  timer.unref?.();
166
181
  pending.set(sessionKey, { name, timer });
167
182
  }
183
+ /**
184
+ * Put `mark` in front of the thread's name, or take it off, and rename the
185
+ * thread now rather than after the cooldown: it's what the user just asked
186
+ * for. The mark joins the prefix, so every later rename keeps it, next to a
187
+ * branch's 🌱. A name the user chose is left as it is.
188
+ *
189
+ * 'renamed' when the thread now has the name, 'user-named' for a name that's
190
+ * the user's, 'unnamed' for a thread the bot doesn't name (a group's topic,
191
+ * one it has never seen a name for) or a rename Telegram refused.
192
+ */
193
+ export async function markThreadName(sessionKey, mark, on) {
194
+ const current = state()[sessionKey];
195
+ if (!api || !isPrivateThread(sessionKey) || !current?.name)
196
+ return 'unnamed';
197
+ if (current.owner === 'user')
198
+ return 'user-named';
199
+ const oldPrefix = current.prefix ?? '';
200
+ const rest = oldPrefix.startsWith(mark) ? oldPrefix.slice(mark.length) : oldPrefix;
201
+ const prefix = on ? mark + rest : rest;
202
+ // A rename held for the cooldown carries the newer topic: that one goes now.
203
+ const held = pending.get(sessionKey);
204
+ if (held)
205
+ clearTimeout(held.timer);
206
+ pending.delete(sessionKey);
207
+ const latest = held?.name ?? current.name;
208
+ const base = latest.startsWith(oldPrefix) ? latest.slice(oldPrefix.length) : latest;
209
+ const name = `${prefix}${base}`.slice(0, MAX_NAME_LENGTH);
210
+ const next = { ...current };
211
+ if (prefix)
212
+ next.prefix = prefix;
213
+ else
214
+ delete next.prefix;
215
+ record(sessionKey, next);
216
+ await rename(sessionKey, name);
217
+ return state()[sessionKey]?.name === name ? 'renamed' : 'unnamed';
218
+ }
219
+ /** The thread's name as last seen or set, for naming it in a message. */
220
+ export function threadDisplayName(sessionKey) {
221
+ return state()[sessionKey]?.name;
222
+ }
223
+ /** Whether the thread still has the name Telegram gave it on creation from the "All" view. */
224
+ export function hasImplicitName(sessionKey) {
225
+ return state()[sessionKey]?.owner === 'implicit';
226
+ }
227
+ /** Drop what's kept about a thread that no longer exists, and any rename still waiting for it. */
228
+ export function forgetThreadTitle(sessionKey) {
229
+ const held = pending.get(sessionKey);
230
+ if (held)
231
+ clearTimeout(held.timer);
232
+ pending.delete(sessionKey);
233
+ lastRenameAt.delete(sessionKey);
234
+ if (!state()[sessionKey])
235
+ return;
236
+ delete state()[sessionKey];
237
+ writeJsonFile(STATE_FILE, { threads: state() }, 'ThreadTitles');
238
+ }
168
239
  /** Start naming threads on `bot`. Call once, after auth, before the handlers. */
169
240
  export function initThreadTitles(bot) {
170
241
  api = bot.api;
@@ -186,5 +257,6 @@ export function resetThreadTitlesForTest(testApi) {
186
257
  for (const { timer } of pending.values())
187
258
  clearTimeout(timer);
188
259
  pending.clear();
260
+ renamesInFlight = 0;
189
261
  }
190
262
  //# sourceMappingURL=thread-titles.js.map
@@ -54,7 +54,7 @@ async function check(bot) {
54
54
  save({ ...state, done: true });
55
55
  console.log('[ThreadsSetup] Threads are on');
56
56
  if (state.chatId !== undefined) {
57
- await bot.api.sendMessage(state.chatId, '✅ Threads are on. Start one from the bot\'s "All" view, or with 🍴 Fork; each is its own conversation, named after what it\'s about.');
57
+ await bot.api.sendMessage(state.chatId, '✅ Threads are on. Start one from the bot\'s "All" view, or with 🌱 Branch; each is its own conversation, named after what it\'s about.');
58
58
  }
59
59
  }
60
60
  function watch(bot) {
@@ -5,7 +5,7 @@
5
5
  * `ALLOWED_USER_IDS` can do everything. That is the right model for a bot with
6
6
  * one user, and it stops being right the moment the bot is shared. An approval
7
7
  * prompt the person who triggered it can tap themselves is not an approval, and
8
- * a guest who can `/restartbot` or flip the transport can step around every
8
+ * a guest who can `/botrestart` or flip the transport can step around every
9
9
  * guardrail the owner configured.
10
10
  *
11
11
  * `ADMIN_USER_IDS` names the subset that keeps those unrestricted rights. Left
@@ -135,7 +135,7 @@ export function hasGuestUsers() {
135
135
  const admins = getAdminIds();
136
136
  return allAllowedUserIds().some((id) => !admins.includes(id));
137
137
  }
138
- /** The allowed users who are not admins. Used by `/permissions` to report the split. */
138
+ /** The allowed users who are not admins. Used by `/gate` to report the split. */
139
139
  export function getGuestIds() {
140
140
  const admins = getAdminIds();
141
141
  return allAllowedUserIds().filter((id) => !admins.includes(id));