@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,520 @@
1
+ // claude-tui/pty-driver.js — PTY-write / paste-throttle layer for ClaudeTuiSession.
2
+ //
3
+ // #5559 — pure-move extraction of the PTY layer out of claude-tui-session.js.
4
+ // These helpers + the throttled-write methods carry the most empirically-tuned
5
+ // behaviour in the repo (paste detector defeat via per-char throttle, bracketed-
6
+ // paste handling, the arrow-nav writer). Bodies are moved
7
+ // BYTE-IDENTICAL from the original; only the module location changed. The write
8
+ // methods live on `PtyDriverMixin` and are copied onto ClaudeTuiSession.prototype
9
+ // via applyMixin() in claude-tui-session.js, so `this` still refers to the
10
+ // session instance and every `this._*` / static reference resolves as before.
11
+ import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'fs'
12
+ import { homedir } from 'os'
13
+ import { dirname, join, resolve } from 'path'
14
+ import { fileURLToPath } from 'url'
15
+ import { randomUUID } from 'crypto'
16
+ import { resolveBinary } from '../utils/resolve-binary.js'
17
+ import { createLogger } from '../logger.js'
18
+ // Imported at call-time only (circular-safe): the writer methods read the
19
+ // PROMPT_CHAR_DELAY_MS / MAX_THROTTLED_CHARS static getters off the class.
20
+ import { ClaudeTuiSession } from '../claude-tui-session.js'
21
+
22
+ const __filename = fileURLToPath(import.meta.url)
23
+ const __dirname = dirname(__filename)
24
+
25
+ const log = createLogger('claude-tui-session')
26
+
27
+
28
+ // Permission hook script — same one CliSession uses. Lives at
29
+ // packages/server/hooks/permission-hook.sh.
30
+ const PERMISSION_HOOK_SCRIPT = resolve(__dirname, '..', '..', 'hooks', 'permission-hook.sh')
31
+
32
+ // ANSI strip pattern covering the escape categories claude TUI emits
33
+ // during startup + redraw — keeps _outputTail readable for inline
34
+ // diagnostics (#3919) and the timeout hex dump.
35
+ //
36
+ // CSI: ESC [ <params> <final byte 0x40..0x7E>
37
+ // OSC: ESC ] <data> ( BEL | ESC \ ) e.g. title set
38
+ // SS3: ESC O <byte> e.g. function keys
39
+ // Bracketed paste: ESC [ ? 2004 [hl] handled by CSI re
40
+ // Single-char: ESC = | ESC > | ESC c | ... terminal-mode bytes
41
+ export const ANSI_STRIP = new RegExp(
42
+ [
43
+ '\\x1b\\[[0-9;?]*[\\x40-\\x7E]', // CSI
44
+ '\\x1b\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)', // OSC ... BEL or ST
45
+ '\\x1bO.', // SS3
46
+ '\\x1b[=>cN]', // common single-char terminal-mode codes
47
+ '[\\x00-\\x08\\x0b-\\x1f\\x7f]', // stray C0 controls except \t and \n
48
+ ].join('|'),
49
+ 'g',
50
+ )
51
+
52
+ // Render a byte buffer as a compact hex + ASCII dump suitable for log
53
+ // lines. Used by the probe-timeout diagnostic so the actual TUI output
54
+ // is visible — no more guessing whether the glyph was missing, mangled,
55
+ // or just past the search window (#4031).
56
+ //
57
+ // Accepts either a Buffer (preferred — see #4031 review on the
58
+ // stripped-tail problem) or a string (utf8-encoded to bytes). `maxBytes`
59
+ // caps the dump size; caller is expected to pass at least the probe-
60
+ // scan window so the dump covers the full region. A smaller cap would
61
+ // hide bytes the probe actually checked, defeating the diagnostic's
62
+ // purpose (review-caught regression: PR originally hardcoded 256
63
+ // internally while the probe widened to 1024).
64
+ export function formatHexDump(input, maxBytes) {
65
+ let buf
66
+ if (Buffer.isBuffer(input)) {
67
+ buf = input
68
+ } else if (typeof input === 'string') {
69
+ buf = Buffer.from(input, 'utf8')
70
+ } else {
71
+ return '<empty>'
72
+ }
73
+ if (buf.length === 0) return '<empty>'
74
+ const cap = typeof maxBytes === 'number' && maxBytes > 0 ? maxBytes : buf.length
75
+ const slice = buf.subarray(-Math.min(buf.length, cap))
76
+ const omitted = buf.length - slice.length
77
+ const lines = []
78
+ for (let i = 0; i < slice.length; i += 16) {
79
+ const chunk = slice.subarray(i, i + 16)
80
+ const hex = Array.from(chunk).map((b) => b.toString(16).padStart(2, '0')).join(' ')
81
+ const ascii = Array.from(chunk).map((b) => (b >= 0x20 && b < 0x7f) ? String.fromCharCode(b) : '.').join('')
82
+ lines.push(`${hex.padEnd(48)} |${ascii}|`)
83
+ }
84
+ const header = omitted > 0
85
+ ? `(${slice.length} of ${buf.length} bytes; first ${omitted} omitted)`
86
+ : `(${slice.length} bytes)`
87
+ return `${header}\n${lines.join('\n')}`
88
+ }
89
+
90
+ export const CLAUDE = resolveBinary('claude', [
91
+ join(homedir(), '.local/bin/claude'),
92
+ '/opt/homebrew/bin/claude',
93
+ '/usr/local/bin/claude',
94
+ join(homedir(), '.claude/local/node_modules/.bin/claude'),
95
+ join(homedir(), '.npm-global/bin/claude'),
96
+ ])
97
+
98
+ // #5321 (WP-4.1) — subscription-auth failure detection. claude-tui routes via
99
+ // the OAuth subscription (ANTHROPIC_API_KEY is deleted from the spawn env), so a
100
+ // logged-out / expired login can't be caught by an env-var check. Instead we
101
+ // classify claude's own logged-out banner.
102
+ //
103
+ // CRITICAL: these are NOT generic-English auth phrases. This user base writes a
104
+ // lot of auth code, so "authentication failed" / "not logged in" / "session
105
+ // token expired" appear constantly in normal model RESPONSE text — and the
106
+ // stall/exit scan paths see that rendered response. So every pattern requires
107
+ // claude's own remediation COMMAND token — the `/login` slash command or the
108
+ // `claude login` CLI command in a "run …" instruction — which essentially only
109
+ // appears in claude's logged-out banner ("Invalid API key · Please run /login"),
110
+ // not in a model discussing auth. Matched on the whitespace-normalized tail so a
111
+ // line-wrapped banner still matches. Best-effort pending a real logged-out
112
+ // capture (scripts/tui-form-recorder.mjs) — tune the tokens, not loosen them.
113
+ export const AUTH_FAILURE_PATTERNS = [
114
+ /please run `?\/login`?/i, // claude's exact logged-out instruction
115
+ /invalid api key.{0,60}\/login/i, // full banner: "Invalid API key · Please run /login"
116
+ /\brun `?\/login`?/i, // "run /login" / "run `/login`"
117
+ /\brun `?claude login`?/i, // CLI-command guidance: "run claude login"
118
+ ]
119
+ // Structured error surfaced when an auth failure is classified.
120
+ export const AUTH_REQUIRED_CODE = 'AUTH_REQUIRED'
121
+ export const AUTH_REQUIRED_MESSAGE = 'Claude is not logged in (or the subscription login expired). Run `claude login` in a terminal on the host, then retry. This provider uses the Claude subscription and does NOT accept ANTHROPIC_API_KEY.'
122
+
123
+ // Pre-trust the cwd in ~/.claude.json so the workspace-trust dialog doesn't
124
+ // block headless spawn. The dialog is interactive-only — without this, the
125
+ // PTY would render "Is this a project you trust?" and wait for Enter.
126
+ // Idempotent: if already trusted, no write.
127
+ export function ensureCwdTrusted(cwd) {
128
+ const realCwd = realpathSync(cwd)
129
+ const claudeConfig = join(homedir(), '.claude.json')
130
+ let config = {}
131
+ if (existsSync(claudeConfig)) {
132
+ try {
133
+ config = JSON.parse(readFileSync(claudeConfig, 'utf8'))
134
+ } catch (err) {
135
+ log.warn(`~/.claude.json unreadable, skipping trust pre-write: ${err.message}`)
136
+ return
137
+ }
138
+ }
139
+ if (!config.projects || typeof config.projects !== 'object') {
140
+ config.projects = {}
141
+ }
142
+ const existing = config.projects[realCwd]
143
+ // #5777 FIX-2 — also require hasCompletedProjectOnboarding. Pre-#5777 the
144
+ // early-return fired on trust alone, so a trusted-but-unonboarded cwd (every
145
+ // fresh worktree-isolated spawn — ensureCwdTrusted set trust but never the
146
+ // onboarding flag) still rendered claude's project-onboarding interstitial,
147
+ // which swallows the injected first prompt → the consumed=0 first_output
148
+ // wedge. Pre-writing both flags suppresses that screen. NOTE: this does NOT
149
+ // cover account-level one-shot notices (release notes / opus / remote-control
150
+ // upsell) which render even on a fully-onboarded trusted folder — those are
151
+ // gated/surfaced by FIX-1, not by per-project config.
152
+ if (existing && existing.hasTrustDialogAccepted === true && existing.hasCompletedProjectOnboarding === true) return
153
+
154
+ config.projects[realCwd] = {
155
+ ...(existing || {}),
156
+ hasTrustDialogAccepted: true,
157
+ hasCompletedProjectOnboarding: true,
158
+ projectOnboardingSeenCount: existing?.projectOnboardingSeenCount ?? 0,
159
+ }
160
+ // Atomic write via temp + rename. Use a per-call random suffix rather
161
+ // than process.pid — concurrent ClaudeTuiSessions in the same chroxy
162
+ // server share the pid, so two start()s racing for a different cwd
163
+ // would clobber each other's temp file (#3922). The realpathSync()
164
+ // earlier in this function still means each session writes a
165
+ // different *target* path, but the temp file is global and needs to
166
+ // be unique per write.
167
+ const tmp = `${claudeConfig}.chroxy.${randomUUID()}.tmp`
168
+ writeFileSync(tmp, JSON.stringify(config, null, 2))
169
+ renameSync(tmp, claudeConfig)
170
+ }
171
+
172
+ // Build a settings.json that registers Stop + tool hooks. Claude pipes the
173
+ // hook event JSON to the command's stdin. Per-event filename pattern:
174
+ // Stop → <sink>/stop-<uuid>.json (one per turn)
175
+ // PreToolUse → <sink>/pre-<uuid>.json (one per tool call)
176
+ // PostToolUse → <sink>/post-<uuid>.json (one per tool call)
177
+ //
178
+ // Unique filenames come from UUID_CMD below. `uuidgen` is the first choice
179
+ // (always present on macOS, and on Linux when `uuid-runtime` is installed) but
180
+ // it is NOT in a minimal Debian/Ubuntu container — a bare `$(uuidgen)` there
181
+ // collapses to an empty string, so every event collides on `pre-.json` /
182
+ // `post-.json` and the poller silently sees only the last one (#6075). We fall
183
+ // back to the kernel UUID source (`/proc/sys/kernel/random/uuid`, present on
184
+ // every Linux with no package) and finally to pid+nanoseconds. The expression
185
+ // is POSIX-sh safe (no `$RANDOM`/bashisms) since claude may run hooks under sh.
186
+ // IMPORTANT: do not use `mktemp <sink>/foo-XXXXXX.json` — macOS BSD mktemp
187
+ // does NOT expand the X-template when there's a `.json` suffix after it,
188
+ // so the file ends up named literally "foo-XXXXXX.json" and every turn
189
+ // overwrites the same file. Found the hard way during the #3902 smoke
190
+ // test: turn-2 Stop hook was written but then skipped by the poller
191
+ // because its filename was already in _consumedFiles from turn 1.
192
+ //
193
+ // Each turn's poller scans the sink for files it hasn't yet consumed —
194
+ // so a persistent PTY can fire 1..N Stop events across the session
195
+ // lifetime and each turn picks up only its own.
196
+ //
197
+ // This is written ONCE per session at start() — the same settings.json is
198
+ // reused across every turn, so changing it mid-session has no effect
199
+ // (claude reads it at spawn time).
200
+ export function writeHookSettings(sinkDir, { permissionsEnabled }) {
201
+ const settingsPath = join(sinkDir, 'settings.json')
202
+ const sinkDirEsc = JSON.stringify(sinkDir)
203
+ // Portable unique-id source for hook filenames — see the UUID note above.
204
+ const UUID_CMD = '$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid 2>/dev/null || echo "$$-$(date +%s%N)")'
205
+ // PreToolUse runs ALL registered hooks in order. We always capture the
206
+ // event for our own observability; when permissions are enabled the
207
+ // chroxy permission-hook.sh runs SECOND, gating the tool call via long-
208
+ // poll to /permission. Claude waits for every hook to exit non-zero
209
+ // before running the tool.
210
+ const preToolUseHooks = [
211
+ { type: 'command', command: `cat > ${sinkDirEsc}/pre-${UUID_CMD}.json` },
212
+ ]
213
+ if (permissionsEnabled) {
214
+ preToolUseHooks.push({
215
+ type: 'command',
216
+ command: PERMISSION_HOOK_SCRIPT,
217
+ timeout: 300,
218
+ })
219
+ }
220
+ const settings = {
221
+ hooks: {
222
+ Stop: [
223
+ { hooks: [{ type: 'command', command: `cat > ${sinkDirEsc}/stop-${UUID_CMD}.json` }] },
224
+ ],
225
+ PreToolUse: [
226
+ { hooks: preToolUseHooks },
227
+ ],
228
+ PostToolUse: [
229
+ // First hook: forensic sink — tee preserves stdin for the
230
+ // sibling-cleanup hook below. Replaces the pre-#4668 cat-to-file
231
+ // because cat would consume stdin entirely, leaving the cleanup
232
+ // hook with an empty payload.
233
+ { hooks: [
234
+ { type: 'command', command: `tee ${sinkDirEsc}/post-${UUID_CMD}.json | grep -q '"tool_name":"AskUserQuestion"' && rm -rf ${sinkDirEsc}/askuserquestion-active || true` },
235
+ ] },
236
+ ],
237
+ },
238
+ }
239
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2))
240
+ return settingsPath
241
+ }
242
+
243
+ // --- PTY writer methods (mixed onto ClaudeTuiSession.prototype) ---
244
+ export class PtyDriverMixin {
245
+ /**
246
+ * Write a string to the PTY one character at a time with
247
+ * PROMPT_CHAR_DELAY_MS between each, wrapped in bracketed-paste-disable
248
+ * / re-enable so claude TUI's paste detector accepts it as typed input
249
+ * (#4269). Returns true on completion, false if `_activeTurn.aborted`
250
+ * or `_ptyExited` (#4275) tripped mid-write — in either case `onAbort`
251
+ * was called.
252
+ *
253
+ * Used by both sendMessage's prompt write and respondToQuestion's
254
+ * answer write (#4278). The control sequences (\x1b[?2004l/h, \r) are
255
+ * single writes — only the visible text is throttled, since that's
256
+ * what claude's heuristic measures.
257
+ *
258
+ * Above MAX_THROTTLED_CHARS the helper switches to a single bulk
259
+ * `_term.write(text)` (#4276). Per-char throttling is O(N) blocking
260
+ * latency and unbounded for huge prompts (e.g. pasted file contents)
261
+ * — the bulk path may trip claude's paste detector but that's
262
+ * preferable to multi-minute silent hangs.
263
+ *
264
+ * Multi-line input (any embedded `\n`) takes a separate fast-path
265
+ * (#4678): the body is normalised, wrapped in CSI bracketed-paste
266
+ * markers, and delivered as a single atomic write — see the inline
267
+ * comment in the function body for the why.
268
+ *
269
+ * @param {string} text — the text to write (no trailing CR; \r appended)
270
+ * @param {object} [opts]
271
+ * @param {() => void} [opts.onAbort] — called if abort tripped; caller
272
+ * typically uses this to surface a turn-level error.
273
+ * @returns {Promise<boolean>} true if completed, false if aborted.
274
+ */
275
+ async _writePtyTextThrottled(text, { onAbort } = {}) {
276
+ // Wedge instrumentation (#4678 follow-up): track which path the
277
+ // write took, the byte/code-point count, and elapsed ms. The wedge
278
+ // symptom (`stream_start` then silence) is consistent with this
279
+ // function never returning OR returning but the bytes never being
280
+ // consumed by claude TUI. The log line at finish() distinguishes
281
+ // the two — if the line never appears in the log, the wedge is in
282
+ // here; if it appears with completed=true, the wedge is downstream
283
+ // (hook poll loop, or claude TUI itself).
284
+ const writeStartMs = this._nowMonotonic()
285
+ const codePointCount = [...text].length
286
+ const byteLength = Buffer.byteLength(text, 'utf8')
287
+ const finish = (path, completed) => {
288
+ const elapsedMs = this._nowMonotonic() - writeStartMs
289
+ if (this._activeTurn) {
290
+ this._activeTurn.writePath = path
291
+ this._activeTurn.writeMs = elapsedMs
292
+ this._activeTurn.writeBytes = byteLength
293
+ this._activeTurn.writeCompleted = completed
294
+ }
295
+ log.info(`writePtyText (msg=${this._activeTurn?.messageId ?? 'none'} path=${path} codePoints=${codePointCount} bytes=${byteLength} elapsedMs=${elapsedMs} completed=${completed})`)
296
+ return completed
297
+ }
298
+ // #4678: multi-line prompts (from Shift+Enter in the dashboard
299
+ // composer) need to be delivered as a single bracketed paste —
300
+ // claude TUI v2.1.x treats raw \n in the input box as "insert
301
+ // newline in multi-line composition" with no way to break out via
302
+ // a subsequent \r (the bare \r is also interpreted as a newline
303
+ // when the cursor is in a multi-line composition). Wrapping the
304
+ // content in CSI bracketed-paste markers (\x1b[200~ ... \x1b[201~)
305
+ // tells claude TUI the content was pasted; on receipt of the close
306
+ // marker the input is ready to submit and the trailing \r fires.
307
+ //
308
+ // Single-line content keeps the per-char throttled write — the
309
+ // #4269 throttle exists to defeat claude TUI's heuristic paste
310
+ // detector when the input is typed input (not a real paste). For
311
+ // genuine paste we use the explicit markers and rely on claude TUI
312
+ // honouring DEC mode 2004 for those bytes.
313
+ const hasNewlines = /\r?\n/.test(text)
314
+ if (hasNewlines) {
315
+ // Normalise CRLF → LF so the pasted body contains a single line
316
+ // break per logical newline. Trailing newlines are dropped so
317
+ // the close marker lands at the end of the visible content
318
+ // rather than after an empty trailing line. Embedded paste-end
319
+ // markers (`\x1b[201~`) are stripped from the body — leaving
320
+ // them intact would let attacker-controlled content (an MCP tool
321
+ // result echoed into a follow-up prompt, an evaluator rewrite,
322
+ // any future content-injection path) terminate the bracketed
323
+ // paste early and land the suffix as typed input in claude TUI.
324
+ // Defense-in-depth; the typing-user case is zero-risk today.
325
+ // Order matters: strip embedded \x1b[201~ markers BEFORE the
326
+ // trailing-newline strip. Removing markers can expose trailing
327
+ // newlines that were hidden by them — e.g. "\n\x1b[201~\n" needs
328
+ // to become "" (empty body → abort), not "\n" (a degenerate
329
+ // one-newline paste). Doing trailing-strip first would keep the
330
+ // newline that the marker was masking.
331
+ const body = text
332
+ .replace(/\r\n/g, '\n')
333
+ .replace(/\x1b\[201~/g, '')
334
+ .replace(/\n+$/, '')
335
+ if (this._activeTurn?.aborted || this._ptyExited) {
336
+ onAbort?.()
337
+ return finish('paste-abort', false)
338
+ }
339
+ // After stripping, an all-whitespace or all-control-bytes prompt
340
+ // can collapse to an empty body. Sending the degenerate
341
+ // `\x1b[200~\x1b[201~\r` produces a CR-on-empty-input — at best
342
+ // a no-op, at worst behaviour the TUI doesn't expect. Drop the
343
+ // turn cleanly via the abort path so the caller sees a finished
344
+ // turn (no message ever leaves chroxy) rather than chroxy
345
+ // claiming to have sent and then waiting forever for a reply.
346
+ if (body.length === 0) {
347
+ onAbort?.()
348
+ return finish('paste-empty', false)
349
+ }
350
+ this._term.write('\x1b[200~' + body + '\x1b[201~\r')
351
+ return finish('paste', true)
352
+ }
353
+
354
+ // #4805: single-line throttled path used to feed `freeformText`
355
+ // verbatim into _term.write — no defense against C0 control bytes
356
+ // or ANSI escape sequences embedded in the input. The newline
357
+ // bracketed-paste branch above (#4678) already strips embedded
358
+ // `\x1b[201~` markers and explicitly cites attacker-controlled MCP
359
+ // tool results as the threat model; the single-line branch has the
360
+ // same input shape and applies the parallel defense.
361
+ //
362
+ // Stripped (in this order, since the first match wins):
363
+ // - ANSI CSI: ESC [ <params 0x30-0x3f> <intermediates 0x20-0x2f>
364
+ // <final 0x40-0x7e> — the full ECMA-48 grammar including
365
+ // DEC-private sequences `?`/`<`/`=`/`>`/`:` (W2 #4805)
366
+ // - String controls: ESC ] / P / X / ^ / _ <payload> (BEL | ESC \)
367
+ // — covers OSC (title-set), DCS (sixel/ReGIS/termcap),
368
+ // SOS / PM / APC (W2 #4805 — original regex covered OSC only)
369
+ // - Stray two-byte ESC + final-byte sequences: RIS `\x1b c`,
370
+ // DECSC/DECRC `\x1b 7`/`8`, IND/RI/NEL/HTS `\x1b D`/`M`/`E`/`H`,
371
+ // keypad-mode `\x1b =`/`>` — `\x1b.?` catch-all (W2 #4805)
372
+ // - C0 control bytes \x00-\x08 + \x0b-\x1f + \x7f — the range
373
+ // now includes \x1b so any unmatched lone ESC is stripped
374
+ // (W2 #4805 closed the 0x1b char-class gap). Excludes \t (a
375
+ // normal printable whitespace a user may paste); \r/\n never
376
+ // reach this path (the multi-line branch handles them).
377
+ // Note: the sequence-matching alternations come BEFORE the
378
+ // C0 class so a full escape is matched as one unit. If the
379
+ // lone-byte class came first the regex would peel off the \x1b
380
+ // introducer and leave the [<final> bytes as printable garbage.
381
+ // Known damage paths covered:
382
+ // - \x03 (Ctrl-C) aborts the active TUI form
383
+ // - OSC \x1b]0;...\x07 rewrites the window title on some hosts
384
+ // - DEC-private CSI (\x1b[?25l hide-cursor, \x1b[?1049h alt-
385
+ // screen, \x1b[?1000h / \x1b[?1006h mouse-tracking) desync
386
+ // the TUI input state machine — the recurring wedge symptom
387
+ // class
388
+ // - RIS \x1b c full-terminal-reset clears the scrollback
389
+ // - APC payloads (iTerm2 proprietary commands)
390
+ const stripped = []
391
+ text = text.replace(
392
+ // eslint-disable-next-line no-control-regex
393
+ /\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|\x1b[\]PX^_][\s\S]*?(?:\x07|\x1b\\)|\x1b.?|[\x00-\x08\x0b-\x1f\x7f]/g,
394
+ (match) => {
395
+ stripped.push(match)
396
+ return ''
397
+ },
398
+ )
399
+ if (stripped.length > 0) {
400
+ // Bounded hex preview (first 32 stripped bytes total) gives an
401
+ // incident-response footprint without blowing the log on a
402
+ // malicious flood. Sequences are concatenated then truncated so
403
+ // each warn line carries the same payload shape regardless of
404
+ // how many distinct sequences were stripped.
405
+ const totalBytes = stripped.reduce((n, s) => n + Buffer.byteLength(s, 'utf8'), 0)
406
+ const sampleHex = Buffer.from(stripped.join(''), 'utf8').slice(0, 32).toString('hex')
407
+ const truncated = totalBytes > 32 ? ',…' : ''
408
+ log.warn(`writePtyText (msg=${this._activeTurn?.messageId ?? 'none'}) stripped ${totalBytes} control/escape bytes from single-line input (sample=${sampleHex}${truncated}) (#4805)`)
409
+ }
410
+ // After stripping, an all-control-byte prompt can collapse to an
411
+ // empty body. Mirror the multi-line branch's `body.length === 0`
412
+ // guard (:1358): abort the turn cleanly rather than write a bare
413
+ // \r submit to the TUI — the caller sees a finished turn (no
414
+ // message ever leaves chroxy) instead of chroxy claiming to have
415
+ // sent and waiting forever for a reply.
416
+ if (text.length === 0) {
417
+ onAbort?.()
418
+ return finish('throttled-empty', false)
419
+ }
420
+ // Re-compute counts now that the body may have shrunk so the bulk-
421
+ // path threshold check + finish() bookkeeping stay accurate.
422
+ const sanitizedCodePointCount = [...text].length
423
+
424
+ this._term.write('\x1b[?2004l')
425
+ try {
426
+ // #4276: huge prompts bypass the throttle. Code-point count
427
+ // (counted once at function entry) keeps the threshold
428
+ // consistent with how the loop iterates — an emoji-only 5000-
429
+ // char string [...].length is 5000, not 10000.
430
+ if (sanitizedCodePointCount > ClaudeTuiSession.MAX_THROTTLED_CHARS) {
431
+ // Re-check the turn lifecycle exactly once before the bulk
432
+ // write — same shape as the loop's per-iter guards, so a
433
+ // caller that aborted between scheduling and execution doesn't
434
+ // flood a torn-down PTY with a huge payload.
435
+ if (this._activeTurn?.aborted || this._ptyExited) {
436
+ onAbort?.()
437
+ return finish('bulk-abort', false)
438
+ }
439
+ this._term.write(text)
440
+ this._term.write('\r')
441
+ return finish('bulk', true)
442
+ }
443
+ for (const ch of text) {
444
+ // #4275: re-check _ptyExited inside the loop, mirroring the
445
+ // pre-write guard in sendMessage. A long prompt + a mid-write
446
+ // PTY crash previously relied on the next _term.write throwing
447
+ // to bubble up — correct but not the explicit-state-machine
448
+ // pattern the rest of this file uses.
449
+ if (this._activeTurn?.aborted || this._ptyExited) {
450
+ onAbort?.()
451
+ return finish('throttled-abort', false)
452
+ }
453
+ this._term.write(ch)
454
+ if (ClaudeTuiSession.PROMPT_CHAR_DELAY_MS > 0) {
455
+ await new Promise((resolve) => setTimeout(resolve, ClaudeTuiSession.PROMPT_CHAR_DELAY_MS))
456
+ }
457
+ }
458
+ this._term.write('\r')
459
+ return finish('throttled', true)
460
+ } finally {
461
+ // Always restore bracketed-paste mode, even on abort/throw. Write may
462
+ // throw if PTY has exited mid-loop (#4287) — swallow so we don't mask
463
+ // the original error path.
464
+ try { this._term.write('\x1b[?2004h') } catch {}
465
+ }
466
+ }
467
+
468
+ /**
469
+ * Write an arrow-key navigation sequence for the single-question
470
+ * AskUserQuestion form when the user picked an option beyond the
471
+ * single-digit hotkey range (idx >= 9). Emits `targetIdx` Down arrow
472
+ * keystrokes (`\x1b[B`, 3 bytes each) — claude TUI's form cursor
473
+ * starts at idx 0, so `targetIdx` downs land on the picked option —
474
+ * followed by Enter (`\r`) to commit (#4848).
475
+ *
476
+ * Wrapped in bracketed-paste-disable / re-enable exactly once (same
477
+ * defense as _writePtyTextThrottled).
478
+ * A PROMPT_CHAR_DELAY_MS pause runs BETWEEN each Down-arrow write so
479
+ * claude TUI's paste detector doesn't reject the burst. The trailing
480
+ * Enter (`\r`) and the bracketed-paste re-enable write fire
481
+ * immediately after the final delay — no extra pause separates them
482
+ * from the last arrow (the arrival rate at that point is already well
483
+ * under any reasonable paste threshold). Each arrow is one `_term.write`
484
+ * call (3 bytes); 10 arrows ≈ 30 bytes total form-byte payload.
485
+ *
486
+ * **Empirically unreachable (#4880, 2026-06-07):** the recorder pass
487
+ * against a 10+ option AskUserQuestion ran and found the form can't be
488
+ * produced — claude TUI v2.1.168 hard-caps each AskUserQuestion question
489
+ * at 4 options (the call fails server-side with
490
+ * `InputValidationError: too_big, maximum: 4` before any form renders;
491
+ * see docs/empirical/4880-twelve-option-cap.jsonl). So this writer is
492
+ * currently DEAD CODE on real AskUserQuestion forms, kept as forward-compat
493
+ * for a future TUI that raises the cap. The `\x1b[B` + `\r` sequence is the
494
+ * conservative bet (multi-digit chord '1','0' was ruled out — the digit
495
+ * hotkey auto-commits on the first keystroke); it could not be confirmed
496
+ * because the form is unproducible. Revisit if/when the option cap rises.
497
+ *
498
+ * @param {number} targetIdx — 0-indexed option to land on
499
+ * @returns {Promise<boolean>} true if completed, false if PTY aborted mid-write
500
+ */
501
+ async _writePtyArrowNavSequence(targetIdx) {
502
+ if (!this._term) return false
503
+ if (typeof targetIdx !== 'number' || targetIdx < 0) return false
504
+ this._term.write('\x1b[?2004l')
505
+ try {
506
+ for (let i = 0; i < targetIdx; i++) {
507
+ if (this._activeTurn?.aborted || this._ptyExited) return false
508
+ this._term.write('\x1b[B')
509
+ if (ClaudeTuiSession.PROMPT_CHAR_DELAY_MS > 0) {
510
+ await new Promise((resolve) => setTimeout(resolve, ClaudeTuiSession.PROMPT_CHAR_DELAY_MS))
511
+ }
512
+ }
513
+ if (this._activeTurn?.aborted || this._ptyExited) return false
514
+ this._term.write('\r')
515
+ return true
516
+ } finally {
517
+ try { this._term.write('\x1b[?2004h') } catch {}
518
+ }
519
+ }
520
+ }
@@ -0,0 +1,22 @@
1
+ // The claude CLI version chroxy's claude-tui form-driving was last validated
2
+ // against (audit P1-3 / #5821 backstop).
3
+ //
4
+ // ClaudeTuiSession drives the real `claude` interactive TUI by screen-scraping
5
+ // and emitting empirically-pinned keystroke sequences (see pty-driver.js /
6
+ // form-driver.js) — there is NO programmatic answer channel. A claude CLI UI
7
+ // change (hotkey scheme, prompt layout, bracketed-paste handling) can therefore
8
+ // mis-drive AskUserQuestion forms SILENTLY: a wrong key lands, claude resolves
9
+ // *some* option, and the user's choice is quietly mis-applied.
10
+ //
11
+ // This pin lets `chroxy doctor` turn that silent class into a MEASURED, surfaced
12
+ // signal: it warns when the installed claude differs (by major.minor) from the
13
+ // version the byte sequences were validated against. It is the only real
14
+ // backstop against the silent-mis-drive class until a structured answer channel
15
+ // exists.
16
+ //
17
+ // MAINTENANCE: when you re-validate the form-driving against a newer claude CLI
18
+ // (running the AskUserQuestion flows and confirming the keystrokes still resolve
19
+ // the intended option — e.g. via scripts/tui-form-recorder.mjs), bump this to
20
+ // the version you tested. Keep it next to the driving code so the bump is an
21
+ // obvious part of that re-validation.
22
+ export const TESTED_CLAUDE_TUI_CLI_VERSION = '2.1.177'