telecoder 0.0.0-stage → 1.2.0

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