telecoder 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
@@ -0,0 +1,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 works the same for both transports, and
9
+ * it is also what lets a restored session 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 the SDK transport's tool-end signal is not sent
168
+ // for every 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,209 @@
1
+ /**
2
+ * Tracks Claude Agent SDK background tasks per session.
3
+ *
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.
8
+ */
9
+ /** Updates kept per task: the footer shares the status bubble, so only the latest few. */
10
+ const MAX_TASK_UPDATES = 3;
11
+ class TaskTracker {
12
+ sessionTasks = new Map();
13
+ getOrCreateMap(sessionKey) {
14
+ let tasks = this.sessionTasks.get(sessionKey);
15
+ if (!tasks) {
16
+ tasks = new Map();
17
+ this.sessionTasks.set(sessionKey, tasks);
18
+ }
19
+ return tasks;
20
+ }
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
+ }
115
+ }
116
+ /**
117
+ * Remove a finished task from the tracker. Call once the completion
118
+ * notification has been delivered to the user.
119
+ */
120
+ remove(sessionKey, taskId) {
121
+ const tasks = this.sessionTasks.get(sessionKey);
122
+ if (!tasks)
123
+ return;
124
+ tasks.delete(taskId);
125
+ if (tasks.size === 0) {
126
+ this.sessionTasks.delete(sessionKey);
127
+ }
128
+ }
129
+ /**
130
+ * Record something a task did that arrived outside an SDK progress event:
131
+ * a PTY monitor firing. Unknown tasks are ignored.
132
+ */
133
+ noteUpdate(sessionKey, taskId, text, at = Date.now()) {
134
+ const task = this.sessionTasks.get(sessionKey)?.get(taskId);
135
+ if (!task)
136
+ return;
137
+ task.lastActivityAt = at;
138
+ pushUpdate(task, text, at);
139
+ }
140
+ getTask(sessionKey, taskId) {
141
+ return this.sessionTasks.get(sessionKey)?.get(taskId);
142
+ }
143
+ getTasks(sessionKey) {
144
+ const tasks = this.sessionTasks.get(sessionKey);
145
+ return tasks ? Array.from(tasks.values()) : [];
146
+ }
147
+ /**
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.
151
+ */
152
+ getBackgroundedTasks(sessionKey) {
153
+ 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;
163
+ }
164
+ getBackgroundedCount(sessionKey) {
165
+ return this.getBackgroundedTasks(sessionKey).length;
166
+ }
167
+ /** Background tasks still running across every session. */
168
+ getBackgroundedTotal() {
169
+ let total = 0;
170
+ for (const sessionKey of this.sessionTasks.keys())
171
+ total += this.getBackgroundedCount(sessionKey);
172
+ return total;
173
+ }
174
+ /**
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.
178
+ */
179
+ hasActiveMonitor(sessionKey) {
180
+ const tasks = this.sessionTasks.get(sessionKey);
181
+ if (!tasks)
182
+ return false;
183
+ for (const task of tasks.values()) {
184
+ if (task.taskType === 'monitor_mcp' && (task.status === 'running' || task.status === 'pending')) {
185
+ return true;
186
+ }
187
+ }
188
+ return false;
189
+ }
190
+ clear(sessionKey) {
191
+ this.sessionTasks.delete(sessionKey);
192
+ }
193
+ }
194
+ function pushUpdate(task, text, at = Date.now()) {
195
+ const line = text.replace(/\s+/g, ' ').trim();
196
+ if (!line)
197
+ return;
198
+ const updates = task.updates ?? [];
199
+ // A repeat says nothing new; moving its time up keeps the footer honest
200
+ // about when the task last spoke.
201
+ const last = updates[updates.length - 1];
202
+ if (last?.text === line)
203
+ last.at = at;
204
+ else
205
+ updates.push({ at, text: line });
206
+ task.updates = updates.slice(-MAX_TASK_UPDATES);
207
+ }
208
+ export const taskTracker = new TaskTracker();
209
+ //# sourceMappingURL=task-tracker.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Per-chat Telegraph settings — controls whether long replies are offloaded to
3
+ * a Telegraph page instead of being split across Telegram messages.
4
+ */
5
+ import { z } from 'zod';
6
+ import { config } from '../config.js';
7
+ import { createKeyedSettings } from '../utils/keyed-settings.js';
8
+ const store = createKeyedSettings({
9
+ file: 'telegraph-settings.json',
10
+ label: 'Telegraph',
11
+ entrySchema: z.object({ enabled: z.boolean().optional() }),
12
+ normalize: (stored) => ({
13
+ // Default to the global config value if not set
14
+ enabled: typeof stored?.enabled === 'boolean' ? stored.enabled : config.TELEGRAPH_ENABLED,
15
+ }),
16
+ });
17
+ export function getTelegraphSettings(sessionKey) {
18
+ return store.get(sessionKey);
19
+ }
20
+ export function setTelegraphEnabled(sessionKey, enabled) {
21
+ store.update(sessionKey, { enabled });
22
+ }
23
+ /**
24
+ * Whether this chat publishes to Telegraph. The global switch wins: a chat
25
+ * that turned it on while TELEGRAPH_ENABLED was true stops publishing the
26
+ * moment the owner turns it off, since every page is public.
27
+ */
28
+ export function isTelegraphEnabled(sessionKey) {
29
+ return config.TELEGRAPH_ENABLED && store.get(sessionKey).enabled;
30
+ }
31
+ //# sourceMappingURL=telegraph-settings.js.map