telecoder 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.env.example +142 -130
  2. package/CHANGELOG.md +683 -2
  3. package/README.md +36 -32
  4. package/dist/audio/transcribe.js +0 -9
  5. package/dist/bin/mcp-server.js +46 -61
  6. package/dist/bot/bot.js +162 -181
  7. package/dist/bot/command-catalog.js +263 -0
  8. package/dist/bot/deleted-threads.js +103 -0
  9. package/dist/bot/file-access.js +35 -26
  10. package/dist/bot/handlers/album.handler.js +128 -0
  11. package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
  12. package/dist/bot/handlers/command/access.js +1 -1
  13. package/dist/bot/handlers/command/admin.js +86 -110
  14. package/dist/bot/handlers/command/all-view.js +33 -0
  15. package/dist/bot/handlers/command/auto-approve.js +3 -3
  16. package/dist/bot/handlers/command/background.js +37 -0
  17. package/dist/bot/handlers/command/botname.js +76 -0
  18. package/dist/bot/handlers/command/btw.js +20 -69
  19. package/dist/bot/handlers/command/cleanup.js +329 -0
  20. package/dist/bot/handlers/command/model.js +40 -119
  21. package/dist/bot/handlers/command/prefs-scope.js +255 -90
  22. package/dist/bot/handlers/command/project.js +31 -109
  23. package/dist/bot/handlers/command/resume.js +8 -4
  24. package/dist/bot/handlers/command/session.js +74 -213
  25. package/dist/bot/handlers/command/settings.js +92 -447
  26. package/dist/bot/handlers/command/shared.js +32 -35
  27. package/dist/bot/handlers/command/tasks.js +263 -95
  28. package/dist/bot/handlers/command/thread.js +128 -0
  29. package/dist/bot/handlers/command/topic-store.js +14 -53
  30. package/dist/bot/handlers/command/topic.js +8 -61
  31. package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
  32. package/dist/bot/handlers/command-fallback.js +179 -0
  33. package/dist/bot/handlers/command.handler.js +96 -422
  34. package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
  35. package/dist/bot/handlers/media-fallback.js +12 -7
  36. package/dist/bot/handlers/message/replies.js +10 -87
  37. package/dist/bot/handlers/message/shared.js +9 -31
  38. package/dist/bot/handlers/message/turn-notify.js +15 -49
  39. package/dist/bot/handlers/message/turn-runner.js +18 -103
  40. package/dist/bot/handlers/message.handler.js +59 -52
  41. package/dist/bot/handlers/newbot.handler.js +13 -4
  42. package/dist/bot/handlers/photo.handler.js +88 -129
  43. package/dist/bot/handlers/prompts.handler.js +11 -11
  44. package/dist/bot/handlers/running-note.js +2 -2
  45. package/dist/bot/handlers/session-guard.js +4 -4
  46. package/dist/bot/handlers/suggestion.handler.js +2 -2
  47. package/dist/bot/handlers/tree.handler.js +20 -20
  48. package/dist/bot/handlers/voice.handler.js +23 -85
  49. package/dist/bot/kept-threads.js +51 -0
  50. package/dist/bot/middleware/album-collector.js +69 -0
  51. package/dist/bot/middleware/auth.middleware.js +1 -1
  52. package/dist/bot/middleware/group-mention.middleware.js +11 -5
  53. package/dist/bot/middleware/queued-messages.js +143 -32
  54. package/dist/bot/middleware/stale-filter.js +0 -22
  55. package/dist/build-info.json +5 -5
  56. package/dist/claude/ask-user-form.js +517 -0
  57. package/dist/claude/ask-user.js +94 -26
  58. package/dist/claude/auto-topic-haiku.js +17 -0
  59. package/dist/claude/available-commands.js +22 -19
  60. package/dist/claude/background-hint.js +91 -0
  61. package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
  62. package/dist/claude/carry-over.js +0 -2
  63. package/dist/claude/ccr-shim.js +12 -10
  64. package/dist/claude/claude-auth.js +6 -10
  65. package/dist/claude/command-parser.js +49 -43
  66. package/dist/claude/cost-overlay-scraper.js +7 -2
  67. package/dist/claude/effort-level.js +5 -0
  68. package/dist/claude/enabled-plugins.js +12 -16
  69. package/dist/claude/in-flight-tracker.js +21 -0
  70. package/dist/claude/mcp-bridge.js +86 -58
  71. package/dist/claude/memory-guard.js +400 -0
  72. package/dist/claude/message-offsets.js +5 -5
  73. package/dist/claude/modal-relay.js +401 -34
  74. package/dist/claude/model-catalog.js +20 -3
  75. package/dist/claude/monitor-relay.js +130 -15
  76. package/dist/claude/native-commands.js +40 -0
  77. package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
  78. package/dist/claude/permission-gate.js +11 -10
  79. package/dist/claude/permission-mode.js +19 -45
  80. package/dist/claude/prewarm.js +70 -0
  81. package/dist/claude/pty-idle-reaper.js +96 -0
  82. package/dist/claude/pty-provider.js +473 -188
  83. package/dist/claude/pty-spawn-config.js +79 -32
  84. package/dist/claude/pty-watch.js +201 -0
  85. package/dist/claude/request-queue.js +7 -35
  86. package/dist/claude/rewind.js +111 -0
  87. package/dist/claude/scheduled-runner.js +1 -3
  88. package/dist/claude/scheduler.js +6 -2
  89. package/dist/claude/scope-guard.js +8 -3
  90. package/dist/claude/screen-marks.js +83 -0
  91. package/dist/claude/screen-render.js +96 -0
  92. package/dist/claude/session-history.js +4 -2
  93. package/dist/claude/session-jsonl.js +162 -15
  94. package/dist/claude/session-manager.js +29 -8
  95. package/dist/claude/session-move.js +70 -0
  96. package/dist/claude/shell-mode-gate.js +60 -0
  97. package/dist/claude/side-question.js +20 -17
  98. package/dist/claude/stage-images.js +5 -5
  99. package/dist/claude/tasks-overlay-scraper.js +143 -20
  100. package/dist/claude/thread-judge-haiku.js +88 -0
  101. package/dist/claude/tip-scraper.js +3 -4
  102. package/dist/claude/tui-modal.js +272 -27
  103. package/dist/claude/tui-state.js +74 -2
  104. package/dist/claude/turn-end.js +15 -1
  105. package/dist/claude/turn-prose.js +1 -1
  106. package/dist/claude/typed-answer.js +104 -0
  107. package/dist/claude/update-banner-relay.js +1 -1
  108. package/dist/cli/commands/doctor.js +48 -15
  109. package/dist/cli/commands/help.js +11 -2
  110. package/dist/cli/commands/init.js +16 -13
  111. package/dist/cli/commands/service.js +40 -8
  112. package/dist/cli/commands/start.js +10 -0
  113. package/dist/cli/commands/watch.js +322 -0
  114. package/dist/cli/dispatch.js +5 -0
  115. package/dist/cli/init/env-file.js +1 -1
  116. package/dist/cli/init/flow.js +114 -47
  117. package/dist/cli/init/prompter.js +8 -0
  118. package/dist/cli/init/telegram.js +35 -9
  119. package/dist/cli/service/render.js +3 -3
  120. package/dist/config.js +156 -131
  121. package/dist/index.js +107 -31
  122. package/dist/launcher.js +34 -7
  123. package/dist/providers/ccr-introspect.js +1 -8
  124. package/dist/providers/ccr-provider.js +19 -20
  125. package/dist/providers/claude-provider.js +4 -57
  126. package/dist/providers/prefs-sync.js +16 -59
  127. package/dist/providers/provider-router.js +24 -23
  128. package/dist/providers/spawn-settings.js +45 -0
  129. package/dist/providers/user-preferences.js +127 -19
  130. package/dist/restart-when-idle.js +27 -7
  131. package/dist/startup/auto-continue.js +2 -2
  132. package/dist/startup/auto-resume.js +3 -15
  133. package/dist/startup/notices.js +1 -1
  134. package/dist/startup/verify-token.js +4 -4
  135. package/dist/telegram/action-logger.js +3 -165
  136. package/dist/telegram/background-activity-card.js +1 -1
  137. package/dist/telegram/botname-settings.js +71 -125
  138. package/dist/telegram/client-options.js +6 -7
  139. package/dist/telegram/force-reply-tracker.js +55 -16
  140. package/dist/telegram/message-sender.js +92 -360
  141. package/dist/telegram/prompt-label.js +11 -5
  142. package/dist/telegram/streaming-turn.js +5 -7
  143. package/dist/telegram/table-lists.js +56 -0
  144. package/dist/telegram/task-list.js +4 -4
  145. package/dist/telegram/task-tracker.js +45 -126
  146. package/dist/telegram/terminal-renderer.js +1 -5
  147. package/dist/telegram/thread-titles.js +74 -2
  148. package/dist/telegram/threads-setup.js +1 -1
  149. package/dist/utils/admins.js +2 -2
  150. package/dist/utils/bot-icon.js +248 -0
  151. package/dist/utils/bot-token.js +8 -5
  152. package/dist/utils/build-info.js +3 -3
  153. package/dist/utils/caffeinate.js +6 -3
  154. package/dist/utils/claude-env.js +0 -1
  155. package/dist/utils/claude-version.js +2 -2
  156. package/dist/utils/config-home.js +3 -3
  157. package/dist/utils/download.js +41 -15
  158. package/dist/utils/exit-codes.js +11 -0
  159. package/dist/utils/format.js +3 -6
  160. package/dist/utils/home-project.js +1 -1
  161. package/dist/utils/idle-restart.js +1 -1
  162. package/dist/utils/install-mode.js +1 -1
  163. package/dist/utils/instance-config.js +1 -1
  164. package/dist/utils/instances.js +1 -1
  165. package/dist/utils/keyed-settings.js +2 -2
  166. package/dist/utils/memory-pressure.js +60 -0
  167. package/dist/utils/npm-version.js +2 -2
  168. package/dist/utils/resolve-claude-bin.js +13 -24
  169. package/dist/utils/respawn-backoff.js +9 -0
  170. package/dist/utils/stale-launcher.js +1 -1
  171. package/dist/utils/systemd.js +8 -8
  172. package/dist/utils/telegram-proxy.js +72 -0
  173. package/dist/utils/uploads-dir.js +27 -0
  174. package/dist/utils/verbosity.js +8 -8
  175. package/dist/utils/version-check.js +5 -5
  176. package/package.json +3 -4
  177. package/dist/bot/handlers/command/media.js +0 -197
  178. package/dist/bot/handlers/command/streaming-mode.js +0 -16
  179. package/dist/bot/handlers/message/throttle.js +0 -49
  180. package/dist/claude/agent-watchdog.js +0 -162
  181. package/dist/claude/agent.js +0 -1458
  182. package/dist/claude/held-query.js +0 -190
  183. package/dist/claude/mcp-tools.js +0 -354
  184. package/dist/claude/sdk-permission-gate.js +0 -77
  185. package/dist/claude/session-cost.js +0 -41
  186. package/dist/claude/system-prompt.js +0 -162
  187. package/dist/providers/sdk-provider.js +0 -37
  188. package/dist/telegram/telegraph-settings.js +0 -31
  189. package/dist/telegram/telegraph.js +0 -453
  190. package/dist/telegram/terminal-settings.js +0 -25
  191. package/dist/tts/tts-settings.js +0 -62
  192. package/dist/tts/tts.js +0 -245
  193. package/dist/tts/voice-reply.js +0 -78
  194. package/dist/utils/debug-agent.js +0 -117
  195. package/dist/utils/debug-watchdog.js +0 -121
  196. package/dist/utils/project-data-dir.js +0 -33
  197. package/dist/utils/reasoning-summary.js +0 -12
