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
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Claude Code's /cd, followed: when a chat's session moves to another working
3
+ * directory, the bot moves with it.
4
+ *
5
+ * /cd (Claude Code's own; it reaches the pty like any command the bot doesn't
6
+ * have) keeps the conversation and relocates its transcript to the new
7
+ * directory's project slot under ~/.claude/projects. Left alone, the bot
8
+ * would go on reading the transcript where it was — /branch, /history,
9
+ * /resend, /tree, the background relay — and its next respawn would
10
+ * `claude --resume` in the old directory, where the session no longer is.
11
+ *
12
+ * Claude Code runs the CwdChanged hook with old_cwd and new_cwd. That hook may
13
+ * fire for a working-directory change that moves nothing, so the bot follows
14
+ * only once the transcript is in the new directory's slot, and the move is
15
+ * then what the transcript says, not what the hook does.
16
+ */
17
+ import * as path from 'path';
18
+ import { registerIpcHandler } from './ipc-server.js';
19
+ import { sessionManager } from './session-manager.js';
20
+ import { claudeSessionFileExists } from './session-jsonl.js';
21
+ import { onSessionMoved as moveMonitorWatcher } from './monitor-relay.js';
22
+ import { getSessionTopic, setSessionTopic } from '../bot/handlers/command/topic-store.js';
23
+ const listeners = new Set();
24
+ /** Have `listener` told of every move this module follows. The pty provider keeps its live pty's directory this way. */
25
+ export function onSessionMove(listener) {
26
+ listeners.add(listener);
27
+ }
28
+ /** How long, and how often, to look for the transcript in its new slot after the hook. */
29
+ const LOOK_FOR_MS = 5_000;
30
+ const LOOK_EVERY_MS = 250;
31
+ /**
32
+ * Follow `claudeSessionId` to `newCwd` if it is the chat's session, the move
33
+ * is new, and its transcript is there (now, or within LOOK_FOR_MS: the hook
34
+ * and the relocation aren't ordered). Resolves to whether it followed.
35
+ */
36
+ export async function followSessionMove(sessionKey, claudeSessionId, newCwd, { lookForMs = LOOK_FOR_MS, lookEveryMs = LOOK_EVERY_MS } = {}) {
37
+ const deadline = Date.now() + lookForMs;
38
+ for (;;) {
39
+ const session = sessionManager.getSession(sessionKey);
40
+ if (!session || session.claudeSessionId !== claudeSessionId)
41
+ return false;
42
+ if (session.workingDirectory === newCwd)
43
+ return false;
44
+ if (claudeSessionFileExists(newCwd, claudeSessionId))
45
+ break;
46
+ if (Date.now() >= deadline)
47
+ return false;
48
+ await new Promise((resolve) => setTimeout(resolve, lookEveryMs));
49
+ }
50
+ sessionManager.moveSession(sessionKey, newCwd);
51
+ moveMonitorWatcher(sessionKey, newCwd);
52
+ for (const listener of listeners)
53
+ listener(sessionKey, newCwd);
54
+ // The thread's name carries the project: setting the topic again renames it.
55
+ setSessionTopic(sessionKey, getSessionTopic(sessionKey) ?? '');
56
+ console.log(`[SessionMove] ${sessionKey} followed /cd to ${path.basename(newCwd)}`);
57
+ return true;
58
+ }
59
+ registerIpcHandler('/hook/cwdChanged', (turn, body) => {
60
+ const claudeSessionId = typeof body.session_id === 'string' ? body.session_id : undefined;
61
+ const newCwd = typeof body.new_cwd === 'string' ? body.new_cwd : undefined;
62
+ if (claudeSessionId && newCwd) {
63
+ // Not awaited: the hook only reports, and claude shouldn't wait on the look.
64
+ void followSessionMove(turn.sessionKey, claudeSessionId, newCwd).catch((err) => {
65
+ console.error('[SessionMove] failed:', err instanceof Error ? err.message : err);
66
+ });
67
+ }
68
+ return { ok: true };
69
+ }, { betweenTurns: true });
70
+ //# sourceMappingURL=session-move.js.map
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The permission gate for Claude Code's shell mode.
3
+ *
4
+ * A prompt whose first character is `!` never reaches the model. Claude Code
5
+ * runs the rest of it as a shell command, and because that is not a tool call
6
+ * it raises no PreToolUse hook: measured on 2.1.326, a pasted `!echo x > f`
7
+ * wrote the file and the only hook that fired was Stop. The gate and the scope
8
+ * guard live in that hook, so neither saw a command someone typed themselves.
9
+ * On a shared bot a guest's `!sudo …` ran where Claude's own `sudo` would have
10
+ * waited for an admin.
11
+ *
12
+ * So such a message is put to the gate here, as the Bash call it amounts to,
13
+ * before it is typed into the pty. Everything else is the gate's: off on a
14
+ * solo bot, the same patterns and paths, the same people to answer, the same
15
+ * auto-approve window. An admin's `!` is checked as an admin's turn is.
16
+ */
17
+ import { gateToolCall } from './permission-gate.js';
18
+ /** What the approval prompt names as the tool: the command was typed, not Claude's. */
19
+ export const SHELL_MODE_LABEL = '! shell mode';
20
+ /**
21
+ * The command a prompt runs in shell mode, or undefined for an ordinary prompt.
22
+ *
23
+ * Measured against the same CLI: only a `!` in the very first position
24
+ * switches the editor to shell mode (` !echo x` stayed a prompt), and a
25
+ * multi-line message runs whole as one script, also when it is long enough to
26
+ * be collapsed into a `[Pasted text]` chip. So everything after the `!` is the
27
+ * command.
28
+ */
29
+ export function shellModeCommand(prompt) {
30
+ if (!prompt.startsWith('!'))
31
+ return undefined;
32
+ const command = prompt.slice(1).trim();
33
+ return command === '' ? undefined : command;
34
+ }
35
+ /**
36
+ * Put a `!command` to the permission gate before it runs. Anything else, and
37
+ * everything while the gate is off, proceeds untouched.
38
+ */
39
+ export async function screenShellCommand(ctx, sessionKey, prompt) {
40
+ const command = shellModeCommand(prompt);
41
+ if (command === undefined)
42
+ return { proceed: true, message: '', approved: false };
43
+ const decision = await gateToolCall({
44
+ sessionKey,
45
+ toolName: 'Bash',
46
+ toolInput: { command },
47
+ telegramCtx: ctx,
48
+ toolLabel: SHELL_MODE_LABEL,
49
+ });
50
+ if (decision.block) {
51
+ console.log(`[ShellModeGate] blocked session:${sessionKey} user:${ctx?.from?.id ?? '?'}`);
52
+ return {
53
+ proceed: false,
54
+ message: `🔐 ${decision.reason.replace(/\.$/, '')}. Nothing ran.`,
55
+ approved: false,
56
+ };
57
+ }
58
+ return { proceed: true, message: '', approved: decision.approvedByPerson === true };
59
+ }
60
+ //# sourceMappingURL=shell-mode-gate.js.map
@@ -1,11 +1,10 @@
1
1
  /**
2
- * PTY-mode side questions for `/btw`.
2
+ * Side questions for `/btw`.
3
3
  *
4
- * SDK mode answers side questions through the live `Query` object's
5
- * `askSideQuestion()`. PTY mode has no such handle — the conversation lives
6
- * inside a real `claude` CLI process driven through a pseudo-terminal, and
7
- * typing into it mid-turn would just queue a normal prompt (i.e. interrupt the
8
- * task, which is exactly what `/btw` promises not to do).
4
+ * The conversation lives inside a real `claude` CLI process driven through a
5
+ * pseudo-terminal, and typing into it mid-turn would just queue a normal
6
+ * prompt (i.e. interrupt the task, which is exactly what `/btw` promises not
7
+ * to do).
9
8
  *
10
9
  * Instead we answer from a throwaway fork of the live session:
11
10
  *
@@ -19,12 +18,13 @@
19
18
  * so the live session's transcript is never touched.
20
19
  *
21
20
  * `stream-json` makes the fork narrate its own tool calls on stdout, which is
22
- * how `/btw` shows live progress. Nothing else is needed for that — no hooks,
23
- * no MCP, no IPC — because we already own the child process.
21
+ * how `/btw` shows live progress. Nothing of the bot's is needed for that — no
22
+ * hooks, no MCP server, no IPC — because we already own the child process.
24
23
  */
