@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,874 @@
1
+ // claude-tui/form-driver.js — interactive AskUserQuestion form driver for ClaudeTuiSession.
2
+ //
3
+ // respondToQuestion assembles the empirically-pinned keystroke sequences
4
+ // (project memory: tui_multi_question_form_keys, multi_question_post_deny_wedge)
5
+ // — digit auto-advance, Tab between multi-selects, the Submit-settle, the
6
+ // Other/freeform two-stage flow, arrow-nav for 10+ option picks — and the stall
7
+ // watchdog teardown.
8
+ //
9
+ // #5559 first moved these bodies out of claude-tui-session.js byte-identical,
10
+ // but re-coupled them onto ClaudeTuiSession.prototype via applyMixin(), so they
11
+ // still reached into 28 private session fields/methods through `this`.
12
+ //
13
+ // #5617 makes FormDriver an INJECTED COLLABORATOR: the session constructs it as
14
+ // `this._formDriver = new FormDriver(this)` and delegates `respondToQuestion()`;
15
+ // every former session access `this._<member>` is now `this._host._<member>`
16
+ // against the explicit {@link FormDriverHost} surface below (the `_<member>`s are
17
+ // enumerated there). The byte-sequence bodies are otherwise
18
+ // UNCHANGED (the #5617 diff reverses to the #5559 source exactly — a pure
19
+ // receiver swap). The point is testability: a unit test injects a mock host and
20
+ // asserts the keystroke sequences against the pinned recordings WITHOUT a live
21
+ // PTY (see tests/claude-tui-form-driver.test.js).
22
+ //
23
+ /**
24
+ * The slice of ClaudeTuiSession that FormDriver drives. The session satisfies
25
+ * this structurally (FormDriver receives `this`); tests pass a mock. Grouped:
26
+ *
27
+ * - PTY writers: `_writePtyTextThrottled`, `_writePtyArrowNavSequence` —
28
+ * emit the keystroke bytes.
29
+ * - Pending-answer state: `_pendingUserAnswers` (Map), `_pendingUserAnswer`
30
+ * (back-compat getter), `_clearPendingAnswerByToolUseId`.
31
+ * - Turn/result state: `_activeTurn`, `_isBusy`, `_currentMessageId`,
32
+ * `_destroying`, `_assertBusyHasMessageId`, `_emitResult`, `_trackToolResult`,
33
+ * `_cleanupTurnAttachments`, `_outputTailHexDump`, `_sessionId`.
34
+ * - Timers/watchdogs: `_armAskUserQuestionWatchdog`,
35
+ * `_clearAskUserQuestionWatchdog`, `_clearAskUserQuestionLock`,
36
+ * `_clearFirstOutputWatchdog`, `_streamStallTimeout`, `_resultTimeout`,
37
+ * `_hardTimeout`, `_nowMonotonic`.
38
+ * - Misc: `_term`, `_log`, `emit` (the session is an EventEmitter),
39
+ * `sendMessage` (#5776 multi-select reinject — start a new turn with the
40
+ * formatted answer text when the denied multi-select form has no live form
41
+ * to drive).
42
+ *
43
+ * @typedef {import('../claude-tui-session.js').ClaudeTuiSession} FormDriverHost
44
+ */
45
+ import { createLogger } from '../logger.js'
46
+
47
+ const log = createLogger('claude-tui-session')
48
+
49
+
50
+ // #4604 — watchdog window for the AskUserQuestion answer round-trip.
51
+ // respondToQuestion() writes ONE keystroke (the chosen option's digit)
52
+ // and assumes claude TUI emits PostToolUse shortly after. Multi-question
53
+ // AskUserQuestion forms violate that assumption: claude TUI renders a
54
+ // per-question form that needs additional keystrokes + a Submit, and
55
+ // PostToolUse never fires. Without this watchdog the session wedges at
56
+ // _isBusy=true forever (the 8m+ symptom in #4604). On expiry we clear
57
+ // _isBusy + _pendingUserAnswer and emit ASK_USER_QUESTION_STALL so the
58
+ // dashboard can prompt the user to retry. The multi-question wedge this
59
+ // originally guarded was removed in #5773 (assembler deleted); the watchdog
60
+ // now backstops single-question / multi-select-reinject stalls.
61
+ export const ASK_USER_QUESTION_WATCHDOG_MS = 30 * 1000
62
+
63
+ // #4651 — settle delay between the "Other" digit write and the freeform
64
+ // text write. After we press the Other digit, claude TUI swaps from the
65
+ // option-select menu to a text-input prompt. Writing the freeform text
66
+ // too quickly races that swap (the keystrokes land at the menu and jump-
67
+ // nav fires — same footgun as #4288). 150 ms covers the observed local-
68
+ // loop swap time with comfortable margin; tune via the empirical
69
+ // recording in scripts/tui-form-recorder.mjs if dogfood reveals a wedge.
70
+ const OTHER_FREEFORM_SETTLE_MS = 150
71
+
72
+ // #4651 — additional watchdog window granted after the Other digit lands
73
+ // so the freeform text write + claude TUI's text-input acknowledgement
74
+ // have time to complete. Without this, the existing 30s ASK_USER_QUESTION
75
+ // watchdog can fire mid-freeform-write on a slow PTY (laggy tunnel,
76
+ // emoji-heavy text) and tear down a turn that's actively progressing.
77
+ const OTHER_FREEFORM_WATCHDOG_MS = 30 * 1000
78
+
79
+ // #5776 (Phase 0) — multi-select reinject spike. claude TUI is keyboard-only
80
+ // and exposes no structured answer channel, so multi-select forms are denied at
81
+ // permission-hook.sh and (defense-in-depth) refused here. The reinject path
82
+ // flips the strategy: instead of refusing, format the user's selection into a
83
+ // plain-text answer and feed it to claude as a NEW turn via sendMessage(). This
84
+ // works because the form was denied BEFORE it rendered (so there is no live form
85
+ // to drive and no PostToolUse coming), and because a multi-select answer reaches
86
+ // the model as comma-joined TEXT anyway (verified live 2026-06-13 — see project
87
+ // memory tui_askuserquestion_keyboard_only). Gated behind an env flag so the
88
+ // default (refuse) behavior is untouched; the same flag steers the hook's deny
89
+ // reason. Read at call time so tests can toggle it per-case.
90
+ export function multiSelectReinjectEnabled() {
91
+ return process.env.CHROXY_TUI_MULTISELECT_REINJECT === '1'
92
+ }
93
+
94
+ // #5796 — sanitize an untrusted reinject label before it is TYPED into the live
95
+ // claude TUI PTY. Multi-select labels (and the freeform/"Other" text) arrive from
96
+ // the client over the wire, so a crafted value could contain control characters:
97
+ // a bare CR/LF (\r/\n) would submit the composer early, and ESC (\x1b) + the rest
98
+ // of a C0/C1 sequence could inject terminal escape codes or corrupt the prompt.
99
+ // Replace every run of control chars (C0 \x00-\x1f, DEL \x7f, C1 \x80-\x9f — which
100
+ // covers \r, \n, \x1b) with a single space, then collapse and trim surrounding
101
+ // whitespace so the visible label stays clean. Printable unicode is preserved.
102
+ // Pure + never throws: non-string input coerces to '' (drop it).
103
+ function sanitizeReinjectLabel(s) {
104
+ if (typeof s !== 'string') return ''
105
+ // eslint-disable-next-line no-control-regex
106
+ return s.replace(/[\x00-\x1f\x7f-\x9f]+/g, ' ').replace(/\s+/g, ' ').trim()
107
+ }
108
+
109
+ // #5776 — parse a single question's answersMap value into an array of selected
110
+ // option LABELS. Accepts the three wire shapes the dashboard may send: a native
111
+ // array (post-#4735), a JSON-encoded array string, or a comma-joined fallback.
112
+ function parseSelectedLabels(raw) {
113
+ if (Array.isArray(raw)) return raw.filter((s) => typeof s === 'string')
114
+ if (typeof raw === 'string' && raw.length > 0) {
115
+ let parsed = null
116
+ try { parsed = JSON.parse(raw) } catch { parsed = null }
117
+ if (Array.isArray(parsed)) return parsed.filter((s) => typeof s === 'string')
118
+ return raw.split(',').map((s) => s.trim()).filter(Boolean)
119
+ }
120
+ return []
121
+ }
122
+
123
+ // #5776 — format the pending questions + answersMap into the plain-text answer
124
+ // chroxy reinjects as the next user message. Uses option LABELS (not positional
125
+ // digits/letters) so the answer is unambiguous to the model regardless of option
126
+ // ordering. Returns '' when nothing resolvable was selected (caller falls back to
127
+ // teardown). Free-text/"Other" combine is deferred to Phase 1 (#5776 option B).
128
+ export function formatMultiSelectReinject(questions, answersMap) {
129
+ const map = (answersMap && typeof answersMap === 'object') ? answersMap : {}
130
+ const lines = []
131
+ for (const q of questions) {
132
+ if (!q || !q.question) continue
133
+ // #5796 — sanitize each label before it joins the text that gets typed into
134
+ // the live PTY (strip control chars, notably CR/LF/ESC); drop any that
135
+ // sanitize down to empty so they don't leave stray separators.
136
+ const labels = parseSelectedLabels(map[q.question])
137
+ .map(sanitizeReinjectLabel)
138
+ .filter(Boolean)
139
+ if (labels.length === 0) continue
140
+ lines.push(`For "${q.question}": ${labels.join(', ')}`)
141
+ }
142
+ return lines.join('\n')
143
+ }
144
+
145
+ // #5800 — refusal table for the multi-select reinject pre-flight guards. Each
146
+ // reinject guard (empty selection / busy session / not-runnable session /
147
+ // flag-off unsupported) used to inline a near-identical
148
+ // warn → _teardownAskUserQuestion(...) → return block that differed only by
149
+ // these four strings. The strings are the WIRE CONTRACT — the dashboard + app
150
+ // branch on errorCode, and tests assert the exact codes — so they are pinned
151
+ // here verbatim. _refuseReinject() looks a reason up here and tears down; the
152
+ // distinct rationale comment for each guard stays at the call site.
153
+ const REINJECT_REFUSALS = {
154
+ // Nothing resolvable was selected — recover via teardown rather than send an
155
+ // empty turn.
156
+ empty: {
157
+ synthResult: 'No selection received for the multi-select question.',
158
+ emitResultReason: 'ask_user_question_multiselect_empty',
159
+ errorCode: 'ASK_USER_QUESTION_MULTISELECT_EMPTY',
160
+ errorMessage: 'No selection received. Tap Retry to resend your request.',
161
+ },
162
+ // The answer raced ahead of the denied turn's Stop-hook teardown, so the
163
+ // session is still busy; surface a retryable error instead of silently
164
+ // dropping the selection (#5776 busy-race).
165
+ busy: {
166
+ synthResult: 'Multi-select answer arrived before the previous turn finished; not delivered.',
167
+ emitResultReason: 'ask_user_question_multiselect_busy',
168
+ errorCode: 'ASK_USER_QUESTION_MULTISELECT_BUSY',
169
+ errorMessage: 'Your selection arrived while the previous turn was still finishing. Tap Retry to resend it.',
170
+ },
171
+ // The session isn't runnable (PTY exited / not yet started); tear down with a
172
+ // retryable error BEFORE clearing state so the user can resend once it's back
173
+ // (#5781 review / #5784).
174
+ unavailable: {
175
+ synthResult: 'Multi-select answer could not be delivered; the session was not running.',
176
+ emitResultReason: 'ask_user_question_multiselect_unavailable',
177
+ errorCode: 'ASK_USER_QUESTION_MULTISELECT_UNAVAILABLE',
178
+ errorMessage: 'Your selection could not be delivered — the session wasn\'t running. Tap Retry once it\'s back.',
179
+ },
180
+ // Default (flag-off) behavior: multi-select is denied at the permission hook;
181
+ // refuse to drive keystrokes for a form we can't reliably toggle+submit.
182
+ unsupported: {
183
+ synthResult: 'Multi-select questions aren\'t supported by the TUI provider. Ask one single-select question at a time.',
184
+ emitResultReason: 'ask_user_question_multiselect_unsupported',
185
+ errorCode: 'ASK_USER_QUESTION_MULTISELECT_UNSUPPORTED',
186
+ errorMessage: 'Multi-select questions aren\'t supported here. Tap Retry to resend your request.',
187
+ },
188
+ }
189
+
190
+ // --- interactive-form driver: an injected collaborator of ClaudeTuiSession (#5617) ---
191
+ export class FormDriver {
192
+ /**
193
+ * @param {FormDriverHost} host — the owning ClaudeTuiSession (or a mock in tests).
194
+ */
195
+ constructor(host) {
196
+ this._host = host
197
+ }
198
+
199
+ /**
200
+ * Send a response to an AskUserQuestion prompt (#4278). The dashboard's
201
+ * QuestionPrompt UI fires this when the user submits. Supported shapes:
202
+ *
203
+ * - Single-question, single-select (`questions.length === 1`, the v0.9.4
204
+ * happy path): write the 1-indexed option digit through the throttled
205
+ * writer, which appends \r. claude TUI's prompt accepts either; Enter is
206
+ * redundant but harmless. Pin-tested via #4290. Options beyond the
207
+ * single-digit hotkey range (idx >= 9) drive via arrow-key navigation
208
+ * (#4848, _writePtyArrowNavSequence).
209
+ *
210
+ * - Single-question, multi-select (#5776): claude TUI is keyboard-only with
211
+ * no reliable multi-toggle+submit sequence, so multi-select is denied at
212
+ * the permission hook and (flag-gated) reinjected as text — the chosen
213
+ * labels are formatted (formatMultiSelectReinject) and sent as the next
214
+ * user message rather than driven as keystrokes.
215
+ *
216
+ * - Multi-QUESTION forms (`questions.length > 1`): denied at the permission
217
+ * hook since #4648; the keystroke assembler that drove them was removed in
218
+ * #5773. If such an entry reaches here (a fail-open hook) it is refused
219
+ * with a retryable teardown, never driven.
220
+ *
221
+ * `answersMap` keys are the question text (`q.question`), values are either
222
+ * the chosen option's label string (single-select) or a JSON-encoded
223
+ * `["label1","label2"]` array / comma-joined list (multi-select).
224
+ *
225
+ * No-op when no pending answer.
226
+ *
227
+ * @param {string} text — the chosen answer (single-question path); on the
228
+ * Other / freeform path (#4651) this is the Other option's label, used
229
+ * to resolve the 1-indexed TUI digit.
230
+ * @param {object} [answersMap] — `{ [questionText]: string | string[] }`;
231
+ * used by the single multi-select reinject path (#5776).
232
+ * @param {string} [toolUseId] — #4668: target the specific pending entry
233
+ * to answer when multiple AskUserQuestion tool_uses are in flight in
234
+ * the same turn. When omitted, falls back to the most-recently-set
235
+ * pending entry via the back-compat getter.
236
+ * @param {object} [opts] — extra options.
237
+ * @param {string} [opts.freeformText] — #4651 single-question Other path:
238
+ * when set, the session writes the Other digit (resolved from `text`),
239
+ * waits ~150 ms for claude TUI's option-menu → text-input prompt swap,
240
+ * then writes `freeformText` + Enter. Dropped when the chosen option
241
+ * doesn't exist or sits beyond the single-digit hotkey range.
242
+ */
243
+ respondToQuestion(text, answersMap, toolUseId, opts) {
244
+ // #4668: route to the specific pending entry the dashboard answered
245
+ // for. Pre-#4668 chroxy stored a single pending answer in a field
246
+ // and respondToQuestion always read THAT field — so when claude TUI
247
+ // emitted parallel AskUserQuestion tool_use blocks in one turn, the
248
+ // field got overwritten and the user's answer landed in the wrong
249
+ // toolUseId's slot. Now: if the dashboard supplied a toolUseId, look
250
+ // it up in the Map; if not (legacy clients), fall back to the most-
251
+ // recently-set entry via the back-compat getter so behaviour matches
252
+ // pre-#4668 for the single-pending case.
253
+ //
254
+ // #4651: `opts.freeformText` triggers the Other / freeform path —
255
+ // server resolves the chosen option label to its 1-indexed digit,
256
+ // writes the digit to open claude TUI's text-input prompt, waits
257
+ // ~150 ms for the prompt swap, then writes the freeform text + Enter
258
+ // to submit. Mutually exclusive with answersMap (multi-question
259
+ // Other is out of scope per #4648).
260
+ // #5796 — the freeform/"Other" text is untrusted client input that gets
261
+ // TYPED into the live claude TUI PTY (stage-2 write below). Sanitize control
262
+ // chars (notably CR/LF/ESC) out of it the same way as multi-select labels so
263
+ // a crafted value can't submit the composer early or inject escape sequences.
264
+ const rawFreeform = (opts && typeof opts.freeformText === 'string' && opts.freeformText.length > 0)
265
+ ? sanitizeReinjectLabel(opts.freeformText)
266
+ : ''
267
+ const freeformText = rawFreeform.length > 0 ? rawFreeform : null
268
+ let entry = null
269
+ if (toolUseId && this._host._pendingUserAnswers.has(toolUseId)) {
270
+ entry = this._host._pendingUserAnswers.get(toolUseId)
271
+ } else if (toolUseId && this._host._pendingUserAnswers.size > 0) {
272
+ // Dashboard sent a toolUseId we don't have a pending entry for.
273
+ // Common cause: stale answer arriving after the turn's teardown
274
+ // cleared the Map (watchdog fire, user gave up + the late answer
275
+ // came in). Log + drop rather than write keystrokes into whatever
276
+ // form happens to be currently rendered.
277
+ // #4828: session-scoped — respondToQuestion runs strictly post-start.
278
+ ;(this._host._log || log).warn(`respondToQuestion: dashboard sent toolUseId=${toolUseId} but no matching pending entry (Map.size=${this._host._pendingUserAnswers.size} keys=${[...this._host._pendingUserAnswers.keys()].join(',')}) — dropping`)
279
+ return
280
+ } else {
281
+ // Legacy / unidentified path: route to the most-recent entry via
282
+ // the back-compat getter. Maintains the pre-#4668 behaviour for
283
+ // single-pending cases and for callers that haven't been updated
284
+ // to pass toolUseId.
285
+ //
286
+ // #4688: warn when the dashboard omitted toolUseId AND we have
287
+ // multiple pending entries — the back-compat fallback picks the
288
+ // most-recent entry by insertion order, which may not be what
289
+ // the user intended. Loud log so the wedge symptom is greppable.
290
+ if (!toolUseId && this._host._pendingUserAnswers.size > 1) {
291
+ // #4828: session-scoped.
292
+ ;(this._host._log || log).warn(`respondToQuestion: dashboard omitted toolUseId but ${this._host._pendingUserAnswers.size} pending entries exist (keys=${[...this._host._pendingUserAnswers.keys()].join(',')}) — falling back to most-recent which may misroute`)
293
+ }
294
+ entry = this._host._pendingUserAnswer
295
+ }
296
+ const prevToolUseId = entry?.toolUseId || null
297
+ const pendingQuestions = entry?.questions || []
298
+ const answersMapKeyCount = answersMap && typeof answersMap === 'object' ? Object.keys(answersMap).length : 0
299
+ // #4828: session-scoped.
300
+ ;(this._host._log || log).info(`respondToQuestion: tool=${prevToolUseId || '?'} dashboardToolUseId=${toolUseId || 'none'} text.length=${(text || '').length} answersMap.keys=${answersMapKeyCount} questions=${pendingQuestions.length} options=${entry?.options?.length || 0} pendingMapSize=${this._host._pendingUserAnswers.size}`)
301
+ if (!entry) return
302
+ // #5320 (WP-3.3) — arm the stall watchdog the MOMENT we have a live pending
303
+ // entry the dashboard tried to answer, BEFORE any early-return below. The
304
+ // dashboard clears its QuestionPrompt UI when it sends an answer, so ANY
305
+ // respondToQuestion that finds an entry but then bails — the unactionable
306
+ // cases here (non-string / empty text + no answersMap), the validation drops
307
+ // in the freeform path (no options, option-not-found), or `!this._host._term` —
308
+ // would otherwise leave the turn wedged until the 2h hard cap with no
309
+ // dashboard prompt. Arming here (it does NOT clear the pending) gives every
310
+ // such path recovery; a real follow-up answer re-arms idempotently (same
311
+ // key), and the success paths re-arm with a fresh post-write window (the
312
+ // Other-freeform IIFE with its longer second-stage window).
313
+ this._host._armAskUserQuestionWatchdog(prevToolUseId)
314
+ // #5771: a SINGLE multi-select question is denied at the permission hook
315
+ // (permission-hook.sh) because claude TUI is keyboard-only and has no
316
+ // reliable single-toggle+submit keystroke sequence (0/7 production success —
317
+ // swarm audit 2026-06-13, see docs/audit-results/claude-tui-askuserquestion-
318
+ // form-driving/). Defense in depth: if a single multiSelect question reaches
319
+ // the driver anyway (hook failed open on a parse error, or a client bypassed
320
+ // it), refuse to drive it rather than write a wrong single digit, and tear
321
+ // down NOW so the turn recovers immediately instead of waiting out the 30s
322
+ // stall watchdog. (Multi-question forms are denied separately at the hook
323
+ // since #4648 and still flow through the assembler below if hook-bypassed —
324
+ // that dead path is removed in the follow-up cleanup.)
325
+ if (pendingQuestions.length <= 1 && pendingQuestions.some((q) => q && q.multiSelect === true)) {
326
+ // #5800: the single multi-select branch (reinject when flag-on, refuse
327
+ // when flag-off) is its own strategy — extracted so respondToQuestion
328
+ // reads as a router. Pure restructure: no keystroke/timer/teardown change.
329
+ this._reinjectMultiSelect(prevToolUseId, pendingQuestions, answersMap, opts)
330
+ return
331
+ }
332
+ // Single-question / free-text path requires a non-empty `text`. The single
333
+ // multi-select reinject path (#5776) is driven from answersMap (text is
334
+ // ignored when a map is present) so an empty string is permitted there.
335
+ if (typeof text !== 'string') return
336
+ if (text.length === 0 && answersMapKeyCount === 0) return
337
+ const { options } = entry
338
+ const questions = pendingQuestions
339
+ // #4668: clear only this specific entry; sibling pending answers
340
+ // (from parallel AskUserQuestion calls in the same turn) survive.
341
+ this._host._clearPendingAnswerByToolUseId(entry.toolUseId)
342
+ if (!this._host._term) return
343
+ // #4668 diagnostic: capture the PTY output tail just before we write
344
+ // the answer keystroke. The wedge symptom observed 2026-06-01 was
345
+ // "chroxy wrote bytes=1 → TUI silent for 30s → watchdog fires" with
346
+ // no visibility into whether the TUI's input prompt was actually
347
+ // ready to receive a digit. Logging the tail hex dump at write-time
348
+ // tells us exactly what the TUI was showing when our keystroke
349
+ // landed — single-keystroke wedges almost always come from a form
350
+ // misalignment that's visible in the trailing render bytes.
351
+ //
352
+ // #4693: rate-limit to once per turn. The multi-question retry-as-
353
+ // singles wedge fires 4+ respondToQuestion calls in succession; each
354
+ // hex dump is ~70 lines (1024 bytes formatted 16/line + header), so an
355
+ // unbounded emission pumps 280+ lines of diagnostic per affected turn.
356
+ // We stash the emission flag on the active turn object so it resets
357
+ // automatically on every new sendMessage() (which allocates a fresh
358
+ // `_activeTurn`). Subsequent answers in the same turn emit a compact
359
+ // one-line skip notice carrying the tool ids so a log reader can still
360
+ // grep all answer-write events without scanning past 200+ hex lines.
361
+ // #4792: PTY tail hex dumps are the highest-volume, most-sensitive
362
+ // unscoped log lines pre-fix — they emit literal terminal bytes
363
+ // (user prompts, answer text, attachment names) on every
364
+ // respondToQuestion. Routing them through the session-bound logger
365
+ // makes the audit story clean: only operators bound to this session
366
+ // (or unbound) see the dump (#4787 fan-out filter).
367
+ const slog = this._host._log || log
368
+ const turn = this._host._activeTurn
369
+ if (turn && !turn.hexDumpEmitted) {
370
+ slog.info(`respondToQuestion PTY tail before write (tool=${prevToolUseId || '?'}):\n${this._host._outputTailLogDump()}`)
371
+ turn.hexDumpEmitted = true
372
+ } else if (turn) {
373
+ slog.info(`respondToQuestion PTY tail hex dump skipped (tool=${prevToolUseId || '?'}) — already emitted for turn msg=${turn.messageId || '?'}`)
374
+ } else {
375
+ // No active turn (defensive — tests that drive respondToQuestion
376
+ // directly without sendMessage(), late watchdog teardown races).
377
+ // Emit the dump so the diagnostic is still useful in those paths.
378
+ slog.info(`respondToQuestion PTY tail before write (tool=${prevToolUseId || '?'}):\n${this._host._outputTailLogDump()}`)
379
+ }
380
+
381
+ const armWatchdog = () => {
382
+ // #4604: arm a stall watchdog. If claude TUI never emits PostToolUse
383
+ // for this AskUserQuestion (a form shape we don't yet drive),
384
+ // the watchdog clears _isBusy + _pendingUserAnswer and emits
385
+ // ASK_USER_QUESTION_STALL so the dashboard prompts the user to
386
+ // retry. Cancelled on PostToolUse (happy path) and on destroy().
387
+ // #5319 (WP-3.2): keyed by this tool's id so a parallel sibling's arm
388
+ // doesn't clobber it.
389
+ this._host._armAskUserQuestionWatchdog(prevToolUseId)
390
+ }
391
+
392
+ // Single-question / no-questions-array path (back-compat with the
393
+ // pre-Chunk-B happy path). Stay on _writePtyTextThrottled which
394
+ // appends \r — TUI single-select auto-commits on digit, the trailing
395
+ // Enter is redundant but harmless, and the existing test guards
396
+ // (#4290) assert it's present. Requires non-empty `text`: the
397
+ // single-q path is text-driven, not answersMap-driven.
398
+ if (questions.length <= 1) {
399
+ if (text.length === 0) return
400
+
401
+ // #4651 — Other / freeform path. The dashboard picked the "Other"
402
+ // option AND typed freeform text. claude TUI accepts this as a
403
+ // two-stage flow: press the Other digit (swaps the option-select
404
+ // menu to a text-input prompt), wait for the swap, then type the
405
+ // freeform text + Enter. Resolve the chosen label → digit via the
406
+ // same 1-indexed lookup as the happy path. When the chosen option
407
+ // doesn't exist (or sits beyond the single-digit hotkey range),
408
+ // drop the answer — blindly writing the freeform text at the
409
+ // digit menu is the #4288 jump-nav footgun and the dashboard
410
+ // shouldn't have been able to send freeformText for an
411
+ // AskUserQuestion without an Other option in the first place.
412
+ if (freeformText) {
413
+ if (!Array.isArray(options) || options.length === 0) {
414
+ // #4828: session-scoped.
415
+ ;(this._host._log || log).warn(`respondToQuestion: freeformText supplied for question with no options (tool=${prevToolUseId || '?'}) — dropping`)
416
+ return
417
+ }
418
+ const otherIdx = options.findIndex((o) => o && o.label === text)
419
+ if (otherIdx < 0 || otherIdx >= 9) {
420
+ // #4828: session-scoped.
421
+ ;(this._host._log || log).warn(`respondToQuestion: freeformText supplied but chosen option "${text}" not found (or beyond single-digit hotkey range) in pending options for tool=${prevToolUseId || '?'} — dropping`)
422
+ return
423
+ }
424
+ const otherDigit = String(otherIdx + 1)
425
+ // Stage 1: write the digit. _writePtyTextThrottled appends \r —
426
+ // for the option-select menu the trailing \r commits the digit
427
+ // (same shape as the happy single-select path).
428
+ // Stage 2: after OTHER_FREEFORM_SETTLE_MS, write the freeform
429
+ // text + \r via the same throttled writer. claude TUI's text-
430
+ // input prompt accepts typed input directly (no jump-nav),
431
+ // and the trailing \r submits.
432
+ const tag = prevToolUseId || '?'
433
+ ;(async () => {
434
+ // #4808: destroy() can run during ANY of the awaits below
435
+ // (stage-1 write, settle pause, stage-2 write). Without a
436
+ // guard after each await the IIFE keeps running and:
437
+ // - re-arms a `_askUserQuestionWatchdogs` entry past destroy(),
438
+ // leaking a 30s timer that pins `this` in its closure
439
+ // even though `_onAskUserQuestionStall`'s _destroying
440
+ // guard silences the eventual emit
441
+ // - calls `_writePtyTextThrottled(freeformText)` against
442
+ // a `_term` that destroy() set to null, throwing inside
443
+ // the inner write loop
444
+ // Bail out at every await boundary instead.
445
+ const stage1ok = await this._host._writePtyTextThrottled(otherDigit).catch((err) => {
446
+ // #4828: session-scoped.
447
+ ;(this._host._log || log).warn(`respondToQuestion Other-digit PTY write failed: ${err.message} (tool=${tag})`)
448
+ return false
449
+ })
450
+ // #5320 (WP-3.3) — also bail if the turn was ABORTED (interrupt() sets
451
+ // _activeTurn.aborted but does not flip _destroying). Without this the
452
+ // IIFE would keep driving keystrokes into a turn the user already
453
+ // interrupted, and re-arm a watchdog interrupt() just cleared.
454
+ if (this._host._destroying || this._host._activeTurn?.aborted) return
455
+ if (!stage1ok) return
456
+ await new Promise((resolve) => setTimeout(resolve, OTHER_FREEFORM_SETTLE_MS))
457
+ if (this._host._destroying || this._host._activeTurn?.aborted) return
458
+ // Belt-and-braces: destroy() sets _destroying before nulling
459
+ // _term in the same synchronous frame, so the guard above
460
+ // already covers the destroy() race. This null-check is
461
+ // cheap insurance against a future path that releases _term
462
+ // without flipping _destroying (e.g. a PTY-exit handler) —
463
+ // skip the re-arm AND the stage-2 write together so the
464
+ // watchdog never fires for a session that no longer has a
465
+ // PTY behind it.
466
+ if (!this._host._term) return
467
+ // Re-arm the watchdog so the freeform write phase has a fresh
468
+ // OTHER_FREEFORM_WATCHDOG_MS window — the stage-1 arm already
469
+ // counted the settle delay against the original 30s budget.
470
+ // #5319 (WP-3.2): keyed by this tool's id, longer second-stage window.
471
+ this._host._armAskUserQuestionWatchdog(prevToolUseId, OTHER_FREEFORM_WATCHDOG_MS)
472
+ await this._host._writePtyTextThrottled(freeformText).catch((err) => {
473
+ // #4828: session-scoped.
474
+ ;(this._host._log || log).warn(`respondToQuestion Other-freeform PTY write failed: ${err.message} (tool=${tag})`)
475
+ })
476
+ })()
477
+ armWatchdog()
478
+ return
479
+ }
480
+
481
+ // #4290: if the chosen label matches one of the structured options
482
+ // exactly, write the 1-indexed TUI shortcut (e.g. "2") instead of
483
+ // the label text. v0.9.3 wrote the raw label and claude TUI's
484
+ // prompt parser single-character-jump-navigated through the menu,
485
+ // landing on "Other" (see #4288 for the empirical trace). Numbered
486
+ // shortcuts hit claude TUI's hotkey path directly. When no exact
487
+ // match is found (user picked "Other" in the dashboard and typed
488
+ // freeform text), fall through to typing the answer literally —
489
+ // claude TUI's Other-path may still mis-parse that, tracked in
490
+ // #4288 as a separate concern.
491
+ let writeText = text
492
+ // #5803 — track whether we resolved the answer to a safe hotkey digit.
493
+ // If not, `writeText` stays the untrusted literal client answer and must
494
+ // be sanitized before it reaches the PTY (same threat as reinject labels).
495
+ let isHotkeyDigit = false
496
+ if (Array.isArray(options) && options.length > 0) {
497
+ const matchIdx = options.findIndex((o) => o && o.label === text)
498
+ // #4292 + #4746 + #4848: single-digit hotkey covers indices 0..8.
499
+ // For matched picks at idx >= 9 we drive the form via arrow-key
500
+ // navigation instead of the hotkey alphabet — Down arrow (`\x1b[B`)
501
+ // N times moves the cursor from the top option (idx 0) to the
502
+ // target idx, and Enter (`\r`) commits the highlighted option
503
+ // (#4848). Pre-#4848 this path tore the turn down with a
504
+ // structured ASK_USER_QUESTION_TOO_MANY_OPTIONS error (#4746)
505
+ // because the empirical multi-digit keystroke for option 10+
506
+ // was unrecorded; arrow-key navigation was always one of the two
507
+ // candidate paths the recorder script (scripts/tui-form-recorder.mjs)
508
+ // called out and is the more conservative bet (single-keystroke
509
+ // menus that auto-commit on the first digit can't be driven via
510
+ // multi-digit chord like '1','0'; arrow keys are the standard
511
+ // claude TUI navigation primitive used elsewhere in its form
512
+ // pickers).
513
+ //
514
+ // #4880 (resolved 2026-06-07): the recorder pass against a 10+ option
515
+ // AskUserQuestion finally ran (docs/empirical/4880-twelve-option-cap.jsonl)
516
+ // and found the form is UNREACHABLE: claude TUI v2.1.168's
517
+ // AskUserQuestion tool hard-caps each question at 4 options. A prompt
518
+ // asking for 12 options fails server-side with
519
+ // `InputValidationError: too_big, maximum: 4, path: questions[0].options`
520
+ // before any form renders — so `matchIdx >= 9` can never be hit via a
521
+ // real AskUserQuestion on this TUI version. This branch is therefore
522
+ // currently DEAD CODE, retained as forward-compat: if a future claude
523
+ // raises the option cap, the arrow-nav drive is ready. The `\x1b[B`
524
+ // (Down) + `\r` (Enter) bytes remain the best-available unverified
525
+ // sequence — they could not be empirically pinned because the form
526
+ // can't be produced. Revisit if/when the cap is raised.
527
+ //
528
+ // Scoped to MATCHED picks at idx >= 9. An unmatched label still
529
+ // falls through to typing the literal text (the v0.9.3 / pre-#4292
530
+ // path) so the Other / freeform back-compat case is preserved.
531
+ if (matchIdx >= 9) {
532
+ const total = options.length
533
+ ;(this._host._log || log).info(`AskUserQuestion single-question: question has ${total} options and the user picked option ${matchIdx + 1} ("${(text || '').slice(0, 40)}") — driving via arrow-key navigation (#4848) (tool=${prevToolUseId || '?'})`)
534
+ this._host._writePtyArrowNavSequence(matchIdx).catch((err) => {
535
+ ;(this._host._log || log).warn(`respondToQuestion arrow-nav PTY write failed: ${err.message} (tool=${prevToolUseId || '?'})`)
536
+ })
537
+ armWatchdog()
538
+ return
539
+ }
540
+ if (matchIdx >= 0 && matchIdx < 9) {
541
+ writeText = String(matchIdx + 1)
542
+ isHotkeyDigit = true
543
+ }
544
+ }
545
+ // #5803 — the literal-answer fallthrough (no hotkey/arrow match, e.g. the
546
+ // Other/freeform back-compat path) types untrusted client text straight
547
+ // into the live PTY. Sanitize control chars (CR/LF/ESC) out of it the
548
+ // same way as multi-select reinject labels so a crafted answer can't
549
+ // submit the composer early or inject terminal escape sequences. The
550
+ // hotkey-digit path is already a single safe char and is left untouched.
551
+ if (!isHotkeyDigit) {
552
+ writeText = sanitizeReinjectLabel(writeText)
553
+ }
554
+ // Fire-and-forget — the write is async due to the per-char throttle,
555
+ // but the caller (handleUserQuestionResponse) is sync. Errors here
556
+ // are non-fatal; worst case the user re-sends the answer.
557
+ this._host._writePtyTextThrottled(writeText).catch((err) => {
558
+ // #4828: session-scoped.
559
+ ;(this._host._log || log).warn(`respondToQuestion PTY write failed: ${err.message} (tool=${prevToolUseId || '?'})`)
560
+ })
561
+ armWatchdog()
562
+ return
563
+ }
564
+
565
+ // #5773: claude TUI multi-QUESTION forms (questions.length > 1) are denied at
566
+ // the permission hook (since #4648), so this path is unreachable in production.
567
+ // The keystroke assembler that drove them (toggle-digit + Tab + Submit settle
568
+ // timing, #4604 Chunk B) and _writePtyMultiQuestionSequence have been removed
569
+ // as a version-pinned maintenance liability (swarm audit 2026-06-13). Keep a
570
+ // defense-in-depth refusal: if a multi-question entry ever reaches
571
+ // respondToQuestion (a fail-open hook), tear the turn down cleanly instead of
572
+ // driving guessed keystrokes — mirroring the hook deny. Single-question and
573
+ // single multi-select (reinject, #5776) are handled above and return early.
574
+ ;(this._host._log || log).warn(`AskUserQuestion: refusing ${questions.length}-question form (tool=${prevToolUseId || '?'}) — multi-question is denied at the permission hook; not driving keystrokes`)
575
+ this._teardownAskUserQuestion(prevToolUseId, {
576
+ synthResult: 'Multi-question AskUserQuestion forms aren\'t supported by the TUI provider. Ask one single-select question at a time.',
577
+ emitResultReason: 'ask_user_question_multi_question_unsupported',
578
+ errorCode: 'ASK_USER_QUESTION_MULTI_QUESTION_UNSUPPORTED',
579
+ errorMessage: 'Multi-question forms aren\'t supported here. Tap Retry to resend as single questions.',
580
+ })
581
+ }
582
+
583
+ /**
584
+ * #5800 — refuse a multi-select reinject: warn + tear the turn down with the
585
+ * pinned wire payload for `reason` (a key of REINJECT_REFUSALS). Collapses the
586
+ * four near-identical warn → _teardownAskUserQuestion → return blocks the
587
+ * reinject guards used to inline. The error codes/messages/synthResults are
588
+ * UNCHANGED (they're the wire contract); only the duplication is gone.
589
+ * Callers still `return` after calling this (it does not itself return).
590
+ *
591
+ * @param {string|null} toolUseId — the pending entry's tool id.
592
+ * @param {'empty'|'busy'|'unavailable'|'unsupported'} reason — refusal kind.
593
+ * @param {string} warnMessage — the (reason-specific) diagnostic log line.
594
+ */
595
+ _refuseReinject(toolUseId, reason, warnMessage) {
596
+ ;(this._host._log || log).warn(warnMessage)
597
+ this._teardownAskUserQuestion(toolUseId, REINJECT_REFUSALS[reason])
598
+ }
599
+
600
+ /**
601
+ * #5800 — the single multi-select strategy, extracted from respondToQuestion
602
+ * so it reads as a router. When the reinject flag is ON, format the picked
603
+ * labels into plain text and feed claude a fresh turn via sendMessage() (the
604
+ * denied form never rendered → no live form, no PostToolUse). When OFF, refuse
605
+ * + tear down (default behavior preserved). Pre-flight guards (empty / busy /
606
+ * not-runnable) tear down with a retryable error via _refuseReinject instead
607
+ * of reaching sendMessage in a state where the selection would be dropped with
608
+ * no retry path. Pure restructure of the former inline block (#5776/#5781):
609
+ * same control flow, same teardown payloads, same clear ordering.
610
+ *
611
+ * @param {string|null} prevToolUseId — the pending entry's tool id.
612
+ * @param {object[]} pendingQuestions — the entry's questions array.
613
+ * @param {object} [answersMap] — `{ [questionText]: string | string[] }`.
614
+ * @param {object} [opts] — extra options (freeformText is dropped, Phase 1).
615
+ */
616
+ _reinjectMultiSelect(prevToolUseId, pendingQuestions, answersMap, opts) {
617
+ // #5776 (Phase 0) — reinject path: format the selection into text and feed
618
+ // it to claude as a new turn instead of driving (un-drivable) keystrokes.
619
+ // The form was denied at permission-hook.sh before it rendered, so there is
620
+ // no live form and no PostToolUse — claude has stopped and is waiting for
621
+ // the next user message (verified live 2026-06-13). Gated by the env flag;
622
+ // when off, fall through to the original refuse-and-teardown behavior.
623
+ if (multiSelectReinjectEnabled()) {
624
+ const reinjectText = formatMultiSelectReinject(pendingQuestions, answersMap)
625
+ if (opts && typeof opts.freeformText === 'string' && opts.freeformText.length > 0) {
626
+ // Phase 1 (#5776 option B) — free-text combine deferred. Log so a
627
+ // dropped custom answer is visible rather than silent.
628
+ ;(this._host._log || log).warn(`respondToQuestion: multiSelect reinject dropping freeformText (Phase 1, #5776 option B) tool=${prevToolUseId || '?'}`)
629
+ }
630
+ if (reinjectText.length === 0) {
631
+ // Nothing resolvable selected — recover via teardown rather than send
632
+ // an empty turn.
633
+ this._refuseReinject(prevToolUseId, 'empty',
634
+ `respondToQuestion: multiSelect reinject produced empty text (tool=${prevToolUseId || '?'}) — tearing down`)
635
+ return
636
+ }
637
+ // #5776 — the reinject only works once the in-flight (denied) turn has
638
+ // wound down to idle. sendMessage() reports failure via a typed result
639
+ // (#5800: { ok:false, reason:'busy' }) — and still emit('error')s — when
640
+ // _isBusy is true, so a .catch can't observe the drop. In the normal flow
641
+ // the model stops on the deny, its Stop hook drains, and the session is
642
+ // idle by the time the human answers seconds later (verified live
643
+ // 2026-06-13). But if the answer races ahead of that Stop-hook teardown,
644
+ // or the model ignored the deny, the turn is still busy — and silently
645
+ // dropping the selection would wedge the session until the 2h hard cap.
646
+ // Pre-flight on _isBusy here (rather than calling sendMessage and reading
647
+ // its result) so we surface a retryable error WITHOUT firing a redundant
648
+ // emit('error') and WITHOUT clearing the pending state first; the user can
649
+ // resend once the turn has settled (the teardown is a no-op-safe interleave
650
+ // with the Stop-hook drain via the poll loop's !_isBusy early return). A
651
+ // future Phase 1 robustness pass can await-idle and deliver seamlessly.
652
+ if (this._host._isBusy) {
653
+ this._refuseReinject(prevToolUseId, 'busy',
654
+ `respondToQuestion: multiSelect reinject deferred — session still busy (tool=${prevToolUseId || '?'}); the answer raced the turn teardown`)
655
+ return
656
+ }
657
+ // sendMessage() has a SECOND fail-open guard beyond _isBusy: if the
658
+ // session isn't runnable (!_processReady / no _term / _ptyExited) it
659
+ // emit('error')s + returns { ok:false, reason:'not_runnable' } (#5800)
660
+ // without starting a turn. We clear the pending entry + watchdog + lock
661
+ // just below, so reaching sendMessage in that state would drop the
662
+ // selection with no retry path (same wedge class the _isBusy guard
663
+ // closes). Mirror that guard here: tear down with a retryable error BEFORE
664
+ // clearing state so the user can resend once the session is back. (#5781
665
+ // review / #5784)
666
+ if (!this._host._processReady || !this._host._term || this._host._ptyExited) {
667
+ this._refuseReinject(prevToolUseId, 'unavailable',
668
+ `respondToQuestion: multiSelect reinject deferred — session not runnable (tool=${prevToolUseId || '?'}); PTY exited or not yet started`)
669
+ return
670
+ }
671
+ ;(this._host._log || log).info(`respondToQuestion: multiSelect reinject (flag on) tool=${prevToolUseId || '?'} text="${reinjectText.slice(0, 80)}"`)
672
+ // The denied form left a pending entry + armed watchdog; clear both, plus
673
+ // the sibling lock, before starting the new turn.
674
+ this._host._clearPendingAnswerByToolUseId(prevToolUseId)
675
+ this._host._clearAskUserQuestionWatchdog(prevToolUseId)
676
+ this._host._clearAskUserQuestionLock()
677
+ // #5798 (observability-only): open the stop-and-wait watch window. The
678
+ // deny reason steered the model to STOP its turn so this reinjected
679
+ // selection lands as a fresh turn; if instead the model emits another
680
+ // tool_use before the reinjected turn's first output clears this marker,
681
+ // _emitToolHookEvent(PreToolUse) logs a loud WARN (reinject_stop_wait_
682
+ // violation / #5798). Set ONLY here on the flag-on reinject path — never on
683
+ // the flag-off refusal. No behavior change: just a marker field the session
684
+ // reads to decide whether to emit a measurement WARN. Set BEFORE the send
685
+ // so a failed send can close it again (below).
686
+ this._host._reinjectStopWaitWatch = { deniedToolUseId: prevToolUseId, at: this._host._nowMonotonic() }
687
+ Promise.resolve(this._host.sendMessage(reinjectText)).then((result) => {
688
+ // #5798: if the reinject never actually started a turn (busy/not-runnable
689
+ // race → { ok:false }), close the watch so it can't produce a spurious
690
+ // violation WARN against a turn that never began. Guard on the toolUseId
691
+ // so a stale resolution can't clear a newer reinject's watch.
692
+ if (result && result.ok === false && this._host._reinjectStopWaitWatch?.deniedToolUseId === prevToolUseId) {
693
+ this._host._reinjectStopWaitWatch = null
694
+ }
695
+ }).catch((err) => {
696
+ if (this._host._reinjectStopWaitWatch?.deniedToolUseId === prevToolUseId) {
697
+ this._host._reinjectStopWaitWatch = null
698
+ }
699
+ ;(this._host._log || log).warn(`respondToQuestion: multiSelect reinject sendMessage failed: ${err?.message || err} (tool=${prevToolUseId || '?'})`)
700
+ })
701
+ return
702
+ }
703
+ this._refuseReinject(prevToolUseId, 'unsupported',
704
+ `respondToQuestion: refusing single multiSelect AskUserQuestion (tool=${prevToolUseId || '?'}) — multi-select is denied at the permission hook; not driving keystrokes`)
705
+ }
706
+
707
+ /**
708
+ * Watchdog handler for an AskUserQuestion answer that claude TUI never
709
+ * acknowledged via PostToolUse (#4604). Multi-question forms render a
710
+ * per-question form needing more than the single digit chroxy writes,
711
+ * leaving _isBusy=true forever. We tear the turn down end-to-end and
712
+ * surface a structured error so the dashboard renders a retry prompt
713
+ * AND the Working banner / Stop button clear immediately.
714
+ *
715
+ * Pre-#4645 this only cleared `_isBusy` + emitted the stall error,
716
+ * leaving `stream_start` orphaned (no matching `stream_end`) and no
717
+ * `result` for the event-normalizer to fan into `agent_idle`. The
718
+ * dashboard kept showing "Working… Ns ago" + Stop forever (until the
719
+ * 5-min #4638 stream-stall watchdog or the 2h hard cap eventually
720
+ * cleaned up) even though the agent had already given up. Worse: the
721
+ * red error toast told the user to retry, but the Stop button was up
722
+ * and the input box read "Type to send follow-up…" — there was no
723
+ * Send affordance to retry FROM.
724
+ *
725
+ * Now: best-effort Ctrl-C into the TUI (so `claude` itself unsticks
726
+ * from the form screen for the next turn) → emit `stream_end` →
727
+ * `_emitResult` (sweeps orphan tool_starts and fans `result` →
728
+ * `agent_idle` via the event-normalizer, clearing both Working banner
729
+ * and Stop) → emit `error{code:'ASK_USER_QUESTION_STALL'}` last so the
730
+ * dashboard surfaces the user-facing toast AFTER state has settled.
731
+ *
732
+ * Shape mirrors `_handleStreamStall` and `_handleHardTimeout` (which
733
+ * delegate to `_teardownTurn` per #4641). This path is NOT folded into
734
+ * `_teardownTurn` because it has additional side-effects (synthetic
735
+ * `tool_result` emit, clears all three inactivity timers, error
736
+ * payload carries `toolUseId`) that don't generalise to the other two
737
+ * teardown sites — bringing it in would either widen the helper's
738
+ * surface or split the call into multiple stages, neither of which
739
+ * earns its complexity today.
740
+ *
741
+ * No-ops on destroyed sessions and on sessions where PostToolUse
742
+ * already arrived (would have cleared _pendingUserAnswer + busy state
743
+ * in the normal flow before the watchdog timer fired).
744
+ */
745
+ _onAskUserQuestionStall(toolUseId) {
746
+ if (this._host._destroying) return
747
+ if (!this._host._pendingUserAnswer && !this._host._isBusy) return
748
+
749
+ this._host._assertBusyHasMessageId('_onAskUserQuestionStall')
750
+ // #4828: session-scoped — stall watchdog fires strictly post-start.
751
+ ;(this._host._log || log).warn(`AskUserQuestion stall: tool=${toolUseId} — claude TUI never emitted PostToolUse after answer write (${ASK_USER_QUESTION_WATCHDOG_MS}ms). Likely a multi-question form (#4604). Tearing down turn so the session is recoverable.`)
752
+
753
+ this._teardownAskUserQuestion(toolUseId, {
754
+ synthResult: 'AskUserQuestion stalled — no response from claude TUI within 30s. Likely a multi-question form (#4604).',
755
+ emitResultReason: 'ask_user_question_stall',
756
+ errorCode: 'ASK_USER_QUESTION_STALL',
757
+ // #4648: dropped the "likely a multi-question form" jargon. The
758
+ // permission-hook deny path (also #4648) prevents most multi-question
759
+ // forms from reaching this code path at all, and for the cases that
760
+ // slip through, the user doesn't care about chroxy internals — they
761
+ // care about how to recover. The new copy is action-oriented.
762
+ errorMessage: 'Couldn\'t deliver your answers. Tap Retry to resend your original request.',
763
+ })
764
+ }
765
+
766
+ /**
767
+ * Shared teardown for AskUserQuestion failure modes. Used by both the
768
+ * 30s post-write stall watchdog (#4604) and the up-front
769
+ * too-many-options detector (#4625). Mirrors the end-to-end teardown
770
+ * order pinned in #4645: synthetic tool_result → Ctrl-C the TUI →
771
+ * clear inactivity timers → null active turn / busy state →
772
+ * stream_end + _emitResult → error event last. The caller supplies the
773
+ * synth result text, _emitResult reason tag, and error code/message so
774
+ * the same teardown serves both call sites.
775
+ *
776
+ * Splitting this out (vs the original inline form in
777
+ * _onAskUserQuestionStall) is intentional: #4625's too-many-options
778
+ * path needs the full teardown so the dashboard's Working banner +
779
+ * Stop button + activeTools entry all clear immediately, but the
780
+ * trigger and copy differ from the 30s stall path. Inlining the
781
+ * teardown twice risked drift; folding both into _teardownTurn would
782
+ * widen the helper's surface (synth tool_result + 3-timer clear +
783
+ * toolUseId-carrying error don't generalise to the other teardown
784
+ * sites), so a dedicated AskUserQuestion teardown helper earns its
785
+ * keep.
786
+ */
787
+ _teardownAskUserQuestion(toolUseId, { synthResult, emitResultReason, errorCode, errorMessage }) {
788
+ const messageId = this._host._currentMessageId
789
+ const duration = this._host._activeTurn ? this._host._nowMonotonic() - this._host._activeTurn.startedAt : 0
790
+
791
+ // #4691: surgical clear — drop ONLY the entry for the tool that
792
+ // timed out. The other teardown sites (_finishTurnError, hard
793
+ // timeout via _teardownTurn, interrupt, destroy) end the whole
794
+ // turn, so wiping the whole Map there is correct. The watchdog is
795
+ // different: it knows the exact toolUseId that wedged (passed to
796
+ // setTimeout in respondToQuestion) and the rest of the turn is
797
+ // still live — sibling AskUserQuestion entries armed by parallel
798
+ // PreToolUse blocks can still see a PostToolUse arrive. Falling
799
+ // back to `_pendingUserAnswer = null` here would re-trigger the
800
+ // back-compat setter → `_pendingUserAnswers.clear()` and wipe
801
+ // those siblings under their own still-live turns, re-introducing
802
+ // the #4668-class state-shape mismatch (dashboard cleared the
803
+ // QuestionPrompt UI when it sent the answer, but the server-side
804
+ // Map is empty — a late retry-as-singles answer with toolUseId B
805
+ // would hit the "no matching pending entry — dropping" path and
806
+ // wedge the next form silently).
807
+ this._host._clearPendingAnswerByToolUseId(toolUseId)
808
+ // #5319 (WP-3.2): cancel THIS tool's stall watchdog. The 30s-stall path
809
+ // arrives here after its own watchdog already self-deleted, but the
810
+ // too-many-options (#4625) path tears down WITHOUT a prior fire, so clear
811
+ // it explicitly. Idempotent; leaves any sibling watchdog intact.
812
+ this._host._clearAskUserQuestionWatchdog(toolUseId)
813
+ this._host._clearAskUserQuestionLock()
814
+ // #4616: emit a synthetic tool_result FIRST so the dashboard's
815
+ // activeTools entry for this AskUserQuestion is cleared. Without it
816
+ // the footer "Running AskUserQuestion · Ns" pill keeps ticking
817
+ // forever even though _isBusy is clear and the user sees the error
818
+ // toast. The handler ignores any fields beyond {toolUseId, result,
819
+ // truncated, images} (see store-core handleToolResult); pairing-by-
820
+ // toolUseId is what drives the activeTools removal in store-core handlers.
821
+ this._host.emit('tool_result', {
822
+ toolUseId,
823
+ result: synthResult,
824
+ truncated: false,
825
+ })
826
+ // #4628: matching tool_start resolved — drop from the in-flight map.
827
+ this._host._trackToolResult(toolUseId)
828
+
829
+ // #4645: best-effort Ctrl-C so claude TUI itself unsticks from the
830
+ // form screen. Without this the next sendMessage's prompt write
831
+ // would queue behind the still-displayed form and silently desync.
832
+ // Mirrors _handleStreamStall / _handleHardTimeout.
833
+ if (this._host._term) {
834
+ try { this._host._term.write('\x03') } catch { /* ignore */ }
835
+ }
836
+
837
+ // Clear all four inactivity timers — turn is over, nothing to
838
+ // backstop, leaving them armed would fire stale callbacks on a
839
+ // session that's already idle.
840
+ if (this._host._resultTimeout) { clearTimeout(this._host._resultTimeout); this._host._resultTimeout = null }
841
+ if (this._host._hardTimeout) { clearTimeout(this._host._hardTimeout); this._host._hardTimeout = null }
842
+ if (this._host._streamStallTimeout) { clearTimeout(this._host._streamStallTimeout); this._host._streamStallTimeout = null }
843
+ // #4732: pre-first-output watchdog. AskUserQuestion only fires
844
+ // mid-turn (post-stream_start), so the first-output watchdog has
845
+ // typically been disarmed already, but clear it explicitly so a
846
+ // pathological race can't leak a live handle past the stall.
847
+ this._host._clearFirstOutputWatchdog()
848
+
849
+ // #4022: drop per-turn attachment dir (same as the other teardown
850
+ // paths) so a failed turn doesn't leak materialized files until destroy().
851
+ this._host._cleanupTurnAttachments(this._host._activeTurn)
852
+ this._host._activeTurn = null
853
+ this._host._isBusy = false
854
+ this._host._currentMessageId = null
855
+
856
+ // #4645: pair the stream_start fired at turn-start with stream_end +
857
+ // result so the dashboard's streamingMessageId + Working banner +
858
+ // Stop button all clear immediately (event-normalizer turns result
859
+ // into result + agent_idle). The if-guard mirrors _handleStreamStall
860
+ // — silent skip is acceptable here because the only way messageId
861
+ // is null is a contract violation (_isBusy=true without an active
862
+ // turn), tracked in #4642.
863
+ if (messageId) this._host.emit('stream_end', { messageId })
864
+ this._host._emitResult(
865
+ { cost: null, duration, usage: null, sessionId: this._host._sessionId },
866
+ emitResultReason,
867
+ )
868
+ this._host.emit('error', {
869
+ code: errorCode,
870
+ message: errorMessage,
871
+ toolUseId,
872
+ })
873
+ }
874
+ }