telecoder 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,2499 @@
1
+ import { spawn } from 'node-pty';
2
+ import headless from '@xterm/headless';
3
+ import { watchData, watchRegister, watchUnregister } from './pty-watch.js';
4
+ import * as fs from 'fs';
5
+ import { randomUUID } from 'crypto';
6
+ import { config } from '../config.js';
7
+ import { sessionManager } from './session-manager.js';
8
+ import { claudeSessionFileExists, describeLogTail, hasForeignThinkingSignatures, sessionJsonlPath, readCommandReply, readLastApiErrorFromJsonl, readLastAssistantTurnText, readLastCompactionFromJsonl, readLastUsageFromJsonl, readLastUserPromptMarker, readTurnEnded, sessionJsonlMtimeMs, sessionJsonlSize } from './session-jsonl.js';
9
+ import { clearDeliveredProse, getDeliveredProse, stripDeliveredPrefix } from './turn-prose.js';
10
+ import { PtyTurnStream, TurnProseReader } from './pty-stream.js';
11
+ import { isNativeCompactCommand } from './command-parser.js';
12
+ import { isCancelled } from './request-queue.js';
13
+ import { getWorkspaceRoot } from '../utils/workspace-guard.js';
14
+ import { parseSessionKey } from '../utils/session-key.js';
15
+ import { formatCompactionConfirmation } from '../utils/format.js';
16
+ import { envWithoutParentSession } from '../utils/claude-env.js';
17
+ import { legacyEnv } from '../utils/legacy-env.js';
18
+ import { userPreferences } from '../providers/user-preferences.js';
19
+ import { getIpcPort, getIpcToken, IPC_TOKEN_ENV, registerActiveTurn, registerIpcHandler, registerSessionChat, unregisterActiveTurn, unregisterSessionChat, } from './ipc-server.js';
20
+ // Side-effect import: registers /mcp/* IPC handlers that bridge the standalone
21
+ // MCP subprocess back to bot-side state (Telegram API, session topic, …).
22
+ import './mcp-bridge.js';
23
+ import { onAsyncToolArmed, markTurnStart, markTurnEnd, markSelfTurnInterrupted, teardown as teardownMonitorRelay, relayPushNotification, classifyAsyncTool, movedToBackground, noteClaudeTaskId, onTaskStopped } from './monitor-relay.js';
24
+ import { relayUpdateBanner, scrapeUpdateBanner } from './update-banner-relay.js';
25
+ import { gateToolCall, isPermissionGateEnabled, ALLOW_MARKER, DENY_MARKER_START, DENY_MARKER_END } from './permission-gate.js';
26
+ import { sanitizeError } from '../utils/sanitize.js';
27
+ import { buildSettingsJson, buildMcpConfigJson, buildMcpEnv, buildPtySystemPromptNote, loadsUserSetup, userSetupIsolationArgs, } from './pty-spawn-config.js';
28
+ import { getModelsForBinary } from './model-catalog.js';
29
+ import { scrapePromptSuggestion } from './prompt-suggestion-scraper.js';
30
+ import { scrapeTip } from './tip-scraper.js';
31
+ import { scrapeBackgroundHint, backgroundKeystroke } from './background-hint.js';
32
+ import { clearPresses, hasInputBox, inputBoxHolds, inputBoxPastePlaceholders, inputBoxText, isGenerating, newPastePlaceholder, pastePlaceholderIds, pastePlaceholders, replyFromScreen, screenSignature, tailLines, } from './tui-state.js';
33
+ import { stageImagesForPty } from './stage-images.js';
34
+ import { blockingModal, openDialogError, relayDialog, } from './modal-relay.js';
35
+ import { questionTimeoutMs } from './ask-user.js';
36
+ import { ensurePermissionMode, permissionModeInfo, defaultPermissionMode, } from './permission-mode.js';
37
+ import { parseModal } from './tui-modal.js';
38
+ import { screenMarks } from './screen-marks.js';
39
+ import { restoredPromptNeedle, restoresConversation, rewindFailure, rewindIn, rewindReport } from './rewind.js';
40
+ import { claudeSetupScreen, ClaudeNotLoggedInError } from './claude-auth.js';
41
+ import { dialogResumeState, turnHold } from './turn-end.js';
42
+ import { isSuggestionsEnabled } from '../telegram/suggestions-settings.js';
43
+ import { resolvePtyClaudeBin } from '../utils/resolve-claude-bin.js';
44
+ import { withPendingCarryOver } from './carry-over.js';
45
+ import { onSessionMove } from './session-move.js';
46
+ const { Terminal } = headless;
47
+ // ---- Config from prototype --------------------------------------------------
48
+ /**
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).
52
+ */
53
+ const CLAUDE_BIN = resolvePtyClaudeBin();
54
+ // dist/claude/pty-provider.js → sibling dist/bin/mcp-server.js
55
+ /**
56
+ * How many lines of a stuck TUI to log. Enough for a dialog's title, its rows
57
+ * and its footer — the shape that says why the input box never came back.
58
+ */
59
+ const STUCK_SCREEN_LINES = 12;
60
+ /** How many log records to describe when a finished turn has no reply text. */
61
+ const NO_REPLY_LOG_RECORDS = 8;
62
+ const COLS = 120;
63
+ const ROWS = 40;
64
+ /**
65
+ * Characters claude fits on one row of the input box, after the `❯ ` glyph and
66
+ * its right margin. Measured against a live pty at COLS: a 115-character row
67
+ * fits, a 117-character one wraps.
68
+ */
69
+ const INPUT_BOX_COLS = COLS - 5;
70
+ /** Gap between the Ctrl+U presses of one clear, so claude takes them as keys and not as a paste. */
71
+ const CLEAR_PRESS_GAP_MS = 20;
72
+ /** How long the TUI gets to redraw an emptied box before it's read or typed into. */
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;
78
+ const IDLE_MS = 1200;
79
+ /**
80
+ * Short window we wait *after* the Stop hook fires before extracting the
81
+ * screen. Stop fires when claude finishes the response, but the TUI is
82
+ * still redrawing the input box at that point. Without a settle, we'd
83
+ * sometimes capture a half-rendered screen. 200ms is enough in practice.
84
+ */
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;
95
+ /**
96
+ * How often a running turn's live prose is brought up to date (pty-stream.ts).
97
+ * Often enough to catch a streaming block's growth before its head scrolls off
98
+ * the screen; the Telegram side throttles the edits on its own.
99
+ */
100
+ const STREAM_TICK_MS = 500;
101
+ /**
102
+ * Absolute wall-clock cap for a single turn — safety net for a genuinely
103
+ * wedged pty. Substantive investigative turns (multi-step Bash, deep code
104
+ * reads) can legitimately run several minutes; the default (2 h, via
105
+ * CLAUDE_PTY_HARD_TIMEOUT_MS) is long enough to let those finish while still
106
+ * being a sane upper bound. Raise the env var for unusually long turns. Note
107
+ * that the inflight gate and bullet-count gate already prevent the
108
+ * *idle-fallback* from firing prematurely — this timer only fires if neither
109
+ * Stop nor any other resolve path triggers for the full duration.
110
+ */
111
+ const MAX_TURN_MS = config.CLAUDE_PTY_HARD_TIMEOUT_MS;
112
+ const STARTUP_MAX_MS = 15_000;
113
+ /**
114
+ * Readiness thresholds for the first turn on a pty spawned with `--resume`.
115
+ * Claude replays the whole transcript on resume, and a long conversation takes
116
+ * minutes of near-continuous rendering — during which it draws the input glyph
117
+ * early, pauses, and keeps going. The normal 1.2s/15s pair reads one of those
118
+ * pauses as "ready", the prompt is pasted into an editor that isn't listening
119
+ * yet, and the Enter that submits it is swallowed. Demand a longer quiet period
120
+ * and allow far longer to reach it: waiting out the replay beats submitting
121
+ * into it. Still capped, so a genuinely stuck TUI can't hang the bot.
122
+ */
123
+ const RESUME_SETTLE_IDLE_MS = 3_000;
124
+ const RESUME_STARTUP_MAX_MS = 180_000;
125
+ /**
126
+ * Absolute ceilings for the readiness wait. The `MAX` values above bound how
127
+ * long we tolerate *silence*; these bound the wait as a whole. A host under
128
+ * memory pressure replays a transcript in slow bursts, and a cap counted from
129
+ * the moment we started waiting expires mid-replay even though claude is
130
+ * plainly still coming up — we then paste into an editor that isn't listening
131
+ * and the turn dies with "Claude never received your message". So long as
132
+ * bytes keep arriving we keep waiting; reaching one of these means the TUI is
133
+ * genuinely stuck rather than merely slow.
134
+ */
135
+ const STARTUP_READY_CEILING_MS = 60_000;
136
+ const RESUME_READY_CEILING_MS = 600_000;
137
+ /**
138
+ * How long a prompt waits for a turn that is already running in the pty.
139
+ *
140
+ * Separate from the ceilings above because it bounds something different:
141
+ * those cover a TUI that may never open its input box, this covers one that
142
+ * is plainly working and will. Waiting is the right answer — the prompt goes
143
+ * in when the turn ends, which is what a person at the terminal would get —
144
+ * but not forever, so a turn that outlives this reports the delay honestly
145
+ * rather than the bot sitting mute on it.
146
+ */
147
+ const BUSY_READY_CEILING_MS = 30 * 60_000;
148
+ /** Poll interval for the readiness wait. */
149
+ const READY_POLL_MS = 50;
150
+ /**
151
+ * How long a press gets to close the dialog it answered, or move it on to
152
+ * another screen, before the dialog counts as still open. Generous because
153
+ * the key that answers one can start work — a trust dialog releases a session
154
+ * that then loads its project — and the alternative to waiting is telling the
155
+ * chat the message failed when it is about to succeed.
156
+ */
157
+ const DIALOG_CLEAR_MS = 20_000;
158
+ /**
159
+ * How long the screen a press led to must stand still before it is relayed
160
+ * as the dialog's next one: `/mcp`'s server screen after a server was picked,
161
+ * the list it steps back to on Esc. Claude draws those in well under this, so
162
+ * it only costs a beat per screen; reading sooner risks a half-drawn frame.
163
+ */
164
+ const DIALOG_SETTLE_MS = 500;
165
+ /**
166
+ * How often the end-of-turn check re-reads the screen while claude is plainly
167
+ * still generating. The default re-arm is a 50ms tick meant to catch a turn
168
+ * ending between chunks; holding that rate through a silent tool call would
169
+ * scan the whole xterm buffer twenty times a second for as long as the call
170
+ * runs. Any new output re-arms the timer anyway, so this only paces the wait.
171
+ */
172
+ const GENERATING_RECHECK_MS = 500;
173
+ /**
174
+ * How long a turn waits for claude to pick itself back up after a dialog was
175
+ * answered, before the ordinary end-of-turn rules apply again.
176
+ *
177
+ * Generous on purpose. Claude draws its spinner within a moment of resuming,
178
+ * so the honest cases clear this in well under a second; the window only has
179
+ * to outlast a pause long enough to look idle. Getting it wrong in this
180
+ * direction costs a few seconds on a turn that really did end with the
181
+ * dialog. Getting it wrong the other way is what this exists to prevent, and
182
+ * costs the whole session: a turn resolved while claude was still working
183
+ * leaves its hooks arriving with no active turn to attach to, its output
184
+ * going nowhere, and every later message held against a screen that says it
185
+ * is generating.
186
+ */
187
+ const DIALOG_RESUME_GRACE_MS = 15_000;
188
+ /** How often to look for claude resuming, while inside that grace window. */
189
+ const DIALOG_RESUME_POLL_MS = 250;
190
+ /**
191
+ * What the chat is told when a prompt can't be delivered because the session
192
+ * is still working. Names the real cause: the earlier version of this path
193
+ * blamed transcript replay for every unmet readiness wait, which sent people
194
+ * looking at session size when the session was simply mid-turn.
195
+ */
196
+ function stillWorkingError() {
197
+ const minutes = Math.round(BUSY_READY_CEILING_MS / 60_000);
198
+ return `Claude is still working on an earlier message — it's been going for over ${minutes} minutes, `
199
+ + "so this one wasn't delivered. Send it again once that turn finishes, or /cancel to cut it short.";
200
+ }
201
+ /**
202
+ * After writing \r we confirm claude actually took the prompt — it appears in
203
+ * the session log as a user record. Until that lands (or we give up), re-send
204
+ * \r periodically as long as our text is still sitting in the input box: a
205
+ * swallowed keystroke is invisible otherwise, and the turn would resolve on
206
+ * stale log content. Skipped for slash commands, which need not write a record.
207
+ */
208
+ const SUBMIT_CONFIRM_CAP_MS = 30_000;
209
+ const SUBMIT_RETRY_EVERY_MS = 3_000;
210
+ /**
211
+ * Timings for runOverlayCommand. An `immediate` slash command renders locally
212
+ * with no API call, so it draws in well under a second — these only need to
213
+ * outlast one render, not a model turn. The paste settle mirrors the gap
214
+ * _runPtyTurn leaves between pasting text and pressing Enter.
215
+ */
216
+ const OVERLAY_PASTE_SETTLE_MS = 300;
217
+ const OVERLAY_IDLE_MS = 700;
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;
231
+ /**
232
+ * The slice of a prompt we look for on the rendered screen: leading
233
+ * non-whitespace of the first line, long enough to be distinctive. The box may
234
+ * wrap it across rows, which inputBoxHolds sees through. Undefined when the
235
+ * prompt is too short to match meaningfully — callers treat that as "can't tell".
236
+ */
237
+ function promptNeedle(prompt) {
238
+ const firstLine = prompt.replace(/^\s+/, '').split(/\r?\n/, 1)[0] ?? '';
239
+ const needle = firstLine.slice(0, 24);
240
+ return needle.length < 4 ? undefined : needle;
241
+ }
242
+ /**
243
+ * Newlines in `prompt` the way claude's editor counts them: it folds CRLF and
244
+ * bare CR to LF before counting, and the result is roughly the `+N lines` it
245
+ * writes into a collapsed paste's placeholder.
246
+ *
247
+ * Roughly, and for the log only. This once identified our own placeholder among
248
+ * the ones on screen, which it cannot do: claude rewrites a paste before
249
+ * drawing it — an image path becomes an `[Image #N]` chip — so what it reports
250
+ * is short of what we sent, and a prompt written with 10 newlines comes back
251
+ * `+7 lines`. Every photo upload failed on that. Identity is the id;
252
+ * newPastePlaceholder says so too.
253
+ */
254
+ function pasteLineCount(prompt) {
255
+ return (prompt.replace(/\r\n|\r/g, '\n').match(/\n/g) ?? []).length;
256
+ }
257
+ /**
258
+ * Idle + prompt-visible safety net for prompts that produce no JSONL activity.
259
+ * Most prompts (model turns, /compact, /clear, …) write at least one
260
+ * record to the session log, so the JSONL-mtime gate resolves them cleanly.
261
+ * Slash commands like /cost or /config emit purely TUI output without touching
262
+ * the log; without this fallback those would hang until MAX_TURN_MS. 5s of
263
+ * confirmed idle with the input prompt back on screen is well past any
264
+ * realistic typing latency from claude itself.
265
+ */
266
+ const NO_JSONL_FALLBACK_MS = 5_000;
267
+ /**
268
+ * Thrown by sendToAgent when Claude Code wrote a synthetic API-error record to
269
+ * the session log for the just-finished turn (socket dropped, rate limit, …).
270
+ * Surfaced as a distinct class so message handlers can show an API-error
271
+ * banner instead of the generic "⚠️ Request cancelled" used for user /cancel.
272
+ */
273
+ export class ClaudeApiError extends Error {
274
+ detail;
275
+ constructor(detail) {
276
+ super(`Claude Code API error: ${detail}`);
277
+ this.detail = detail;
278
+ this.name = 'ClaudeApiError';
279
+ }
280
+ }
281
+ function resolveCwd(sessionKey) {
282
+ const session = sessionManager.getSession(sessionKey);
283
+ if (!session) {
284
+ throw new Error('No active session. Use /dir to set working directory.');
285
+ }
286
+ const cwd = session.workingDirectory;
287
+ if (cwd && fs.existsSync(cwd))
288
+ return cwd;
289
+ const fallback = process.env.HOME || process.cwd();
290
+ console.warn(`[PtyProvider] Working directory does not exist: ${cwd}, falling back to ${fallback}`);
291
+ return fallback;
292
+ }
293
+ function transcriptSavingDisabled(screenText) {
294
+ return /transcript saving is off/i.test(screenText);
295
+ }
296
+ /**
297
+ * How long a shutdown waits for a hung-up claude to exit on its own before it
298
+ * is killed. Its own clean shutdown takes under a second when idle, and this
299
+ * stays inside the 5s the bot allows its whole shutdown.
300
+ */
301
+ const CLOSE_WAIT_MS = 4_000;
302
+ export class PtyProvider {
303
+ name = 'claude';
304
+ sessions = new Map();
305
+ /** Set by closeAll: from then on no claude is started, and none that exits fails its turn. */
306
+ closing = false;
307
+ /**
308
+ * Last-known usage per sessionKey, refreshed at end-of-turn from claude's
309
+ * on-disk JSONL log. Surfaced via getCachedUsage for the status line and
310
+ * the usage footer.
311
+ */
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
+ }
323
+ getSessionPid(sessionKey) {
324
+ return this.sessions.get(sessionKey)?.term.pid;
325
+ }
326
+ /**
327
+ * Live session keys belonging to `chatId` — the chat itself plus any forum
328
+ * topics under it. Spawn-time settings changed for a whole chat have to
329
+ * reach every one of them, and only this map knows which exist.
330
+ */
331
+ listSessionKeysForChat(chatId) {
332
+ return [...this.sessions.keys()].filter((key) => parseSessionKey(key).chatId === chatId);
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
+ }
391
+ /**
392
+ * Whether claude is generating in this session right now, whoever started the
393
+ * turn. The bot's own bookkeeping can't answer that for a turn claude started
394
+ * itself; the TUI's footer can.
395
+ */
396
+ isSessionGenerating(sessionKey) {
397
+ const session = this.sessions.get(sessionKey);
398
+ return session !== undefined && isGenerating(this._getScreenText(session));
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
+ }
412
+ /**
413
+ * Stop a turn the bot holds no handle on, which is one claude started itself.
414
+ * A turn the bot started goes through its abort controller instead. Returns
415
+ * whether there was a generation to interrupt.
416
+ */
417
+ interruptOwnTurn(sessionKey) {
418
+ const session = this.sessions.get(sessionKey);
419
+ if (!session || !isGenerating(this._getScreenText(session)))
420
+ return false;
421
+ try {
422
+ this._pressEscToInterrupt(session);
423
+ }
424
+ catch {
425
+ return false; // pty already gone
426
+ }
427
+ markSelfTurnInterrupted(sessionKey);
428
+ return true;
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
+ }
490
+ async sendToAgent(sessionKey, message, options) {
491
+ // A provider switch or a cross-backend /resume may have queued a recap of
492
+ // the conversation this fresh session continues.
493
+ const { prompt: promptToSend, tempPaths } = stageImagesForPty(withPendingCarryOver(sessionKey, message), options?.images);
494
+ // Timestamp of the newest compaction already on disk before this turn.
495
+ // Any compaction with a later timestamp afterward was produced by this turn
496
+ // — a manual `/compact` or an auto-compaction that fired near the limit —
497
+ // and we surface it to the caller (compaction renders no `●`, so it's
498
+ // invisible to screen scraping otherwise). See _resolveCompaction below.
499
+ const preCompact = this._readLastCompaction(sessionKey);
500
+ const compactionBeforeMs = preCompact?.timestampMs ?? 0;
501
+ let finalScreenText;
502
+ try {
503
+ finalScreenText = await this._runPtyTurn(sessionKey, promptToSend, options);
504
+ }
505
+ catch (err) {
506
+ // If the user cancelled (/cancel), the pty kill in the abort
507
+ // path was deliberate. Return a graceful "cancelled" response instead
508
+ // of bubbling the error up to handleMessage — handleCancel already
509
+ // showed the user a "🛑 Cancelled" banner; we just need this promise
510
+ // to settle cleanly so subsequent queued messages can proceed.
511
+ if (isCancelled(sessionKey)) {
512
+ return { text: '🛑 Cancelled.', toolsUsed: [] };
513
+ }
514
+ throw err;
515
+ }
516
+ finally {
517
+ // Best-effort cleanup of staged image temp files. Claude has already
518
+ // attached them by the time the turn ends; leaving them around would
519
+ // just accumulate cruft in /tmp. Usually empty — an upload the caller
520
+ // saved itself is never staged.
521
+ for (const p of tempPaths) {
522
+ try {
523
+ fs.unlinkSync(p);
524
+ }
525
+ catch { /* already gone */ }
526
+ }
527
+ }
528
+ // Prefer the JSONL session log over screen scraping. A single turn can
529
+ // emit multiple `●` text blocks separated by tool calls (e.g. "let me
530
+ // check X" → Bash → "found it, here's the answer"); replyFromScreen only
531
+ // sees the last bullet because it reads the final screen. The JSONL log has
532
+ // every text block as a structured record, so joining them gives the user
533
+ // the full reply. The screen is only used when the log has no record of the
534
+ // prompt at all — see below.
535
+ // Before reading anything out of the log, prove claude actually took
536
+ // delivery of this prompt. A pty respawned against a large session spends
537
+ // its first seconds replaying the transcript, and the Enter that submits
538
+ // our prompt gets swallowed while the editor is still coming up. The turn
539
+ // resolves anyway — `--resume` rewrites bookkeeping records on spawn, so
540
+ // the mtime gate in _checkEndOfTurn reads that as "claude did something" —
541
+ // and the JSONL read below then returns the PREVIOUS turn's answer. The
542
+ // user gets a stale reply to a question the model never saw, and every
543
+ // retry repeats it. Only bail when the log demonstrably still ends on the
544
+ // turn it ended on before we submitted; a missing log or missing baseline
545
+ // falls through to the screen-scrape guards below.
546
+ const turnSession = this.sessions.get(sessionKey);
547
+ const markerNow = this._currentPromptMarker(sessionKey);
548
+ const markerAtSubmit = turnSession?.promptMarkerAtSubmit;
549
+ if (turnSession
550
+ && !turnSession.submittedSlashCommand
551
+ && markerNow && markerAtSubmit
552
+ && markerNow.id === markerAtSubmit.id) {
553
+ // Distinguish the two ways the log can fail to move. If claude says it
554
+ // isn't saving the transcript, the prompt was almost certainly answered
555
+ // — we simply can't read it — and the cure is environmental, not a retry.
556
+ if (transcriptSavingDisabled(finalScreenText)) {
557
+ throw new Error("Claude Code isn't saving this session's transcript, so the bot can't read its replies. It inherited a parent Claude session's environment — restart the bot from a shell that isn't inside a Claude Code session.");
558
+ }
559
+ throw new Error("Claude never received your message — the TUI was still busy (this happens on the first message after a restart, while a long session is replayed). Please send it again.");
560
+ }
561
+ // A slash command is answered from the records it wrote, and nothing
562
+ // older. Most commands never reach the model: `/mcp` and the other menus
563
+ // print a line as they close and write no reply at all, so the reader for
564
+ // prompts — which goes back to the latest reply in the log — found the one
565
+ // before the command and sent it again, as though the menu had said it.
566
+ // Nor does the screen scrape below stand in for one: the last `●` on
567
+ // screen is that same reply. An empty answer reads as "Done".
568
+ const fromJsonl = turnSession?.submittedSlashCommand
569
+ ? this._readCommandReply(sessionKey, turnSession.jsonlSizeAtSubmit) ?? ''
570
+ : this._readAssistantResponseFromJsonl(sessionKey);
571
+ // First-turn-in-fresh-cwd failure: claude's TUI is still rendering the
572
+ // welcome banner when _waitForReady's ❯ check trips, our prompt+Enter
573
+ // gets swallowed by the not-yet-receptive editor, the NO_JSONL_FALLBACK
574
+ // timer resolves the turn after 5s, and the screen scrape returns the
575
+ // welcome banner as if it were a reply. Refuse to do that — throw a
576
+ // clear error so the user sees a retry-worthy failure instead of
577
+ // "Done — full response below ↓" followed by `Welcome back Rik!`.
578
+ if (!fromJsonl && looksLikeWelcomeBanner(finalScreenText)) {
579
+ throw new Error("Claude TUI was still on the welcome screen at end-of-turn — your message wasn't received. Please send it again.");
580
+ }
581
+ // Prose already pushed to the chat mid-turn (an ask_user question flushes
582
+ // its own set-up text above the buttons) would otherwise be repeated here,
583
+ // since the JSONL read returns every text record of the turn. Strip it and
584
+ // retire the marker — see turn-prose.ts.
585
+ //
586
+ // A log that holds this prompt but no text after it has already answered:
587
+ // there's nothing to send yet, and the screen can't do better. All it has
588
+ // is older output and chrome, which once went out as the reply. An empty
589
+ // answer reads as "Done". The screen is for a log with no record of the
590
+ // prompt, where it's the only source there is.
591
+ if (fromJsonl === undefined) {
592
+ this._logNoReplyInLog(sessionKey, turnSession, !!markerNow, finalScreenText);
593
+ }
594
+ const assistantResponse = stripDeliveredPrefix(fromJsonl ?? (markerNow ? '' : replyFromScreen(finalScreenText)), getDeliveredProse(sessionKey));
595
+ clearDeliveredProse(sessionKey);
596
+ const usage = this._refreshUsageFromJsonl(sessionKey);
597
+ // If Claude Code's in-flight request died this turn it appended a
598
+ // synthetic `isApiErrorMessage:true` record to the session log. The JSONL
599
+ // readers above already filter that record out (so `assistantResponse` and
600
+ // `usage` reflect the last *real* assistant turn, not the zeroed
601
+ // synthetic), but we still need to surface the failure to the caller — a
602
+ // silent successful return would fire "✅ Done" as if the turn succeeded.
603
+ const botSession = sessionManager.getSession(sessionKey);
604
+ if (botSession?.claudeSessionId) {
605
+ const apiError = readLastApiErrorFromJsonl(botSession.workingDirectory, botSession.claudeSessionId);
606
+ if (apiError)
607
+ throw new ClaudeApiError(apiError);
608
+ }
609
+ const nextPromptSuggestion = await this._awaitPromptSuggestion(sessionKey);
610
+ // Did a compaction land this turn? A newer compact_boundary than the one we
611
+ // saw at submit time means yes. `/compact` writes no assistant prose, so
612
+ // `assistantResponse` would otherwise be the *previous* turn's reply scraped
613
+ // back out of the JSONL — the "I get the same response again" symptom. For a
614
+ // manual compact we replace that stale text with a real confirmation; for an
615
+ // auto-compaction that rode along with a normal turn we keep the assistant's
616
+ // reply and just attach the notification via `compaction`.
617
+ const postCompact = this._readLastCompaction(sessionKey);
618
+ const compactedThisTurn = !!postCompact && postCompact.timestampMs > compactionBeforeMs;
619
+ const isManualCompact = isNativeCompactCommand(message);
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
+ }
628
+ let compaction;
629
+ if (compactedThisTurn && postCompact) {
630
+ compaction = { trigger: postCompact.trigger, preTokens: postCompact.preTokens };
631
+ if (isManualCompact) {
632
+ text = formatCompactionConfirmation(postCompact);
633
+ // The confirmation text already carries the token detail; drop the
634
+ // separate generic notification so the user gets one clean message.
635
+ compaction = undefined;
636
+ }
637
+ }
638
+ else if (isManualCompact) {
639
+ // Command ran but no boundary was recorded — Claude Code skips compaction
640
+ // when the context is already small. Say so instead of echoing stale text.
641
+ text = 'ℹ️ Nothing to compact — the context is already small enough.';
642
+ }
643
+ return {
644
+ text,
645
+ toolsUsed: [], // PTY provider does not have tool usage information
646
+ usage,
647
+ ...(compaction ? { compaction } : {}),
648
+ ...(nextPromptSuggestion ? { nextPromptSuggestion } : {}),
649
+ };
650
+ }
651
+ /** Newest compaction boundary on disk for this session, if any. */
652
+ _readLastCompaction(sessionKey) {
653
+ const botSession = sessionManager.getSession(sessionKey);
654
+ if (!botSession?.claudeSessionId)
655
+ return undefined;
656
+ return readLastCompactionFromJsonl(botSession.workingDirectory, botSession.claudeSessionId);
657
+ }
658
+ /**
659
+ * After end-of-turn extraction completes, poll the xterm buffer briefly
660
+ * for Claude Code's ghost-text prompt suggestion. The probe showed it
661
+ * arrives within ~500ms of the last byte; we already waited
662
+ * POST_STOP_SETTLE_MS (200ms) before reaching here, so a single fast poll
663
+ * with a short cap is plenty. Returns null when:
664
+ * - the chat hasn't opted in (we never set the env var, so claude won't
665
+ * have generated one)
666
+ * - the suggestion didn't arrive within the deadline (rate limit, growth-
667
+ * book gate off, API error during speculation, etc.)
668
+ * - the input box is showing the deterministic "Try ..." placeholder
669
+ */
670
+ async _awaitPromptSuggestion(sessionKey) {
671
+ if (!isSuggestionsEnabled(sessionKey))
672
+ return null;
673
+ const session = this.sessions.get(sessionKey);
674
+ if (!session)
675
+ return null;
676
+ const deadline = Date.now() + 1500;
677
+ while (Date.now() < deadline) {
678
+ const found = scrapePromptSuggestion(session.xterm);
679
+ if (found)
680
+ return found;
681
+ await new Promise((r) => setTimeout(r, 100));
682
+ }
683
+ return null;
684
+ }
685
+ /**
686
+ * Read the last assistant turn's full text from the JSONL session log.
687
+ * Returns undefined when there's no session yet or the log hasn't been
688
+ * written — sendToAgent falls back to screen scrape in that case.
689
+ */
690
+ _readAssistantResponseFromJsonl(sessionKey) {
691
+ const botSession = sessionManager.getSession(sessionKey);
692
+ if (!botSession?.claudeSessionId)
693
+ return undefined;
694
+ return readLastAssistantTurnText(botSession.workingDirectory, botSession.claudeSessionId);
695
+ }
696
+ /**
697
+ * Record why a finished turn had no reply text in the log. This can't be
698
+ * worked out afterwards: whether Stop had arrived separates a turn that
699
+ * ended without text from one the bot ended before the text was written,
700
+ * and the log and screen have both moved on by the next look.
701
+ */
702
+ _logNoReplyInLog(sessionKey, session, logHasPrompt, screenText) {
703
+ const botSession = sessionManager.getSession(sessionKey);
704
+ const logTail = botSession?.claudeSessionId
705
+ ? describeLogTail(botSession.workingDirectory, botSession.claudeSessionId, NO_REPLY_LOG_RECORDS)
706
+ : [];
707
+ const elapsed = session ? `${Math.round((Date.now() - session.submitTimeMs) / 1000)}s` : 'unknown';
708
+ console.warn(`[PtyProvider] ${sessionKey}: no reply text in the log ${elapsed} after submitting `
709
+ + `(stop received: ${session?.stopReceived ?? 'unknown'}, tools in flight: ${session?.inflightTools ?? 'unknown'}, `
710
+ + `log has this prompt: ${logHasPrompt}) — ${logHasPrompt ? 'sending an empty reply' : 'reading the reply off the screen'}`);
711
+ console.warn(`[PtyProvider] ${sessionKey}: last log records:\n`
712
+ + (logTail.length ? logTail.map((l) => ` | ${l}`).join('\n') : ' | (none)'));
713
+ console.warn(`[PtyProvider] ${sessionKey}: last screen lines:\n`
714
+ + tailLines(screenText, STUCK_SCREEN_LINES).map((l) => ` | ${l.trimEnd()}`).join('\n'));
715
+ }
716
+ /** What a slash command answered with, from the records it wrote after `fromByte`. */
717
+ _readCommandReply(sessionKey, fromByte) {
718
+ const botSession = sessionManager.getSession(sessionKey);
719
+ if (!botSession?.claudeSessionId)
720
+ return undefined;
721
+ return readCommandReply(botSession.workingDirectory, botSession.claudeSessionId, fromByte);
722
+ }
723
+ /**
724
+ * Tail the active session's JSONL log for the most recent usage block and
725
+ * cache it. Falls back to undefined if claude hasn't written a usage record
726
+ * yet (very first turn, or pre-existing session without compatible records).
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.
733
+ */
734
+ _refreshUsageFromJsonl(sessionKey) {
735
+ const botSession = sessionManager.getSession(sessionKey);
736
+ if (!botSession?.claudeSessionId)
737
+ return undefined;
738
+ const snapshot = readLastUsageFromJsonl(botSession.workingDirectory, botSession.claudeSessionId);
739
+ if (!snapshot)
740
+ return undefined;
741
+ const usage = {
742
+ inputTokens: snapshot.inputTokens,
743
+ outputTokens: snapshot.outputTokens,
744
+ cacheReadTokens: snapshot.cacheReadTokens,
745
+ cacheWriteTokens: snapshot.cacheWriteTokens,
746
+ // The bot runs claude with the user's 1m-context entitlement (the banner
747
+ // reads "Opus 4.8 (1M context) · Claude Max"). Hardcoding 1_000_000 is
748
+ // a reasonable default — the bot's % calculation just needs *some* sane
749
+ // denominator.
750
+ contextWindow: 1_000_000,
751
+ numTurns: snapshot.numTurns,
752
+ // Report what actually served the turn. If the log has no model on it,
753
+ // say so rather than inventing one — claude picks its own default.
754
+ model: snapshot.model
755
+ || userPreferences.getModel(sessionKey)
756
+ || 'Claude Code default',
757
+ ...(snapshot.effort ? { effort: snapshot.effort } : {}),
758
+ };
759
+ this.usageCache.set(sessionKey, usage);
760
+ return usage;
761
+ }
762
+ async _runPtyTurn(sessionKey, prompt, options) {
763
+ const session = this._getOrCreateSession(sessionKey, options);
764
+ // Bind the in-flight options to claude's session_id so hook callbacks
765
+ // dispatched by the IPC server can find the right AgentOptions to fire.
766
+ // onClaudeStop is the Stop hook bridge — flips stopReceived and re-arms
767
+ // the idle timer with the shorter settle window so we don't wait the
768
+ // full IDLE_MS if no more chunks arrive after Stop fires.
769
+ const activeTurn = {
770
+ sessionKey,
771
+ options: options ?? {},
772
+ onClaudeStop: () => {
773
+ session.stopReceived = true;
774
+ if (session.endOfTurnResolver) {
775
+ if (session.idleTimer)
776
+ clearTimeout(session.idleTimer);
777
+ session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), POST_STOP_SETTLE_MS);
778
+ }
779
+ },
780
+ onToolStart: () => { session.inflightTools++; },
781
+ onToolEnd: () => {
782
+ session.inflightTools = Math.max(0, session.inflightTools - 1);
783
+ // A tool just completed — the screen may be about to update. If the
784
+ // idle timer was waiting, reschedule it so we don't fire while output
785
+ // is still settling.
786
+ if (session.endOfTurnResolver && session.idleTimer) {
787
+ clearTimeout(session.idleTimer);
788
+ const idleMs = session.stopReceived ? POST_STOP_SETTLE_MS : IDLE_MS;
789
+ session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), idleMs);
790
+ }
791
+ },
792
+ };
793
+ registerActiveTurn(session.claudeSessionId, activeTurn);
794
+ // Kept past this turn: claude starts a turn of its own when a background
795
+ // task reports back, and a tool it calls there — ask_user, send_file —
796
+ // reaches the user in this chat.
797
+ if (options?.telegramCtx)
798
+ registerSessionChat(session.claudeSessionId, sessionKey, options.telegramCtx);
799
+ // Tell the monitor relay we're in a turn so it suppresses event posts
800
+ // for assistant text that's being delivered through the normal pipeline.
801
+ markTurnStart(sessionKey);
802
+ // Start clean: a turn that died before its end-of-turn strip must not
803
+ // leave a marker behind that eats the front of the next turn's reply.
804
+ clearDeliveredProse(sessionKey);
805
+ // Mid-turn abort. Two stages:
806
+ // 1. Write Esc (0x1b) into the pty — claude code's TUI shortcut for
807
+ // "interrupt current generation and return to prompt".
808
+ // 2. If Esc doesn't take effect within 2s (claude v2.1.143 sometimes
809
+ // ignores it during certain tool-use states), kill the pty outright.
810
+ // The next turn will respawn with --resume to restore conversation
811
+ // context from the JSONL log, so the user loses at most their place
812
+ // in the in-memory transcript — not the conversation itself.
813
+ const abortSignal = options?.abortController?.signal;
814
+ let abortKillTimer = null;
815
+ const abortHandler = () => {
816
+ try {
817
+ this._pressEscToInterrupt(session);
818
+ }
819
+ catch { /* pty already gone */ }
820
+ abortKillTimer = setTimeout(() => {
821
+ if (session.endOfTurnRejector) {
822
+ console.warn('[PtyProvider] Esc did not interrupt within 2s, killing pty');
823
+ try {
824
+ session.term.kill();
825
+ }
826
+ catch { /* already dead */ }
827
+ // onExit handler will reject endOfTurnRejector and clear the map.
828
+ }
829
+ }, 2000);
830
+ };
831
+ if (abortSignal?.aborted) {
832
+ // Pre-aborted (e.g. user hit /cancel before we even started writing). Skip
833
+ // the whole pty round-trip and return whatever's currently on screen.
834
+ unregisterActiveTurn(session.claudeSessionId);
835
+ return this._getScreenText(session);
836
+ }
837
+ abortSignal?.addEventListener('abort', abortHandler);
838
+ try {
839
+ if (await this._awaitReady(session, sessionKey, options, abortSignal) === 'aborted') {
840
+ return this._getScreenText(session);
841
+ }
842
+ this._maybeRelayUpdateBanner(session, sessionKey);
843
+ await this._applyPermissionMode(session, sessionKey);
844
+ await this._clearAfterEsc(session);
845
+ // Baseline for the idle fallback: capture both wall-clock and the
846
+ // session-log mtime now, so _checkEndOfTurn can tell whether claude has
847
+ // actually produced output for *this* prompt (mtime advanced) or we're
848
+ // looking at a no-op slash command (mtime unchanged → NO_JSONL_FALLBACK_MS
849
+ // safety net).
850
+ session.submitTimeMs = Date.now();
851
+ session.jsonlMtimeAtSubmit = this._currentJsonlMtimeMs(sessionKey);
852
+ session.jsonlSizeAtSubmit = this._currentJsonlSize(sessionKey);
853
+ // Which turn the log ends on right now, so end-of-turn can prove our
854
+ // prompt actually landed rather than trusting a bumped mtime.
855
+ session.promptMarkerAtSubmit = this._currentPromptMarker(sessionKey);
856
+ session.submittedSlashCommand = prompt.trimStart().startsWith('/');
857
+ session.rewound = null;
858
+ // Submit handling for claude's TUI input editor:
859
+ //
860
+ // claude v2.1.143 integrated an Nvim-style multi-line editor (the
861
+ // status bar shows "ctrl+g to edit in Nvim"). It uses a size/timing
862
+ // heuristic to decide whether stdin is a paste vs typing, and on a
863
+ // freshly-spawned PTY (where claude is still mid-init when our prompt
864
+ // arrives) that heuristic occasionally folds the trailing \r into the
865
+ // paste buffer instead of treating it as Enter — the prompt then sits
866
+ // in the input box unsent, the model never runs, and the welcome
867
+ // banner is what survives end-of-turn extraction.
868
+ //
869
+ // Three-part defence:
870
+ // 1. Wrap the prompt in bracketed-paste markers (xterm DECSET 2004).
871
+ // Claude's editor parses them and strips them, so the model sees
872
+ // the same payload as before, but the END marker unambiguously
873
+ // closes the paste — the next byte (\r) is then a real keystroke.
874
+ // 2. Echo-verify: poll the screen until the prompt provably reaches
875
+ // the editor — either its opening words appear in the input box,
876
+ // or claude collapses it into a `[Pasted text #N]` placeholder.
877
+ // Both prove claude's input loop consumed our bytes; the second is
878
+ // what a prompt of four or more lines always looks like.
879
+ // 3. Retry loop: if echo-verify misses (claude's input loop wasn't
880
+ // receptive yet — happens on first-launch of a fresh PTY when
881
+ // ❯ is drawn before the editor is wired up), clear whatever the
882
+ // last attempt may have left in the box, wait a beat and write
883
+ // again. The welcome-banner guard in sendToAgent is the final
884
+ // safety net.
885
+ const ECHO_CAP_MS = 2_000;
886
+ const MAX_ATTEMPTS = 3;
887
+ const RETRY_BACKOFF_MS = 750;
888
+ let echoed = false;
889
+ let pasteId;
890
+ session.lastTypedPrompt = prompt;
891
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
892
+ if (attempt > 0) {
893
+ console.warn(`[PtyProvider] echo-verify miss on attempt ${attempt}/${MAX_ATTEMPTS}, retrying write`);
894
+ await new Promise((r) => setTimeout(r, RETRY_BACKOFF_MS));
895
+ // Empty the box first. A paste that landed too late to be seen is
896
+ // still in the editor, and pasting on top of it would submit the
897
+ // prompt twice over.
898
+ await this._clearInputBox(session, prompt);
899
+ await new Promise((r) => setTimeout(r, CLEAR_SETTLE_MS));
900
+ }
901
+ // Snapshot after the clear: echo-verify proves the prompt landed by
902
+ // what this write *added* to the screen, and the clear is the last
903
+ // thing to change it beforehand.
904
+ const screenBefore = this._getScreenText(session);
905
+ session.term.write(`\x1b[200~${prompt}\x1b[201~`);
906
+ ({ echoed, pasteId } = await this._waitForPromptEcho(session, prompt, ECHO_CAP_MS, screenBefore));
907
+ if (echoed || abortSignal?.aborted)
908
+ break;
909
+ }
910
+ // /cancel landed while the text was going in. It hasn't been submitted, so
911
+ // it needn't be: Enter would hand claude the very prompt just cancelled.
912
+ if (abortSignal?.aborted) {
913
+ session.boxMayHold = undefined;
914
+ await this._clearInputBox(session, prompt);
915
+ return this._getScreenText(session);
916
+ }
917
+ // Enter only once the text is provably in the editor. Writing it anyway
918
+ // was how a swallowed paste turned into a keypress: whatever had focus
919
+ // took the \r, and when that was a dialog it answered it — measured
920
+ // against a live pty, a prompt pasted at `/model` and followed by \r
921
+ // selected the highlighted row and saved it. A prompt that did not land
922
+ // is a prompt to report, not one to punctuate.
923
+ if (!echoed) {
924
+ // Say what the screen actually looked like. Every attempt reports the
925
+ // same sentence to the user, and on its own it names nothing that
926
+ // would tell one cause from another — a prompt claude collapsed and
927
+ // we failed to recognise, a dialog that ate the paste, an editor not
928
+ // yet wired up. Three days of this failing daily produced logs that
929
+ // could not distinguish them, so the screen goes in the log before
930
+ // the box is cleared.
931
+ const screenAtFailure = this._getScreenText(session);
932
+ const seen = pastePlaceholders(screenAtFailure)
933
+ .map((pl) => `#${pl.id}+${pl.lines}`).join(' ') || 'none';
934
+ console.warn(`[PtyProvider] echo-verify gave up: wanted needle ${JSON.stringify(promptNeedle(prompt))}`
935
+ + ` in the input box, or a paste placeholder with an id new since the write`
936
+ + ` (we sent ${pasteLineCount(prompt)} lines);`
937
+ + ` box held ${JSON.stringify(inputBoxText(screenAtFailure) ?? null)};`
938
+ + ` placeholders on screen: ${seen}`);
939
+ console.warn(`[PtyProvider] screen at failure:\n${tailLines(screenAtFailure, 16).join('\n')}`);
940
+ // Leave the editor as we found it. Anything the failed attempts did
941
+ // land would otherwise sit in the box and ride along with whatever
942
+ // the user sends next.
943
+ await this._clearInputBox(session, prompt);
944
+ throw new Error("Claude Code's input box didn't take your message, so nothing was sent. "
945
+ + 'Please send it again.');
946
+ }
947
+ session.submittedPasteId = pasteId;
948
+ session.term.write('\r');
949
+ this._startStream(session, sessionKey);
950
+ await this._confirmSubmitted(session, sessionKey, prompt, abortSignal);
951
+ // From here until the turn ends, a dialog can open with nobody holding
952
+ // these arguments — the end-of-turn timer is all that's watching.
953
+ session.turnRelay = { sessionKey, options };
954
+ return await this._awaitEndOfTurn(session);
955
+ }
956
+ finally {
957
+ this._stopStream(session);
958
+ session.turnRelay = null;
959
+ if (abortKillTimer)
960
+ clearTimeout(abortKillTimer);
961
+ abortSignal?.removeEventListener('abort', abortHandler);
962
+ unregisterActiveTurn(session.claudeSessionId);
963
+ // Re-enable monitor-event relay; the turn pipeline is done forwarding.
964
+ markTurnEnd(sessionKey);
965
+ }
966
+ }
967
+ _getOrCreateSession(sessionKey, options, ahead = false) {
968
+ // closeAll has ended every claude; one started now would outlive the bot.
969
+ if (this.closing) {
970
+ throw new Error("TeleCoder is shutting down, so this didn't reach Claude. Send it again once it's back.");
971
+ }
972
+ const requiredCwd = resolveCwd(sessionKey);
973
+ const executable = options?.executableOverride ?? CLAUDE_BIN;
974
+ const existing = this.sessions.get(sessionKey);
975
+ if (existing) {
976
+ if (existing.cwd === requiredCwd && existing.executable === executable
977
+ && existing.userSetup === loadsUserSetup()) {
978
+ // Reuse the live pty so claude keeps prior turns in context.
979
+ existing.lastUsedAt = Date.now();
980
+ existing.onProgress = options?.onProgress;
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
+ }
987
+ return existing;
988
+ }
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.
991
+ this._cleanupSession(sessionKey);
992
+ }
993
+ // Resume the prior claude session if we have one on disk for this cwd.
994
+ // Bot restarts (or any pty teardown) wipe the live process's in-memory
995
+ // context, but `claude --resume <id>` replays the JSONL log so claude
996
+ // picks up exactly where the previous turn left off. The id is preserved
997
+ // across resumes, so our IPC routing key stays stable.
998
+ const botSession = sessionManager.getSession(sessionKey);
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
+ }
1022
+ const resuming = !!(priorId && claudeSessionFileExists(requiredCwd, priorId));
1023
+ const claudeSessionId = resuming ? priorId : randomUUID();
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);
1028
+ }
1029
+ const ipcPort = getIpcPort();
1030
+ const settingsJson = buildSettingsJson(ipcPort);
1031
+ const mcpConfigJson = buildMcpConfigJson(buildMcpEnv({
1032
+ TELECODER_IPC_PORT: String(ipcPort),
1033
+ TELECODER_CLAUDE_SESSION_ID: claudeSessionId,
1034
+ // Workspace root for the MCP subprocess (used by list_projects). This is
1035
+ // the top-level dev directory (`config.WORKSPACE_DIR`), NOT the current
1036
+ // project cwd — list_projects needs to enumerate sibling projects.
1037
+ TELECODER_WORKSPACE_ROOT: getWorkspaceRoot(),
1038
+ }));
1039
+ // /effort and /model are per-thread preferences the CLI accepts as flags.
1040
+ // They can only be applied at spawn, so changing either tears the pty down
1041
+ // (see handleEffort / handleModelCommand) to force a respawn — context
1042
+ // survives because the next spawn resumes the same session id.
1043
+ const effort = userPreferences.getEffort(sessionKey);
1044
+ const model = userPreferences.getModel(sessionKey);
1045
+ const userSetup = loadsUserSetup();
1046
+ const args = [
1047
+ '--dangerously-skip-permissions',
1048
+ ...(resuming ? ['--resume', claudeSessionId] : ['--session-id', claudeSessionId]),
1049
+ ...(effort ? ['--effort', effort] : []),
1050
+ ...(model ? ['--model', model] : []),
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.
1058
+ '--settings', settingsJson,
1059
+ // Spawn our standalone MCP server as a stdio subprocess, beside
1060
+ // whatever EXTRA_MCP_CONFIG names.
1061
+ '--mcp-config', mcpConfigJson,
1062
+ // Make our MCP tools discoverable to claude. Without this the tool
1063
+ // names appear in claude's deferred-tools list but claude often picks
1064
+ // WebFetch/Bash for the same task because the deferred listing has
1065
+ // no descriptions. The same note says a message arriving inside
1066
+ // <pasted_content> tags is still the user's own (PASTED_MESSAGE_NOTE).
1067
+ '--append-system-prompt', buildPtySystemPromptNote(),
1068
+ // Hard-disable claude's built-in AskUserQuestion. The headless xterm has
1069
+ // no real user to type a response, so an AskUserQuestion call freezes
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).
1074
+ //
1075
+ // CronCreate / ScheduleWakeup / RemoteTrigger are also blocked: their
1076
+ // fires land outside our session (cron in claude's own process, RemoteTrigger on
1077
+ // claude.ai's servers) and never reach the Telegram chat.
1078
+ // telecoder_loop / telecoder_schedule replace them and route fires
1079
+ // through the bot. Set TELECODER_ALLOW_NATIVE_SCHEDULING=1 to keep
1080
+ // the built-ins enabled if you want to experiment.
1081
+ '--disallowedTools', legacyEnv('ALLOW_NATIVE_SCHEDULING') === '1'
1082
+ ? 'AskUserQuestion'
1083
+ : 'AskUserQuestion,CronCreate,ScheduleWakeup,RemoteTrigger',
1084
+ ];
1085
+ // Five minutes past the question timeout, and never under the 15 min it
1086
+ // has always been, so the bot's own question timer is the one that fires.
1087
+ const mcpCallMs = String(Math.max(15 * 60 * 1000, questionTimeoutMs() + 5 * 60 * 1000));
1088
+ const term = spawn(executable, args, {
1089
+ name: 'xterm-256color',
1090
+ cols: COLS,
1091
+ rows: ROWS,
1092
+ cwd: requiredCwd,
1093
+ env: {
1094
+ ...envWithoutParentSession(),
1095
+ TERM: 'xterm-256color',
1096
+ // The IPC server's token, for the hooks and the MCP subprocess (which
1097
+ // inherits claude's env). Here and nowhere in `args`, which `ps` shows.
1098
+ [IPC_TOKEN_ENV]: getIpcToken(),
1099
+ // Belt and braces alongside the stripped markers above: whatever else
1100
+ // the bot inherited, this pty must write its session log — the bot has
1101
+ // no other way to read the model's reply.
1102
+ CLAUDE_CODE_FORCE_SESSION_PERSISTENCE: '1',
1103
+ // Claude code's default MCP tool-call timeout is 60s. telecoder_ask_user
1104
+ // long-polls for up to QUESTION_TIMEOUT_MINUTES waiting on a Telegram
1105
+ // button tap; without this override claude aborts the call at 60s,
1106
+ // fires postToolUseFailure with an empty tool_response (rendered as
1107
+ // "(no output)" in the action log), and the model gives up on the tool.
1108
+ MCP_TOOL_TIMEOUT: mcpCallMs,
1109
+ // And claude (2.1.311 at least) moves an MCP call still running after
1110
+ // 120s to the background, and the turn goes on without it: a question
1111
+ // left unanswered for two minutes ended its turn there, its answer to
1112
+ // come back later as a task notification. Not before the call would
1113
+ // time out. A time rather than 0, which would also stop claude moving
1114
+ // a call aside when a message arrives mid-call, to let it through.
1115
+ CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS: mcpCallMs,
1116
+ // Suppress claude's "How is Claude doing this session?" feedback
1117
+ // survey. It renders as plain text in the PTY ("1: Bad 2: Fine ..."),
1118
+ // which has no clickable buttons in Telegram and just clutters the
1119
+ // chat — there's no real user at a TUI to respond.
1120
+ CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY: '1',
1121
+ // Keep claude on its classic renderer. Every reader of this screen —
1122
+ // the input box, the spinner, the dialogs — is built for it, and
1123
+ // 2.1.310 can switch a launch to its fullscreen one without being
1124
+ // asked: an upsell trial, a fresh install or a remote feature gate
1125
+ // all turn it on. Fullscreen draws on the alternate screen, puts a
1126
+ // dialog in a pane of its own, and makes `/mcp`'s tool list taller
1127
+ // than the dialog parser reads, so a probe pty that came up that way
1128
+ // was offered "Enter — select" on a list whose cursor it couldn't
1129
+ // see. Claude checks this ahead of every one of those switches.
1130
+ CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN: '1',
1131
+ // Enable Claude Code's speculative next-prompt feature when the chat
1132
+ // has opted in. Suggestion is rendered as ghost text in the input box;
1133
+ // the scraper picks it up at end-of-turn (see prompt-suggestion-scraper).
1134
+ // Spawn-time only — toggling /suggestions mid-session has no effect
1135
+ // until the PTY is respawned.
1136
+ ...(isSuggestionsEnabled(sessionKey) ? { CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION: '1' } : {}),
1137
+ },
1138
+ });
1139
+ const xterm = new Terminal({
1140
+ cols: COLS,
1141
+ rows: ROWS,
1142
+ scrollback: 1000,
1143
+ allowProposedApi: true,
1144
+ });
1145
+ const session = {
1146
+ term,
1147
+ xterm,
1148
+ cwd: requiredCwd,
1149
+ executable,
1150
+ userSetup,
1151
+ claudeSessionId,
1152
+ lastChunkAt: Date.now(),
1153
+ lastUsedAt: Date.now(),
1154
+ screenSeen: null,
1155
+ screenChangedAt: Date.now(),
1156
+ endOfTurnResolver: null,
1157
+ endOfTurnRejector: null,
1158
+ idleTimer: null,
1159
+ hardTimer: null,
1160
+ onProgress: options?.onProgress,
1161
+ stream: null,
1162
+ onTip: options?.onTip,
1163
+ lastTip: null,
1164
+ onBackgroundHint: options?.onBackgroundHint,
1165
+ lastBackgroundHint: false,
1166
+ stopReceived: false,
1167
+ inflightTools: 0,
1168
+ submitTimeMs: 0,
1169
+ jsonlMtimeAtSubmit: 0,
1170
+ jsonlSizeAtSubmit: 0,
1171
+ promptMarkerAtSubmit: undefined,
1172
+ submittedSlashCommand: false,
1173
+ submittedPasteId: undefined,
1174
+ lastTypedPrompt: undefined,
1175
+ boxMayHold: undefined,
1176
+ awaitingResumeReplay: resuming,
1177
+ idUnclaimed,
1178
+ updateBannerChecked: false,
1179
+ turnRelay: null,
1180
+ relayingModal: false,
1181
+ dialogAnsweredAt: null,
1182
+ rewound: null,
1183
+ };
1184
+ term.onData((chunk) => this._onData(session, chunk));
1185
+ term.onExit(({ exitCode, signal }) => {
1186
+ // Not when the bot is shutting down: the turn ends with it, as it always
1187
+ // has, rather than as an error posted to the chat on the way out.
1188
+ if (session.endOfTurnRejector && !this.closing) {
1189
+ session.endOfTurnRejector(new Error(`claude exited (code=${exitCode}, signal=${signal}) mid-turn`));
1190
+ }
1191
+ // Identity check: /clear or a workspace switch synchronously kills
1192
+ // this term, removes us from the map, and may immediately spawn a
1193
+ // replacement at the same sessionKey. By the time *this* late onExit
1194
+ // fires, the replacement is the live session — don't wipe it out.
1195
+ watchUnregister(sessionKey, session.xterm);
1196
+ if (this.sessions.get(sessionKey) === session) {
1197
+ this.sessions.delete(sessionKey);
1198
+ unregisterSessionChat(session.claudeSessionId);
1199
+ // claude went down on its own — a crash, an OOM kill — so nothing has
1200
+ // been through _cleanupSession. Its background tasks went with it, and
1201
+ // the respawn reports them stopped by task id alone, which the relay
1202
+ // can't match to what it armed: left in place they'd count as running
1203
+ // for good.
1204
+ teardownMonitorRelay(sessionKey);
1205
+ }
1206
+ });
1207
+ this.sessions.set(sessionKey, session);
1208
+ watchRegister(sessionKey, requiredCwd, xterm);
1209
+ return session;
1210
+ }
1211
+ _onData(session, chunk) {
1212
+ session.lastChunkAt = Date.now();
1213
+ session.xterm.write(chunk);
1214
+ watchData(session.xterm, chunk);
1215
+ // Mirror Claude Code's live spinner tip into the Telegram status line.
1216
+ // The tip is drawn in place at the bottom of the TUI — scrape it directly
1217
+ // and only fire when it actually changes (including when it clears to null).
1218
+ if (session.onTip) {
1219
+ const tip = scrapeTip(session.xterm);
1220
+ if (tip !== session.lastTip) {
1221
+ session.lastTip = tip;
1222
+ session.onTip(tip);
1223
+ }
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
+ }
1234
+ if (session.endOfTurnResolver) {
1235
+ if (session.idleTimer)
1236
+ clearTimeout(session.idleTimer);
1237
+ const idleMs = session.stopReceived ? POST_STOP_SETTLE_MS : IDLE_MS;
1238
+ session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), idleMs);
1239
+ }
1240
+ }
1241
+ _checkEndOfTurn(session) {
1242
+ if (!session.endOfTurnResolver)
1243
+ return;
1244
+ const idleMs = session.stopReceived ? POST_STOP_SETTLE_MS : IDLE_MS;
1245
+ const sinceLast = Date.now() - session.lastChunkAt;
1246
+ const isIdle = sinceLast >= idleMs;
1247
+ // Ahead of the in-flight guard below, deliberately: claude asks for
1248
+ // permission *inside* a tool call, so inflightTools is >0 for exactly the
1249
+ // dialogs this catches, and checking after it would never see one.
1250
+ if (isIdle && !session.relayingModal
1251
+ && blockingModal(this._getScreenText(session), screenMarks(session.xterm))) {
1252
+ this._relayMidTurn(session);
1253
+ session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), idleMs);
1254
+ return;
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
+ }
1264
+ // Stop hook fired → Stop itself is the authoritative end-of-turn signal,
1265
+ // we just wait for a brief settle. Otherwise fall back to the idle path:
1266
+ // pty quiet for IDLE_MS, the input prompt is back on screen, AND claude
1267
+ // has either written something to the JSONL log since we submitted
1268
+ // (model turns, /compact, /clear all do) or we've waited
1269
+ // NO_JSONL_FALLBACK_MS to cover purely-TUI slash commands like /cost.
1270
+ // The JSONL-mtime gate replaces an older bullet-count check that hung
1271
+ // indefinitely on /compact because compaction renders no `●` glyph.
1272
+ const jsonlMtime = this._lookupJsonlMtime(session);
1273
+ const sawJsonlActivity = jsonlMtime > session.jsonlMtimeAtSubmit;
1274
+ const sinceSubmit = Date.now() - session.submitTimeMs;
1275
+ const claudeProducedSomething = sawJsonlActivity || sinceSubmit >= NO_JSONL_FALLBACK_MS;
1276
+ // Idle plus a visible prompt is not end-of-turn. The glyph is drawn for
1277
+ // the whole turn, so all that separates a finished turn from a paused one
1278
+ // is how long the pty has been quiet — and a turn long enough to pause
1279
+ // past the idle window reads as finished. A 51-minute turn was handed
1280
+ // back that way: the queue moved on and pushed the next message into a
1281
+ // claude still working on the previous one, which then sat in the
1282
+ // readiness wait until its ceiling ran out. The interrupt hint is on
1283
+ // screen for exactly as long as there is a generation to interrupt. Stop
1284
+ // stays authoritative — it fires at the real end of the turn — and
1285
+ // MAX_TURN_MS remains the backstop for a turn neither path resolves.
1286
+ const stillGenerating = isGenerating(this._getScreenText(session));
1287
+ // A dialog we just answered is claude resuming, not claude finishing, and
1288
+ // for a moment the two are indistinguishable on screen. Hold the idle path
1289
+ // off until claude proves which it is, bounded so a dialog whose answer
1290
+ // genuinely did end the turn still resolves. Stop stays authoritative: it
1291
+ // fires at the real end of a turn, so it is never worth waiting past.
1292
+ const resume = dialogResumeState(session.dialogAnsweredAt, {
1293
+ generating: stillGenerating,
1294
+ inflightTools: session.inflightTools,
1295
+ now: Date.now(),
1296
+ graceMs: DIALOG_RESUME_GRACE_MS,
1297
+ });
1298
+ session.dialogAnsweredAt = resume.answeredAt;
1299
+ const resumingAfterDialog = resume.resuming;
1300
+ const hold = turnHold({
1301
+ stopReceived: session.stopReceived,
1302
+ inflightTools: session.inflightTools,
1303
+ isIdle,
1304
+ hasInputBox: this._hasInputBox(session),
1305
+ stillGenerating,
1306
+ claudeProducedSomething,
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),
1311
+ });
1312
+ // A count that outlived its Stop is a lost hook, not a live tool. Say so:
1313
+ // silence here is what made a two-hour hang look like a long turn.
1314
+ if (session.stopReceived && session.inflightTools > 0) {
1315
+ console.warn(`[PtyProvider] ${session.claudeSessionId}: Stop fired with ${session.inflightTools} tool(s) `
1316
+ + 'still counted as open — a PostToolUse hook was lost; trusting Stop');
1317
+ session.inflightTools = 0;
1318
+ }
1319
+ if (hold === null) {
1320
+ const resolved = session.endOfTurnResolver;
1321
+ session.endOfTurnResolver = null;
1322
+ session.endOfTurnRejector = null;
1323
+ if (session.hardTimer)
1324
+ clearTimeout(session.hardTimer);
1325
+ resolved(this._getScreenText(session));
1326
+ }
1327
+ else {
1328
+ // If we're only waiting on NO_JSONL_FALLBACK_MS, re-arm just past the
1329
+ // deadline so a no-op slash command doesn't sit on an idle timer that
1330
+ // only re-fires when the pty produces another chunk.
1331
+ const idleRemaining = Math.max(stillGenerating ? GENERATING_RECHECK_MS : 50, idleMs - sinceLast);
1332
+ const fallbackRemaining = claudeProducedSomething
1333
+ ? Infinity
1334
+ : Math.max(50, NO_JSONL_FALLBACK_MS - sinceSubmit);
1335
+ // Waiting on claude to resume is its own cadence: the pty is quiet by
1336
+ // definition here, so idleRemaining has already collapsed to its floor
1337
+ // and would otherwise spin this check every 50ms for the whole window.
1338
+ const wait = hold === 'resuming'
1339
+ ? DIALOG_RESUME_POLL_MS
1340
+ : hold === 'tools' || hold === 'stop'
1341
+ ? idleMs
1342
+ : Math.min(idleRemaining, fallbackRemaining);
1343
+ session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), wait);
1344
+ }
1345
+ }
1346
+ /** Identity of the last user prompt in the active session's log, if any. */
1347
+ _currentPromptMarker(sessionKey) {
1348
+ const botSession = sessionManager.getSession(sessionKey);
1349
+ if (!botSession?.claudeSessionId)
1350
+ return undefined;
1351
+ return readLastUserPromptMarker(botSession.workingDirectory, botSession.claudeSessionId);
1352
+ }
1353
+ /** Cheap fs.stat on the active session's JSONL log; 0 if not on disk yet. */
1354
+ _currentJsonlMtimeMs(sessionKey) {
1355
+ const botSession = sessionManager.getSession(sessionKey);
1356
+ if (!botSession?.claudeSessionId)
1357
+ return 0;
1358
+ return sessionJsonlMtimeMs(botSession.workingDirectory, botSession.claudeSessionId);
1359
+ }
1360
+ /** Size in bytes of the active session's JSONL log; 0 if not on disk yet. */
1361
+ _currentJsonlSize(sessionKey) {
1362
+ const botSession = sessionManager.getSession(sessionKey);
1363
+ if (!botSession?.claudeSessionId)
1364
+ return 0;
1365
+ return sessionJsonlSize(botSession.workingDirectory, botSession.claudeSessionId);
1366
+ }
1367
+ _lookupJsonlMtime(session) {
1368
+ return sessionJsonlMtimeMs(session.cwd, session.claudeSessionId);
1369
+ }
1370
+ _hasInputBox(session) {
1371
+ return hasInputBox(this._getScreenText(session));
1372
+ }
1373
+ _awaitEndOfTurn(session) {
1374
+ return new Promise((resolve, reject) => {
1375
+ // Intentionally NOT resetting xterm: the pty is shared across turns.
1376
+ // stopReceived MUST be reset — it's per-turn state and the previous turn
1377
+ // left it true. inflightTools should already be 0 at end-of-turn but
1378
+ // reset defensively in case a Pre→Post pair was skipped (e.g. claude
1379
+ // killed mid-tool).
1380
+ session.stopReceived = false;
1381
+ session.inflightTools = 0;
1382
+ // Per-turn, like stopReceived: a dialog answered in the previous turn
1383
+ // must not hold this one's first idle check off.
1384
+ session.dialogAnsweredAt = null;
1385
+ // Each turn gets a fresh Telegram status message (StreamState.tip starts
1386
+ // null), so clear lastTip to force a re-push of the current tip.
1387
+ session.lastTip = null;
1388
+ session.lastBackgroundHint = false;
1389
+ session.endOfTurnResolver = resolve;
1390
+ session.endOfTurnRejector = reject;
1391
+ session.idleTimer = setTimeout(() => this._checkEndOfTurn(session), IDLE_MS);
1392
+ session.hardTimer = setTimeout(() => {
1393
+ if (session.endOfTurnRejector) {
1394
+ const r = session.endOfTurnRejector;
1395
+ session.endOfTurnResolver = null;
1396
+ session.endOfTurnRejector = null;
1397
+ r(new Error(`turn exceeded ${MAX_TURN_MS}ms`));
1398
+ }
1399
+ }, MAX_TURN_MS);
1400
+ });
1401
+ }
1402
+ /**
1403
+ * Wait until claude is actually ready to receive a prompt: it isn't
1404
+ * generating, the input prompt glyph is on screen, and the render has stood
1405
+ * still for `idleMs`.
1406
+ *
1407
+ * Stillness rather than stdout-idle, because a working TUI never falls
1408
+ * silent: it redraws several times a second for as long as the turn lasts,
1409
+ * so waiting for quiet on a session that is mid-turn can only end in the
1410
+ * ceiling expiring. That is what cost a delivery ten minutes and then
1411
+ * blamed transcript replay for it. The input glyph doesn't separate the two
1412
+ * either; claude draws it throughout a turn. `isGenerating` reads the state
1413
+ * off the TUI's own chrome instead of guessing at it from the pipe.
1414
+ *
1415
+ * Three outcomes, because they need different answers:
1416
+ * - `ready`: submit.
1417
+ * - `busy`: claude is mid-turn and stayed there past BUSY_READY_CEILING_MS.
1418
+ * The prompt was never the problem and a retry will behave the same until
1419
+ * the turn ends.
1420
+ * - `modal`: claude is asking something — a dialog is covering the input
1421
+ * box. It will not clear on its own, so the caller relays it to the chat
1422
+ * rather than waiting out a ceiling that cannot help.
1423
+ * - `unready`: the input box never appeared. `capMs` bounds *silence* here
1424
+ * and `ceilingMs` the wait as a whole, measured from when the TUI last
1425
+ * stopped working — a session that spent twenty minutes on a turn hasn't
1426
+ * used up its startup budget.
1427
+ * - `aborted`: the user cancelled while we waited. Nothing was submitted,
1428
+ * so the caller hands back the screen as it stands.
1429
+ *
1430
+ * The caller must not submit on anything but `ready` — a prompt written into
1431
+ * a TUI that isn't listening is lost silently, and the turn then resolves on
1432
+ * the previous turn's log.
1433
+ */
1434
+ async _waitForReady(session, sessionKey, idleMs, capMs, ceilingMs, abortSignal) {
1435
+ let waitingSince = Date.now();
1436
+ let generatingSince = null;
1437
+ let sawGenerating = false;
1438
+ let signature = screenSignature(this._getScreenText(session));
1439
+ // Anchored to the last chunk, not to now: nothing can have redrawn the
1440
+ // screen since then, so a pty that has sat at its prompt for an hour is
1441
+ // already still and submits immediately instead of waiting out `idleMs`
1442
+ // it has plainly served — or tripping the silence cap on the way there.
1443
+ let stillSince = session.lastChunkAt;
1444
+ // Back-to-back turns — a session driven from elsewhere, or one working
1445
+ // through its own background-task notifications — reset both budgets
1446
+ // below every time generation resumes, so bound the wait as a whole too.
1447
+ const hardDeadline = Date.now() + BUSY_READY_CEILING_MS + ceilingMs;
1448
+ for (;;) {
1449
+ // The wait can now outlast a turn, so /cancel has to reach it. The abort
1450
+ // handler has already written Esc at the pty; there is no prompt to
1451
+ // deliver on the other side of that.
1452
+ if (abortSignal?.aborted)
1453
+ return 'aborted';
1454
+ if (Date.now() >= hardDeadline) {
1455
+ console.warn(`[PtyProvider] ${sessionKey}: pty never came free within `
1456
+ + `${Math.round((BUSY_READY_CEILING_MS + ceilingMs) / 60_000)}m — not submitting into it`);
1457
+ return sawGenerating ? 'busy' : 'unready';
1458
+ }
1459
+ const screenText = this._getScreenText(session);
1460
+ const current = screenSignature(screenText);
1461
+ if (current !== signature) {
1462
+ signature = current;
1463
+ stillSince = Date.now();
1464
+ }
1465
+ if (isGenerating(screenText)) {
1466
+ sawGenerating = true;
1467
+ if (generatingSince === null) {
1468
+ generatingSince = Date.now();
1469
+ console.warn(`[PtyProvider] ${sessionKey}: claude is mid-turn — holding this prompt until it finishes`);
1470
+ }
1471
+ if (Date.now() - generatingSince >= BUSY_READY_CEILING_MS) {
1472
+ const busyFor = Math.round((Date.now() - generatingSince) / 60_000);
1473
+ console.warn(`[PtyProvider] ${sessionKey}: still generating after ${busyFor}m — not submitting into it`);
1474
+ return 'busy';
1475
+ }
1476
+ }
1477
+ else {
1478
+ // The turn just ended: the screen is mid-redraw and the startup
1479
+ // budget starts from here, not from a wait spent watching it work.
1480
+ if (generatingSince !== null) {
1481
+ generatingSince = null;
1482
+ waitingSince = Date.now();
1483
+ stillSince = session.lastChunkAt;
1484
+ }
1485
+ if (Date.now() - stillSince >= idleMs) {
1486
+ if (hasInputBox(screenText))
1487
+ return 'ready';
1488
+ // Settled on something that isn't the input box. A dialog is the
1489
+ // one case worth reporting separately: it will never clear on its
1490
+ // own, so waiting out the ceiling only delays telling someone.
1491
+ if (parseModal(screenText, screenMarks(session.xterm)))
1492
+ return 'modal';
1493
+ }
1494
+ const waited = Date.now() - waitingSince;
1495
+ const quiet = Date.now() - session.lastChunkAt;
1496
+ // Quiet this long with no input box is a stuck TUI, not a slow one.
1497
+ if (waited >= ceilingMs || quiet >= capMs) {
1498
+ console.warn(`[PtyProvider] ${sessionKey}: TUI not ready after ${Math.round(waited / 1000)}s `
1499
+ + `(quiet ${Math.round(quiet / 1000)}s, still ${Math.round((Date.now() - stillSince) / 1000)}s, `
1500
+ + `input box ${hasInputBox(screenText) ? 'open' : 'absent'}) — refusing to submit into it`);
1501
+ // What it was stuck *on*, not merely that it was stuck. Without this
1502
+ // the log says "input box absent" and nothing else, and working out
1503
+ // that claude was sitting on a folder-trust prompt meant spawning
1504
+ // ptys by hand outside the bot to see the screen it had already
1505
+ // read. The tail is where a dialog's rows and footer live.
1506
+ console.warn(`[PtyProvider] ${sessionKey}: last screen lines:\n`
1507
+ + screenText.split('\n').map((l) => l.trimEnd()).filter((l) => l.trim())
1508
+ .slice(-STUCK_SCREEN_LINES).map((l) => ` | ${l}`).join('\n'));
1509
+ return 'unready';
1510
+ }
1511
+ }
1512
+ await new Promise((r) => setTimeout(r, READY_POLL_MS));
1513
+ }
1514
+ }
1515
+ /**
1516
+ * Wait for the input box, relaying a dialog to the chat if one is in the way.
1517
+ *
1518
+ * Wraps {@link _waitForReady} with the two things a caller always wants: the
1519
+ * right patience for a resuming pty, and an answer to `modal`. Throws with a
1520
+ * chat-ready message on every outcome that isn't a delivered prompt.
1521
+ */
1522
+ async _awaitReady(session, sessionKey, options, abortSignal) {
1523
+ // A pty spawned with --resume is still replaying the transcript; give it
1524
+ // the patience that needs rather than pasting into a busy editor.
1525
+ const resuming = session.awaitingResumeReplay;
1526
+ const [idleMs, capMs, ceilingMs] = resuming
1527
+ ? [RESUME_SETTLE_IDLE_MS, RESUME_STARTUP_MAX_MS, RESUME_READY_CEILING_MS]
1528
+ : [IDLE_MS, STARTUP_MAX_MS, STARTUP_READY_CEILING_MS];
1529
+ // One relay per prompt. A dialog with several screens — a menu, or one
1530
+ // dialog straight behind another — is followed inside that relay until
1531
+ // the input box is back. A dialog that opens after that, once claude has
1532
+ // already returned to its input box, wants a person at a terminal, not a
1533
+ // bot working through a stack of them on someone's behalf.
1534
+ let relayed = false;
1535
+ for (;;) {
1536
+ const verdict = await this._waitForReady(session, sessionKey, idleMs, capMs, ceilingMs, abortSignal);
1537
+ if (verdict === 'ready') {
1538
+ session.awaitingResumeReplay = false;
1539
+ return 'ready';
1540
+ }
1541
+ if (verdict === 'aborted')
1542
+ return 'aborted';
1543
+ if (verdict === 'busy')
1544
+ throw new Error(stillWorkingError());
1545
+ // A CLI that was never set up or signed in opens its first-run screens
1546
+ // instead of the input box. The theme picker and the login menu would
1547
+ // parse as dialogs, but relaying them only leads to a sign-in link and a
1548
+ // code prompt the chat can't complete — that wants the bot's machine.
1549
+ const setup = claudeSetupScreen(this._getScreenText(session));
1550
+ if (setup && (verdict === 'modal' || verdict === 'unready')) {
1551
+ console.warn(`[PtyProvider] ${sessionKey}: claude is at its ${setup} screen — not logged in or not set up`);
1552
+ throw new ClaudeNotLoggedInError(setup);
1553
+ }
1554
+ if (verdict === 'modal' && !relayed) {
1555
+ relayed = true;
1556
+ // Throws unless a key was actually pressed, in which case we go round
1557
+ // and wait for the input box the dialog was covering.
1558
+ await this._relayModal(session, sessionKey, options, 'before-prompt');
1559
+ continue;
1560
+ }
1561
+ if (verdict === 'modal') {
1562
+ throw new Error("Claude Code opened another dialog straight after the last one, so your message "
1563
+ + "wasn't delivered. That usually wants a person at the terminal — check the "
1564
+ + 'session before sending it again.');
1565
+ }
1566
+ // Leave awaitingResumeReplay set on failure: the replay is still the
1567
+ // thing we're waiting out, so the retry deserves the same patience.
1568
+ throw new Error(resuming
1569
+ ? "Claude Code is still replaying this session's transcript and hasn't opened its input box, so your message wasn't delivered. That normally means the machine is under heavy load — please send it again in a minute."
1570
+ : "Claude Code's input box never appeared, so your message wasn't delivered. Please send it again.");
1571
+ }
1572
+ }
1573
+ /**
1574
+ * Put the session in this chat's mode, before anything is submitted.
1575
+ *
1576
+ * The pty is spawned with `--dangerously-skip-permissions` and cycled from
1577
+ * there, rather than launched in the mode we want. That looks backwards and
1578
+ * isn't: measured against a live pty, the shift+tab cycle has five stops
1579
+ * when the flag is present and four when it isn't, and the missing one is
1580
+ * bypass. Launching without it would make `/mode bypass` unreachable for
1581
+ * good, so the flag buys the full cycle and the first turn spends one
1582
+ * keypress leaving it.
1583
+ *
1584
+ * A chosen mode and the default fail differently, which is the whole reason
1585
+ * the two are tracked separately here. A choice is a constraint: every mode
1586
+ * other than bypass asks claude to check in more often, so running the turn
1587
+ * in whatever the session happens to be in would hand it more freedom than
1588
+ * the chat allowed, and refusing is the safer failure. The default is a
1589
+ * preference — falling back to the launch mode is exactly what every turn
1590
+ * did before this existed, so it is worth a log line and nothing more.
1591
+ */
1592
+ async _applyPermissionMode(session, sessionKey) {
1593
+ const chosen = userPreferences.getPermissionMode(sessionKey);
1594
+ const target = chosen ?? defaultPermissionMode();
1595
+ const pty = {
1596
+ write: (data) => session.term.write(data),
1597
+ screen: () => this._getScreenText(session),
1598
+ };
1599
+ const outcome = await ensurePermissionMode(pty, target);
1600
+ const label = permissionModeInfo(target).label;
1601
+ if (outcome.kind === 'already')
1602
+ return;
1603
+ if (outcome.kind === 'switched') {
1604
+ console.log(`[PtyProvider] ${sessionKey}: permission mode ${outcome.from} → ${outcome.to}`);
1605
+ return;
1606
+ }
1607
+ if (!chosen) {
1608
+ console.warn(`[PtyProvider] ${sessionKey}: couldn't reach the default "${label}" mode `
1609
+ + `(${outcome.kind}) — running in the mode the pty launched in`);
1610
+ return;
1611
+ }
1612
+ if (outcome.kind === 'unreadable') {
1613
+ throw new Error(`I couldn't read which permission mode Claude Code is in, so I didn't send your `
1614
+ + `message — running it outside "${label}" mode isn't mine to decide. `
1615
+ + 'Try again in a moment.');
1616
+ }
1617
+ throw new Error(`I couldn't switch Claude Code into "${label}" mode — it stopped at `
1618
+ + `${outcome.last ?? 'something unreadable'}, so your message wasn't sent. `
1619
+ + 'Check the session, or pick a different mode with /mode.');
1620
+ }
1621
+ /**
1622
+ * Ask the chat about a dialog that opened mid-turn, without blocking the
1623
+ * timer that found it.
1624
+ *
1625
+ * Every outcome other than "a key was pressed and the dialog cleared" ends
1626
+ * the turn with the reason, rather than letting it ride to the hard ceiling
1627
+ * — two silent hours was the old behaviour and the whole point of this. The
1628
+ * dialog is left exactly as it is when nobody answers, so the next message
1629
+ * meets it in `_awaitReady` and gets offered the same buttons again.
1630
+ */
1631
+ _relayMidTurn(session) {
1632
+ const relay = session.turnRelay;
1633
+ if (!relay)
1634
+ return;
1635
+ session.relayingModal = true;
1636
+ void this._relayModal(session, relay.sessionKey, relay.options, 'mid-turn')
1637
+ .catch((error) => {
1638
+ this._failTurn(session, error instanceof Error ? error : new Error(String(error)));
1639
+ })
1640
+ .finally(() => { session.relayingModal = false; });
1641
+ }
1642
+ /** End the in-flight turn with `error`, if one is still waiting. */
1643
+ _failTurn(session, error) {
1644
+ const reject = session.endOfTurnRejector;
1645
+ if (!reject)
1646
+ return;
1647
+ session.endOfTurnResolver = null;
1648
+ session.endOfTurnRejector = null;
1649
+ if (session.hardTimer)
1650
+ clearTimeout(session.hardTimer);
1651
+ reject(error);
1652
+ }
1653
+ /**
1654
+ * Put claude's dialog in the chat and press what comes back, screen after
1655
+ * screen for a dialog that has more than one.
1656
+ *
1657
+ * Returns only once the dialog has closed. Every other outcome throws,
1658
+ * saying what it means for `stage` (see openDialogError) — that beats a
1659
+ * silent retry. Nothing is pressed on a timeout: see modal-relay.ts for why
1660
+ * an unanswered dialog is left exactly as it is.
1661
+ */
1662
+ async _relayModal(session, sessionKey, options, stage) {
1663
+ const modal = parseModal(this._getScreenText(session), screenMarks(session.xterm));
1664
+ const ctx = options?.telegramCtx;
1665
+ if (!ctx?.chat?.id) {
1666
+ // No chat to ask in — a scheduled run, or a turn started without a ctx.
1667
+ // The dialog still rides out in the error so it isn't lost entirely.
1668
+ throw new Error('Claude Code is waiting on a dialog and there\'s no chat here to answer it in:\n\n'
1669
+ + `${modal?.body ?? '(unreadable)'}`);
1670
+ }
1671
+ const pty = {
1672
+ write: (data) => session.term.write(data),
1673
+ screen: () => this._getScreenText(session),
1674
+ marks: () => screenMarks(session.xterm),
1675
+ };
1676
+ const outcome = await relayDialog(pty, sessionKey, ctx, session.cwd, stage, {
1677
+ clearMs: DIALOG_CLEAR_MS,
1678
+ settleMs: DIALOG_SETTLE_MS,
1679
+ });
1680
+ console.warn(`[PtyProvider] ${sessionKey}: claude opened a dialog — relay ${outcome.kind}`);
1681
+ if (outcome.kind !== 'closed')
1682
+ throw new Error(openDialogError(outcome, stage));
1683
+ // Marked only now, with the dialog gone: from here the screen looks like a
1684
+ // finished turn until claude resumes, and _checkEndOfTurn needs to know
1685
+ // not to believe it.
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)) });
1758
+ }
1759
+ /**
1760
+ * Wait until stdout has been quiet for `idleMs`, capped at `capMs`. The
1761
+ * weaker sibling of _waitForReady: it can't require the input prompt glyph,
1762
+ * because an overlay covers it. Returns true if it settled, false on cap.
1763
+ */
1764
+ async _waitQuiet(session, idleMs, capMs) {
1765
+ const start = Date.now();
1766
+ while (Date.now() - start < capMs) {
1767
+ if (Date.now() - session.lastChunkAt >= idleMs)
1768
+ return true;
1769
+ await new Promise((r) => setTimeout(r, 50));
1770
+ }
1771
+ return false;
1772
+ }
1773
+ /**
1774
+ * Type an `immediate` slash command into the live TUI, scrape what it draws,
1775
+ * then dismiss it with Esc. Built for `/tasks`, whose answer exists only in
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.
1779
+ *
1780
+ * Refuses while a turn is in flight. The keyboard belongs to the turn: our
1781
+ * keystrokes would land in its input box, and the overlay would corrupt the
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.
1787
+ */
1788
+ async runOverlayCommand(sessionKey, command, steer) {
1789
+ const session = this.sessions.get(sessionKey);
1790
+ if (!session)
1791
+ return { ok: false, reason: 'no-session' };
1792
+ if (session.endOfTurnResolver)
1793
+ return { ok: false, reason: 'turn-active' };
1794
+ if (!this._hasInputBox(session))
1795
+ return { ok: false, reason: 'not-ready' };
1796
+ try {
1797
+ // Whatever Enter is about to run, a prompt left in the box would run too.
1798
+ await this._clearAfterEsc(session);
1799
+ // Same submission path as a prompt: bracketed paste so the TUI takes the
1800
+ // text verbatim, then \r to run it.
1801
+ session.term.write(`\x1b[200~${command}\x1b[201~`);
1802
+ await new Promise((r) => setTimeout(r, OVERLAY_PASTE_SETTLE_MS));
1803
+ session.term.write('\r');
1804
+ const settled = await this._waitQuiet(session, OVERLAY_IDLE_MS, OVERLAY_MAX_MS);
1805
+ if (!settled) {
1806
+ console.warn(`[PtyProvider] overlay "${command}" did not settle within ${OVERLAY_MAX_MS}ms; scraping anyway`);
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
+ }
1814
+ return { ok: true, screen: this._getScreenText(session) };
1815
+ }
1816
+ finally {
1817
+ // Unconditional: an overlay left open would swallow the next turn's
1818
+ // prompt, so this has to run even if the settle threw.
1819
+ try {
1820
+ session.term.write('\x1b');
1821
+ }
1822
+ catch { /* pty already gone */ }
1823
+ }
1824
+ }
1825
+ /**
1826
+ * Wait for evidence that claude took delivery of the prompt: a user record
1827
+ * appearing in the session log. While it hasn't, and our text is still
1828
+ * visible in the input box, re-send \r every SUBMIT_RETRY_EVERY_MS — the
1829
+ * editor swallows the keystroke silently when it's busy (transcript replay,
1830
+ * late startup), and nothing downstream can tell that from a slow model.
1831
+ *
1832
+ * The log read is gated on the log's mtime so a large transcript isn't
1833
+ * re-parsed on every poll. Returns true once the prompt lands; false on
1834
+ * cap-hit, where the end-of-turn guard in sendToAgent reports the failure.
1835
+ * Slash commands skip the whole thing — they needn't write a record at all,
1836
+ * and blind \r retries would be the only outcome.
1837
+ */
1838
+ async _confirmSubmitted(session, sessionKey, prompt, abortSignal) {
1839
+ if (session.submittedSlashCommand)
1840
+ return true;
1841
+ const baselineId = session.promptMarkerAtSubmit?.id;
1842
+ const deadline = Date.now() + SUBMIT_CONFIRM_CAP_MS;
1843
+ let seenMtime = session.jsonlMtimeAtSubmit;
1844
+ let lastRetryAt = Date.now();
1845
+ while (Date.now() < deadline) {
1846
+ // Stop waiting the moment the turn is cancelled or the pty dies —
1847
+ // _awaitEndOfTurn handles both, and retrying \r into a dead term or a
1848
+ // cancelled turn is pointless.
1849
+ if (abortSignal?.aborted)
1850
+ return false;
1851
+ if (this.sessions.get(sessionKey) !== session)
1852
+ return false;
1853
+ const mtime = this._currentJsonlMtimeMs(sessionKey);
1854
+ if (mtime !== seenMtime) {
1855
+ seenMtime = mtime;
1856
+ const markerNow = this._currentPromptMarker(sessionKey);
1857
+ if (markerNow && markerNow.id !== baselineId)
1858
+ return true;
1859
+ }
1860
+ if (Date.now() - lastRetryAt >= SUBMIT_RETRY_EVERY_MS) {
1861
+ lastRetryAt = Date.now();
1862
+ // With persistence off the log will never confirm anything, so retrying
1863
+ // just fires Enter into a session that already took the prompt. Stop
1864
+ // and let the end-of-turn guard name the real problem.
1865
+ if (transcriptSavingDisabled(this._getScreenText(session))) {
1866
+ console.warn('[PtyProvider] transcript saving is off — cannot confirm submission from the log');
1867
+ return false;
1868
+ }
1869
+ if (this._screenHasPromptText(session, prompt)) {
1870
+ console.warn('[PtyProvider] prompt still in the input box after Enter — re-sending submit');
1871
+ session.term.write('\r');
1872
+ }
1873
+ }
1874
+ await new Promise((r) => setTimeout(r, 250));
1875
+ }
1876
+ console.warn(`[PtyProvider] prompt not confirmed submitted within ${Math.round(SUBMIT_CONFIRM_CAP_MS / 1000)}s`);
1877
+ return false;
1878
+ }
1879
+ /** True if the prompt is still sitting unsent in the input box. */
1880
+ _screenHasPromptText(session, prompt) {
1881
+ const screenText = this._getScreenText(session);
1882
+ // A collapsed paste never renders its own text, so the placeholder's id is
1883
+ // the only handle on it — and only the box counts, because the frames the
1884
+ // box scrolls off keep showing the placeholder it held at the time, which
1885
+ // a whole-screen scan would go on finding long after Enter took it.
1886
+ const pasteId = session.submittedPasteId;
1887
+ if (pasteId !== undefined) {
1888
+ return inputBoxPastePlaceholders(screenText).some((p) => p.id === pasteId);
1889
+ }
1890
+ const needle = promptNeedle(prompt);
1891
+ // Too short to match reliably — assume it's still pending and let the
1892
+ // caller re-send; a stray Enter on an empty input box is a no-op.
1893
+ if (!needle)
1894
+ return true;
1895
+ // Same reasoning as the placeholder branch, and the same trap: a submitted
1896
+ // prompt is drawn into the transcript and stays there, so a whole-screen
1897
+ // search reports "still unsent" forever and re-fires Enter into a session
1898
+ // that took the prompt long ago. No box at all reads as "don't" — an
1899
+ // overlay is up, and Enter is the keypress that answers one.
1900
+ return inputBoxHolds(screenText, needle);
1901
+ }
1902
+ /**
1903
+ * Poll the xterm buffer until `prompt` provably reaches claude's editor,
1904
+ * before we send \r. Returns `echoed` plus, when claude swallowed the
1905
+ * prompt into a `[Pasted text #N]` placeholder, the id it minted for it.
1906
+ * Caller retries the write on a miss; the welcome-banner guard in
1907
+ * sendToAgent is the final safety net if every retry misses.
1908
+ *
1909
+ * Two ways the prompt can prove it landed, because claude draws it two ways:
1910
+ *
1911
+ * - Literally, in the input box, for a short prompt. The needle is the
1912
+ * leading non-whitespace slice of the first line, long enough to be
1913
+ * distinctive, and it is matched through any row break the box wraps
1914
+ * it across. Only the box is searched, never the whole screen: the box
1915
+ * is the one region that holds unsent text and nothing else, so a hit
1916
+ * there is proof on its own and needs no before/after comparison.
1917
+ * - As a placeholder, once the paste runs past 800 characters or two
1918
+ * newlines. The text is then never on screen at all, so the needle can
1919
+ * never match: every prompt built from a template — an upload note, a
1920
+ * staged image list — is only ever provable this way.
1921
+ *
1922
+ * A placeholder counts on an id `screenBefore` had not seen, and never on
1923
+ * the `+N lines` it reports. Both halves of that are scars. Claude rewrites a
1924
+ * paste before it renders one, lifting any image path out of the text into an
1925
+ * `[Image #N]` chip, so a staged-image prompt written with 10 newlines comes
1926
+ * back as `+7 lines` — matching that count against what we sent was a check
1927
+ * that could only fail, and it failed on every photo upload. And ids outlive
1928
+ * the turn that minted them, because the frames the box scrolls off keep
1929
+ * showing the placeholder they held, so an id alone proves nothing without
1930
+ * the baseline.
1931
+ *
1932
+ * The needle wanted no such baseline and was given one anyway — `screenBefore`
1933
+ * was scanned for it too, and a hit only counted if the whole-screen tally
1934
+ * went *up*. On a saturated buffer that tally cannot go up: `_getScreenText`
1935
+ * reads all 1000 scrollback rows plus the 40 live ones, and once they are
1936
+ * full every row the TUI draws evicts one off the top, so a needle the
1937
+ * transcript already uses loses an occurrence up there for each one the box
1938
+ * gains. Measured on a headless xterm with these exact settings: 149
1939
+ * occurrences before the write, 149 after the box drew the prompt, 148 after
1940
+ * the redraw that followed — with the prompt plainly on screen the whole
1941
+ * time. Every retry made it worse, each redraw pushing another copy of the
1942
+ * box into the scrollback to inflate the baseline further, so all three
1943
+ * attempts missed and the user was told nothing was sent when it had been.
1944
+ *
1945
+ * Returns echoed immediately when the needle would be too short to be a
1946
+ * meaningful match (very short prompts can race the \r submit, but they also
1947
+ * rarely fall victim to the paste heuristic so the retry loop isn't
1948
+ * load-bearing for them).
1949
+ */
1950
+ async _waitForPromptEcho(session, prompt, capMs, screenBefore) {
1951
+ const needle = promptNeedle(prompt);
1952
+ if (!needle) {
1953
+ await new Promise((r) => setTimeout(r, 100));
1954
+ return { echoed: true };
1955
+ }
1956
+ const knownPasteIds = pastePlaceholderIds(screenBefore);
1957
+ const deadline = Date.now() + capMs;
1958
+ while (Date.now() < deadline) {
1959
+ const screenText = this._getScreenText(session);
1960
+ if (inputBoxHolds(screenText, needle))
1961
+ return { echoed: true };
1962
+ const mine = newPastePlaceholder(knownPasteIds, screenText);
1963
+ if (mine)
1964
+ return { echoed: true, pasteId: mine.id };
1965
+ await new Promise((r) => setTimeout(r, 25));
1966
+ }
1967
+ return { echoed: false };
1968
+ }
1969
+ /**
1970
+ * Empty claude's input box of a prompt we pasted into it. One Ctrl+U clears
1971
+ * only the row the cursor is on, so this sends as many as the prompt can
1972
+ * need; clearPresses says why.
1973
+ */
1974
+ async _clearInputBox(session, prompt) {
1975
+ const presses = clearPresses(prompt, INPUT_BOX_COLS);
1976
+ for (let i = 0; i < presses; i++) {
1977
+ session.term.write('\x15');
1978
+ await new Promise((r) => setTimeout(r, CLEAR_PRESS_GAP_MS));
1979
+ }
1980
+ }
1981
+ /** Stop claude generating, and note what that may have put back in the input box. */
1982
+ _pressEscToInterrupt(session) {
1983
+ session.term.write('\x1b');
1984
+ session.boxMayHold = session.lastTypedPrompt;
1985
+ }
1986
+ /** Empty the box if an Esc may have left a prompt in it. See `boxMayHold`. */
1987
+ async _clearAfterEsc(session) {
1988
+ if (session.boxMayHold === undefined)
1989
+ return;
1990
+ const prompt = session.boxMayHold;
1991
+ session.boxMayHold = undefined;
1992
+ await this._clearInputBox(session, prompt);
1993
+ await new Promise((r) => setTimeout(r, CLEAR_SETTLE_MS));
1994
+ }
1995
+ /**
1996
+ * After the first _waitForReady of this pty's lifetime, scan the rendered
1997
+ * screen for claude's "Update available" / "Successfully updated" banner
1998
+ * and relay it to Telegram. Guarded so we only fire once per pty spawn —
1999
+ * the banner sits in the xterm scrollback indefinitely otherwise.
2000
+ */
2001
+ _maybeRelayUpdateBanner(session, sessionKey) {
2002
+ if (session.updateBannerChecked)
2003
+ return;
2004
+ session.updateBannerChecked = true;
2005
+ const banner = scrapeUpdateBanner(this._getScreenText(session));
2006
+ if (!banner)
2007
+ return;
2008
+ relayUpdateBanner(sessionKey, banner).catch((err) => {
2009
+ console.error('[PtyProvider] relay update banner failed:', err instanceof Error ? err.message : err);
2010
+ });
2011
+ }
2012
+ /**
2013
+ * Start feeding the turn's live prose to onProgress (pty-stream.ts): the
2014
+ * records the turn writes to the log from submit on, and the text block it
2015
+ * is streaming on screen. Started once the prompt is submitted and stopped
2016
+ * when the turn settles either way, so a turn claude starts on its own — which
2017
+ * monitor-relay delivers whole when it closes — never streams.
2018
+ */
2019
+ _startStream(session, sessionKey) {
2020
+ this._stopStream(session);
2021
+ if (!session.onProgress)
2022
+ return;
2023
+ const botSession = sessionManager.getSession(sessionKey);
2024
+ if (!botSession?.claudeSessionId)
2025
+ return;
2026
+ const reader = new TurnProseReader(sessionJsonlPath(botSession.workingDirectory, botSession.claudeSessionId), session.jsonlSizeAtSubmit, session.submittedSlashCommand);
2027
+ const prose = new PtyTurnStream(reader, (text) => session.onProgress?.(text), () => getDeliveredProse(sessionKey));
2028
+ const timer = setInterval(() => {
2029
+ try {
2030
+ // Text only streams while the turn runs and nothing is asked of the
2031
+ // user; the log still has records to bring in either way.
2032
+ const screenMayStream = !session.stopReceived && !session.relayingModal;
2033
+ prose.tick(screenMayStream ? this._getScreenText(session) : undefined, session.xterm.cols);
2034
+ }
2035
+ catch (err) {
2036
+ console.warn('[PtyProvider] live prose tick failed:', err instanceof Error ? err.message : err);
2037
+ }
2038
+ }, STREAM_TICK_MS);
2039
+ timer.unref?.();
2040
+ session.stream = { prose, timer };
2041
+ }
2042
+ _stopStream(session) {
2043
+ if (!session.stream)
2044
+ return;
2045
+ clearInterval(session.stream.timer);
2046
+ session.stream = null;
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
+ }
2064
+ _getScreenText(session) {
2065
+ const buffer = session.xterm.buffer.active;
2066
+ let text = '';
2067
+ for (let i = 0; i < buffer.length; i++) {
2068
+ text += buffer.getLine(i)?.translateToString(true) + '\n';
2069
+ }
2070
+ return text.replace(/\n+$/, ''); // Trim trailing newlines
2071
+ }
2072
+ _cleanupSession(sessionKey) {
2073
+ const session = this.sessions.get(sessionKey);
2074
+ if (session) {
2075
+ try {
2076
+ session.term.kill();
2077
+ }
2078
+ catch (e) {
2079
+ // ignore
2080
+ }
2081
+ if (session.idleTimer)
2082
+ clearTimeout(session.idleTimer);
2083
+ if (session.hardTimer)
2084
+ clearTimeout(session.hardTimer);
2085
+ this._stopStream(session);
2086
+ this.sessions.delete(sessionKey);
2087
+ unregisterSessionChat(session.claudeSessionId);
2088
+ watchUnregister(sessionKey, session.xterm);
2089
+ }
2090
+ // Stop any monitor relay tied to this session — the JSONL it was watching
2091
+ // belongs to a now-dead claudeSessionId; the next session gets a new one.
2092
+ teardownMonitorRelay(sessionKey);
2093
+ }
2094
+ /**
2095
+ * End every claude this provider started, for a shutdown, and wait for them
2096
+ * to go. Left to the bot's exit, a claude outlived it by as long as it took
2097
+ * to notice: on 10-27 one wrote another reply into its transcript a second
2098
+ * after the restarted bot had resumed that conversation in a new claude, so
2099
+ * two processes had the one transcript open.
2100
+ *
2101
+ * Each is hung up the way /clear does it, which claude answers with its own
2102
+ * clean shutdown, cleaning up what it started. One still running after
2103
+ * `waitMs` is killed outright.
2104
+ */
2105
+ async closeAll(waitMs = CLOSE_WAIT_MS) {
2106
+ this.closing = true;
2107
+ const running = new Set();
2108
+ const exits = [...this.sessions.keys()].map((sessionKey) => {
2109
+ const { term } = this.sessions.get(sessionKey);
2110
+ running.add(term);
2111
+ const exited = new Promise((resolve) => {
2112
+ term.onExit(() => {
2113
+ running.delete(term);
2114
+ resolve();
2115
+ });
2116
+ });
2117
+ this._cleanupSession(sessionKey);
2118
+ return exited;
2119
+ });
2120
+ if (exits.length === 0)
2121
+ return;
2122
+ let timer;
2123
+ await Promise.race([Promise.all(exits), new Promise((resolve) => { timer = setTimeout(resolve, waitMs); })]);
2124
+ clearTimeout(timer);
2125
+ for (const term of running) {
2126
+ console.warn(`[PtyProvider] claude (pid ${term.pid}) still running ${waitMs / 1000}s after hangup, killing it`);
2127
+ try {
2128
+ term.kill('SIGKILL');
2129
+ }
2130
+ catch { /* already gone */ }
2131
+ }
2132
+ }
2133
+ clearConversation(sessionKey) {
2134
+ this._cleanupSession(sessionKey);
2135
+ this.usageCache.delete(sessionKey);
2136
+ console.log(`[PtyProvider] Cleared conversation for session ${sessionKey}`);
2137
+ }
2138
+ setModel(scope, model) {
2139
+ // Applied as `--model` on the next spawn; the caller tears the pty down so
2140
+ // that happens on the next turn rather than whenever the session restarts.
2141
+ userPreferences.setModel(scope, model);
2142
+ }
2143
+ /**
2144
+ * The model actually serving this chat, read from the last usage record in
2145
+ * the session log. Falls back to the pending preference (set but not yet
2146
+ * spawned), then to an honest placeholder — claude picks its own default and
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.
2152
+ */
2153
+ getModel(scope) {
2154
+ const cached = this._findUsageForScope(scope) ?? this._refreshUsageFromJsonl(String(scope));
2155
+ if (cached?.model)
2156
+ return cached.model;
2157
+ return userPreferences.getModel(scope) ?? 'Claude Code default';
2158
+ }
2159
+ clearModel(scope) {
2160
+ userPreferences.clearModel(scope);
2161
+ }
2162
+ /**
2163
+ * usageCache is keyed by session key (chat, or chat:thread for threads). A
2164
+ * thread's scope is its session key; a chat-wide scope matches the plain
2165
+ * chat key first, then any thread under it.
2166
+ */
2167
+ _findUsageForScope(scope) {
2168
+ const direct = this.usageCache.get(String(scope));
2169
+ if (direct || typeof scope === 'string')
2170
+ return direct;
2171
+ const prefix = `${scope}:`;
2172
+ for (const [key, usage] of this.usageCache) {
2173
+ if (key.startsWith(prefix))
2174
+ return usage;
2175
+ }
2176
+ return undefined;
2177
+ }
2178
+ /**
2179
+ * The last turn's usage, or the session log's when no turn has reported one
2180
+ * since the chat got here: a branch, a /tree jump, a /resume and a restart all
2181
+ * start with nothing cached. The log sizes the point the chat is now at, which
2182
+ * after a jump is not the figure it last saw.
2183
+ */
2184
+ getCachedUsage(sessionKey) {
2185
+ return this.usageCache.get(sessionKey) ?? this._refreshUsageFromJsonl(sessionKey);
2186
+ }
2187
+ /**
2188
+ * The usage as the session log has it now, cached for /info and the status line.
2189
+ * For after a turn claude started itself: no turn of ours ran to refresh the
2190
+ * cache, which still holds the figure from before that turn grew the context.
2191
+ * Falls back on the cached figure when the log has none to give.
2192
+ */
2193
+ refreshUsage(sessionKey) {
2194
+ return this._refreshUsageFromJsonl(sessionKey) ?? this.usageCache.get(sessionKey);
2195
+ }
2196
+ async getAvailableModels(_scope) {
2197
+ // The aliases CLAUDE_BIN accepts for --model, minus any it predates.
2198
+ return getModelsForBinary(CLAUDE_BIN);
2199
+ }
2200
+ }
2201
+ // ---- Hook → AgentOptions callback bridge ------------------------------------
2202
+ //
2203
+ // The handlers below run inside the IPC server when claude-spawned hook curls
2204
+ // reach us. They translate hook payloads into the callbacks the bot
2205
+ // implements (onToolStart / onToolEnd / onToolResult / onEditDiff), which
2206
+ // drive the verbose UI.
2207
+ //
2208
+ // Callbacks are fire-and-forget — the hook command blocks claude until the
2209
+ // HTTP POST returns, so we ack fast and let the bot's Telegram calls run on
2210
+ // their own microtasks. Errors are logged, never rethrown into claude.
2211
+ /**
2212
+ * True if the xterm buffer is still showing Claude Code's first-launch welcome
2213
+ * screen. The two greeting strings only render together at startup — after any
2214
+ * prompt submits and the model produces output, they scroll out of the visible
2215
+ * buffer. Used by sendToAgent to detect the "prompt swallowed during TUI
2216
+ * startup" failure mode and throw instead of returning the banner as a reply.
2217
+ */
2218
+ function looksLikeWelcomeBanner(screenText) {
2219
+ return screenText.includes('Welcome back') && screenText.includes('Tips for getting started');
2220
+ }
2221
+ function fireAndForget(label, fn) {
2222
+ if (!fn)
2223
+ return;
2224
+ void Promise.resolve()
2225
+ .then(() => fn())
2226
+ .catch(err => console.error(`[PTY hook] ${label} threw:`, err));
2227
+ }
2228
+ /**
2229
+ * Pick the model-facing string out of a hook payload's `tool_response`.
2230
+ *
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:
2234
+ * Read → { type: 'text', file: { filePath, content } }
2235
+ * Bash → { stdout, stderr, exit_code, … }
2236
+ *
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.
2240
+ */
2241
+ /**
2242
+ * Join an MCP-style content array (`[{type:'text',text:'...'}, ...]`) into a
2243
+ * plain string. Returns `null` if the input isn't a recognizable MCP content
2244
+ * array, so callers can fall through to other shapes.
2245
+ */
2246
+ function joinMcpContentArray(arr) {
2247
+ const texts = [];
2248
+ for (const item of arr) {
2249
+ if (!item || typeof item !== 'object')
2250
+ return null;
2251
+ const o = item;
2252
+ if (typeof o.text === 'string')
2253
+ texts.push(o.text);
2254
+ }
2255
+ return texts.length ? texts.join('\n') : null;
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
+ }
2275
+ function extractToolResponseContent(toolResponse) {
2276
+ if (toolResponse == null)
2277
+ return '';
2278
+ if (typeof toolResponse === 'string')
2279
+ return toolResponse;
2280
+ // MCP tool result shapes: claude delivers MCP tool_response either as the
2281
+ // raw content array `[{type:'text', text:'...'}]` or as the wrapped form
2282
+ // `{content: [...], isError?: bool}`. Both should render as plain text in
2283
+ // the action log, not as JSON.
2284
+ if (Array.isArray(toolResponse)) {
2285
+ const joined = joinMcpContentArray(toolResponse);
2286
+ if (joined !== null)
2287
+ return joined;
2288
+ }
2289
+ if (typeof toolResponse !== 'object')
2290
+ return String(toolResponse);
2291
+ const obj = toolResponse;
2292
+ if (Array.isArray(obj.content)) {
2293
+ const joined = joinMcpContentArray(obj.content);
2294
+ if (joined !== null)
2295
+ return joined;
2296
+ }
2297
+ // Read → unwrap file.content
2298
+ if (obj.file && typeof obj.file === 'object') {
2299
+ const file = obj.file;
2300
+ if (typeof file.content === 'string')
2301
+ return file.content;
2302
+ }
2303
+ // Bash → combine stdout + stderr (matches what the model sees)
2304
+ if ('stdout' in obj || 'stderr' in obj) {
2305
+ const parts = [];
2306
+ if (typeof obj.stdout === 'string' && obj.stdout)
2307
+ parts.push(obj.stdout);
2308
+ if (typeof obj.stderr === 'string' && obj.stderr)
2309
+ parts.push(obj.stderr);
2310
+ return parts.join('\n').trim();
2311
+ }
2312
+ // Common single-field shapes
2313
+ for (const key of ['content', 'result', 'output', 'text']) {
2314
+ if (typeof obj[key] === 'string')
2315
+ return obj[key];
2316
+ }
2317
+ // Unknown shape — JSON-dump as a last resort so something shows up
2318
+ try {
2319
+ return JSON.stringify(obj);
2320
+ }
2321
+ catch {
2322
+ return String(obj);
2323
+ }
2324
+ }
2325
+ /**
2326
+ * Arm the monitor relay for a backgrounded tool call, which also registers it
2327
+ * with the tracker behind /tasks and the footer. `startedAt` is for a call
2328
+ * that was already running before it went to the background.
2329
+ */
2330
+ function armAsyncTool(turn, kind, toolInput, toolUseId, startedAt) {
2331
+ const session = sessionManager.getSession(turn.sessionKey);
2332
+ if (!session?.claudeSessionId)
2333
+ return;
2334
+ const description = String(toolInput.description ??
2335
+ // Workflow documents `description` as ignored, so it's often absent;
2336
+ // `name` is the field that actually identifies the run.
2337
+ toolInput.name ??
2338
+ toolInput.target ??
2339
+ toolInput.file_path ??
2340
+ toolInput.path ??
2341
+ toolInput.command ??
2342
+ toolInput.prompt ??
2343
+ kind);
2344
+ onAsyncToolArmed(kind, turn.sessionKey, session.workingDirectory, session.claudeSessionId, description, typeof toolUseId === 'string' && toolUseId ? toolUseId : undefined, startedAt, typeof toolInput.command === 'string' ? toolInput.command : undefined);
2345
+ }
2346
+ /**
2347
+ * What the PreToolUse hook is told when no turn or chat matches its session:
2348
+ * a pty TeleCoder has no chat on record for. Allowed where the gate is off, as
2349
+ * every hook outside a turn always was; denied where it is on, since nobody
2350
+ * can be asked.
2351
+ */
2352
+ export function preToolUseWithoutChat() {
2353
+ if (!isPermissionGateEnabled())
2354
+ return ALLOW_MARKER;
2355
+ return `${DENY_MARKER_START}TeleCoder permission gate is on but has no Telegram chat on record for this session, so nobody can approve tools. Denied.${DENY_MARKER_END}`;
2356
+ }
2357
+ registerIpcHandler('/hook/preToolUse', async (turn, body) => {
2358
+ const toolName = String(body.tool_name ?? 'unknown');
2359
+ const toolInput = (body.tool_input ?? {});
2360
+ // A call from between TeleCoder's turns — a background agent, a turn claude
2361
+ // started itself — comes here only to pass the gate. Its UI is the monitor
2362
+ // relay's, as before.
2363
+ if (!turn.selfStarted) {
2364
+ // The hook fails closed, so a bug in the bookkeeping must not reach the
2365
+ // reply: it would block every tool rather than miss a UI update.
2366
+ try {
2367
+ turn.onToolStart?.();
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
+ }
2372
+ // Arm the relay so any task-notifications that fire AFTER this turn ends
2373
+ // still get routed to Telegram, and register the task with the tracker
2374
+ // behind /tasks. See classifyAsyncTool for which tools qualify.
2375
+ const asyncKind = classifyAsyncTool(toolName, toolInput);
2376
+ if (asyncKind)
2377
+ armAsyncTool(turn, asyncKind, toolInput, body.tool_use_id);
2378
+ // PushNotification: claude's "ping the user" tool. The native impl fires
2379
+ // an OS-level notification on the bot host (no real user there); for us
2380
+ // Telegram is the notification surface, so we relay the message text.
2381
+ if (toolName === 'PushNotification') {
2382
+ const message = String(toolInput.message ?? '').trim();
2383
+ if (message)
2384
+ relayPushNotification(turn.sessionKey, message);
2385
+ }
2386
+ }
2387
+ catch (err) {
2388
+ console.error('[PTY hook] preToolUse bookkeeping threw:', sanitizeError(err));
2389
+ }
2390
+ }
2391
+ // Permission gate: on with guests or TELECODER_PERMISSION_PROMPTS=1. For
2392
+ // tools matching a dangerous pattern, blocks the call and waits for Telegram
2393
+ // approval. Decision returned as a marker string the shell wrapper parses:
2394
+ // the deny marker exits 2 (claude code's "block this tool" signal), the
2395
+ // allow marker exits 0, and anything else blocks too.
2396
+ if (isPermissionGateEnabled()) {
2397
+ const ctx = turn.options.telegramCtx;
2398
+ const decision = await gateToolCall({
2399
+ sessionKey: turn.sessionKey,
2400
+ toolName,
2401
+ toolInput,
2402
+ telegramCtx: ctx,
2403
+ });
2404
+ if (decision.block) {
2405
+ // Bump the inflight counter back down — the tool isn't actually going
2406
+ // to run, so PostToolUse won't fire and inflightTools would otherwise
2407
+ // stay stuck high.
2408
+ if (!turn.selfStarted)
2409
+ turn.onToolEnd?.();
2410
+ return `${DENY_MARKER_START}${decision.reason}${DENY_MARKER_END}`;
2411
+ }
2412
+ }
2413
+ return ALLOW_MARKER;
2414
+ }, { betweenTurns: true, noTurn: preToolUseWithoutChat });
2415
+ registerIpcHandler('/hook/postToolUse', (turn, body) => {
2416
+ const toolName = String(body.tool_name ?? 'unknown');
2417
+ const toolInput = (body.tool_input ?? {});
2418
+ const toolUseId = String(body.tool_use_id ?? '');
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
+ //
2422
+ // A Bash call that ran into claude's foreground cap carries on in the
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)) {
2429
+ const ranForMs = Number(body.tool_response.timedOutAfterMs) || 0;
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);
2445
+ }
2446
+ if (turn.selfStarted)
2447
+ return { ok: true };
2448
+ turn.onToolEnd?.();
2449
+ fireAndForget('onToolEnd', () => turn.options.onToolEnd?.());
2450
+ if (toolName === 'Edit' || toolName === 'Write') {
2451
+ // Successful Edit/Write — surface the diff so the bot shows before/after.
2452
+ const event = {
2453
+ toolUseId,
2454
+ toolName,
2455
+ filePath: String(toolInput.file_path ?? ''),
2456
+ oldString: toolName === 'Edit' ? String(toolInput.old_string ?? '') : undefined,
2457
+ newString: toolName === 'Edit'
2458
+ ? String(toolInput.new_string ?? '')
2459
+ : String(toolInput.content ?? ''),
2460
+ };
2461
+ fireAndForget('onEditDiff', () => turn.options.onEditDiff?.(event));
2462
+ }
2463
+ else {
2464
+ const event = {
2465
+ toolUseId,
2466
+ toolName,
2467
+ input: toolInput,
2468
+ content: backgroundedResultText(toolName, body.tool_response) ?? extractToolResponseContent(body.tool_response),
2469
+ isError: false,
2470
+ };
2471
+ fireAndForget('onToolResult', () => turn.options.onToolResult?.(event));
2472
+ }
2473
+ return { ok: true };
2474
+ }, { betweenTurns: true });
2475
+ registerIpcHandler('/hook/postToolUseFailure', (turn, body) => {
2476
+ const toolName = String(body.tool_name ?? 'unknown');
2477
+ const toolInput = (body.tool_input ?? {});
2478
+ const toolUseId = String(body.tool_use_id ?? '');
2479
+ turn.toolStartedAt?.delete(toolUseId);
2480
+ turn.onToolEnd?.();
2481
+ fireAndForget('onToolEnd', () => turn.options.onToolEnd?.());
2482
+ const event = {
2483
+ toolUseId,
2484
+ toolName,
2485
+ input: toolInput,
2486
+ content: extractToolResponseContent(body.tool_response),
2487
+ isError: true,
2488
+ };
2489
+ fireAndForget('onToolResult', () => turn.options.onToolResult?.(event));
2490
+ return { ok: true };
2491
+ });
2492
+ // Stop fires when claude finishes responding. PtyProvider's onClaudeStop sets
2493
+ // stopReceived on the live pty session so end-of-turn detection switches to
2494
+ // the short settle window and stops requiring the input prompt to be visible.
2495
+ registerIpcHandler('/hook/stop', (turn) => {
2496
+ turn.onClaudeStop?.();
2497
+ return { ok: true };
2498
+ });
2499
+ //# sourceMappingURL=pty-provider.js.map