25
24
  import { execFile } from 'child_process';
25
+ import { resolvePtyClaudeBin } from '../utils/resolve-claude-bin.js';
26
+ import { userSetupIsolationArgs } from './pty-spawn-config.js';
26
27
  import { sessionJsonlPath } from './session-jsonl.js';
27
- import { config } from '../config.js';
28
28
  import * as fs from 'fs';
29
29
  /** Same shape claude uses for session ids; also guards the execFile argv. */
30
30
  const SESSION_ID_RE = /^[a-zA-Z0-9_-]{8,128}$/;
@@ -148,9 +148,9 @@ function consumeStreamRecord(record, state, onProgress) {
148
148
  });
149
149
  }
150
150
  }
151
- function runClaude(args, cwd, timeoutMs, onProgress) {
151
+ function runClaude(executable, args, cwd, timeoutMs, onProgress) {
152
152
  return new Promise((resolve, reject) => {
153
- const child = execFile(process.env.CLAUDE_BIN || config.CLAUDE_EXECUTABLE_PATH, args, { cwd, timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, env: process.env }, (error, stdout, stderr) => {
153
+ const child = execFile(executable, args, { cwd, timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, env: process.env }, (error, stdout, stderr) => {
154
154
  if (error) {
155
155
  const message = (stderr || error.message).trim();
156
156
  reject(new SideQuestionError(message || 'Failed to run claude'));
@@ -188,6 +188,7 @@ function runClaude(args, cwd, timeoutMs, onProgress) {
188
188
  */
189
189
  export async function askForkedSideQuestion(opts) {
190
190
  const { question, sessionId, cwd, onProgress } = opts;
191
+ const executable = opts.executable ?? resolvePtyClaudeBin();
191
192
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
192
193
  const startedAt = Date.now();
193
194
  if (!SESSION_ID_RE.test(sessionId)) {
@@ -200,10 +201,12 @@ export async function askForkedSideQuestion(opts) {
200
201
  '-p', question,
201
202
  '--resume', sessionId,
202
203
  '--fork-session',
203
- // Mirror PTY mode: project/local settings only, no user-level config.
204
- '--setting-sources', 'project,local',
205
- // No MCP servers — the fork must not be able to message Telegram.
206
- '--strict-mcp-config',
204
+ // The account's own Claude Code setup, or not, as the pty it forks from
205
+ // has it: the same instructions, default model and plugins, and the
206
+ // servers those plugins' hooks send claude to. Never the bot's own MCP
207
+ // server, which no flag here names — the fork must not be able to message
208
+ // Telegram.
209
+ ...userSetupIsolationArgs(),
207
210
  // The fork inherits the live session's bypassed permissions so tool calls
208
211
  // resolve instead of hanging on approval; the disallow list below is what
209
212
  // actually keeps it read-only.
@@ -227,14 +230,14 @@ export async function askForkedSideQuestion(opts) {
227
230
  };
228
231
  let result;
229
232
  try {
230
- result = extractAnswer(await runClaude(streamArgs, cwd, timeoutMs, trackProgress));
233
+ result = extractAnswer(await runClaude(executable, streamArgs, cwd, timeoutMs, trackProgress));
231
234
  }
232
235
  catch (error) {
233
236
  const message = error instanceof Error ? error.message : String(error);
234
237
  if (!isUnknownOptionError(message))
235
238
  throw error;
236
239
  console.warn('[btw] CLI rejected the streaming flags — retrying without progress');
237
- result = extractAnswer(await runClaude(fallbackArgs, cwd, timeoutMs));
240
+ result = extractAnswer(await runClaude(executable, fallbackArgs, cwd, timeoutMs));
238
241
  if (result.forkSessionId && result.forkSessionId !== sessionId) {
239
242
  try {
240
243
  fs.rmSync(sessionJsonlPath(cwd, result.forkSessionId), { force: true });
@@ -21,11 +21,11 @@ export function imageExtension(mediaType) {
21
21
  * Make every attachment reachable from the prompt text — exactly once.
22
22
  *
23
23
  * Claude turns an image path it finds in a pasted prompt into an `[Image #N]`
24
- * chip and takes the path back out of the text. That is how a pty-mode upload
25
- * gets the same vision semantics as sdk mode, and it needs no Read tool. But
26
- * it fires once per distinct file, so staging a second copy of a picture the
27
- * caller had already saved attached the same image twice: double the image
28
- * tokens, and a note left reading "Saved at:" with nothing after it.
24
+ * chip and takes the path back out of the text. That is how an upload reaches
25
+ * the model as an image, and it needs no Read tool. But it fires once per
26
+ * distinct file, so staging a second copy of a picture the caller had already
27
+ * saved attached the same image twice: double the image tokens, and a note
28
+ * left reading "Saved at:" with nothing after it.
29
29
  *
30
30
  * So an image the caller already wrote to disk and named in the prompt needs
31
31
  * nothing from us. Only an attachment with no on-disk copy is staged to /tmp,
@@ -9,34 +9,63 @@
9
9
  * predates a bot restart.
10
10
  *
11
11
  * Two shapes, decided by claude, not by us. With several tasks it opens on the
12
- * list:
12
+ * list (2.1.311 shown; up to 2.1.226 the rows read `sleep 500 (running)` with
13
+ * no bullet or status column):
13
14
  *
14
- * ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
15
- * Background
16
- * 2 active shells
15
+ * ────────────────────────────────────────────────────────────
16
+ * Background
17
+ * 3 active shells
17
18
  *
18
- * ❯ sleep 500 (running)
19
- * sleep 400 (running)
19
+ * ❯ ● sleep 100 running
20
+ * ● sleep 150 running
21
+ * ● for i in $(seq 1 40); do echo "line $i";… running
20
22
  *
21
- * ↑/↓ to select · Enter to view · x to stop · Esc to close
23
+ * Earlier in this session (0)
22
24
  *
23
- * With exactly one it opens that task's detail instead (Status / Runtime /
24
- * Command / Output, ending in a `← to go back …` hint). Both are worth
25
- * relaying, so we take whichever we're given rather than forcing one.
25
+ * ↑/↓ to select · Enter to view · x to stop · Esc to close
26
26
  *
27
- * Anchor: the overlay is always preceded by a full-width run of `▔` (U+2594).
28
- * That glyph is specific to it — the input box and separators use `─` (U+2500)
29
- * — so the last such rule in the buffer marks where the overlay starts, with
30
- * everything above it being scrollback. Returns null when no overlay is found,
31
- * which callers surface as "couldn't read it" rather than guessing.
27
+ * With exactly one it opens that task's detail instead, which Enter on a row
28
+ * opens too:
29
+ *
30
+ * Shell details
31
+ *
32
+ * Status: running
33
+ * Runtime: 22s
34
+ * Command: for i in $(seq 1 40); do echo "line $i"; sleep 2; done
35
+ *
36
+ * Output:
37
+ * ╭──────────────────────────────────────────────────────────╮
38
+ * │ line 4 │
39
+ * │ line 5 │
40
+ * ╰──────────────────────────────────────────────────────────╯
41
+ * Showing 9 lines
42
+ *
43
+ * ← to go back · Esc/Enter/Space to close · x to stop
44
+ *
45
+ * Anchor: the overlay sits under a full-width rule, and while it is open the
46
+ * input box (two rules around a `❯` row) is not drawn, so the lowest rule in
47
+ * the buffer is the overlay's — with everything above it being scrollback. Up
48
+ * to 2.1.226 that rule was `▔` (U+2594), a glyph nothing else used; 2.1.311
49
+ * draws it with the same `─` (U+2500) as the input box, so the body under the
50
+ * lowest rule has to identify itself: it opens with `Background` or a `…
51
+ * details` title. Returns null when no overlay is found, which callers
52
+ * surface as "couldn't read it" rather than guessing.
32
53
  */
33
54
  /** The overlay's top rule. Full-width in practice; 10 is a safe floor. */
34
- const OVERLAY_RULE_RE = /^▔{10,}$/;
55
+ const OVERLAY_RULE_RE = /^(?:▔{10,}|─{10,})$/;
56
+ /**
57
+ * What the overlay's body opens with. `Background` is the list (and the idle
58
+ * view); `Shell details`, `Agent details`, … are a task. The status lines
59
+ * under a closed overlay's input box open with neither, which is what keeps
60
+ * them from being read as an overlay.
61
+ */
62
+ const HEADING_RE = /^(?:Background|\S.* details)$/;
35
63
  /**
36
64
  * The trailing keyboard-hint line ("… Esc to close"). Useless over Telegram —
37
65
  * there's no keyboard attached — so it gets dropped. Both shapes end in
38
- * "to close"; the leading-glyph alternatives guard against a task whose own
39
- * text happens to contain that phrase.
66
+ * "to close" or carry on past it ("… Esc/Enter/Space to close · x to stop");
67
+ * the leading-glyph alternatives guard against a task whose own text happens
68
+ * to contain that phrase.
40
69
  */
41
70
  const HINT_RE = /(?:↑\/↓|←|Esc|Enter)\s.*\bto close\b/;
42
71
  /**
@@ -55,8 +84,9 @@ function dedent(lines) {
55
84
  }
56
85
  export function scrapeTasksOverlay(screenText) {
57
86
  const lines = screenText.split('\n');
58
- // Scan bottom-up: the overlay is pinned to the bottom, and an earlier rule
59
- // could survive in scrollback from a previous invocation.
87
+ // The lowest rule, and only that one: the overlay is pinned to the bottom,
88
+ // and a rule higher up is the input box's or an earlier overlay's, still in
89
+ // scrollback. Reading past the lowest one would hand back stale data.
60
90
  let ruleIndex = -1;
61
91
  for (let i = lines.length - 1; i >= 0; i--) {
62
92
  if (OVERLAY_RULE_RE.test(lines[i].trim())) {
@@ -85,10 +115,103 @@ export function scrapeTasksOverlay(screenText) {
85
115
  .trim();
86
116
  if (!text)
87
117
  return null;
118
+ if (!HEADING_RE.test(text.split('\n', 1)[0].trim()))
119
+ return null;
88
120
  // claude's own wording for the idle case. Matched loosely so a phrasing
89
121
  // change degrades to "not empty" (we show the text) rather than a wrong
90
122
  // "nothing running".
91
123
  const empty = /\bno (?:tasks|shells|agents)\b.*\brunning\b/i.test(text);
92
124
  return { text, empty };
93
125
  }
126
+ /**
127
+ * A row: a `●` bullet, the label, and (2.1.311) two or more spaces before
128
+ * the status word. The `Earlier in this session (0)` section heading carries
129
+ * no bullet, so it isn't one.
130
+ */
131
+ const ROW_RE = /^\s*●\s+(.+?)(?:\s{2,}(\S+))?\s*$/;
132
+ /**
133
+ * The list's rows, top to bottom. Cursor position `i` in the TUI is `i`
134
+ * presses of ↓ from the top, which is what makes the index worth having.
135
+ * Empty for a detail view, the idle view, or a layout without bullets.
136
+ */
137
+ export function parseTaskRows(overlayText) {
138
+ const rows = [];
139
+ for (const line of overlayText.split('\n')) {
140
+ const m = ROW_RE.exec(line);
141
+ if (!m)
142
+ continue;
143
+ const raw = m[1].trim();
144
+ const truncated = /(?:…|\.\.\.)$/.test(raw);
145
+ rows.push({
146
+ label: truncated ? raw.replace(/(?:…|\.\.\.)$/, '').trimEnd() : raw,
147
+ status: m[2] ?? '',
148
+ truncated,
149
+ });
150
+ }
151
+ return rows;
152
+ }
153
+ const DETAIL_TITLE_RE = /^\S.* details$/;
154
+ const FIELD_RE = /^([A-Z][\w ]*):\s+(.*)$/;
155
+ const OUTPUT_HEADING_RE = /^Output:\s*$/;
156
+ /** The output box's top and bottom edges. */
157
+ const BOX_EDGE_RE = /^[╭╰]─*[╮╯]\s*$/;
158
+ /** A line inside the box: `│ text │`. */
159
+ const BOX_LINE_RE = /^│ ?(.*?)\s*│?\s*$/;
160
+ const NO_OUTPUT_RE = /^no output available$/i;
161
+ /**
162
+ * A task's detail view, or null when the overlay text is the list. The
163
+ * fields are kept as drawn rather than mapped to known names, so a field
164
+ * added in a later release shows up instead of vanishing.
165
+ */
166
+ export function parseTaskDetail(overlayText) {
167
+ const lines = overlayText.split('\n');
168
+ const title = lines[0]?.trim() ?? '';
169
+ if (!DETAIL_TITLE_RE.test(title))
170
+ return null;
171
+ const fields = [];
172
+ const outputLines = [];
173
+ let note;
174
+ let inOutput = false;
175
+ let inBox = false;
176
+ for (const line of lines.slice(1)) {
177
+ if (!inOutput) {
178
+ if (OUTPUT_HEADING_RE.test(line.trim())) {
179
+ inOutput = true;
180
+ continue;
181
+ }
182
+ const m = FIELD_RE.exec(line.trim());
183
+ if (m)
184
+ fields.push({ label: m[1], value: m[2].trim() });
185
+ continue;
186
+ }
187
+ const trimmed = line.trim();
188
+ if (BOX_EDGE_RE.test(trimmed)) {
189
+ inBox = !inBox;
190
+ continue;
191
+ }
192
+ if (inBox) {
193
+ const m = BOX_LINE_RE.exec(trimmed);
194
+ outputLines.push(m ? m[1] : trimmed);
195
+ continue;
196
+ }
197
+ if (trimmed === '')
198
+ continue;
199
+ if (NO_OUTPUT_RE.test(trimmed))
200
+ continue;
201
+ // Under the box: `Showing 9 lines`. Before any box: output drawn bare.
202
+ if (outputLines.length > 0)
203
+ note = trimmed;
204
+ else
205
+ outputLines.push(trimmed);
206
+ }
207
+ while (outputLines.length > 0 && outputLines[outputLines.length - 1].trim() === '') {
208
+ outputLines.pop();
209
+ }
210
+ return {
211
+ title,
212
+ fields,
213
+ output: outputLines.length > 0 ? outputLines.join('\n') : null,
214
+ ...(note !== undefined ? { note } : {}),
215
+ };
216
+ }
94
217
  //# sourceMappingURL=tasks-overlay-scraper.js.map
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Haiku's guess at which threads /threadcleanup can delete: for each, whether the
3
+ * work in it looks finished or has loose ends.
4
+ *
5
+ * One call for every thread at once, so a cleanup of thirty threads starts one
6
+ * claude, not thirty. All Haiku sees of a thread is what the chat history
7
+ * keeps: its topic, the last thing the user said and the end of the last
8
+ * reply. That's enough to tell "done, pushed" from "want me to go on?".
9
+ *
10
+ * The guess only decides which threads start ticked. The user reads the list
11
+ * and confirms, so a wrong guess costs a tap. Any failure (timeout, a reply
12
+ * out of format) gives no guess, and /threadcleanup says so.
13
+ */
14
+ import { query } from '@anthropic-ai/claude-agent-sdk';
15
+ import { sideCallOptions } from './side-call-options.js';
16
+ const JUDGE_TIMEOUT_MS = 45_000;
17
+ const MAX_USER_CHARS = 300;
18
+ const MAX_REPLY_CHARS = 600;
19
+ const INSTRUCTIONS = 'Each numbered item below is a chat thread between a user and a coding agent: its topic, the user\'s last ' +
20
+ 'message and the end of the agent\'s last reply. For each, decide whether the work looks finished (DONE) or ' +
21
+ 'has loose ends the user may still want to come back to (OPEN): the agent asked a question or offered a next ' +
22
+ 'step that wasn\'t taken up, work was left half done, something failed, or a plan was agreed but not carried out.\n' +
23
+ 'When in doubt, answer OPEN.\n' +
24
+ 'Output one line per item, nothing else, in the form "<number>: DONE" or "<number>: OPEN".\n\n';
25
+ function clip(text, max, fromEnd = false) {
26
+ const flat = (text ?? '').replace(/\s+/g, ' ').trim();
27
+ if (flat.length <= max)
28
+ return flat;
29
+ return fromEnd ? '…' + flat.slice(flat.length - max) : flat.slice(0, max) + '…';
30
+ }
31
+ export function buildJudgePrompt(threads) {
32
+ const items = threads.map((t, i) => [
33
+ `${i + 1}.`,
34
+ `Topic: ${clip(t.topic, 120) || '(none)'}`,
35
+ `User: ${clip(t.lastUserMessage, MAX_USER_CHARS) || '(nothing)'}`,
36
+ `Agent: ${clip(t.lastReply, MAX_REPLY_CHARS, true) || '(nothing)'}`,
37
+ ].join('\n'));
38
+ return INSTRUCTIONS + items.join('\n\n');
39
+ }
40
+ /** The verdicts in a reply, by item; an item Haiku skipped stays undefined. */
41
+ export function parseVerdicts(reply, count) {
42
+ const verdicts = new Array(count).fill(undefined);
43
+ for (const line of reply.split('\n')) {
44
+ const m = /^\s*(\d+)\s*[:.)-]\s*\**\s*(DONE|OPEN)\b/i.exec(line);
45
+ if (!m)
46
+ continue;
47
+ const index = Number(m[1]) - 1;
48
+ if (index >= 0 && index < count)
49
+ verdicts[index] = m[2].toLowerCase();
50
+ }
51
+ return verdicts;
52
+ }
53
+ /** A verdict per thread, or undefined when Haiku gave none at all. */
54
+ export async function judgeThreads(threads) {
55
+ if (threads.length === 0)
56
+ return [];
57
+ const controller = new AbortController();
58
+ const timer = setTimeout(() => controller.abort(), JUDGE_TIMEOUT_MS);
59
+ try {
60
+ const response = query({
61
+ prompt: buildJudgePrompt(threads),
62
+ options: sideCallOptions('You sort chat threads into finished and unfinished.', controller),
63
+ });
64
+ let collected = '';
65
+ for await (const message of response) {
66
+ if (message.type === 'assistant') {
67
+ for (const block of message.message.content) {
68
+ if (block.type === 'text')
69
+ collected += block.text;
70
+ }
71
+ }
72
+ if (message.type === 'result')
73
+ break;
74
+ }
75
+ const verdicts = parseVerdicts(collected, threads.length);
76
+ return verdicts.some((v) => v !== undefined) ? verdicts : undefined;
77
+ }
78
+ catch (err) {
79
+ if (!controller.signal.aborted) {
80
+ console.debug('[ThreadJudge] Haiku side-call failed:', err instanceof Error ? err.message : err);
81
+ }
82
+ return undefined;
83
+ }
84
+ finally {
85
+ clearTimeout(timer);
86
+ }
87
+ }
88
+ //# sourceMappingURL=thread-judge-haiku.js.map
@@ -9,10 +9,9 @@
9
9
  * /plugin install frontend-design@claude-plugins-official
10
10
  *
11
11
  * These tips are bundled into the CLI (with client-side relevance + per-session
12
- * cooldown logic) and never surface through the SDK event stream — they exist
13
- * only in the live render. In PTY mode we already feed that render into an
14
- * @xterm/headless buffer, so we can pull the tip back out and mirror it in the
15
- * Telegram status indicator, exactly as Claude Code shows it.
12
+ * cooldown logic) and exist only in the live render. We already feed that
13
+ * render into an @xterm/headless buffer, so we can pull the tip back out and
14
+ * mirror it in the Telegram status indicator, exactly as Claude Code shows it.
16
15
  *
17
16
  * Detection: the spinner tip is rendered with a `⎿` tree connector preceding
18
17
  * `Tip:`. That connector is the discriminator that distinguishes it from the