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,367 @@
1
+ /**
2
+ * Claude Code's task list, mirrored into the chat.
3
+ *
4
+ * Claude Code keeps the list with four tools: TaskCreate and TaskUpdate write
5
+ * it, TaskList and TaskGet read it. None of their inputs carries the whole list
6
+ * (TodoWrite, which they replaced, sent the complete array on every call), so
7
+ * the list is read from where Claude Code stores it: one JSON file per task in
8
+ * `~/.claude/tasks/<session id>/`. That is also what lets a restored session
9
+ * show the list it left off with.
10
+ *
11
+ * The rendering copies the CLI's own task panel (2.1.322, the component that
12
+ * draws `N tasks (X done, Y in progress, Z open)`):
13
+ *
14
+ * 3 tasks (1 done, 1 in progress, 1 open)
15
+ * ✔ Write the changelog completed: struck through, dimmed
16
+ * ◼ Run the tests in progress: bold
17
+ * ◻ Tag the release › blocked by #2 pending; the note lists open blockers
18
+ *
19
+ * The rows show the subject (never `activeForm`), sorted by numeric id. The
20
+ * header is dimmed with its counts in bold, and "in progress" is left out when
21
+ * nothing is. Telegram has no dim, so dimmed text is italic here; the TUI's
22
+ * colours (green tick, orange square) have no equivalent either.
23
+ */
24
+ import * as fs from 'fs';
25
+ import * as os from 'os';
26
+ import * as path from 'path';
27
+ import { GrammyError } from 'grammy';
28
+ import { EntityText } from './entities.js';
29
+ import { sendFormatted, editFormatted } from './send.js';
30
+ import { parseSessionKey } from '../utils/session-key.js';
31
+ import { sessionManager } from '../claude/session-manager.js';
32
+ /** The tools that change the list; a call to one means the card is stale. */
33
+ export const TASK_WRITE_TOOLS = new Set(['TaskCreate', 'TaskUpdate']);
34
+ /** Every task-list tool, reads included. */
35
+ export const TASK_TOOLS = new Set(['TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet']);
36
+ // Claude Code's `figures`: tick, squareSmallFilled, squareSmall, pointerSmall.
37
+ // Each square and the tick also exist as emoji, which some Telegram clients
38
+ // draw in colour at emoji size; U+FE0E asks for the text glyph the TUI shows.
39
+ const TEXT_STYLE = '\uFE0E';
40
+ const GLYPHS = {
41
+ completed: `✔${TEXT_STYLE}`,
42
+ in_progress: `◼${TEXT_STYLE}`,
43
+ pending: `◻${TEXT_STYLE}`,
44
+ };
45
+ const POINTER_SMALL = '›';
46
+ /** Where Claude Code keeps a session's task list (its `tasks/<id>` directory). */
47
+ export function taskListDir(claudeSessionId) {
48
+ const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
49
+ // Claude Code sanitises the list id the same way before using it as a name.
50
+ return path.join(configDir, 'tasks', claudeSessionId.replace(/[^a-zA-Z0-9_-]/g, '-'));
51
+ }
52
+ /** Claude Code's own order: numeric ids numerically, anything else by name. */
53
+ function compareIds(a, b) {
54
+ const x = parseInt(a, 10);
55
+ const y = parseInt(b, 10);
56
+ if (!Number.isNaN(x) && !Number.isNaN(y))
57
+ return x - y;
58
+ return a.localeCompare(b);
59
+ }
60
+ const STATUSES = new Set(['pending', 'in_progress', 'completed']);
61
+ function stringList(value) {
62
+ return Array.isArray(value) ? value.filter((v) => typeof v === 'string') : [];
63
+ }
64
+ /** One task file's contents, or null if it isn't a task. */
65
+ export function parseTask(raw) {
66
+ let data;
67
+ try {
68
+ data = JSON.parse(raw);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ if (!data || typeof data !== 'object')
74
+ return null;
75
+ const t = data;
76
+ if (typeof t.id !== 'string' || typeof t.subject !== 'string')
77
+ return null;
78
+ if (typeof t.status !== 'string' || !STATUSES.has(t.status))
79
+ return null;
80
+ return {
81
+ id: t.id,
82
+ subject: t.subject,
83
+ description: typeof t.description === 'string' ? t.description : undefined,
84
+ activeForm: typeof t.activeForm === 'string' ? t.activeForm : undefined,
85
+ status: t.status,
86
+ blocks: stringList(t.blocks),
87
+ blockedBy: stringList(t.blockedBy),
88
+ owner: typeof t.owner === 'string' ? t.owner : undefined,
89
+ };
90
+ }
91
+ /**
92
+ * Read a session's task list. A missing directory is an empty list. A file
93
+ * that won't parse is left out and reported as `partial`: Claude Code may be
94
+ * writing it at that moment, so the caller can look again shortly.
95
+ */
96
+ export function readTaskList(claudeSessionId, dir = taskListDir(claudeSessionId)) {
97
+ let names;
98
+ try {
99
+ names = fs.readdirSync(dir);
100
+ }
101
+ catch {
102
+ return { tasks: [], partial: false };
103
+ }
104
+ const tasks = [];
105
+ let partial = false;
106
+ // Claude Code's own filter: `.lock` and its other dotfiles are not tasks.
107
+ for (const name of names) {
108
+ if (!name.endsWith('.json') || name.startsWith('.'))
109
+ continue;
110
+ let raw;
111
+ try {
112
+ raw = fs.readFileSync(path.join(dir, name), 'utf-8');
113
+ }
114
+ catch {
115
+ // Deleted between the listing and the read: Claude Code clears a list
116
+ // file by file. Not partial — the next read won't find it either.
117
+ continue;
118
+ }
119
+ const task = parseTask(raw);
120
+ if (task)
121
+ tasks.push(task);
122
+ else
123
+ partial = true;
124
+ }
125
+ tasks.sort((a, b) => compareIds(a.id, b.id));
126
+ return { tasks, partial };
127
+ }
128
+ /** The list as Claude Code's task panel draws it, or null when there is none. */
129
+ export function renderTaskList(tasks) {
130
+ if (tasks.length === 0)
131
+ return null;
132
+ const sorted = [...tasks].sort((a, b) => compareIds(a.id, b.id));
133
+ const done = sorted.filter((t) => t.status === 'completed').length;
134
+ const open = sorted.filter((t) => t.status === 'pending').length;
135
+ const inProgress = sorted.length - done - open;
136
+ // A blocker only counts while it is a task on the list that isn't done.
137
+ const unfinished = new Set(sorted.filter((t) => t.status !== 'completed').map((t) => t.id));
138
+ const b = new EntityText();
139
+ b.wrap('italic', (h) => {
140
+ h.bold(String(sorted.length)).add(' tasks (').bold(String(done)).add(' done, ');
141
+ if (inProgress > 0)
142
+ h.bold(String(inProgress)).add(' in progress, ');
143
+ h.bold(String(open)).add(' open)');
144
+ });
145
+ for (const task of sorted) {
146
+ b.newline().add(`${GLYPHS[task.status]} `);
147
+ const subject = task.subject.trim() || `#${task.id}`;
148
+ if (task.status === 'completed')
149
+ b.strikethrough(subject);
150
+ else if (task.status === 'in_progress')
151
+ b.bold(subject);
152
+ else
153
+ b.add(subject);
154
+ const blockers = task.blockedBy.filter((id) => unfinished.has(id)).sort(compareIds);
155
+ if (blockers.length > 0) {
156
+ b.italic(` ${POINTER_SMALL} blocked by ${blockers.map((id) => `#${id}`).join(', ')}`);
157
+ }
158
+ }
159
+ return b.build();
160
+ }
161
+ /** Read and render in one step; null when the session has no tasks. */
162
+ export function renderSessionTaskList(claudeSessionId) {
163
+ return renderTaskList(readTaskList(claudeSessionId).tasks);
164
+ }
165
+ // After a TaskCreate/TaskUpdate starts, look at the files this long after —
166
+ // again and again while nothing has changed, since the write lands some time
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
+ const DIRTY_RECHECK_MS = [300, 1000, 2500, 5000];
170
+ // A file caught mid-write is read again after this long, this many times;
171
+ // after that it is taken to be broken for good and left out.
172
+ const PARTIAL_RETRY_MS = 250;
173
+ const PARTIAL_RETRY_MAX = 8;
174
+ function isNotModified(err) {
175
+ return err instanceof GrammyError && err.description.includes('message is not modified');
176
+ }
177
+ /**
178
+ * One live task-list card per session: posted on the turn's first change,
179
+ * edited in place on every later one, and posted afresh in the next turn.
180
+ */
181
+ export class TaskListDisplay {
182
+ states = new Map();
183
+ postListener = null;
184
+ getClaudeSessionId;
185
+ read;
186
+ constructor(options = {}) {
187
+ this.getClaudeSessionId = options.getClaudeSessionId
188
+ ?? ((sessionKey) => sessionManager.getSession(sessionKey)?.claudeSessionId);
189
+ this.read = options.read ?? ((id) => readTaskList(id));
190
+ }
191
+ /**
192
+ * Called for every new card a live refresh posts, timer-driven ones included
193
+ * — the message sender counts those as posts that bury the status bubble.
194
+ */
195
+ onPost(listener) {
196
+ this.postListener = listener;
197
+ }
198
+ state(sessionKey) {
199
+ let s = this.states.get(sessionKey);
200
+ if (!s) {
201
+ s = {
202
+ messageId: null, lastText: '', newTurn: false, dirty: false, recheck: 0, partialRetries: 0,
203
+ timer: null, chain: Promise.resolve(false), api: null,
204
+ };
205
+ this.states.set(sessionKey, s);
206
+ }
207
+ return s;
208
+ }
209
+ /** A new turn: its first change to the list posts a new card. */
210
+ startTurn(sessionKey) {
211
+ const s = this.states.get(sessionKey);
212
+ if (!s)
213
+ return;
214
+ s.newTurn = true;
215
+ }
216
+ /**
217
+ * A tool started. A TaskCreate or TaskUpdate marks the card stale and
218
+ * schedules a look at the files; anything else is ignored.
219
+ */
220
+ noteToolStart(api, sessionKey, toolName, claudeSessionId) {
221
+ if (!TASK_WRITE_TOOLS.has(toolName))
222
+ return;
223
+ const s = this.state(sessionKey);
224
+ s.api = api;
225
+ s.claudeSessionId = claudeSessionId;
226
+ s.dirty = true;
227
+ s.recheck = 0;
228
+ s.partialRetries = 0;
229
+ this.schedule(sessionKey, DIRTY_RECHECK_MS[0]);
230
+ }
231
+ /** A tool finished (no name is known here): refresh now if a write was pending. */
232
+ noteToolEnd(sessionKey) {
233
+ const s = this.states.get(sessionKey);
234
+ if (!s?.dirty || !s.api)
235
+ return;
236
+ this.schedule(sessionKey, 0);
237
+ }
238
+ /** Stop the timers of a session whose turn is over, after one last look. */
239
+ async flush(sessionKey) {
240
+ const s = this.states.get(sessionKey);
241
+ if (!s?.dirty || !s.api)
242
+ return false;
243
+ this.cancelTimer(s);
244
+ const posted = await this.refresh(s.api, sessionKey, s.claudeSessionId);
245
+ s.dirty = false;
246
+ this.cancelTimer(s);
247
+ return posted;
248
+ }
249
+ /** Forget a session entirely (e.g. on /clear). */
250
+ reset(sessionKey) {
251
+ const s = this.states.get(sessionKey);
252
+ if (s)
253
+ this.cancelTimer(s);
254
+ this.states.delete(sessionKey);
255
+ }
256
+ cancelTimer(s) {
257
+ if (s.timer)
258
+ clearTimeout(s.timer);
259
+ s.timer = null;
260
+ }
261
+ schedule(sessionKey, delayMs) {
262
+ const s = this.state(sessionKey);
263
+ this.cancelTimer(s);
264
+ s.timer = setTimeout(() => {
265
+ s.timer = null;
266
+ if (!s.api)
267
+ return;
268
+ this.refresh(s.api, sessionKey, s.claudeSessionId).catch((err) => {
269
+ console.error('[TaskList] Refresh failed:', err instanceof Error ? err.message : err);
270
+ });
271
+ }, delayMs);
272
+ s.timer.unref?.();
273
+ }
274
+ /**
275
+ * Draw the session's list: post it on the turn's first change, edit the card
276
+ * after that, and do nothing when it would read the same. Returns whether a
277
+ * new message was posted.
278
+ */
279
+ refresh(api, sessionKey, claudeSessionId) {
280
+ const s = this.state(sessionKey);
281
+ s.api = api;
282
+ if (claudeSessionId !== undefined)
283
+ s.claudeSessionId = claudeSessionId;
284
+ const run = s.chain.then(() => this.doRefresh(api, sessionKey, s), () => this.doRefresh(api, sessionKey, s));
285
+ s.chain = run.catch(() => false);
286
+ return run;
287
+ }
288
+ async doRefresh(api, sessionKey, s) {
289
+ // Resolved on every refresh: /resume can move the key to another session.
290
+ const id = s.claudeSessionId ?? this.getClaudeSessionId(sessionKey);
291
+ if (!id)
292
+ return false;
293
+ const read = this.read(id);
294
+ // A file still unreadable after the retries is broken, not mid-write.
295
+ const partial = read.partial && s.partialRetries < PARTIAL_RETRY_MAX;
296
+ const message = renderTaskList(read.tasks);
297
+ const sameSession = s.shownFor === id;
298
+ const changed = !!message && (!sameSession || message.text !== s.lastText);
299
+ // Called from a timer (or with none pending) while a write is unseen:
300
+ // decide whether to look again.
301
+ if (s.dirty && !s.timer) {
302
+ if (partial) {
303
+ s.partialRetries += 1;
304
+ this.schedule(sessionKey, PARTIAL_RETRY_MS);
305
+ }
306
+ else if (changed || s.recheck + 1 >= DIRTY_RECHECK_MS.length) {
307
+ s.dirty = false;
308
+ }
309
+ else {
310
+ s.recheck += 1;
311
+ this.schedule(sessionKey, DIRTY_RECHECK_MS[s.recheck]);
312
+ }
313
+ }
314
+ // Don't draw a list with a task missing because its file was mid-write;
315
+ // the retry above draws it whole.
316
+ if (partial || !message || !changed)
317
+ return false;
318
+ const { chatId, threadId } = parseSessionKey(sessionKey);
319
+ if (s.messageId !== null && !s.newTurn && sameSession) {
320
+ try {
321
+ await editFormatted(api, chatId, s.messageId, message);
322
+ s.lastText = message.text;
323
+ return false;
324
+ }
325
+ catch (err) {
326
+ if (isNotModified(err)) {
327
+ s.lastText = message.text;
328
+ return false;
329
+ }
330
+ // Deleted, or too old to edit: post a fresh card below.
331
+ console.warn('[TaskList] Edit failed, posting a new card:', err instanceof Error ? err.message : err);
332
+ }
333
+ }
334
+ const sent = await sendFormatted(api, chatId, message, threadId !== undefined ? { message_thread_id: threadId } : {});
335
+ s.messageId = sent.message_id;
336
+ s.lastText = message.text;
337
+ s.shownFor = id;
338
+ s.newTurn = false;
339
+ this.postListener?.(sessionKey);
340
+ return true;
341
+ }
342
+ /**
343
+ * Post a restored session's whole list, if it has one. The card is not
344
+ * adopted for live edits: the session's next change posts its own, below
345
+ * whatever the restore printed after this. Returns whether it posted.
346
+ */
347
+ async showRestored(api, sessionKey, claudeSessionId) {
348
+ if (!claudeSessionId)
349
+ return false;
350
+ const message = renderTaskList(this.read(claudeSessionId).tasks);
351
+ if (!message)
352
+ return false;
353
+ const { threadId, chatId } = parseSessionKey(sessionKey);
354
+ try {
355
+ await sendFormatted(api, chatId, message, threadId !== undefined ? { message_thread_id: threadId } : {});
356
+ }
357
+ catch (err) {
358
+ console.error('[TaskList] Failed to show restored list:', err instanceof Error ? err.message : err);
359
+ return false;
360
+ }
361
+ // A live card from before belongs above the restore; the next change gets a new one.
362
+ this.startTurn(sessionKey);
363
+ return true;
364
+ }
365
+ }
366
+ export const taskListDisplay = new TaskListDisplay();
367
+ //# sourceMappingURL=task-list.js.map
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Tracks the work each session has running in the background: monitors,
3
+ * backgrounded shells, subagents and workflows.
4
+ *
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.
10
+ */
11
+ /** Updates kept per task: the footer shares the status bubble, so only the latest few. */
12
+ const MAX_TASK_UPDATES = 3;
13
+ class TaskTracker {
14
+ sessionTasks = new Map();
15
+ getOrCreateMap(sessionKey) {
16
+ let tasks = this.sessionTasks.get(sessionKey);
17
+ if (!tasks) {
18
+ tasks = new Map();
19
+ this.sessionTasks.set(sessionKey, tasks);
20
+ }
21
+ return tasks;
22
+ }
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;
36
+ }
37
+ /**
38
+ * Remove a finished task from the tracker. Call once the completion
39
+ * notification has been delivered to the user.
40
+ */
41
+ remove(sessionKey, taskId) {
42
+ const tasks = this.sessionTasks.get(sessionKey);
43
+ if (!tasks)
44
+ return;
45
+ tasks.delete(taskId);
46
+ if (tasks.size === 0) {
47
+ this.sessionTasks.delete(sessionKey);
48
+ }
49
+ }
50
+ /** Record something a task reported: a monitor firing. Unknown tasks are ignored. */
51
+ noteUpdate(sessionKey, taskId, text, at = Date.now()) {
52
+ const task = this.sessionTasks.get(sessionKey)?.get(taskId);
53
+ if (!task)
54
+ return;
55
+ task.lastActivityAt = at;
56
+ pushUpdate(task, text, at);
57
+ }
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;
63
+ }
64
+ /** The task claude knows by `claudeTaskId`, if its launching call reported it. */
65
+ findByClaudeTaskId(sessionKey, claudeTaskId) {
66
+ const tasks = this.sessionTasks.get(sessionKey);
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);
76
+ }
77
+ /**
78
+ * The session's tasks running in the background, oldest first. Drives
79
+ * `/tasks` and the streaming UI's "in background" footer.
80
+ */
81
+ getTasks(sessionKey) {
82
+ const tasks = this.sessionTasks.get(sessionKey);
83
+ return tasks ? Array.from(tasks.values()) : [];
84
+ }
85
+ getBackgroundedCount(sessionKey) {
86
+ return this.sessionTasks.get(sessionKey)?.size ?? 0;
87
+ }
88
+ /** Background tasks still running across every session. */
89
+ getBackgroundedTotal() {
90
+ let total = 0;
91
+ for (const sessionKey of this.sessionTasks.keys())
92
+ total += this.getBackgroundedCount(sessionKey);
93
+ return total;
94
+ }
95
+ /**
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.
98
+ */
99
+ hasActiveMonitor(sessionKey) {
100
+ const tasks = this.sessionTasks.get(sessionKey);
101
+ if (!tasks)
102
+ return false;
103
+ for (const task of tasks.values()) {
104
+ if (task.taskType === 'monitor_mcp')
105
+ return true;
106
+ }
107
+ return false;
108
+ }
109
+ clear(sessionKey) {
110
+ this.sessionTasks.delete(sessionKey);
111
+ }
112
+ }
113
+ function pushUpdate(task, text, at = Date.now()) {
114
+ const line = text.replace(/\s+/g, ' ').trim();
115
+ if (!line)
116
+ return;
117
+ const updates = task.updates ?? [];
118
+ // A repeat says nothing new; moving its time up keeps the footer honest
119
+ // about when the task last spoke.
120
+ const last = updates[updates.length - 1];
121
+ if (last?.text === line)
122
+ last.at = at;
123
+ else
124
+ updates.push({ at, text: line });
125
+ task.updates = updates.slice(-MAX_TASK_UPDATES);
126
+ }
127
+ export const taskTracker = new TaskTracker();
128
+ //# sourceMappingURL=task-tracker.js.map