@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,1083 @@
1
+ import { performance } from 'node:perf_hooks'
2
+ import { toShortModelId } from './models.js'
3
+ import { createLogger } from './logger.js'
4
+ import { buildPermissionRequestMessage } from '@chroxy/protocol'
5
+
6
+ const log = createLogger('event-normalizer')
7
+
8
+ // #5555: caps on the delta coalescing buffer's un-flushed residency.
9
+ // - MAX_DELTA_KEY_BYTES: per-stream ceiling. One message buffering more than
10
+ // this between flushes forces an immediate flush of THAT key, preserving
11
+ // order (it is flushed and re-buffered fresh on the next delta).
12
+ // - MAX_DELTA_TOTAL_BYTES: aggregate ceiling across all streams. Crossing it
13
+ // forces a full flush. Guards the many-small-streams case that no per-key
14
+ // cap catches.
15
+ // Chosen so a normal stream (sub-second flush windows of a few KB) never trips
16
+ // them, while a runaway provider is bounded to ~2MB of residency instead of
17
+ // growing the heap until V8 OOMs. Forced flush, never truncation — no data loss.
18
+ const MAX_DELTA_KEY_BYTES = 256 * 1024 // 256 KB per stream
19
+ const MAX_DELTA_TOTAL_BYTES = 2 * 1024 * 1024 // 2 MB across all streams
20
+
21
+ // #5578: deflate-aware coalescing windows. The #5568 floors (8ms single / 16ms
22
+ // multi) are correct for LAN/loopback peers — deflate is stripped at upgrade,
23
+ // each tiny stream_delta is cheap, and a fast emitter producing ~125 frames/sec
24
+ // is fine. They are WRONG for deflate-negotiated (tunnel/cellular) peers: every
25
+ // stream_delta is ~40-75 bytes including serverTs, UNDER the permessage-deflate
26
+ // threshold:1024, so it ships UNCOMPRESSED. The 8ms floor then triples the
27
+ // small-packet count (~40 frames/sec at the old 25ms → ~125/sec at 8ms) on
28
+ // exactly the links where per-frame cost dominates (small-packet overhead,
29
+ // cellular radio wake-ups, tunnel framing). We re-coalesce a beat longer when
30
+ // any subscriber is on a deflate socket: ~16ms single / ~25ms multi. These are
31
+ // still fixed micro-batch windows below the client-side adaptive EWMA floor
32
+ // (store-core resolveDeltaFlushMs, 16-100ms), so they don't reintroduce the
33
+ // pre-#5562 server/client window stacking — they only halve the frame rate on
34
+ // the links that pay for each frame. LAN sessions keep the tight floors.
35
+ const DEFLATE_FLUSH_INTERVAL_MS = 25 // any deflate subscriber, multi-client
36
+ const DEFLATE_SINGLE_CLIENT_FLUSH_INTERVAL_MS = 16 // any deflate subscriber, single client
37
+
38
+ /**
39
+ * Declarative event-to-WS-message mapping.
40
+ *
41
+ * Each entry in EVENT_MAP is:
42
+ * eventName: (data, ctx) => { messages, sideEffects, registrations }
43
+ *
44
+ * Where:
45
+ * messages — Array of { msg, filter? } to broadcast
46
+ * filter: optional (client) => boolean predicate
47
+ * sideEffects — Array of { type, ... } descriptors executed by WsServer
48
+ * registrations — Array of { map, key, value } to register in WsServer maps
49
+ *
50
+ * ctx shape:
51
+ * { sessionId, mode, getSessionEntry, listSessions, getSessionContext }
52
+ * mode: 'multi' | 'legacy-cli'
53
+ */
54
+
55
+ /**
56
+ * #5431 — project a session's outstanding-background-work snapshot into the
57
+ * optional `claude_ready` wire fields. Returns null when the session type
58
+ * doesn't expose a snapshot (only claude-tui implements
59
+ * `getBackgroundTaskSnapshot()` today), the snapshot is unavailable
60
+ * (degraded transcript parse), or there is simply nothing outstanding —
61
+ * in all of those cases the wire message stays byte-identical to the
62
+ * pre-#5431 plain ready, which is the no-regression contract.
63
+ */
64
+ function backgroundTaskFields(ctx) {
65
+ try {
66
+ const snap = ctx?.getSessionEntry?.()?.session?.getBackgroundTaskSnapshot?.()
67
+ if (!snap) return null
68
+ // A computed snapshot is ALWAYS emitted, even when empty: clients treat a
69
+ // present `backgroundTasks` (including `[]`) as authoritative and an
70
+ // absent field as "no information — keep state". A task-notification that
71
+ // lands mid-turn would otherwise strand a stale indicator: the turn-end
72
+ // ready computes an empty snapshot, and the idle re-scan poll never arms
73
+ // because nothing is outstanding.
74
+ const tasks = Array.isArray(snap.backgroundTasks) ? snap.backgroundTasks : []
75
+ const fields = { backgroundTasks: tasks }
76
+ if (snap.scheduledWakeup) fields.scheduledWakeup = snap.scheduledWakeup
77
+ return fields
78
+ } catch (err) {
79
+ log.debug?.(`backgroundTaskFields failed: ${err?.message} — emitting plain ready`)
80
+ return null
81
+ }
82
+ }
83
+
84
+ const EVENT_MAP = Object.create(null)
85
+ Object.assign(EVENT_MAP, {
86
+ ready: (data, ctx) => {
87
+ // #5431: attach outstanding background work (if any) so a respawn /
88
+ // reconnect mid-orchestration doesn't present the session as fully idle.
89
+ const bgFields = backgroundTaskFields(ctx)
90
+ const messages = [{ msg: { type: 'claude_ready', ...(bgFields || {}) } }]
91
+ const entry = ctx.getSessionEntry?.()
92
+ if (entry) {
93
+ // #3687: prefer the actual model the underlying CLI/SDK reports at
94
+ // init (`data.model`) — that's the truth for the running session.
95
+ // Then fall back to the user's explicit override (`entry.session.model`)
96
+ // so a later `setModel()` call isn't masked by a stale `bootedModel`
97
+ // (SdkSession's setModel doesn't restart the process, so its
98
+ // bootedModel only refreshes on the next init). Finally fall back
99
+ // to bootedModel for the case the original bug fixed: user didn't
100
+ // specify a model AND we're past init AND data.model is missing
101
+ // (e.g. legacy callers, replay paths).
102
+ const reportedModel = data?.model || entry.session.model || entry.session.bootedModel
103
+ messages.push({
104
+ msg: {
105
+ type: 'model_changed',
106
+ model: reportedModel ? toShortModelId(reportedModel) : null,
107
+ },
108
+ })
109
+ messages.push({
110
+ msg: {
111
+ type: 'permission_mode_changed',
112
+ mode: entry.session.permissionMode || 'approve',
113
+ },
114
+ })
115
+ }
116
+ return { messages }
117
+ },
118
+
119
+ // #5431: claude-tui's idle transcript re-scan saw the outstanding-work set
120
+ // change (a task-notification landed / a wakeup fired while no turn was
121
+ // running). Re-emit `claude_ready` with the fresh snapshot — the session is
122
+ // idle by definition when this fires, so the ready state is accurate, and
123
+ // an explicit empty `backgroundTasks: []` is the client's signal to clear a
124
+ // stale indicator (absence means "no information", per the schema contract).
125
+ background_tasks_changed: (data) => {
126
+ const tasks = Array.isArray(data?.backgroundTasks) ? data.backgroundTasks : []
127
+ const msg = { type: 'claude_ready', backgroundTasks: tasks }
128
+ if (data?.scheduledWakeup) msg.scheduledWakeup = data.scheduledWakeup
129
+ return { messages: [{ msg }] }
130
+ },
131
+
132
+ conversation_id: (data, ctx) => {
133
+ const messages = [
134
+ { msg: { type: 'conversation_id', sessionId: ctx.sessionId, conversationId: data.conversationId } },
135
+ ]
136
+ return {
137
+ messages,
138
+ sideEffects: [{ type: 'session_list' }],
139
+ }
140
+ },
141
+
142
+ stream_start: (data, ctx) => {
143
+ const messages = [
144
+ { msg: { type: 'stream_start', messageId: data.messageId } },
145
+ { msg: { type: 'agent_busy' } },
146
+ ]
147
+ return {
148
+ messages,
149
+ sideEffects: [
150
+ { type: 'log', message: `[ws] Broadcasting stream_start: ${data.messageId}${ctx.sessionId ? ` (session ${ctx.sessionId})` : ''}` },
151
+ { type: 'session_list' },
152
+ ],
153
+ }
154
+ },
155
+
156
+ stream_delta: (data, _ctx) => {
157
+ // Delta buffering is handled externally — normalizer returns the raw delta
158
+ // and the caller decides whether to buffer or flush.
159
+ return {
160
+ messages: [{ msg: { type: 'stream_delta', messageId: data.messageId, delta: data.delta } }],
161
+ buffer: true, // signal to caller to buffer this delta
162
+ }
163
+ },
164
+
165
+ stream_end: (data, ctx) => {
166
+ return {
167
+ messages: [{ msg: { type: 'stream_end', messageId: data.messageId } }],
168
+ sideEffects: [
169
+ { type: 'flush_deltas', sessionId: ctx.sessionId },
170
+ { type: 'log', message: `[ws] Broadcasting stream_end: ${data.messageId}${ctx.sessionId ? ` (session ${ctx.sessionId})` : ''}` },
171
+ ],
172
+ }
173
+ },
174
+
175
+ message: (data, _ctx) => {
176
+ const msg = {
177
+ type: 'message',
178
+ messageType: data.type,
179
+ content: data.content,
180
+ tool: data.tool,
181
+ options: data.options,
182
+ timestamp: data.timestamp,
183
+ }
184
+ return { messages: [{ msg }] }
185
+ },
186
+
187
+ tool_start: (data) => {
188
+ const msg = { type: 'tool_start', messageId: data.messageId, toolUseId: data.toolUseId, tool: data.tool, input: data.input }
189
+ if (data.serverName) msg.serverName = data.serverName
190
+ return { messages: [{ msg }] }
191
+ },
192
+
193
+ // #4080: incremental partial-JSON chunk for a streaming tool_use
194
+ // `input`. Emitted between tool_start and tool_result while the
195
+ // SDK's input_json_delta chunks arrive. The wire shape mirrors the
196
+ // chroxy event the session emits — clients concatenate partialJson
197
+ // onto a per-toolUseId accumulator (see #4081 / PR #4239 for the
198
+ // dashboard + mobile renderer that consumes this).
199
+ tool_input_delta: (data) => ({
200
+ messages: [{
201
+ msg: {
202
+ type: 'tool_input_delta',
203
+ messageId: data.messageId,
204
+ toolUseId: data.toolUseId,
205
+ partialJson: data.partialJson,
206
+ },
207
+ }],
208
+ }),
209
+
210
+ tool_result: (data) => {
211
+ const msg = { type: 'tool_result', toolUseId: data.toolUseId, result: data.result, truncated: data.truncated }
212
+ if (data.images?.length) msg.images = data.images
213
+ return { messages: [{ msg }] }
214
+ },
215
+
216
+ agent_spawned: (data) => ({
217
+ messages: [{
218
+ msg: { type: 'agent_spawned', toolUseId: data.toolUseId, description: data.description, startedAt: data.startedAt },
219
+ }],
220
+ }),
221
+
222
+ agent_completed: (data) => ({
223
+ messages: [{
224
+ msg: { type: 'agent_completed', toolUseId: data.toolUseId },
225
+ }],
226
+ }),
227
+
228
+ // #5016: nested-sub-bubble support — a Task subagent's intermediate
229
+ // wire event (tool_start / tool_result / tool_input_delta /
230
+ // stream_delta) re-emitted by the parent under `agent_event` so the
231
+ // dashboard renders it inside the parent's Task tool_call bubble.
232
+ // `parentToolUseId` is the parent's tool_use id (same key used by
233
+ // agent_spawned / agent_completed). `eventType` is the child's
234
+ // original event name. `payload` is the verbatim child event payload.
235
+ agent_event: (data, ctx) => {
236
+ const out = {
237
+ messages: [{
238
+ msg: {
239
+ type: 'agent_event',
240
+ parentToolUseId: data.parentToolUseId,
241
+ eventType: data.type,
242
+ payload: data.payload ?? {},
243
+ },
244
+ }],
245
+ }
246
+ // #5056: a relayed Task-subagent permission_request must register its
247
+ // requestId in permissionSessionMap (keyed to the PARENT session id,
248
+ // ctx.sessionId) — exactly like a top-level permission_request does
249
+ // (see the permission_request normalizer above). Two reasons:
250
+ // 1. A pairing-BOUND dashboard client's Approve/Deny is rejected
251
+ // unless permissionSessionMap[requestId] === boundSessionId
252
+ // (handlePermissionResponse, settings-handlers.js ~line 309).
253
+ // The dashboard responds on the PARENT session (the only one it
254
+ // knows), so the map must point requestId → parent session.
255
+ // 2. registerPermissionRoute auto-subscribes eligible clients to
256
+ // the session so the broadcast actually reaches them (#4798).
257
+ // The in-process redirect to the child PermissionManager then happens
258
+ // in ClaudeByokSession.respondToPermission via its routing table — so
259
+ // the wire-level routing (parent session) and the in-process routing
260
+ // (child manager) compose correctly. permission_resolved emits the
261
+ // matching delete so the map is pruned on every resolution path.
262
+ const payload = (data.payload && typeof data.payload === 'object') ? data.payload : {}
263
+ if (data.type === 'permission_request' && payload.requestId) {
264
+ out.registrations = [{ map: 'permission', key: payload.requestId, value: ctx?.sessionId }]
265
+ } else if (data.type === 'permission_resolved' && payload.requestId) {
266
+ out.registrations = [{ map: 'permission', key: payload.requestId, action: 'delete' }]
267
+ }
268
+ return out
269
+ },
270
+
271
+ // #4307: pending-background-shells snapshot changed for a session.
272
+ // BaseSession emits this on both push (run_in_background tool_result
273
+ // observed) and clear (BashOutput tool_use observed). Full snapshot
274
+ // is on the wire so a client subscribed to this event but missing
275
+ // earlier broadcasts (e.g. just-reconnected, late-listener) sees the
276
+ // canonical state without needing a delta protocol. The
277
+ // session_list snapshot carries the same field for the late-joining
278
+ // path. Also pushes a session_list side effect so the SessionInfo
279
+ // entry's `pendingBackgroundShells` slot refreshes for clients that
280
+ // render off the list rather than subscribing to the event directly.
281
+ background_work_changed: (data, ctx) => ({
282
+ messages: [{
283
+ msg: {
284
+ type: 'background_work_changed',
285
+ sessionId: ctx.sessionId,
286
+ pending: Array.isArray(data?.pending) ? data.pending : [],
287
+ },
288
+ }],
289
+ sideEffects: [{ type: 'session_list' }],
290
+ }),
291
+
292
+ // #5160: Control Room activity tree. The ActivityRegistry (owned by
293
+ // BaseSession) maps the existing in-flight signals (tool_start /
294
+ // agent_spawned / background_work_changed / permission_request / …) into
295
+ // `ActivityEntry` records and emits these two events. We inject the
296
+ // canonical `ctx.sessionId` (matching `background_work_changed`) so the
297
+ // wire message carries the SessionManager key the dashboard routes on,
298
+ // regardless of what internal id the session held. Both are transient —
299
+ // not replayed from history; a reconnecting client gets the full tree from
300
+ // the snapshot-on-subscribe in ws-history.sendSessionInfo.
301
+ activity_delta: (data, ctx) => ({
302
+ messages: [{
303
+ msg: {
304
+ type: 'activity_delta',
305
+ sessionId: ctx.sessionId,
306
+ schemaVersion: data.schemaVersion,
307
+ op: data.op,
308
+ entry: data.entry,
309
+ },
310
+ }],
311
+ }),
312
+
313
+ activity_snapshot: (data, ctx) => ({
314
+ messages: [{
315
+ msg: {
316
+ type: 'activity_snapshot',
317
+ sessionId: ctx.sessionId,
318
+ schemaVersion: data.schemaVersion,
319
+ entries: Array.isArray(data?.entries) ? data.entries : [],
320
+ },
321
+ }],
322
+ }),
323
+
324
+ mcp_servers: (data) => ({
325
+ messages: [{
326
+ msg: { type: 'mcp_servers', servers: data.servers },
327
+ }],
328
+ }),
329
+
330
+ // #5936 (epic #5935): outgoing-message queue mirror. The session emits these
331
+ // when a send-while-busy follow-up enters (`message_queued`) or leaves
332
+ // (`message_dequeued`) the server-authoritative queue. We inject the canonical
333
+ // `ctx.sessionId` (the SessionManager key the dashboard routes on) — exactly
334
+ // like activity_delta / background_work_changed — regardless of any internal
335
+ // id the session held. Both transient deltas: not replayed from history. A
336
+ // server→client queue SNAPSHOT for reconnect rehydration is the store-core
337
+ // follow-up (#5937); this slice ships only the live deltas.
338
+ message_queued: (data, ctx) => ({
339
+ messages: [{
340
+ msg: {
341
+ type: 'message_queued',
342
+ sessionId: ctx.sessionId,
343
+ ...(typeof data?.clientMessageId === 'string' ? { clientMessageId: data.clientMessageId } : {}),
344
+ text: typeof data?.text === 'string' ? data.text : '',
345
+ queueLength: typeof data?.queueLength === 'number' ? data.queueLength : 0,
346
+ },
347
+ }],
348
+ }),
349
+
350
+ message_dequeued: (data, ctx) => ({
351
+ messages: [{
352
+ msg: {
353
+ type: 'message_dequeued',
354
+ sessionId: ctx.sessionId,
355
+ ...(typeof data?.clientMessageId === 'string' ? { clientMessageId: data.clientMessageId } : {}),
356
+ queueLength: typeof data?.queueLength === 'number' ? data.queueLength : 0,
357
+ // #5943: pass the per-item cancel reason through alongside the two
358
+ // slice-① reasons; anything unrecognised collapses to 'flush' (the
359
+ // benign default — the client transitions the bubble to sent).
360
+ reason: data?.reason === 'interrupted' || data?.reason === 'cancelled' ? data.reason : 'flush',
361
+ },
362
+ }],
363
+ }),
364
+
365
+ // #3234: skill content-hash mismatch detected by SkillsTrustStore. Only the
366
+ // 8-char hash prefixes go on the wire — the full SHA never leaves the
367
+ // server, matching the sanitised log format from #3215. `mode` is the
368
+ // active trust mode at the time of detection ('warn' or 'block') so a
369
+ // dashboard can render distinct UX (warn = banner, block = the skill is
370
+ // already filtered out so a stronger prompt is appropriate). The event
371
+ // is transient — not replayed on reconnect, since the loader re-checks
372
+ // hashes every time it scans skills.
373
+ //
374
+ // #3241: prefer the explicit `mode` carried by the loader payload over
375
+ // deriving from `blocked`. The loader projects `trustStore.mode`
376
+ // directly so the wire signal matches the operator-facing config rather
377
+ // than a downstream consequence. Falls back to deriving from `blocked`
378
+ // for older callers and stays defensive against unknown values.
379
+ skill_changed: (data, ctx) => {
380
+ const oldHash = typeof data?.oldHash === 'string' ? data.oldHash : ''
381
+ const newHash = typeof data?.newHash === 'string' ? data.newHash : ''
382
+ const explicitMode = data?.mode === 'block' || data?.mode === 'warn' ? data.mode : null
383
+ const mode = explicitMode || (data?.blocked ? 'block' : 'warn')
384
+ return {
385
+ messages: [{
386
+ msg: {
387
+ type: 'skill_changed',
388
+ skillName: data?.name || '',
389
+ sessionId: ctx.sessionId || null,
390
+ oldHashPrefix: oldHash.slice(0, 8),
391
+ newHashPrefix: newHash.slice(0, 8),
392
+ mode,
393
+ },
394
+ }],
395
+ }
396
+ },
397
+
398
+ // #3297: community skill pending first-activation trust grant. Transient —
399
+ // not replayed on reconnect. Fired when the loader discovers a community
400
+ // skill for which no trust grant exists yet.
401
+ skill_trust_request: (data, ctx) => ({
402
+ messages: [{
403
+ msg: {
404
+ type: 'skill_trust_request',
405
+ skillName: data?.name || '',
406
+ author: data?.author || '',
407
+ source: data?.source || 'global',
408
+ description: data?.description || '',
409
+ path: data?.path || '',
410
+ sessionId: ctx.sessionId || null,
411
+ },
412
+ }],
413
+ }),
414
+
415
+ plan_started: () => ({
416
+ messages: [{ msg: { type: 'plan_started' } }],
417
+ }),
418
+
419
+ plan_ready: (data) => ({
420
+ messages: [{
421
+ msg: { type: 'plan_ready', allowedPrompts: data.allowedPrompts },
422
+ }],
423
+ }),
424
+
425
+ // #3899: soft inactivity warning. Session emits this after the soft
426
+ // window of silence; we forward it as a transient WS message so the
427
+ // dashboard / mobile app can render the check-in chip. Session stays
428
+ // alive (no `agent_idle`, no `result`) so existing busy/pending state
429
+ // is preserved. Push notification is dispatched by server-cli's own
430
+ // listener — keep the WS path unmuted so an actively-watching client
431
+ // still gets the chip even if push is suppressed.
432
+ inactivity_warning: (data) => ({
433
+ messages: [{
434
+ msg: {
435
+ type: 'inactivity_warning',
436
+ messageId: data.messageId,
437
+ idleMs: data.idleMs,
438
+ prefab: data.prefab,
439
+ },
440
+ }],
441
+ }),
442
+
443
+ // #4653: chroxy-side multi-question AskUserQuestion deny — surfaces the
444
+ // permission-hook's silent intervention (#4648) as a user-visible event.
445
+ // Forwarded only to subscribers of THIS session: the counter is per-
446
+ // session and a deny on session A shouldn't tick the chip on session B.
447
+ multi_question_intervention: (data) => ({
448
+ messages: [{
449
+ msg: {
450
+ type: 'multi_question_intervention',
451
+ toolUseId: data.toolUseId,
452
+ questionCount: data.questionCount,
453
+ reason: data.reason,
454
+ timestamp: data.timestamp,
455
+ },
456
+ }],
457
+ }),
458
+
459
+ result: (data, ctx) => {
460
+ const messages = [
461
+ { msg: { type: 'result', cost: data.cost, duration: data.duration, usage: data.usage, sessionId: data.sessionId } },
462
+ { msg: { type: 'agent_idle' } },
463
+ ]
464
+ const sideEffects = [{ type: 'session_list' }]
465
+ if (ctx.mode === 'multi') {
466
+ sideEffects.push({ type: 'refresh_context', sessionId: ctx.sessionId })
467
+ }
468
+ return { messages, sideEffects }
469
+ },
470
+
471
+ cost_update: (data) => ({
472
+ messages: [{ msg: { type: 'cost_update', sessionCost: data.sessionCost, totalCost: data.totalCost, budget: data.budget } }],
473
+ }),
474
+
475
+ // #4072: cumulative per-session usage + cost broadcast on every priced
476
+ // result. Fires alongside cost_update — the two carry different shapes
477
+ // (cost_update is budget-oriented; session_usage is the full token
478
+ // breakdown for the dashboard / app badge). Subscription-only
479
+ // providers (claude-tui) emit `result` without a numeric `cost` so
480
+ // their session_usage never fires and `cumulativeUsage` stays zero.
481
+ session_usage: (data) => ({
482
+ messages: [{ msg: { type: 'session_usage', cumulativeUsage: data.cumulativeUsage } }],
483
+ }),
484
+
485
+ // #4075: soft per-session cost-threshold crossing. Distinct from
486
+ // budget_warning (which is budget-cap-relative); this is the
487
+ // "you've spent $X" notification that fires ONCE per session when
488
+ // cumulativeUsage.costUsd crosses the configured threshold (default
489
+ // $5). The dashboard + app render a dismissible banner.
490
+ session_cost_threshold_crossed: (data) => ({
491
+ messages: [{ msg: { type: 'session_cost_threshold_crossed', costUsd: data.costUsd, thresholdUsd: data.thresholdUsd } }],
492
+ }),
493
+
494
+ budget_warning: (data) => ({
495
+ messages: [{ msg: { type: 'budget_warning', sessionCost: data.sessionCost, budget: data.budget, percent: data.percent, message: data.message } }],
496
+ }),
497
+
498
+ budget_exceeded: (data) => ({
499
+ messages: [{ msg: { type: 'budget_exceeded', sessionCost: data.sessionCost, budget: data.budget, percent: data.percent, message: data.message } }],
500
+ }),
501
+
502
+ user_question: (data, ctx) => ({
503
+ messages: [{
504
+ msg: { type: 'user_question', toolUseId: data.toolUseId, questions: data.questions },
505
+ }],
506
+ registrations: [{ map: 'question', key: data.toolUseId, value: ctx.sessionId }],
507
+ }),
508
+
509
+ permission_request: (data, ctx) => ({
510
+ messages: [{
511
+ msg: buildPermissionRequestMessage({
512
+ requestId: data.requestId,
513
+ tool: data.tool,
514
+ description: data.description,
515
+ input: data.input,
516
+ remainingMs: data.remainingMs,
517
+ }),
518
+ }],
519
+ registrations: [{ map: 'permission', key: data.requestId, value: ctx.sessionId }],
520
+ sideEffects: [{
521
+ type: 'push',
522
+ category: 'permission',
523
+ title: 'Permission needed',
524
+ body: `Claude wants to use: ${data.tool}`,
525
+ data: { requestId: data.requestId, tool: data.tool },
526
+ channelId: 'permission',
527
+ }],
528
+ }),
529
+
530
+ permission_expired: (data, ctx) => ({
531
+ messages: [{
532
+ msg: {
533
+ type: 'permission_expired',
534
+ requestId: data.requestId,
535
+ sessionId: ctx.sessionId,
536
+ message: data.message,
537
+ },
538
+ }],
539
+ }),
540
+
541
+ // #3048: clear stale prompts on every connected client when a permission
542
+ // resolves via any path (user response, timeout, abort signal, clearAll).
543
+ // The SDK paths in settings-handlers.js (WS) and ws-permissions.js (HTTP)
544
+ // were de-inlined to use this mapping, but the legacy non-SDK branches in
545
+ // those files (no PermissionManager available) still broadcast inline.
546
+ //
547
+ // #3736: also emit a delete registration so the WsServer routing map
548
+ // (permissionSessionMap or questionSessionMap) is pruned on every
549
+ // resolution path — including the internal auto-resolve paths (timeout,
550
+ // aborted, auto_mode, cleared) where no user response ever arrives to
551
+ // trigger the message-handler-level delete. Without this, long-running
552
+ // sessions accumulate stale entries (small leak, unbounded growth until
553
+ // session destroy). The AskUserQuestion variant carries `toolUseId`
554
+ // instead of `requestId` and uses a separate map.
555
+ permission_resolved: (data, ctx) => {
556
+ const out = { messages: [] }
557
+ if (data.requestId) {
558
+ // Permission-prompt variant — broadcast a permission_resolved message
559
+ // matching the original permission_request and prune the routing-map
560
+ // entry that ws-forwarding set when the request was first registered.
561
+ out.messages.push({
562
+ msg: {
563
+ type: 'permission_resolved',
564
+ requestId: data.requestId,
565
+ decision: data.decision,
566
+ sessionId: ctx.sessionId,
567
+ },
568
+ })
569
+ out.registrations = [{ map: 'permission', key: data.requestId, action: 'delete' }]
570
+ } else if (data.toolUseId) {
571
+ // AskUserQuestion variant — there is no `permission_resolved` wire
572
+ // contract for questions (clients dismiss the prompt via the
573
+ // user_question_response round-trip, not via a broadcast), so don't
574
+ // synthesise a bogus message with `requestId`/`decision` both
575
+ // undefined. Only emit the cleanup registration so questionSessionMap
576
+ // is pruned. Pre-#3736 the sdk-session re-emit was gated on
577
+ // `requestId` and dropped the question variant entirely, so the
578
+ // normalizer never saw it; widening the gate would now have emitted
579
+ // a malformed broadcast if we kept the unconditional messages entry.
580
+ out.registrations = [{ map: 'question', key: data.toolUseId, action: 'delete' }]
581
+ }
582
+ return out
583
+ },
584
+
585
+ error: (data) => {
586
+ const msg = {
587
+ type: 'message',
588
+ messageType: 'error',
589
+ content: data.message,
590
+ timestamp: Date.now(),
591
+ }
592
+ if (data.code) msg.code = data.code
593
+ // #4947: forward `attemptedResumeId` when CliSession's resume-failure
594
+ // path tagged the error envelope (see cli-session.js
595
+ // `_handleChildClose` — emits `error{code:'resume_unknown',
596
+ // attemptedResumeId, message}` from server PR #4944). The dashboard
597
+ // ResumeUnknownChip surfaces this id as subtext so operators can
598
+ // correlate against `~/.chroxy/session-state.json.resumeConversationId`
599
+ // without grepping logs.
600
+ //
601
+ // #4948: also forward on `resume_unknown_exhausted` — the terminal
602
+ // escalation code emitted when the post-fallback retry ALSO matches the
603
+ // unknown-resume pattern. Same operator-correlation rationale; the
604
+ // dashboard renders a distinct "auto-recovery exhausted" affordance but
605
+ // still wants to surface the attempted id as subtext.
606
+ //
607
+ // Hardening (from PR #4967 Copilot review):
608
+ // 1. Gate strictly on the two resume-failure codes so a buggy producer
609
+ // can't sneak the field onto unrelated error envelopes.
610
+ // 2. Trim whitespace and treat whitespace-only as missing — same UX
611
+ // guard the chip's render-time check already applies, but enforced
612
+ // at the wire boundary so downstream consumers (mobile app, future
613
+ // log/console viewers) see a consistent "present or absent, never
614
+ // present-but-empty" shape.
615
+ // 3. Enforce the same 256-char cap the wire schema declares
616
+ // (`ServerMessageSchema.attemptedResumeId`). The server doesn't
617
+ // validate outgoing messages against ServerMessageSchema before
618
+ // send, so without this guard a misbehaving producer could ship a
619
+ // megabyte payload that the dashboard accepts (lax client parse)
620
+ // but trips Zod-validating consumers. Silently truncate rather
621
+ // than drop — the truncated id still helps operator triage.
622
+ if (
623
+ (data.code === 'resume_unknown' || data.code === 'resume_unknown_exhausted') &&
624
+ typeof data.attemptedResumeId === 'string'
625
+ ) {
626
+ const trimmed = data.attemptedResumeId.trim()
627
+ if (trimmed.length > 0) {
628
+ msg.attemptedResumeId = trimmed.length > 256 ? trimmed.slice(0, 256) : trimmed
629
+ }
630
+ }
631
+ // #5067: forward captured `stdout` / `stderr` on docker-byok
632
+ // postCreateCommand failures so the operator can diagnose without
633
+ // re-running the broken setup. The session layer
634
+ // (docker-byok-session.js) already tail-caps each stream to
635
+ // POST_CREATE_OUTPUT_CAP_BYTES (4 KiB) before emitting; we re-cap at
636
+ // the wire boundary at 8 KiB per stream as a belt-and-suspenders
637
+ // bound (matches ServerMessageSchema.{stdout,stderr}.max(8192)) so a
638
+ // misbehaving producer can't ship a megabyte payload that the
639
+ // dashboard accepts but trips Zod-validating consumers. Gated
640
+ // strictly on the post-create-failure code so a buggy producer can't
641
+ // sneak the fields onto unrelated error envelopes — same hardening
642
+ // pattern as the resume_unknown gate above. Empty-string and
643
+ // non-string both treated as "absent" so receivers see a consistent
644
+ // "present or absent, never present-but-empty" shape.
645
+ if (data.code === 'post_create_command_failed') {
646
+ if (typeof data.stdout === 'string' && data.stdout.length > 0) {
647
+ msg.stdout = data.stdout.length > 8192 ? data.stdout.slice(0, 8192) : data.stdout
648
+ }
649
+ if (typeof data.stderr === 'string' && data.stderr.length > 0) {
650
+ msg.stderr = data.stderr.length > 8192 ? data.stderr.slice(0, 8192) : data.stderr
651
+ }
652
+ }
653
+ return { messages: [{ msg }] }
654
+ },
655
+
656
+ // #4756: user-initiated Stop confirmation. CliSession emits `stopped`
657
+ // when the child process exits cleanly after `interrupt()` set the
658
+ // `_intentionalStop` flag (see cli-session.js `_handleChildClose`). This
659
+ // pairs with `error` — `error` is the louder "crashed unexpectedly,
660
+ // restarting" toast that the auto-respawn path triggers, while
661
+ // `session_stopped` is the quiet "you asked, it stopped" confirmation.
662
+ // Clients should treat it as informational, NOT an error condition.
663
+ // `code` is the exit status from the child; typically 0 on clean SIGINT
664
+ // exit but kept on the wire so clients can render the numeric code for
665
+ // diagnostic purposes if non-zero (e.g. SIGTERM = 143). Gated on
666
+ // `Number.isInteger` (not bare `typeof === 'number'`) so NaN / Infinity
667
+ // / floats from a defensive provider can't reach the wire — the schema
668
+ // is `z.number().int()`, so non-integers would fail client-side parsing.
669
+ // `sessionId` is OMITTED on the legacy-cli path where ctx.sessionId is
670
+ // null, matching the `claude_ready` / `error` legacy-cli convention so
671
+ // receivers treat the message as "applies to the connected legacy CLI"
672
+ // rather than seeing `sessionId: null`. On the multi-session path the
673
+ // field is also injected by `_broadcastToSession`, so this guard
674
+ // additionally protects against accidental `sessionId: null` if the
675
+ // upstream ctx ever degrades.
676
+ stopped: (data, ctx) => {
677
+ const msg = { type: 'session_stopped' }
678
+ if (typeof ctx.sessionId === 'string' && ctx.sessionId.length > 0) {
679
+ msg.sessionId = ctx.sessionId
680
+ }
681
+ if (Number.isInteger(data?.code)) msg.code = data.code
682
+ return { messages: [{ msg }] }
683
+ },
684
+
685
+ // #3544: surface the cumulative stdin_dropped totals on the wire so
686
+ // dashboards and the mobile app can render a "X bytes lost over N drops"
687
+ // banner / badge for sessions that are silently truncating input at the
688
+ // SidecarProcess pre-dial cap. Transient — not replayed on reconnect,
689
+ // but the cumulative counters are session-lifetime so the next drop
690
+ // re-publishes the running total. The `escalated` flag mirrors the
691
+ // server-side log level (true = first drop / threshold-cross / every-Nth)
692
+ // so the UI can use a louder treatment for the loud-signal moments.
693
+ stdin_dropped_totals: (data, ctx) => {
694
+ const bytes = typeof data?.bytes === 'number' && Number.isFinite(data.bytes)
695
+ ? Math.max(0, Math.trunc(data.bytes))
696
+ : 0
697
+ const count = typeof data?.count === 'number' && Number.isFinite(data.count)
698
+ ? Math.max(0, Math.trunc(data.count))
699
+ : 0
700
+ const reason = typeof data?.reason === 'string' && data.reason.length > 0
701
+ ? data.reason
702
+ : 'unknown'
703
+ const escalated = typeof data?.escalated === 'boolean' ? data.escalated : false
704
+ return {
705
+ messages: [{
706
+ msg: {
707
+ type: 'stdin_dropped_totals',
708
+ sessionId: ctx.sessionId ?? null,
709
+ bytes,
710
+ count,
711
+ reason,
712
+ escalated,
713
+ },
714
+ }],
715
+ }
716
+ },
717
+
718
+ })
719
+
720
+ /**
721
+ * EventNormalizer transforms session events into a uniform set of
722
+ * WS messages, side effects, and registration actions.
723
+ *
724
+ * Owns delta buffering with configurable flush interval.
725
+ */
726
+ export class EventNormalizer {
727
+ /**
728
+ * @param {object} [opts]
729
+ * @param {number} [opts.flushIntervalMs=16] - #5562: default delta micro-batch
730
+ * window. This is NOT an adaptive throttle — it's a small fixed window that
731
+ * coalesces the burst of per-token deltas a provider emits into a single
732
+ * emit + broadcast, bounding per-token CPU/socket overhead. The ADAPTIVE
733
+ * throttle lives client-side (store-core resolveDeltaFlushMs, a 16-100ms
734
+ * EWMA keyed on render cost). Before #5562 the server window was 25/50ms,
735
+ * which STACKED on top of the client EWMA — up to ~150ms of pure buffering
736
+ * on a poor link, and a LAN client never got under the 25ms floor. Shrinking
737
+ * it to ~8-16ms leaves the client EWMA as the sole adaptive system while the
738
+ * server still amortizes the per-token broadcast cost.
739
+ * @param {number} [opts.singleClientFlushIntervalMs=8] - #5562: tighter
740
+ * micro-batch window used when EXACTLY ONE client is subscribed to the
741
+ * session being buffered. With a single viewer there's no fan-out to
742
+ * amortize, so the window only needs to absorb the immediate per-token burst
743
+ * (the common phone-on-LAN / single-dashboard case). The subscriber-count
744
+ * distinction is kept because it bounds broadcast amplification — a wider
745
+ * window on multi-client sessions still batches the fan-out — but both
746
+ * values are now far below the client EWMA floor so they no longer dominate
747
+ * end-to-end latency.
748
+ * @param {(sessionId: string|null) => (number|null)} [opts.getSubscriberCount]
749
+ * - returns how many clients are subscribed to `sessionId`, or null when
750
+ * unknown (e.g. legacy single-session mode). When the count is exactly 1 the
751
+ * single-client window is used; otherwise (0, ≥2, or null) the default.
752
+ * @param {number} [opts.deflateFlushIntervalMs=25] - #5578: multi-client
753
+ * window used when ANY subscriber of the session is on a deflate-negotiated
754
+ * (tunnel/cellular) socket. Wider than the LAN default because each
755
+ * sub-threshold delta ships uncompressed; see DEFLATE_FLUSH_INTERVAL_MS.
756
+ * @param {number} [opts.deflateSingleClientFlushIntervalMs=16] - #5578:
757
+ * single-client window when the sole subscriber is on a deflate socket.
758
+ * @param {(sessionId: string|null) => boolean} [opts.getHasDeflateSubscriber]
759
+ * - returns true when ANY subscriber of `sessionId` is on a
760
+ * deflate-negotiated socket. Resolved O(subscribers) via the reverse index
761
+ * (#5575). When absent (legacy mode) the deflate-aware widening is disabled
762
+ * and the LAN floors apply.
763
+ */
764
+ constructor({ flushIntervalMs = 16, singleClientFlushIntervalMs = 8, getSubscriberCount = null, getHasDeflateSubscriber = null, deflateFlushIntervalMs = DEFLATE_FLUSH_INTERVAL_MS, deflateSingleClientFlushIntervalMs = DEFLATE_SINGLE_CLIENT_FLUSH_INTERVAL_MS, maxKeyBytes = MAX_DELTA_KEY_BYTES, maxTotalBytes = MAX_DELTA_TOTAL_BYTES } = {}) {
765
+ this._flushIntervalMs = flushIntervalMs
766
+ this._singleClientFlushIntervalMs = singleClientFlushIntervalMs
767
+ this._deflateFlushIntervalMs = deflateFlushIntervalMs
768
+ this._deflateSingleClientFlushIntervalMs = deflateSingleClientFlushIntervalMs
769
+ this._getSubscriberCount = typeof getSubscriberCount === 'function' ? getSubscriberCount : null
770
+ this._getHasDeflateSubscriber = typeof getHasDeflateSubscriber === 'function' ? getHasDeflateSubscriber : null
771
+ // #5555: residency caps for the coalescing buffer. A runaway provider (huge
772
+ // tool output, model repetition loop) can grow this Map between flushes
773
+ // faster than ws-broadcaster's socket backpressure can react — the data
774
+ // hasn't reached a socket yet, so backpressure never trips and V8 OOMs the
775
+ // daemon. We bound RESIDENCY (not content): exceeding a cap forces an
776
+ // immediate ordered flush of the affected key / whole buffer. No truncation,
777
+ // no data loss — the cap just shortens how long bytes live un-flushed.
778
+ this._maxKeyBytes = maxKeyBytes
779
+ this._maxTotalBytes = maxTotalBytes
780
+ // Byte sizes tracked incrementally (UTF-8) so the hot path never
781
+ // re-serializes the buffer to measure it.
782
+ this._deltaKeyBytes = new Map() // key -> byte length of its accumulated text
783
+ this._deltaTotalBytes = 0 // sum of _deltaKeyBytes values
784
+ // Delta buffer: key -> accumulated text
785
+ // In multi-session mode key = `${sessionId}:${messageId}`, otherwise just messageId
786
+ this._deltaBuffer = new Map()
787
+ // #5515 (epic #5514): key -> monotonic ms of the FIRST delta buffered into
788
+ // the current (un-flushed) window. Lets ws-forwarding measure the time the
789
+ // oldest token in a flush spent inside the server (coalescing + forwarding)
790
+ // — a true monotonic duration, same process both ends.
791
+ this._deltaEmitMono = new Map()
792
+ this._deltaFlushTimer = null
793
+ // #5516: monotonic deadline (performance.now ms) the pending flush timer is
794
+ // scheduled to fire at. Lets a later single-client buffer SHORTEN an
795
+ // already-scheduled default-window timer instead of waiting it out.
796
+ this._deltaFlushDeadline = 0
797
+ this._onFlush = null // callback: (entries) => void, where entries = [{ key, sessionId, messageId, delta, emitMonoMs }]
798
+ }
799
+
800
+ /**
801
+ * #5516/#5562/#5578: resolve the fixed micro-batch window for the session
802
+ * currently being buffered. Two axes:
803
+ * - subscriber COUNT: exactly 1 → tighter single-client window; else (0, 2+,
804
+ * unknown) → the multi-client window.
805
+ * - deflate LOCALITY: any subscriber on a deflate-negotiated (tunnel/
806
+ * cellular) socket → widen to the deflate window for the resolved count.
807
+ * #5578 — on those links each sub-1024B stream_delta ships uncompressed,
808
+ * so the LAN floors (8/16ms) triple the small-packet count where per-frame
809
+ * cost dominates. All-LAN sessions keep the tight floors.
810
+ * No subscriber-count resolver wired (legacy mode) → always the default LAN
811
+ * window. This is a fixed window, not an adaptive throttle — the adaptive part
812
+ * lives in the client's resolveDeltaFlushMs EWMA (store-core).
813
+ * @param {string|null} sessionId
814
+ * @returns {number} flush interval in ms
815
+ */
816
+ _resolveFlushIntervalMs(sessionId) {
817
+ if (!this._getSubscriberCount) return this._flushIntervalMs
818
+ const count = this._getSubscriberCount(sessionId)
819
+ const single = count === 1
820
+ // #5578: prefer the deflate window when any subscriber sits on a deflate
821
+ // socket. The predicate is O(subscribers) and short-circuits on the first
822
+ // match (ws-broadcaster._hasDeflateSubscriber) — no O(all-clients) scan.
823
+ if (this._getHasDeflateSubscriber && this._getHasDeflateSubscriber(sessionId)) {
824
+ return single ? this._deflateSingleClientFlushIntervalMs : this._deflateFlushIntervalMs
825
+ }
826
+ return single ? this._singleClientFlushIntervalMs : this._flushIntervalMs
827
+ }
828
+
829
+ /**
830
+ * Register a custom event type handler at runtime.
831
+ * Allows provider plugins to extend the normalizer without modifying EVENT_MAP.
832
+ *
833
+ * @param {string} name - Event name (e.g. 'my_provider_event')
834
+ * @param {Function} handler - (data, ctx) => { messages, sideEffects?, registrations? }
835
+ * @throws {Error} if name is not a non-empty string or handler is not a function
836
+ */
837
+ registerEventType(name, handler) {
838
+ if (typeof name !== 'string' || !name) {
839
+ throw new Error('registerEventType: name must be a non-empty string')
840
+ }
841
+ if (name === '__proto__' || name === 'constructor' || name === 'prototype') {
842
+ throw new Error(`registerEventType: reserved key '${name}' is not allowed`)
843
+ }
844
+ if (typeof handler !== 'function') {
845
+ throw new Error('registerEventType: handler must be a function')
846
+ }
847
+ EVENT_MAP[name] = handler
848
+ }
849
+
850
+ /**
851
+ * Set the flush callback. Called with buffered deltas when the timer fires.
852
+ * @param {Function} cb - (entries: Array<{ key, sessionId, messageId, delta }>) => void
853
+ */
854
+ set onFlush(cb) {
855
+ this._onFlush = cb
856
+ }
857
+
858
+ /**
859
+ * Normalize a session event into WS actions.
860
+ *
861
+ * @param {string} event - Event name (e.g., 'stream_start', 'message')
862
+ * @param {object} data - Event data from the session
863
+ * @param {object} ctx - Context: { sessionId, mode, getSessionEntry, listSessions, getSessionContext }
864
+ * @returns {{ messages?: Array, sideEffects?: Array, registrations?: Array, buffer?: boolean } | null}
865
+ */
866
+ normalize(event, data, ctx) {
867
+ const handler = EVENT_MAP[event]
868
+ if (!handler) return null
869
+ return handler(data, ctx)
870
+ }
871
+
872
+ /**
873
+ * Buffer a stream_delta for coalesced delivery.
874
+ * @param {string} sessionId - Session ID (may be null for legacy mode)
875
+ * @param {string} messageId - Stream message ID
876
+ * @param {string} delta - Text delta to buffer
877
+ * @param {number} [emitMonoMs] - #5515: monotonic ms the provider emitted this
878
+ * delta. First-write-wins per flush window so the flushed entry reports how
879
+ * long the OLDEST coalesced token waited inside the server.
880
+ */
881
+ bufferDelta(sessionId, messageId, delta, emitMonoMs) {
882
+ const key = sessionId ? `${sessionId}:${messageId}` : messageId
883
+ // #5555: coerce a non-string delta to its string form ONCE and use that for
884
+ // both the buffer concat AND the byte count. A bare `existing + delta` would
885
+ // string-coerce a non-string into the buffer (real residency) while a
886
+ // `typeof delta === 'string'` byte guard scored it as 0 — the caps would
887
+ // under-count actual residency and could miss the OOM ceiling this fix
888
+ // exists to enforce. Coercing once keeps the accounting equal to what's
889
+ // stored. (Providers always emit strings; this is purely defensive.)
890
+ const text = typeof delta === 'string' ? delta : String(delta ?? '')
891
+ const existing = this._deltaBuffer.get(key) || ''
892
+ this._deltaBuffer.set(key, existing + text)
893
+ if (typeof emitMonoMs === 'number' && !this._deltaEmitMono.has(key)) {
894
+ this._deltaEmitMono.set(key, emitMonoMs)
895
+ }
896
+ // #5555: maintain byte-size counters incrementally (UTF-8) — no
897
+ // re-serialization on the hot path. `text` is the only new content, so its
898
+ // byte length is the per-call growth for both the key total and the global
899
+ // total, and it matches exactly what was concatenated above.
900
+ const addedBytes = Buffer.byteLength(text)
901
+ const keyBytes = (this._deltaKeyBytes.get(key) || 0) + addedBytes
902
+ this._deltaKeyBytes.set(key, keyBytes)
903
+ this._deltaTotalBytes += addedBytes
904
+
905
+ // #5555: residency caps. Order matters — flush the over-cap KEY first
906
+ // (bounded, targeted), then re-check the global total. A forced flush
907
+ // emits via the same onFlush path the timer uses, so coalescing order is
908
+ // preserved: the over-cap key goes out now, fresh deltas re-buffer behind
909
+ // it. We flush BEFORE arming/keeping the timer below so a tripped cap
910
+ // doesn't also leave a redundant timer pointing at an empty key.
911
+ if (keyBytes >= this._maxKeyBytes) {
912
+ this._forceFlushKey(key)
913
+ }
914
+ if (this._deltaTotalBytes >= this._maxTotalBytes) {
915
+ this._flushDeltas()
916
+ }
917
+ if (this._deltaBuffer.size === 0) {
918
+ // Everything just got force-flushed — no timer needed.
919
+ if (this._deltaFlushTimer) {
920
+ clearTimeout(this._deltaFlushTimer)
921
+ this._deltaFlushTimer = null
922
+ this._deltaFlushDeadline = 0
923
+ }
924
+ return
925
+ }
926
+ // #5516/#5562/#5578: fixed micro-batch window (NOT an adaptive coalescing
927
+ // window) — tighter (8ms) when this session has a single LAN subscriber,
928
+ // default (16ms) for multi/LAN, and WIDER (16/25ms) when any subscriber is
929
+ // on a deflate (tunnel/cellular) socket where each sub-threshold frame ships
930
+ // uncompressed. Its only job is to absorb the per-token burst into one
931
+ // emit/broadcast and bound that overhead; the ADAPTIVE throttle lives
932
+ // client-side in store-core resolveDeltaFlushMs (16-100ms EWMA). The flush
933
+ // timer is shared across all buffered sessions, so a single-client session
934
+ // buffered AFTER a default-window timer was already armed must be able to
935
+ // pull the deadline IN (reschedule to the sooner target) rather than wait
936
+ // out the wider window. We never push a deadline out.
937
+ const intervalMs = this._resolveFlushIntervalMs(sessionId)
938
+ const now = performance.now()
939
+ const wantDeadline = now + intervalMs
940
+ if (!this._deltaFlushTimer) {
941
+ this._deltaFlushDeadline = wantDeadline
942
+ this._deltaFlushTimer = setTimeout(() => this._flushDeltas(), intervalMs)
943
+ } else if (wantDeadline < this._deltaFlushDeadline) {
944
+ clearTimeout(this._deltaFlushTimer)
945
+ this._deltaFlushDeadline = wantDeadline
946
+ this._deltaFlushTimer = setTimeout(() => this._flushDeltas(), Math.max(0, wantDeadline - now))
947
+ }
948
+ }
949
+
950
+ /**
951
+ * #5555: force an immediate flush of a SINGLE over-cap key via the onFlush
952
+ * path, preserving coalescing order. The key is removed from all buffer maps;
953
+ * subsequent deltas for it re-buffer fresh behind whatever just went out.
954
+ * No-op (but still drops the key's accounting) when no onFlush is wired.
955
+ * @param {string} key
956
+ */
957
+ _forceFlushKey(key) {
958
+ if (!this._deltaBuffer.has(key)) return
959
+ const delta = this._deltaBuffer.get(key)
960
+ const emitMonoMs = this._deltaEmitMono.get(key)
961
+ this._deltaBuffer.delete(key)
962
+ this._deltaEmitMono.delete(key)
963
+ this._deltaTotalBytes -= this._deltaKeyBytes.get(key) || 0
964
+ this._deltaKeyBytes.delete(key)
965
+ if (this._deltaTotalBytes < 0) this._deltaTotalBytes = 0
966
+ if (this._onFlush) {
967
+ const sepIdx = key.indexOf(':')
968
+ const entry = sepIdx !== -1
969
+ ? { key, sessionId: key.slice(0, sepIdx), messageId: key.slice(sepIdx + 1), delta, emitMonoMs }
970
+ : { key, sessionId: null, messageId: key, delta, emitMonoMs }
971
+ // Mirror _flushDeltas' containment: a throwing broadcast must not escape
972
+ // the buffer hot path (which runs under the provider's event emit).
973
+ try {
974
+ this._onFlush([entry])
975
+ } catch (err) {
976
+ const message = err?.message || String(err)
977
+ log.error(`Delta force-flush onFlush callback threw: ${message}${err?.stack ? '\n' + err.stack : ''}`)
978
+ }
979
+ }
980
+ }
981
+
982
+ /**
983
+ * Flush all buffered deltas for a specific session (called before stream_end).
984
+ * Returns the flushed entries so the caller can broadcast them.
985
+ * @param {string|null} sessionId - Session to flush (null = flush all)
986
+ * @returns {Array<{ key, sessionId, messageId, delta, emitMonoMs }>}
987
+ */
988
+ flushSession(sessionId) {
989
+ const entries = []
990
+ if (sessionId) {
991
+ const prefix = `${sessionId}:`
992
+ for (const [key, delta] of this._deltaBuffer) {
993
+ if (key.startsWith(prefix)) {
994
+ const messageId = key.slice(prefix.length)
995
+ entries.push({ key, sessionId, messageId, delta, emitMonoMs: this._deltaEmitMono.get(key) })
996
+ this._deltaBuffer.delete(key)
997
+ this._deltaEmitMono.delete(key)
998
+ // #5555: keep residency counters in sync as keys leave the buffer.
999
+ this._deltaTotalBytes -= this._deltaKeyBytes.get(key) || 0
1000
+ this._deltaKeyBytes.delete(key)
1001
+ }
1002
+ }
1003
+ if (this._deltaTotalBytes < 0) this._deltaTotalBytes = 0
1004
+ } else {
1005
+ // Legacy mode: flush everything
1006
+ for (const [key, delta] of this._deltaBuffer) {
1007
+ entries.push({ key, sessionId: null, messageId: key, delta, emitMonoMs: this._deltaEmitMono.get(key) })
1008
+ }
1009
+ this._deltaBuffer.clear()
1010
+ this._deltaEmitMono.clear()
1011
+ this._deltaKeyBytes.clear()
1012
+ this._deltaTotalBytes = 0
1013
+ }
1014
+ // If buffer is now empty, cancel the pending timer
1015
+ if (this._deltaBuffer.size === 0 && this._deltaFlushTimer) {
1016
+ clearTimeout(this._deltaFlushTimer)
1017
+ this._deltaFlushTimer = null
1018
+ this._deltaFlushDeadline = 0
1019
+ }
1020
+ return entries
1021
+ }
1022
+
1023
+ /**
1024
+ * Internal: flush all deltas via the onFlush callback.
1025
+ */
1026
+ _flushDeltas() {
1027
+ this._deltaFlushTimer = null
1028
+ this._deltaFlushDeadline = 0
1029
+ if (this._deltaBuffer.size === 0) return
1030
+ if (this._onFlush) {
1031
+ const entries = []
1032
+ for (const [key, delta] of this._deltaBuffer) {
1033
+ const emitMonoMs = this._deltaEmitMono.get(key)
1034
+ const sepIdx = key.indexOf(':')
1035
+ if (sepIdx !== -1) {
1036
+ entries.push({ key, sessionId: key.slice(0, sepIdx), messageId: key.slice(sepIdx + 1), delta, emitMonoMs })
1037
+ } else {
1038
+ entries.push({ key, sessionId: null, messageId: key, delta, emitMonoMs })
1039
+ }
1040
+ }
1041
+ // #5313 (WP-1.3): _onFlush is a broadcast callback invoked from a
1042
+ // setTimeout. A throw here escapes the timer → uncaughtException →
1043
+ // process.exit(1), crashing the whole daemon over one bad flush.
1044
+ // Contain it: log and swallow. The buffer is cleared in the finally
1045
+ // below regardless, so a throwing flush can't wedge the delta buffer
1046
+ // and stall every subsequent stream.
1047
+ try {
1048
+ this._onFlush(entries)
1049
+ } catch (err) {
1050
+ const message = err?.message || String(err)
1051
+ log.error(`Delta flush onFlush callback threw: ${message}${err?.stack ? '\n' + err.stack : ''}`)
1052
+ } finally {
1053
+ this._deltaBuffer.clear()
1054
+ this._deltaEmitMono.clear()
1055
+ this._deltaKeyBytes.clear()
1056
+ this._deltaTotalBytes = 0
1057
+ }
1058
+ return
1059
+ }
1060
+ this._deltaBuffer.clear()
1061
+ this._deltaEmitMono.clear()
1062
+ this._deltaKeyBytes.clear()
1063
+ this._deltaTotalBytes = 0
1064
+ }
1065
+
1066
+ /**
1067
+ * Clean up timers.
1068
+ */
1069
+ destroy() {
1070
+ if (this._deltaFlushTimer) {
1071
+ clearTimeout(this._deltaFlushTimer)
1072
+ this._deltaFlushTimer = null
1073
+ }
1074
+ this._deltaFlushDeadline = 0
1075
+ this._deltaBuffer.clear()
1076
+ this._deltaEmitMono.clear()
1077
+ this._deltaKeyBytes.clear()
1078
+ this._deltaTotalBytes = 0
1079
+ }
1080
+ }
1081
+
1082
+ // Export EVENT_MAP for testing
1083
+ export { EVENT_MAP }