@@ -1,10 +1,11 @@
1
1
  import { spawn } from 'node-pty';
2
2
  import headless from '@xterm/headless';
3
+ import { watchData, watchRegister, watchUnregister } from './pty-watch.js';
3
4
  import * as fs from 'fs';
4
5
  import { randomUUID } from 'crypto';
5
6
  import { config } from '../config.js';
6
7
  import { sessionManager } from './session-manager.js';
7
- import { claudeSessionFileExists, describeLogTail, sessionJsonlPath, readCommandReply, readLastApiErrorFromJsonl, readLastAssistantTurnText, readLastCompactionFromJsonl, readLastUsageFromJsonl, readLastUserPromptMarker, sessionJsonlMtimeMs, sessionJsonlSize } from './session-jsonl.js';
8
+ import { claudeSessionFileExists, describeLogTail, hasForeignThinkingSignatures, sessionJsonlPath, readCommandReply, readLastApiErrorFromJsonl, readLastAssistantTurnText, readLastCompactionFromJsonl, readLastUsageFromJsonl, readLastUserPromptMarker, readTurnEnded, sessionJsonlMtimeMs, sessionJsonlSize } from './session-jsonl.js';
8
9
  import { clearDeliveredProse, getDeliveredProse, stripDeliveredPrefix } from './turn-prose.js';
9
10
  import { PtyTurnStream, TurnProseReader } from './pty-stream.js';
10
11
  import { isNativeCompactCommand } from './command-parser.js';
