@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,1048 @@
1
+ /**
2
+ * Input and user interaction message handlers.
3
+ *
4
+ * Handles: input, interrupt, resume_budget, register_push_token,
5
+ * user_question_response, notification_prefs_get,
6
+ * notification_prefs_set (#4541)
7
+ */
8
+ import { randomUUID } from 'node:crypto'
9
+ import { validateAttachments, resolveFileRefAttachments, resolveSession, sendError, sendSessionError, buildSessionTokenMismatchPayload, isSessionViewer, isUserShellSession } from '../handler-utils.js'
10
+ import { evaluateDraft as defaultEvaluateDraft, shouldSkipEvaluator } from '../prompt-evaluator.js'
11
+ import { PushManager } from '../push.js'
12
+ import { createLogger, sessionLogger } from '../logger.js'
13
+
14
+ const log = createLogger('ws')
15
+
16
+ // #3186 — auto-evaluation hook config.
17
+ //
18
+ // MAX_EVALUATOR_ITERATIONS caps the clarify loop. After 3 consecutive clarify
19
+ // verdicts on a session, the NEXT user message bypasses the evaluator call
20
+ // entirely — the cap fires BEFORE the await, so there is no verdict on that
21
+ // message; the original draft is force-forwarded sight-unseen and the
22
+ // counter resets so a subsequent send can re-enter the evaluator gate.
23
+ // Without the cap an evaluator that never settles would silently swallow
24
+ // every message. (#3642 tightened this comment — the cap doesn't
25
+ // "force-forward regardless of verdict", it bypasses the evaluator entirely
26
+ // so there's no verdict to override.)
27
+ const MAX_EVALUATOR_ITERATIONS = 3
28
+
29
+ // Per-session iteration counter. Owned by WsServer at runtime
30
+ // (`this._evaluatorIterations`, exposed on `ctx.runtime.evaluatorIterations`)
31
+ // because handler ctx is spread fresh on every dispatch — without a
32
+ // stable home the counter would reset on every message and the cap
33
+ // would never fire in production. Cleaned up by `_sessionDestroyedHandler`
34
+ // so destroyed sessions don't leak counter entries (#3637). The lazy
35
+ // creation below remains so tests that don't pass the Map through ctx
36
+ // still work.
37
+ //
38
+ // Reset to 0 once the cap fires so a subsequent send starts fresh — see
39
+ // test "force-forwards original draft after 3 consecutive clarify verdicts".
40
+ function _getEvaluatorIterations(ctx) {
41
+ if (!ctx.runtime.evaluatorIterations) ctx.runtime.evaluatorIterations = new Map()
42
+ return ctx.runtime.evaluatorIterations
43
+ }
44
+
45
+ // #3636 — per-session evaluator-await lock. Without this, two messages
46
+ // arriving close together for the same session can both pass the pre-await
47
+ // input_conflict / primary checks, both invoke the evaluator concurrently,
48
+ // and produce non-deterministic interleaving (two evaluator round-trips,
49
+ // two `session.sendMessage` calls in unspecified order, broadcasts mixed).
50
+ // We reject the second concurrent draft with the same input_conflict
51
+ // category the user already understands — not queue it — so callers retry
52
+ // rather than silently waiting on an unbounded queue.
53
+ function _getEvaluatorAwaits(ctx) {
54
+ if (!ctx._pendingEvaluatorAwaits) ctx._pendingEvaluatorAwaits = new Map()
55
+ return ctx._pendingEvaluatorAwaits
56
+ }
57
+
58
+ // #3665 — build the history text appended for a recorded user input.
59
+ // When attachments are present we annotate the recorded text with a
60
+ // `[N file(s) attached]` marker so audit/replay shows what came alongside
61
+ // the message. The marker carries its own leading separator, so any
62
+ // trailing whitespace on `text` is stripped first — the auto-evaluator
63
+ // rewrite path commonly returns strings with a trailing newline, and
64
+ // without normalization the recorded text reads `'foo \n[1 file(s) attached]'`
65
+ // (double whitespace before the marker). Empty/whitespace-only text drops
66
+ // to a marker-only entry.
67
+ export function buildHistoryText(text, attCount) {
68
+ if (!attCount) return text
69
+ const stripped = typeof text === 'string' ? text.replace(/\s+$/, '') : ''
70
+ return stripped
71
+ ? `${stripped} [${attCount} file(s) attached]`
72
+ : `[${attCount} file(s) attached]`
73
+ }
74
+
75
+ // #3639 — build the minimal config object passed into shouldSkipEvaluator.
76
+ // The per-session promptEvaluatorSkipPattern (string source) takes precedence;
77
+ // the server-wide ctx.services.config.promptEvaluatorSkipPattern (#3187) is the
78
+ // fallback so existing global-config deployments keep working unchanged.
79
+ // shouldSkipEvaluator only reads `config.promptEvaluatorSkipPattern` (verified
80
+ // in prompt-evaluator.js), so we return a single-key object rather than
81
+ // spreading the whole ctx.services.config — this runs on the user_input hot path and
82
+ // the spread was unnecessary allocation/copy work.
83
+ function _resolveSkipConfig(entry, ctx) {
84
+ const sessionSource = entry?.session?.promptEvaluatorSkipPattern
85
+ const sessionPattern = typeof sessionSource === 'string' && sessionSource.length > 0
86
+ ? sessionSource
87
+ : null
88
+ const globalSource = ctx?.services?.config?.promptEvaluatorSkipPattern
89
+ const globalPattern = typeof globalSource === 'string' && globalSource.length > 0
90
+ ? globalSource
91
+ : null
92
+ return { promptEvaluatorSkipPattern: sessionPattern ?? globalPattern }
93
+ }
94
+
95
+ // Stable user-input message IDs (issue #2902). A client that sends its own
96
+ // `clientMessageId` gets it adopted verbatim — that lets the sender dedup its
97
+ // optimistic entry against the rehydrated history after a reconnect. Only
98
+ // loose format validation: we don't trust client input beyond size/charset,
99
+ // but collisions inside one session's ring buffer are the client's problem.
100
+ const USER_INPUT_ID_RE = /^[A-Za-z0-9_-]+$/
101
+ const MAX_CLIENT_MESSAGE_ID_LEN = 128
102
+ // IDs the clients treat specially in their stores (e.g. the "thinking"
103
+ // placeholder shown while waiting for the first stream_delta). Never let a
104
+ // client-supplied id collide with these — it would clobber the placeholder
105
+ // or cause the indicator to leak.
106
+ const RESERVED_USER_INPUT_IDS = new Set(['thinking', 'pending', 'queued'])
107
+ let _userInputIdCounter = 0
108
+ function generateUserInputId() {
109
+ _userInputIdCounter = (_userInputIdCounter + 1) % Number.MAX_SAFE_INTEGER
110
+ return `uin-${Date.now()}-${_userInputIdCounter}`
111
+ }
112
+ function resolveUserInputId(candidate) {
113
+ if (typeof candidate !== 'string') return generateUserInputId()
114
+ if (candidate.length === 0 || candidate.length > MAX_CLIENT_MESSAGE_ID_LEN) return generateUserInputId()
115
+ if (!USER_INPUT_ID_RE.test(candidate)) return generateUserInputId()
116
+ if (RESERVED_USER_INPUT_IDS.has(candidate)) return generateUserInputId()
117
+ return candidate
118
+ }
119
+
120
+ // #5281 ①.3 — an input_conflict rejection: the session can't accept this send
121
+ // right now (busy with another device's request, or still evaluating a previous
122
+ // draft on the same session). Echo the session and the rejected clientMessageId
123
+ // (when well-formed) so the dashboard can remove the stranded optimistic user
124
+ // message + clear its thinking spinner instead of leaving a ghost send behind a
125
+ // calm notice. `message` carries the specific reason so the dashboard can show
126
+ // it verbatim (cross-device vs same-session evaluator lock differ).
127
+ const INPUT_CONFLICT_CROSS_DEVICE_MESSAGE =
128
+ 'Session is already processing input from another device. Wait for it to finish or interrupt first.'
129
+ function buildInputConflictError(sessionId, clientMessageId, message = INPUT_CONFLICT_CROSS_DEVICE_MESSAGE) {
130
+ const err = {
131
+ type: 'session_error',
132
+ category: 'input_conflict',
133
+ message,
134
+ sessionId,
135
+ }
136
+ // Echo only a well-formed id. Mirror resolveUserInputId's guards (incl. the
137
+ // reserved-id exclusion) so we never reflect a value the history path itself
138
+ // would have regenerated — keeps the echoed id consistent with the recorded
139
+ // one and avoids reflecting a reserved placeholder like 'thinking'.
140
+ if (
141
+ typeof clientMessageId === 'string' &&
142
+ clientMessageId.length > 0 &&
143
+ clientMessageId.length <= MAX_CLIENT_MESSAGE_ID_LEN &&
144
+ USER_INPUT_ID_RE.test(clientMessageId) &&
145
+ !RESERVED_USER_INPUT_IDS.has(clientMessageId)
146
+ ) {
147
+ err.clientMessageId = clientMessageId
148
+ }
149
+ return err
150
+ }
151
+
152
+ async function handleInput(ws, client, msg, ctx) {
153
+ const text = msg.data
154
+ let attachments = Array.isArray(msg.attachments) ? msg.attachments : undefined
155
+ const targetSessionId = msg.sessionId || client.activeSessionId
156
+ const entry = resolveSession(ctx, msg, client)
157
+ if (!entry) {
158
+ // #4935 — visibility fix for the silent post-restart wedge. Before this,
159
+ // a stale `sessionId` (common when the dashboard's persisted activeSessionId
160
+ // references a pre-restart session ID that no longer exists after
161
+ // session-manager regenerates IDs on restoreState) would silently drop
162
+ // the input on the floor — sendSessionError ran but the operator log only
163
+ // showed a debug-level `Message from ...` line below, and that line is
164
+ // never reached on this branch. The dashboard's session_error toast DID
165
+ // fire, but with a generic "Session not found: <id>" string that gave the
166
+ // user nothing actionable. Now:
167
+ // 1. Log at INFO with the attempted ID + client ID so chroxy.log
168
+ // shows the mismatch and operators can correlate against the
169
+ // session_list / session-state.json after a restart.
170
+ // 2. Emit a structured `code: 'SESSION_NOT_FOUND'` + `attemptedSessionId`
171
+ // on the session_error envelope so the dashboard can surface an
172
+ // actionable hint ("session restarted — pick a session below")
173
+ // and clear its stale activeSessionId locally. Mirrors the existing
174
+ // `code: 'resume_unknown'` affordance (#4947).
175
+ //
176
+ // IMPORTANT (Copilot review #4979): `resolveSession()` returns null for
177
+ // two distinct reasons — (a) the session truly does not exist, and
178
+ // (b) the client has a `boundSessionId` and `msg.sessionId` disagrees with
179
+ // it (session-token binding enforcement in handler-utils.js). Case (b) is
180
+ // a SESSION_TOKEN_MISMATCH, not a SESSION_NOT_FOUND, and conflating them
181
+ // would (i) mislabel the operator log line and (ii) cause a dashboard
182
+ // consumer keyed on SESSION_NOT_FOUND to clear local state for what is
183
+ // actually an authorization failure. Check the binding-mismatch case
184
+ // FIRST and emit the canonical SESSION_TOKEN_MISMATCH envelope (#2912 —
185
+ // unified shape across all call sites via buildSessionTokenMismatchPayload).
186
+ if (msg.sessionId && client.boundSessionId && client.boundSessionId !== msg.sessionId) {
187
+ log.info(`input rejected: session-token mismatch sessionId=${msg.sessionId} boundSessionId=${client.boundSessionId} client=${client.id}`)
188
+ ctx.transport.send(ws, {
189
+ type: 'session_error',
190
+ ...buildSessionTokenMismatchPayload({
191
+ sessionManager: ctx.sessions.sessionManager,
192
+ boundSessionId: client.boundSessionId,
193
+ }),
194
+ })
195
+ return
196
+ }
197
+ if (msg.sessionId) {
198
+ log.info(`input dropped: session not found sessionId=${msg.sessionId} client=${client.id} (likely stale ID after daemon restart — see #4935)`)
199
+ ctx.transport.send(ws, {
200
+ type: 'session_error',
201
+ code: 'SESSION_NOT_FOUND',
202
+ message: `Session not found: ${msg.sessionId}`,
203
+ attemptedSessionId: msg.sessionId,
204
+ })
205
+ } else {
206
+ log.info(`input dropped: no active session client=${client.id}`)
207
+ sendSessionError(ws, ctx, 'No active session')
208
+ }
209
+ return
210
+ }
211
+
212
+ if (attachments?.length) {
213
+ const err = validateAttachments(attachments)
214
+ if (err) {
215
+ sendSessionError(ws, ctx, `Invalid attachment: ${err}`)
216
+ return
217
+ }
218
+ }
219
+
220
+ // Resolve file_ref attachments to actual file content
221
+ if (attachments?.length) {
222
+ attachments = resolveFileRefAttachments(attachments, entry.cwd)
223
+ }
224
+
225
+ if ((!text || !text.trim()) && !attachments?.length) return
226
+ const trimmed = text?.trim() || ''
227
+ const attCount = attachments?.length || 0
228
+ log.debug(`Message from ${client.id} to session ${targetSessionId}: "${trimmed.slice(0, 80)}"${attCount ? ` (+${attCount} attachment(s))` : ''}`)
229
+
230
+ // #4733 — wire-arrival fingerprint. Logs the byte/codepoint/whitespace
231
+ // shape of the inbound `data` so a corrupted-text reproduction can be
232
+ // localized to the dashboard boundary vs the server's PTY write path
233
+ // by correlating against the `writePtyText (msg=… codePoints=… bytes=…)`
234
+ // line in `claude-tui-session.js`. No content is logged — only counts —
235
+ // so this stays safe to enable when the env flag is set.
236
+ //
237
+ // Concretely, the original #4733 repro showed `writePtyText … codePoints=332`
238
+ // for a message the user intended at ~360 chars with ~24 spaces missing.
239
+ // Without an inbound-side counter we cannot tell whether the 28-codepoint
240
+ // delta was stripped before the WS arrived, in `trim()` (leading/trailing
241
+ // only, max +2 codepoints), in the evaluator rewrite path (#3635), or by
242
+ // the throttle. The four counts here pin which boundary stripped them.
243
+ //
244
+ // Gated behind `CHROXY_LOG_WIRE_FINGERPRINT=1` so it stays off by default
245
+ // — the input handler is the hot path for every typed/pasted user message
246
+ // and an unconditional info-level log line per message is too noisy for
247
+ // production user logs. Flip the env var when actively investigating
248
+ // #4733 (or any future "text stripped between dashboard and PTY" report).
249
+ if (process.env.CHROXY_LOG_WIRE_FINGERPRINT === '1' && typeof text === 'string' && text.length > 0) {
250
+ // Strip a SINGLE trailing newline (CR, LF, or CRLF) before fingerprinting
251
+ // so counts line up with `_writePtyTextThrottled` in claude-tui-session.js,
252
+ // which strips one trailing newline before the bracketed-paste body. Shift+
253
+ // Enter ends multi-line dashboard drafts with a trailing \n; counting it
254
+ // here would inflate `codePoints`/`wsTotal` by 1 (or 2 for \r\n) and skew
255
+ // the dashboard-vs-PTY boundary correlation by the same amount.
256
+ let fp = text
257
+ if (fp.endsWith('\r\n')) fp = fp.slice(0, -2)
258
+ else if (fp.endsWith('\n') || fp.endsWith('\r')) fp = fp.slice(0, -1)
259
+ const bytes = Buffer.byteLength(fp, 'utf8')
260
+ const codePoints = [...fp].length
261
+ // Counts ALL interior whitespace runs as one-per-run AND total chars
262
+ // separately — the run count survives a "double-space collapsed to
263
+ // single" bug (each run keeps at least one char) while the total
264
+ // catches "all interior spaces stripped" (run count → 0, total → 0).
265
+ let whitespaceTotal = 0
266
+ let whitespaceRuns = 0
267
+ let maxWordLen = 0
268
+ let currWordLen = 0
269
+ let inWhitespace = false
270
+ for (const ch of fp) {
271
+ if (/\s/.test(ch)) {
272
+ whitespaceTotal += 1
273
+ if (!inWhitespace) whitespaceRuns += 1
274
+ inWhitespace = true
275
+ if (currWordLen > maxWordLen) maxWordLen = currWordLen
276
+ currWordLen = 0
277
+ } else {
278
+ inWhitespace = false
279
+ currWordLen += 1
280
+ }
281
+ }
282
+ if (currWordLen > maxWordLen) maxWordLen = currWordLen
283
+ log.info(`input wire-fingerprint (client=${client.id} session=${targetSessionId} bytes=${bytes} codePoints=${codePoints} wsTotal=${whitespaceTotal} wsRuns=${whitespaceRuns} maxWordLen=${maxWordLen}) (#4733)`)
284
+ }
285
+
286
+ if (ctx.sessions.sessionManager.isBudgetPaused(targetSessionId)) {
287
+ sendSessionError(ws, ctx, 'Session is paused — cost budget exceeded. Use "Resume Budget" to continue.')
288
+ return
289
+ }
290
+
291
+ // Input conflict: reject if session is already processing input from a different client
292
+ if (entry.session.isRunning) {
293
+ const primaryClientId = ctx.transport.getPrimary(targetSessionId)
294
+ if (primaryClientId && primaryClientId !== client.id) {
295
+ ctx.transport.send(ws, buildInputConflictError(targetSessionId, msg.clientMessageId))
296
+ return
297
+ }
298
+ }
299
+
300
+ // #3666 — hoist the per-session evaluator-await lock check above the
301
+ // routing logic so trivial-skip-path messages also reject during an
302
+ // in-flight evaluator round-trip. Without this, a fast trivial draft
303
+ // (short ack, configured skip pattern, or evaluator-disabled session)
304
+ // can sneak through to record+send while a slower non-trivial draft
305
+ // is still awaiting the evaluator on the same session — history
306
+ // insertion order then doesn't match arrival order. Same input_conflict
307
+ // category as the existing pre-await check; rejection (not queueing)
308
+ // matches the #3636 design.
309
+ const _pendingAwaits = _getEvaluatorAwaits(ctx)
310
+ if (_pendingAwaits.has(targetSessionId)) {
311
+ ctx.transport.send(ws, buildInputConflictError(
312
+ targetSessionId,
313
+ msg.clientMessageId,
314
+ 'Session is already evaluating a previous draft. Wait for it to finish or interrupt first.',
315
+ ))
316
+ return
317
+ }
318
+
319
+ if (entry.session.resumeSessionId) {
320
+ ctx.services.checkpointManager.createCheckpoint({
321
+ sessionId: targetSessionId,
322
+ resumeSessionId: entry.session.resumeSessionId,
323
+ cwd: entry.cwd,
324
+ description: trimmed.slice(0, 100),
325
+ messageCount: ctx.sessions.sessionManager.getHistoryCount(targetSessionId),
326
+ }).catch((err) => log.warn(`Auto-checkpoint failed: ${err.message}`))
327
+ }
328
+ // Adopt the sender's clientMessageId if present and well-formed; otherwise
329
+ // generate one. Same ID is stored in history and emitted in the live-echo
330
+ // broadcast so any reconnecting client can match rehydrated entries
331
+ // against their optimistic/echo copies (issue #2902).
332
+ const messageId = resolveUserInputId(msg.clientMessageId)
333
+
334
+ // #3635 + #3636 merged: record-after-evaluator AND rejection-safe.
335
+ //
336
+ // #3635 — the auto-evaluator (#3186) can rewrite a draft before
337
+ // forwarding. Historically we recorded the ORIGINAL draft to history
338
+ // before awaiting the evaluator, so replayed history showed the
339
+ // user's original text against an assistant response that answered
340
+ // the rewrite (confusing divergence). Decision: record what was
341
+ // actually forwarded on rewrite, original on forward/clarify/skip/
342
+ // fail-open.
343
+ //
344
+ // #3636 — the auto-evaluator hook also added rejection paths
345
+ // (pending-evaluator guard, post-await input_conflict re-check) that
346
+ // return without forwarding. Recording before those checks would
347
+ // produce phantom history entries — appears in replay/reconnect
348
+ // history but was neither forwarded nor broadcast.
349
+ //
350
+ // Resolution: defer recording until a success boundary (clarify path
351
+ // OR forward boundary), recording the text that was actually used.
352
+ // Rejection paths return without calling recordHistoryEntry().
353
+ // touchActivity moves with it so a rejected message doesn't bump the
354
+ // session's activity timestamp.
355
+ let _historyRecorded = false
356
+ function recordHistoryEntry(text) {
357
+ if (_historyRecorded) return
358
+ _historyRecorded = true
359
+ ctx.sessions.sessionManager.recordUserInput(targetSessionId, buildHistoryText(text, attCount), messageId)
360
+ ctx.sessions.sessionManager.touchActivity(targetSessionId)
361
+ }
362
+
363
+ // #3186 — auto-evaluation hook. Gates message forwarding on a per-session
364
+ // promptEvaluator toggle. Skips evaluation for trivial drafts (acks, short
365
+ // replies) that wouldn't benefit from a round-trip. Verdict routing:
366
+ // - forward → original message goes through unchanged
367
+ // - rewrite → broadcast evaluator_rewrite, forward the rewritten text
368
+ // - clarify → broadcast evaluator_clarify, do NOT forward (wait for
369
+ // follow-up). Capped at MAX_EVALUATOR_ITERATIONS clarify
370
+ // cycles — the next message force-forwards.
371
+ // Fail-open: any evaluator error is logged and the original message is
372
+ // forwarded so a key-missing or upstream outage never blocks the user.
373
+ //
374
+ // #3639: per-session promptEvaluatorSkipPattern overrides the server-wide
375
+ // `ctx.services.config.promptEvaluatorSkipPattern` when set, falling back to the
376
+ // global default (#3187) when null. Mirrors how `entry.session.promptEvaluator`
377
+ // (the toggle) is also per-session — the skip pattern shouldn't be the
378
+ // odd one out forced through global config.
379
+ let textToSend = trimmed
380
+ if (
381
+ entry.session.promptEvaluator === true
382
+ && trimmed.length > 0
383
+ && !shouldSkipEvaluator(trimmed, _resolveSkipConfig(entry, ctx))
384
+ ) {
385
+ const counters = _getEvaluatorIterations(ctx)
386
+ const currentIteration = (counters.get(targetSessionId) || 0) + 1
387
+
388
+ if (currentIteration > MAX_EVALUATOR_ITERATIONS) {
389
+ // Cap fired — force-forward and reset for the next cycle so the
390
+ // session isn't permanently locked out of evaluator gating.
391
+ log.warn(`Evaluator iteration cap hit for session ${targetSessionId}; force-forwarding draft`)
392
+ counters.delete(targetSessionId)
393
+ } else {
394
+ // #3636 — per-session serialization. Reject (don't queue) a second
395
+ // concurrent draft for the same session while an evaluator round-trip
396
+ // is in flight. The hoisted check at function entry (#3666) already
397
+ // rejects messages arriving during an in-flight await, so by the time
398
+ // we reach here the lock is guaranteed empty — we just take it.
399
+ const pending = _pendingAwaits
400
+
401
+ const evaluator = typeof ctx.evaluateDraft === 'function' ? ctx.evaluateDraft : defaultEvaluateDraft
402
+ let result
403
+ const evalPromise = (async () => {
404
+ try {
405
+ return await evaluator({ draft: trimmed, cwd: entry.cwd })
406
+ } catch (err) {
407
+ // Fail-open: logged-then-forwarded keeps the user moving when
408
+ // ANTHROPIC_API_KEY is missing or the upstream is down.
409
+ log.warn(`Auto-evaluator failed (${err?.code || 'UNKNOWN'}): ${err?.message || err}; forwarding original draft`)
410
+ return null
411
+ }
412
+ })()
413
+ pending.set(targetSessionId, evalPromise)
414
+ try {
415
+ result = await evalPromise
416
+ } finally {
417
+ // Always release the lock — even on rewrite/clarify/forward paths
418
+ // and on fail-open. Without this, a single failed evaluator call
419
+ // would permanently block all future input on the session.
420
+ if (pending.get(targetSessionId) === evalPromise) {
421
+ pending.delete(targetSessionId)
422
+ }
423
+ }
424
+
425
+ // #3636 — re-check input_conflict after the await. State may have
426
+ // flipped during the round-trip (e.g. another path started the
427
+ // session). Without this, the rewritten/forward draft would race
428
+ // ahead of the now-busy session and produce out-of-order sends.
429
+ if (entry.session.isRunning) {
430
+ const primaryClientId = ctx.transport.getPrimary(targetSessionId)
431
+ if (primaryClientId && primaryClientId !== client.id) {
432
+ ctx.transport.send(ws, buildInputConflictError(targetSessionId, msg.clientMessageId))
433
+ return
434
+ }
435
+ }
436
+
437
+ if (result?.verdict === 'rewrite' && typeof result.rewritten === 'string' && result.rewritten.trim()) {
438
+ counters.delete(targetSessionId)
439
+ const evaluatorIterationId = randomUUID()
440
+ ctx.transport.broadcastToSession(targetSessionId, {
441
+ type: 'evaluator_rewrite',
442
+ sessionId: targetSessionId,
443
+ originalDraft: trimmed,
444
+ rewritten: result.rewritten,
445
+ reasoning: result.reasoning || '',
446
+ evaluatorIterationId,
447
+ })
448
+ textToSend = result.rewritten
449
+ } else if (result?.verdict === 'clarify' && typeof result.clarification === 'string' && result.clarification.trim()) {
450
+ // Clarify path: hold the message, surface the question, increment
451
+ // the counter. The user's NEXT input will be evaluated against the
452
+ // same counter — once it reaches MAX_EVALUATOR_ITERATIONS+1 we cap.
453
+ counters.set(targetSessionId, currentIteration)
454
+ const evaluatorIterationId = randomUUID()
455
+ // #3636: record the draft in history NOW (clarify path is a
456
+ // legitimate persisted entry, not a rejection) so the dashboard
457
+ // sees the draft + the clarification on replay.
458
+ // #3635: record the ORIGINAL draft (not a rewrite) — the
459
+ // dashboard renders the clarify card alongside what the user
460
+ // typed, so the user's intent IS reflected by `trimmed`.
461
+ recordHistoryEntry(trimmed)
462
+ ctx.transport.broadcastToSession(targetSessionId, {
463
+ type: 'evaluator_clarify',
464
+ sessionId: targetSessionId,
465
+ originalDraft: trimmed,
466
+ clarification: result.clarification,
467
+ reasoning: result.reasoning || '',
468
+ evaluatorIterationId,
469
+ evaluatorIteration: currentIteration,
470
+ })
471
+ // DO NOT forward to the session — return early.
472
+ //
473
+ // Update primary even though the message wasn't forwarded — the
474
+ // user's intent was to drive the session, and the input-conflict
475
+ // and primary-changed bookkeeping that downstream clients depend
476
+ // on should reflect that. Without this, two paired clients can
477
+ // both have stale "you're primary" views during a clarify cycle.
478
+ ctx.transport.updatePrimary(targetSessionId, client.id)
479
+ ctx.transport.broadcast(
480
+ { type: 'user_input', sessionId: targetSessionId, clientId: client.id, text: trimmed, messageId, timestamp: Date.now() },
481
+ (c) => c.id !== client.id,
482
+ )
483
+ return
484
+ } else {
485
+ // forward verdict (or unrecognised result) — drop the iteration
486
+ // counter so a clarify-then-forward sequence resets cleanly.
487
+ counters.delete(targetSessionId)
488
+ }
489
+ }
490
+ }
491
+
492
+ // #3636: record history at the forward boundary. All earlier
493
+ // rejection paths (input_conflict pre-await, pending-evaluator guard,
494
+ // post-await re-check) returned without recording. The clarify path
495
+ // already recorded above before its own return.
496
+ // #3635: record what was actually forwarded — `textToSend` is the
497
+ // rewritten string on the rewrite verdict, the original `trimmed`
498
+ // draft on every other path (forward, skip-heuristic, fail-open,
499
+ // cap-bypass).
500
+ recordHistoryEntry(textToSend)
501
+
502
+ // #5313 (WP-1.3): sendMessage is fire-and-forget. If a provider's
503
+ // sendMessage returns a rejecting promise, an unhandled rejection escapes
504
+ // to process-level unhandledRejection → process.exit(1), crashing EVERY
505
+ // session in the daemon over a single per-session send fault. Capture the
506
+ // return and, if thenable, attach a .catch that logs and swallows — real
507
+ // delivery failures still surface to the client via the provider's 'error'
508
+ // event. Mirrors the start() guard in session-manager.js createSession.
509
+ // #5936: forward the resolved clientMessageId so that if this send lands
510
+ // mid-turn and the provider queues it (BaseSession `_outgoingQueue`), the
511
+ // `message_queued` mirror carries the id the sender's optimistic copy uses —
512
+ // letting that client reconcile its queued bubble. Providers that send
513
+ // immediately ignore the extra option.
514
+ const sendResult = entry.session.sendMessage(textToSend, attachments, { isVoice: !!msg.isVoice, clientMessageId: messageId })
515
+ if (sendResult && typeof sendResult.catch === 'function') {
516
+ sendResult.catch((err) => {
517
+ const message = err?.message || String(err)
518
+ log.error(`sendMessage rejected for session ${targetSessionId}: ${message}${err?.stack ? '\n' + err.stack : ''}`)
519
+ })
520
+ }
521
+
522
+ ctx.transport.updatePrimary(targetSessionId, client.id)
523
+
524
+ // Echo user_input to other clients so they see what was sent (#1119).
525
+ // The echo carries `trimmed` (the user's original text) so paired
526
+ // clients can dedup their optimistic copy of what the user typed —
527
+ // the rewritten text is signalled separately via evaluator_rewrite.
528
+ ctx.transport.broadcast(
529
+ { type: 'user_input', sessionId: targetSessionId, clientId: client.id, text: trimmed, messageId, timestamp: Date.now() },
530
+ (c) => c.id !== client.id
531
+ )
532
+ }
533
+
534
+ function handleInterrupt(ws, client, msg, ctx) {
535
+ const interruptSessionId = msg.sessionId || client.activeSessionId
536
+ const entry = resolveSession(ctx, msg, client)
537
+ if (entry) {
538
+ log.info(`Interrupt from ${client.id} to session ${interruptSessionId}`)
539
+ entry.session.interrupt()
540
+ return
541
+ }
542
+ // #4935 — same visibility fix as handleInput for the silent post-restart
543
+ // wedge. An interrupt addressed to a stale session ID used to drop on the
544
+ // floor with no log line and no client-side error. Surface both so the
545
+ // dashboard can clear stale state and the operator can grep chroxy.log.
546
+ //
547
+ // IMPORTANT (Copilot review #4979): like handleInput, resolveSession() can
548
+ // return null for binding mismatches as well as truly-missing sessions.
549
+ // Disambiguate before emitting so a binding mismatch surfaces as the
550
+ // canonical SESSION_TOKEN_MISMATCH envelope rather than being mislabelled
551
+ // as a stale-ID drop.
552
+ if (msg.sessionId && client.boundSessionId && client.boundSessionId !== msg.sessionId) {
553
+ log.info(`interrupt rejected: session-token mismatch sessionId=${msg.sessionId} boundSessionId=${client.boundSessionId} client=${client.id}`)
554
+ ctx.transport.send(ws, {
555
+ type: 'session_error',
556
+ ...buildSessionTokenMismatchPayload({
557
+ sessionManager: ctx.sessions.sessionManager,
558
+ boundSessionId: client.boundSessionId,
559
+ }),
560
+ })
561
+ return
562
+ }
563
+ if (msg.sessionId) {
564
+ log.info(`interrupt dropped: session not found sessionId=${msg.sessionId} client=${client.id} (likely stale ID after daemon restart — see #4935)`)
565
+ ctx.transport.send(ws, {
566
+ type: 'session_error',
567
+ code: 'SESSION_NOT_FOUND',
568
+ message: `Session not found: ${msg.sessionId}`,
569
+ attemptedSessionId: msg.sessionId,
570
+ })
571
+ }
572
+ }
573
+
574
+ /**
575
+ * #5943 (epic #5935): cancel ONE queued send-while-busy follow-up by its
576
+ * `clientMessageId`. Authority mirrors `interrupt` — acting on your OWN bound
577
+ * session, not a privilege escalation — so resolveSession's binding check is the
578
+ * only gate (a pairing-bound client may cancel a queued message in its own
579
+ * session but not another's). Whole-queue cancellation stays on `interrupt`.
580
+ *
581
+ * The session removes the matching `_outgoingQueue` entry and emits
582
+ * `message_dequeued { reason: 'cancelled' }`, which mirrors to every client via
583
+ * the EventNormalizer — so there is no extra reply on success here. A
584
+ * stale/duplicate cancel (id already flushed) is a silent no-op, like an
585
+ * `interrupt` to an idle session. Binding/stale-id failures surface the same
586
+ * session_error envelopes as handleInterrupt.
587
+ */
588
+ function handleCancelQueued(ws, client, msg, ctx) {
589
+ const entry = resolveSession(ctx, msg, client)
590
+ if (entry) {
591
+ const cancelled = entry.session.cancelQueuedMessage(msg.clientMessageId)
592
+ log.info(`cancel_queued ${msg.clientMessageId} from ${client.id} → ${cancelled ? 'removed' : 'no-op (not queued)'}`)
593
+ return
594
+ }
595
+ // Disambiguate a binding mismatch from a truly-missing session, exactly as
596
+ // handleInterrupt does (Copilot review #4979).
597
+ if (msg.sessionId && client.boundSessionId && client.boundSessionId !== msg.sessionId) {
598
+ log.info(`cancel_queued rejected: session-token mismatch sessionId=${msg.sessionId} boundSessionId=${client.boundSessionId} client=${client.id}`)
599
+ ctx.transport.send(ws, {
600
+ type: 'session_error',
601
+ ...buildSessionTokenMismatchPayload({
602
+ sessionManager: ctx.sessions.sessionManager,
603
+ boundSessionId: client.boundSessionId,
604
+ }),
605
+ })
606
+ return
607
+ }
608
+ if (msg.sessionId) {
609
+ log.info(`cancel_queued dropped: session not found sessionId=${msg.sessionId} client=${client.id}`)
610
+ ctx.transport.send(ws, {
611
+ type: 'session_error',
612
+ code: 'SESSION_NOT_FOUND',
613
+ message: `Session not found: ${msg.sessionId}`,
614
+ attemptedSessionId: msg.sessionId,
615
+ })
616
+ }
617
+ }
618
+
619
+ /**
620
+ * #5271 (Control Room Phase 2a): cancel a single in-flight activity node
621
+ * (currently a Task subagent) in a session. Authority mirrors `interrupt` —
622
+ * acting on your own session, NOT a privilege escalation — so resolveSession's
623
+ * standard binding check is the only gate: a pairing-bound client may cancel
624
+ * activity in its OWN bound session but not another's. Whole-turn interruption
625
+ * stays on the `interrupt` message.
626
+ *
627
+ * The session does the work via `cancelActivity(activityId)`, which returns a
628
+ * structured `{ ok, reason }` (never throws). On success the terminal
629
+ * `activity_delta` is broadcast through the existing agent_completed → registry
630
+ * path, so the tree updates live with no extra reply here. Only failures are
631
+ * surfaced to the caller, as a `session_error` (the same envelope interrupt
632
+ * uses for binding/stale-id problems).
633
+ */
634
+ async function handleCancelActivity(ws, client, msg, ctx) {
635
+ const entry = resolveSession(ctx, msg, client)
636
+ if (!entry) {
637
+ // Disambiguate a binding mismatch from a truly-missing session, exactly as
638
+ // handleInterrupt/handleInput do (Copilot review #4979) — a bound client
639
+ // aiming at another session must see SESSION_TOKEN_MISMATCH, not a stale-id
640
+ // drop.
641
+ if (msg.sessionId && client.boundSessionId && client.boundSessionId !== msg.sessionId) {
642
+ log.info(`cancel_activity rejected: session-token mismatch sessionId=${msg.sessionId} boundSessionId=${client.boundSessionId} client=${client.id}`)
643
+ ctx.transport.send(ws, {
644
+ type: 'session_error',
645
+ ...buildSessionTokenMismatchPayload({
646
+ sessionManager: ctx.sessions.sessionManager,
647
+ boundSessionId: client.boundSessionId,
648
+ }),
649
+ })
650
+ return
651
+ }
652
+ const sid = msg.sessionId || client.activeSessionId
653
+ if (!sid) {
654
+ // No id at all to act on — emit the canonical "No active session"
655
+ // envelope (mirrors handleInput) rather than a misleading
656
+ // "Session not found: undefined" with a null attemptedSessionId.
657
+ log.info(`cancel_activity dropped: no active session client=${client.id}`)
658
+ sendSessionError(ws, ctx, 'No active session')
659
+ return
660
+ }
661
+ log.info(`cancel_activity dropped: session not found sessionId=${sid} client=${client.id}`)
662
+ ctx.transport.send(ws, {
663
+ type: 'session_error',
664
+ code: 'SESSION_NOT_FOUND',
665
+ message: `Session not found: ${sid}`,
666
+ attemptedSessionId: sid,
667
+ })
668
+ return
669
+ }
670
+
671
+ const session = entry.session
672
+ if (typeof session.cancelActivity !== 'function') {
673
+ // Defensive: every BaseSession defines it (defaulting to not-supported),
674
+ // but guard so a provider that somehow lacks it can't crash the handler.
675
+ ctx.transport.send(ws, {
676
+ type: 'session_error',
677
+ code: 'CANCEL_ACTIVITY_FAILED',
678
+ message: 'This session does not support cancelling activity',
679
+ reason: 'not-supported',
680
+ activityId: msg.activityId,
681
+ sessionId: msg.sessionId,
682
+ requestId: msg.requestId,
683
+ })
684
+ return
685
+ }
686
+
687
+ const result = await session.cancelActivity(msg.activityId)
688
+ if (!result || result.ok !== true) {
689
+ const reason = (result && result.reason) || 'unknown'
690
+ log.info(`cancel_activity ${msg.activityId} not actioned (${reason}) client=${client.id}`)
691
+ ctx.transport.send(ws, {
692
+ type: 'session_error',
693
+ code: 'CANCEL_ACTIVITY_FAILED',
694
+ message: `Could not cancel activity: ${reason}`,
695
+ reason,
696
+ activityId: msg.activityId,
697
+ sessionId: msg.sessionId,
698
+ requestId: msg.requestId,
699
+ })
700
+ return
701
+ }
702
+ // Success: the node's terminal activity_delta (via agent_completed → registry)
703
+ // is still the substantive change, but #5277 also sends an explicit positive
704
+ // ack echoing the activityId + requestId so the dashboard can correlate this
705
+ // specific cancel click to its outcome — the delta alone is uncorrelated and
706
+ // may lag or drop.
707
+ log.info(`cancel_activity ${msg.activityId} actioned by ${client.id}`)
708
+ ctx.transport.send(ws, {
709
+ type: 'cancel_activity_ack',
710
+ activityId: msg.activityId,
711
+ sessionId: msg.sessionId,
712
+ requestId: msg.requestId,
713
+ })
714
+ }
715
+
716
+ function handleResumeBudget(ws, client, msg, ctx) {
717
+ const budgetSessionId = msg.sessionId || client.activeSessionId
718
+ if (!budgetSessionId || !resolveSession(ctx, msg, client)) {
719
+ sendSessionError(ws, ctx, 'No valid session for budget resume')
720
+ return
721
+ }
722
+ // #5752: only un-pause + broadcast `budget_resumed` (which injects a "session
723
+ // resumed" chat note) when the session was actually paused. Always ack the
724
+ // requesting client so the resume control is never a dead button — a click on
725
+ // an already-resumed session (a second client in a shared session, or a stale
726
+ // tap) resolves cleanly with wasPaused:false instead of silence.
727
+ const wasPaused = ctx.sessions.sessionManager.isBudgetPaused(budgetSessionId)
728
+ if (wasPaused) {
729
+ ctx.sessions.sessionManager.resumeBudget(budgetSessionId)
730
+ ctx.transport.broadcastToSession(budgetSessionId, { type: 'budget_resumed', sessionId: budgetSessionId })
731
+ log.info(`Budget resumed for session ${budgetSessionId} by ${client.id}`)
732
+ } else {
733
+ log.info(`resume_budget no-op for session ${budgetSessionId} (not paused) by ${client.id}`)
734
+ }
735
+ ctx.transport.send(ws, {
736
+ type: 'budget_resume_ack',
737
+ sessionId: budgetSessionId,
738
+ wasPaused,
739
+ // Echo requestId for correlation. The inbound ResumeBudgetSchema caps it at
740
+ // 128 (#5752), so the ack always satisfies ServerBudgetResumeAckSchema —
741
+ // same single-enforcement-point pattern as cancel_activity_ack (#5277).
742
+ ...(typeof msg.requestId === 'string' ? { requestId: msg.requestId } : {}),
743
+ })
744
+ }
745
+
746
+ function handleRegisterPushToken(ws, client, msg, ctx) {
747
+ if (!ctx.services.pushManager || typeof msg.token !== 'string') return
748
+
749
+ // Pass the client's stable ID as the token owner so PushManager can
750
+ // ref-count ownership for multi-connection scenarios (2026-04-11
751
+ // audit blocker 6 + Copilot review on PR #2806): two clients that
752
+ // register the same token must both be released before the token
753
+ // is actually pruned from the registry. Without ref-counting, the
754
+ // first disconnect would strip the token from the second client's
755
+ // active session.
756
+ const ok = ctx.services.pushManager.registerToken(msg.token, client.id)
757
+ if (!ok) {
758
+ ctx.transport.send(ws, {
759
+ type: 'push_token_error',
760
+ // Keep the wording close to the actual validator: minimum length
761
+ // plus a blacklist of obvious garbage characters. The check is a
762
+ // heuristic, not a true Expo/FCM format enforcement (found by
763
+ // Copilot review on PR #2806).
764
+ message: 'Push token rejected — token must be at least 20 characters and contain no whitespace, quotes, URL/shell/JSON punctuation',
765
+ })
766
+ return
767
+ }
768
+
769
+ // Track which tokens this client registered so _handleClientDeparture
770
+ // can release ownership when they disconnect. Without this, an
771
+ // attacker who authenticated, registered their token, and
772
+ // disconnected would leave their token in the registry forever,
773
+ // continuing to receive every future permission prompt.
774
+ if (!client._ownedPushTokens) {
775
+ client._ownedPushTokens = new Set()
776
+ }
777
+ client._ownedPushTokens.add(msg.token)
778
+
779
+ // #4587: bump lastSeenAt + platform on the matching per-device entry
780
+ // (if one exists) so the per-device list UI reflects last-connect time
781
+ // rather than last-pref-change time. NO-OPs on devices that have never
782
+ // muted anything — touchDevice deliberately won't create empty entries.
783
+ ctx.services.pushManager.touchDevice(msg.token, client.deviceInfo?.platform || null)
784
+ }
785
+
786
+ /**
787
+ * Notification preferences handlers (#4541).
788
+ *
789
+ * Two message types: get the current prefs snapshot, patch + re-emit. The
790
+ * server shallow-merges the patch over existing prefs (so the UI can send
791
+ * one toggle at a time) and persists the result via PushManager.setPrefs,
792
+ * which atomically writes ~/.chroxy/notification-prefs.json.
793
+ *
794
+ * After a successful set the snapshot is broadcast to every connected
795
+ * client so additional dashboards / mobile sessions stay in lockstep —
796
+ * mirrors the BYOK credentials handler pattern (#4052).
797
+ *
798
+ * Auth posture: any authenticated WS client can call these. chroxy isn't
799
+ * multi-tenant — the user controls their own notification routing. The
800
+ * existing WS auth gate is sufficient.
801
+ */
802
+ function handleNotificationPrefsGet(ws, client, msg, ctx) {
803
+ if (!ctx.services.pushManager) {
804
+ sendError(ws, msg?.requestId, 'NOT_AVAILABLE', 'notification prefs unavailable (no push manager)', undefined, ctx)
805
+ return
806
+ }
807
+ ctx.transport.send(ws, {
808
+ type: 'notification_prefs',
809
+ requestId: msg?.requestId,
810
+ prefs: ctx.services.pushManager.getPrefs(),
811
+ })
812
+ }
813
+
814
+ function handleNotificationPrefsSet(ws, client, msg, ctx) {
815
+ if (!ctx.services.pushManager) {
816
+ sendError(ws, msg?.requestId, 'NOT_AVAILABLE', 'notification prefs unavailable (no push manager)', undefined, ctx)
817
+ return
818
+ }
819
+ const patch = msg?.prefs
820
+ if (!patch || typeof patch !== 'object') {
821
+ sendError(ws, msg?.requestId, 'INVALID_REQUEST', 'prefs object is required', undefined, ctx)
822
+ return
823
+ }
824
+ // #4551 — validate every device-key against the same gate
825
+ // register_push_token enforces (see PushManager.isValidPushTokenFormat
826
+ // for the canonical rules). The Zod schema caps the devices map size
827
+ // as a DoS guard but does not check key format, so without this an
828
+ // authenticated client can stuff arbitrary strings into
829
+ // ~/.chroxy/notification-prefs.json and have them re-served on every
830
+ // notification_prefs_get. Reject the whole patch on the first bad key
831
+ // (no partial-apply) so the on-disk state stays clean.
832
+ if (patch.devices && typeof patch.devices === 'object') {
833
+ // #4610 — `typeof [] === 'object'` so an array-typed `devices`
834
+ // payload would otherwise reach the key-format loop and reject
835
+ // with a misleading "Invalid device token format" error (true,
836
+ // since '0'/'1'/... fail the 20-char gate, but it mis-describes
837
+ // the real shape mismatch). Reject arrays explicitly with a
838
+ // shape-specific message so misbehaving clients get a clear
839
+ // signal that `devices` must be a map keyed by push token.
840
+ if (Array.isArray(patch.devices)) {
841
+ sendError(ws, msg?.requestId, 'INVALID_REQUEST', 'devices must be an object, not an array', undefined, ctx)
842
+ return
843
+ }
844
+ for (const key of Object.keys(patch.devices)) {
845
+ if (!PushManager.isValidPushTokenFormat(key)) {
846
+ sendError(ws, msg?.requestId, 'INVALID_REQUEST', 'Invalid device token format in notification_prefs_set', undefined, ctx)
847
+ return
848
+ }
849
+ }
850
+ }
851
+ let next
852
+ try {
853
+ // #4587: pass the auth-derived platform so new per-device entries get
854
+ // tagged with ios/android/desktop/web without the client having to
855
+ // include it in every patch. A patch-supplied `platform` (future
856
+ // client carrying richer info) still wins inside setPrefs.
857
+ next = ctx.services.pushManager.setPrefs(patch, { platform: client.deviceInfo?.platform || null })
858
+ } catch (err) {
859
+ log.warn(`notification_prefs_set persist failed: ${err?.message}`)
860
+ sendError(ws, msg?.requestId, 'NOTIFICATION_PREFS_WRITE_FAILED', err?.message || 'write failed', undefined, ctx)
861
+ return
862
+ }
863
+ // Reply to the originating client with the requestId so promise-style
864
+ // callers can resolve.
865
+ ctx.transport.send(ws, { type: 'notification_prefs', requestId: msg?.requestId, prefs: next })
866
+ // Broadcast without requestId so other dashboards / clients update too.
867
+ // Without this, a second dashboard would keep showing stale state until
868
+ // the user re-opened Settings.
869
+ if (typeof ctx.transport.broadcast === 'function') {
870
+ ctx.transport.broadcast({ type: 'notification_prefs', prefs: next })
871
+ }
872
+ }
873
+
874
+ function handleUserQuestionResponse(ws, client, msg, ctx) {
875
+ // #5753 — route by toolUseId when one is supplied. `_registerQuestionRoute`
876
+ // maps every question that has a toolUseId at DISPATCH time (before the
877
+ // client can answer) and the entry is pruned the moment the question is
878
+ // answered (below) or its session is destroyed (ws-server `_questionSessionMap`
879
+ // sweep). So a toolUseId that is supplied but NO LONGER IN THE MAP means the
880
+ // question is already gone — answered, expired-and-cleared, or a double
881
+ // submit. Falling back to `client.activeSessionId` in that case (the old
882
+ // behavior) would mis-deliver the late answer to whatever DIFFERENT question
883
+ // that session is now waiting on — a deny meant for one tool landing on
884
+ // another (Guardian's #5731 finding). Fail CLOSED: drop it.
885
+ //
886
+ // Gate on `.has()`, not value-truthiness: legacy-cli forwarding registers the
887
+ // route with a NULL sessionId (single default session, `getSession(null)`
888
+ // serves the default entry), so a mapped-but-null value is a VALID route, not
889
+ // a drop. And use `typeof === 'string'` (not truthiness) so an empty-string
890
+ // toolUseId — allowed by the wire schema — is treated as supplied (and thus
891
+ // dropped when unmapped), never as "no toolUseId".
892
+ //
893
+ // Only fall back to the active session when NO toolUseId was supplied at all
894
+ // (legacy single-session mode / clients that don't send one), where there is
895
+ // a single question in flight and no cross-question mis-route risk.
896
+ let questionSessionId
897
+ if (typeof msg.toolUseId === 'string') {
898
+ if (!ctx.permissions.questionSessionMap.has(msg.toolUseId)) {
899
+ sessionLogger(client.activeSessionId || undefined).info(
900
+ `user_question_response dropped: stale/unknown toolUseId=${msg.toolUseId} (question already resolved or its session is gone)`,
901
+ )
902
+ return
903
+ }
904
+ questionSessionId = ctx.permissions.questionSessionMap.get(msg.toolUseId)
905
+ } else {
906
+ questionSessionId = client.activeSessionId
907
+ }
908
+
909
+ // Enforce session binding before consuming the mapping — if the client
910
+ // is bound to a different session, leave the mapping intact so the
911
+ // correct client can still respond.
912
+ if (client.boundSessionId && client.boundSessionId !== questionSessionId) return
913
+
914
+ // #4788 (audit P0.2): for UNBOUND clients, require the questionSessionId
915
+ // to match the client's active or subscribed sessions before routing the
916
+ // answer. Without this, an unbound dashboard tab could submit an answer
917
+ // for any session by replaying a known toolUseId — paired with the log
918
+ // leak in #4787 this enables cross-session answer hijacking. Routes through
919
+ // isSessionViewer (#6030) — the SAME predicate _broadcastToSession uses to
920
+ // pick recipients (ws-broadcaster.js _matchesSession) — so the set of clients
921
+ // permitted to ANSWER a question is provably the same set that could
922
+ // legitimately have RECEIVED it, and the two can never drift. Leaves the
923
+ // mapping intact so the legitimate subscribed client can still respond.
924
+ if (!client.boundSessionId) {
925
+ if (!isSessionViewer(client, questionSessionId)) return
926
+ }
927
+
928
+ if (msg.toolUseId) ctx.permissions.questionSessionMap.delete(msg.toolUseId)
929
+
930
+ const entry = ctx.sessions.sessionManager.getSession(questionSessionId)
931
+ if (entry && typeof entry.session.respondToQuestion === 'function' && typeof msg.answer === 'string') {
932
+ // #4604: log the incoming response shape so a multi-question form
933
+ // wedge is correlatable from chroxy.log alone (toolUseId + map-key
934
+ // count distinguishes the SDK's per-question form from the TUI's
935
+ // single-answer string).
936
+ // #4651: log freeformText presence so the Other-path two-stage write
937
+ // is greppable in chroxy.log without leaking the user's text.
938
+ // Copilot review (#4753): explicit boolean — `&&` of a string yields
939
+ // the string, not a boolean, which downstream conditionals can read
940
+ // but is confusing in a `freeform=${...}` log template.
941
+ const hasFreeform = typeof msg.freeformText === 'string' && msg.freeformText.length > 0
942
+ // #4792: scope this entry to the question's session so the WsServer
943
+ // log fan-out (#4787) routes it to the bound dashboard for that
944
+ // session rather than dropping it for all bound clients. The line
945
+ // carries toolUseId + freeform.length — useful for correlating
946
+ // multi-question form wedges per-session in chroxy.log.
947
+ //
948
+ // Legacy single-session mode (ws-message-handlers.js createCliSessionAdapter)
949
+ // serves `getSession(undefined)` from a synthetic default entry, so
950
+ // `questionSessionId` can legitimately be falsy here. In that mode
951
+ // there's exactly one session and no cross-session fan-out leak risk,
952
+ // so fall back to the unscoped `log` instead of throwing — multi-session
953
+ // deployments always have a real sessionId from the toolUseId map or
954
+ // client.activeSessionId.
955
+ const qlog = sessionLogger(questionSessionId)
956
+ qlog.info(`user_question_response received: toolUseId=${msg.toolUseId || '?'} answer.length=${(msg.answer || '').length} answers.keys=${msg.answers ? Object.keys(msg.answers).length : 0} freeform=${hasFreeform ? msg.freeformText.length : 0}`)
957
+ // #4668: forward msg.toolUseId so claude-tui-session can route the
958
+ // answer to the right pending entry in its Map. Sessions that don't
959
+ // care about toolUseId (cli-session, sdk-session via permission-
960
+ // manager) ignore the extra argument — JS positional args make this
961
+ // a safe addition. ByokSession's respondToQuestion forwards to
962
+ // _permissions.respondToQuestion which similarly ignores trailing
963
+ // args it doesn't read.
964
+ // #4651: forward msg.freeformText as a final opts object — claude-tui-
965
+ // session uses it to drive the two-stage Other-path write (digit →
966
+ // text-input prompt → freeform text + Enter). Other providers ignore
967
+ // the trailing arg.
968
+ const opts = hasFreeform ? { freeformText: msg.freeformText } : undefined
969
+ entry.session.respondToQuestion(msg.answer, msg.answers, msg.toolUseId, opts)
970
+ }
971
+ }
972
+
973
+ // #5835 Phase 3: forward raw client keystrokes to the live claude-tui PTY — true
974
+ // remote control (the read-only mirror becomes interactive). Authority mirrors
975
+ // handleInput, deliberately reusing this file's gate primitives:
976
+ // - resolveSession enforces the pairing-bound session binding (a bound token may
977
+ // only drive its own session); a mismatch surfaces the canonical
978
+ // SESSION_TOKEN_MISMATCH envelope (same disambiguation as handleInput/interrupt).
979
+ // - The primary-ownership gate keeps a SINGLE driver: claimPrimary (NON-force)
980
+ // claims an unclaimed session for this client, no-ops if already primary, and
981
+ // REJECTS (input_conflict) if another client owns it. Unlike a chat send — which
982
+ // force-adopts an idle session — a stray keystroke must NOT silently steal a live
983
+ // TUI from its driver; taking over is the explicit claim_primary hand-off, and an
984
+ // observer rides along on the read-only mirror.
985
+ // Only claude-tui sessions expose writeTerminalInput; other providers have no PTY,
986
+ // so the keystroke is silently dropped for them.
987
+ function handleTerminalInput(ws, client, msg, ctx) {
988
+ const sid = msg.sessionId || client.activeSessionId
989
+ const entry = resolveSession(ctx, msg, client)
990
+ if (!entry) {
991
+ // Disambiguate a binding mismatch from a truly-missing session (same as
992
+ // handleInput/handleInterrupt) so a bound client aiming elsewhere sees the
993
+ // canonical SESSION_TOKEN_MISMATCH rather than a silent drop. A truly-missing
994
+ // session returns silently (no SESSION_NOT_FOUND envelope, unlike handleInput):
995
+ // terminal_input is a high-frequency keystroke stream, so a per-key error toast
996
+ // would be noise — the dashboard already clears stale ids off the chat path.
997
+ if (msg.sessionId && client.boundSessionId && client.boundSessionId !== msg.sessionId) {
998
+ log.info(`terminal_input rejected: session-token mismatch sessionId=${msg.sessionId} boundSessionId=${client.boundSessionId} client=${client.id}`)
999
+ ctx.transport.send(ws, {
1000
+ type: 'session_error',
1001
+ ...buildSessionTokenMismatchPayload({
1002
+ sessionManager: ctx.sessions.sessionManager,
1003
+ boundSessionId: client.boundSessionId,
1004
+ }),
1005
+ })
1006
+ }
1007
+ return
1008
+ }
1009
+ if (typeof entry.session.writeTerminalInput !== 'function') return
1010
+ // #5985b (epic #5982): keystrokes into a user-shell PTY require the PRIMARY
1011
+ // token class (audit C1/C4) — a paired device must NEVER type into a root
1012
+ // shell. Silent return (parity with the viewer guard below); the create +
1013
+ // terminal_subscribe gates already prevent a non-primary client from becoming
1014
+ // a shell viewer, so this is defense-in-depth on the keystroke path.
1015
+ if (isUserShellSession(entry) && client.isPrimaryToken !== true) return
1016
+ // Must be VIEWING the session to drive its PTY (#5842 review) — parity with
1017
+ // terminal_resize/terminal_size (#5840): keystrokes are strictly more powerful
1018
+ // than a resize, so they require at least the same viewer precondition. A client
1019
+ // that merely knows an (even unclaimed) session id can't silently become its
1020
+ // driver without watching it. The normal flow (Output tab open → activeSessionId
1021
+ // === sid) passes; this only blocks blind cross-session poking.
1022
+ if (!isSessionViewer(client, sid)) return
1023
+ if (typeof msg.data !== 'string' || msg.data.length === 0) return
1024
+ // Single-driver gate: claim (or confirm) primary; reject an observer's keystroke.
1025
+ const res = ctx.transport.claimPrimary(sid, client.id)
1026
+ if (res?.rejected) {
1027
+ ctx.transport.send(ws, buildInputConflictError(
1028
+ sid,
1029
+ undefined,
1030
+ 'Another device is driving this session. Take over from the session menu to type into the terminal.',
1031
+ ))
1032
+ return
1033
+ }
1034
+ entry.session.writeTerminalInput(msg.data)
1035
+ }
1036
+
1037
+ export const inputHandlers = {
1038
+ input: handleInput,
1039
+ interrupt: handleInterrupt,
1040
+ cancel_queued: handleCancelQueued,
1041
+ terminal_input: handleTerminalInput,
1042
+ cancel_activity: handleCancelActivity,
1043
+ resume_budget: handleResumeBudget,
1044
+ register_push_token: handleRegisterPushToken,
1045
+ notification_prefs_get: handleNotificationPrefsGet,
1046
+ notification_prefs_set: handleNotificationPrefsSet,
1047
+ user_question_response: handleUserQuestionResponse,
1048
+ }