@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,4029 @@
1
+ import { randomBytes, randomUUID } from 'crypto'
2
+ import { mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'
3
+ // #6132 (HOL fix from #5337): the per-turn hook-drain hot path uses async fs so a
4
+ // slow/stuck sink (FUSE/NFS, full disk, tmpwatch race) can't block the shared
5
+ // event loop — which would freeze EVERY claude-tui session (the default provider).
6
+ import { readdir, readFile, unlink } from 'fs/promises'
7
+ import { homedir, tmpdir } from 'os'
8
+ import { performance } from 'node:perf_hooks'
9
+ import { dirname, join } from 'path'
10
+ import { fileURLToPath } from 'url'
11
+ import { BaseSession, buildBaseSessionOpts } from './base-session.js'
12
+ import { CLAUDE_TUI_PTY_SIZE } from '@chroxy/protocol'
13
+ // #5417 — the TUI shares CliSession's pinned "unknown resume id" patterns
14
+ // (RESUME_UNKNOWN_STDERR_PATTERNS, #4929/#4950) via this matcher: the PTY
15
+ // merges stdout+stderr, so claude's resume rejection lands in _outputTail.
16
+ import { stderrIndicatesUnknownResume } from './cli-session.js'
17
+ import { ALLOWED_MODEL_IDS } from './models.js'
18
+ import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
19
+ import { RespawnRateLimiter } from './utils/respawn-rate-limiter.js'
20
+ import { CHROXY_SECRET_DENYLIST } from './utils/spawn-env.js'
21
+ import { createLogger, loggerForSession, redactSensitive, redactSensitivePreservingEscapes } from './logger.js'
22
+ import { formatIdleDuration } from './session-timeout-manager.js'
23
+ import { isOperatorTimeoutInRange } from './duration.js'
24
+ import { materializeAttachments, buildAttachmentsPromptSuffix } from './claude-tui-attachments.js'
25
+ import { TranscriptTaskScanner, transcriptPathForSessionFile } from './transcript-tasks.js'
26
+ import { hasClaudeOAuthCreds } from './auth-probes.js'
27
+ import { BILLING_CLASSES } from './billing-class.js'
28
+ import {
29
+ parseBackgroundShellId,
30
+ parseBackgroundShellOutputPath,
31
+ isRunInBackgroundInput,
32
+ parseBashOutputShellId,
33
+ } from './background-shells.js'
34
+ // #5559 — PTY-write / paste-throttle layer + interactive-form driver carved out
35
+ // into focused modules. The empirically-pinned helpers, constants and methods
36
+ // are moved byte-identically; the *Mixin classes carry the write/form methods,
37
+ // applied onto ClaudeTuiSession.prototype via applyMixin() below.
38
+ import {
39
+ ANSI_STRIP,
40
+ formatHexDump,
41
+ CLAUDE,
42
+ AUTH_FAILURE_PATTERNS,
43
+ AUTH_REQUIRED_CODE,
44
+ AUTH_REQUIRED_MESSAGE,
45
+ ensureCwdTrusted,
46
+ writeHookSettings,
47
+ PtyDriverMixin,
48
+ } from './claude-tui/pty-driver.js'
49
+ import {
50
+ ASK_USER_QUESTION_WATCHDOG_MS,
51
+ FormDriver,
52
+ multiSelectReinjectEnabled,
53
+ } from './claude-tui/form-driver.js'
54
+
55
+ // Re-export the public writeHookSettings helper so existing
56
+ // `import { writeHookSettings } from './claude-tui-session.js'` callers (and the
57
+ // permission-hook test) keep working unchanged after the #5559 split.
58
+ export { writeHookSettings }
59
+
60
+ const __filename = fileURLToPath(import.meta.url)
61
+ const __dirname = dirname(__filename)
62
+
63
+ const log = createLogger('claude-tui-session')
64
+
65
+ // #5792: how long a DENIED-shape AskUserQuestion pending entry may linger past
66
+ // turn-end before the reaper drops it. Derived from (not a re-declared copy of)
67
+ // the stall-watchdog window so the two can't drift: long enough for any
68
+ // in-flight teardown / reinject to clear the entry on its own (making the reaper
69
+ // a no-op), short enough that a leaked entry can't shadow the most-recent
70
+ // fallback for long. Same recovery-window class as the answer stall.
71
+ const DENIED_QUESTION_REAPER_MS = ASK_USER_QUESTION_WATCHDOG_MS
72
+
73
+ /**
74
+ * ClaudeTuiSession — drives the interactive `claude` TUI under a PTY so the
75
+ * round-trip bills as a subscription instead of programmatic (`claude -p` and
76
+ * the Agent SDK are meter-shifted to programmatic pricing starting 2026-06-15;
77
+ * the TUI path is untouched). #3902.
78
+ *
79
+ * Persistent-process shape — start() spawns ONE PTY (paying ~3.5s warmup
80
+ * once), then every sendMessage() writes the next prompt to the same PTY
81
+ * and reads its Stop hook payload. destroy() kills the PTY.
82
+ * Deliver-on-complete only (no incremental streaming).
83
+ *
84
+ * Events emitted:
85
+ * ready { sessionId, model, tools }
86
+ * stream_start { messageId }
87
+ * stream_delta { messageId, delta }
88
+ * stream_end { messageId }
89
+ * result { cost, duration, usage, sessionId }
90
+ * tool_start { messageId, toolUseId, tool, input }
91
+ * tool_result { toolUseId, result, truncated }
92
+ * error { message }
93
+ */
94
+
95
+ /**
96
+ * #6178: bound an fs promise so a stuck mount can't hold it open forever. Races
97
+ * `promise` against a timer that rejects with a tagged `HOOK_FS_TIMEOUT` error
98
+ * after `ms`. The timer is `unref`'d (never keeps the process alive) and cleared
99
+ * on settle (no leak on the happy path). Used only on the hot-path hook-drain
100
+ * fs ops. Exported for unit testing.
101
+ */
102
+ export function withHookFsTimeout(promise, ms, label) {
103
+ let timer
104
+ const timeout = new Promise((_resolve, reject) => {
105
+ timer = setTimeout(() => {
106
+ const err = new Error(`hook-fs ${label} timed out after ${ms}ms`)
107
+ err.code = 'HOOK_FS_TIMEOUT'
108
+ reject(err)
109
+ }, ms)
110
+ if (typeof timer.unref === 'function') timer.unref()
111
+ })
112
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer))
113
+ }
114
+
115
+ export class ClaudeTuiSession extends BaseSession {
116
+ // #5858: Claude-family flag — single source of truth for isClaudeProvider().
117
+ // This is the DEFAULT_PROVIDER, so its membership is load-bearing (#5855).
118
+ static claudeFamily = true
119
+
120
+ // #5984 (epic #5982): this IS the claude-tui PTY mirror — the only legitimate
121
+ // target for server-initiated PTY writes (mailbox wakeup) and the Control
122
+ // Room isTui flag. See BaseSession.isClaudeTui for why this is a positive
123
+ // discriminator rather than `typeof writeTerminalInput` duck-typing.
124
+ static get isClaudeTui() {
125
+ return true
126
+ }
127
+
128
+ static get displayLabel() {
129
+ return 'Claude Code (TUI · subscription)'
130
+ }
131
+
132
+ static get dataDir() {
133
+ return join(homedir(), '.claude')
134
+ }
135
+
136
+ static get capabilities() {
137
+ return {
138
+ // Permissions are gated via the chroxy permission-hook.sh script that
139
+ // posts to /permission on the chroxy HTTP server, same flow as
140
+ // CliSession. Requires a `port` arg at construction so the
141
+ // PreToolUse hook can phone home.
142
+ permissions: true,
143
+ inProcessPermissions: false,
144
+ modelSwitch: false,
145
+ // #4013: TUI supports mid-session permission switch via a sidecar
146
+ // file the hook script re-reads on every tool call. No PTY restart
147
+ // (which would lose the resumed conversation context), unlike
148
+ // CliSession's restart-based setPermissionMode.
149
+ permissionModeSwitch: true,
150
+ // #5609: the sidecar rewrite above means a mid-turn switch to 'auto'
151
+ // takes effect on the next tool call WITHOUT a PTY restart — the
152
+ // running turn survives. False keeps the matrix uniform; only CliSession
153
+ // interrupts the turn on the auto-switch.
154
+ interruptsTurnOnAutoSwitch: false,
155
+ planMode: false,
156
+ // #5307 (WP-0.1) — the TUI now persists its upstream conversation uuid
157
+ // (get resumeSessionId) and, on restore, respawns claude with
158
+ // `--resume <id>` so the conversation continues across daemon restart /
159
+ // upgrade / crash-recovery instead of silently starting a fresh chat.
160
+ resume: true,
161
+ terminal: false,
162
+ thinkingLevel: false,
163
+ streaming: false,
164
+ tools: true,
165
+ // #5791 — advertise whether the server will actually honor a single
166
+ // multi-select AskUserQuestion (the #5776 reinject path, gated by
167
+ // CHROXY_TUI_MULTISELECT_REINJECT, default OFF). Clients gate the
168
+ // checkbox-form affordance on this so they don't render a form the
169
+ // server is wired to refuse. Read at access time (listProviders is
170
+ // called per connection), so it reflects the daemon's env.
171
+ multiSelectReinject: multiSelectReinjectEnabled(),
172
+ }
173
+ }
174
+
175
+ static get preflight() {
176
+ return {
177
+ label: 'Claude TUI',
178
+ binary: {
179
+ name: 'claude',
180
+ args: ['--version'],
181
+ candidates: [
182
+ join(homedir(), '.local/bin/claude'),
183
+ '/opt/homebrew/bin/claude',
184
+ '/usr/local/bin/claude',
185
+ join(homedir(), '.claude/local/node_modules/.bin/claude'),
186
+ join(homedir(), '.npm-global/bin/claude'),
187
+ ],
188
+ installHint: 'install Claude Code CLI',
189
+ },
190
+ credentials: {
191
+ envVars: [],
192
+ hint: 'run `claude login` (subscription required — this provider does NOT accept ANTHROPIC_API_KEY)',
193
+ optional: true,
194
+ },
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Resolve runtime auth state for the dashboard (#4769).
200
+ *
201
+ * claude-tui explicitly deletes ANTHROPIC_API_KEY from the spawn env and
202
+ * routes via the OAuth subscription. #5321 (WP-4.1): best-effort on-disk
203
+ * probe instead of the old hardcoded `ready:true`, via the shared
204
+ * `hasClaudeOAuthCreds()` (#3674), which covers all known on-disk stores
205
+ * (`~/.claude/auth.json`, `~/.claude/.credentials.json`, the `claudeAiOauth`
206
+ * block in `~/.claude.json`) and honours `CHROXY_CLAUDE_HOME` /
207
+ * `CHROXY_CLAUDE_CONFIG`. macOS stores the token in the Keychain (no file),
208
+ * so a miss there is inconclusive. Hence:
209
+ * - creds found on disk → ready (authenticated)
210
+ * - absent on darwin → can't rule out Keychain → ready, flagged
211
+ * - absent on non-darwin → logged out → ready:false + `claude login`
212
+ * This is a pre-spawn hint only; the AUTHORITATIVE check is the runtime warmup
213
+ * classifier (#5321), which surfaces AUTH_REQUIRED at session start on every
214
+ * platform regardless of where the token lives.
215
+ *
216
+ * @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string, billingClass:string}}
217
+ */
218
+ static resolveAuth() {
219
+ const envVars = this.preflight.credentials.envVars
220
+ const hasFileCreds = hasClaudeOAuthCreds()
221
+ if (hasFileCreds) {
222
+ return {
223
+ ready: true,
224
+ source: 'oauth',
225
+ envVar: null,
226
+ envVars,
227
+ hint: 'authenticated — Claude OAuth credentials found on disk',
228
+ detail: 'Claude subscription (OAuth credentials on disk)',
229
+ // TUI is an interactive PTY that bypasses programmatic credit metering
230
+ // — flat subscription billing in both eras (#5629 leaves this UNCHANGED).
231
+ billingClass: BILLING_CLASSES.SUBSCRIPTION,
232
+ }
233
+ }
234
+ const keychainPossible = process.platform === 'darwin'
235
+ return {
236
+ // On macOS the token lives in the Keychain (unreadable here), so absence of
237
+ // the file does NOT prove logged-out — stay ready but flag it. On other
238
+ // platforms the file is the only store, so absence means logged out.
239
+ ready: keychainPossible,
240
+ source: 'oauth',
241
+ envVar: null,
242
+ envVars,
243
+ hint: keychainPossible
244
+ ? 'auth not verifiable on disk (macOS Keychain) — run `claude login` if a session reports AUTH_REQUIRED'
245
+ : 'run `claude login` — no Claude OAuth credentials found (subscription required; ANTHROPIC_API_KEY is not accepted)',
246
+ detail: keychainPossible
247
+ ? 'Claude subscription (OAuth in macOS Keychain — not on-disk-verifiable; runtime AUTH_REQUIRED is authoritative)'
248
+ : 'Claude subscription — no on-disk OAuth credentials found (logged out)',
249
+ billingClass: BILLING_CLASSES.SUBSCRIPTION,
250
+ }
251
+ }
252
+
253
+ static getFallbackModels() {
254
+ return CLAUDE_FALLBACK_MODELS
255
+ }
256
+
257
+ static getAllowedModels() {
258
+ return [...ALLOWED_MODEL_IDS]
259
+ }
260
+
261
+ static getModelMetadata(modelId) {
262
+ return claudeModelMetadata(modelId)
263
+ }
264
+
265
+ /**
266
+ * #4653: provider-specific events the SessionManager should forward as
267
+ * transient `session_event`s. `multi_question_intervention` fires from
268
+ * `_emitToolHookEvent` whenever PreToolUse sees an AskUserQuestion whose
269
+ * `questions[]` has length > 1 — i.e. the EXACT condition the bash
270
+ * permission-hook (`packages/server/hooks/permission-hook.sh`, #4648)
271
+ * denies on. The dashboard renders an inline notice + a session-footer
272
+ * counter so the user knows chroxy intercepted the multi-question form.
273
+ * Without this surface the user wonders if the model is being clever
274
+ * (asking one at a time naturally) or if chroxy is intervening — see
275
+ * the v0.9.24 dogfood feedback captured on #4653.
276
+ */
277
+ static get customEvents() {
278
+ // #5315 (WP-2.1) — `respawn_exhausted` is emitted by `_scheduleRespawn`
279
+ // when bounded PTY auto-respawn gives up (max attempts reached). WHY it's a
280
+ // custom event and not just an `error`: SessionManager keys its
281
+ // drop-the-session-from-the-list coordination on this distinct signal
282
+ // (`_wireSessionEvents` calls destroySession on it) so the session leaves
283
+ // the list with a clear error instead of lingering as an input-rejecting
284
+ // zombie tab. Listing it here also forwards it to paired clients as a
285
+ // transient `session_event` so the dashboard can surface the give-up reason.
286
+ return ['multi_question_intervention', 'respawn_exhausted']
287
+ }
288
+
289
+ constructor(opts = {}) {
290
+ super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-tui' }))
291
+ // ClaudeTuiSession-local opts (not BaseSession opts — see buildBaseSessionOpts).
292
+ const { port, firstOutputTimeoutMs, skipPermissions, resumeSessionId, monotonicNow } = opts
293
+
294
+ // #5332: monotonic clock for turn-duration logging and watchdog poll-loop
295
+ // deadlines (hook poll, waitForPrompt, PTY write). Wall-clock (Date.now())
296
+ // jumps backward on laptop sleep / NTP step, which can make a `while
297
+ // (Date.now() - start < timeout)` deadline never expire (hang) or expire
298
+ // early (false stall). performance.now() is monotonic — immune to both.
299
+ // Truncated to integer ms so it is a drop-in for the Date.now() deltas the
300
+ // instrumentation logs already print. Injectable so tests can step the
301
+ // clock backward and prove the watchdogs don't false-fire. Date.now() is
302
+ // retained ONLY where a real wall-clock epoch is required (file mtime
303
+ // comparison, timestamp payloads to clients, log-throttle bookkeeping).
304
+ // Truncate at the seam (not just the default) so the integer-ms invariant
305
+ // holds for an injected clock too — `performance.now()` and a test clock
306
+ // may both be fractional.
307
+ const rawMonotonicNow = typeof monotonicNow === 'function' ? monotonicNow : () => performance.now()
308
+ this._monotonicNowFn = () => Math.trunc(rawMonotonicNow())
309
+
310
+ // #6178: per-call bound for the hot-path hook-drain fs ops. #6132 made the
311
+ // drain async so a stuck sink fs can't block OTHER sessions; this bound lets
312
+ // the stuck session ITSELF self-recover — a hung readdir/readFile/unlink
313
+ // rejects after this many ms so the poll loop re-checks its hard-timeout
314
+ // guard instead of awaiting a frozen mount forever. Overridable in tests.
315
+ this._hookFsTimeoutMs = ClaudeTuiSession.HOOK_FS_TIMEOUT_MS
316
+ // #6178 (review): a timed-out fs op can't be canceled — it stays pending in
317
+ // the libuv threadpool. Re-issuing it every poll pass would pile up stuck
318
+ // work and exhaust the shared 4-thread pool, reintroducing the cross-session
319
+ // impact #6132 fixed. So coalesce: keep ONE outstanding op per (kind,path)
320
+ // and re-race the SAME promise each pass until it settles (see _boundedHookFs).
321
+ this._inFlightHookFs = new Map()
322
+
323
+ this._port = port || null
324
+ // #4044: when true, spawn `claude` with --dangerously-skip-permissions
325
+ // and skip chroxy's permission-hook + sidecar entirely. The user wants
326
+ // unmediated Claude TUI behaviour, not chroxy's `auto` mode (which still
327
+ // routes every call through the hook). Distinct from `permissionMode`:
328
+ // skipPermissions disables the whole permission system; permissionMode
329
+ // selects between approve/auto/acceptEdits/plan WITHIN it.
330
+ this.skipPermissions = !!skipPermissions
331
+ // Per-session hook secret — picked up by WsServer's session_created handler
332
+ // (ws-server.js:_registerSessionHookSecretIfMissing reads
333
+ // `entry.session._hookSecret` duck-typed). Mirrors the same name CliSession
334
+ // uses so the existing permission HTTP route routes us with no changes.
335
+ this._hookSecret = this._port ? randomBytes(32).toString('hex') : null
336
+ // #5307 (WP-0.1) — seed the upstream conversation uuid from the persisted
337
+ // resume id (SessionManager.restoreState passes it through from the saved
338
+ // sdkSessionId). When present, start() reuses it and spawns claude with
339
+ // `--resume <id>` so the conversation continues across restart; when absent
340
+ // (fresh session, or an older state file) it stays null and start() mints a
341
+ // new uuid spawned with `--session-id <id>`, exactly as before. Provider-
342
+ // local — NOT a BaseSession opt, so it is not forwarded via super() (matches
343
+ // CliSession's seeding pattern, cli-session.js:333).
344
+ this._sessionId = (typeof resumeSessionId === 'string' && resumeSessionId.length > 0)
345
+ ? resumeSessionId
346
+ : null // upstream claude conversation uuid, assigned at start() when fresh
347
+ this._resumedFromPersisted = this._sessionId !== null
348
+ // #5348 — remember whether this session was SEEDED from a persisted resume
349
+ // id. `_resumedFromPersisted` flips to true on every respawn (the respawn
350
+ // must `--resume` the live conversation), so later code can't use it to
351
+ // tell a restored session from an originally-fresh one. #5417: no longer
352
+ // the retry-FRESH eligibility gate (the PTY-tail classification in
353
+ // _scheduleRespawn is — claude itself must report the conversation id as
354
+ // unknown); kept to word the resume_unknown message honestly (restored =
355
+ // "the persisted conversation is gone from this machine" vs fresh = "it
356
+ // was likely never persisted before the PTY died").
357
+ this._seededFromPersisted = this._resumedFromPersisted
358
+ // #5348 — one-shot latch for the retry-FRESH fallback (mirrors
359
+ // cli-session.js's `_didFallbackFromUnknownResume`). Re-armed by a respawn
360
+ // that survives warmup, so a FUTURE doomed-resume window can fall back
361
+ // again; the #5349 rolling rate cap bounds any flapping alternation.
362
+ this._didFallbackFromUnknownResume = false
363
+ // #5348 — set by _scheduleRespawn when the next respawn attempt must spawn
364
+ // FRESH (`--session-id` with the newly-minted uuid) instead of `--resume`.
365
+ // Consumed (cleared) by _respawnPty before the spawn.
366
+ this._freshRetryPending = false
367
+ // #5348 — the conversation uuid abandoned by the retry-FRESH fallback,
368
+ // surfaced as `attemptedResumeId` on the terminal resume_unknown_exhausted
369
+ // emit (by then `_sessionId` is already the replacement uuid).
370
+ this._abandonedResumeId = null
371
+ // #4792: session-scoped logger. Assigned in start() once _sessionId is
372
+ // generated. Until then, code paths that need to log MUST fall back to
373
+ // the module-level `log` (e.g. trust pre-write failure, sink dir create
374
+ // failure). Per-session log lines (sendMessage, respondToQuestion,
375
+ // attachment materialization) prefer `this._log` so the WsServer log
376
+ // listener can route them to the right bound client (#4787, #4793).
377
+ this._log = null
378
+ this._sinkDir = null // created on start, removed on destroy
379
+ this._sinkRecoverErrLoggedMs = 0 // #5329: throttle the can't-recreate error log
380
+ this._sinkTransientWarnLoggedMs = 0 // #5329: throttle the dir-exists-but-readdir-failed warn
381
+ this._term = null // persistent PTY for the session's lifetime
382
+ this._settingsPath = null
383
+ // #4013: sidecar file containing the current permission mode. The
384
+ // hook script re-reads it on every tool call so setPermissionMode()
385
+ // can take effect without restarting the PTY (which would lose the
386
+ // resumed conversation context).
387
+ this._permissionModeFile = null
388
+ this._consumedFiles = new Set() // hook payload filenames already processed
389
+ this._activeTurn = null // { messageId, startedAt, aborted, synthSeq }
390
+ this._ptyExited = false
391
+ this._ptyExitInfo = null
392
+ // #5321 (WP-4.1) — latched true when warmup classifies claude's output as a
393
+ // logged-out / expired-login failure, so start() rejects with AUTH_REQUIRED.
394
+ this._authFailureDetected = false
395
+ // #5315 (WP-2.1) — bounded per-session PTY auto-respawn state, mirroring
396
+ // CliSession (cli-session.js:351). WHY: when the persistent claude PTY dies
397
+ // unexpectedly mid-session, `_onPtyGone` used to tear the session down into
398
+ // a permanently input-rejecting zombie (every later sendMessage rejected
399
+ // "no longer alive"). The TUI provider is becoming the PRIMARY backend, so
400
+ // it must self-heal like CliSession does. Backoff [1s,2s,4s,8s,15s], max 5
401
+ // attempts, then `respawn_exhausted` (SessionManager drops the session).
402
+ this._respawnCount = 0
403
+ this._respawnTimer = null
404
+ this._respawnScheduled = false
405
+ this._respawning = false
406
+ // #5349: a rolling-window cap INDEPENDENT of `_respawnCount` (which resets
407
+ // on every warmup that survives — see _onWarmupComplete). A session that
408
+ // dies shortly after each successful warmup flaps forever under the
409
+ // consecutive cap alone; this gives up once it exceeds the window cap
410
+ // regardless of warmup success. Mirrors the same guard in CliSession.
411
+ this._respawnRateLimiter = new RespawnRateLimiter()
412
+ // #5317 (WP-2.3) — SIGKILL escalation timer armed by destroy() after SIGTERM.
413
+ // Cleared by _onPtyGone the moment the process is confirmed gone (which also
414
+ // closes the pid-reuse window — we only force-kill when onExit never fired).
415
+ this._killTimer = null
416
+ // Ring buffer of recent PTY output bytes — surfaces in error
417
+ // messages when the TUI renders a diagnostic (rate-limit, auth
418
+ // failure, "switch back to API mode") that would otherwise be
419
+ // silently dropped (#3919). Kept small (~4KB) so it doesn't eat
420
+ // memory on long sessions.
421
+ this._outputTail = ''
422
+ // #5794: monotonic count of ALL PTY output bytes ever appended. Unlike
423
+ // _outputTail (capped at PTY_TAIL_BYTES, so its length stops growing once
424
+ // full — e.g. after a long resume transcript), this keeps growing, so the
425
+ // first-turn nudge can detect "output arrived since arm" even when the tail
426
+ // is already at the cap (#5809 review).
427
+ this._totalOutputBytes = 0
428
+ // #4031 (review): _outputTail is ANSI-stripped for readability +
429
+ // probe stability, so the hex-dump diagnostic sourced from it
430
+ // could never surface the very escape/control bytes we wanted to
431
+ // see when the probe missed. Keep an UNSTRIPPED parallel tail —
432
+ // sized in real bytes via Buffer — exclusively for the hex dump
433
+ // so 0x1b/OSC/SS3 sequences land in the log. node-pty returns
434
+ // UTF-8 strings already decoded, but the relevant control bytes
435
+ // are 7-bit ASCII and survive the decode unchanged.
436
+ this._outputTailRaw = Buffer.alloc(0)
437
+ // #6601: PTY output-quiescence readiness signal. `_lastOutputMs` is the
438
+ // monotonic time of the most recent onData chunk; `_sawFirstOutput` gates the
439
+ // signal until claude has actually rendered something on THIS spawn (so the
440
+ // `now - 0` at init doesn't read as "already quiescent"). Together (checkReady)
441
+ // they detect a settled composer when no ~/.claude/sessions file exists.
442
+ this._lastOutputMs = 0
443
+ this._sawFirstOutput = false
444
+ // #5835 Phase 1: live remote-viewer mirror. PTY onData fires very frequently
445
+ // during a TUI redraw, so coalesce bytes into a buffer and flush one
446
+ // `terminal_output` event per tick (MIRROR_FLUSH_MS) — bounding the broadcast
447
+ // rate to the tunnel rather than emitting per byte. Buffer + timer are reset
448
+ // on flush and cleared on teardown.
449
+ this._mirrorBuffer = ''
450
+ this._mirrorTimer = null
451
+ // #5837: gate the coalescer on having ≥1 subscriber. The mirror is OFF until a
452
+ // client opts in (terminal_subscribe), so a claude-tui session nobody is
453
+ // watching pays nothing per PTY redraw (no string concat, no timer, no
454
+ // session_event). WsServer toggles this via setTerminalMirrorActive when the
455
+ // terminal-subscriber count for the session crosses 0↔1 (subscribe / unsubscribe
456
+ // / client departure). Forward-only: a subscriber sees redraws from when it
457
+ // subscribed onward — same as Phase 1, the mirror was never a snapshot.
458
+ this._terminalMirrorActive = false
459
+ // #5835 Phase 2: the live PTY's current grid size. Spawns at the shared
460
+ // default and tracks every applied resize so a respawn re-spawns at the
461
+ // operator's chosen size (not back to the default), and so a newly-
462
+ // subscribing viewer can be told the authoritative size to letterbox to.
463
+ this._ptyCols = CLAUDE_TUI_PTY_SIZE.cols
464
+ this._ptyRows = CLAUDE_TUI_PTY_SIZE.rows
465
+ // #4278: when claude TUI calls AskUserQuestion, chroxy's PreToolUse
466
+ // hook emits user_question and stashes the toolUseId here. The
467
+ // dashboard's QuestionPrompt UI eventually sends a
468
+ // `user_question_response` which routes to respondToQuestion() —
469
+ // that method writes the chosen answer back to the PTY (claude's
470
+ // own TTY-style prompt is waiting on stdin).
471
+ //
472
+ // #4668 (Map refactor): when claude TUI emits parallel AskUserQuestion
473
+ // tool_use blocks in one assistant turn (which it has been observed to
474
+ // do post-#4648 deny), the single-field `_pendingUserAnswer` was
475
+ // overwritten by each new tool_use — so the user's answer to question
476
+ // 1 got routed to question 4's slot. Map keyed by toolUseId preserves
477
+ // every pending answer independently; respondToQuestion(toolUseId, …)
478
+ // routes the dashboard's answer to the right entry. Back-compat getter
479
+ // `_pendingUserAnswer` returns the most-recently-set entry so legacy
480
+ // tests + callers that read the single field keep working.
481
+ this._pendingUserAnswers = new Map()
482
+ this._lastPendingAnswerToolUseId = null
483
+ // #5617 — the interactive-form driver is an injected collaborator rather than
484
+ // a prototype mixin; it reaches session state/PTY writers through `this` as
485
+ // its host. `respondToQuestion` (below) delegates to it; the stall watchdog
486
+ // calls `this._formDriver._onAskUserQuestionStall`.
487
+ this._formDriver = new FormDriver(this)
488
+ // #4604 / #5319 (WP-3.2): per-toolUseId stall watchdogs armed in
489
+ // respondToQuestion(). If PostToolUse never arrives after we write an answer
490
+ // (multi-question form wedge), the matching watchdog fires
491
+ // _onAskUserQuestionStall to clear busy state + emit an error so the session
492
+ // is recoverable. Keyed by toolUseId (mirrors the #4668 _pendingUserAnswers
493
+ // Map) so PARALLEL AskUserQuestion calls each get an independent watchdog —
494
+ // answering / stalling one no longer disarms the others. Cleared per-id on
495
+ // PostToolUse and cleared wholesale on the turn-ending paths + destroy().
496
+ this._askUserQuestionWatchdogs = new Map()
497
+ // #5792: denied-shape AskUserQuestion reapers, keyed by toolUseId. A
498
+ // multi-question (questions.length > 1) or multi-select (any question
499
+ // multiSelect:true) AskUserQuestion is DENIED at the permission hook, so
500
+ // claude blocks → Stops with no PostToolUse. The Stop success path
501
+ // (_clearTurnEndState) clears the sibling lock + stall watchdogs but
502
+ // deliberately NOT _pendingUserAnswers (a legit sibling answer may still be
503
+ // in flight — see _pendingUserAnswers_clearAll's doc). For a denied shape
504
+ // there is NO legit answer coming, so that pending entry leaks: a later
505
+ // no-toolUseId respondToQuestion would misroute to it via the most-recent
506
+ // back-compat fallback. This reaper, armed ONLY for denied shapes at
507
+ // pending-creation, drops the still-leaked entry after a short window. It is
508
+ // deliberately keyed/cleared per toolUseId and does NOT touch the global
509
+ // askuserquestion-active lock (already cleared at the denied turn's Stop; a
510
+ // later turn may own a fresh lock by the time the reaper fires).
511
+ this._deniedQuestionReapers = new Map()
512
+ // #5798: observability-only marker for the multi-select reinject "stop and
513
+ // wait" steer. When CHROXY_TUI_MULTISELECT_REINJECT is on and a multi-select
514
+ // AskUserQuestion is denied, the deny reason steers the model to STOP its
515
+ // turn so the reinjected selection (sendMessage) lands as a fresh turn. The
516
+ // FormDriver sets this marker right after the flag-on sendMessage; if the
517
+ // model instead emits another tool_use before the reinjected turn's first
518
+ // output clears it, we log a loud WARN (greppable: reinject_stop_wait_violation
519
+ // / #5798) — the signal the steer was NOT honored. Shape when set:
520
+ // { deniedToolUseId, at } where `at` is _nowMonotonic(). Null = no window
521
+ // open. Set ONLY on the flag-on reinject path; cleared one-shot on the WARN,
522
+ // on the reinjected turn's first consumed hook (_clearFirstOutputWatchdog),
523
+ // and on every teardown/destroy/pty-gone path so a stale marker can't leak.
524
+ // This NEVER changes behavior — it is a measurement aid only.
525
+ this._reinjectStopWaitWatch = null
526
+ // #4732: effective pre-first-output timeout in ms. Distinct from
527
+ // _streamStallTimeoutMs (#4638) — that watchdog only re-arms BETWEEN
528
+ // hook events, so a turn where claude TUI accepts the prompt write
529
+ // but never emits ANY hook (stuck Anthropic API call, frozen dialog
530
+ // screen) had no recoverable watchdog short of the 2h hard cap. This
531
+ // timer arms at _armResultTimeout() time and disarms on the first
532
+ // consumed hook event. 0 disables; non-finite, negative, or above
533
+ // the 24h ceiling falls back to FIRST_OUTPUT_TIMEOUT_MS (90s).
534
+ this._firstOutputTimeoutMs =
535
+ isOperatorTimeoutInRange(firstOutputTimeoutMs, { allowZero: true, name: 'firstOutputTimeoutMs', log })
536
+ ? firstOutputTimeoutMs
537
+ : ClaudeTuiSession.FIRST_OUTPUT_TIMEOUT_MS
538
+ this._firstOutputTimeout = null
539
+ this._firstOutputArmedAt = 0
540
+ // #4732: per-turn latch — flipped true by `_clearFirstOutputWatchdog`
541
+ // so subsequent `_armResultTimeout` re-arms (one per consumed hook)
542
+ // don't re-arm the first-output timer. Reset to false on each new
543
+ // turn via `_resetFirstOutputWatchdogForTurn` (sendMessage entry path).
544
+ this._firstOutputDisarmed = false
545
+ // #5777: first-message submit nudge. A freshly-spawned TUI can report
546
+ // status:idle (ready) before its composer actually accepts the submit, so
547
+ // the FIRST message's trailing \r lands on a not-yet-interactive prompt and
548
+ // the text sits unsent until a second message nudges it (the manual "go"
549
+ // workaround). On the first turn only, a one-shot timer re-sends a bare \r
550
+ // if no hook output has arrived within the window. 0 disables.
551
+ this._firstTurnSubmitNudgeMs = ClaudeTuiSession.FIRST_TURN_SUBMIT_NUDGE_MS
552
+ this._firstTurnSubmitNudgeTimer = null
553
+ // #5794: per-spawn latch so the nudge arms on the FIRST message after each
554
+ // (re)spawn, not only the lifetime-first message. `_messageCounter` is
555
+ // monotonic (never reset), so keying the nudge on `=== 1` left a mid-session
556
+ // respawn's first turn un-nudged even though the warm-composer wedge can
557
+ // recur on the fresh PTY. Reset to false in _spawnPty (every successful
558
+ // (re)spawn), flipped true the first time sendMessage arms the nudge.
559
+ this._firstTurnNudgedForSpawn = false
560
+ // #6578: cache the session-file path resolved by resolveSessionFile so the
561
+ // per-turn readiness probe doesn't re-scan ~/.claude/sessions every turn.
562
+ // Invalidated on every (re)spawn (reset in _spawnPty alongside the nudge
563
+ // latch) because a respawn under a wrapper shim can land on a new pid, and a
564
+ // retry-FRESH fallback mints a new sessionId → the old path no longer maps.
565
+ this._resolvedSessionFile = null
566
+ // #6578: last time the readiness probe ran the (readdir-heavy) session-file
567
+ // dir-scan, so it can be throttled to ~2/sec during warmup. -Infinity so the
568
+ // first cold-resolve scans immediately; reset on each (re)spawn.
569
+ this._lastSessionDirScanMs = -Infinity
570
+ // #5431: incremental transcript scanner for outstanding background work
571
+ // (run_in_background Bash/Agent, Monitor, ScheduleWakeup). Created
572
+ // lazily by getBackgroundTaskSnapshot() once the per-PID session file
573
+ // resolves to a transcript path; replaced if the transcript path
574
+ // changes (new conversation id after /clear or resume).
575
+ this._transcriptTaskScanner = null
576
+ // #5431: change-detection poll armed while the last snapshot reported
577
+ // outstanding work. Re-scans the transcript so a task-notification that
578
+ // lands while the session is IDLE still clears the dashboard indicator
579
+ // (the TUI re-invokes itself on notifications — chroxy sees no turn).
580
+ this._backgroundTaskPollTimer = null
581
+ this._lastBackgroundTaskKey = null
582
+ }
583
+
584
+ /**
585
+ * Back-compat getter for the pre-#4668 single-field `_pendingUserAnswer`.
586
+ * Returns the most-recently-set pending answer entry, or null when none
587
+ * are pending. New code should iterate / look up `_pendingUserAnswers`
588
+ * directly by toolUseId.
589
+ */
590
+ get _pendingUserAnswer() {
591
+ if (!this._lastPendingAnswerToolUseId) return null
592
+ return this._pendingUserAnswers.get(this._lastPendingAnswerToolUseId) || null
593
+ }
594
+
595
+ /**
596
+ * Back-compat setter: writing an entry sets it in the Map keyed by its
597
+ * toolUseId AND updates the "most recent" pointer. Pre-#4668 callers
598
+ * that wrote `_pendingUserAnswer = { ... }` don't need to change.
599
+ *
600
+ * #4802: the previous null-branch behaviour (`= null` → Map.clear()) is
601
+ * removed. Implicit clear-all at every teardown site silently wiped
602
+ * sibling AskUserQuestion entries that still had answers in flight
603
+ * (see `_pendingUserAnswers_clearAll` for the audit + the per-callsite
604
+ * rationale). Writing null now throws so the regression is loud — each
605
+ * callsite must pick `_pendingUserAnswers_clearAll()` (intentional
606
+ * turn-level wipe with documented reason) or
607
+ * `_clearPendingAnswerByToolUseId(tid)` (surgical, the watchdog path)
608
+ * explicitly.
609
+ */
610
+ set _pendingUserAnswer(entry) {
611
+ if (entry === null || entry === undefined) {
612
+ throw new Error('_pendingUserAnswer = null/undefined forbidden (#4802) — use _pendingUserAnswers_clearAll() or _clearPendingAnswerByToolUseId(tid) so the destructive intent is visible at the call site')
613
+ }
614
+ const toolUseId = entry.toolUseId
615
+ if (toolUseId) {
616
+ this._pendingUserAnswers.set(toolUseId, entry)
617
+ this._lastPendingAnswerToolUseId = toolUseId
618
+ }
619
+ }
620
+
621
+ /**
622
+ * #4802: explicit clear-all for the turn-level teardown sites that
623
+ * unambiguously kill the PTY for the current turn (Ctrl-C via
624
+ * `_teardownTurn` / `interrupt()`, or SIGTERM via `destroy()`). After
625
+ * any of those, even a surviving Map entry can't be served — claude
626
+ * TUI is no longer waiting on its prompt — so wiping the slot keeps
627
+ * a late `respondToQuestion` from writing into a torn-down form.
628
+ *
629
+ * NOT used by `_finishTurnError` (no Ctrl-C, sibling answers may still
630
+ * be valid for the brief race window — see audit P1.2) nor by the
631
+ * AskUserQuestion stall watchdog (knows the exact `toolUseId` that
632
+ * stalled, so it calls `_clearPendingAnswerByToolUseId` instead per
633
+ * #4691).
634
+ */
635
+ _pendingUserAnswers_clearAll() {
636
+ this._pendingUserAnswers.clear()
637
+ this._lastPendingAnswerToolUseId = null
638
+ // #5792: pending entries are gone → their reapers have nothing to guard.
639
+ this._clearAllDeniedQuestionReapers()
640
+ }
641
+
642
+ /** Internal: drop a specific pending answer entry (PostToolUse cleanup). */
643
+ _clearPendingAnswerByToolUseId(toolUseId) {
644
+ if (!toolUseId) return
645
+ this._pendingUserAnswers.delete(toolUseId)
646
+ // #5792: the entry is gone → cancel its denied-shape reaper (no-op if none).
647
+ this._clearDeniedQuestionReaper(toolUseId)
648
+ if (this._lastPendingAnswerToolUseId === toolUseId) {
649
+ // Advance the "most recent" pointer to whichever entry was set most
650
+ // recently after the one we just removed (insertion-order via Map
651
+ // iteration). null when the Map is empty.
652
+ const keys = [...this._pendingUserAnswers.keys()]
653
+ this._lastPendingAnswerToolUseId = keys.length > 0 ? keys[keys.length - 1] : null
654
+ }
655
+ }
656
+
657
+ /**
658
+ * #5617 — delegate the AskUserQuestion answer to the injected FormDriver.
659
+ * Kept on the session because external callers (input-handlers.js) and the
660
+ * provider contract call `session.respondToQuestion(...)`; the driving logic
661
+ * lives in form-driver.js, reaching session state/PTY writers via its host.
662
+ */
663
+ respondToQuestion(text, answersMap, toolUseId, opts) {
664
+ return this._formDriver.respondToQuestion(text, answersMap, toolUseId, opts)
665
+ }
666
+
667
+ /**
668
+ * #5319 (WP-3.2): arm (or re-arm) the per-toolUseId AskUserQuestion stall
669
+ * watchdog. Each toolUseId gets its own timer so a parallel sibling's arm
670
+ * can't clobber this one. On fire it deletes its own Map entry, then calls
671
+ * _formDriver._onAskUserQuestionStall. A null/undefined toolUseId is keyed
672
+ * verbatim (one anonymous slot) so the defensive no-toolUseId path keeps a
673
+ * watchdog. `ms` defaults to the standard window but the Other-freeform
674
+ * two-stage flow passes OTHER_FREEFORM_WATCHDOG_MS for its longer second stage.
675
+ */
676
+ _armAskUserQuestionWatchdog(toolUseId, ms = ASK_USER_QUESTION_WATCHDOG_MS) {
677
+ const existing = this._askUserQuestionWatchdogs.get(toolUseId)
678
+ if (existing) clearTimeout(existing)
679
+ const t = setTimeout(() => {
680
+ this._askUserQuestionWatchdogs.delete(toolUseId)
681
+ this._formDriver._onAskUserQuestionStall(toolUseId)
682
+ }, ms)
683
+ this._askUserQuestionWatchdogs.set(toolUseId, t)
684
+ }
685
+
686
+ /** #5319 (WP-3.2): cancel + drop ONE toolUseId's stall watchdog (PostToolUse / per-question teardown). Idempotent. */
687
+ _clearAskUserQuestionWatchdog(toolUseId) {
688
+ const t = this._askUserQuestionWatchdogs.get(toolUseId)
689
+ if (t) {
690
+ clearTimeout(t)
691
+ this._askUserQuestionWatchdogs.delete(toolUseId)
692
+ }
693
+ }
694
+
695
+ /** #5319 (WP-3.2): cancel + drop ALL stall watchdogs (turn-ending paths + destroy()). Idempotent. */
696
+ _clearAllAskUserQuestionWatchdogs() {
697
+ for (const t of this._askUserQuestionWatchdogs.values()) clearTimeout(t)
698
+ this._askUserQuestionWatchdogs.clear()
699
+ }
700
+
701
+ /**
702
+ * #5792: arm (or re-arm) the denied-shape reaper for one toolUseId. Called
703
+ * from `_emitToolHookEvent` ONLY when the AskUserQuestion payload is a denied
704
+ * shape (multi-question or multi-select) — a legitimate single single-select
705
+ * arms its own stall watchdog in `respondToQuestion` instead and is left
706
+ * alone. On fire, `_reapDeniedQuestion` drops the pending entry if it still
707
+ * leaks. Unlike the stall watchdog (which assumes a live, busy turn), this
708
+ * reaper must OUTLIVE the turn: the denied turn Stops immediately, so the
709
+ * reaper is intentionally NOT cleared by `_clearTurnEndState` — only when the
710
+ * pending entry it guards is cleared (see `_clearPendingAnswerByToolUseId` /
711
+ * `_pendingUserAnswers_clearAll`).
712
+ */
713
+ _armDeniedQuestionReaper(toolUseId, ms = DENIED_QUESTION_REAPER_MS) {
714
+ if (!toolUseId) return
715
+ const existing = this._deniedQuestionReapers.get(toolUseId)
716
+ if (existing) clearTimeout(existing)
717
+ const t = setTimeout(() => {
718
+ this._deniedQuestionReapers.delete(toolUseId)
719
+ this._reapDeniedQuestion(toolUseId)
720
+ }, ms)
721
+ this._deniedQuestionReapers.set(toolUseId, t)
722
+ }
723
+
724
+ /** #5792: cancel + drop ONE toolUseId's denied-shape reaper. Idempotent. */
725
+ _clearDeniedQuestionReaper(toolUseId) {
726
+ const t = this._deniedQuestionReapers.get(toolUseId)
727
+ if (t) {
728
+ clearTimeout(t)
729
+ this._deniedQuestionReapers.delete(toolUseId)
730
+ }
731
+ }
732
+
733
+ /** #5792: cancel + drop ALL denied-shape reapers (turn-level wipe + destroy()). Idempotent. */
734
+ _clearAllDeniedQuestionReapers() {
735
+ for (const t of this._deniedQuestionReapers.values()) clearTimeout(t)
736
+ this._deniedQuestionReapers.clear()
737
+ }
738
+
739
+ /**
740
+ * #5792: drop a denied-shape AskUserQuestion's pending entry if it STILL
741
+ * leaks after the reaper window (deny → Stop → idle with no answer). A no-op
742
+ * when the entry is already gone (PostToolUse arrived, the user answered, or a
743
+ * turn-ending teardown cleared it). Clears only this toolUseId's state — the
744
+ * pending entry and its own (keyed) stall watchdog. It deliberately does NOT
745
+ * touch the global `askuserquestion-active` lock: that lock is already cleared
746
+ * at the denied turn's Stop (`_clearTurnEndState`), and clearing it here could
747
+ * drop a LATER turn's legitimate lock if a fresh AskUserQuestion is in flight
748
+ * when the reaper fires.
749
+ */
750
+ _reapDeniedQuestion(toolUseId) {
751
+ if (this._destroying) return
752
+ if (!this._pendingUserAnswers.has(toolUseId)) return
753
+ ;(this._log || log).warn(`AskUserQuestion denied-shape reaper (#5792): tool=${toolUseId} pending entry never cleared after deny→Stop→idle — dropping leaked entry so a later no-toolUseId answer can't misroute to it`)
754
+ // _clearPendingAnswerByToolUseId re-enters _clearDeniedQuestionReaper; that's
755
+ // an idempotent no-op here (this reaper already self-deleted from the Map
756
+ // before its callback ran).
757
+ this._clearPendingAnswerByToolUseId(toolUseId)
758
+ this._clearAskUserQuestionWatchdog(toolUseId)
759
+ }
760
+
761
+ /**
762
+ * #4668 cleanup: drop the askuserquestion-active sibling lock the
763
+ * permission-hook.sh leaves under our sink dir. The hook script's
764
+ * PostToolUse cleanup (tee | grep | rm) handles the happy path, but
765
+ * when a turn tears down for ANY other reason (watchdog fire, stream
766
+ * stall, hard timeout, PTY exit mid-turn, destroy()) the lock leaks
767
+ * and blocks the next turn's AskUserQuestion at the sibling-deny
768
+ * check. Cheap idempotent rm — call from every teardown path.
769
+ */
770
+ _clearAskUserQuestionLock() {
771
+ if (!this._sinkDir) return
772
+ try { rmSync(join(this._sinkDir, 'askuserquestion-active'), { recursive: true, force: true }) } catch {}
773
+ }
774
+
775
+ // #6178: hot-path hook-drain fs accessors. Thin wrappers over fs/promises so a
776
+ // test can override them to simulate a hung mount; production just forwards.
777
+ // The drain calls them via _boundedHookFs (bound + coalesced), never directly.
778
+ _hookReaddir(dir) { return readdir(dir) }
779
+ _hookReadFile(path) { return readFile(path, 'utf8') }
780
+ _hookUnlink(path) { return unlink(path) }
781
+
782
+ /**
783
+ * #6178 (review) — run a hot-path hook-drain fs op bounded by HOOK_FS_TIMEOUT_MS
784
+ * AND coalesced so at most one underlying op per (kind,path) is outstanding.
785
+ *
786
+ * A timed-out fs op can't be canceled: the real readdir/readFile/unlink stays
787
+ * pending in the libuv threadpool until the mount unfreezes. If each poll pass
788
+ * started a fresh op we'd accumulate stuck threadpool work and exhaust the
789
+ * shared 4-thread pool — reintroducing the cross-session blocking #6132 fixed.
790
+ * So we keep the SAME underlying promise per (kind,path) and re-race a fresh
791
+ * timer against it each pass; only after it finally settles is a new op issued.
792
+ *
793
+ * @param {'readdir'|'readFile'|'unlink'} kind
794
+ * @param {string} path the sink dir (readdir) or a hook file (readFile/unlink)
795
+ * @returns {Promise<*>} the op result, or a HOOK_FS_TIMEOUT rejection
796
+ */
797
+ _boundedHookFs(kind, path) {
798
+ const key = `${kind}:${path}`
799
+ let inflight = this._inFlightHookFs.get(key)
800
+ if (!inflight) {
801
+ inflight = kind === 'readdir' ? this._hookReaddir(path)
802
+ : kind === 'readFile' ? this._hookReadFile(path)
803
+ : this._hookUnlink(path)
804
+ // Free the slot when the real op finally settles (even long after our race
805
+ // gave up), so a recovered mount can issue a fresh op. The then(noop,noop)
806
+ // marks the underlying promise handled so a late rejection is never an
807
+ // unhandledRejection; the guard avoids clobbering a newer entry.
808
+ inflight.then(() => {}, () => {}).finally(() => {
809
+ if (this._inFlightHookFs.get(key) === inflight) this._inFlightHookFs.delete(key)
810
+ })
811
+ this._inFlightHookFs.set(key, inflight)
812
+ }
813
+ return withHookFsTimeout(inflight, this._hookFsTimeoutMs, kind)
814
+ }
815
+
816
+ /**
817
+ * #5329 (IP-1): recover the hook sink dir after a readdir failure during the
818
+ * poll loop. The sink lives under /tmp, so a tmpwatch sweep / tmpfs clear /
819
+ * manual rm can delete it mid-turn — and claude's hook commands write to this
820
+ * exact path, so once the dir is gone every `cat > <sink>/…` also fails and
821
+ * the turn wedges silently until the hard timeout.
822
+ *
823
+ * Recreate the SAME path (claude's already-loaded hooks embed it) plus the
824
+ * owner.pid stamp and the permission-mode sidecar (so the hook reads the live
825
+ * mode rather than falling back to the stale spawn-time env var). If
826
+ * recreation itself fails (e.g. /tmp is full → ENOSPC), surface it loudly
827
+ * (throttled) instead of spinning silently.
828
+ *
829
+ * @param {Error} [cause] the readdir error that triggered recovery
830
+ * @returns {boolean} true if the sink is usable afterward
831
+ */
832
+ _recoverSinkDir(cause) {
833
+ if (!this._sinkDir) return false
834
+ const logger = this._log || log
835
+ // Distinguish three states by what's actually AT the sink path:
836
+ // - a real directory → readdir failed transiently (EACCES/EMFILE); warn
837
+ // (throttled) but don't thrash recreation.
838
+ // - nothing → vanished (tmpwatch/rm); recreate.
839
+ // - a non-directory (file/symlink squatting the path) → readdir would
840
+ // throw ENOTDIR forever; rm the squatter, then recreate.
841
+ let isDir = false
842
+ try { isDir = statSync(this._sinkDir).isDirectory() } catch { /* missing or unstat-able */ }
843
+ if (isDir) {
844
+ const now = Date.now()
845
+ if (now - this._sinkTransientWarnLoggedMs >= 5000) {
846
+ this._sinkTransientWarnLoggedMs = now
847
+ logger.warn(`hook sink readdir failed though ${this._sinkDir} is a directory: ${cause?.message || cause}`)
848
+ }
849
+ return true
850
+ }
851
+ try {
852
+ // Clear a non-directory squatting the path (no-op if nothing is there)
853
+ // so mkdir can create a real directory.
854
+ try { rmSync(this._sinkDir, { recursive: true, force: true }) } catch { /* best effort */ }
855
+ mkdirSync(this._sinkDir, { recursive: true })
856
+ try { writeFileSync(join(this._sinkDir, 'owner.pid'), String(process.pid)) } catch { /* best effort */ }
857
+ if (this._permissionModeFile) {
858
+ try { this._writePermissionModeSidecarAtomic(this._permissionModeFile, this.permissionMode || 'approve') } catch { /* hook falls back to env var */ }
859
+ }
860
+ this._sinkRecoverErrLoggedMs = 0
861
+ logger.warn(`hook sink ${this._sinkDir} vanished mid-turn and was recreated — hook delivery restored (cause: ${cause?.message || cause})`)
862
+ return true
863
+ } catch (err) {
864
+ // Persistent failure (disk full, parent gone): throttle the error so a
865
+ // 150ms poll loop doesn't flood the log.
866
+ const now = Date.now()
867
+ if (now - this._sinkRecoverErrLoggedMs >= 5000) {
868
+ this._sinkRecoverErrLoggedMs = now
869
+ logger.error(`hook sink ${this._sinkDir} vanished and could NOT be recreated (${err.message}) — tool events for this turn may be lost (disk full?)`)
870
+ }
871
+ return false
872
+ }
873
+ }
874
+
875
+ // #5332: monotonic now (integer ms). Used for every turn-duration delta and
876
+ // watchdog poll-loop deadline so a wall-clock jump can't hang or false-fire
877
+ // them. See the _monotonicNowFn note in the constructor.
878
+ _nowMonotonic() { return this._monotonicNowFn() }
879
+
880
+ // Tail length to keep + length to include in error diagnostics.
881
+ static get PTY_TAIL_BYTES() { return 4096 }
882
+ static get PTY_TAIL_DIAGNOSTIC_BYTES() { return 1024 }
883
+
884
+ // #5835 Phase 1: coalescing window for the live remote-viewer mirror. PTY
885
+ // onData fires many times per redraw; flushing one `terminal_output` per
886
+ // ~50ms caps the broadcast rate (the deliberate latency-for-bandwidth trade —
887
+ // a faithful-but-slightly-laggy mirror) without dropping any bytes.
888
+ static get MIRROR_FLUSH_MS() { return 50 }
889
+
890
+ // #4269: per-character delay when writing the prompt to the PTY.
891
+ // claude TUI's paste detector triggers on byte-arrival rate, not DEC
892
+ // mode 2004 — a single bulk write of ~hundreds of bytes is collapsed
893
+ // into a "[Pasted text #1 +N lines] paste again to expand" placeholder
894
+ // that chroxy never confirms, hanging the turn silently. Throttling to
895
+ // ~1 ms per char makes the bytes look like typed input. A 600-char
896
+ // prompt costs ~600 ms of one-time latency before claude starts —
897
+ // imperceptible during interactive use.
898
+ //
899
+ // The loop iterates by code-point (`for (const ch of text)`), not by
900
+ // UTF-16 code unit, so each non-BMP char (emoji, supplementary CJK)
901
+ // is one write of a 2-code-unit string and writes its 4 UTF-8 bytes
902
+ // in a single tick. An emoji-heavy prompt therefore arrives at ~4×
903
+ // the byte-rate of ASCII, still well under any reasonable bulk-paste
904
+ // threshold given the 1ms throttle. If paste-detection symptoms ever
905
+ // surface for emoji-only prompts, decompose to UTF-8 bytes (or
906
+ // graphemes) before the loop (#4274).
907
+ static get PROMPT_CHAR_DELAY_MS() { return 1 }
908
+
909
+ // #4732: default pre-first-output silence timeout (ms). Fires once at
910
+ // turn start when claude TUI accepts the prompt write but emits no
911
+ // hook events for this long — see _firstOutputTimeoutMs JSDoc + the
912
+ // describe block in claude-tui-session.test.js for the why. Sized at
913
+ // 90s: wide enough to cover slow first-token latency (cold model,
914
+ // big context, slow Anthropic backend) but tight enough that the
915
+ // dashboard chip surfaces within a minute or two of a real stall so
916
+ // the user can retry without waiting for the 2h hard cap.
917
+ static get FIRST_OUTPUT_TIMEOUT_MS() { return 90 * 1000 }
918
+
919
+ // #5777: first-turn submit-nudge interval (ms) and max attempts. A freshly-
920
+ // spawned TUI can report ready before its composer accepts the submit, so the
921
+ // first message's \r is dropped. If no hook output arrives within this window
922
+ // the nudge re-sends a bare \r. 1.5s is long enough that a normally-submitted
923
+ // turn has usually produced its first hook (so the nudge no-ops), short enough
924
+ // that a real wedge unsticks in seconds instead of waiting for the 90s
925
+ // first-output watchdog. Two attempts (≈1.5s, ≈3s) then defer to the watchdog.
926
+ static get FIRST_TURN_SUBMIT_NUDGE_MS() { return 1500 }
927
+ static get FIRST_TURN_SUBMIT_NUDGE_MAX_ATTEMPTS() { return 2 }
928
+
929
+ // #4276: per-char throttling is O(N) blocking latency. For huge
930
+ // prompts (pasted file contents, JSON dumps) the cumulative cost
931
+ // dominates the turn — at ~1ms per code-point a 100K-char prompt
932
+ // would block sendMessage for over a minute with no user-visible
933
+ // progress. Above this threshold the helper falls back to a single
934
+ // bulk `_term.write(text)`, accepting that very large prompts may
935
+ // trip claude TUI's paste detector. That symptom (visible "Pasted
936
+ // text" placeholder) is strictly better than a multi-minute silent
937
+ // hang, and small/medium prompts — the typical interactive path —
938
+ // are unaffected.
939
+ //
940
+ // 8192 was chosen as a generous interactive ceiling: ~8s worst case
941
+ // even with a 1ms-floor event loop, and well above any realistic
942
+ // hand-typed or single-paragraph prompt. Adjust if the dirty-test
943
+ // stub (#4271) measures the actual paste-detector threshold.
944
+ static get MAX_THROTTLED_CHARS() { return 8192 }
945
+
946
+ // Path to the per-PID session file claude TUI maintains. The file
947
+ // surfaces a `status` field (busy/idle/...) updated by claude itself
948
+ // on every state transition — `claude ps` consumes the same files.
949
+ // Polling this is the readiness signal #4040 adopted in place of the
950
+ // prior screen-scrape, which was fundamentally fragile (the TUI's
951
+ // input prompt is bordered + has status widgets rendered AFTER it,
952
+ // so any "glyph at trailing edge" regex misses, and any "glyph
953
+ // anywhere in window" regex false-positives on welcome text).
954
+ //
955
+ // Coupling worth flagging: claude only writes `status` when its
956
+ // entrypoint is `cli` (the plain `claude` binary we spawn). If a
957
+ // future refactor switches this provider to spawn via `sdk-cli` or
958
+ // a different entrypoint, the file may exist without a `status`
959
+ // field — `readSessionStatus` will return null forever, the probe
960
+ // will time out on every turn, and we degrade silently to "always
961
+ // not-ready" (the warn at the timeout site catches this at runtime).
962
+ static sessionFilePath(pid) {
963
+ return join(homedir(), '.claude', 'sessions', `${pid}.json`)
964
+ }
965
+
966
+ // Read + parse the session file. Returns the `status` string when
967
+ // the file exists and is valid JSON with a string status; otherwise
968
+ // returns null. Any error is swallowed (file not yet written, mid-
969
+ // write JSON.parse failure, transient FS race) — callers re-poll.
970
+ static readSessionStatus(filePath) {
971
+ try {
972
+ const data = JSON.parse(readFileSync(filePath, 'utf8'))
973
+ return typeof data.status === 'string' ? data.status : null
974
+ } catch {
975
+ return null
976
+ }
977
+ }
978
+
979
+ /**
980
+ * #6578: resolve the on-disk session file for THIS session, keyed on the
981
+ * deterministic `sessionId` (passed to claude as `--session-id`/`--resume`)
982
+ * rather than only the pty pid. Two breakages on current claude (2.1.186+)
983
+ * made the pid-only path unreliable:
984
+ * - MODE A: under a wrapper-shim install the real claude pid != pty pid,
985
+ * so `~/.claude/sessions/<pty-pid>.json` never appears.
986
+ * - MODE B: the session file carries NO `status` field at all, so the old
987
+ * status-only signal returned null even when the file WAS found.
988
+ * Since claude writes this file at startup with a matching `sessionId`, the
989
+ * file is resolvable by directory scan regardless of pid, and its mere
990
+ * existence (with a matching sessionId) is itself a startup-readiness signal.
991
+ *
992
+ * Resolution order:
993
+ * 1. Fast path — `sessionFilePath(ptyPid)`; verify its parsed `sessionId`
994
+ * matches (or accept it verbatim when `sessionId` is falsy, preserving
995
+ * the legacy pid-keyed behaviour for callers without a known id).
996
+ * 2. Dir-scan — read `~/.claude/sessions` and return the first `*.json`
997
+ * whose parsed `sessionId === sessionId`.
998
+ *
999
+ * Swallows ALL I/O/parse errors (returns null) — this feeds the readiness
1000
+ * path and must NEVER throw. Returns the absolute path or null.
1001
+ *
1002
+ * @param {string|null} sessionId the upstream claude conversation uuid
1003
+ * @param {number} ptyPid the pty child pid (fast-path filename)
1004
+ * @returns {string|null}
1005
+ */
1006
+ static resolveSessionFile(sessionId, ptyPid, { allowDirScan = true } = {}) {
1007
+ // Fast path: the pty-pid-named file. When we have no sessionId to match on
1008
+ // (older callers), accept it verbatim if it exists — matches the legacy
1009
+ // pid-keyed behaviour. With a sessionId, only accept it on a match. This is a
1010
+ // single stat+read and runs on every poll; the dir-scan below is the costly
1011
+ // part and the caller throttles it via `allowDirScan`.
1012
+ if (Number.isInteger(ptyPid) && ptyPid > 0) {
1013
+ const fast = this.sessionFilePath(ptyPid)
1014
+ try {
1015
+ const data = JSON.parse(readFileSync(fast, 'utf8'))
1016
+ if (!sessionId || data.sessionId === sessionId) return fast
1017
+ } catch { /* not written yet / mid-write race / wrong pid — fall through */ }
1018
+ }
1019
+ // Dir-scan fallback keyed on sessionId. Nothing to scan for without an id, and
1020
+ // callers can suppress the scan (allowDirScan=false) to throttle its per-poll
1021
+ // cost during the warmup window — the cheap fast-path above still runs.
1022
+ if (!sessionId || !allowDirScan) return null
1023
+ try {
1024
+ const dir = join(homedir(), '.claude', 'sessions')
1025
+ for (const name of readdirSync(dir)) {
1026
+ if (!name.endsWith('.json')) continue
1027
+ const full = join(dir, name)
1028
+ try {
1029
+ const data = JSON.parse(readFileSync(full, 'utf8'))
1030
+ if (data.sessionId === sessionId) return full
1031
+ } catch { /* skip unreadable/half-written sibling files */ }
1032
+ }
1033
+ } catch { /* sessions dir missing / unreadable — degrade to null */ }
1034
+ return null
1035
+ }
1036
+
1037
+ /**
1038
+ * #6578: does `filePath` still map to `sessionId`? Used to validate a cached
1039
+ * `_resolvedSessionFile` before reusing it — the file could be deleted or
1040
+ * (after a retry-FRESH fallback) now carry a different id. When `sessionId`
1041
+ * is falsy the check reduces to "the file still exists AND parses as JSON"
1042
+ * (legacy pid-keyed callers). Swallows errors → false (a missing OR
1043
+ * unreadable/corrupt file), so a stale cache forces a re-resolve.
1044
+ */
1045
+ static _sessionFileMatches(filePath, sessionId) {
1046
+ try {
1047
+ const data = JSON.parse(readFileSync(filePath, 'utf8'))
1048
+ return sessionId ? data.sessionId === sessionId : true
1049
+ } catch {
1050
+ return false
1051
+ }
1052
+ }
1053
+
1054
+ // #5431: cadence for the idle background-task re-scan. 15s mirrors the
1055
+ // BackgroundShellTracker sweep — fast enough that a task-notification
1056
+ // landing while the session is idle clears the dashboard indicator
1057
+ // promptly, slow enough to be negligible I/O (each tick reads only the
1058
+ // transcript bytes appended since the last scan).
1059
+ static get BACKGROUND_TASK_POLL_MS() { return 15_000 }
1060
+
1061
+ /**
1062
+ * #5431 — outstanding background work derived from the session transcript:
1063
+ * `{ backgroundTasks: [{ toolUseId, kind, description, startedAt }],
1064
+ * scheduledWakeup: { at, reason } | null }`, or null when no transcript
1065
+ * is resolvable (no PTY pid, no per-PID session file, parse failure — the
1066
+ * "degrade to plain ready" contract).
1067
+ *
1068
+ * The per-PID session file that drives the readiness probe carries
1069
+ * `sessionId` + `cwd`, which derive the transcript path
1070
+ * (`~/.claude/projects/<slug>/<sessionId>.jsonl`). The scanner is
1071
+ * incremental (byte offset per instance) so calling this on every
1072
+ * readiness edge costs only the new transcript tail.
1073
+ *
1074
+ * Side effect: arms/disarms the idle re-scan poll (`_backgroundTaskPollTimer`)
1075
+ * based on whether the snapshot reports outstanding work, so callers
1076
+ * (event-normalizer's `ready` / `result` handlers, ws-history replay)
1077
+ * keep the watch fresh without extra wiring. Never throws.
1078
+ */
1079
+ getBackgroundTaskSnapshot() {
1080
+ try {
1081
+ const pid = this._term && this._term.pid
1082
+ if (!Number.isInteger(pid) || pid <= 0) return null
1083
+ const transcriptPath = transcriptPathForSessionFile(ClaudeTuiSession.sessionFilePath(pid))
1084
+ if (!transcriptPath) return null
1085
+ if (!this._transcriptTaskScanner || this._transcriptTaskScanner.path !== transcriptPath) {
1086
+ this._transcriptTaskScanner = new TranscriptTaskScanner(transcriptPath, this._log || log)
1087
+ }
1088
+ const snapshot = this._transcriptTaskScanner.scan()
1089
+ this._lastBackgroundTaskKey = JSON.stringify(snapshot)
1090
+ this._refreshBackgroundTaskPoll(snapshot)
1091
+ return snapshot
1092
+ } catch (err) {
1093
+ ;(this._log || log).debug?.(`getBackgroundTaskSnapshot failed: ${err.message} — degrading to plain ready`)
1094
+ return null
1095
+ }
1096
+ }
1097
+
1098
+ /**
1099
+ * #5431 — arm the idle re-scan while work is outstanding, stop it when
1100
+ * the snapshot drains. The tick skips busy turns (the turn-end `result`
1101
+ * path recomputes anyway) and emits `background_tasks_changed` only when
1102
+ * the snapshot actually changed, which the event-normalizer maps to an
1103
+ * enriched `claude_ready` wire message (empty `backgroundTasks: []` on
1104
+ * the final tick clears the client indicator).
1105
+ */
1106
+ _refreshBackgroundTaskPoll(snapshot) {
1107
+ const outstanding = snapshot && (snapshot.backgroundTasks.length > 0 || snapshot.scheduledWakeup)
1108
+ if (!outstanding) {
1109
+ this._stopBackgroundTaskPoll()
1110
+ return
1111
+ }
1112
+ if (this._backgroundTaskPollTimer || this._destroying) return
1113
+ this._backgroundTaskPollTimer = setInterval(() => {
1114
+ try {
1115
+ if (this._destroying || this._ptyExited) {
1116
+ this._stopBackgroundTaskPoll()
1117
+ return
1118
+ }
1119
+ if (this._isBusy || !this._transcriptTaskScanner) return
1120
+ const next = this._transcriptTaskScanner.scan()
1121
+ const key = JSON.stringify(next)
1122
+ if (key === this._lastBackgroundTaskKey) return
1123
+ this._lastBackgroundTaskKey = key
1124
+ this.emit('background_tasks_changed', next)
1125
+ if (next.backgroundTasks.length === 0 && !next.scheduledWakeup) {
1126
+ this._stopBackgroundTaskPoll()
1127
+ }
1128
+ } catch (err) {
1129
+ // Never let the poll throw out of a timer tick — stop watching and
1130
+ // degrade to "no live updates until the next readiness edge".
1131
+ ;(this._log || log).debug?.(`background-task poll failed: ${err.message} — stopping poll`)
1132
+ this._stopBackgroundTaskPoll()
1133
+ }
1134
+ }, ClaudeTuiSession.BACKGROUND_TASK_POLL_MS)
1135
+ // Don't keep the event loop alive solely for the background-task watch.
1136
+ if (typeof this._backgroundTaskPollTimer.unref === 'function') this._backgroundTaskPollTimer.unref()
1137
+ }
1138
+
1139
+ /** #5431 — idempotent stop for the background-task re-scan poll. */
1140
+ _stopBackgroundTaskPoll() {
1141
+ if (this._backgroundTaskPollTimer) {
1142
+ clearInterval(this._backgroundTaskPollTimer)
1143
+ this._backgroundTaskPollTimer = null
1144
+ }
1145
+ }
1146
+
1147
+ /**
1148
+ * #5323 (WP-5.1) — boot-time sweep of orphaned hook-sink dirs under
1149
+ * `/tmp/chroxy-claude-tui/s-*`. destroy() rmSyncs a session's own sink dir,
1150
+ * but a CRASH leaks it forever, so a long-lived host accumulates one dir per
1151
+ * crashed session. Mirrors the worktree reaper's dead-pid-lock logic: each
1152
+ * dir carries an `owner.pid` (written at start()); a dir is removed only when
1153
+ * its owner is DEAD (or the pidfile is missing/garbage). A live owner — this
1154
+ * just-booted daemon, or another chroxy on the host — keeps its dirs, so the
1155
+ * sweep is safe to run unconditionally at boot (our own pid is alive, so we
1156
+ * never delete a dir we are about to use).
1157
+ * @param {object} [logger] - logger with info/warn (defaults to module log)
1158
+ * @returns {{swept:number, kept:number}}
1159
+ */
1160
+ static sweepStaleSinkDirs(logger = log) {
1161
+ const base = join(tmpdir(), 'chroxy-claude-tui')
1162
+ let entries
1163
+ try { entries = readdirSync(base) } catch { return { swept: 0, kept: 0 } }
1164
+ let swept = 0
1165
+ let kept = 0
1166
+ for (const name of entries) {
1167
+ if (!name.startsWith('s-')) continue
1168
+ const dir = join(base, name)
1169
+ let ownerPid = null
1170
+ try {
1171
+ const n = parseInt(readFileSync(join(dir, 'owner.pid'), 'utf8').trim(), 10)
1172
+ if (Number.isInteger(n) && n > 0) ownerPid = n
1173
+ } catch { /* no/garbage pidfile → orphaned, subject to the grace below */ }
1174
+ if (ownerPid !== null) {
1175
+ let alive
1176
+ try {
1177
+ process.kill(ownerPid, 0) // signal 0 = existence probe
1178
+ alive = true
1179
+ } catch (err) {
1180
+ // ESRCH → dead; EPERM → exists but not ours → still alive, keep it.
1181
+ alive = err && err.code === 'EPERM'
1182
+ }
1183
+ if (alive) { kept++; continue }
1184
+ } else {
1185
+ // #5359 review — a pidfile-less dir might be another process's sink dir
1186
+ // caught BETWEEN its mkdir and its owner.pid write (a cross-process race;
1187
+ // within one process those are synchronous). Give brand-new pidfile-less
1188
+ // dirs a grace window before reaping so we can't delete one mid-creation;
1189
+ // a genuinely orphaned dir is older than the grace and still gets swept.
1190
+ try {
1191
+ // #5332: wall-clock deliberately — compared against the filesystem
1192
+ // mtime (also wall-clock). A monotonic clock would be meaningless here.
1193
+ if (Date.now() - statSync(dir).mtimeMs < ClaudeTuiSession.SINK_SWEEP_GRACE_MS) {
1194
+ kept++
1195
+ continue
1196
+ }
1197
+ } catch { /* stat failed (dir vanished) → fall through to rmSync (no-op) */ }
1198
+ }
1199
+ try {
1200
+ rmSync(dir, { recursive: true, force: true })
1201
+ swept++
1202
+ } catch (err) {
1203
+ logger?.warn?.(`sink-dir sweep: failed to remove ${dir}: ${err.message}`)
1204
+ }
1205
+ }
1206
+ if (swept > 0) logger?.info?.(`Swept ${swept} stale claude-tui sink dir(s) from ${base} (kept ${kept} live)`)
1207
+ return { swept, kept }
1208
+ }
1209
+
1210
+ // Upper bounds on how long we'll wait for status=idle before falling
1211
+ // through (and writing anyway, with a warn). Spawn warmup is generous
1212
+ // because cold claude can take a few seconds on a fresh keychain
1213
+ // unlock; per-turn is short because between-turn idle->busy->idle
1214
+ // transitions are sub-second once the session is up.
1215
+ static get SPAWN_WARMUP_MAX_MS() { return 15_000 }
1216
+ static get TURN_PROMPT_WAIT_MAX_MS() { return 5_000 }
1217
+ // #6601: how long PTY output must be quiet before the composer counts as ready
1218
+ // when no session file resolves (current claude's INTERACTIVE TUI writes none,
1219
+ // so the file probe never resolves and the caller used to burn the full
1220
+ // warmup/turn ceiling then "write anyway"). The composer's render burst settles
1221
+ // well within this window; the idle TUI then stays silent for seconds. Validated
1222
+ // live: cold composer ready ~1.1s (vs the 15s warmup ceiling), between-turn
1223
+ // redraw sub-second (vs the 5s per-turn ceiling). Comfortably above the observed
1224
+ // intra-render gaps (~270ms) so it can't false-trigger mid-render; the
1225
+ // warmup/turn ceilings still backstop a genuinely-stuck TUI.
1226
+ static get READY_QUIESCENCE_MS() { return 400 }
1227
+ // #5317 (WP-2.3) — grace window between destroy()'s SIGTERM and the SIGKILL
1228
+ // escalation. Long enough for claude to flush its Stop hook + reap its own
1229
+ // tool children on a clean SIGTERM, short enough that a hung claude (or a
1230
+ // child holding the PTY open) can't orphan past it.
1231
+ static get DESTROY_GRACE_MS() { return 3_000 }
1232
+ // #5359 review — grace window before the boot sweep reaps a PIDFILE-LESS sink
1233
+ // dir, so a dir caught between another process's mkdir and its owner.pid write
1234
+ // (a cross-process race) isn't deleted mid-creation. Dirs with a (dead) pid
1235
+ // are reaped immediately; only the pidfile-less ambiguous case waits this out.
1236
+ static get SINK_SWEEP_GRACE_MS() { return 60_000 }
1237
+ // Wedge instrumentation (#4678 follow-up): hook-poll loop emits a
1238
+ // heartbeat log line every HOOK_HEARTBEAT_MS of silent waiting (no
1239
+ // stop-hook yet). Sized so healthy short turns (<5s end-to-end) emit
1240
+ // zero heartbeats but wedges produce a 5s-cadence trail of state.
1241
+ static get HOOK_HEARTBEAT_MS() { return 5_000 }
1242
+ // #6178: per-call timeout for the hot-path hook-drain fs ops (readdir/readFile/
1243
+ // unlink). A healthy sink read is sub-ms; this generous 2s bound only trips on
1244
+ // a genuinely stuck mount (FUSE/NFS freeze), letting the poll loop re-check its
1245
+ // hard-timeout guard rather than awaiting a frozen fs forever.
1246
+ static get HOOK_FS_TIMEOUT_MS() { return 2_000 }
1247
+
1248
+ get sessionId() {
1249
+ return this._sessionId
1250
+ }
1251
+
1252
+ // #5307 (WP-0.1) — SessionManager.serializeState reads `resumeSessionId` off
1253
+ // the session and persists it as `sdkSessionId`; restoreState passes it back
1254
+ // into the constructor so the conversation resumes. Without this getter the
1255
+ // read was `undefined` → persisted null → every restart started a brand-new
1256
+ // claude conversation while the dashboard replayed stale history (the silent
1257
+ // context-amnesia bug, audit TUI-AUDIT-001). Mirrors cli-session.js:386.
1258
+ get resumeSessionId() {
1259
+ return this._sessionId
1260
+ }
1261
+
1262
+ async start() {
1263
+ // Pre-flight: ensure cwd is trusted so the dialog doesn't block PTY spawns.
1264
+ try {
1265
+ ensureCwdTrusted(this.cwd)
1266
+ } catch (err) {
1267
+ log.warn(`trust pre-write failed (continuing): ${err.message}`)
1268
+ }
1269
+
1270
+ // Create per-session sink dir for hook payloads + settings.json.
1271
+ const base = join(tmpdir(), 'chroxy-claude-tui')
1272
+ mkdirSync(base, { recursive: true })
1273
+ this._sinkDir = join(base, `s-${randomUUID()}`)
1274
+ mkdirSync(this._sinkDir, { recursive: true })
1275
+ // #5323 (WP-5.1) — stamp the owning pid so the boot-time sweep
1276
+ // (sweepStaleSinkDirs) can tell a live daemon's sink dir from one orphaned
1277
+ // by a prior crash. Best-effort: a missing pidfile just makes the dir
1278
+ // sweep-eligible, which is the safe default for an orphan.
1279
+ try { writeFileSync(join(this._sinkDir, 'owner.pid'), String(process.pid)) } catch { /* best effort */ }
1280
+
1281
+ // Generate the upstream session uuid here so the JSONL path is
1282
+ // predictable + so claude resumes the same conversation across turns.
1283
+ // #5307 (WP-0.1) — only mint a fresh uuid when this isn't a restore. When
1284
+ // the constructor seeded `_sessionId` from a persisted resume id, keep it
1285
+ // so the spawn below can `--resume <id>` the same conversation.
1286
+ if (!this._sessionId) this._sessionId = randomUUID()
1287
+ // #4792: now that the session id exists, bind the per-instance logger
1288
+ // so subsequent log lines carry sessionId and route correctly through
1289
+ // the WsServer log fan-out (#4787). Anything that logs before this
1290
+ // point uses the module-level `log` (unscoped) and only reaches
1291
+ // unbound dashboard clients — that is the desired behaviour for
1292
+ // pre-start setup failures.
1293
+ this._log = loggerForSession('claude-tui-session', this._sessionId)
1294
+
1295
+ // #4044: skipPermissions wins over port — when the user opts in to
1296
+ // unmediated TUI behaviour, the hook installation + sidecar write must
1297
+ // both be elided. Otherwise we'd run two competing permission systems
1298
+ // (chroxy's hook + claude's own --dangerously-skip-permissions flag).
1299
+ const permissionsEnabled = !!(this._port && this._hookSecret) && !this.skipPermissions
1300
+ this._settingsPath = writeHookSettings(this._sinkDir, { permissionsEnabled })
1301
+
1302
+ // #4013: write the initial permission mode to a sidecar file so the
1303
+ // hook script can pick up mid-session changes (env vars on the
1304
+ // running PTY can't be mutated from outside). The file is the source
1305
+ // of truth once start() returns; the CHROXY_PERMISSION_MODE env var
1306
+ // only matters as a fallback when the file is unreadable. If the
1307
+ // initial write itself fails (disk full, permissions, etc.) we drop
1308
+ // the sidecar and continue with env-var-only mode — losing the
1309
+ // ability to hot-swap is acceptable; failing session start is not.
1310
+ if (permissionsEnabled) {
1311
+ const sidecarPath = join(this._sinkDir, 'permission-mode')
1312
+ try {
1313
+ // Atomic from the first write too (#5334): a respawn / hot-restart can
1314
+ // rewrite this sidecar while a hook from a still-draining turn reads it.
1315
+ this._writePermissionModeSidecarAtomic(sidecarPath, this.permissionMode || 'approve')
1316
+ this._permissionModeFile = sidecarPath
1317
+ } catch (err) {
1318
+ log.warn(`initial permission-mode sidecar write failed (${err.message}) — falling back to env-var-only mode; mid-session permission switch will not take effect`)
1319
+ this._permissionModeFile = null
1320
+ }
1321
+ }
1322
+
1323
+ // Spawn node-pty + wait for TUI warmup. Extracted so tests can stub
1324
+ // the prototype method instead of mocking node-pty at the module level.
1325
+ await this._spawnPty(permissionsEnabled)
1326
+
1327
+ // #5316 (WP-2.2) — never resolve start() (and never emit `ready` / set
1328
+ // `_processReady`) when the PTY failed to come up. Before this, start()
1329
+ // emitted an `error` and *returned*, so SessionManager's
1330
+ // `session.start().catch(...)` guard never fired and the dead session sat in
1331
+ // the list as an input-rejecting zombie. Worse, the two `_spawnPty`
1332
+ // early-return failure paths (node-pty import fail, spawn throw) emit `error`
1333
+ // and return WITHOUT setting `_ptyExited` and WITHOUT a live `_term`, so the
1334
+ // old `if (this._ptyExited)` guard missed them entirely and fell straight
1335
+ // through to `emit('ready')` — marking a session with no process alive
1336
+ // (the audit's "never mark a dead PTY ready"). Cover every no-live-PTY shape
1337
+ // by rejecting, so SessionManager surfaces the failure (fresh → cleanup;
1338
+ // restore → preserve history, mark retryable).
1339
+ if (this._destroying) {
1340
+ // destroy() raced the spawn; `_spawnPty`'s post-spawn guard already killed
1341
+ // the fresh PTY and nulled `_term`. This is a benign abort, not a start
1342
+ // failure to surface — resolve quietly without emitting `ready`.
1343
+ return
1344
+ }
1345
+ // #5321 (WP-4.1) — surface a logged-out / expired subscription login as a
1346
+ // clear AUTH_REQUIRED error (with `claude login` guidance) BEFORE the generic
1347
+ // exit/timeout paths, so the operator gets actionable guidance instead of a
1348
+ // bare "PTY exited" or a 90s silent hang. Covers both shapes: claude printed
1349
+ // its login banner and sat there (_authFailureDetected, latched in
1350
+ // _spawnPty's warmup scan) AND claude printed it then exited (re-scan the
1351
+ // tail here, since the warmup loop returns on _ptyExited before scanning).
1352
+ if (this._authFailureDetected || this._scanOutputForAuthFailure()) {
1353
+ this.emit('error', { code: AUTH_REQUIRED_CODE, message: AUTH_REQUIRED_MESSAGE })
1354
+ const err = new Error(AUTH_REQUIRED_MESSAGE)
1355
+ err.code = AUTH_REQUIRED_CODE
1356
+ throw err
1357
+ }
1358
+ if (this._ptyExited) {
1359
+ // #6576 (Option A) — the dying warmup already went through _onPtyGone →
1360
+ // _scheduleRespawn. If claude's own tail CONFIRMED the resume id is unknown,
1361
+ // that path armed a retry-FRESH (`_freshRetryPending`) + scheduled a respawn
1362
+ // on a brand-new conversation. Do NOT reject start() in that case: a restore
1363
+ // start() rejection makes SessionManager (`_handleAsyncStartFailure`) tear
1364
+ // down the provider, which cancels the scheduled respawn — the exact
1365
+ // restore-on-restart wedge #6576 is about (the background retry never runs).
1366
+ // Return quietly instead; the scheduled respawn spawns the fresh conversation
1367
+ // and emits `ready` when it warms up, so the session recovers in place with no
1368
+ // `session_restore_failed` and no teardown. A genuinely unrecoverable death
1369
+ // (no retry armed) still rejects below.
1370
+ if (this._freshRetryPending) {
1371
+ return
1372
+ }
1373
+ const message = `claude PTY exited during warmup (code=${this._ptyExitInfo?.exitCode ?? 'unknown'})`
1374
+ this.emit('error', { message })
1375
+ throw new Error(message)
1376
+ }
1377
+ if (!this._term) {
1378
+ // `_spawnPty` hit an early-return failure path (node-pty unavailable /
1379
+ // spawn throw). It already emitted a descriptive `error`; reject so the
1380
+ // failure isn't swallowed.
1381
+ throw new Error('claude PTY failed to spawn (no live process after _spawnPty)')
1382
+ }
1383
+
1384
+ this._processReady = true
1385
+ this.emit('ready', { sessionId: this._sessionId, model: this.model, tools: [] })
1386
+ }
1387
+
1388
+ /**
1389
+ * #5311 (WP-1.1) — single idempotent teardown for "the PTY is gone", reached
1390
+ * from onExit (process exit) AND from the 'close'/'error' socket events that
1391
+ * fire on a node-pty fault with no process-exit callback. Resets turn state so
1392
+ * the next sendMessage() sees a clean idle (it still rejects with "no longer
1393
+ * alive", but isn't locked by a stale _isBusy from the interrupted turn,
1394
+ * #3924) and emits ONE session-scoped error. Guards on `_ptyExited` so the
1395
+ * several wired events collapse to a single teardown + error emit.
1396
+ *
1397
+ * @param {object|null} info — node-pty exit info ({exitCode, signal}) when known
1398
+ * @param {string} source — diagnostic label for the log line
1399
+ */
1400
+ _onPtyGone(info, source) {
1401
+ // Always capture the most specific exit info, even on a repeat event.
1402
+ if (info) this._ptyExitInfo = info
1403
+ if (this._ptyExited) return
1404
+ this._ptyExited = true
1405
+ this._processReady = false
1406
+ // #5317 (WP-2.3) — the process is confirmed gone (onExit/close/error fired),
1407
+ // so cancel any pending SIGKILL escalation destroy() armed. Doing this here
1408
+ // (rather than via a timer-only check) is what closes the pid-reuse window:
1409
+ // the escalation only fires when onExit NEVER arrives, i.e. the process is
1410
+ // genuinely still alive, so the captured pid can't have been recycled.
1411
+ if (this._killTimer) { clearTimeout(this._killTimer); this._killTimer = null }
1412
+ // #5835: drop any pending live-mirror flush so a dead PTY's leftover frame
1413
+ // never broadcasts and the timer doesn't leak.
1414
+ this._clearTerminalMirror()
1415
+ // Reset turn state so the next sendMessage() sees a clean idle.
1416
+ const hadActiveTurn = this._activeTurn !== null
1417
+ // #4022: clean up the in-flight turn's attachment dir BEFORE nulling
1418
+ // _activeTurn, otherwise sendMessage's poll loop reaches _finishTurnError
1419
+ // with activeTurn=null and the helper no-ops → dir leaks until destroy().
1420
+ // The cleanup is idempotent (rmSync force:true) so a later call is fine.
1421
+ this._cleanupTurnAttachments(this._activeTurn)
1422
+ this._activeTurn = null
1423
+ this._isBusy = false
1424
+ this._currentMessageId = null
1425
+ // #4307: the PTY is gone, so the ephemeral intra-turn run_in_background
1426
+ // tool_use→command map can never be resolved by a result on this PTY — drop
1427
+ // it (matches _clearTurnEndState / base _clearMessageState). On respawn the
1428
+ // next turn starts clean; on destroy _clearMessageState would clear it anyway.
1429
+ this._pendingBackgroundCommands.clear()
1430
+ // #5777 (#5788): cancel a pending first-turn submit nudge directly here.
1431
+ // _onPtyGone is the one teardown path that does NOT route through
1432
+ // _clearFirstOutputWatchdog, so without this an armed nudge would only be
1433
+ // saved by the tick's !_isBusy guard — fragile. Clear before the
1434
+ // _destroying early-return so it runs on both the destroy and respawn paths.
1435
+ this._clearFirstTurnSubmitNudge()
1436
+ // #5798: _onPtyGone does NOT route through _clearFirstOutputWatchdog, so
1437
+ // close the reinject stop-and-wait window explicitly here (before the
1438
+ // _destroying early-return, so it runs on both the destroy and respawn
1439
+ // paths) — a dead/respawning PTY can't legitimately emit the reinjected
1440
+ // turn, and a stale marker must not leak into a later turn. Observability-only.
1441
+ this._reinjectStopWaitWatch = null
1442
+ if (this._destroying) return
1443
+ // #5311 review — the socket 'close'/'error' paths have no exit info, so
1444
+ // render a clear "unknown" instead of a bare "code=undefined". The
1445
+ // "Claude PTY exited" prefix is preserved (clients/log scrapers key on it).
1446
+ const code = this._ptyExitInfo?.exitCode
1447
+ const codeStr = (code === undefined || code === null) ? 'unknown' : code
1448
+ log.warn(`claude PTY gone (${source}) (code=${codeStr} signal=${this._ptyExitInfo?.signal ?? 'unknown'})`)
1449
+ // Suppress the generic error when a turn was in flight — sendMessage's poll
1450
+ // loop emits a more specific "PTY exited mid-turn" error instead, so the
1451
+ // dashboard sees one root cause not two.
1452
+ if (!hadActiveTurn) {
1453
+ // #5321 (WP-4.1) — if the PTY died with a logged-out / expired-login
1454
+ // banner in its tail, surface AUTH_REQUIRED (actionable) rather than a
1455
+ // bare exit code. The respawn below will keep failing the same way until
1456
+ // the operator re-logs in, so the categorized error is what matters.
1457
+ if (this._scanOutputForAuthFailure()) {
1458
+ this.emit('error', { code: AUTH_REQUIRED_CODE, message: AUTH_REQUIRED_MESSAGE })
1459
+ } else {
1460
+ const tail = this._outputTailDiagnostic()
1461
+ const base = `Claude PTY exited (code=${codeStr})`
1462
+ this.emit('error', { message: tail ? `${base}\nTUI output tail:\n${tail}` : base })
1463
+ }
1464
+ }
1465
+ // #5315 (WP-2.1) — an UNEXPECTED PTY death (we already returned above when
1466
+ // `_destroying`, so this is never a deliberate teardown). Try to bring the
1467
+ // session back instead of leaving a zombie. The error(s) above still fire
1468
+ // so the dashboard sees the death; the respawn is the recovery layer on top.
1469
+ this._scheduleRespawn()
1470
+ }
1471
+
1472
+ /**
1473
+ * #5315 (WP-2.1) — schedule a bounded PTY respawn with exponential backoff,
1474
+ * mirroring CliSession._scheduleRespawn (cli-session.js:556). Backoff is
1475
+ * [1s,2s,4s,8s,15s] and caps at 5 attempts (a session whose dying PTY tail
1476
+ * confirms the resume id is unknown gets ONE extra drop-and-retry-FRESH
1477
+ * attempt at the cap, #5348/#5417); on exhaustion it
1478
+ * emits a categorized `error` AND a `respawn_exhausted` event so
1479
+ * SessionManager drops the session from its list (no input-rejecting zombie
1480
+ * tab — the audit AC).
1481
+ * Guarded on `_destroying` / `_respawning` / `_respawnScheduled` so the
1482
+ * several wired PTY-fault events (onExit/close/error) can't stack timers.
1483
+ */
1484
+ _scheduleRespawn() {
1485
+ if (this._destroying) return
1486
+ if (this._respawning) return
1487
+ if (this._respawnScheduled) return
1488
+
1489
+ // #5349: rolling-window cap, checked BEFORE _respawnCount so a session that
1490
+ // keeps surviving warmup (resetting _respawnCount) still gives up once it
1491
+ // flaps past the window cap.
1492
+ if (!this._respawnRateLimiter.record()) {
1493
+ const { maxPerWindow, windowMs } = this._respawnRateLimiter
1494
+ ;(this._log || log).error(`PTY respawn rate cap reached (>${maxPerWindow} respawns in ${Math.round(windowMs / 60000)}min), giving up — session is flapping`)
1495
+ const tail = this._outputTailDiagnostic()
1496
+ const base = `Claude PTY is flapping — exceeded ${maxPerWindow} respawns in ${Math.round(windowMs / 60000)} minutes`
1497
+ this.emit('error', { code: 'pty_respawn_exhausted', message: tail ? `${base}\nTUI output tail:\n${tail}` : base })
1498
+ this.emit('respawn_exhausted', { reason: 'pty_respawn_rate_capped' })
1499
+ return
1500
+ }
1501
+
1502
+ this._respawnCount++
1503
+ // #6576 — fire the retry-FRESH as soon as the dying tail CONFIRMS the resume id
1504
+ // is unknown (the `_scanOutputForUnknownResume()` disjunct), not only at the
1505
+ // 5-respawn cap. Retrying a `--resume` claude has ALREADY rejected is pointless,
1506
+ // and the cap-gated ~30s of backoff exceeds a client's readiness timeout — a
1507
+ // ghost resume otherwise broadcast `session_restore_failed` and wedged every
1508
+ // real client into a reconnect loop (daemon restarts also reset `_respawnCount`,
1509
+ // so the cap was never reached). The one-shot `_didFallbackFromUnknownResume`
1510
+ // latch (the `|| this._didFallbackFromUnknownResume` disjunct) keeps a fresh
1511
+ // attempt that ALSO dies routing to exhaustion instead of looping; the
1512
+ // `_respawnCount > 5` disjunct still governs UNCONFIRMED crash loops (#5417) so a
1513
+ // real conversation is never abandoned without claude's own rejection.
1514
+ if (this._scanOutputForUnknownResume() || this._didFallbackFromUnknownResume || this._respawnCount > 5) {
1515
+ // #5348 — drop-and-retry-FRESH fallback. A FRESH session (spawned with
1516
+ // `--session-id`) that died before claude persisted its conversation
1517
+ // makes every `--resume` respawn doomed: claude can't find the
1518
+ // conversation and exits during warmup. Reaching this cap means 5
1519
+ // consecutive respawns never survived warmup — spend ONE extra attempt
1520
+ // on a brand-new conversation id before giving up.
1521
+ //
1522
+ // #5417 — eligibility is the PTY-tail CLASSIFICATION, not the seeding
1523
+ // origin. The cap alone proves 5 respawns died during warmup, NOT that
1524
+ // the conversation is missing: a crash loop with an unrelated cause
1525
+ // (OOM, broken install, claude crashing while loading a large-but-
1526
+ // present conversation file) used to trigger the #5348 blunt fallback
1527
+ // on originally-fresh sessions and abandon real context a fresh spawn
1528
+ // may not even fix. Requiring claude's own resume rejection in the
1529
+ // dying output ("No conversation found with session ID …" — the same
1530
+ // pinned patterns CliSession's #4929 stderr classifier uses; the PTY
1531
+ // merges stdout+stderr so it lands in _outputTail, which _spawnPty
1532
+ // resets per attempt so the match describes the LAST death) confines
1533
+ // the fallback to the failure it was designed for AND safely extends
1534
+ // it to RESTORED sessions (CliSession parity): when claude confirms
1535
+ // the persisted conversation is gone (wiped ~/.claude/projects/, state
1536
+ // file from another machine), a loud fresh retry beats burning to a
1537
+ // destroyed session. No match → exhaustion is the honest outcome for
1538
+ // both seeding origins (the TUI-AUDIT-001 amnesia class stays closed:
1539
+ // an UNCONFIRMED cause never abandons a conversation id).
1540
+ if (this._scanOutputForUnknownResume() && !this._didFallbackFromUnknownResume) {
1541
+ this._didFallbackFromUnknownResume = true
1542
+ this._freshRetryPending = true
1543
+ const abandonedId = this._sessionId
1544
+ // Kept for the terminal resume_unknown_exhausted emit below — by the
1545
+ // time the fallback attempt fails, _sessionId is already the new uuid.
1546
+ this._abandonedResumeId = abandonedId
1547
+ this._sessionId = randomUUID()
1548
+ this._resumedFromPersisted = false
1549
+ // Rebind the session-scoped logger to the new conversation uuid so
1550
+ // subsequent lines route under the id the dashboard will see on the
1551
+ // re-emitted `ready` (mirrors cli-session.js rebinding on system.init).
1552
+ this._log = loggerForSession('claude-tui-session', this._sessionId)
1553
+ ;(this._log || log).warn(
1554
+ `all --resume respawns died during warmup and the PTY tail confirms claude does not know the ` +
1555
+ `conversation id (attemptedResumeId=${abandonedId}) — retrying once with a fresh --session-id`,
1556
+ )
1557
+ // Loud one-shot signal (same code as cli-session.js) so the dashboard
1558
+ // can render "starting fresh" instead of a generic crash toast.
1559
+ this.emit('error', {
1560
+ code: 'resume_unknown',
1561
+ message: this._seededFromPersisted
1562
+ ? 'Previous Claude conversation could not be resumed (claude reports the persisted conversation id ' +
1563
+ 'as unknown on this machine — it may have been wiped from ~/.claude/projects/). Retrying once with ' +
1564
+ 'a fresh conversation; the model will not see the earlier transcript.'
1565
+ : 'Previous Claude conversation could not be resumed (claude reports the conversation id as unknown — ' +
1566
+ 'it may never have been persisted before the PTY died, or it was removed from this machine). ' +
1567
+ 'Retrying once with a fresh conversation; the model will not see any earlier transcript.',
1568
+ attemptedResumeId: abandonedId,
1569
+ })
1570
+ // Fall through to the scheduling below — this IS the extra attempt.
1571
+ } else {
1572
+ // #6576 — with the early retry-FRESH firing, this else can be reached via
1573
+ // the `_didFallbackFromUnknownResume` latch (fresh fallback also died) BEFORE
1574
+ // the 5-respawn cap, so log the real reason instead of a misleading
1575
+ // "Max PTY respawn attempts reached" when the count never hit the cap.
1576
+ ;(this._log || log).error(this._didFallbackFromUnknownResume
1577
+ ? `Fresh-conversation retry also died during warmup after the resume id was rejected — giving up (${this._respawnCount - 1} attempt(s))`
1578
+ : `Max PTY respawn attempts reached (${this._respawnCount - 1}), giving up`)
1579
+ const tail = this._outputTailDiagnostic()
1580
+ // When the retry-FRESH fallback itself failed, escalate with the same
1581
+ // terminal code CliSession uses (resume_unknown_exhausted, #5004) —
1582
+ // event-normalizer forwards it + attemptedResumeId, and the dashboard/
1583
+ // app already render the distinct "auto-recovery exhausted" affordance.
1584
+ // Otherwise keep the provider's own distinct code so the dashboard can
1585
+ // render a terminal "give up" state rather than a recoverable crash
1586
+ // toast.
1587
+ const failedFallback = this._didFallbackFromUnknownResume
1588
+ const code = failedFallback ? 'resume_unknown_exhausted' : 'pty_respawn_exhausted'
1589
+ const base = failedFallback
1590
+ ? 'Auto-recovery exhausted: every --resume respawn died during warmup and a fresh-conversation retry also failed. Start a new session manually to continue.'
1591
+ : `Claude PTY failed to stay alive after ${this._respawnCount - 1} respawn attempts`
1592
+ const errEnvelope = { code, message: tail ? `${base}\nTUI output tail:\n${tail}` : base }
1593
+ if (failedFallback && this._abandonedResumeId) errEnvelope.attemptedResumeId = this._abandonedResumeId
1594
+ this.emit('error', errEnvelope)
1595
+ // SessionManager listens for this and calls destroySession() so the
1596
+ // session leaves the list cleanly (see _wireSessionEvents).
1597
+ this.emit('respawn_exhausted', { reason: code, attempts: this._respawnCount - 1 })
1598
+ return
1599
+ }
1600
+ }
1601
+
1602
+ const delays = [1000, 2000, 4000, 8000, 15000]
1603
+ const delay = delays[Math.min(this._respawnCount - 1, delays.length - 1)]
1604
+ // The #5348 fallback attempt is the one-past-the-cap extra — label it
1605
+ // honestly instead of logging a nonsensical "attempt 6/5".
1606
+ ;(this._log || log).info(this._freshRetryPending
1607
+ ? `Respawning claude PTY in ${delay}ms (fresh-conversation retry after ${this._respawnCount - 1} failed resume attempts)`
1608
+ : `Respawning claude PTY in ${delay}ms (attempt ${this._respawnCount}/5)`)
1609
+
1610
+ this._respawnScheduled = true
1611
+ this._respawnTimer = setTimeout(() => {
1612
+ this._respawnTimer = null
1613
+ this._respawnScheduled = false
1614
+ if (this._destroying) return
1615
+ this._respawnPty()
1616
+ }, delay)
1617
+ }
1618
+
1619
+ /**
1620
+ * #5315 (WP-2.1) — re-spawn the persistent PTY in place after an unexpected
1621
+ * death. Reuses the existing sink dir / settings.json / hook secret (does NOT
1622
+ * re-create them) by re-invoking `_spawnPty()` with the same
1623
+ * `permissionsEnabled` decision start() made.
1624
+ *
1625
+ * Two subtleties that are load-bearing:
1626
+ * 1. Guard reset — `_onPtyGone` latched `_ptyExited=true` (plus
1627
+ * `_ptyExitInfo` / `_processReady=false`). Without resetting these,
1628
+ * `_onPtyGone`'s `if (this._ptyExited) return` guard stays latched and
1629
+ * the NEXT death would no-op instead of tearing down / respawning again
1630
+ * (the #5315 #1 footgun). Reset them before re-spawning.
1631
+ * 2. Conversation continuity — the upstream claude conversation already
1632
+ * exists from the prior PTY run and `_sessionId` is preserved, so the
1633
+ * respawn MUST use `--resume <id>`, NOT `--session-id` (claude rejects a
1634
+ * reused session-id as "already in use"). Set `_resumedFromPersisted`
1635
+ * so `_spawnPty`'s idArgs picks `--resume`; do NOT mint a new id.
1636
+ */
1637
+ async _respawnPty() {
1638
+ if (this._destroying) return
1639
+ this._respawning = true
1640
+ // (1) reset the teardown latches so a future death re-triggers _onPtyGone.
1641
+ this._ptyExited = false
1642
+ this._ptyExitInfo = null
1643
+ this._processReady = false
1644
+ // #5321 (WP-4.1) — clear the auth latch so the respawn's own warmup scan
1645
+ // re-evaluates fresh (a re-login between attempts must let the session
1646
+ // recover; a still-logged-out respawn re-sets it via _spawnPty's scan).
1647
+ this._authFailureDetected = false
1648
+ // (2) continue the SAME upstream conversation via --resume — UNLESS
1649
+ // #5348's retry-FRESH fallback armed this attempt: then `_sessionId` is a
1650
+ // freshly-minted uuid claude has never seen, so the spawn must use
1651
+ // `--session-id` (forcing `--resume` here would re-doom the attempt).
1652
+ if (this._freshRetryPending) {
1653
+ this._freshRetryPending = false
1654
+ } else {
1655
+ this._resumedFromPersisted = true
1656
+ }
1657
+ // Recompute permissionsEnabled exactly as start() did — the sink dir, hook
1658
+ // secret and settings.json are all still in place from the original start,
1659
+ // so we re-use them rather than re-deriving (no re-mint, no re-create).
1660
+ const permissionsEnabled = !!(this._port && this._hookSecret) && !this.skipPermissions
1661
+ try {
1662
+ await this._spawnPty(permissionsEnabled)
1663
+ } catch (err) {
1664
+ ;(this._log || log).error(`PTY respawn threw: ${err?.message || err}`)
1665
+ this._respawning = false
1666
+ // Treat a throw like a death: schedule the next attempt (respects the cap).
1667
+ this._scheduleRespawn()
1668
+ return
1669
+ }
1670
+ this._respawning = false
1671
+ if (this._destroying) {
1672
+ // #5315 review (MAJOR-1) — destroy() raced our respawn. _spawnPty's own
1673
+ // post-spawn guard kills a PTY it managed to assign, but cover it here too
1674
+ // (and so a stubbed _spawnPty in tests can't leave a live _term): kill any
1675
+ // PTY that exists and bail without emitting `ready`.
1676
+ try { this._term?.kill?.('SIGTERM') } catch {}
1677
+ this._term = null
1678
+ return
1679
+ }
1680
+ // #5315 review (MINOR-1) — _spawnPty has early-return paths (node-pty import
1681
+ // fail, spawn throw) that emit('error') and return WITHOUT setting
1682
+ // _ptyExited and without assigning a live _term. Treat "no live PTY" the
1683
+ // same as a death so we don't falsely emit `ready` + mark _processReady on a
1684
+ // dead session; reschedule (respects the cap).
1685
+ if (!this._term || this._ptyExited) {
1686
+ // Respawn warmup failed: the PTY died again during _spawnPty. _onPtyGone
1687
+ // DID fire (it set _ptyExited), but its _scheduleRespawn was suppressed
1688
+ // by the `_respawning` guard that was true for the whole _spawnPty await.
1689
+ // Now that we've cleared `_respawning`, schedule the next attempt here so
1690
+ // the backoff chain continues toward the cap (it won't loop forever —
1691
+ // _scheduleRespawn enforces the 5-attempt limit).
1692
+ this._scheduleRespawn()
1693
+ return
1694
+ }
1695
+ // #5321 (WP-4.1) — the respawn's warmup classified a logged-out / expired
1696
+ // login (live PTY sitting at the login banner, never reaching ready). Do NOT
1697
+ // emit `ready` on an unauthenticated session — surface AUTH_REQUIRED and stop
1698
+ // respawning: every further attempt re-resumes into the same logged-out state
1699
+ // until the operator runs `claude login`, so retrying is futile. (start() is
1700
+ // not on the respawn path, so this is the only place to catch it here.)
1701
+ if (this._authFailureDetected) {
1702
+ ;(this._log || log).warn(`claude TUI respawn warmup classified ${AUTH_REQUIRED_CODE} — surfacing instead of marking ready`)
1703
+ this.emit('error', { code: AUTH_REQUIRED_CODE, message: AUTH_REQUIRED_MESSAGE })
1704
+ this.emit('respawn_exhausted', { reason: AUTH_REQUIRED_CODE, attempts: this._respawnCount })
1705
+ return
1706
+ }
1707
+ // Respawn succeeded and stayed alive through warmup. Reset the count so a
1708
+ // FUTURE unrelated death gets the full retry budget again (matches how
1709
+ // CliSession resets _respawnCount on system.init, cli-session.js:888), mark
1710
+ // ready, and re-emit `ready` so the dashboard knows the session recovered.
1711
+ this._respawnCount = 0
1712
+ // #5348 — release the one-shot retry-FRESH latch on a warmup that survived
1713
+ // (mirrors cli-session.js releasing it on system.init): a FUTURE
1714
+ // doomed-resume window may fall back again; the #5349 rolling rate cap
1715
+ // bounds any flapping alternation.
1716
+ this._didFallbackFromUnknownResume = false
1717
+ this._processReady = true
1718
+ this.emit('ready', { sessionId: this._sessionId, model: this.model, tools: [] })
1719
+ }
1720
+
1721
+ /**
1722
+ * Build the env object for the spawned claude TUI PTY.
1723
+ *
1724
+ * Unlike the claude-cli path (which goes through buildSpawnEnv('claude')),
1725
+ * the TUI inherits the operator's full shell env (denylist semantics) so
1726
+ * Claude Code tools see the user's environment — but two classes of secret
1727
+ * are stripped:
1728
+ * - ANTHROPIC_API_KEY: would pin auth to API billing and defeat the whole
1729
+ * point of this subscription/OAuth provider.
1730
+ * - CHROXY_SECRET_DENYLIST (API_TOKEN): the full-authority primary bearer
1731
+ * token must never reach a tool/MCP/subagent the TUI runs (#6311). The
1732
+ * scoped per-session CHROXY_HOOK_SECRET below is the only chroxy secret
1733
+ * the child legitimately needs.
1734
+ *
1735
+ * Extracted from _spawnPty so the secret-stripping invariant is unit-testable
1736
+ * without spawning a real PTY.
1737
+ *
1738
+ * @param {boolean} permissionsEnabled
1739
+ * @returns {Record<string, string>}
1740
+ */
1741
+ _buildPtyEnv(permissionsEnabled) {
1742
+ const env = { ...process.env }
1743
+ // The TUI path must route via OAuth subscription. ANTHROPIC_API_KEY would
1744
+ // pin auth to API and defeat the whole point of this provider.
1745
+ delete env.ANTHROPIC_API_KEY
1746
+ // #6311: strip chroxy-owned daemon secrets (the primary API_TOKEN) so a
1747
+ // tool/MCP/subagent/shell the TUI runs can't read them from process.env.
1748
+ for (const key of CHROXY_SECRET_DENYLIST) {
1749
+ delete env[key]
1750
+ }
1751
+ env.TERM = 'xterm-256color'
1752
+
1753
+ // permission-hook.sh reads these to phone home to /permission on the
1754
+ // chroxy HTTP server with the per-session secret.
1755
+ if (permissionsEnabled) {
1756
+ env.CHROXY_PORT = String(this._port)
1757
+ env.CHROXY_HOOK_SECRET = this._hookSecret
1758
+ env.CHROXY_PERMISSION_MODE = this.permissionMode || 'approve'
1759
+ // #4013: hook reads sidecar first (per-tool-call, picks up
1760
+ // mid-session changes from setPermissionMode), falls back to the
1761
+ // env var above when the file is missing/unreadable.
1762
+ if (this._permissionModeFile) {
1763
+ env.CHROXY_PERMISSION_MODE_FILE = this._permissionModeFile
1764
+ }
1765
+ // #4668 (short-term): per-session sink directory so the hook can
1766
+ // place its sibling-AskUserQuestion lockfile somewhere that's
1767
+ // automatically cleaned up by destroy()'s rmSync of this._sinkDir.
1768
+ // The hook silently no-ops the sibling-deny check when this env
1769
+ // var is absent, so removing it again later is safe. Set under
1770
+ // permissionsEnabled because the hook itself only runs in that
1771
+ // mode — outside it, claude TUI takes its own permission path and
1772
+ // none of CHROXY_* env vars are read.
1773
+ env.CHROXY_SINK_DIR = this._sinkDir
1774
+ }
1775
+ return env
1776
+ }
1777
+
1778
+ /**
1779
+ * Spawn the persistent PTY under node-pty + wait for the TUI to render.
1780
+ * Sets `this._term`, wires onData/onExit handlers, then sleeps for
1781
+ * WARMUP_MS so the TUI's input prompt is ready before the first
1782
+ * sendMessage() writes. Tests stub this method on the prototype to
1783
+ * skip the real spawn.
1784
+ *
1785
+ * @param {boolean} permissionsEnabled
1786
+ */
1787
+ async _spawnPty(permissionsEnabled) {
1788
+ let ptyMod
1789
+ // Test seam (#6417): a test may inject a capturing node-pty stand-in so the
1790
+ // REAL arg-builder below runs against it — catching drift on the actual spawn
1791
+ // argv (e.g. a dropped --no-chrome), which a wholesale _spawnPty mock cannot.
1792
+ // Undefined in production → the genuine dynamic import runs unchanged.
1793
+ if (this._ptyModOverride) {
1794
+ ptyMod = this._ptyModOverride
1795
+ } else {
1796
+ try {
1797
+ ptyMod = await import('node-pty')
1798
+ } catch (err) {
1799
+ this.emit('error', { message: `node-pty unavailable: ${err.message}` })
1800
+ return
1801
+ }
1802
+ }
1803
+
1804
+ const cwdReal = realpathSync(this.cwd)
1805
+ const env = this._buildPtyEnv(permissionsEnabled)
1806
+
1807
+ // #5307 (WP-0.1) — on a fresh session, set the conversation uuid with
1808
+ // `--session-id <id>` (claude requires a brand-new uuid here). On restore,
1809
+ // the same uuid is now claude's existing conversation id, so resume it with
1810
+ // `--resume <id>` instead — reusing `--session-id` with an already-used id
1811
+ // is rejected by claude. Falls back to the fresh path whenever the session
1812
+ // wasn't seeded from a persisted id. Resume-failure handling (claude can't
1813
+ // find the conversation, e.g. cleared ~/.claude history) surfaces via the
1814
+ // warmup `_ptyExited` error path → bounded respawn (#5315) → and, when 5
1815
+ // resume-respawns all died during warmup AND the dying PTY tail confirms
1816
+ // claude does not know the conversation id, ONE drop-and-retry-FRESH
1817
+ // attempt with a new uuid (#5348/#5417, see _scheduleRespawn) before
1818
+ // exhaustion destroys the session.
1819
+ const idArgs = this._resumedFromPersisted
1820
+ ? ['--resume', this._sessionId]
1821
+ : ['--session-id', this._sessionId]
1822
+ const args = [
1823
+ ...idArgs,
1824
+ '--settings', this._settingsPath,
1825
+ // Claude Code 2.1.186 added a "Claude in Chrome extension detected"
1826
+ // first-run prompt that interactively blocks the TUI (1/2/Enter/Esc) when
1827
+ // the browser extension is installed. chroxy's PTY driver can't dismiss
1828
+ // that prompt, so the session wedges and the claude PTY exits mid-turn
1829
+ // (code=1). A headless chroxy TUI session never drives the browser
1830
+ // integration, so disable it at spawn — no prompt, no wedge.
1831
+ '--no-chrome',
1832
+ ]
1833
+ if (this.skipPermissions) {
1834
+ // #4044: bypass chroxy's hook + claude's per-tool prompt entirely.
1835
+ // Caller is expected to opt in explicitly via the session option.
1836
+ // The dashboard CreateSessionModal surface + warning copy + WS
1837
+ // protocol plumbing are tracked separately in #4208 — until then
1838
+ // this option is only reachable via direct programmatic construction.
1839
+ args.push('--dangerously-skip-permissions')
1840
+ }
1841
+ if (this.model) {
1842
+ // claude TUI accepts --model (verified against `claude --help`). Without
1843
+ // this the requested model was silently dropped, leaving ready.model
1844
+ // disagreeing with the actual model the TUI booted on (#3921).
1845
+ args.push('--model', this.model)
1846
+ }
1847
+ // Inject the append-bucket skills text via --append-system-prompt at
1848
+ // spawn time so the TUI sees it as part of the system prompt — same
1849
+ // channel CliSession uses (#3917). The prepend bucket would need to
1850
+ // ride on the first user message instead, but writing multi-line text
1851
+ // to a PTY input box prematurely-submits on every embedded \n, so
1852
+ // we route the prepend bucket through the same system-prompt channel
1853
+ // here. Semantically not identical to CliSession's split (prepend goes
1854
+ // to user message there), but functionally correct for the MVP and
1855
+ // avoids the PTY newline problem.
1856
+ const skillsPrefix = (typeof this._buildCombinedSkillsPrefix === 'function')
1857
+ ? this._buildCombinedSkillsPrefix()
1858
+ : ''
1859
+ if (skillsPrefix) {
1860
+ args.push('--append-system-prompt', skillsPrefix)
1861
+ }
1862
+ log.info(`spawn claude TUI (uuid=${this._sessionId.slice(0, 8)} model=${this.model || 'default'} perms=${permissionsEnabled} skills=${skillsPrefix ? skillsPrefix.length + 'b' : 'none'})`)
1863
+
1864
+ try {
1865
+ // node-pty spawns CLAUDE directly — no cmd.exe routing needed even when
1866
+ // the Windows resolver lands on a `claude.cmd` shim. node-pty routes
1867
+ // through conpty/cmd.exe internally and runs a `.cmd` fine (verified),
1868
+ // unlike child_process.spawn which throws EINVAL on a `.cmd` (Node 24) and
1869
+ // needs the utils/win-spawn.js escaping the cli-session path uses.
1870
+ this._term = ptyMod.spawn(CLAUDE, args, {
1871
+ name: 'xterm-256color',
1872
+ // #5839: single-sourced default so the dashboard mirror renders at the
1873
+ // same grid. #5835 Phase 2: a prior resize is preserved across respawns
1874
+ // via _ptyCols/_ptyRows (seeded from CLAUDE_TUI_PTY_SIZE on construct).
1875
+ cols: this._ptyCols,
1876
+ rows: this._ptyRows,
1877
+ cwd: cwdReal,
1878
+ env,
1879
+ })
1880
+ } catch (err) {
1881
+ this.emit('error', { message: `Failed to spawn claude under PTY: ${err.message}` })
1882
+ return
1883
+ }
1884
+
1885
+ // #5315 (WP-2.1) review — destroy() can race an in-flight (re)spawn: it kills
1886
+ // the OLD _term and sets _destroying while we're awaiting the spawn above, so
1887
+ // the PTY we just created would be orphaned (nothing left to kill it). If a
1888
+ // teardown landed during the await, kill the fresh PTY now and bail.
1889
+ if (this._destroying) {
1890
+ try { this._term.kill('SIGTERM') } catch {}
1891
+ this._term = null
1892
+ return
1893
+ }
1894
+
1895
+ // #5321 (WP-4.1) — reset the output tails for THIS spawn so the warmup auth
1896
+ // scan (and a later _onPtyGone / stall scan) can't match a banner left over
1897
+ // from a prior process on a respawn. Constructor already empties these for
1898
+ // the first spawn; this covers every subsequent _respawnPty.
1899
+ this._outputTail = ''
1900
+ this._outputTailRaw = Buffer.alloc(0)
1901
+ // #6601: re-evaluate output-quiescence readiness for THIS spawn — require
1902
+ // fresh output before trusting a quiet stretch, so a leftover _lastOutputMs
1903
+ // from the prior process can't read as "ready" the instant we respawn.
1904
+ this._sawFirstOutput = false
1905
+ this._lastOutputMs = this._nowMonotonic()
1906
+
1907
+ // #5794: a fresh PTY can swallow the first submit again, so re-arm the
1908
+ // first-turn submit nudge for the first message on THIS spawn. Reset after
1909
+ // the destroy-race guard above so an aborted (re)spawn doesn't clear it.
1910
+ this._firstTurnNudgedForSpawn = false
1911
+ // #6578: a (re)spawn can land on a new pid (wrapper shim) or a new sessionId
1912
+ // (retry-FRESH fallback), so the cached session-file path is stale — force
1913
+ // the next readiness probe to re-resolve (and scan immediately).
1914
+ this._resolvedSessionFile = null
1915
+ this._lastSessionDirScanMs = -Infinity
1916
+
1917
+ this._term.onData((data) => {
1918
+ this._appendToOutputTail(data)
1919
+ // #5835 Phase 1: feed the live remote-viewer mirror (the authenticity
1920
+ // surface). Same raw bytes that go to _outputTail, but coalesced and
1921
+ // broadcast to subscribed clients so they can watch the real TUI redraw.
1922
+ this._feedTerminalMirror(data)
1923
+ })
1924
+ this._term.onExit((info) => this._onPtyGone(info, 'exit'))
1925
+
1926
+ // #5311 (WP-1.1) — keep a per-session PTY fault from crashing the WHOLE
1927
+ // daemon (every session on the host) via an uncaught throw. node-pty's
1928
+ // internal socket 'error' handler (unixTerminal.js) returns silently for
1929
+ // EAGAIN/EIO (the normal child-exit path, which surfaces through onExit
1930
+ // above) but for any OTHER error it calls _close() + emits 'close' and then
1931
+ // `throw err` UNLESS the Terminal has >= 2 'error' listeners. It never
1932
+ // emits 'error' to those listeners — they exist solely to clear that
1933
+ // rethrow threshold. So:
1934
+ // - drive the actual teardown off 'close' (which node-pty DOES emit), and
1935
+ // - also off 'error' in case a future node-pty starts emitting it, and
1936
+ // - register a second no-op 'error' listener so the count is >= 2 and the
1937
+ // otherwise-uncaught throw is suppressed.
1938
+ // _onPtyGone is idempotent (guards on _ptyExited) so onExit + close + error
1939
+ // firing in any order tears down + emits exactly once.
1940
+ this._term.on('error', (err) => this._onPtyGone(null, `error: ${err?.message || 'unknown'}`))
1941
+ this._term.on('error', () => {}) // bumps listener count >= 2 so node-pty does not rethrow
1942
+ this._term.on('close', () => this._onPtyGone(null, 'close'))
1943
+
1944
+ // Wait for the TUI to reach status=idle before returning. The prior
1945
+ // implementations (hardcoded sleep, then glyph screen-scrape across
1946
+ // #4014/#4031/#4035/#4039) all failed silently when claude's render
1947
+ // shape didn't match expectation. #4040 swaps to claude's own
1948
+ // session file — `~/.claude/sessions/<pid>.json` carries a `status`
1949
+ // field claude updates on every state transition. Atomic, kernel-
1950
+ // backed, decoupled from TUI rendering changes. On miss we still
1951
+ // proceed so a transient FS race doesn't brick the session.
1952
+ const ready = await this._waitForPrompt(ClaudeTuiSession.SPAWN_WARMUP_MAX_MS, { detectAuthFailure: true })
1953
+ // #5321 (WP-4.1) — also scan once on the timeout fallback (a logged-out
1954
+ // claude may print its login prompt and then sit there without ever exiting
1955
+ // or writing a `status`, so the in-loop scan above could miss a late banner).
1956
+ if (!ready && !this._ptyExited && !this._authFailureDetected && this._scanOutputForAuthFailure()) {
1957
+ this._authFailureDetected = true
1958
+ }
1959
+ if (this._authFailureDetected) {
1960
+ log.warn(`claude TUI auth failure detected during warmup — ${AUTH_REQUIRED_CODE}`)
1961
+ // start() inspects _authFailureDetected and rejects with AUTH_REQUIRED.
1962
+ return
1963
+ }
1964
+ if (!ready && !this._ptyExited) {
1965
+ ;(this._log || log).warn(
1966
+ `TUI session file did not reach status=idle within ${ClaudeTuiSession.SPAWN_WARMUP_MAX_MS}ms${this._degradedProbeSuffix()} — proceeding (first sendMessage may stall)\n` +
1967
+ `_outputTail dump:\n${this._outputTailLogDump()}`,
1968
+ )
1969
+ }
1970
+ }
1971
+
1972
+ /**
1973
+ * #5328 (WP-5.6) / #6578: build the diagnostic suffix for a readiness-probe
1974
+ * timeout. Since #6578 the probe resolves the session file by matching
1975
+ * `sessionId` (resolveSessionFile) and treats existence-with-matching-id as
1976
+ * ready even when the file carries no `status`, so `_lastProbeSawStatus` now
1977
+ * means "resolved a matching session file". That collapses the degraded case
1978
+ * to ONE: no session file carrying this session's `sessionId` was found
1979
+ * anywhere under ~/.claude/sessions — neither at the pty pid nor via the
1980
+ * dir-scan. Likely causes: a wrapper shim whose real claude writes to a
1981
+ * DIFFERENT ~/.claude (so no matching file is reachable), or claude never
1982
+ * wrote the file. Returns '' when the probe resolved a matching file (found
1983
+ * but busy = healthy, real busy).
1984
+ */
1985
+ _degradedProbeSuffix() {
1986
+ if (this._lastProbeSawStatus !== false) return ''
1987
+ const pid = this._term && this._term.pid
1988
+ const pidNote = Number.isInteger(pid) && pid > 0 ? ` (pty pid ${pid})` : ''
1989
+ const idNote = this._sessionId ? ` sessionId ${this._sessionId}` : ' (no sessionId)'
1990
+ return ` — no session file for${idNote} found under ~/.claude/sessions${pidNote}; claude may be running under a different pid or a different ~/.claude (a wrapper shim that forks node without exec, or a redirected HOME), so the readiness probe can't resolve its state and readiness gating is effectively disabled for this session`
1991
+ }
1992
+
1993
+ /**
1994
+ * Resolve `true` when the TUI is ready for input (claude's per-PID
1995
+ * session file reports a status other than 'busy'), `false` on
1996
+ * timeout or PTY exit.
1997
+ *
1998
+ * Reads `~/.claude/sessions/<pty.pid>.json` — the same file
1999
+ * `claude ps` consumes. Claude TUI writes this file at startup and
2000
+ * updates `status` on every state transition: 'busy' while processing
2001
+ * a turn, 'idle' (or other non-busy variants) when waiting for input.
2002
+ *
2003
+ * Used by _spawnPty (one-time, generous timeout) and sendMessage
2004
+ * (per-turn, short timeout). Replaces the #4014/#4031/#4035 screen-
2005
+ * scrape approaches, which never had a stable signal to anchor on:
2006
+ * the input box is followed by status widgets in the trailing buffer,
2007
+ * so a trailing-edge match never fires, and a looser line-anchored
2008
+ * match false-positives on welcome text. The session file is what
2009
+ * claude itself uses for the `claude ps` state machine, so it's
2010
+ * decoupled from rendering and survives TUI redraw changes (#4040).
2011
+ */
2012
+ async _waitForPrompt(timeoutMs, { detectAuthFailure = false } = {}) {
2013
+ // No usable PTY pid — treat as not-ready and fall through to the
2014
+ // existing warn-and-write path. Returning true here would silently
2015
+ // disable readiness gating on any platform/runtime where node-pty
2016
+ // doesn't populate `pid` (Copilot review on #4040). Tests that
2017
+ // explicitly want to skip the probe stub `_waitForPrompt` directly
2018
+ // rather than rely on this guard.
2019
+ //
2020
+ // Wedge instrumentation (#4678 follow-up): record elapsedMs +
2021
+ // sawStatus + result on every exit path. The wedge symptom is
2022
+ // `stream_start` then silence — without this log we cannot tell
2023
+ // whether the call returned promptly (write stage stalled) or
2024
+ // burned its 5s timeout (probe degraded). Routes via `_activeTurn`
2025
+ // so the line is sourced from the same turn the caller is logging.
2026
+ const startMs = this._nowMonotonic()
2027
+ const finish = (ready) => {
2028
+ const elapsedMs = this._nowMonotonic() - startMs
2029
+ if (this._activeTurn) {
2030
+ this._activeTurn.waitForPromptMs = elapsedMs
2031
+ this._activeTurn.waitForPromptReady = ready
2032
+ this._activeTurn.waitForPromptSawStatus = this._lastProbeSawStatus
2033
+ }
2034
+ log.info(`waitForPrompt (msg=${this._activeTurn?.messageId ?? 'none'} elapsedMs=${elapsedMs} sawStatus=${this._lastProbeSawStatus} ready=${ready})`)
2035
+ // #5777 FIX-0 (diagnostic) — readiness is a session-FILE status check,
2036
+ // decoupled from what the TUI renders, so claude can report status:idle
2037
+ // (ready=true) WHILE a one-shot startup interstitial (trust dialog,
2038
+ // release-notes / opus-notice / remote-control upsell / onboarding) is
2039
+ // on screen and silently swallowing the injected first prompt → the
2040
+ // consumed=0 first_output_timeout wedge (#5777). The existing tail dumps
2041
+ // only fire on !ready, so that wedged-but-"ready" screen was invisible.
2042
+ // Dump the readable tail ONCE per session on the first ready so the exact
2043
+ // interstitial can be named and FIX-1's detector anchored on a real
2044
+ // token. Opt-in (CHROXY_TUI_DUMP_READY_TAIL=1) so healthy sessions are
2045
+ // untouched; one-shot latch so even when enabled it logs at most once.
2046
+ if (ready && !this._readyTailDumped && process.env.CHROXY_TUI_DUMP_READY_TAIL === '1') {
2047
+ this._readyTailDumped = true
2048
+ // #5322 redaction: route through _outputTailDiagnostic() (redactSensitive
2049
+ // + bounded slice) instead of dumping raw _outputTail, so an enabled
2050
+ // diagnostic can't leak token-shaped secrets into the server log.
2051
+ const tail = this._outputTailDiagnostic()
2052
+ log.info(`waitForPrompt ready-path tail (FIX-0 #5777, msg=${this._activeTurn?.messageId ?? 'none'}):\n${tail}`)
2053
+ }
2054
+ return ready
2055
+ }
2056
+ const pid = this._term && this._term.pid
2057
+ if (!Number.isInteger(pid) || pid <= 0) {
2058
+ this._lastProbeSawStatus = false
2059
+ return finish(false)
2060
+ }
2061
+ // #6578: resolve the session file by matching `sessionId` (not just the pty
2062
+ // pid) so a wrapper-shim install (real claude pid != pty pid, MODE A) still
2063
+ // finds the file, and treat the file's EXISTENCE-with-matching-sessionId as
2064
+ // a readiness signal because current claude session files carry no `status`
2065
+ // field at all (MODE B). `_lastProbeSawStatus` now means "resolved a
2066
+ // matching session file this poll" (not "read a non-null status string").
2067
+ let sawStatus = false
2068
+ const checkReady = () => {
2069
+ // Reuse the cached path when it still resolves to this session's file;
2070
+ // re-resolve (dir-scan) when the cache is cold or has gone stale (file
2071
+ // deleted / sessionId changed). Caching keeps the per-turn probe from
2072
+ // scanning ~/.claude/sessions every poll.
2073
+ let sessFile = this._resolvedSessionFile
2074
+ if (!sessFile || !ClaudeTuiSession._sessionFileMatches(sessFile, this._sessionId)) {
2075
+ // Throttle the readdir-heavy dir-scan to ~2/sec during the cold-resolve
2076
+ // warmup window. The cheap fast-path (pty-pid file read) still runs every
2077
+ // 100ms poll; only the fallback scan is rate-limited — so a MODE-A file
2078
+ // (real pid != pty pid) is still detected within ~500ms of appearing,
2079
+ // negligible against the multi-second warmup.
2080
+ const now = this._nowMonotonic()
2081
+ const allowDirScan = (now - this._lastSessionDirScanMs) >= 500
2082
+ if (allowDirScan) this._lastSessionDirScanMs = now
2083
+ sessFile = ClaudeTuiSession.resolveSessionFile(this._sessionId, pid, { allowDirScan })
2084
+ this._resolvedSessionFile = sessFile
2085
+ }
2086
+ if (!sessFile) {
2087
+ // #6601: no session file resolved. Current claude's INTERACTIVE TUI
2088
+ // writes no ~/.claude/sessions/<pid>.json at all, so the file probe
2089
+ // never resolves and the caller used to burn the full warmup/turn
2090
+ // ceiling then "write anyway" (the degraded path). Fall back to PTY
2091
+ // OUTPUT QUIESCENCE: once claude has rendered on this spawn and output
2092
+ // has been quiet for READY_QUIESCENCE_MS, the composer's render burst has
2093
+ // settled and it is ready for input. Validated live (cold ready ~1.1s,
2094
+ // between-turn redraw sub-second). The file path below is UNCHANGED for
2095
+ // -p / claude-desktop / any version that DOES write a file; the
2096
+ // warmup/turn ceilings still backstop a genuinely-stuck TUI, and the
2097
+ // auth-failure scan (poll loop, above this) still runs first so a
2098
+ // logged-out banner can't be mistaken for a settled composer.
2099
+ return this._sawFirstOutput &&
2100
+ (this._nowMonotonic() - this._lastOutputMs) >= ClaudeTuiSession.READY_QUIESCENCE_MS
2101
+ }
2102
+ // A matching file was resolved → we have this session's readiness signal.
2103
+ sawStatus = true
2104
+ const status = ClaudeTuiSession.readSessionStatus(sessFile)
2105
+ // Ready = a status is present and it's not 'busy' (versions that still
2106
+ // write status keep between-turn gating), OR the file exists with no
2107
+ // status field at all (current claude — existence IS the ready signal).
2108
+ return status === null ? true : status !== 'busy'
2109
+ }
2110
+ while (this._nowMonotonic() - startMs < timeoutMs) {
2111
+ if (this._ptyExited) {
2112
+ this._lastProbeSawStatus = sawStatus
2113
+ return finish(false)
2114
+ }
2115
+ // #5321 (WP-4.1) — short-circuit the (up to 90s) warmup wait the moment
2116
+ // claude prints a logged-out / expired-login message, so start() can
2117
+ // surface AUTH_REQUIRED immediately instead of burning the full timeout
2118
+ // on a session that can never become ready. Warmup-only (opt-in) so
2119
+ // normal per-turn output is never scanned.
2120
+ if (detectAuthFailure && this._scanOutputForAuthFailure()) {
2121
+ this._authFailureDetected = true
2122
+ this._lastProbeSawStatus = sawStatus
2123
+ return finish(false)
2124
+ }
2125
+ if (checkReady()) {
2126
+ this._lastProbeSawStatus = sawStatus
2127
+ return finish(true)
2128
+ }
2129
+ await new Promise((r) => setTimeout(r, 100))
2130
+ }
2131
+ const ready = checkReady()
2132
+ this._lastProbeSawStatus = sawStatus
2133
+ return finish(ready)
2134
+ }
2135
+
2136
+ /**
2137
+ * Append a PTY onData chunk to the recent-output tails (#3919).
2138
+ *
2139
+ * Maintains two tails:
2140
+ * - `_outputTailRaw` — an UNSTRIPPED byte Buffer for the timeout hex
2141
+ * dump (#4031), and the canonical source the readable tail is
2142
+ * derived from.
2143
+ * - `_outputTail` — an ANSI-stripped, human-readable string for inline
2144
+ * error diagnostics and the auth-failure scan.
2145
+ *
2146
+ * #5325 (WP-5.3): the readable tail is derived by stripping ANSI from
2147
+ * the CONCATENATED raw buffer, NOT per-chunk. An escape sequence split
2148
+ * across two onData chunks (e.g. "\x1b[" arriving in one chunk, "0m" in
2149
+ * the next) survives a per-chunk strip and corrupts the tail; deriving
2150
+ * from the merged buffer strips the sequence once it's whole. We don't
2151
+ * visual-render the PTY, so the colors aren't useful. Strip pattern
2152
+ * covers CSI / OSC / SS3 / single-char terminal-mode codes (#4031).
2153
+ */
2154
+ _appendToOutputTail(data) {
2155
+ // #6601: output-quiescence readiness — stamp the recency of PTY output so
2156
+ // checkReady can detect a settled composer (see READY_QUIESCENCE_MS) when no
2157
+ // session file exists. Two cheap field writes on a hot (per-redraw) path.
2158
+ this._lastOutputMs = this._nowMonotonic()
2159
+ this._sawFirstOutput = true
2160
+ const rawStr = String(data)
2161
+ const chunk = Buffer.from(rawStr, 'utf8')
2162
+ // #5794/#5809: monotonic total — never capped, so the nudge's progress check
2163
+ // works even when _outputTail is pinned at PTY_TAIL_BYTES.
2164
+ this._totalOutputBytes += chunk.length
2165
+ const merged = this._outputTailRaw.length === 0
2166
+ ? chunk
2167
+ : Buffer.concat([this._outputTailRaw, chunk])
2168
+ this._outputTailRaw = merged.length > ClaudeTuiSession.PTY_TAIL_BYTES
2169
+ ? merged.subarray(-ClaudeTuiSession.PTY_TAIL_BYTES)
2170
+ : merged
2171
+ this._outputTail = this._outputTailRaw
2172
+ .toString('utf8')
2173
+ .replace(ANSI_STRIP, '')
2174
+ .slice(-ClaudeTuiSession.PTY_TAIL_BYTES)
2175
+ }
2176
+
2177
+ /**
2178
+ * #5835 Phase 1: feed the live remote-viewer mirror. Appends a raw PTY chunk
2179
+ * (ANSI intact — the viewer xterm renders it) to the coalescing buffer and
2180
+ * arms a single flush timer if one isn't already pending. The bytes are NOT
2181
+ * stripped or transformed: faithful reproduction is the whole point.
2182
+ */
2183
+ _feedTerminalMirror(data) {
2184
+ // #5837: skip ALL coalescer work when nobody is subscribed to this session's
2185
+ // mirror. This is the common case (the Output tab is closed), and onData fires
2186
+ // very frequently — gating here saves the per-redraw string concat + timer +
2187
+ // session_event for the whole life of an unwatched session.
2188
+ if (!this._terminalMirrorActive) return
2189
+ this._mirrorBuffer += String(data)
2190
+ if (this._mirrorTimer) return
2191
+ this._mirrorTimer = setTimeout(() => this._flushTerminalMirror(), ClaudeTuiSession.MIRROR_FLUSH_MS)
2192
+ // Don't keep the event loop alive for a mirror flush — teardown clears it.
2193
+ if (typeof this._mirrorTimer.unref === 'function') this._mirrorTimer.unref()
2194
+ }
2195
+
2196
+ /**
2197
+ * #5837: turn the live mirror coalescer on/off based on whether any client is
2198
+ * subscribed to this session's terminal. WsServer calls this when the
2199
+ * terminal-subscriber count crosses 0↔1. When turning OFF, drop any pending
2200
+ * buffer/timer (nobody is watching, so a trailing flush is pure waste) — this
2201
+ * reuses the same teardown as _clearTerminalMirror.
2202
+ */
2203
+ setTerminalMirrorActive(active) {
2204
+ const next = !!active
2205
+ if (next === this._terminalMirrorActive) return
2206
+ this._terminalMirrorActive = next
2207
+ if (!next) this._clearTerminalMirror()
2208
+ }
2209
+
2210
+ /**
2211
+ * Emit the coalesced mirror buffer as one `terminal_output` event and reset.
2212
+ * No-op when the buffer is empty (e.g. a stray flush after teardown).
2213
+ */
2214
+ _flushTerminalMirror() {
2215
+ this._mirrorTimer = null
2216
+ const data = this._mirrorBuffer
2217
+ if (!data) return
2218
+ this._mirrorBuffer = ''
2219
+ this.emit('terminal_output', { data })
2220
+ }
2221
+
2222
+ /**
2223
+ * #5835 Phase 2: the live PTY's current grid size, for a newly-subscribing
2224
+ * viewer to letterbox to (and for tests). Always reflects the last applied
2225
+ * resize, or the spawn default before any resize.
2226
+ * @returns {{cols: number, rows: number}}
2227
+ */
2228
+ getTerminalSize() {
2229
+ return { cols: this._ptyCols, rows: this._ptyRows }
2230
+ }
2231
+
2232
+ /**
2233
+ * #5835 Phase 2: resize the live PTY (the remote-viewer mirror). Clamps to the
2234
+ * same bounds the protocol schema enforces so a bad caller can't throw inside
2235
+ * node-pty, records the size so it survives a respawn, and applies it to the
2236
+ * running PTY when one exists (a resize requested before/after the PTY is alive
2237
+ * still updates the tracked size, taking effect on the next spawn). The real
2238
+ * TUI redraws at the new size; those bytes flow out through the normal mirror.
2239
+ * @returns {{cols: number, rows: number}|null} the applied size, or null if the
2240
+ * request was a no-op (unchanged) so the caller can skip a redundant broadcast.
2241
+ */
2242
+ resizeTerminal(cols, rows) {
2243
+ const c = Math.max(1, Math.min(1000, Math.floor(Number(cols))))
2244
+ const r = Math.max(1, Math.min(1000, Math.floor(Number(rows))))
2245
+ // Load-bearing guard: NaN (e.g. resizeTerminal('x', 'y')) survives
2246
+ // Math.floor/min/max unchanged, so the clamp above does NOT guarantee
2247
+ // finiteness — without this a NaN would reach _term.resize. Don't remove.
2248
+ if (!Number.isFinite(c) || !Number.isFinite(r)) return null
2249
+ if (c === this._ptyCols && r === this._ptyRows) return null
2250
+ this._ptyCols = c
2251
+ this._ptyRows = r
2252
+ if (this._term && !this._ptyExited) {
2253
+ try {
2254
+ this._term.resize(c, r)
2255
+ } catch (err) {
2256
+ // A resize race against PTY teardown shouldn't crash the daemon; the
2257
+ // tracked size still applies on the next spawn.
2258
+ log.warn(`claude-tui resize failed (${c}x${r}): ${err?.message || err}`)
2259
+ }
2260
+ }
2261
+ // Tell subscribed viewers the new authoritative size (ws-forwarding routes
2262
+ // this to terminal subscribers as `terminal_size`), so observers re-letterbox
2263
+ // and the requesting primary renders the confirmed grid.
2264
+ this.emit('terminal_resize', { cols: c, rows: r })
2265
+ return { cols: c, rows: r }
2266
+ }
2267
+
2268
+ /**
2269
+ * #6313: force the live PTY to repaint by toggling the grid width one column and
2270
+ * back. Each resize sends SIGWINCH, so the real TUI redraws its canvas (and a
2271
+ * shell prompt redraws its current line). This is the only recovery for the
2272
+ * stateless raw-byte mirror after a WS-backpressure-dropped frame desyncs the
2273
+ * xterm grid — there is no app-level snapshot to replay. The width is restored,
2274
+ * so the authoritative size is unchanged. No-op (false) when there is no live
2275
+ * PTY. Caveat: a process that ignores SIGWINCH won't repaint.
2276
+ * @returns {boolean} whether a repaint was driven against a live PTY.
2277
+ */
2278
+ forceTerminalRepaint() {
2279
+ if (!this._term || this._ptyExited) return false
2280
+ const { cols, rows } = this.getTerminalSize()
2281
+ // Toggle to a definitely-different width (cols-1, or 2 when at the 1-col
2282
+ // floor) then restore — each resizeTerminal call changes the width so neither
2283
+ // hits its unchanged-size no-op guard, and the original grid is restored.
2284
+ const toggleCols = cols > 1 ? cols - 1 : 2
2285
+ this.resizeTerminal(toggleCols, rows)
2286
+ this.resizeTerminal(cols, rows)
2287
+ return true
2288
+ }
2289
+
2290
+ /**
2291
+ * #5835 Phase 3: write raw client keystrokes to the live PTY — true remote
2292
+ * control (the read-only mirror becomes interactive). Bytes are written AS-IS:
2293
+ * no prompt throttle (interactive keys arrive naturally paced over the wire;
2294
+ * the throttle exists only for bulk programmatic prompts) and no transform
2295
+ * (faithful remote keyboard, including control bytes like \x03 / escape seqs).
2296
+ * The handler enforces authority (bound session + primary-ownership gate); this
2297
+ * just writes. No-op (returns false) when there is no live PTY.
2298
+ * @returns {boolean} true if the bytes were written to a live PTY.
2299
+ */
2300
+ writeTerminalInput(data) {
2301
+ if (typeof data !== 'string' || data.length === 0) return false
2302
+ if (!this._term || this._ptyExited || this._destroying) return false
2303
+ try {
2304
+ this._term.write(data)
2305
+ return true
2306
+ } catch (err) {
2307
+ log.warn(`claude-tui terminal input write failed: ${err?.message || err}`)
2308
+ return false
2309
+ }
2310
+ }
2311
+
2312
+ /**
2313
+ * Drop any pending mirror flush + buffered bytes. Called on teardown so a
2314
+ * dead PTY's leftover frame never broadcasts and no timer leaks.
2315
+ */
2316
+ _clearTerminalMirror() {
2317
+ if (this._mirrorTimer) {
2318
+ clearTimeout(this._mirrorTimer)
2319
+ this._mirrorTimer = null
2320
+ }
2321
+ this._mirrorBuffer = ''
2322
+ }
2323
+
2324
+ /**
2325
+ * Dump the trailing bytes of the UNSTRIPPED PTY tail as a hex+ASCII
2326
+ * block for a log line (#4031). Called on readiness timeout or any
2327
+ * other diagnostic surface where seeing what claude actually wrote —
2328
+ * including escape/control sequences — saves a debugging round-trip.
2329
+ * Public-ish (single underscore) so tests can assert on the format
2330
+ * without re-implementing it.
2331
+ *
2332
+ * Sourced from `_outputTailRaw` rather than the ANSI-stripped tail so
2333
+ * 0x1b / OSC / SS3 bytes land in the log; the stripped variant would
2334
+ * hide the very bytes the diagnostic exists to surface (#4031 review).
2335
+ */
2336
+ _outputTailHexDump() {
2337
+ // Cap at PTY_TAIL_DIAGNOSTIC_BYTES so logs stay bounded while still
2338
+ // showing enough context to identify a TUI-rendered error inline.
2339
+ // The raw (un-stripped) buffer is used so escape/control bytes
2340
+ // survive into the diagnostic — sourcing from the stripped tail
2341
+ // would hide the very bytes we want to see (#4031 review).
2342
+ //
2343
+ // #5322 (WP-4.2, security) — redact token-shaped runs BEFORE hex-encoding so
2344
+ // a pasted/echoed OAuth token can't leak via the dump's hex AND ASCII
2345
+ // columns. The redact runs on a latin1 (binary) round-trip, which preserves
2346
+ // every byte 0–255 losslessly (so 0x1b / OSC / SS3 escape bytes still land
2347
+ // in the dump); redactSensitive only rewrites the ASCII token runs.
2348
+ // #5358: redactSensitivePreservingEscapes is used ALONE (NOT layered after
2349
+ // redactSensitive). It must see the ORIGINAL bytes to reassemble a token the
2350
+ // TUI split with a mid-token escape: running redactSensitive first would
2351
+ // partially redact a marker-prefixed split token (e.g. `token=sk-ant-AAAA`
2352
+ // → `token= [REDACTED]`), consuming the marker so the escape-aware pass can
2353
+ // no longer detect the run — and the tail after the escape would LEAK. This
2354
+ // pass covers the contiguous case too (same patterns, incl. Bearer / JWT /
2355
+ // key=value), scrubbing token chars to 'X' while preserving the escape bytes
2356
+ // the dump exists to show.
2357
+ const latin1 = this._outputTailRaw.toString('latin1')
2358
+ const redacted = Buffer.from(redactSensitivePreservingEscapes(latin1), 'latin1')
2359
+ return formatHexDump(redacted, ClaudeTuiSession.PTY_TAIL_DIAGNOSTIC_BYTES)
2360
+ }
2361
+
2362
+ /**
2363
+ * Log-facing variant of the PTY tail dump. Token-shaped runs are ALWAYS
2364
+ * redacted (#5322/#5358), but the full hex dump still emits prompt/answer
2365
+ * CONTENT verbatim (question text, answer text, attachment names) at info
2366
+ * level — residual content-at-rest exposure in ~/.chroxy/logs. So the full
2367
+ * dump is gated behind CHROXY_DEBUG_PTY_TAIL; by default we emit a compact
2368
+ * structural summary (redacted byte length + a bounded 32-byte hex preview,
2369
+ * mirroring pty-driver.js's #4805 incident-response footprint). Every log
2370
+ * call site routes through here; the unit-tested `_outputTailHexDump()`
2371
+ * remains the full redacted dump. (audit P2-12)
2372
+ */
2373
+ _outputTailLogDump() {
2374
+ if (process.env.CHROXY_DEBUG_PTY_TAIL) return this._outputTailHexDump()
2375
+ const latin1 = this._outputTailRaw.toString('latin1')
2376
+ const redacted = Buffer.from(redactSensitivePreservingEscapes(latin1), 'latin1')
2377
+ if (redacted.length === 0) return '<empty>'
2378
+ const sampleHex = redacted.slice(0, 32).toString('hex')
2379
+ const truncated = redacted.length > 32 ? ',…' : ''
2380
+ return `${redacted.length} bytes redacted (set CHROXY_DEBUG_PTY_TAIL=1 for full dump; sample=${sampleHex}${truncated})`
2381
+ }
2382
+
2383
+ /**
2384
+ * #5321 (WP-4.1) — classify the ANSI-stripped PTY tail as a subscription-auth
2385
+ * failure (logged out / expired login). Returns true when claude's output
2386
+ * matches an AUTH_FAILURE_PATTERNS entry. Called during warmup (before ready)
2387
+ * and once a turn has stalled / the PTY exited — those tails CAN contain
2388
+ * rendered response text, so the false-positive defence lives in the patterns
2389
+ * themselves: each requires claude's `/login` / `claude login` remediation
2390
+ * command token, which a model merely *discussing* authentication won't emit.
2391
+ */
2392
+ _scanOutputForAuthFailure() {
2393
+ const tail = this._outputTail || ''
2394
+ if (!tail) return false
2395
+ // Collapse whitespace (the TUI wraps/box-pads the banner with newlines +
2396
+ // spaces) so a line-wrapped "Please run\n /login" still matches.
2397
+ const normalized = tail.replace(/\s+/g, ' ')
2398
+ return AUTH_FAILURE_PATTERNS.some((re) => re.test(normalized))
2399
+ }
2400
+
2401
+ /**
2402
+ * #5417 — classify the ANSI-stripped PTY tail as a "--resume id unknown"
2403
+ * failure. The PTY merges stdout+stderr, so the same diagnostics
2404
+ * CliSession's stderr classifier pins ("No conversation found with session
2405
+ * ID …" — RESUME_UNKNOWN_STDERR_PATTERNS in cli-session.js, #4929/#4950)
2406
+ * land in `_outputTail` when claude rejects a `--resume <id>` and exits
2407
+ * during warmup. `_outputTail` is reset at the top of every _spawnPty, so a
2408
+ * match always describes the MOST RECENT death, never a stale prior
2409
+ * attempt.
2410
+ *
2411
+ * Matching is PER LINE plus adjacent-line pairs — NOT one collapsed blob.
2412
+ * CliSession's classifier tests each stderr line separately, which bounds
2413
+ * the `.*` in the #4950 co-occurrence patterns (e.g.
2414
+ * `/(fail|error|…).*resum(e|ing).*(session|conversation|\bid\b)/i`) to a
2415
+ * single line. Collapsing the whole 4KB tail into one string would let
2416
+ * those patterns match "error" + "resume" + "session" scattered across
2417
+ * UNRELATED lines — and a `--resume` warmup re-renders the restored
2418
+ * transcript into the tail, so ordinary conversation content (the exact
2419
+ * large-but-present-conversation crash this gate exists to protect) could
2420
+ * false-positive and abandon a real conversation id. Joining each adjacent
2421
+ * line pair (whitespace-collapsed, mirroring _scanOutputForAuthFailure's
2422
+ * normalization) still catches a rejection the TUI wrapped/box-padded
2423
+ * across one rendered line break, while keeping the match window ≤ two
2424
+ * lines instead of the whole tail. Consulted by _scheduleRespawn at the
2425
+ * respawn cap to decide retry-FRESH eligibility. The tail is only SCANNED
2426
+ * here, never logged — every diagnostic surface keeps routing through the
2427
+ * redaction helpers (_outputTailDiagnostic / _outputTailHexDump,
2428
+ * #5322/#5358).
2429
+ */
2430
+ _scanOutputForUnknownResume() {
2431
+ const tail = this._outputTail || ''
2432
+ if (!tail) return false
2433
+ const lines = tail
2434
+ .split(/[\r\n]+/)
2435
+ .map((line) => line.replace(/\s+/g, ' ').trim())
2436
+ .filter(Boolean)
2437
+ if (lines.length === 0) return false
2438
+ const candidates = lines.slice()
2439
+ for (let i = 0; i + 1 < lines.length; i++) candidates.push(`${lines[i]} ${lines[i + 1]}`)
2440
+ return stderrIndicatesUnknownResume(candidates)
2441
+ }
2442
+
2443
+ async sendMessage(prompt, attachments, _options = {}) {
2444
+ // #5800: these two guards signal failure to callers via a typed result
2445
+ // ({ ok: false, reason }) IN ADDITION to the legacy emit('error', ...).
2446
+ // The emit is unchanged (existing error surfacing relies on it); the
2447
+ // typed return lets a caller (e.g. the multi-select reinject path in
2448
+ // form-driver.js) observe the failure via the call result instead of
2449
+ // mirroring these host internals from the outside. The happy path
2450
+ // returns undefined as before — callers branch only on the failure
2451
+ // shape. input-handlers.js (the non-reinject caller) ignores the
2452
+ // resolved value entirely; it only attaches a defensive .catch, which a
2453
+ // resolved typed object never trips.
2454
+ if (this._isBusy) {
2455
+ this.emit('error', { message: 'Already processing a message' })
2456
+ return { ok: false, reason: 'busy' }
2457
+ }
2458
+ if (!this._processReady || !this._term || this._ptyExited) {
2459
+ this.emit('error', { message: 'Session not started or PTY no longer alive' })
2460
+ return { ok: false, reason: 'not_runnable' }
2461
+ }
2462
+
2463
+ this._isBusy = true
2464
+ this._messageCounter += 1
2465
+ const messageId = `${this._messageIdPrefix}-${this._messageCounter}`
2466
+ this._currentMessageId = messageId
2467
+ const startedAt = this._nowMonotonic()
2468
+ this._activeTurn = { messageId, startedAt, aborted: false, synthSeq: 0 }
2469
+ // Wedge instrumentation (#4678 follow-up): entry log for grep'ing
2470
+ // every turn from chroxy.log. Per-stage timings + completion get
2471
+ // accumulated on _activeTurn and emitted in the summary line at
2472
+ // turn finish (success or error). Together they let us reconstruct
2473
+ // where the wedge actually sits without re-instrumenting the file.
2474
+ // #4792: prefer the session-bound logger so the entry routes to the
2475
+ // correct bound dashboard client. Falls back to module-level `log`
2476
+ // only if start() hasn't run (defensive — sendMessage on an unstarted
2477
+ // session is a misuse, but the fallback keeps the diagnostic alive).
2478
+ ;(this._log || log).info(`sendMessage start (msg=${messageId} sessionId=${this._sessionId} bytes=${Buffer.byteLength(prompt || '', 'utf8')} attachments=${attachments?.length || 0})`)
2479
+
2480
+ // #4012: TUI can't accept inline multimodal blocks the way SDK/CLI
2481
+ // do, but it CAN read files via the Read tool. Materialize each
2482
+ // attachment under the per-session sink dir and append a structured
2483
+ // suffix to the prompt naming each file. Pre-fix, attachments were
2484
+ // dropped on the floor (the `_attachments` underscore was load-
2485
+ // bearing). Failure here is non-fatal: we log and proceed with the
2486
+ // unaugmented prompt so a write-fault doesn't lose the user's text.
2487
+ let promptToSend = prompt
2488
+ if (attachments?.length && this._sinkDir) {
2489
+ try {
2490
+ const baseDir = join(this._sinkDir, 'attachments')
2491
+ // #4022: record the per-turn dir up-front so cleanup runs on
2492
+ // every exit path (success, abort, hard timeout, PTY exit
2493
+ // mid-turn). materializeAttachments() creates the dir before it
2494
+ // decides whether any individual attachment is salvageable, so
2495
+ // even an "all skipped" outcome (every att.data invalid → files
2496
+ // returns []) leaves the empty dir on disk. If we only recorded
2497
+ // attachmentsDir when the suffix was truthy, that empty dir
2498
+ // would leak until destroy() rmSync'd the whole sinkDir — fine
2499
+ // for short sessions, an on-disk drip for long-lived ones.
2500
+ this._activeTurn.attachmentsDir = join(baseDir, messageId)
2501
+ const files = materializeAttachments(attachments, baseDir, messageId)
2502
+ const suffixResult = buildAttachmentsPromptSuffix(files)
2503
+ if (suffixResult.suffix) {
2504
+ promptToSend = (prompt || '') + suffixResult.suffix
2505
+ log.info(`TUI attachments materialized (msg=${messageId} count=${files.length} dir=${this._activeTurn.attachmentsDir})`)
2506
+ // #4026: cap-firing diagnostic. The whole point of
2507
+ // MAX_ATTACHMENT_SUFFIX_BYTES is to catch pathological path-
2508
+ // generation regressions (deterministic hashes, deeper base
2509
+ // dirs) before users hit the PTY's silent ~4KB truncation —
2510
+ // a quiet truncation here defeats the cap's purpose. Two
2511
+ // distinct warn lines so ops can grep for either degradation:
2512
+ // - regular truncation: some files dropped from the list
2513
+ // - bareFallback: even one entry exceeded the cap (worst)
2514
+ // #4792: same session-scoped logger fallback as sendMessage start.
2515
+ const slog = this._log || log
2516
+ if (suffixResult.bareFallback) {
2517
+ slog.warn(`TUI attachment suffix bare-fallback fired (msg=${messageId} count=${files.length} cap=${suffixResult.cap}B) — all file paths omitted from prompt suffix; agent will only see the size-cap marker. Pathological path-generation regression?`)
2518
+ } else if (suffixResult.truncated) {
2519
+ slog.warn(`TUI attachment suffix truncated (msg=${messageId} suffixBytes=${suffixResult.byteLength} cap=${suffixResult.cap}B omitted=${suffixResult.omitted} of=${files.length})`)
2520
+ }
2521
+ }
2522
+ } catch (err) {
2523
+ log.warn(`TUI attachment materialization failed (msg=${messageId}): ${err.message} — sending prompt without attachments`)
2524
+ }
2525
+ }
2526
+
2527
+ // #4010: fire stream_start the moment the turn begins, not after the
2528
+ // Stop hook arrives. This is the only signal the dashboard has for
2529
+ // `agent_busy` (event-normalizer.js:62-66 synthesizes it from
2530
+ // stream_start). Pre-fix, stream_start was deferred until the response
2531
+ // came back as one burst — fine on a normal 10-30s turn, but if the
2532
+ // TUI stalls (claude not yet at the prompt when our bytes arrive),
2533
+ // stream_start NEVER fires, the dashboard thinks the session is idle
2534
+ // even though _isBusy=true, so the Send button doesn't toggle to Stop
2535
+ // and the user has no UI escape hatch from a stuck session.
2536
+ this.emit('stream_start', { messageId })
2537
+
2538
+ // #4014/#4040: wait for the TUI to report status=idle before writing.
2539
+ // Between turns the TUI flips back to idle after the Stop hook fires
2540
+ // (it must — claude updates its own session file on every transition,
2541
+ // and `claude ps` relies on the same field). If our bytes arrive
2542
+ // mid-busy the keystrokes get dropped or queued behind the in-flight
2543
+ // turn. On the first turn this also catches the case where
2544
+ // _spawnPty's warmup window expired before claude wrote idle. We
2545
+ // still write if the probe misses — a transient FS race shouldn't
2546
+ // refuse to deliver the prompt.
2547
+ const ready = await this._waitForPrompt(ClaudeTuiSession.TURN_PROMPT_WAIT_MAX_MS)
2548
+ if (!ready && !this._ptyExited) {
2549
+ ;(this._log || log).warn(
2550
+ `TUI session file not at status=idle before turn (msg=${messageId})${this._degradedProbeSuffix()} — writing anyway\n` +
2551
+ `_outputTail dump:\n${this._outputTailLogDump()}`,
2552
+ )
2553
+ }
2554
+ if (this._ptyExited) {
2555
+ const code = this._ptyExitInfo?.exitCode
2556
+ const signal = this._ptyExitInfo?.signal
2557
+ this._finishTurnError(`Claude PTY exited before prompt write (code=${code}${signal ? ` signal=${signal}` : ''})`, messageId)
2558
+ // #5813: return the typed failure (like the up-front busy/not_runnable
2559
+ // guards) so callers that key off `result.ok === false` — e.g. the reinject
2560
+ // stop-and-wait watch-close in form-driver.js — don't have to rely on
2561
+ // _finishTurnError's side-effect to know the turn never started.
2562
+ return { ok: false, reason: 'pty_exited' }
2563
+ }
2564
+ // If the user clicked Stop during the probe wait, interrupt() has
2565
+ // already written Ctrl-C to the PTY and marked the turn aborted.
2566
+ // Writing the prompt now would queue it behind the cancel and either
2567
+ // execute against a half-reset TUI or silently desync busy state
2568
+ // (server clears busy via _finishTurnError below, but the TUI might
2569
+ // still process the bytes once it returns to prompt). Bail cleanly.
2570
+ if (this._activeTurn?.aborted) {
2571
+ this._finishTurnError('Turn aborted before prompt write', messageId)
2572
+ return { ok: false, reason: 'aborted' } // #5813: typed failure
2573
+ }
2574
+
2575
+ // #4732: reset the per-turn pre-first-output watchdog latch so the
2576
+ // upcoming `_armResultTimeout` call arms a fresh first-output timer
2577
+ // for this turn (the latch was set true when the PREVIOUS turn
2578
+ // consumed its first hook). Must happen BEFORE `_armResultTimeout`
2579
+ // below — that helper checks the latch.
2580
+ this._resetFirstOutputWatchdogForTurn()
2581
+
2582
+ try {
2583
+ // #4269: claude TUI's paste detector triggers on byte-arrival rate,
2584
+ // not DEC mode 2004 — a single bulk write of the whole prompt is
2585
+ // collapsed into "[Pasted text #1 +N lines] paste again to expand"
2586
+ // and chroxy never confirms, hanging the turn silently. The
2587
+ // shared _writePtyTextThrottled() helper writes the text one char
2588
+ // at a time with PROMPT_CHAR_DELAY_MS between each so the bytes
2589
+ // look like typed input. The bracketed-paste-disable / re-enable
2590
+ // wrap is kept as defense-in-depth for any claude version that
2591
+ // DOES honor mode 2004; the throttle is what actually fixes the
2592
+ // bug. Same helper also serves respondToQuestion() (#4278).
2593
+ const completed = await this._writePtyTextThrottled(promptToSend, {
2594
+ onAbort: () => this._finishTurnError('Turn aborted during prompt write', messageId),
2595
+ })
2596
+ // #5813: typed failure. _writePtyTextThrottled returns false for BOTH an
2597
+ // aborted turn AND a mid-write PTY exit, so report the actual cause (#5848
2598
+ // review) rather than always labelling it 'aborted'.
2599
+ if (!completed) return { ok: false, reason: this._ptyExited ? 'pty_exited' : 'aborted' }
2600
+ } catch (err) {
2601
+ this._finishTurnError(`Failed to write prompt to PTY: ${err.message}`, messageId)
2602
+ return { ok: false, reason: 'write_failed' } // #5813: typed failure
2603
+ }
2604
+
2605
+ // Arm soft + hard inactivity timers (#3920). Each new hook file the
2606
+ // poll loop drains re-arms both, so a long turn that's making
2607
+ // progress (tool calls firing, intermediate hooks) never trips them.
2608
+ // Soft fires once per silent stretch → inactivity_warning;
2609
+ // hard fires after the full window of silence → force-clear + error.
2610
+ this._armResultTimeout()
2611
+
2612
+ // #5777/#5794: on the FIRST message of each (re)spawn, schedule the submit
2613
+ // nudge. A freshly-spawned TUI sometimes reports ready before its composer
2614
+ // accepts the trailing \r, so the prompt sits typed-but-unsent. If no hook
2615
+ // output arrives within the window, _scheduleFirstTurnSubmitNudge re-sends a
2616
+ // bare \r (a no-op on an already-submitted/empty composer, a submit on a
2617
+ // stuck one). Two gates keep the blast radius minimal:
2618
+ // - #5794 (1): single-line only. A multi-line prompt takes the
2619
+ // bracketed-paste path in _writePtyTextThrottled (its own `hasNewlines`
2620
+ // check, mirrored here on the SAME promptToSend the write used), where a
2621
+ // bare \r is interpreted as a newline-in-composition / can submit a
2622
+ // partial paste — not a safe re-submit. Skip the nudge for that path.
2623
+ // - #5794 (2): first-message-per-spawn, not lifetime-first. `_messageCounter`
2624
+ // is monotonic and never reset, so the old `=== 1` gate left a post-respawn
2625
+ // wedge un-nudged. The `_firstTurnNudgedForSpawn` latch (reset in
2626
+ // _spawnPty) re-arms once per (re)spawn instead.
2627
+ const hasNewlines = /\r?\n/.test(promptToSend || '')
2628
+ if (!this._firstTurnNudgedForSpawn && !hasNewlines) {
2629
+ this._firstTurnNudgedForSpawn = true
2630
+ this._scheduleFirstTurnSubmitNudge(messageId)
2631
+ }
2632
+
2633
+ // Poll the sink dir for new hook files. mktemp-named filenames make each
2634
+ // turn's Stop / Pre / Post events distinct from previous turns'; the
2635
+ // session-level _consumedFiles Set ensures we never re-process a file
2636
+ // that an earlier turn already handled.
2637
+ const HOOK_TIMEOUT_MS = this._hardTimeoutMs
2638
+ const pollStart = this._nowMonotonic()
2639
+ let stopPayload = null
2640
+ // Wedge instrumentation (#4678 follow-up): track loop progress so
2641
+ // a wedge that manifests as "stuck waiting for stop-hook" produces
2642
+ // a heartbeat log every HOOK_HEARTBEAT_MS — without this we cannot
2643
+ // tell whether the loop is iterating but the sink dir stays empty,
2644
+ // or whether the loop itself has stopped iterating.
2645
+ let pollIters = 0
2646
+ let lastHeartbeatMs = pollStart
2647
+ // #5323 (WP-5.1) — track consumed-file count explicitly. We can no longer
2648
+ // infer progress from `_consumedFiles.size` because consumed files are now
2649
+ // unlinked + dropped from the Set in the same drain, so the Set size doesn't
2650
+ // grow. This cumulative counter drives the heartbeat/exit diagnostics.
2651
+ let totalConsumed = 0
2652
+
2653
+ const drainHookFiles = async () => {
2654
+ let entries
2655
+ try {
2656
+ entries = await this._boundedHookFs('readdir', this._sinkDir)
2657
+ } catch (err) {
2658
+ // #6178: a hung sink fs (FUSE/NFS freeze) — DON'T treat it as deletion.
2659
+ // Skip this pass and return; the while-guard re-checks HOOK_TIMEOUT_MS so
2660
+ // the turn self-terminates via the hard-timeout watchdog instead of
2661
+ // awaiting a frozen mount. Recreating the sink (below) would be wrong (the
2662
+ // dir isn't gone, it's slow) and its sync mkdir could itself block.
2663
+ if (err && err.code === 'HOOK_FS_TIMEOUT') {
2664
+ log.warn(`hook drain readdir timed out (${this._hookFsTimeoutMs}ms) — sink fs may be stuck; skipping pass`)
2665
+ return
2666
+ }
2667
+ // #5329 (IP-1): the sink lives under /tmp, which a tmpwatch sweep, a
2668
+ // tmpfs clear, or a manual rm can delete mid-turn. A silent return here
2669
+ // spins this poll loop to the hard timeout while every claude
2670
+ // `cat > <sink>/…` hook write also fails — the turn wedges with no
2671
+ // signal. Try to recover the sink (recreate the same path so hook
2672
+ // delivery resumes); fail loud if recreation itself fails.
2673
+ this._recoverSinkDir(err)
2674
+ return
2675
+ }
2676
+ // Per-drain progress counter — replaces the old `_consumedFiles.size`
2677
+ // delta, which no longer changes now that consumed files are unlinked +
2678
+ // pruned (#5323). Drives the first-output disarm + timer re-arm below.
2679
+ let drainedThisPass = 0
2680
+ // Process prefixes in causal order: pre- (tool_start) MUST fire
2681
+ // before post- (tool_result) so the dashboard can pair them via
2682
+ // toolUseId. Naive lex sort puts "post-…" before "pre-…" because
2683
+ // 'o' < 'r', which surfaced as tool_result-before-tool_start in
2684
+ // the #3902 smoke test. stop- is processed last so we drain any
2685
+ // late-arriving tool files before returning to the caller.
2686
+ const ordered = []
2687
+ for (const prefix of ['pre-', 'post-', 'stop-']) {
2688
+ for (const name of entries.sort()) {
2689
+ if (name.startsWith(prefix)) ordered.push(name)
2690
+ }
2691
+ }
2692
+ for (const name of ordered) {
2693
+ if (this._consumedFiles.has(name)) continue
2694
+ const full = join(this._sinkDir, name)
2695
+ let parsed
2696
+ try {
2697
+ // #6178: bounded + coalesced — a timeout rejects and folds into this
2698
+ // skip-and-retry (same as a partial-write/parse failure: re-read next
2699
+ // pass), and the SAME readFile is re-raced rather than re-issued.
2700
+ const raw = await this._boundedHookFs('readFile', full)
2701
+ if (raw.length === 0) continue // partial write — poll again
2702
+ parsed = JSON.parse(raw)
2703
+ } catch { continue }
2704
+ this._consumedFiles.add(name)
2705
+ drainedThisPass++
2706
+ totalConsumed++
2707
+
2708
+ if (name.startsWith('stop-')) {
2709
+ stopPayload = parsed
2710
+ } else {
2711
+ try {
2712
+ this._emitToolHookEvent(name.startsWith('pre-') ? 'PreToolUse' : 'PostToolUse', parsed, messageId)
2713
+ } catch (err) {
2714
+ log.warn(`tool hook emit failed: ${err.message}`)
2715
+ }
2716
+ }
2717
+ // #5323 (WP-5.1) — unlink the consumed hook file so the per-session sink
2718
+ // dir stays bounded over a long-lived persistent PTY (one file per turn
2719
+ // + 2 per tool call accumulate fast). On a successful unlink drop the
2720
+ // name from _consumedFiles too — the on-disk file is gone, so it can't be
2721
+ // re-read, which keeps the Set bounded as well (filenames are UUID-unique
2722
+ // so there's no cross-turn collision to guard against). If unlink fails
2723
+ // (rare), KEEP the name in _consumedFiles as the dedup guard so a later
2724
+ // readdir can't re-process it.
2725
+ try {
2726
+ // #6178: bounded — a timeout rejects into the catch below, which keeps
2727
+ // the name in _consumedFiles as the dedup guard (same as any unlink
2728
+ // failure), so a stuck unlink can't re-process the file or wedge. The
2729
+ // file then stays on disk (never re-unlinked); on a permanently stuck
2730
+ // mount that's bounded sink growth, with sweepStaleSinkDirs as backstop.
2731
+ await this._boundedHookFs('unlink', full)
2732
+ this._consumedFiles.delete(name)
2733
+ } catch { /* leave the dedup guard in place */ }
2734
+ }
2735
+ // Any new hook file = progress evidence. Re-arm timers so a turn
2736
+ // that's actively producing tool events doesn't trip the soft
2737
+ // inactivity warning (#3920). #5323: gate on the per-drain counter, NOT
2738
+ // `_consumedFiles.size` (which no longer grows — files are unlinked +
2739
+ // pruned), otherwise the disarm/re-arm would stop firing on progress.
2740
+ if (drainedThisPass > 0 && this._isBusy) {
2741
+ // #4732: a consumed hook file = first output observed for this
2742
+ // turn. Disarm the pre-first-output watchdog BEFORE the
2743
+ // re-arm below — `_armResultTimeout` would otherwise re-arm
2744
+ // it, defeating the disarm and giving the watchdog a fresh
2745
+ // window after every hook. The inter-stream `_streamStallTimeout`
2746
+ // continues to re-arm on each consumed event as before.
2747
+ this._clearFirstOutputWatchdog()
2748
+ this._armResultTimeout()
2749
+ }
2750
+ }
2751
+
2752
+ while (this._nowMonotonic() - pollStart < HOOK_TIMEOUT_MS) {
2753
+ if (this._activeTurn?.aborted) break
2754
+ if (this._ptyExited) break
2755
+ // _handleHardTimeout clears _isBusy; bail out cleanly if it fired.
2756
+ if (!this._isBusy) break
2757
+ await drainHookFiles()
2758
+ pollIters++
2759
+ // Wedge instrumentation (#4678 follow-up): if the loop has been
2760
+ // running >= HOOK_HEARTBEAT_MS since the last heartbeat with no
2761
+ // stop-hook, emit a progress line. Sized at 5s so a healthy
2762
+ // ~2-5s tool turn emits zero heartbeats while a wedge gets
2763
+ // logged every 5s with sink-dir state.
2764
+ const now = this._nowMonotonic()
2765
+ if (now - lastHeartbeatMs >= ClaudeTuiSession.HOOK_HEARTBEAT_MS) {
2766
+ lastHeartbeatMs = now
2767
+ let sinkFileCount = 0
2768
+ // #6178 (review): shares the coalesced readdir slot with the drain, so the
2769
+ // heartbeat never enqueues a second stuck readdir on a frozen mount.
2770
+ try { sinkFileCount = (await this._boundedHookFs('readdir', this._sinkDir)).length } catch {}
2771
+ log.info(`hookPoll heartbeat (msg=${messageId} iters=${pollIters} elapsedMs=${now - pollStart} sinkFiles=${sinkFileCount} consumed=${totalConsumed} stopFound=${stopPayload ? 'yes' : 'no'})`)
2772
+ }
2773
+ if (stopPayload) break
2774
+ await new Promise((r) => setTimeout(r, 150))
2775
+ }
2776
+ // Wedge instrumentation (#4678 follow-up): always log the loop's
2777
+ // exit shape — whether it broke on stopPayload, abort, ptyExited,
2778
+ // !isBusy, or timeout. Pair with sendMessage's final summary to
2779
+ // reconstruct the wedge stage post-hoc.
2780
+ log.info(`hookPoll exit (msg=${messageId} iters=${pollIters} elapsedMs=${this._nowMonotonic() - pollStart} consumed=${totalConsumed} stopFound=${stopPayload ? 'yes' : 'no'} aborted=${this._activeTurn?.aborted ? 'yes' : 'no'} ptyExited=${this._ptyExited ? 'yes' : 'no'} stillBusy=${this._isBusy ? 'yes' : 'no'})`)
2781
+
2782
+ if (!stopPayload) {
2783
+ let reason
2784
+ if (this._activeTurn?.aborted) {
2785
+ reason = 'turn aborted'
2786
+ } else if (this._ptyExited) {
2787
+ const code = this._ptyExitInfo?.exitCode
2788
+ const signal = this._ptyExitInfo?.signal
2789
+ reason = `Claude PTY exited mid-turn (code=${code}${signal ? ` signal=${signal}` : ''})`
2790
+ } else if (!this._isBusy) {
2791
+ // _handleHardTimeout already cleared state + emitted its own
2792
+ // error. Just return without double-firing.
2793
+ return
2794
+ } else {
2795
+ reason = `Stop hook timeout after ${Math.round((this._nowMonotonic() - pollStart) / 1000)}s`
2796
+ }
2797
+ const tail = this._outputTailDiagnostic()
2798
+ this._finishTurnError(tail ? `${reason}\nTUI output tail:\n${tail}` : reason, messageId)
2799
+ return
2800
+ }
2801
+
2802
+ const duration = this._nowMonotonic() - startedAt
2803
+ const text = typeof stopPayload.last_assistant_message === 'string' ? stopPayload.last_assistant_message : ''
2804
+
2805
+ // Deliver the response as a single stream burst so the dashboard renders
2806
+ // one assistant bubble (matches CliSession's event shape on Claude's side).
2807
+ // stream_start was already emitted at turn start (#4010) — don't fire it
2808
+ // again here or the dashboard creates two assistant bubbles for one turn.
2809
+ if (text) this.emit('stream_delta', { messageId, delta: text })
2810
+ this.emit('stream_end', { messageId })
2811
+
2812
+ // #4628: sweep any tool_starts whose PostToolUse hook never fired
2813
+ // BEFORE emitting result. _emitResult does this in one step. The
2814
+ // sweep ensures the synthetic tool_result is broadcast first, so
2815
+ // the dashboard's activeTools clears as part of the same turn-end
2816
+ // burst rather than zombifying until next chroxy restart.
2817
+ this._emitResult({
2818
+ // #4072: `cost: null` (not 0) is the chroxy convention for
2819
+ // "subscription-billed provider, cost not measured". The session-
2820
+ // manager `_trackCost`/`_trackUsage` gate is
2821
+ // `typeof data.cost === 'number'`, so null skips the cumulative
2822
+ // accumulator and keeps `cumulativeUsage` at zero — that's the
2823
+ // signal the dashboard / app uses to suppress the cost badge.
2824
+ cost: null, // not exposed by Stop hook in MVP
2825
+ duration,
2826
+ usage: null, // not exposed by Stop hook in MVP
2827
+ sessionId: this._sessionId,
2828
+ }, 'stop_hook_fired_without_post_hook')
2829
+
2830
+ // Wedge instrumentation (#4678 follow-up): summary log on success
2831
+ // path, matching the one _finishTurnError emits on error paths so
2832
+ // every turn lands one grep-able line regardless of outcome.
2833
+ this._logSendMessageSummary('success')
2834
+ // Per-turn teardown: inactivity timers (#3920, #4638, #4732), pre-first-output
2835
+ // watchdog, per-turn attachment dir (#4022 — Read results are already in the
2836
+ // model's context window), the busy-state triple, and — previously MISSING on
2837
+ // this path — the AskUserQuestion sibling lock + stall watchdogs (#4604/#5319).
2838
+ // Shared with _finishTurnError so the two can't re-diverge. See helper doc.
2839
+ this._clearTurnEndState()
2840
+ }
2841
+
2842
+ /**
2843
+ * #4022: rmSync the per-turn attachment directory if the turn
2844
+ * materialized any files. No-op when the turn had no attachments
2845
+ * (the common case). rmSync uses `force: true` so a missing dir
2846
+ * (already cleaned up by an earlier path, or never created) doesn't
2847
+ * throw. The session-level _sinkDir cleanup in destroy() remains as
2848
+ * a backstop for any cleanup we miss here.
2849
+ */
2850
+ _cleanupTurnAttachments(activeTurn) {
2851
+ const dir = activeTurn?.attachmentsDir
2852
+ if (!dir) return
2853
+ try {
2854
+ rmSync(dir, { recursive: true, force: true })
2855
+ } catch (err) {
2856
+ log.warn(`per-turn attachment cleanup failed (${dir}): ${err.message}`)
2857
+ }
2858
+ }
2859
+
2860
+ /**
2861
+ * Translate one PreToolUse / PostToolUse hook payload into BaseSession tool
2862
+ * events. Hook payloads carry tool_use_id (when Claude Code provides it),
2863
+ * tool_name, tool_input, and on Post a tool_response. The dashboard pairs
2864
+ * `tool_start` with `tool_result` by toolUseId so each tool call renders as
2865
+ * one collapsible bubble.
2866
+ *
2867
+ * tool_use_id is sometimes absent from hook payloads (older claude
2868
+ * builds, certain MCP tools); when missing we synthesize a stable id
2869
+ * from messageId + a per-turn sequence so the pair still matches.
2870
+ *
2871
+ * @param {'PreToolUse' | 'PostToolUse'} kind
2872
+ * @param {object} payload — parsed hook JSON
2873
+ * @param {string} messageId — the current turn's wire-level messageId
2874
+ */
2875
+ _emitToolHookEvent(kind, payload, messageId) {
2876
+ if (!payload || typeof payload !== 'object') return
2877
+ const toolName = typeof payload.tool_name === 'string' ? payload.tool_name : 'unknown'
2878
+ let toolUseId = typeof payload.tool_use_id === 'string' && payload.tool_use_id.length > 0
2879
+ ? payload.tool_use_id
2880
+ : null
2881
+ if (!toolUseId) {
2882
+ // Synthesize a stable id when the hook payload omits tool_use_id
2883
+ // (older claude builds, certain MCP tools). Increment ONLY on
2884
+ // PreToolUse; reuse the current value on the matching PostToolUse
2885
+ // so the dashboard can pair tool_start with tool_result by
2886
+ // toolUseId (#3923). Breaks if tool calls overlap or Pre fires
2887
+ // without a Post, but strictly better than the previous always-
2888
+ // mismatch behaviour. The common path — payload carries
2889
+ // tool_use_id from claude — is unaffected.
2890
+ if (!this._activeTurn) return
2891
+ if (kind === 'PreToolUse') {
2892
+ this._activeTurn.synthSeq = (this._activeTurn.synthSeq || 0) + 1
2893
+ }
2894
+ toolUseId = `${messageId}-tool-${this._activeTurn.synthSeq || 1}`
2895
+ }
2896
+
2897
+ if (kind === 'PreToolUse') {
2898
+ // #5798: observability-only — did the model honor the reinject "stop and
2899
+ // wait" steer? When a flag-on multi-select reinject fired, the FormDriver
2900
+ // opened a watch window (this._reinjectStopWaitWatch). The model SHOULD
2901
+ // have ended its turn so the reinjected selection becomes a fresh turn; a
2902
+ // PreToolUse arriving while the window is still open means it kept going
2903
+ // and tool-called instead. Log a loud WARN with greppable fields, then
2904
+ // clear the marker (one-shot — log once per reinject). The window is also
2905
+ // cleared on the reinjected turn's first consumed hook
2906
+ // (_clearFirstOutputWatchdog) and on teardown/destroy/pty-gone, so this
2907
+ // fires ONLY for a tool_use in the gap between the deny and the reinjected
2908
+ // turn's start.
2909
+ //
2910
+ // Heuristic + honest false-pos/neg profile (this is a tunable measurement
2911
+ // aid, not a gate): the detector is "any PreToolUse observed while the
2912
+ // post-reinject-deny watch is open". FALSE POSITIVE risk: a leftover
2913
+ // pre-*.json hook file from the DENIED turn that drains after the marker is
2914
+ // set could trip the WARN even though it predates the reinject (the denied
2915
+ // form is denied before it renders, so no PostToolUse is expected, but a
2916
+ // racing pre- file is theoretically possible). FALSE NEGATIVE risk: if the
2917
+ // reinjected turn's own first legitimate output is a non-tool hook (or its
2918
+ // first PreToolUse is preceded by another consumed hook in the same drain
2919
+ // pass that clears the window first), a later "didn't stop" tool_use would
2920
+ // be missed. Both are acceptable for a default-on gating signal — count the
2921
+ // greppable token and tune later if the rate is noisy.
2922
+ if (this._reinjectStopWaitWatch) {
2923
+ const watch = this._reinjectStopWaitWatch
2924
+ this._reinjectStopWaitWatch = null
2925
+ const deltaMs = Math.round(this._nowMonotonic() - watch.at)
2926
+ ;(this._log || log).warn(`reinject stop-and-wait NOT honored (#5798, reinject_stop_wait_violation): model emitted tool_use after a multi-select reinject deny instead of stopping | deniedToolUseId=${watch.deniedToolUseId || '?'} newTool=${toolName} newToolUseId=${toolUseId} deltaMs=${deltaMs}`)
2927
+ }
2928
+ // #4307: stash the command text so the matching PostToolUse can
2929
+ // record the resulting shellId with the original command. Same
2930
+ // behaviour as sdk-session.js _handleToolUseBlock — keeps TUI
2931
+ // parity for the dashboard "waiting on …" chip.
2932
+ if (isRunInBackgroundInput(toolName, payload.tool_input)) {
2933
+ const cmd = typeof payload.tool_input?.command === 'string'
2934
+ ? payload.tool_input.command : ''
2935
+ this._pendingBackgroundCommands.set(toolUseId, cmd)
2936
+ }
2937
+ // #4307: a BashOutput call means the agent has acknowledged the
2938
+ // backgrounded shell. Clear the pending entry so the session is
2939
+ // no longer reported as waiting (the agent saw the output or is
2940
+ // about to act on it — either way our pending model is stale).
2941
+ const bashOutputShellId = parseBashOutputShellId(toolName, payload.tool_input)
2942
+ if (bashOutputShellId) {
2943
+ this.clearBackgroundShell(bashOutputShellId)
2944
+ }
2945
+ this.emit('tool_start', {
2946
+ messageId: toolUseId,
2947
+ toolUseId,
2948
+ tool: toolName,
2949
+ input: payload.tool_input ?? null,
2950
+ })
2951
+ // #4628: track this tool_start so _emitResult can sweep it on
2952
+ // turn-end if the matching PostToolUse hook is never written
2953
+ // (the upstream failure mode observed in #4628).
2954
+ this._trackToolStart(toolUseId, toolName)
2955
+ // #4278: AskUserQuestion in TUI sessions previously had no special
2956
+ // path — the tool_use bubble appeared in the chat with no
2957
+ // interactive way to answer, and claude sat on its own TTY-style
2958
+ // prompt waiting for stdin until the inactivity hard timeout. Now
2959
+ // we ALSO emit user_question (same shape sdk-session emits) so
2960
+ // the dashboard renders its QuestionPrompt UI. The user's answer
2961
+ // arrives via respondToQuestion() which writes it back to the PTY.
2962
+ //
2963
+ // tool_start above still fires so the existing tool-pairing path
2964
+ // works once PostToolUse arrives — we accept the duplicate display
2965
+ // (collapsed bubble + standalone QuestionPrompt) as MVP; #4279
2966
+ // makes the bubble usefully expandable so this is acceptable.
2967
+ if (toolName === 'AskUserQuestion') {
2968
+ const questions = (payload.tool_input && Array.isArray(payload.tool_input.questions))
2969
+ ? payload.tool_input.questions
2970
+ : []
2971
+ // #4290 / #4604 Chunk B: stash the FULL questions array (not just
2972
+ // q[0].options) so respondToQuestion can drive multi-question
2973
+ // forms keystroke-by-keystroke. `options` is kept on the entry
2974
+ // for back-compat with pre-Chunk-B tests/callers that read
2975
+ // `_pendingUserAnswer.options` directly — it always points at
2976
+ // questions[0].options (the only question the single-q happy
2977
+ // path drives).
2978
+ const options = (questions[0] && Array.isArray(questions[0].options))
2979
+ ? questions[0].options
2980
+ : []
2981
+ this._pendingUserAnswer = { toolUseId, questions, options }
2982
+ // #4604: surface the AskUserQuestion shape in chroxy.log so the
2983
+ // multi-question wedge condition is greppable. The bug was
2984
+ // diagnosed via /tmp/.../pre-*.json spelunking — never again.
2985
+ const questionCount = questions.length
2986
+ // #4828: session-scoped — runs strictly post-start when `this._log`
2987
+ // is cached. Falls back to module-level `log` only defensively.
2988
+ ;(this._log || log).info(`AskUserQuestion pending: tool=${toolUseId} questions=${questionCount} options.q1=${options.length}`)
2989
+ if (questionCount > 1) {
2990
+ // #4604 Chunk B note: kept the historical "not yet supported"
2991
+ // wording so existing test guards (regex on this string) keep
2992
+ // matching. The driver IS now multi-question-aware — what's
2993
+ // still unsupported is the dashboard sending an answersMap
2994
+ // covering all N questions on every client build. The
2995
+ // back-compat default-to-option-1 fallback in respondToQuestion
2996
+ // means even old dashboards no longer wedge the session, just
2997
+ // pick defaults the user can re-prompt past.
2998
+ // #4828: session-scoped.
2999
+ ;(this._log || log).warn(`AskUserQuestion has ${questionCount} questions — multi-question forms are not yet supported (see #4604). Only question 1 will be answered.`)
3000
+ // #4653: surface the deny to the user. The bash permission-hook
3001
+ // returns `permissionDecision: deny` for this exact payload
3002
+ // shape (questions.length > 1), so this server-side mirror
3003
+ // event reports the same decision through the WS wire. Without
3004
+ // it, the deny is invisible — the user wonders if the model is
3005
+ // being clever (asking one at a time naturally) or if chroxy
3006
+ // intervened. Per-toolUseId so the dashboard can dedup repeats
3007
+ // when claude TUI re-emits the same multi-q payload (a known
3008
+ // failure mode pre-#4668).
3009
+ // #5320 (WP-3.3) — isolate this emit. A synchronous throw from a
3010
+ // listener here would skip the `user_question` emit + backstop suspend
3011
+ // below, leaving `_pendingUserAnswer` set with no dashboard prompt and
3012
+ // no recovery — an orphaned pending. Swallow + log so the question
3013
+ // still surfaces.
3014
+ try {
3015
+ this.emit('multi_question_intervention', {
3016
+ toolUseId,
3017
+ questionCount,
3018
+ reason: 'multi_question',
3019
+ timestamp: Date.now(), // #5332: wall-clock epoch — a payload field for clients, not a duration
3020
+
3021
+ })
3022
+ } catch (err) {
3023
+ ;(this._log || log).warn(`multi_question_intervention listener threw (continuing): ${err?.message || err}`)
3024
+ }
3025
+ }
3026
+ this.emit('user_question', { toolUseId, questions })
3027
+ // #5318 (WP-3.1) — we're now blocked on a human answer. Suspend the
3028
+ // turn backstops immediately rather than waiting for the next drain-loop
3029
+ // _armResultTimeout(); the _armResultTimeout() guard keeps them suspended
3030
+ // across any subsequent re-arm until the answer's PostToolUse clears the
3031
+ // pending entry.
3032
+ this._suspendBackstopsForPendingQuestion()
3033
+ // #5792: a DENIED shape (multi-question OR any multi-select question) is
3034
+ // rejected at the permission hook, so claude Stops with no PostToolUse
3035
+ // and no answer ever arrives — the pending entry above would leak past
3036
+ // turn-end (the Stop success path keeps pending). Arm a reaper to drop
3037
+ // it. A legitimate single single-select is NOT a denied shape: it gets a
3038
+ // PostToolUse (or its own respondToQuestion stall watchdog) and is left
3039
+ // untouched.
3040
+ const isDeniedShape = questionCount > 1 || questions.some((q) => q && q.multiSelect === true)
3041
+ if (isDeniedShape) {
3042
+ this._armDeniedQuestionReaper(toolUseId)
3043
+ }
3044
+ }
3045
+ return
3046
+ }
3047
+
3048
+ // #4278 (PostToolUse half): claude resolved its own AskUserQuestion
3049
+ // prompt — either via the answer chroxy wrote in respondToQuestion()
3050
+ // or via the underlying terminal multiplexer if a human typed into
3051
+ // the same PTY. Either way, clear the pending state so the next
3052
+ // user_question_response doesn't write into a stale context.
3053
+ //
3054
+ // #4668: clear only THIS specific tool_use's entry from the pending
3055
+ // Map, not every entry. Pre-#4668 chroxy used a single field so
3056
+ // clearing was all-or-nothing; with the Map there may be sibling
3057
+ // pending answers from other tool_uses in the same turn that
3058
+ // shouldn't be wiped when this one completes.
3059
+ //
3060
+ // #4689: clear by the resolved local `toolUseId`, not by raw
3061
+ // `payload.tool_use_id`. When the hook payload omits `tool_use_id`
3062
+ // (older claude builds, certain MCP tools), `_emitToolHookEvent`
3063
+ // synthesizes a stable id at line ~1340 and the PreToolUse branch
3064
+ // above stores the pending entry under THAT synthesized id. Gating
3065
+ // cleanup on `payload.tool_use_id` would skip the clear for those
3066
+ // builds and leak Map entries indefinitely.
3067
+ if (toolName === 'AskUserQuestion' && toolUseId) {
3068
+ this._clearPendingAnswerByToolUseId(toolUseId)
3069
+ }
3070
+ // #4669 cleanup: drop the askuserquestion-active sibling lock for THIS
3071
+ // tool_use's PostToolUse (the original PostToolUse hook in
3072
+ // writeHookSettings() does this via tee/grep/rm — duplicated here for
3073
+ // the defensive path where the hook script's cleanup didn't run, e.g.
3074
+ // when claude TUI emitted PostToolUse but the hook chain raced with
3075
+ // turn teardown). Cheap idempotent rm via the canonical helper so
3076
+ // teardown/cleanup behaviour stays consistent (#4692).
3077
+ if (toolName === 'AskUserQuestion') {
3078
+ this._clearAskUserQuestionLock()
3079
+ }
3080
+ // #4604: PostToolUse means claude accepted the answer (single-question
3081
+ // happy path). Cancel THIS tool's stall watchdog so it doesn't fire a
3082
+ // spurious ASK_USER_QUESTION_STALL error 30s later. #5319 (WP-3.2): clear
3083
+ // only this toolUseId's watchdog — a parallel sibling's watchdog stays armed.
3084
+ if (toolName === 'AskUserQuestion' && toolUseId) {
3085
+ this._clearAskUserQuestionWatchdog(toolUseId)
3086
+ }
3087
+
3088
+ // PostToolUse — extract a string-ish result for the dashboard.
3089
+ let result = ''
3090
+ let truncated = false
3091
+ const resp = payload.tool_response
3092
+ if (typeof resp === 'string') {
3093
+ result = resp
3094
+ } else if (resp && typeof resp === 'object') {
3095
+ // Most Claude tools return { stdout, stderr } or { content: [...] }.
3096
+ // Stringify and let the existing tool-result truncation handle size.
3097
+ try { result = JSON.stringify(resp) } catch { result = String(resp) }
3098
+ }
3099
+ const MAX = 10240 // mirror tool-result.js MAX_TOOL_RESULT_SIZE
3100
+ if (result.length > MAX) {
3101
+ result = result.slice(0, MAX)
3102
+ truncated = true
3103
+ }
3104
+
3105
+ this.emit('tool_result', {
3106
+ toolUseId,
3107
+ result,
3108
+ truncated,
3109
+ })
3110
+ // #4628: matching tool_start resolved — drop from the in-flight map
3111
+ // so _emitResult's sweep doesn't double-emit a synthetic for it.
3112
+ this._trackToolResult(toolUseId)
3113
+
3114
+ // #4307: scan PostToolUse output for the canonical "Command running
3115
+ // in background with ID: <id>" pattern. The PostToolUse hook
3116
+ // payload runs through stringify above, so the same regex SDK uses
3117
+ // matches against the resulting JSON (the shellId pattern is
3118
+ // unique enough that a false positive on stringified-quoted text
3119
+ // is improbable). Pull the command stashed at PreToolUse so the
3120
+ // pending-shell entry carries it. Note we parse from the
3121
+ // post-truncation text intentionally: the canonical message is
3122
+ // ~60 chars and lands at the FRONT of the response, so truncation
3123
+ // never strips it (and if it ever did we'd accept that — the
3124
+ // result event already carries truncated=true, the dashboard chip
3125
+ // would just lack the command).
3126
+ const shellId = parseBackgroundShellId(result)
3127
+ if (shellId) {
3128
+ const command = this._pendingBackgroundCommands.get(toolUseId) || ''
3129
+ this._pendingBackgroundCommands.delete(toolUseId)
3130
+ // #5177: capture the output file path so the completion sweep can reap
3131
+ // the shell on quiescence without an explicit BashOutput poll.
3132
+ const outputPath = parseBackgroundShellOutputPath(result)
3133
+ this.trackBackgroundShell({ shellId, command, outputPath })
3134
+ }
3135
+ }
3136
+
3137
+ /**
3138
+ * Wedge instrumentation (#4678 follow-up): one-line per-turn summary
3139
+ * with all the per-stage timings accumulated on _activeTurn during
3140
+ * sendMessage. Called from both the success path and _finishTurnError
3141
+ * so every turn ends with the same grep-able shape regardless of
3142
+ * outcome. Reads from _activeTurn; safe to call when it is null.
3143
+ */
3144
+ _logSendMessageSummary(reason) {
3145
+ const turn = this._activeTurn
3146
+ if (!turn) {
3147
+ log.info(`sendMessage done (msg=none reason=${reason})`)
3148
+ return
3149
+ }
3150
+ const duration = this._nowMonotonic() - turn.startedAt
3151
+ log.info(`sendMessage done (msg=${turn.messageId} reason=${reason} duration=${duration}` +
3152
+ ` waitForPromptMs=${turn.waitForPromptMs ?? 'n/a'} ready=${turn.waitForPromptReady ?? 'n/a'} sawStatus=${turn.waitForPromptSawStatus ?? 'n/a'}` +
3153
+ ` writePath=${turn.writePath ?? 'n/a'} writeMs=${turn.writeMs ?? 'n/a'} writeBytes=${turn.writeBytes ?? 'n/a'} writeCompleted=${turn.writeCompleted ?? 'n/a'})`)
3154
+ }
3155
+
3156
+ /**
3157
+ * #4642: observability-only invariant check. Every `sendMessage` sets
3158
+ * `_isBusy=true` AND `_currentMessageId` together (lines 848/851), and
3159
+ * every teardown path clears them together. If a teardown site ever
3160
+ * observes `_isBusy=true` with `_currentMessageId=null`, the session
3161
+ * is in a state the construction contract forbids — the `if(messageId)`
3162
+ * guards in `_finishTurnError`, `_handleHardTimeout`,
3163
+ * `_handleStreamStall`, and `_onAskUserQuestionStall` would silently
3164
+ * skip `stream_end`, recreating the wedge mode #4638 fixed.
3165
+ *
3166
+ * Cheap (one warn line on violation, no-op otherwise) defensive
3167
+ * instrumentation so a future regression that breaks the invariant
3168
+ * surfaces in logs rather than as a wedge only triageable from
3169
+ * screenshots. Callsite tag is grep-able so an operator can identify
3170
+ * which teardown path observed the corruption.
3171
+ */
3172
+ _assertBusyHasMessageId(callsite) {
3173
+ if (this._isBusy && !this._currentMessageId) {
3174
+ log.warn(
3175
+ `[invariant violation] ${callsite}: _isBusy=true but _currentMessageId=null — ` +
3176
+ `construction contract requires both set together (sendMessage) or both cleared together (teardown). ` +
3177
+ `Silently skipping stream_end here would recreate the #4638 wedge.`,
3178
+ )
3179
+ }
3180
+ }
3181
+
3182
+ /**
3183
+ * Common per-turn teardown shared by the success path and `_finishTurnError`
3184
+ * (audit P1-1). Both previously hand-rolled these clears and the success path
3185
+ * had DRIFTED — it omitted the AskUserQuestion sibling-lock clear and the
3186
+ * stall-watchdog clear, so a Stop-hook success whose PostToolUse never fired
3187
+ * could (a) leak the `askuserquestion-active` lock and spuriously deny the
3188
+ * NEXT turn's question inside the 60s stale-reclaim window (#4604), and
3189
+ * (b) leave an armed 30s watchdog that could tear down a later unrelated busy
3190
+ * turn. Routing both paths through one helper keeps them from re-diverging.
3191
+ *
3192
+ * Owns: the inactivity timers, the pre-first-output watchdog, the per-turn
3193
+ * attachment dir (cleaned BEFORE `_activeTurn` is nulled so it still has the
3194
+ * dir), the busy-state triple, the AskUserQuestion sibling lock, and the
3195
+ * per-toolUseId stall watchdogs.
3196
+ *
3197
+ * Deliberately does NOT call `_pendingUserAnswers_clearAll()`: neither caller
3198
+ * issues Ctrl-C, so a sibling AskUserQuestion answer already on the wire can
3199
+ * still validly consume its entry (#4802). The Ctrl-C / kill paths
3200
+ * (`_teardownTurn`, `interrupt`, `destroy`) clear pending answers themselves.
3201
+ *
3202
+ * DOES clear `_pendingBackgroundCommands` — the ephemeral intra-turn
3203
+ * tool_use→command lookup (#4307). Per its base-session contract that map is
3204
+ * dropped every turn (CLI/SDK do so via `_clearMessageState`): once a turn
3205
+ * ends, any run_in_background `tool_use` that never saw its result this turn is
3206
+ * stranded, and the agent re-emits a fresh `tool_use` next turn if it still
3207
+ * cares. This is NOT the cross-turn "waiting on background shell" state — that
3208
+ * lives in `_backgroundShellTracker` (transient-by-design, quiesced
3209
+ * separately) and is untouched here. Leaving the map uncleared per-turn was
3210
+ * the leak audit P1-1 flagged: ClaudeTuiSession is the only subclass that
3211
+ * didn't run the base per-turn reset.
3212
+ */
3213
+ _clearTurnEndState() {
3214
+ if (this._resultTimeout) { clearTimeout(this._resultTimeout); this._resultTimeout = null }
3215
+ if (this._hardTimeout) { clearTimeout(this._hardTimeout); this._hardTimeout = null }
3216
+ if (this._streamStallTimeout) { clearTimeout(this._streamStallTimeout); this._streamStallTimeout = null }
3217
+ this._clearFirstOutputWatchdog()
3218
+ this._cleanupTurnAttachments(this._activeTurn)
3219
+ this._activeTurn = null
3220
+ this._isBusy = false
3221
+ this._currentMessageId = null
3222
+ this._clearAskUserQuestionLock()
3223
+ this._clearAllAskUserQuestionWatchdogs()
3224
+ this._pendingBackgroundCommands.clear()
3225
+ }
3226
+
3227
+ _finishTurnError(message, callerMessageId) {
3228
+ this._assertBusyHasMessageId('_finishTurnError')
3229
+ this._logSendMessageSummary('error')
3230
+ // #4010: balance the early stream_start with stream_end + result so the
3231
+ // dashboard's busy state clears (event-normalizer.js:215 synthesizes
3232
+ // agent_idle from result). Without this, an aborted/failed TUI turn
3233
+ // leaves the Send button toggled to Stop indefinitely.
3234
+ //
3235
+ // Prefer the caller-supplied messageId so a PTY-exit-mid-turn race
3236
+ // (onExit nulls _currentMessageId before the poll loop falls through
3237
+ // to here) still pairs stream_end with the stream_start we opened.
3238
+ // Without that fallback, the if(messageId) guard would silently skip
3239
+ // stream_end, leaving session-message-history._pendingStreams holding
3240
+ // the entry until destroy(). Read messageId/duration BEFORE the teardown
3241
+ // helper nulls the turn fields.
3242
+ const messageId = callerMessageId || this._currentMessageId
3243
+ const duration = this._activeTurn ? this._nowMonotonic() - this._activeTurn.startedAt : 0
3244
+ if (messageId) this.emit('stream_end', { messageId })
3245
+ this.emit('error', { message })
3246
+ // #4072: subscription-billed → cost: null so SessionManager skips
3247
+ // accumulation. See companion sites above.
3248
+ // #4628: sweep orphan tool_starts before result so the dashboard's
3249
+ // activeTools clears as part of the same error burst.
3250
+ this._emitResult(
3251
+ { cost: null, duration, usage: null, sessionId: this._sessionId },
3252
+ 'turn_finished_with_error',
3253
+ )
3254
+ // Shared per-turn teardown: timers, pre-first-output watchdog, attachment
3255
+ // dir (#4022), the busy-state triple, the AskUserQuestion sibling lock
3256
+ // (#4604), and the per-toolUseId stall watchdogs (#5319). The emits above
3257
+ // are synchronous, so deferring the timer clears into the helper (vs the
3258
+ // old before-emit position) cannot let a timer fire in between. The helper
3259
+ // intentionally does NOT clear `_pendingUserAnswers` — see its doc (#4286 /
3260
+ // #4802): this path issues no Ctrl-C, so a sibling answer already on the
3261
+ // wire can still validly consume its entry; the Ctrl-C/kill paths
3262
+ // (`_teardownTurn` / `interrupt()` / `destroy()`) clear pending answers.
3263
+ this._clearTurnEndState()
3264
+ }
3265
+
3266
+ /**
3267
+ * Return the tail of recent PTY output suitable for inclusion in an
3268
+ * error message, or '' when there's nothing useful. Collapses
3269
+ * whitespace runs so the diagnostic is compact (#3919).
3270
+ */
3271
+ _outputTailDiagnostic() {
3272
+ if (!this._outputTail) return ''
3273
+ // #5322 (WP-4.2, security) — this tail rides into `error` events that fan
3274
+ // out to clients and the System tab, so redact any token-shaped run (pasted
3275
+ // or echoed OAuth token / API key) before it leaves the process.
3276
+ // #5357 review — redact BEFORE slicing: a token straddling the
3277
+ // PTY_TAIL_DIAGNOSTIC_BYTES boundary must be matched in full (and collapse
3278
+ // to [REDACTED]) rather than leaving a trailing fragment the regex can't
3279
+ // catch. The slice then bounds the already-scrubbed string.
3280
+ return redactSensitive(this._outputTail)
3281
+ .slice(-ClaudeTuiSession.PTY_TAIL_DIAGNOSTIC_BYTES)
3282
+ .replace(/[\r\n]+/g, '\n')
3283
+ .replace(/[ \t]{2,}/g, ' ')
3284
+ .trim()
3285
+ }
3286
+
3287
+ /**
3288
+ * Arm (or re-arm) the soft + hard inactivity + stream-stall timers
3289
+ * (#3920, #4638).
3290
+ *
3291
+ * Soft: fires `inactivity_warning` after _resultTimeoutMs of silence.
3292
+ * Session stays alive — the dashboard renders a check-in chip.
3293
+ *
3294
+ * Hard: force-clears busy state + emits `error` after _hardTimeoutMs.
3295
+ * Last-resort kill path for sessions that are genuinely stuck.
3296
+ *
3297
+ * Stream-stall: active-recovery for the `stream_start fired then
3298
+ * nothing` wedge — claude TUI accepting the prompt write, emitting
3299
+ * nothing, never returning a Stop hook. #4467 wired the same timer
3300
+ * into CliSession + SdkSession; the TUI provider was the outlier, so
3301
+ * this wedge surfaced as a "Working…" banner that ticked indefinitely.
3302
+ * Default lives in `BaseSession.DEFAULT_STREAM_STALL_TIMEOUT_MS`; only
3303
+ * armed when `_streamStallTimeoutMs > 0` (operators can disable via 0).
3304
+ *
3305
+ * All three are cleared+re-armed on each call, so any progress signal
3306
+ * (new hook file processed) resets every window. Mirrors
3307
+ * `CliSession._armResultTimeout()`.
3308
+ */
3309
+ /**
3310
+ * #5318 (WP-3.1) — suspend the "claude went silent" backstops while a human is
3311
+ * answering an AskUserQuestion: the soft-inactivity, stream-stall, and
3312
+ * pre-first-output timers. When a question is pending the HUMAN is the
3313
+ * bottleneck, not claude, so these would only fire a misleading
3314
+ * force-cancel / stall error / check-in chip mid-answer. The dedicated
3315
+ * per-toolUseId `_askUserQuestionWatchdogs` (armed in respondToQuestion) still
3316
+ * recover a genuinely wedged form after the answer is written.
3317
+ *
3318
+ * Deliberately does NOT touch the HARD cap (`_hardTimeout`): that 2h
3319
+ * last-resort backstop stays armed even across a pending question, so a human
3320
+ * who walks away and never answers still gets force-cleared eventually (and
3321
+ * `_handleHardTimeout` keeps its existing pending-answer cleanup). Idempotent.
3322
+ */
3323
+ _suspendBackstopsForPendingQuestion() {
3324
+ if (this._resultTimeout) { clearTimeout(this._resultTimeout); this._resultTimeout = null }
3325
+ if (this._streamStallTimeout) { clearTimeout(this._streamStallTimeout); this._streamStallTimeout = null }
3326
+ // Disarms + latches the per-turn first-output watchdog. By the time a
3327
+ // question is pending the first output (the tool_use) has already arrived,
3328
+ // so the watchdog is moot for the rest of this turn anyway.
3329
+ this._clearFirstOutputWatchdog()
3330
+ }
3331
+
3332
+ _armResultTimeout() {
3333
+ if (this._resultTimeout) clearTimeout(this._resultTimeout)
3334
+ if (this._hardTimeout) clearTimeout(this._hardTimeout)
3335
+ if (this._streamStallTimeout) clearTimeout(this._streamStallTimeout)
3336
+ this._resultTimeout = null
3337
+ this._hardTimeout = null
3338
+ this._streamStallTimeout = null
3339
+ // Hard cap ALWAYS arms — it's the last-resort backstop and stays live even
3340
+ // while an AskUserQuestion answer is pending (a human who never answers for
3341
+ // hours still gets force-cleared). #5318 suspends only the silence-detecting
3342
+ // backstops below.
3343
+ this._hardTimeout = setTimeout(() => {
3344
+ this._hardTimeout = null
3345
+ this._handleHardTimeout()
3346
+ }, this._hardTimeoutMs)
3347
+ // #5318 (WP-3.1) — while an AskUserQuestion answer is pending, keep the
3348
+ // silence backstops suspended even though hook drains (or a defensive
3349
+ // re-arm) call through here. Resuming is automatic: PostToolUse clears the
3350
+ // pending entry, and the next drain-loop _armResultTimeout() falls through.
3351
+ if (this._pendingUserAnswers.size > 0) {
3352
+ this._suspendBackstopsForPendingQuestion()
3353
+ return
3354
+ }
3355
+ this._resultTimeout = setTimeout(() => {
3356
+ this._resultTimeout = null
3357
+ this._handleInactivityWarning()
3358
+ }, this._resultTimeoutMs)
3359
+ // #4638: only arm if configured > 0 (operators can disable via 0).
3360
+ if (this._streamStallTimeoutMs > 0) {
3361
+ this._streamStallTimeout = setTimeout(() => {
3362
+ this._streamStallTimeout = null
3363
+ this._handleStreamStall()
3364
+ }, this._streamStallTimeoutMs)
3365
+ }
3366
+ // #4732: first-output watchdog. Independent from the inter-stream
3367
+ // stall timer above — that one only re-arms BETWEEN hook events, so
3368
+ // a turn where claude TUI accepts the prompt and emits zero hooks
3369
+ // gets no protection from it. The first-output timer arms once per
3370
+ // turn here, disarms on the first consumed hook event via
3371
+ // `_clearFirstOutputWatchdog()`, and on fire calls
3372
+ // `_handleFirstOutputTimeout` which routes through `_teardownTurn`
3373
+ // with the stream_stall error code so the dashboard chip surfaces
3374
+ // through the same wire path. 0 disables.
3375
+ this._armFirstOutputWatchdog()
3376
+ }
3377
+
3378
+ /**
3379
+ * #4732: arm (or re-arm) the pre-first-output silence watchdog.
3380
+ * No-op when `_firstOutputTimeoutMs` is 0 (operator opt-out) or
3381
+ * when `_firstOutputDisarmed` is true (a hook event was already
3382
+ * consumed this turn — re-arming would defeat the disarm). Always
3383
+ * clears any existing handle before re-arming so back-to-back
3384
+ * `_armResultTimeout` calls produce exactly one live timer.
3385
+ *
3386
+ * Called from `_armResultTimeout()`. The matching disarm helper
3387
+ * (`_clearFirstOutputWatchdog`) is called from the hook-drain loop
3388
+ * on first consumed event and from every teardown path (success,
3389
+ * error, hard timeout, stream stall, AskUserQuestion stall,
3390
+ * destroy) so a late fire cannot land on an idle session.
3391
+ */
3392
+ _armFirstOutputWatchdog() {
3393
+ if (this._firstOutputTimeout) {
3394
+ clearTimeout(this._firstOutputTimeout)
3395
+ this._firstOutputTimeout = null
3396
+ }
3397
+ if (this._firstOutputTimeoutMs <= 0) return
3398
+ if (this._firstOutputDisarmed) return
3399
+ this._firstOutputArmedAt = this._nowMonotonic()
3400
+ this._firstOutputTimeout = setTimeout(() => {
3401
+ this._firstOutputTimeout = null
3402
+ this._handleFirstOutputTimeout()
3403
+ }, this._firstOutputTimeoutMs)
3404
+ }
3405
+
3406
+ /**
3407
+ * #4732: disarm the pre-first-output silence watchdog without
3408
+ * affecting the inter-stream stall timer. Called from the hook-drain
3409
+ * loop the first time any hook file is consumed, and from every
3410
+ * teardown path so a late fire cannot land on a torn-down session.
3411
+ * Idempotent and safe to call when the timer was never armed.
3412
+ *
3413
+ * Sets the per-turn `_firstOutputDisarmed` latch so subsequent
3414
+ * `_armResultTimeout` calls (one per consumed hook) don't re-arm
3415
+ * the watchdog. The latch is reset to false in `sendMessage` at
3416
+ * turn start via `_resetFirstOutputWatchdogForTurn` so the NEXT
3417
+ * turn gets a fresh arm cycle.
3418
+ */
3419
+ _clearFirstOutputWatchdog() {
3420
+ if (this._firstOutputTimeout) {
3421
+ clearTimeout(this._firstOutputTimeout)
3422
+ this._firstOutputTimeout = null
3423
+ }
3424
+ // #5777: first output (or any teardown) means the submit landed / the turn
3425
+ // is over — cancel any pending first-turn submit nudge so a late \r can't
3426
+ // land on an idle composer. _clearFirstOutputWatchdog is called from the
3427
+ // hook-drain loop on first consumed event and from every teardown path, so
3428
+ // this one site covers all of them.
3429
+ this._clearFirstTurnSubmitNudge()
3430
+ this._firstOutputDisarmed = true
3431
+ // #5798: first consumed hook of a turn (or any teardown that routes through
3432
+ // here) is the legitimate turn-start boundary — close the reinject
3433
+ // stop-and-wait window so a tool_use in a LATER, unrelated turn can't trip
3434
+ // the violation WARN. In the hook-drain loop this runs AFTER the per-event
3435
+ // _emitToolHookEvent pass (line ~2046 vs the clear at ~2076), so a PreToolUse
3436
+ // that IS the first hook of the reinjected turn still fires the WARN first;
3437
+ // this clear then prevents any spurious re-fire. Observability-only.
3438
+ this._reinjectStopWaitWatch = null
3439
+ }
3440
+
3441
+ /**
3442
+ * #4732: reset the per-turn `_firstOutputDisarmed` latch so the
3443
+ * next turn's `_armResultTimeout` call arms the watchdog fresh.
3444
+ * Called from `sendMessage` immediately before the prompt write so
3445
+ * a long-lived session with many turns gets first-output protection
3446
+ * on every turn (not just the first).
3447
+ */
3448
+ _resetFirstOutputWatchdogForTurn() {
3449
+ this._firstOutputDisarmed = false
3450
+ }
3451
+
3452
+ /**
3453
+ * #5777: schedule the first-turn submit nudge. A freshly-spawned claude TUI
3454
+ * can write status:idle (readiness is a session-FILE check, decoupled from
3455
+ * what's rendered) before its composer is actually interactive, so the first
3456
+ * message's trailing \r is swallowed and the prompt sits typed-but-unsent
3457
+ * until a later keystroke submits it (the manual "go" workaround). This
3458
+ * re-sends a bare \r after the nudge window if no hook output has been
3459
+ * consumed yet (`!_firstOutputDisarmed`). A bare \r is a no-op on an
3460
+ * already-submitted (empty) composer and a submit on a stuck one, so it is
3461
+ * safe either way. Retries up to FIRST_TURN_SUBMIT_NUDGE_MAX_ATTEMPTS, then
3462
+ * defers to the longer first-output watchdog. Cancelled by
3463
+ * _clearFirstOutputWatchdog (first output / any teardown / destroy).
3464
+ *
3465
+ * #5794 hardening:
3466
+ * - The CALLER (sendMessage) only schedules this for a SINGLE-LINE first
3467
+ * message of each (re)spawn — a multi-line prompt goes through the
3468
+ * bracketed-paste write path where a bare \r is unsafe.
3469
+ * - Belt-and-braces no-op guard: the tick also skips the \r if PTY output
3470
+ * (`_totalOutputBytes`) has grown since arm time. The submit landing
3471
+ * re-renders the TUI (output before any hook), so new output is
3472
+ * independent evidence the composer accepted the submit on a slow-but-
3473
+ * healthy turn — don't risk a stray second submit; defer to the
3474
+ * first-output watchdog instead. Uses the uncapped byte total (not
3475
+ * _outputTail.length, which stops growing at PTY_TAIL_BYTES — #5809).
3476
+ *
3477
+ * @param {string} messageId
3478
+ */
3479
+ _scheduleFirstTurnSubmitNudge(messageId) {
3480
+ if (!(this._firstTurnSubmitNudgeMs > 0)) return
3481
+ this._clearFirstTurnSubmitNudge()
3482
+ let attempts = 0
3483
+ // #5794 (3): snapshot the total PTY output bytes at arm time. The submit
3484
+ // landing makes the TUI re-render (the typed prompt scrolls up, the thinking
3485
+ // spinner appears) which arrives as PTY output BEFORE the first hook is
3486
+ // written — so growth here is independent evidence the composer accepted the
3487
+ // submit, even on a slow-but-healthy turn whose first hook arrives after the
3488
+ // window. We re-snapshot before each retry so a nudge that itself produced
3489
+ // progress doesn't double-fire. _totalOutputBytes is 0 in the stubbed-term
3490
+ // unit tests (no onData wired), so the existing nudge tests still fire.
3491
+ // Uses the uncapped byte total, not _outputTail.length — the tail caps at
3492
+ // PTY_TAIL_BYTES and would stop growing after a long resume transcript (#5809).
3493
+ let bytesAtArm = this._totalOutputBytes
3494
+ const tick = () => {
3495
+ this._firstTurnSubmitNudgeTimer = null
3496
+ // Nothing to nudge if the turn ended/aborted, the PTY died, the composer
3497
+ // is gone, or first output already arrived (the submit landed).
3498
+ if (!this._isBusy) return
3499
+ if (this._activeTurn?.aborted) return
3500
+ if (this._ptyExited || !this._term) return
3501
+ if (this._firstOutputDisarmed) return
3502
+ // #5794 (3): genuine progress since we armed → the submit landed; a stray
3503
+ // \r now risks an empty second submit on an already-warm composer. Defer
3504
+ // to the first-output watchdog instead of nudging.
3505
+ if (this._totalOutputBytes > bytesAtArm) {
3506
+ ;(this._log || log).info(`first-turn submit nudge skipped (#5794, msg=${messageId}) — output grew since arm, submit landed`)
3507
+ return
3508
+ }
3509
+ attempts += 1
3510
+ try {
3511
+ this._term.write('\r')
3512
+ ;(this._log || log).info(`first-turn submit nudge #${attempts} (#5777, msg=${messageId}) — no hook output yet, re-sent \\r`)
3513
+ } catch (err) {
3514
+ ;(this._log || log).warn(`first-turn submit nudge write failed (#5777, msg=${messageId}): ${err.message}`)
3515
+ return
3516
+ }
3517
+ if (attempts < ClaudeTuiSession.FIRST_TURN_SUBMIT_NUDGE_MAX_ATTEMPTS) {
3518
+ // Re-snapshot so the next tick's no-progress check measures growth since
3519
+ // THIS nudge (if our \r landed the submit, the next tick should skip).
3520
+ bytesAtArm = this._totalOutputBytes
3521
+ this._firstTurnSubmitNudgeTimer = setTimeout(tick, this._firstTurnSubmitNudgeMs)
3522
+ }
3523
+ }
3524
+ this._firstTurnSubmitNudgeTimer = setTimeout(tick, this._firstTurnSubmitNudgeMs)
3525
+ }
3526
+
3527
+ /**
3528
+ * #5777: cancel any pending first-turn submit nudge. Idempotent and safe to
3529
+ * call when no nudge was ever scheduled.
3530
+ */
3531
+ _clearFirstTurnSubmitNudge() {
3532
+ if (this._firstTurnSubmitNudgeTimer) {
3533
+ clearTimeout(this._firstTurnSubmitNudgeTimer)
3534
+ this._firstTurnSubmitNudgeTimer = null
3535
+ }
3536
+ }
3537
+
3538
+ _handleInactivityWarning() {
3539
+ if (!this._isBusy) return
3540
+ // #5318 (WP-3.1) — defence in depth: never warn while blocked on a human
3541
+ // answer (the suspend should already have cleared this timer).
3542
+ if (this._pendingUserAnswers.size > 0) return
3543
+ const idleMs = this._resultTimeoutMs
3544
+ const friendly = formatIdleDuration(idleMs)
3545
+ log.info(`Inactivity warning (${friendly}) — session alive, prompting check-in`)
3546
+ this.emit('inactivity_warning', {
3547
+ messageId: this._currentMessageId,
3548
+ idleMs,
3549
+ prefab: 'Status update?',
3550
+ })
3551
+ }
3552
+
3553
+ _handleHardTimeout() {
3554
+ if (!this._isBusy) return
3555
+ // #5318 (WP-3.1) — NOTE: intentionally NOT guarded on a pending question.
3556
+ // The hard cap is the last-resort backstop and must still fire (and run its
3557
+ // pending-answer cleanup, #4691) even if a human never answers.
3558
+ this._assertBusyHasMessageId('_handleHardTimeout')
3559
+ const friendly = formatIdleDuration(this._hardTimeoutMs)
3560
+ log.warn(`Hard-cap timeout (${friendly}) — force-clearing busy state`)
3561
+ const duration = this._activeTurn ? this._nowMonotonic() - this._activeTurn.startedAt : this._hardTimeoutMs
3562
+ // #4641: shared teardown helper. Flags preserve exact historical
3563
+ // behaviour — hard-timeout emits stream_end unconditionally (even if
3564
+ // messageId is null) and emits error BEFORE _emitResult; stream-stall
3565
+ // gates stream_end on messageId and emits error AFTER. Both are kept
3566
+ // as-is so this refactor is behaviour-preserving.
3567
+ this._teardownTurn('hard_timeout', {
3568
+ duration,
3569
+ errorPayload: { message: `Response timed out after ${friendly}` },
3570
+ errorBeforeResult: true,
3571
+ gateStreamEndOnMessageId: false,
3572
+ })
3573
+ }
3574
+
3575
+ /**
3576
+ * #4638: stream-stall active recovery. Fires after
3577
+ * `_streamStallTimeoutMs` of silence post-stream_start with no Stop
3578
+ * hook, no tool hooks, and no PTY output at all — the wedge mode
3579
+ * observed live in v0.9.21 where claude TUI accepts the prompt and
3580
+ * then emits nothing forever. Mirrors `CliSession._handleStreamStall`
3581
+ * (#4467) and `SdkSession._handleStreamStall` (#4616) so the
3582
+ * dashboard's recovery path is provider-agnostic.
3583
+ *
3584
+ * Distinct from the soft inactivity warning (passive chip after 30
3585
+ * min) and the hard cap (force-clear after 2h): this is the ACTIVE
3586
+ * recovery in minutes, not hours, so a user staring at a stuck
3587
+ * "Working…" banner can retry without waiting for the hard backstop
3588
+ * or having to click Stop and hope.
3589
+ *
3590
+ * Sequence: best-effort Ctrl-C into the TUI (so claude TUI itself
3591
+ * unsticks for the next turn) → emit stream_end (pairs with the
3592
+ * stream_start fired at turn-start) → _emitResult (sweeps orphan
3593
+ * tool_starts, fires synthetic result → agent_idle fan-out via the
3594
+ * event-normalizer) → emit error with `code: 'stream_stall'` so the
3595
+ * dashboard surfaces a dedicated retry affordance distinct from
3596
+ * generic errors.
3597
+ */
3598
+ _handleStreamStall() {
3599
+ if (!this._isBusy) return
3600
+ // #5318 (WP-3.1) — defence in depth: a pending human answer is not a stall
3601
+ // (the suspend should already have cleared this timer).
3602
+ if (this._pendingUserAnswers.size > 0) return
3603
+ this._assertBusyHasMessageId('_handleStreamStall')
3604
+ const friendly = formatIdleDuration(this._streamStallTimeoutMs)
3605
+ const messageId = this._currentMessageId
3606
+ log.warn(
3607
+ `Stream stalled (${friendly}, messageId=${messageId}) — clearing busy state for retry`,
3608
+ )
3609
+ const duration = this._activeTurn ? this._nowMonotonic() - this._activeTurn.startedAt : this._streamStallTimeoutMs
3610
+ // #5321 (WP-4.1) — a turn that stalled WITH a logged-out / expired-login
3611
+ // banner in its tail is an auth failure, not a generic stall. Upgrade the
3612
+ // error so mid-session expiry gives actionable `claude login` guidance
3613
+ // instead of "try sending again" (which would just stall again). The tail
3614
+ // still holds rendered RESPONSE text here, so false-positive safety rests on
3615
+ // the patterns requiring claude's `/login` / `claude login` command token
3616
+ // (see AUTH_FAILURE_PATTERNS) — a model merely DISCUSSING auth won't match.
3617
+ const authFail = this._scanOutputForAuthFailure()
3618
+ // #4641: shared teardown helper. See companion call in _handleHardTimeout
3619
+ // for the meaning of the asymmetric flags — preserved here as-is so this
3620
+ // refactor introduces no behaviour change.
3621
+ this._teardownTurn('stream_stall', {
3622
+ duration,
3623
+ errorPayload: authFail
3624
+ ? { code: AUTH_REQUIRED_CODE, message: AUTH_REQUIRED_MESSAGE }
3625
+ : {
3626
+ code: 'stream_stall',
3627
+ message: `Stream stalled — no response for ${friendly}. Try sending again.`,
3628
+ },
3629
+ errorBeforeResult: false,
3630
+ gateStreamEndOnMessageId: true,
3631
+ })
3632
+ }
3633
+
3634
+ /**
3635
+ * #4732: pre-first-output silence watchdog handler. Fires once per
3636
+ * turn when claude TUI accepts the prompt write (writePtyText
3637
+ * completed=true) but emits NO hook events for
3638
+ * `_firstOutputTimeoutMs`. Distinct from `_handleStreamStall` —
3639
+ * that one fires on silence BETWEEN hook events, this one fires on
3640
+ * silence BEFORE the first one.
3641
+ *
3642
+ * Live failure that motivated this (v0.9.32 dogfooding, #4732):
3643
+ * `writePtyText completed=true` at T+0; 200s of `hookPoll
3644
+ * heartbeat … consumed=0 stopFound=no` with no recovery. claude TUI
3645
+ * subprocess had 2.71s CPU after 4 min wall — consistent with a
3646
+ * stuck Anthropic API call. User clicked Stop manually.
3647
+ *
3648
+ * Reuses the `stream_stall` error code so the dashboard's existing
3649
+ * recovery chip surfaces without provider-specific wiring. The
3650
+ * distinct teardown reason `'first_output_timeout'` keeps the two
3651
+ * stall flavors distinguishable in post-mortem logs / metrics.
3652
+ */
3653
+ _handleFirstOutputTimeout() {
3654
+ if (!this._isBusy) return
3655
+ // #5318 (WP-3.1) — defence in depth: don't fire while blocked on a human
3656
+ // answer. (Normally moot — first output already arrived before any question
3657
+ // — but kept symmetric with the other backstop handlers.)
3658
+ if (this._pendingUserAnswers.size > 0) return
3659
+ // #4642: mirror the invariant check the other teardown sites
3660
+ // (`_finishTurnError`, `_handleHardTimeout`, `_handleStreamStall`,
3661
+ // `_onAskUserQuestionStall`) emit so a future regression that
3662
+ // breaks the `_isBusy ↔ _currentMessageId` construction contract
3663
+ // surfaces from THIS path too.
3664
+ this._assertBusyHasMessageId('_handleFirstOutputTimeout')
3665
+ const elapsedMs = this._firstOutputArmedAt > 0
3666
+ ? this._nowMonotonic() - this._firstOutputArmedAt
3667
+ : this._firstOutputTimeoutMs
3668
+ const friendly = formatIdleDuration(this._firstOutputTimeoutMs)
3669
+ log.warn(`first-output watchdog fired (elapsedMs=${elapsedMs}) — claude TUI did not respond`)
3670
+ const duration = this._activeTurn
3671
+ ? this._nowMonotonic() - this._activeTurn.startedAt
3672
+ : this._firstOutputTimeoutMs
3673
+ // #5321 (WP-4.1) — upgrade to AUTH_REQUIRED when the pre-first-output
3674
+ // silence came WITH a logged-out / expired-login banner (e.g. an expired
3675
+ // login on the very first turn after restore). False-positive safety rests
3676
+ // on the command-token patterns (see AUTH_FAILURE_PATTERNS), not on the turn
3677
+ // having stalled.
3678
+ const authFail = this._scanOutputForAuthFailure()
3679
+ // Mirrors _handleStreamStall's `_teardownTurn` call shape (result
3680
+ // before error, gate stream_end on messageId) so the dashboard sees
3681
+ // the same fan-out it already handles for the inter-stream stall.
3682
+ this._teardownTurn('first_output_timeout', {
3683
+ duration,
3684
+ errorPayload: authFail
3685
+ ? { code: AUTH_REQUIRED_CODE, message: AUTH_REQUIRED_MESSAGE }
3686
+ : {
3687
+ code: 'stream_stall',
3688
+ message: `No response from claude TUI within ${friendly}. Try sending again.`,
3689
+ },
3690
+ errorBeforeResult: false,
3691
+ gateStreamEndOnMessageId: true,
3692
+ })
3693
+ }
3694
+
3695
+ /**
3696
+ * #4641: shared per-turn teardown for the timeout/stall recovery paths
3697
+ * (`_handleHardTimeout`, `_handleStreamStall`). Centralises the cleanup
3698
+ * sequence so the next #4286/#4604-class symmetry fix only needs to
3699
+ * touch one site.
3700
+ *
3701
+ * Sequence (matches the historical inline code in both callers):
3702
+ * 1. Best-effort Ctrl-C into the PTY so claude TUI unsticks the
3703
+ * in-flight request and returns to its prompt. Doesn't kill the
3704
+ * process — _isBusy=false below lets the next sendMessage proceed.
3705
+ * 2. Emit `stream_end` so the dashboard clears `streamingMessageId`.
3706
+ * The two callers disagree on whether to gate on `messageId`
3707
+ * (hard-timeout emits unconditionally, stream-stall gates),
3708
+ * hence the `gateStreamEndOnMessageId` flag — kept asymmetric
3709
+ * because changing either side would alter observable wire
3710
+ * behaviour for a contract-violation edge case (_isBusy=true with
3711
+ * a null _currentMessageId, tracked in #4642).
3712
+ * 3. Drop the per-turn attachment dir (#4022), null `_activeTurn`,
3713
+ * clear `_isBusy` + `_currentMessageId`.
3714
+ * 4. Clear the pending AskUserQuestion answer slot (#4286), the
3715
+ * askuserquestion-active lock (#4669), and the AskUserQuestion
3716
+ * stall watchdog (#4604) — all symmetric across teardown paths.
3717
+ * 5. Emit `error` and `_emitResult` in the order the caller requests.
3718
+ * Hard-timeout historically fired error BEFORE result; stream-stall
3719
+ * after. The order is observable to listeners and the asymmetry
3720
+ * is preserved here verbatim (`errorBeforeResult` flag) so this
3721
+ * refactor is strictly behaviour-preserving — flipping the order
3722
+ * to a single canonical sequence is intentionally OUT OF SCOPE
3723
+ * and tracked separately if ever needed.
3724
+ *
3725
+ * `errorPayload` is optional — when omitted no error is emitted (none
3726
+ * of the current callers exercise this, but it leaves room for future
3727
+ * teardown paths that only want the cleanup half).
3728
+ */
3729
+ _teardownTurn(reason, {
3730
+ duration,
3731
+ errorPayload = null,
3732
+ errorBeforeResult = false,
3733
+ gateStreamEndOnMessageId = true,
3734
+ } = {}) {
3735
+ const messageId = this._currentMessageId
3736
+ // #4682: per-turn summary log so the wedge-mode teardown paths
3737
+ // (hard_timeout, stream_stall) land the same grep-able
3738
+ // `sendMessage done` line as the success and _finishTurnError paths.
3739
+ // Placed before any state mutation so the helper sees populated
3740
+ // turn fields (messageId, startedAt, waitForPrompt*, write*).
3741
+ // PR #4681 added the summary helper for the wedge investigation;
3742
+ // missing it on the stream-stall path defeated the whole point.
3743
+ this._logSendMessageSummary(reason)
3744
+ // 1. Best-effort Ctrl-C into the PTY.
3745
+ if (this._term) {
3746
+ try { this._term.write('\x03') } catch { /* ignore */ }
3747
+ }
3748
+ // 2. Emit stream_end (gated per caller).
3749
+ if (gateStreamEndOnMessageId) {
3750
+ if (messageId) this.emit('stream_end', { messageId })
3751
+ } else {
3752
+ this.emit('stream_end', { messageId })
3753
+ }
3754
+ // 3. Per-turn attachment + busy-state cleanup. _cleanupTurnAttachments
3755
+ // runs BEFORE _activeTurn is nulled so the helper still has access
3756
+ // to attachmentsDir; no-op when the turn had no attachments.
3757
+ this._cleanupTurnAttachments(this._activeTurn)
3758
+ this._activeTurn = null
3759
+ this._isBusy = false
3760
+ this._currentMessageId = null
3761
+ // 4. AskUserQuestion-related slot/lock/watchdog symmetry. #4802:
3762
+ // explicit `_pendingUserAnswers_clearAll()` (was an implicit
3763
+ // `_pendingUserAnswer = null` via the back-compat setter). Safe
3764
+ // here because _teardownTurn always issues Ctrl-C above
3765
+ // (step 1), so the TUI has dropped its current AskUserQuestion
3766
+ // form — any sibling pending entry can no longer be served and
3767
+ // leaving it would just risk a late respondToQuestion writing
3768
+ // stale keystrokes into whatever form the next turn brings up.
3769
+ this._pendingUserAnswers_clearAll()
3770
+ this._clearAskUserQuestionLock()
3771
+ // #5319 (WP-3.2): Ctrl-C above dropped the TUI's current form, so every
3772
+ // per-toolUseId watchdog is now stale — clear them all.
3773
+ this._clearAllAskUserQuestionWatchdogs()
3774
+ // #4732: clear the pre-first-output watchdog so a teardown via
3775
+ // `_handleHardTimeout` / `_handleStreamStall` / `_handleFirstOutputTimeout`
3776
+ // can never leak a live handle that would re-fire on a torn-down turn.
3777
+ this._clearFirstOutputWatchdog()
3778
+ // #4307: drop the ephemeral intra-turn run_in_background tool_use→command
3779
+ // map on this turn-end too (matches _clearTurnEndState / base _clearMessageState).
3780
+ this._pendingBackgroundCommands.clear()
3781
+ // 5. Error + result emit, in the order the caller requests. The two
3782
+ // existing callers disagree (hard-timeout: error first; stream-stall:
3783
+ // result first), and that asymmetry is preserved exactly.
3784
+ const emitResult = () => {
3785
+ this._emitResult(
3786
+ { cost: null, duration, usage: null, sessionId: this._sessionId },
3787
+ reason,
3788
+ )
3789
+ }
3790
+ const emitError = () => {
3791
+ if (errorPayload) this.emit('error', errorPayload)
3792
+ }
3793
+ if (errorBeforeResult) {
3794
+ emitError()
3795
+ emitResult()
3796
+ } else {
3797
+ emitResult()
3798
+ emitError()
3799
+ }
3800
+ }
3801
+
3802
+ /**
3803
+ * #4013: mid-session permission switch. Unlike CliSession, the TUI
3804
+ * does NOT restart its PTY on mode change — env vars on a running
3805
+ * process can't be mutated from outside, so we write the new mode to
3806
+ * a sidecar file the hook script re-reads on every tool call. The
3807
+ * persistent conversation context survives the change. Takes effect
3808
+ * on the next tool-call boundary; an in-flight tool that already
3809
+ * routed to /permission is unaffected.
3810
+ */
3811
+ // #5374: BaseSession.setPermissionMode owns the validation + guard and fires
3812
+ // this hook after `this.permissionMode` is set, only when the mode changed.
3813
+ // #5334 (IP-6): atomically write the permission-mode sidecar — write a tmp
3814
+ // file then rename(2) over the target. Direct writeFileSync truncates-then-
3815
+ // writes, so a concurrent PreToolUse hook `cat` could observe an empty/partial
3816
+ // value mid-write and fall through to the stale env var. rename(2) is atomic
3817
+ // within the same filesystem, so readers see either the OLD complete value or
3818
+ // the NEW complete value — never an empty/partial one. Throws on failure
3819
+ // (after best-effort tmp cleanup) so each caller applies its own fallback.
3820
+ _writePermissionModeSidecarAtomic(path, value) {
3821
+ const tmpPath = `${path}.tmp-${randomUUID()}`
3822
+ try {
3823
+ writeFileSync(tmpPath, value)
3824
+ renameSync(tmpPath, path)
3825
+ } catch (err) {
3826
+ try { rmSync(tmpPath, { force: true }) } catch { /* ignore */ }
3827
+ throw err
3828
+ }
3829
+ }
3830
+
3831
+ _onPermissionModeChanged(mode) {
3832
+ if (!this._permissionModeFile) {
3833
+ // Permissions weren't enabled at start (no port). Mode was already
3834
+ // updated on `this.permissionMode` by BaseSession; nothing else to do.
3835
+ log.info(`Permission mode changed to ${mode} (no sidecar — hook script not active)`)
3836
+ return
3837
+ }
3838
+ try {
3839
+ this._writePermissionModeSidecarAtomic(this._permissionModeFile, mode)
3840
+ log.info(`Permission mode changed to ${mode} (sidecar updated, no PTY restart)`)
3841
+ } catch (err) {
3842
+ // Hook precedence is file → env var. If the rename failed the
3843
+ // sidecar still holds the previous mode, so the next tool call
3844
+ // reads the stale FILE value (not the env var). Be explicit so
3845
+ // the operator isn't misled.
3846
+ log.warn(`failed to write permission-mode sidecar (${err.message}) — next tool call will use the previously written mode from the sidecar file`)
3847
+ }
3848
+ }
3849
+
3850
+ /**
3851
+ * Abort the current turn. Sends SIGINT to the persistent PTY — claude's
3852
+ * TUI treats Ctrl-C as "cancel current request, return to input prompt"
3853
+ * (NOT as a process kill), so the session stays alive and the next
3854
+ * sendMessage() works normally.
3855
+ */
3856
+ interrupt() {
3857
+ if (!this._activeTurn) return
3858
+ this._activeTurn.aborted = true
3859
+ if (this._term) {
3860
+ // Write Ctrl-C (0x03) to the PTY rather than killing the process.
3861
+ // Claude TUI intercepts it as "cancel current request, return to
3862
+ // input prompt", so the session stays alive and the next
3863
+ // sendMessage() works normally. Matches _handleHardTimeout.
3864
+ try { this._term.write('\x03') } catch { /* ignore */ }
3865
+ }
3866
+ // #4278 / #4802: drop any pending AskUserQuestion so a subsequent
3867
+ // user_question_response can't write into a torn-down context.
3868
+ // Explicit `_pendingUserAnswers_clearAll()` (was an implicit
3869
+ // `_pendingUserAnswer = null` → Map.clear() via the back-compat
3870
+ // setter). Safe here: interrupt() writes Ctrl-C to the PTY above,
3871
+ // so the TUI is no longer waiting on any AskUserQuestion form —
3872
+ // every sibling pending entry is now equally stale.
3873
+ this._pendingUserAnswers_clearAll()
3874
+ this._clearAskUserQuestionLock()
3875
+ // #4604: cancel the stall watchdogs too. interrupt() does NOT clear
3876
+ // _isBusy directly (Ctrl-C surfaces async via _finishTurn*), so without
3877
+ // this a watchdog could fire ~30s later and emit a spurious
3878
+ // ASK_USER_QUESTION_STALL for a session the user already interrupted.
3879
+ // #5319 (WP-3.2): clear every per-toolUseId watchdog.
3880
+ this._clearAllAskUserQuestionWatchdogs()
3881
+ // #4732: same reasoning for the pre-first-output watchdog. interrupt()
3882
+ // doesn't synchronously flip _isBusy=false, so without this clear the
3883
+ // watchdog could fire in the 150ms poll-loop window before
3884
+ // _finishTurnError runs and emit a spurious stream_stall for a
3885
+ // session the user has already interrupted.
3886
+ this._clearFirstOutputWatchdog()
3887
+ }
3888
+
3889
+ async destroy() {
3890
+ this._destroying = true
3891
+ this._processReady = false
3892
+ this._isBusy = false
3893
+ this._activeTurn = null
3894
+ // #5315 (WP-2.1) — cancel any pending respawn so a scheduled _respawnPty
3895
+ // can't fire after teardown and spawn a fresh claude into a destroyed
3896
+ // session. `_destroying` is already true above, so _scheduleRespawn would
3897
+ // short-circuit anyway, but a timer already armed before destroy() must be
3898
+ // cleared explicitly. _respawning is reset so a re-create of this instance
3899
+ // (defensive) starts from a clean state.
3900
+ if (this._respawnTimer) { clearTimeout(this._respawnTimer); this._respawnTimer = null }
3901
+ this._respawnScheduled = false
3902
+ this._respawning = false
3903
+ // #4278 / #4802: drop any pending AskUserQuestion so a late
3904
+ // user_question_response can't write into a dead PTY. Explicit
3905
+ // `_pendingUserAnswers_clearAll()` (was an implicit
3906
+ // `_pendingUserAnswer = null` → Map.clear() via the back-compat
3907
+ // setter). Unambiguous here: destroy() SIGTERMs the PTY below and
3908
+ // nulls `_term`, so every pending entry is permanently unservable.
3909
+ this._pendingUserAnswers_clearAll()
3910
+ this._clearAskUserQuestionLock()
3911
+ if (this._resultTimeout) { clearTimeout(this._resultTimeout); this._resultTimeout = null }
3912
+ if (this._hardTimeout) { clearTimeout(this._hardTimeout); this._hardTimeout = null }
3913
+ // #4638: clear the stream-stall watchdog on destroy too — otherwise
3914
+ // a late fire could land in _handleStreamStall after _term is null,
3915
+ // skipping the Ctrl-C path but still emitting events into a dead session.
3916
+ if (this._streamStallTimeout) { clearTimeout(this._streamStallTimeout); this._streamStallTimeout = null }
3917
+ // #4732: same reasoning for the pre-first-output watchdog — a late
3918
+ // fire post-destroy must not emit a stream_stall error into a torn-
3919
+ // down listener set or write Ctrl-C into a killed PTY.
3920
+ this._clearFirstOutputWatchdog()
3921
+ // #4604 / #5319 (WP-3.2): cancel every AskUserQuestion stall watchdog so
3922
+ // none can fire a stale ASK_USER_QUESTION_STALL event into a torn-down
3923
+ // listener.
3924
+ this._clearAllAskUserQuestionWatchdogs()
3925
+ // #5431: stop the background-task transcript re-scan so a late tick
3926
+ // can't emit background_tasks_changed into a torn-down listener set.
3927
+ this._stopBackgroundTaskPoll()
3928
+ if (this._term) {
3929
+ // #5317 (WP-2.3) — capture the handle + pid BEFORE nulling so the
3930
+ // escalation timer (and _onPtyGone's cancel) still have something to act
3931
+ // on. SIGTERM first so claude can flush its Stop hook and reap its own
3932
+ // tool children; escalate to SIGKILL only if it ignores us.
3933
+ const term = this._term
3934
+ const pid = term.pid
3935
+ this._term = null
3936
+ // #5351 review — only signal a PTY we believe is still alive. _onPtyGone
3937
+ // does NOT null _term, so after an unexpected exit (crash / respawn
3938
+ // exhaustion) destroy() sees `_term` non-null AND `_ptyExited` true. The
3939
+ // process has already been reaped by then, so sending ANY signal — even
3940
+ // SIGTERM — risks hitting a recycled pid. Skip the whole kill path; the
3941
+ // PTY is already gone and there's nothing to reap.
3942
+ if (!this._ptyExited) {
3943
+ try { term.kill('SIGTERM') } catch { /* already dead */ }
3944
+ }
3945
+ // Arm the SIGKILL escalation. _onPtyGone clears this timer when the JS
3946
+ // onExit/close/error callback runs, which handles the common case. But that
3947
+ // is NOT sufficient on its own to rule out pid reuse: node-pty reaps the
3948
+ // child with waitpid() on its internal thread BEFORE it schedules the JS
3949
+ // onExit callback, so the OS can recycle the pid in the gap between the
3950
+ // reap and our latch being set — and the grace timer + the onExit callback
3951
+ // are unordered event-loop tasks. So the timer callback re-checks the
3952
+ // _ptyExited latch AND probes liveness with signal 0 before escalating, so
3953
+ // a blind `process.kill(-pid)` can't land on a recycled process group.
3954
+ if (!this._ptyExited && Number.isInteger(pid) && pid > 0) {
3955
+ const graceMs = ClaudeTuiSession.DESTROY_GRACE_MS
3956
+ this._killTimer = setTimeout(() => {
3957
+ this._killTimer = null
3958
+ // The onExit callback has run since we armed the timer → process is
3959
+ // already gone (and possibly its pid recycled). Never escalate.
3960
+ if (this._ptyExited) return
3961
+ // Liveness probe: signal 0 throws ESRCH if the pid is gone. This won't
3962
+ // catch a pid that was reaped-then-recycled into a live process, but
3963
+ // combined with the _ptyExited latch above it narrows escalation to
3964
+ // "the latch never fired AND the pid is still alive" — i.e. a genuinely
3965
+ // hung claude, not a recycled stranger.
3966
+ try { process.kill(pid, 0) } catch { return /* already exited */ }
3967
+ log.warn(`claude PTY (pid=${pid}) did not exit ${graceMs}ms after SIGTERM — escalating to SIGKILL`)
3968
+ // Reap the whole process group so claude's tool children die too, not
3969
+ // just the session leader. node-pty spawns claude with setsid, so it's
3970
+ // its own process-group leader (pgid == pid) and `-pid` targets the
3971
+ // group. Fall back to the single pid (and node-pty's own kill) when the
3972
+ // group signal isn't deliverable (non-POSIX, or the leader already reaped).
3973
+ let killed = false
3974
+ if (process.platform !== 'win32') {
3975
+ try { process.kill(-pid, 'SIGKILL'); killed = true } catch { /* group gone / not a leader */ }
3976
+ }
3977
+ if (!killed) {
3978
+ try { term.kill('SIGKILL') } catch {
3979
+ try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }
3980
+ }
3981
+ }
3982
+ }, graceMs)
3983
+ // Don't keep the event loop alive solely for the grace timer.
3984
+ if (typeof this._killTimer.unref === 'function') this._killTimer.unref()
3985
+ }
3986
+ }
3987
+ // Clean up the per-session sink dir so we don't leak hook payload
3988
+ // files under /tmp (#3918). One file per turn (stop) plus 2 per
3989
+ // tool call (pre + post) accumulate fast on long-running sessions.
3990
+ if (this._sinkDir) {
3991
+ try { rmSync(this._sinkDir, { recursive: true, force: true }) }
3992
+ catch (err) { log.warn(`sink dir cleanup failed: ${err.message}`) }
3993
+ this._sinkDir = null
3994
+ }
3995
+ // Sidecar file lived inside _sinkDir which we just removed — clear
3996
+ // the reference so setPermissionMode() after destroy() no-ops cleanly.
3997
+ this._permissionModeFile = null
3998
+ this._consumedFiles.clear()
3999
+ this._clearMessageState()
4000
+ // #4307: drop any pending background-shell entries so the session-
4001
+ // list snapshot doesn't carry phantom entries past destroy. Done
4002
+ // after _clearMessageState (which preserves the pending shells —
4003
+ // the #4307 core invariant); the explicit destroy hook is the only
4004
+ // path that removes them.
4005
+ this._destroyPendingBackgroundShells()
4006
+ }
4007
+ }
4008
+
4009
+ // #5559 — copy the moved PTY-write / form-driver methods onto the prototype.
4010
+ // Class methods are non-enumerable, so Object.assign won't see them; copy the
4011
+ // own property descriptors verbatim instead (preserving non-enumerability).
4012
+ // The method bodies are byte-identical to their pre-split form and run with
4013
+ // `this` bound to the ClaudeTuiSession instance exactly as before.
4014
+ function applyMixin(targetClass, mixinClass) {
4015
+ const proto = mixinClass.prototype
4016
+ for (const name of Object.getOwnPropertyNames(proto)) {
4017
+ if (name === 'constructor') continue
4018
+ Object.defineProperty(
4019
+ targetClass.prototype,
4020
+ name,
4021
+ Object.getOwnPropertyDescriptor(proto, name),
4022
+ )
4023
+ }
4024
+ }
4025
+
4026
+ applyMixin(ClaudeTuiSession, PtyDriverMixin)
4027
+ // #5617 — FormDriver is no longer mixed onto the prototype; it's an injected
4028
+ // collaborator constructed per-session (see the constructor) and reached via
4029
+ // the `respondToQuestion` delegator + `this._formDriver` for the stall callback.