@@ -19,39 +20,37 @@ import { getIpcPort, getIpcToken, IPC_TOKEN_ENV, registerActiveTurn, registerIpc
19
20
  // Side-effect import: registers /mcp/* IPC handlers that bridge the standalone
20
21
  // MCP subprocess back to bot-side state (Telegram API, session topic, …).
21
22
  import './mcp-bridge.js';
22
- import { onAsyncToolArmed, markTurnStart, markTurnEnd, markSelfTurnInterrupted, teardown as teardownMonitorRelay, relayPushNotification, classifyAsyncTool, movedToBackground } from './monitor-relay.js';
23
+ import { onAsyncToolArmed, markTurnStart, markTurnEnd, markSelfTurnInterrupted, teardown as teardownMonitorRelay, relayPushNotification, classifyAsyncTool, movedToBackground, noteClaudeTaskId, onTaskStopped } from './monitor-relay.js';
23
24
  import { relayUpdateBanner, scrapeUpdateBanner } from './update-banner-relay.js';
24
25
  import { gateToolCall, isPermissionGateEnabled, ALLOW_MARKER, DENY_MARKER_START, DENY_MARKER_END } from './permission-gate.js';
25
26
  import { sanitizeError } from '../utils/sanitize.js';
26
- import { buildSettingsJson, buildMcpConfigJson, buildMcpEnv, buildPtySystemPromptNote, } from './pty-spawn-config.js';
27
+ import { buildSettingsJson, buildMcpConfigJson, buildMcpEnv, buildPtySystemPromptNote, loadsUserSetup, userSetupIsolationArgs, } from './pty-spawn-config.js';
27
28
  import { getModelsForBinary } from './model-catalog.js';
28
29
  import { scrapePromptSuggestion } from './prompt-suggestion-scraper.js';
29
30
  import { scrapeTip } from './tip-scraper.js';
31
+ import { scrapeBackgroundHint, backgroundKeystroke } from './background-hint.js';
30
32
  import { clearPresses, hasInputBox, inputBoxHolds, inputBoxPastePlaceholders, inputBoxText, isGenerating, newPastePlaceholder, pastePlaceholderIds, pastePlaceholders, replyFromScreen, screenSignature, tailLines, } from './tui-state.js';
31
33
  import { stageImagesForPty } from './stage-images.js';
32
34
  import { blockingModal, openDialogError, relayDialog, } from './modal-relay.js';
33
35
  import { questionTimeoutMs } from './ask-user.js';
34
- import { ensurePermissionMode, permissionModeInfo, transportDefaultMode, } from './permission-mode.js';
36
+ import { ensurePermissionMode, permissionModeInfo, defaultPermissionMode, } from './permission-mode.js';
35
37
  import { parseModal } from './tui-modal.js';
38
+ import { screenMarks } from './screen-marks.js';
39
+ import { restoredPromptNeedle, restoresConversation, rewindFailure, rewindIn, rewindReport } from './rewind.js';
36
40
  import { claudeSetupScreen, ClaudeNotLoggedInError } from './claude-auth.js';
37
41
  import { dialogResumeState, turnHold } from './turn-end.js';
38
42
  import { isSuggestionsEnabled } from '../telegram/suggestions-settings.js';
39
- import { resolveBin } from '../utils/resolve-bin.js';
43
+ import { resolvePtyClaudeBin } from '../utils/resolve-claude-bin.js';
40
44
  import { withPendingCarryOver } from './carry-over.js';
45
+ import { onSessionMove } from './session-move.js';
41
46
  const { Terminal } = headless;
42
47
  // ---- Config from prototype --------------------------------------------------
43
48
  /**
44
- * Resolved, not left bare. node-pty execs this name directly, so a bare
45
- * `claude` is looked up in the *service's* PATH — and a systemd user unit gets
46
- * the bare default, without ~/.local/bin, which is where the native installer
47
- * puts the CLI. The failure is silent in the worst way: execvp writes "No such
48
- * file or directory" into the pty and exits, so the bot sees a session that
49
- * produced nothing and reports that the input box never appeared.
50
- *
51
- * resolveBin exists for this and searches ~/.local/bin first on Linux; it just
52
- * was never wired up here. CLAUDE_BIN still wins for a CLI kept elsewhere.
49
+ * Resolved, not left bare, so the exec finds it in a service's PATH too; see
50
+ * resolvePtyClaudeBin. CCR's wrapper script takes its place for a chat on CCR
51
+ * (AgentOptions.executableOverride).
53
52
  */
54
- const CLAUDE_BIN = process.env.CLAUDE_BIN || resolveBin('claude');
53
+ const CLAUDE_BIN = resolvePtyClaudeBin();
55
54
  // dist/claude/pty-provider.js → sibling dist/bin/mcp-server.js
56
55
  /**
57
56
  * How many lines of a stuck TUI to log. Enough for a dialog's title, its rows
@@ -72,6 +71,10 @@ const INPUT_BOX_COLS = COLS - 5;
72
71
  const CLEAR_PRESS_GAP_MS = 20;
73
72
  /** How long the TUI gets to redraw an emptied box before it's read or typed into. */
74
73
  const CLEAR_SETTLE_MS = 150;
74
+ /** How long a prompt `/rewind` hands back gets to show up in the input box. */
75
+ const REWIND_PROMPT_WAIT_MS = 2_000;
76
+ /** Rows of input box a restored prompt nobody saw is assumed to fill, for the clear before the next message. */
77
+ const MAX_RESTORED_PROMPT_ROWS = 16;
75
78
  const IDLE_MS = 1200;
76
79
  /**
77
80
  * Short window we wait *after* the Stop hook fires before extracting the
@@ -80,6 +83,15 @@ const IDLE_MS = 1200;
80
83
  * sometimes capture a half-rendered screen. 200ms is enough in practice.
81
84
  */
82
85
  const POST_STOP_SETTLE_MS = 200;
86
+ /**
87
+ * How long the pty has to stay quiet before a turn ends without Stop, when the
88
+ * session log doesn't show the turn's end either. Stop comes within a moment
89
+ * of claude writing its reply, so a turn that runs its course never waits this
90
+ * out. It bounds the wait for a Stop hook that was lost: the hook is a curl
91
+ * call fired and forgotten. Too short, and a pause in the middle of a reply
92
+ * ends the turn before the reply is written.
93
+ */
94
+ const STOP_WAIT_MS = 15_000;
83
95
  /**
84
96
  * How often a running turn's live prose is brought up to date (pty-stream.ts).
85
97
  * Often enough to catch a streaming block's growth before its head scrolls off
@@ -184,7 +196,7 @@ const DIALOG_RESUME_POLL_MS = 250;
184
196
  function stillWorkingError() {
185
197
  const minutes = Math.round(BUSY_READY_CEILING_MS / 60_000);
186
198
  return `Claude is still working on an earlier message — it's been going for over ${minutes} minutes, `
187
- + "so this one wasn't delivered. Send it again once that turn finishes, or /stop to cut it short.";
199
+ + "so this one wasn't delivered. Send it again once that turn finishes, or /cancel to cut it short.";
188
200
  }
189
201
  /**
190
202
  * After writing \r we confirm claude actually took the prompt — it appears in
@@ -204,6 +216,18 @@ const SUBMIT_RETRY_EVERY_MS = 3_000;
204
216
  const OVERLAY_PASTE_SETTLE_MS = 300;
205
217
  const OVERLAY_IDLE_MS = 700;
206
218
  const OVERLAY_MAX_MS = 8_000;
219
+ /**
220
+ * Gap between a keystroke into an open overlay and reading the screen. The
221
+ * overlay redraws a few hundred ms after a ↓ or Enter; a quiet-wait alone
222
+ * returns at once when stdout was already idle, and reads the old screen.
223
+ */
224
+ const OVERLAY_KEY_SETTLE_MS = 400;
225
+ /**
226
+ * How long moveToBackground watches for Claude Code's hint to leave the screen
227
+ * after the key press. The task row is redrawn within a few hundred ms.
228
+ */
229
+ const BACKGROUND_KEY_MS = 3_000;
230
+ const BACKGROUND_POLL_MS = 100;
207
231
  /**
208
232
  * The slice of a prompt we look for on the rendered screen: leading
209
233
  * non-whitespace of the first line, long enough to be distinctive. The box may
@@ -232,7 +256,7 @@ function pasteLineCount(prompt) {
232
256
  }
233
257
  /**
234
258
  * Idle + prompt-visible safety net for prompts that produce no JSONL activity.
235
- * Most prompts (model turns, /compact, /clear, /handoff, …) write at least one
259
+ * Most prompts (model turns, /compact, /clear, …) write at least one
236
260
  * record to the session log, so the JSONL-mtime gate resolves them cleanly.
237
261
  * Slash commands like /cost or /config emit purely TUI output without touching
238
262
  * the log; without this fallback those would hang until MAX_TURN_MS. 5s of
@@ -244,7 +268,7 @@ const NO_JSONL_FALLBACK_MS = 5_000;
244
268
  * Thrown by sendToAgent when Claude Code wrote a synthetic API-error record to
245
269
  * the session log for the just-finished turn (socket dropped, rate limit, …).
246
270
  * Surfaced as a distinct class so message handlers can show an API-error
247
- * banner instead of the generic "⚠️ Request cancelled" used for user /stop.
271
+ * banner instead of the generic "⚠️ Request cancelled" used for user /cancel.
248
272
  */
249
273
  export class ClaudeApiError extends Error {
250
274
  detail;
@@ -257,7 +281,7 @@ export class ClaudeApiError extends Error {
257
281
  function resolveCwd(sessionKey) {
258
282
  const session = sessionManager.getSession(sessionKey);
259
283
  if (!session) {
260
- throw new Error('No active session. Use /project to set working directory.');
284
+ throw new Error('No active session. Use /dir to set working directory.');
261
285
  }
262
286
  const cwd = session.workingDirectory;
263
287
  if (cwd && fs.existsSync(cwd))
@@ -282,10 +306,20 @@ export class PtyProvider {
282
306
  closing = false;
283
307
  /**
284
308
  * Last-known usage per sessionKey, refreshed at end-of-turn from claude's
285
- * on-disk JSONL log. Surfaced via getCachedUsage so the status line and
286
- * per-turn usage chips light up the same as SDK mode.
309
+ * on-disk JSONL log. Surfaced via getCachedUsage for the status line and
310
+ * the usage footer.
287
311
  */
288
312
  usageCache = new Map();
313
+ constructor() {
314
+ // Claude Code's /cd moved a live pty's session: it runs in the new
315
+ // directory now, and the next turn's directory check shouldn't take that
316
+ // for a workspace change and restart it, background work and all.
317
+ onSessionMove((sessionKey, cwd) => {
318
+ const live = this.sessions.get(sessionKey);
319
+ if (live)
320
+ live.cwd = cwd;
321
+ });
322
+ }
289
323
  getSessionPid(sessionKey) {
290
324
  return this.sessions.get(sessionKey)?.term.pid;
291
325
  }
@@ -297,6 +331,63 @@ export class PtyProvider {
297
331
  listSessionKeysForChat(chatId) {
298
332
  return [...this.sessions.keys()].filter((key) => parseSessionKey(key).chatId === chatId);
299
333
  }
334
+ /** Every live session key on this bot, for a setting changed bot-wide. */
335
+ listSessionKeys() {
336
+ return [...this.sessions.keys()];
337
+ }
338
+ /**
339
+ * End the claudes that have sat idle for `maxIdleMs` or longer, skipping any
340
+ * session `isBusy` vouches for. Nothing of the conversation is lost: the
341
+ * next turn in that session resumes it from the transcript in a new claude,
342
+ * as it does after a restart. Returns the session keys that were ended.
343
+ */
344
+ endIdleSessions(maxIdleMs, isBusy) {
345
+ const now = Date.now();
346
+ const ended = [];
347
+ for (const [sessionKey, session] of [...this.sessions]) {
348
+ if (this._idleMs(session, now) < maxIdleMs)
349
+ continue;
350
+ if (session.endOfTurnResolver || isGenerating(this._getScreenText(session)))
351
+ continue;
352
+ if (isBusy(sessionKey, session.term.pid))
353
+ continue;
354
+ this._cleanupSession(sessionKey);
355
+ ended.push(sessionKey);
356
+ }
357
+ return ended;
358
+ }
359
+ /** Whether this session has a claude running right now. */
360
+ hasLiveSession(sessionKey) {
361
+ return this.sessions.has(sessionKey);
362
+ }
363
+ /**
364
+ * Every live claude, with how long it has sat idle and whether its TUI shows
365
+ * it generating. For the memory guard and /info.
366
+ */
367
+ describeSessions() {
368
+ const now = Date.now();
369
+ return [...this.sessions].map(([sessionKey, session]) => ({
370
+ sessionKey,
371
+ pid: session.term.pid,
372
+ idleMs: this._idleMs(session, now),
373
+ generating: !!session.endOfTurnResolver || isGenerating(this._getScreenText(session)),
374
+ }));
375
+ }
376
+ /**
377
+ * End the one claude that has sat idle the longest, whatever its idle time,
378
+ * skipping any that is generating or that `isBusy` says still has work.
379
+ * Returns its session key, or null when every claude is busy.
380
+ */
381
+ endLongestIdleSession(isBusy) {
382
+ const candidates = this.describeSessions()
383
+ .filter((s) => !s.generating && !isBusy(s.sessionKey, s.pid))
384
+ .sort((a, b) => b.idleMs - a.idleMs);
385
+ const victim = candidates[0];
386
+ if (!victim)
387
+ return null;
388
+ this._cleanupSession(victim.sessionKey);
389
+ return victim.sessionKey;
390
+ }
300
391
  /**
301
392
  * Whether claude is generating in this session right now, whoever started the
302
393
  * turn. The bot's own bookkeeping can't answer that for a turn claude started
@@ -306,6 +397,18 @@ export class PtyProvider {
306
397
  const session = this.sessions.get(sessionKey);
307
398
  return session !== undefined && isGenerating(this._getScreenText(session));
308
399
  }
400
+ /**
401
+ * Whether this session's claude sits at its input box doing nothing: no turn
402
+ * of ours, not generating, no dialog up. For telling a turn claude started
403
+ * itself that was never closed in the log from one still going.
404
+ */
405
+ isSessionAtPrompt(sessionKey) {
406
+ const session = this.sessions.get(sessionKey);
407
+ if (!session || session.endOfTurnResolver)
408
+ return false;
409
+ const screenText = this._getScreenText(session);
410
+ return !isGenerating(screenText) && hasInputBox(screenText) && !parseModal(screenText, screenMarks(session.xterm));
411
+ }
309
412
  /**
310
413
  * Stop a turn the bot holds no handle on, which is one claude started itself.
311
414
  * A turn the bot started goes through its abort controller instead. Returns
@@ -324,11 +427,70 @@ export class PtyProvider {
324
427
  markSelfTurnInterrupted(sessionKey);
325
428
  return true;
326
429
  }
430
+ /**
431
+ * Press Claude Code's move-to-background key (Ctrl+B) for this session: the
432
+ * shell command or subagent running in the foreground carries on in the
433
+ * background, and the turn goes on without waiting for it.
434
+ *
435
+ * Only while Claude Code offers the key on screen, and with the key it
436
+ * names; see background-hint.ts. Whose turn it is doesn't matter, so this
437
+ * works in one claude started itself too. Done once the offer has left the
438
+ * screen: the tool call then returns with a background task id, which the
439
+ * PostToolUse hook picks up for /tasks.
440
+ */
441
+ async moveToBackground(sessionKey) {
442
+ const session = this.sessions.get(sessionKey);
443
+ if (!session)
444
+ return { ok: false, reason: 'no-session' };
445
+ const key = scrapeBackgroundHint(session.xterm);
446
+ if (key === null)
447
+ return { ok: false, reason: 'not-offered' };
448
+ // A dialog over the running task takes the keys, and Ctrl+B means
449
+ // something else in it or nothing.
450
+ if (parseModal(this._getScreenText(session), screenMarks(session.xterm))) {
451
+ return { ok: false, reason: 'dialog-open' };
452
+ }
453
+ const keystroke = backgroundKeystroke(key);
454
+ if (keystroke === null)
455
+ return { ok: false, reason: 'unknown-key', key };
456
+ try {
457
+ session.term.write(keystroke);
458
+ }
459
+ catch {
460
+ return { ok: false, reason: 'no-session' }; // pty already gone
461
+ }
462
+ const deadline = Date.now() + BACKGROUND_KEY_MS;
463
+ while (Date.now() < deadline) {
464
+ await new Promise((r) => setTimeout(r, BACKGROUND_POLL_MS));
465
+ if (scrapeBackgroundHint(session.xterm) === null)
466
+ return { ok: true };
467
+ }
468
+ return { ok: false, reason: 'still-running' };
469
+ }
470
+ /**
471
+ * Start this chat's claude now, ahead of the message that would otherwise
472
+ * start it, so that message finds the input box already open. Spawns and
473
+ * nothing more: the readiness wait a turn runs reads the screen as it
474
+ * stands, so the first prompt waits out whatever is left of the startup,
475
+ * and a dialog claude opened on the way (folder trust) is relayed then, as
476
+ * it always was. A chat that already has a claude is left alone — a turn
477
+ * may be using it. Returns whether one was started.
478
+ */
479
+ prewarm(sessionKey, options) {
480
+ if (this.closing || this.sessions.has(sessionKey))
481
+ return false;
482
+ const session = this._getOrCreateSession(sessionKey, options, true);
483
+ // Claude can start a turn of its own before the first prompt (a resumed
484
+ // session reporting a task that ended while it was down), and a tool
485
+ // called there needs the chat.
486
+ if (options?.telegramCtx)
487
+ registerSessionChat(session.claudeSessionId, sessionKey, options.telegramCtx);
488
+ return true;
489
+ }
327
490
  async sendToAgent(sessionKey, message, options) {
328
491
  // A provider switch or a cross-backend /resume may have queued a recap of
329
492
  // the conversation this fresh session continues.
330
- const commandWrapped = wrapCommandPrompt(withPendingCarryOver(sessionKey, message), options?.command);
331
- const { prompt: promptToSend, tempPaths } = stageImagesForPty(commandWrapped, options?.images);
493
+ const { prompt: promptToSend, tempPaths } = stageImagesForPty(withPendingCarryOver(sessionKey, message), options?.images);
332
494
  // Timestamp of the newest compaction already on disk before this turn.
333
495
  // Any compaction with a later timestamp afterward was produced by this turn
334
496
  // — a manual `/compact` or an auto-compaction that fired near the limit —
@@ -341,7 +503,7 @@ export class PtyProvider {
341
503
  finalScreenText = await this._runPtyTurn(sessionKey, promptToSend, options);
342
504
  }
343
505
  catch (err) {
344
- // If the user cancelled (/stop or /cancel), the pty kill in the abort
506
+ // If the user cancelled (/cancel), the pty kill in the abort
345
507
  // path was deliberate. Return a graceful "cancelled" response instead
346
508
  // of bubbling the error up to handleMessage — handleCancel already
347
509
  // showed the user a "🛑 Cancelled" banner; we just need this promise
@@ -456,6 +618,13 @@ export class PtyProvider {
456
618
  const compactedThisTurn = !!postCompact && postCompact.timestampMs > compactionBeforeMs;
457
619
  const isManualCompact = isNativeCompactCommand(message);
458
620
  let text = assistantResponse;
621
+ // `/rewind` writes nothing to the log. What it did is known from the
622
+ // dialog the relay answered for it, and that is the reply.
623
+ if (turnSession?.rewound) {
624
+ const report = await this._rewindReport(turnSession, turnSession.rewound);
625
+ turnSession.rewound = null;
626
+ text = text ? `${report}\n\n${text}` : report;
627
+ }
459
628
  let compaction;
460
629
  if (compactedThisTurn && postCompact) {
461
630
  compaction = { trigger: postCompact.trigger, preTokens: postCompact.preTokens };
@@ -555,12 +724,12 @@ export class PtyProvider {
555
724
  * Tail the active session's JSONL log for the most recent usage block and
556
725
  * cache it. Falls back to undefined if claude hasn't written a usage record
557
726
  * yet (very first turn, or pre-existing session without compatible records).
558
- * Both cost figures are left at 0. Claude doesn't write pricing into the
559
- * log, and this mode has no result message to read one off — the long-lived
560
- * TUI process knows its own running total, but the only way to that number
561
- * is typing `/cost` into it and scraping the screen, and on a subscription
562
- * that view reports account limits with no session cost in it at all.
563
- * Recomputing from a pricing table here would be brittle instead of absent.
727
+ * There is no cost figure in it. Claude doesn't write pricing into the log;
728
+ * the long-lived TUI process knows its own running total, but the only way
729
+ * to that number is typing `/cost` into it and scraping the screen, which
730
+ * is what the /cost command does, and on a subscription that view reports
731
+ * account limits with no session cost in it at all. Recomputing from a
732
+ * pricing table here would be brittle instead of absent.
564
733
  */
565
734
  _refreshUsageFromJsonl(sessionKey) {
566
735
  const botSession = sessionManager.getSession(sessionKey);
@@ -574,10 +743,7 @@ export class PtyProvider {
574
743
  outputTokens: snapshot.outputTokens,
575
744
  cacheReadTokens: snapshot.cacheReadTokens,
576
745
  cacheWriteTokens: snapshot.cacheWriteTokens,
577
- totalCostUsd: 0,
578
- sessionCostUsd: 0,
579
- sessionCostTurns: 0,
580
- // PTY mode runs claude with the user's 1m-context entitlement (the banner
746
+ // The bot runs claude with the user's 1m-context entitlement (the banner
581
747
  // reads "Opus 4.8 (1M context) · Claude Max"). Hardcoding 1_000_000 is
582
748
  // a reasonable default — the bot's % calculation just needs *some* sane
583
749
  // denominator.
@@ -588,6 +754,7 @@ export class PtyProvider {
588
754
  model: snapshot.model
589
755
  || userPreferences.getModel(sessionKey)
590
756
  || 'Claude Code default',
757
+ ...(snapshot.effort ? { effort: snapshot.effort } : {}),
591
758
  };
592
759
  this.usageCache.set(sessionKey, usage);
593
760
  return usage;
@@ -662,7 +829,7 @@ export class PtyProvider {
662
829
  }, 2000);
663
830
  };
664
831
  if (abortSignal?.aborted) {
665
- // Pre-aborted (e.g. user hit /stop before we even started writing). Skip
832
+ // Pre-aborted (e.g. user hit /cancel before we even started writing). Skip
666
833
  // the whole pty round-trip and return whatever's currently on screen.
667
834
  unregisterActiveTurn(session.claudeSessionId);
668
835
  return this._getScreenText(session);
@@ -687,6 +854,7 @@ export class PtyProvider {
687
854
  // prompt actually landed rather than trusting a bumped mtime.
688
855
  session.promptMarkerAtSubmit = this._currentPromptMarker(sessionKey);
689
856
  session.submittedSlashCommand = prompt.trimStart().startsWith('/');
857
+ session.rewound = null;
690
858
  // Submit handling for claude's TUI input editor:
691
859
  //
692
860
  // claude v2.1.143 integrated an Nvim-style multi-line editor (the
@@ -796,21 +964,30 @@ export class PtyProvider {
796
964
  markTurnEnd(sessionKey);
797
965
  }
798
966
  }
799
- _getOrCreateSession(sessionKey, options) {
967
+ _getOrCreateSession(sessionKey, options, ahead = false) {
800
968
  // closeAll has ended every claude; one started now would outlive the bot.
801
969
  if (this.closing) {
802
970
  throw new Error("TeleCoder is shutting down, so this didn't reach Claude. Send it again once it's back.");
803
971
  }
804
972
  const requiredCwd = resolveCwd(sessionKey);
973
+ const executable = options?.executableOverride ?? CLAUDE_BIN;
805
974
  const existing = this.sessions.get(sessionKey);
806
975
  if (existing) {
807
- if (existing.cwd === requiredCwd) {
976
+ if (existing.cwd === requiredCwd && existing.executable === executable
977
+ && existing.userSetup === loadsUserSetup()) {
808
978
  // Reuse the live pty so claude keeps prior turns in context.
979
+ existing.lastUsedAt = Date.now();
809
980
  existing.onProgress = options?.onProgress;
810
981
  existing.onTip = options?.onTip;
982
+ existing.onBackgroundHint = options?.onBackgroundHint;
983
+ if (existing.idUnclaimed && !ahead) {
984
+ existing.idUnclaimed = false;
985
+ sessionManager.setClaudeSessionId(sessionKey, existing.claudeSessionId, options?.providerName);
986
+ }
811
987
  return existing;
812
988
  }
813
- // Workspace changed under us — restart cleanly.
989
+ // Workspace or backend changed under us, or the bot gained its first
990
+ // guest (or lost its last) since this pty started — restart cleanly.
814
991
  this._cleanupSession(sessionKey);
815
992
  }
816
993
  // Resume the prior claude session if we have one on disk for this cwd.
@@ -819,11 +996,35 @@ export class PtyProvider {
819
996
  // picks up exactly where the previous turn left off. The id is preserved
820
997
  // across resumes, so our IPC routing key stays stable.
821
998
  const botSession = sessionManager.getSession(sessionKey);
822
- const priorId = botSession?.claudeSessionId;
999
+ let priorId = botSession?.claudeSessionId;
1000
+ // A session one backend minted can't be resumed by another: DeepSeek via
1001
+ // CCR writes placeholder thinking-block signatures that the real Anthropic
1002
+ // API rejects with `400 Invalid signature in thinking block`. The switch
1003
+ // paths fork the session for us; this is the last-resort net for the ones
1004
+ // that didn't (legacy sessions, in-memory loss over a restart). A
1005
+ // mismatch abandons the old session id and starts fresh.
1006
+ const providerName = options?.providerName;
1007
+ if (priorId && providerName && botSession) {
1008
+ const owner = botSession.ownerProvider;
1009
+ const ownerMismatch = owner !== undefined && owner !== providerName;
1010
+ // No recorded owner (legacy / restarted): fall back to a content scan,
1011
+ // but only when resuming on real Anthropic — CCR/DeepSeek ignore sigs.
1012
+ const poisonedForAnthropic = owner === undefined &&
1013
+ providerName === 'claude' &&
1014
+ hasForeignThinkingSignatures(requiredCwd, priorId);
1015
+ if (ownerMismatch || poisonedForAnthropic) {
1016
+ console.warn(`[PtyProvider] Refusing cross-backend resume of ${priorId} ` +
1017
+ `(owner=${owner ?? 'unknown'}, now=${providerName}${poisonedForAnthropic ? ', foreign thinking signatures' : ''}); starting a fresh session.`);
1018
+ sessionManager.startNewConversation(sessionKey);
1019
+ priorId = undefined;
1020
+ }
1021
+ }
823
1022
  const resuming = !!(priorId && claudeSessionFileExists(requiredCwd, priorId));
824
1023
  const claudeSessionId = resuming ? priorId : randomUUID();
825
- if (!resuming) {
826
- sessionManager.setClaudeSessionId(sessionKey, claudeSessionId);
1024
+ // A new id is the bot session's from the first prompt on, not before.
1025
+ const idUnclaimed = !resuming && ahead;
1026
+ if (!resuming && !ahead) {
1027
+ sessionManager.setClaudeSessionId(sessionKey, claudeSessionId, providerName);
827
1028
  }
828
1029
  const ipcPort = getIpcPort();
829
1030
  const settingsJson = buildSettingsJson(ipcPort);
@@ -841,24 +1042,23 @@ export class PtyProvider {
841
1042
  // survives because the next spawn resumes the same session id.
842
1043
  const effort = userPreferences.getEffort(sessionKey);
843
1044
  const model = userPreferences.getModel(sessionKey);
1045
+ const userSetup = loadsUserSetup();
844
1046
  const args = [
845
1047
  '--dangerously-skip-permissions',
846
1048
  ...(resuming ? ['--resume', claudeSessionId] : ['--session-id', claudeSessionId]),
847
1049
  ...(effort ? ['--effort', effort] : []),
848
1050
  ...(model ? ['--model', model] : []),
849
- // Exclude user-level settings. This keeps PTY mode predictable —
850
- // most importantly it drops `editorMode: "vim"` which makes \r insert
851
- // a newline instead of submitting (we saw prompts pile up in the
852
- // multi-line buffer and never reach the model). Project + local
853
- // settings still load, as does our injected --settings JSON below,
854
- // which also carries the one user setting a spawn can't do without.
855
- '--setting-sources', 'project,local',
1051
+ // The account's own Claude Code setup (~/.claude, its MCP servers and
1052
+ // connectors) comes along as it does in a terminal, unless the bot has
1053
+ // guests: these are the flags that keep it out, or none. See
1054
+ // loadsUserSetup.
1055
+ ...userSetupIsolationArgs(userSetup),
1056
+ // Our hooks, and the two settings pinned for the sake of the terminal
1057
+ // driving (see buildSettingsJson). The flag tier outranks the others.
856
1058
  '--settings', settingsJson,
857
- // Spawn our standalone MCP server as a stdio subprocess. Strict mode
858
- // scopes MCP to *only* what we pass here — the user's globally
859
- // configured MCP servers don't load in PTY mode.
1059
+ // Spawn our standalone MCP server as a stdio subprocess, beside
1060
+ // whatever EXTRA_MCP_CONFIG names.
860
1061
  '--mcp-config', mcpConfigJson,
861
- '--strict-mcp-config',
862
1062
  // Make our MCP tools discoverable to claude. Without this the tool
863
1063
  // names appear in claude's deferred-tools list but claude often picks
864
1064
  // WebFetch/Bash for the same task because the deferred listing has
@@ -867,13 +1067,13 @@ export class PtyProvider {
867
1067
  '--append-system-prompt', buildPtySystemPromptNote(),
868
1068
  // Hard-disable claude's built-in AskUserQuestion. The headless xterm has
869
1069
  // no real user to type a response, so an AskUserQuestion call freezes
870
- // the turn until MAX_TURN_MS fires (~30 min). The system-prompt note
871
- // already steers claude toward telecoder_ask_user, but the model still
872
- // reaches for the built-in sometimes mid-turn — a hard deny forces it
873
- // to the MCP variant (or plain text).
1070
+ // the turn until MAX_TURN_MS fires (two hours by default). The
1071
+ // system-prompt note already steers claude toward telecoder_ask_user,
1072
+ // but the model still reaches for the built-in sometimes mid-turn — a
1073
+ // hard deny forces it to the MCP variant (or plain text).
874
1074
  //
875
1075
  // CronCreate / ScheduleWakeup / RemoteTrigger are also blocked: their
876
- // fires land outside our session (cron in PTY mode, RemoteTrigger on
1076
+ // fires land outside our session (cron in claude's own process, RemoteTrigger on
877
1077
  // claude.ai's servers) and never reach the Telegram chat.
878
1078
  // telecoder_loop / telecoder_schedule replace them and route fires
879
1079
  // through the bot. Set TELECODER_ALLOW_NATIVE_SCHEDULING=1 to keep
@@ -885,7 +1085,7 @@ export class PtyProvider {
885
1085
  // Five minutes past the question timeout, and never under the 15 min it
886
1086
  // has always been, so the bot's own question timer is the one that fires.
887
1087
  const mcpCallMs = String(Math.max(15 * 60 * 1000, questionTimeoutMs() + 5 * 60 * 1000));
888
- const term = spawn(CLAUDE_BIN, args, {
1088
+ const term = spawn(executable, args, {
889
1089
  name: 'xterm-256color',
890
1090
  cols: COLS,
891
1091
  rows: ROWS,
@@ -946,8 +1146,13 @@ export class PtyProvider {
946
1146
  term,
947
1147
  xterm,
948
1148
  cwd: requiredCwd,
1149
+ executable,
1150
+ userSetup,
949
1151
  claudeSessionId,
950
1152
  lastChunkAt: Date.now(),
1153
+ lastUsedAt: Date.now(),
1154
+ screenSeen: null,
1155
+ screenChangedAt: Date.now(),
951
1156
  endOfTurnResolver: null,
952
1157
  endOfTurnRejector: null,
953
1158
  idleTimer: null,
@@ -956,6 +1161,8 @@ export class PtyProvider {
956
1161
  stream: null,
957
1162
  onTip: options?.onTip,
958
1163
  lastTip: null,
1164
+ onBackgroundHint: options?.onBackgroundHint,
1165
+ lastBackgroundHint: false,
959
1166
  stopReceived: false,
960
1167
  inflightTools: 0,
961
1168
  submitTimeMs: 0,
@@ -967,10 +1174,12 @@ export class PtyProvider {
967
1174
  lastTypedPrompt: undefined,
968
1175
  boxMayHold: undefined,
969
1176
  awaitingResumeReplay: resuming,
1177
+ idUnclaimed,
970
1178
  updateBannerChecked: false,
971
1179
  turnRelay: null,
972
1180
  relayingModal: false,
973
1181
  dialogAnsweredAt: null,
1182
+ rewound: null,
974
1183
  };
975
1184
  term.onData((chunk) => this._onData(session, chunk));
976
1185
  term.onExit(({ exitCode, signal }) => {
@@ -983,6 +1192,7 @@ export class PtyProvider {
983
1192
  // this term, removes us from the map, and may immediately spawn a
984
1193
  // replacement at the same sessionKey. By the time *this* late onExit
985
1194
  // fires, the replacement is the live session — don't wipe it out.
1195
+ watchUnregister(sessionKey, session.xterm);
986
1196
  if (this.sessions.get(sessionKey) === session) {
987
1197
  this.sessions.delete(sessionKey);
988
1198
  unregisterSessionChat(session.claudeSessionId);
@@ -995,11 +1205,13 @@ export class PtyProvider {
995
1205
  }
996
1206
  });
997
1207
  this.sessions.set(sessionKey, session);
1208
+ watchRegister(sessionKey, requiredCwd, xterm);
998
1209
  return session;
999
1210
  }
1000
1211
  _onData(session, chunk) {
1001
1212
  session.lastChunkAt = Date.now();
1002
1213
  session.xterm.write(chunk);
1214
+ watchData(session.xterm, chunk);
1003
1215
  // Mirror Claude Code's live spinner tip into the Telegram status line.
1004
1216
  // The tip is drawn in place at the bottom of the TUI — scrape it directly
1005
1217
  // and only fire when it actually changes (including when it clears to null).
@@ -1010,6 +1222,15 @@ export class PtyProvider {
1010
1222
  session.onTip(tip);
1011
1223
  }
1012
1224
  }
1225
+ // The same for the line that offers to move a running command to the
1226
+ // background: the chat's status line carries it while Claude Code's does.
1227
+ if (session.onBackgroundHint) {
1228
+ const offered = scrapeBackgroundHint(session.xterm) !== null;
1229
+ if (offered !== session.lastBackgroundHint) {
1230
+ session.lastBackgroundHint = offered;
1231
+ session.onBackgroundHint(offered);
1232
+ }
1233
+ }
1013
1234
  if (session.endOfTurnResolver) {
1014
1235
  if (session.idleTimer)
1015
1236
  clearTimeout(session.idleTimer);
@@ -1026,16 +1247,25 @@ export class PtyProvider {
1026
1247
  // Ahead of the in-flight guard below, deliberately: claude asks for
1027
1248
  // permission *inside* a tool call, so inflightTools is >0 for exactly the
1028
1249
  // dialogs this catches, and checking after it would never see one.
1029
- if (isIdle && !session.relayingModal && blockingModal(this._getScreenText(session))) {
1250
+ if (isIdle && !session.relayingModal
1251
+ && blockingModal(this._getScreenText(session), screenMarks(session.xterm))) {
1030
1252
  this._relayMidTurn(session);
1031
1253
  session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), idleMs);
1032
1254
  return;
1033
1255
  }
1256
+ // The relay still has the dialog in hand. That holds for a moment after
1257
+ // the dialog has gone from the screen too: a `/rewind` leaves a prompt in
1258
+ // the input box for the relay to take out, and a turn handed back before
1259
+ // then would have the next message typed onto the end of it.
1260
+ if (session.relayingModal) {
1261
+ session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), idleMs);
1262
+ return;
1263
+ }
1034
1264
  // Stop hook fired → Stop itself is the authoritative end-of-turn signal,
1035
1265
  // we just wait for a brief settle. Otherwise fall back to the idle path:
1036
1266
  // pty quiet for IDLE_MS, the input prompt is back on screen, AND claude
1037
1267
  // has either written something to the JSONL log since we submitted
1038
- // (model turns, /compact, /handoff, /clear all do) or we've waited
1268
+ // (model turns, /compact, /clear all do) or we've waited
1039
1269
  // NO_JSONL_FALLBACK_MS to cover purely-TUI slash commands like /cost.
1040
1270
  // The JSONL-mtime gate replaces an older bullet-count check that hung
1041
1271
  // indefinitely on /compact because compaction renders no `●` glyph.
@@ -1075,6 +1305,9 @@ export class PtyProvider {
1075
1305
  stillGenerating,
1076
1306
  claudeProducedSomething,
1077
1307
  resumingAfterDialog,
1308
+ stopWaitOver: sinceLast >= STOP_WAIT_MS,
1309
+ // A slash command fires no Stop and writes no end to the log.
1310
+ turnEndedInLog: () => session.submittedSlashCommand || readTurnEnded(session.cwd, session.claudeSessionId),
1078
1311
  });
1079
1312
  // A count that outlived its Stop is a lost hook, not a live tool. Say so:
1080
1313
  // silence here is what made a two-hour hang look like a long turn.
@@ -1104,7 +1337,7 @@ export class PtyProvider {
1104
1337
  // and would otherwise spin this check every 50ms for the whole window.
1105
1338
  const wait = hold === 'resuming'
1106
1339
  ? DIALOG_RESUME_POLL_MS
1107
- : hold === 'tools'
1340
+ : hold === 'tools' || hold === 'stop'
1108
1341
  ? idleMs
1109
1342
  : Math.min(idleRemaining, fallbackRemaining);
1110
1343
  session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), wait);
@@ -1152,6 +1385,7 @@ export class PtyProvider {
1152
1385
  // Each turn gets a fresh Telegram status message (StreamState.tip starts
1153
1386
  // null), so clear lastTip to force a re-push of the current tip.
1154
1387
  session.lastTip = null;
1388
+ session.lastBackgroundHint = false;
1155
1389
  session.endOfTurnResolver = resolve;
1156
1390
  session.endOfTurnRejector = reject;
1157
1391
  session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), IDLE_MS);
@@ -1212,7 +1446,7 @@ export class PtyProvider {
1212
1446
  // below every time generation resumes, so bound the wait as a whole too.
1213
1447
  const hardDeadline = Date.now() + BUSY_READY_CEILING_MS + ceilingMs;
1214
1448
  for (;;) {
1215
- // The wait can now outlast a turn, so /stop has to reach it. The abort
1449
+ // The wait can now outlast a turn, so /cancel has to reach it. The abort
1216
1450
  // handler has already written Esc at the pty; there is no prompt to
1217
1451
  // deliver on the other side of that.
1218
1452
  if (abortSignal?.aborted)
@@ -1254,7 +1488,7 @@ export class PtyProvider {
1254
1488
  // Settled on something that isn't the input box. A dialog is the
1255
1489
  // one case worth reporting separately: it will never clear on its
1256
1490
  // own, so waiting out the ceiling only delays telling someone.
1257
- if (parseModal(screenText))
1491
+ if (parseModal(screenText, screenMarks(session.xterm)))
1258
1492
  return 'modal';
1259
1493
  }
1260
1494
  const waited = Date.now() - waitingSince;
@@ -1357,7 +1591,7 @@ export class PtyProvider {
1357
1591
  */
1358
1592
  async _applyPermissionMode(session, sessionKey) {
1359
1593
  const chosen = userPreferences.getPermissionMode(sessionKey);
1360
- const target = chosen ?? transportDefaultMode('pty', config.DANGEROUS_MODE);
1594
+ const target = chosen ?? defaultPermissionMode();
1361
1595
  const pty = {
1362
1596
  write: (data) => session.term.write(data),
1363
1597
  screen: () => this._getScreenText(session),
@@ -1426,7 +1660,7 @@ export class PtyProvider {
1426
1660
  * an unanswered dialog is left exactly as it is.
1427
1661
  */
1428
1662
  async _relayModal(session, sessionKey, options, stage) {
1429
- const modal = parseModal(this._getScreenText(session));
1663
+ const modal = parseModal(this._getScreenText(session), screenMarks(session.xterm));
1430
1664
  const ctx = options?.telegramCtx;
1431
1665
  if (!ctx?.chat?.id) {
1432
1666
  // No chat to ask in — a scheduled run, or a turn started without a ctx.
@@ -1437,6 +1671,7 @@ export class PtyProvider {
1437
1671
  const pty = {
1438
1672
  write: (data) => session.term.write(data),
1439
1673
  screen: () => this._getScreenText(session),
1674
+ marks: () => screenMarks(session.xterm),
1440
1675
  };
1441
1676
  const outcome = await relayDialog(pty, sessionKey, ctx, session.cwd, stage, {
1442
1677
  clearMs: DIALOG_CLEAR_MS,
@@ -1449,6 +1684,77 @@ export class PtyProvider {
1449
1684
  // finished turn until claude resumes, and _checkEndOfTurn needs to know
1450
1685
  // not to believe it.
1451
1686
  session.dialogAnsweredAt = Date.now();
1687
+ const rewind = rewindIn(outcome.steps);
1688
+ if (rewind)
1689
+ await this._afterRewind(session, sessionKey, ctx, stage, rewind);
1690
+ }
1691
+ /**
1692
+ * Finish a `/rewind` the relay just answered: take the prompt Claude Code
1693
+ * handed back out of the input box, and see that the chat is told what was
1694
+ * restored.
1695
+ *
1696
+ * The report is the turn's reply when `/rewind` was the turn, and is made
1697
+ * when the turn ends (see {@link _rewindReport}). A rewind answered from a
1698
+ * dialog an earlier turn left open has no reply to be, so it goes out on
1699
+ * its own, ahead of the message that was waiting behind it.
1700
+ */
1701
+ async _afterRewind(session, sessionKey, ctx, stage, rewind) {
1702
+ const promptCleared = await this._clearRestoredPrompt(session, rewind, REWIND_PROMPT_WAIT_MS);
1703
+ if (stage === 'mid-turn' && session.submittedSlashCommand) {
1704
+ session.rewound = { rewind, promptCleared };
1705
+ return;
1706
+ }
1707
+ const report = await this._rewindReport(session, { rewind, promptCleared });
1708
+ const { chatId, threadId } = parseSessionKey(sessionKey);
1709
+ await ctx.api.sendMessage(chatId, report, threadId !== undefined ? { message_thread_id: threadId } : {})
1710
+ .catch((err) => {
1711
+ console.warn(`[PtyProvider] ${sessionKey}: couldn't post the rewind report:`, sanitizeError(err));
1712
+ });
1713
+ }
1714
+ /**
1715
+ * Take the prompt a rewind handed back out of the input box, looking for
1716
+ * up to `waitMs`. True once it was seen there and is gone.
1717
+ *
1718
+ * The prompt is looked for by its opening words, as the list showed them,
1719
+ * since a box can't be read for "is anything in it" (see `boxMayHold`). It
1720
+ * is drawn a moment after the dialog goes, and after the summary when the
1721
+ * rewind makes one, which can take a while. So a rewind that takes the
1722
+ * conversation back and whose prompt hasn't shown up yet sets `boxMayHold`
1723
+ * all the same: the next message then clears before it types, which costs a
1724
+ * second and can't be wrong.
1725
+ */
1726
+ async _clearRestoredPrompt(session, rewind, waitMs) {
1727
+ const needle = restoredPromptNeedle(rewind);
1728
+ if (!restoresConversation(rewind) || !needle)
1729
+ return false;
1730
+ const deadline = Date.now() + waitMs;
1731
+ for (;;) {
1732
+ const screenText = this._getScreenText(session);
1733
+ if (inputBoxHolds(screenText, needle)) {
1734
+ await this._clearInputBox(session, inputBoxText(screenText) ?? rewind.prompt);
1735
+ await new Promise((r) => setTimeout(r, CLEAR_SETTLE_MS));
1736
+ if (!inputBoxHolds(this._getScreenText(session), needle)) {
1737
+ session.boxMayHold = undefined;
1738
+ return true;
1739
+ }
1740
+ }
1741
+ if (Date.now() >= deadline)
1742
+ break;
1743
+ await new Promise((r) => setTimeout(r, READY_POLL_MS));
1744
+ }
1745
+ session.boxMayHold = ' '.repeat(INPUT_BOX_COLS * MAX_RESTORED_PROMPT_ROWS);
1746
+ return false;
1747
+ }
1748
+ /**
1749
+ * What the chat is told about a rewind, read off the screen as it stands
1750
+ * now: a line saying it failed, and one more look for the prompt, which a
1751
+ * summary puts back only once it is done.
1752
+ */
1753
+ async _rewindReport(session, rewound) {
1754
+ const promptCleared = rewound.promptCleared || await this._clearRestoredPrompt(session, rewound.rewind, 0);
1755
+ console.log(`[PtyProvider] ${session.claudeSessionId}: /rewind (${rewound.rewind.choice})`
1756
+ + ` — restored prompt ${promptCleared ? 'cleared from the input box' : 'not seen in the input box'}`);
1757
+ return rewindReport(rewound.rewind, { promptCleared, failure: rewindFailure(this._getScreenText(session)) });
1452
1758
  }
1453
1759
  /**
1454
1760
  * Wait until stdout has been quiet for `idleMs`, capped at `capMs`. The
@@ -1467,15 +1773,19 @@ export class PtyProvider {
1467
1773
  /**
1468
1774
  * Type an `immediate` slash command into the live TUI, scrape what it draws,
1469
1775
  * then dismiss it with Esc. Built for `/tasks`, whose answer exists only in
1470
- * the running process's memory — the `-p --resume --fork-session` shell-out
1471
- * that backs /context would spawn a process with no background work at all
1472
- * and dutifully report none.
1776
+ * the running process's memory — a `-p --resume --fork-session` shell-out
1777
+ * would spawn a process with no background work at all and dutifully
1778
+ * report none.
1473
1779
  *
1474
1780
  * Refuses while a turn is in flight. The keyboard belongs to the turn: our
1475
1781
  * keystrokes would land in its input box, and the overlay would corrupt the
1476
1782
  * screen extraction its response is scraped from.
1783
+ *
1784
+ * `steer` sees the overlay as first drawn and may answer with keystrokes to
1785
+ * send into it — ↓ and Enter to open a row of `/tasks`. Each is given time
1786
+ * to redraw, and the screen returned is the one after the last of them.
1477
1787
  */
1478
- async runOverlayCommand(sessionKey, command) {
1788
+ async runOverlayCommand(sessionKey, command, steer) {
1479
1789
  const session = this.sessions.get(sessionKey);
1480
1790
  if (!session)
1481
1791
  return { ok: false, reason: 'no-session' };
@@ -1495,6 +1805,12 @@ export class PtyProvider {
1495
1805
  if (!settled) {
1496
1806
  console.warn(`[PtyProvider] overlay "${command}" did not settle within ${OVERLAY_MAX_MS}ms; scraping anyway`);
1497
1807
  }
1808
+ const keys = steer?.(this._getScreenText(session)) ?? [];
1809
+ for (const key of keys) {
1810
+ session.term.write(key);
1811
+ await new Promise((r) => setTimeout(r, OVERLAY_KEY_SETTLE_MS));
1812
+ await this._waitQuiet(session, OVERLAY_IDLE_MS, OVERLAY_MAX_MS);
1813
+ }
1498
1814
  return { ok: true, screen: this._getScreenText(session) };
1499
1815
  }
1500
1816
  finally {
@@ -1729,6 +2045,22 @@ export class PtyProvider {
1729
2045
  clearInterval(session.stream.timer);
1730
2046
  session.stream = null;
1731
2047
  }
2048
+ /**
2049
+ * How long since a turn last picked this session up or its screen last
2050
+ * changed. The screen, not the output: between turns Claude Code still
2051
+ * writes to its terminal — its update check puts "Checking for updates" in
2052
+ * the footer and takes it away again within the second — and with every
2053
+ * byte counted, a claude never sat idle for the hour the reaper waits.
2054
+ * Looked at every sweep, so a change that comes and goes between two looks
2055
+ * doesn't count; one that lasts, like a turn's reply, does.
2056
+ */
2057
+ _idleMs(session, now = Date.now()) {
2058
+ const screen = this._getScreenText(session);
2059
+ if (session.screenSeen !== null && screen !== session.screenSeen)
2060
+ session.screenChangedAt = now;
2061
+ session.screenSeen = screen;
2062
+ return now - Math.max(session.lastUsedAt, session.screenChangedAt);
2063
+ }
1732
2064
  _getScreenText(session) {
1733
2065
  const buffer = session.xterm.buffer.active;
1734
2066
  let text = '';
@@ -1753,6 +2085,7 @@ export class PtyProvider {
1753
2085
  this._stopStream(session);
1754
2086
  this.sessions.delete(sessionKey);
1755
2087
  unregisterSessionChat(session.claudeSessionId);
2088
+ watchUnregister(sessionKey, session.xterm);
1756
2089
  }
1757
2090
  // Stop any monitor relay tied to this session — the JSONL it was watching
1758
2091
  // belongs to a now-dead claudeSessionId; the next session gets a new one.
@@ -1797,55 +2130,6 @@ export class PtyProvider {
1797
2130
  catch { /* already gone */ }
1798
2131
  }
1799
2132
  }
1800
- async sendLoopToAgent(sessionKey, message, options = {}) {
1801
- const { onProgress, abortController, maxIterations = config.MAX_LOOP_ITERATIONS, onIterationComplete, } = options;
1802
- if (!sessionManager.getSession(sessionKey)) {
1803
- throw new Error('No active session. Use /project to set working directory.');
1804
- }
1805
- // Wrap only the first prompt with the DONE convention. Continuation turns
1806
- // reuse the live pty so conversation context is already in claude's memory.
1807
- const loopPrompt = `${message}\n\nIMPORTANT: When you have fully completed this task, respond with the word "DONE" on its own line at the end of your response. If you need to continue working, do not say "DONE".`;
1808
- let iteration = 0;
1809
- let combinedText = '';
1810
- const allToolsUsed = [];
1811
- let isComplete = false;
1812
- while (iteration < maxIterations && !isComplete) {
1813
- iteration++;
1814
- if (abortController?.signal.aborted) {
1815
- return { text: combinedText + '\n\n🛑 Loop cancelled.', toolsUsed: allToolsUsed };
1816
- }
1817
- const iterationPrefix = `\n\n--- Iteration ${iteration}/${maxIterations} ---\n\n`;
1818
- combinedText += iterationPrefix;
1819
- onProgress?.(combinedText);
1820
- const currentPrompt = iteration === 1 ? loopPrompt : 'Continue the task. Say "DONE" when complete.';
1821
- try {
1822
- const response = await this.sendToAgent(sessionKey, currentPrompt, {
1823
- ...options,
1824
- // `text` is this iteration's prose so far, whole, so the live message
1825
- // is the iterations before it plus this one as it grows.
1826
- onProgress: (text) => onProgress?.(combinedText + text),
1827
- });
1828
- combinedText += response.text;
1829
- allToolsUsed.push(...response.toolsUsed);
1830
- onIterationComplete?.(iteration, response.text);
1831
- if (response.text.includes('DONE')) {
1832
- isComplete = true;
1833
- combinedText += '\n\n✅ Loop completed.';
1834
- }
1835
- else if (iteration >= maxIterations) {
1836
- combinedText += `\n\n⚠️ Max iterations (${maxIterations}) reached.`;
1837
- }
1838
- onProgress?.(combinedText);
1839
- }
1840
- catch (error) {
1841
- if (abortController?.signal.aborted) {
1842
- return { text: combinedText + '\n\n🛑 Loop cancelled.', toolsUsed: allToolsUsed };
1843
- }
1844
- throw error;
1845
- }
1846
- }
1847
- return { text: combinedText, toolsUsed: allToolsUsed };
1848
- }
1849
2133
  clearConversation(sessionKey) {
1850
2134
  this._cleanupSession(sessionKey);
1851
2135
  this.usageCache.delete(sessionKey);
@@ -1861,9 +2145,13 @@ export class PtyProvider {
1861
2145
  * the session log. Falls back to the pending preference (set but not yet
1862
2146
  * spawned), then to an honest placeholder — claude picks its own default and
1863
2147
  * we genuinely don't know which until a turn has been written.
2148
+ *
2149
+ * Nothing is cached before the first turn of this bot process, so after a
2150
+ * restart the log is read for the chat's own session; that is where the
2151
+ * model is, and /info asked about this very chat.
1864
2152
  */
1865
2153
  getModel(scope) {
1866
- const cached = this._findUsageForScope(scope);
2154
+ const cached = this._findUsageForScope(scope) ?? this._refreshUsageFromJsonl(String(scope));
1867
2155
  if (cached?.model)
1868
2156
  return cached.model;
1869
2157
  return userPreferences.getModel(scope) ?? 'Claude Code default';
@@ -1889,7 +2177,7 @@ export class PtyProvider {
1889
2177
  }
1890
2178
  /**
1891
2179
  * The last turn's usage, or the session log's when no turn has reported one
1892
- * since the chat got here: a fork, a /tree jump, a /resume and a restart all
2180
+ * since the chat got here: a branch, a /tree jump, a /resume and a restart all
1893
2181
  * start with nothing cached. The log sizes the point the chat is now at, which
1894
2182
  * after a jump is not the figure it last saw.
1895
2183
  */
@@ -1897,7 +2185,7 @@ export class PtyProvider {
1897
2185
  return this.usageCache.get(sessionKey) ?? this._refreshUsageFromJsonl(sessionKey);
1898
2186
  }
1899
2187
  /**
1900
- * The usage as the session log has it now, cached for /status and /context.
2188
+ * The usage as the session log has it now, cached for /info and the status line.
1901
2189
  * For after a turn claude started itself: no turn of ours ran to refresh the
1902
2190
  * cache, which still holds the figure from before that turn grew the context.
1903
2191
  * Falls back on the cached figure when the log has none to give.
@@ -1905,37 +2193,21 @@ export class PtyProvider {
1905
2193
  refreshUsage(sessionKey) {
1906
2194
  return this._refreshUsageFromJsonl(sessionKey) ?? this.usageCache.get(sessionKey);
1907
2195
  }
1908
- isDangerousMode() {
1909
- return true;
1910
- }
1911
2196
  async getAvailableModels(_scope) {
1912
- // The aliases CLAUDE_BIN accepts for --model, minus any it predates. SDK
1913
- // mode asks the same question of its own binary, so the two lists agree
1914
- // whenever both point at the same install.
2197
+ // The aliases CLAUDE_BIN accepts for --model, minus any it predates.
1915
2198
  return getModelsForBinary(CLAUDE_BIN);
1916
2199
  }
1917
2200
  }
1918
2201
  // ---- Hook → AgentOptions callback bridge ------------------------------------
1919
2202
  //
1920
2203
  // The handlers below run inside the IPC server when claude-spawned hook curls
1921
- // reach us. They translate hook payloads into the SDK-shaped callbacks the bot
1922
- // already implements (onToolStart / onToolEnd / onToolResult / onEditDiff), so
1923
- // PTY mode lights up the same verbose UI as SDK mode.
2204
+ // reach us. They translate hook payloads into the callbacks the bot
2205
+ // implements (onToolStart / onToolEnd / onToolResult / onEditDiff), which
2206
+ // drive the verbose UI.
1924
2207
  //
1925
2208
  // Callbacks are fire-and-forget — the hook command blocks claude until the
1926
2209
  // HTTP POST returns, so we ack fast and let the bot's Telegram calls run on
1927
2210
  // their own microtasks. Errors are logged, never rethrown into claude.
1928
- /**
1929
- * Apply per-command prompt wrapping so /plan and /explore behave the same in
1930
- * PTY mode as in SDK mode. SDK does this differently:
1931
- * - explore: prepends "Explore the codebase and answer: " to the prompt
1932
- * - plan: sets the SDK permissionMode to 'plan' (claude code then enforces
1933
- * read-only tool access)
1934
- * In PTY mode we spawn with --dangerously-skip-permissions, so we can't flip
1935
- * permission mode mid-run. Instead, plan mode is steered by a strong prompt
1936
- * directive — claude will follow it on subscription-side too, matching the
1937
- * SDK-mode user experience for the common case.
1938
- */
1939
2211
  /**
1940
2212
  * True if the xterm buffer is still showing Claude Code's first-launch welcome
1941
2213
  * screen. The two greeting strings only render together at startup — after any
@@ -1946,37 +2218,6 @@ export class PtyProvider {
1946
2218
  function looksLikeWelcomeBanner(screenText) {
1947
2219
  return screenText.includes('Welcome back') && screenText.includes('Tips for getting started');
1948
2220
  }
1949
- function wrapCommandPrompt(message, command) {
1950
- if (command === 'explore') {
1951
- return `Explore the codebase and answer: ${message}`;
1952
- }
1953
- if (command === 'plan') {
1954
- return `═══ PLAN MODE — STRICT ═══
1955
-
1956
- You are in plan mode. Your only job this turn is to produce an implementation plan. Read the codebase, understand the task, and output a numbered plan.
1957
-
1958
- PROHIBITED THIS TURN (treat as if these tools are disabled):
1959
- • Edit, Write, NotebookEdit — no file changes of any kind
1960
- • Bash commands that mutate state (no rm, mv, cp, mkdir, npm install, git commit, git push, etc.)
1961
- • Any side-effecting MCP tool (no send_file, no telegraph publishing)
1962
- • Do not run a build, do not run tests
1963
- • Do not "just fix one quick thing while you're there"
1964
-
1965
- ALLOWED:
1966
- • Read, Grep, Glob — read-only file inspection
1967
- • Bash for strictly read-only commands (ls, cat, grep, git log, git diff, git status, wc)
1968
- • telecoder_list_projects, telecoder_ask_user — read-only or interactive-only
1969
-
1970
- If you find yourself about to call a prohibited tool, STOP and put the action into the plan instead. The user will review the plan and explicitly ask you to execute in a follow-up message.
1971
-
1972
- Output format: numbered steps, one per change you'd make. End with an "Out of scope" list of things you're deliberately not touching.
1973
-
1974
- ═══ TASK ═══
1975
-
1976
- ${message}`;
1977
- }
1978
- return message;
1979
- }
1980
2221
  function fireAndForget(label, fn) {
1981
2222
  if (!fn)
1982
2223
  return;
@@ -1987,15 +2228,15 @@ function fireAndForget(label, fn) {
1987
2228
  /**
1988
2229
  * Pick the model-facing string out of a hook payload's `tool_response`.
1989
2230
  *
1990
- * SDK mode delivers tool results as the *serialized* form the model sees
1991
- * (Read → just the file content, Bash → stdout+stderr text). Hook payloads
1992
- * instead give us claude's internal structured object:
2231
+ * The model sees a tool result in its *serialized* form (Read → just the file
2232
+ * content, Bash → stdout+stderr text). Hook payloads instead give us claude's
2233
+ * internal structured object:
1993
2234
  * Read → { type: 'text', file: { filePath, content } }
1994
2235
  * Bash → { stdout, stderr, exit_code, … }
1995
2236
  *
1996
- * We unwrap the common shapes so PTY mode renders tool results the same way
1997
- * SDK mode does. Unknown shapes fall back to a JSON dump — better than
1998
- * nothing for diagnostics, even if it's ugly.
2237
+ * We unwrap the common shapes so the chat shows what the model saw. Unknown
2238
+ * shapes fall back to a JSON dump — better than nothing for diagnostics, even
2239
+ * if it's ugly.
1999
2240
  */
2000
2241
  /**
2001
2242
  * Join an MCP-style content array (`[{type:'text',text:'...'}, ...]`) into a
@@ -2013,6 +2254,24 @@ function joinMcpContentArray(arr) {
2013
2254
  }
2014
2255
  return texts.length ? texts.join('\n') : null;
2015
2256
  }
2257
+ /**
2258
+ * What the live log shows for a Bash call that is now running in the
2259
+ * background, instead of its output. A `run_in_background` call returns at
2260
+ * once with no stdout, and a call moved to the background at the foreground
2261
+ * cap returns with whatever it had printed so far, so rendering the response
2262
+ * as output would show an empty result for the first and a finished-looking
2263
+ * one for the second. Claude Code's own tool row says "Running in the
2264
+ * background (↓ to manage)" for both; the manage key here is /tasks, which
2265
+ * also has the output so far.
2266
+ */
2267
+ export function backgroundedResultText(toolName, toolResponse) {
2268
+ if (toolName !== 'Bash' || !toolResponse || typeof toolResponse !== 'object')
2269
+ return null;
2270
+ const { backgroundTaskId } = toolResponse;
2271
+ if (typeof backgroundTaskId !== 'string' || !backgroundTaskId)
2272
+ return null;
2273
+ return 'Running in the background (/tasks to manage)';
2274
+ }
2016
2275
  function extractToolResponseContent(toolResponse) {
2017
2276
  if (toolResponse == null)
2018
2277
  return '';
@@ -2082,7 +2341,7 @@ function armAsyncTool(turn, kind, toolInput, toolUseId, startedAt) {
2082
2341
  toolInput.command ??
2083
2342
  toolInput.prompt ??
2084
2343
  kind);
2085
- onAsyncToolArmed(kind, turn.sessionKey, session.workingDirectory, session.claudeSessionId, description, typeof toolUseId === 'string' && toolUseId ? toolUseId : undefined, startedAt);
2344
+ onAsyncToolArmed(kind, turn.sessionKey, session.workingDirectory, session.claudeSessionId, description, typeof toolUseId === 'string' && toolUseId ? toolUseId : undefined, startedAt, typeof toolInput.command === 'string' ? toolInput.command : undefined);
2086
2345
  }
2087
2346
  /**
2088
2347
  * What the PreToolUse hook is told when no turn or chat matches its session:
@@ -2107,6 +2366,9 @@ registerIpcHandler('/hook/preToolUse', async (turn, body) => {
2107
2366
  try {
2108
2367
  turn.onToolStart?.();
2109
2368
  fireAndForget('onToolStart', () => turn.options.onToolStart?.(toolName, toolInput));
2369
+ if (typeof body.tool_use_id === 'string' && body.tool_use_id) {
2370
+ (turn.toolStartedAt ??= new Map()).set(body.tool_use_id, Date.now());
2371
+ }
2110
2372
  // Arm the relay so any task-notifications that fire AFTER this turn ends
2111
2373
  // still get routed to Telegram, and register the task with the tracker
2112
2374
  // behind /tasks. See classifyAsyncTool for which tools qualify.
@@ -2130,8 +2392,7 @@ registerIpcHandler('/hook/preToolUse', async (turn, body) => {
2130
2392
  // tools matching a dangerous pattern, blocks the call and waits for Telegram
2131
2393
  // approval. Decision returned as a marker string the shell wrapper parses:
2132
2394
  // the deny marker exits 2 (claude code's "block this tool" signal), the
2133
- // allow marker exits 0, and anything else blocks too. gateToolCall is shared
2134
- // with the SDK transport's hook (sdk-permission-gate.ts).
2395
+ // allow marker exits 0, and anything else blocks too.
2135
2396
  if (isPermissionGateEnabled()) {
2136
2397
  const ctx = turn.options.telegramCtx;
2137
2398
  const decision = await gateToolCall({
@@ -2155,14 +2416,37 @@ registerIpcHandler('/hook/postToolUse', (turn, body) => {
2155
2416
  const toolName = String(body.tool_name ?? 'unknown');
2156
2417
  const toolInput = (body.tool_input ?? {});
2157
2418
  const toolUseId = String(body.tool_use_id ?? '');
2158
- turn.onToolEnd?.();
2159
- fireAndForget('onToolEnd', () => turn.options.onToolEnd?.());
2419
+ // Task bookkeeping first: it holds in a turn claude started itself too,
2420
+ // where the rest of this hook has no UI to drive.
2421
+ //
2160
2422
  // A Bash call that ran into claude's foreground cap carries on in the
2161
- // background. Track it from here, dated from when it actually started.
2162
- if (movedToBackground(toolName, toolInput, body.tool_response)) {
2423
+ // background, and so does one the user moved there with /ctrlb. Track it
2424
+ // from here, dated from when it actually started: the cap's response says
2425
+ // how long it ran, and for the user's move the PreToolUse hook noted when.
2426
+ const startedAt = turn.toolStartedAt?.get(toolUseId);
2427
+ turn.toolStartedAt?.delete(toolUseId);
2428
+ if (!turn.selfStarted && movedToBackground(toolName, toolInput, body.tool_response)) {
2163
2429
  const ranForMs = Number(body.tool_response.timedOutAfterMs) || 0;
2164
- armAsyncTool(turn, 'bash_background', toolInput, body.tool_use_id, Date.now() - ranForMs);
2430
+ armAsyncTool(turn, 'bash_background', toolInput, body.tool_use_id, ranForMs > 0 ? Date.now() - ranForMs : startedAt ?? Date.now());
2431
+ }
2432
+ // A backgrounded Bash call's response carries claude's own id for the task,
2433
+ // which is what a later TaskStop names it by.
2434
+ if (toolName === 'Bash') {
2435
+ const claudeTaskId = body.tool_response?.backgroundTaskId;
2436
+ if (typeof claudeTaskId === 'string' && claudeTaskId && toolUseId) {
2437
+ noteClaudeTaskId(turn.sessionKey, toolUseId, claudeTaskId);
2438
+ }
2439
+ }
2440
+ // Claude stopped a task: no task-notification follows, so retire it here.
2441
+ if (toolName === 'TaskStop') {
2442
+ const claudeTaskId = String(toolInput.task_id ?? '');
2443
+ if (claudeTaskId)
2444
+ onTaskStopped(turn.sessionKey, claudeTaskId);
2165
2445
  }
2446
+ if (turn.selfStarted)
2447
+ return { ok: true };
2448
+ turn.onToolEnd?.();
2449
+ fireAndForget('onToolEnd', () => turn.options.onToolEnd?.());
2166
2450
  if (toolName === 'Edit' || toolName === 'Write') {
2167
2451
  // Successful Edit/Write — surface the diff so the bot shows before/after.
2168
2452
  const event = {
@@ -2181,17 +2465,18 @@ registerIpcHandler('/hook/postToolUse', (turn, body) => {
2181
2465
  toolUseId,
2182
2466
  toolName,
2183
2467
  input: toolInput,
2184
- content: extractToolResponseContent(body.tool_response),
2468
+ content: backgroundedResultText(toolName, body.tool_response) ?? extractToolResponseContent(body.tool_response),
2185
2469
  isError: false,
2186
2470
  };
2187
2471
  fireAndForget('onToolResult', () => turn.options.onToolResult?.(event));
2188
2472
  }
2189
2473
  return { ok: true };
2190
- });
2474
+ }, { betweenTurns: true });
2191
2475
  registerIpcHandler('/hook/postToolUseFailure', (turn, body) => {
2192
2476
  const toolName = String(body.tool_name ?? 'unknown');
2193
2477
  const toolInput = (body.tool_input ?? {});
2194
2478
  const toolUseId = String(body.tool_use_id ?? '');
2479
+ turn.toolStartedAt?.delete(toolUseId);
2195
2480
  turn.onToolEnd?.();
2196
2481
  fireAndForget('onToolEnd', () => turn.options.onToolEnd?.());
2197
2482
  const event = {