@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,543 @@
1
+ import { createLogger } from './logger.js'
2
+ import { getDefaultModelId, getRegistryForProvider } from './models.js'
3
+ import { settlePush } from './push.js'
4
+ import { terminalMirrorRecipient } from './handler-utils.js'
5
+
6
+ const log = createLogger('ws-forwarding')
7
+
8
+ // #5515 (epic #5514): the stream message types we stamp with a broadcast-time
9
+ // wall-clock serverTs so clients can measure token-to-render latency.
10
+ const STREAM_TS_TYPES = new Set(['stream_start', 'stream_delta', 'stream_end'])
11
+
12
+ // #5515: stamp a wall-clock (ms epoch) serverTs on a stream message at the
13
+ // moment it is handed to broadcast. Wall-clock — not the #5414 monotonic
14
+ // watchdog clock — because the field crosses machines; clients treat it as
15
+ // skew-prone and derive one-way numbers from the RTT split, not raw
16
+ // subtraction. Returns a new object so we never mutate a caller's message
17
+ // (the normalizer/flush callers build fresh literals, but this keeps the
18
+ // helper safe regardless). No-op for non-stream messages.
19
+ function withServerTs(msg) {
20
+ if (!msg || !STREAM_TS_TYPES.has(msg.type)) return msg
21
+ return { ...msg, serverTs: Date.now() }
22
+ }
23
+
24
+ // #5515 — emit→broadcast instrumentation. The provider (sdk-session) stamps the
25
+ // monotonic time it emitted a delta onto the event (`_emitMonoMs`); we compute
26
+ // the time spent inside the server (coalescing buffer + forwarding) here and
27
+ // log a throttled p50/p95 summary so the coalescing buffer can be confirmed as
28
+ // the only meaningful server-side cost. Monotonic both ends (same process), so
29
+ // this is a true elapsed duration — unlike the cross-machine serverTs field.
30
+ const _emitToBroadcastSamples = []
31
+ const EMIT_BROADCAST_RING = 200
32
+ let _lastEmitBroadcastLogMs = 0
33
+ const EMIT_BROADCAST_LOG_INTERVAL_MS = 5000
34
+
35
+ function recordEmitToBroadcast(emitMonoMs) {
36
+ if (typeof emitMonoMs !== 'number') return
37
+ const elapsed = Number(process.hrtime.bigint() / 1_000_000n) - emitMonoMs
38
+ if (!Number.isFinite(elapsed) || elapsed < 0) return
39
+ _emitToBroadcastSamples.push(elapsed)
40
+ if (_emitToBroadcastSamples.length > EMIT_BROADCAST_RING) _emitToBroadcastSamples.shift()
41
+ const now = Date.now()
42
+ if (now - _lastEmitBroadcastLogMs < EMIT_BROADCAST_LOG_INTERVAL_MS) return
43
+ _lastEmitBroadcastLogMs = now
44
+ const sorted = [..._emitToBroadcastSamples].sort((a, b) => a - b)
45
+ // Standard nearest-rank: ceil(q*n) - 1, clamped to [0, n-1]. floor(q*n)
46
+ // biases one position high and makes p95 the max for small n (#5520 review).
47
+ const p = (q) => sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))]
48
+ log.debug(`[latency] emit→broadcast n=${sorted.length} p50=${Math.round(p(0.5))}ms p95=${Math.round(p(0.95))}ms`)
49
+ }
50
+
51
+ // #5313 (WP-1.3) — wrap a forwarding listener so a throw in its body (almost
52
+ // always a broadcast to a torn-down client, or a downstream devPreview call)
53
+ // can't unwind the EventEmitter's emit() in the emitting code (session-manager /
54
+ // CliSession / devPreview) and crash the whole daemon over one bad event. Logs
55
+ // with a label for triage, then swallows. Used for the small one-liner
56
+ // forwarders; the two large normalizer-driven listeners use inline try/catch.
57
+ function safeForward(label, fn) {
58
+ return (...args) => {
59
+ try {
60
+ fn(...args)
61
+ } catch (err) {
62
+ log.error(`forwarding listener "${label}" threw: ${err?.message || err}${err?.stack ? '\n' + err.stack : ''}`)
63
+ }
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Set up event forwarding from backends to clients via EventNormalizer.
69
+ *
70
+ * @param {Object} ctx
71
+ * @param {EventNormalizer} ctx.normalizer
72
+ * @param {Object|null} ctx.sessionManager
73
+ * @param {Object|null} ctx.cliSession
74
+ * @param {Object|null} ctx.devPreview
75
+ * @param {Object|null} ctx.pushManager
76
+ * @param {Map} ctx.permissionSessionMap
77
+ * @param {Map} ctx.questionSessionMap
78
+ * @param {Function} ctx.broadcast - (message, filter?) => void
79
+ * @param {Function} ctx.broadcastToSession - (sessionId, message, filter?) => void
80
+ */
81
+ export function setupForwarding(ctx) {
82
+ const {
83
+ normalizer,
84
+ sessionManager,
85
+ cliSession,
86
+ broadcast,
87
+ broadcastToSession,
88
+ } = ctx
89
+
90
+ // Wire the normalizer's timer-based delta flush to broadcast
91
+ normalizer.onFlush = (entries) => {
92
+ for (const { sessionId, messageId, delta, emitMonoMs } of entries) {
93
+ recordEmitToBroadcast(emitMonoMs)
94
+ if (sessionId) {
95
+ broadcastToSession(sessionId, withServerTs({ type: 'stream_delta', messageId, delta }))
96
+ } else {
97
+ broadcast(withServerTs({ type: 'stream_delta', messageId, delta }))
98
+ }
99
+ }
100
+ }
101
+
102
+ if (sessionManager) {
103
+ setupSessionForwarding(normalizer, ctx)
104
+ } else if (cliSession) {
105
+ setupCliForwarding(normalizer, ctx)
106
+ }
107
+ }
108
+
109
+ /**
110
+ * #5835: the single recipient predicate for a session's live-terminal traffic
111
+ * (terminal_output bytes AND terminal_size). A custom broadcastToSession filter
112
+ * OVERRIDES the default session scoping, so this re-asserts it: deliver only to a
113
+ * client that is BOTH a viewer of the session (activeSessionId / subscribedSessionIds)
114
+ * AND opted into its terminal mirror (terminal_subscribe). Opt-in alone must not
115
+ * bypass scoping, and unsubscribing must stop the traffic. Shared so the size
116
+ * broadcast can never reach a different audience than the bytes (#5840 review S2).
117
+ */
118
+ function terminalSubscriberFilter(sessionId) {
119
+ return (client) => terminalMirrorRecipient(client, sessionId)
120
+ }
121
+
122
+ /** Multi-session forwarding via normalizer */
123
+ function setupSessionForwarding(normalizer, ctx) {
124
+ const { sessionManager, devPreview, checkpointManager, broadcast, broadcastToSession } = ctx
125
+
126
+ sessionManager.on('session_event', ({ sessionId, event, data }) => {
127
+ // #5313 (WP-1.3): this listener runs synchronously inside the
128
+ // SessionManager EventEmitter's emit(). A throw here unwinds emit() and
129
+ // escapes to the emitting code (session-manager), which can crash the
130
+ // whole daemon — taking down every other session — over one bad event.
131
+ // Contain it: wrap the body, log with the session id, and swallow so a
132
+ // single malformed event can't bring down the process.
133
+ try {
134
+ // models_updated is global — broadcast to ALL clients, not per-session.
135
+ // Look up the session's provider so clients receive the provider-scoped
136
+ // defaultModel rather than the Claude-only global. Falls back to the
137
+ // Claude default registry when the session is not found (e.g. already
138
+ // destroyed). Includes the provider name in the payload so clients can
139
+ // route the model list to the correct session type. (#2993)
140
+ if (event === 'models_updated' && data?.models) {
141
+ const sessionEntry = sessionManager.getSession(sessionId)
142
+ const providerName = sessionEntry?.provider ?? null
143
+ const registry = providerName ? getRegistryForProvider(providerName) : null
144
+ const defaultModel = registry ? registry.getDefaultModelId() : getDefaultModelId()
145
+ // When the session is not found (race with teardown) providerName is null
146
+ // but we still fall back to the Claude default registry, so advertise
147
+ // 'claude-sdk' rather than null so clients can route the model list
148
+ // consistently. (#2993)
149
+ const resolvedProvider = providerName ?? 'claude-sdk'
150
+ broadcast({ type: 'available_models', models: data.models, defaultModel, provider: resolvedProvider })
151
+ return
152
+ }
153
+
154
+ // #5665: monthly programmatic-credit meter is machine-wide — broadcast to
155
+ // ALL authenticated clients, not per-session.
156
+ if (event === 'monthly_budget') {
157
+ broadcast({ type: 'monthly_budget', ...data })
158
+ return
159
+ }
160
+
161
+ // #5835 Phase 1: claude-tui live PTY mirror (the remote-viewer / authenticity
162
+ // surface). Broadcast ONLY to clients that explicitly opted into terminal
163
+ // output for THIS session (terminal_subscribe) — not every session
164
+ // subscriber — so a Chat-tab client never pays for raw PTY bytes it isn't
165
+ // rendering. Transient: no history, no normalizer, no serverTs.
166
+ if (event === 'terminal_output') {
167
+ broadcastToSession(
168
+ sessionId,
169
+ { type: 'terminal_output', sessionId, data: typeof data?.data === 'string' ? data.data : '' },
170
+ terminalSubscriberFilter(sessionId),
171
+ )
172
+ return
173
+ }
174
+
175
+ // #5835 Phase 2: the authoritative live-PTY grid size changed (a primary
176
+ // viewer drove a resize). Tell every terminal subscriber — the SAME audience
177
+ // as terminal_output (shared terminalSubscriberFilter) — so observers can
178
+ // re-letterbox. cols/rows are already clamped by resizeTerminal.
179
+ if (event === 'terminal_resize') {
180
+ broadcastToSession(
181
+ sessionId,
182
+ { type: 'terminal_size', sessionId, cols: data?.cols, rows: data?.rows },
183
+ terminalSubscriberFilter(sessionId),
184
+ )
185
+ return
186
+ }
187
+
188
+ // Sidebar activity feed: lightweight status broadcast to ALL authenticated clients
189
+ if (event === 'stream_start') {
190
+ broadcast({ type: 'session_activity', sessionId, isBusy: true, lastCost: null })
191
+ } else if (event === 'result') {
192
+ broadcast({ type: 'session_activity', sessionId, isBusy: false, lastCost: data?.cost ?? null })
193
+ }
194
+
195
+ // Dev server preview: scan tool_result events for localhost server patterns
196
+ if (event === 'tool_result' && data?.result) {
197
+ devPreview.handleToolResult(sessionId, data.result)
198
+ }
199
+
200
+ const normCtx = {
201
+ sessionId,
202
+ mode: 'multi',
203
+ getSessionEntry: () => sessionManager.getSession(sessionId),
204
+ }
205
+ const result = normalizer.normalize(event, data, normCtx)
206
+ if (!result) return
207
+
208
+ // Handle delta buffering
209
+ if (result.buffer) {
210
+ normalizer.bufferDelta(sessionId, data.messageId, data.delta, data._emitMonoMs)
211
+ return
212
+ }
213
+
214
+ // Execute side effects before messages (flush_deltas must happen before stream_end broadcast)
215
+ executeSideEffects(result.sideEffects, sessionId, ctx)
216
+ executeRegistrations(result.registrations, sessionId, ctx)
217
+
218
+ // Broadcast messages
219
+ for (const { msg, filter } of result.messages) {
220
+ const stamped = withServerTs(msg)
221
+ if (filter) {
222
+ broadcastToSession(sessionId, stamped, filter)
223
+ } else {
224
+ broadcastToSession(sessionId, stamped)
225
+ }
226
+ }
227
+ } catch (err) {
228
+ // #5313 (WP-1.3): see the try at the top of this listener.
229
+ const message = err?.message || String(err)
230
+ log.error(`session_event forwarding threw for session ${sessionId} (event=${event}): ${message}${err?.stack ? '\n' + err.stack : ''}`)
231
+ }
232
+ })
233
+
234
+ // Session metadata updates (e.g. auto-labeling) — broadcast to ALL clients
235
+ // #5313 (WP-1.3): safeForward — a broadcast throw must not unwind emit().
236
+ sessionManager.on('session_updated', safeForward('session_updated', ({ sessionId, name }) => {
237
+ broadcast({ type: 'session_updated', sessionId, name })
238
+ }))
239
+
240
+ // Restore failures — surface to clients so the UI can show a "needs
241
+ // attention" card for sessions whose env vars / provider setup is broken
242
+ // (#2954). History stays on disk; client shows a retry affordance.
243
+ sessionManager.on('session_restore_failed', safeForward('session_restore_failed', (payload) => {
244
+ broadcast({ type: 'session_restore_failed', ...payload })
245
+ }))
246
+
247
+ // Persist failures — surface to clients so the user knows a session-list
248
+ // mutation (create/rename/destroy) did NOT make it to disk and will be lost on
249
+ // restart, instead of silently believing it was saved (#5714 / #5701). The
250
+ // write is atomic so on-disk state isn't corrupted; this is purely the
251
+ // "your change wasn't saved" signal.
252
+ sessionManager.on('session_persist_failed', safeForward('session_persist_failed', (payload) => {
253
+ broadcast({ type: 'session_persist_failed', ...payload })
254
+ }))
255
+
256
+ // #5731 (T6): a FRESH session whose async start() rejected (claude-tui's PTY
257
+ // failing to spawn) is fully destroyed. Without this the client — which just
258
+ // got `session_created` + a success ack — would see only `session_destroyed`
259
+ // and the session would vanish with no reason. Surface it as a per-session
260
+ // error toast, reusing the existing `session_error` message (both clients
261
+ // route it to their error toast) rather than minting a new wire type. The
262
+ // SessionManager emits this synchronously BEFORE `session_destroyed`, so the
263
+ // session is still mapped here and `broadcastToSession` reaches its
264
+ // subscribers. recoverable:false — there's no retry affordance for a fresh
265
+ // session (unlike a failed restore); the user must re-create it.
266
+ sessionManager.on('session_create_failed', safeForward('session_create_failed', ({ sessionId, errorCode, errorMessage, provider }) => {
267
+ if (!sessionId) return
268
+ broadcastToSession(sessionId, {
269
+ type: 'session_error',
270
+ code: errorCode || 'SESSION_START_FAILED',
271
+ sessionId,
272
+ recoverable: false,
273
+ message: errorMessage
274
+ ? `The session failed to start: ${errorMessage}`
275
+ : `The session failed to start${provider ? ` (${provider})` : ''}.`,
276
+ })
277
+ }))
278
+
279
+ // #5731 (T3): a checkpoint create/delete that couldn't be flushed to disk will
280
+ // be lost (or reappear) on restart. Surface it as a per-session error banner —
281
+ // reuse the existing `session_error` message (both clients route it to their
282
+ // error toast) rather than minting a new wire type. checkpointManager is
283
+ // optional on ctx for legacy single-session callers that don't wire it.
284
+ if (checkpointManager && typeof checkpointManager.on === 'function') {
285
+ checkpointManager.on('checkpoint_persist_failed', safeForward('checkpoint_persist_failed', ({ sessionId, operation }) => {
286
+ if (!sessionId) return
287
+ const what = operation === 'delete' ? 'checkpoint deletion' : 'checkpoint'
288
+ broadcastToSession(sessionId, {
289
+ type: 'session_error',
290
+ code: 'CHECKPOINT_PERSIST_FAILED',
291
+ sessionId,
292
+ recoverable: true,
293
+ message: `Couldn't save your ${what} — it may be lost on restart. Check the daemon's disk space and write permissions.`,
294
+ })
295
+ }))
296
+ }
297
+
298
+ // Dev server preview: broadcast tunnel start/stop to clients
299
+ devPreview.on('dev_preview_started', safeForward('dev_preview_started', ({ sessionId, port, url }) => {
300
+ broadcastToSession(sessionId, { type: 'dev_preview', port, url })
301
+ }))
302
+ devPreview.on('dev_preview_stopped', safeForward('dev_preview_stopped', ({ sessionId, port }) => {
303
+ broadcastToSession(sessionId, { type: 'dev_preview_stopped', port })
304
+ }))
305
+ // #5731: a tunnel.stop() that failed during closePreview — the public tunnel
306
+ // (and the exposed local port) may still be live. Surface it as a per-session
307
+ // error banner (reusing `session_error`, like the checkpoint/persist failure
308
+ // paths) so the user can verify / kill cloudflared instead of assuming the
309
+ // port is closed. recoverable:true — informational; the slot is already freed.
310
+ devPreview.on('dev_preview_stop_failed', safeForward('dev_preview_stop_failed', ({ sessionId, port, error }) => {
311
+ if (!sessionId) return
312
+ broadcastToSession(sessionId, {
313
+ type: 'session_error',
314
+ code: 'DEV_PREVIEW_STOP_FAILED',
315
+ sessionId,
316
+ recoverable: true,
317
+ message: `Couldn't fully stop the preview tunnel on port ${port} — it may still be exposed. Check the daemon logs and kill cloudflared manually if needed.${error ? ` (${error})` : ''}`,
318
+ })
319
+ }))
320
+
321
+ // Dev server preview: cleanup on session destroy
322
+ sessionManager.on('session_destroyed', safeForward('session_destroyed', ({ sessionId }) => {
323
+ devPreview.closeSession(sessionId)
324
+ }))
325
+
326
+ }
327
+
328
+ /** Legacy single CLI session forwarding via normalizer */
329
+ function setupCliForwarding(normalizer, ctx) {
330
+ const { cliSession, devPreview, broadcast } = ctx
331
+
332
+ // #3240: `skill_changed` is forwarded so legacy single-CLI users get the
333
+ // same trust-mismatch broadcast as multi-session mode. The normaliser
334
+ // emits `sessionId: null` here — see the `normCtx` built in the
335
+ // forwarding loop below — which the schema explicitly allows for this
336
+ // path; #3205's dashboard prompt treats null as "applies to whatever
337
+ // CLI is connected".
338
+ // #4756: `stopped` mirrors the multi-session forwarding list (see
339
+ // session-manager.js `_wireSessionEvents` builtinTransient) so the legacy
340
+ // single-CLI path also surfaces the user-initiated Stop confirmation via
341
+ // the normalizer's `session_stopped` wire message.
342
+ const FORWARDED_EVENTS = [
343
+ 'ready', 'stream_start', 'stream_delta', 'stream_end',
344
+ 'message', 'tool_start', 'tool_result', 'result', 'error',
345
+ 'user_question', 'agent_spawned', 'agent_completed',
346
+ 'plan_started', 'plan_ready', 'mcp_servers',
347
+ 'permission_expired', 'skill_changed', 'skill_trust_request', 'skill_trust_granted',
348
+ 'stopped',
349
+ ]
350
+ for (const event of FORWARDED_EVENTS) {
351
+ cliSession.on(event, (data) => {
352
+ // #5313 (WP-1.3): same crash shape as the multi-session listener — a
353
+ // throw here unwinds the CliSession EventEmitter's emit() and escapes
354
+ // to the emitting code, which can crash the daemon over one bad event.
355
+ // Contain it: wrap the body, log the event, and swallow.
356
+ try {
357
+ const normCtx = {
358
+ sessionId: null,
359
+ mode: 'legacy-cli',
360
+ getSessionEntry: () => ({
361
+ session: cliSession,
362
+ }),
363
+ }
364
+ const result = normalizer.normalize(event, data, normCtx)
365
+ if (!result) return
366
+
367
+ if (result.buffer) {
368
+ normalizer.bufferDelta(null, data.messageId, data.delta, data._emitMonoMs)
369
+ return
370
+ }
371
+
372
+ executeSideEffects(result.sideEffects, null, ctx)
373
+ executeRegistrations(result.registrations, null, ctx)
374
+
375
+ for (const { msg, filter } of result.messages) {
376
+ const stamped = withServerTs(msg)
377
+ if (filter) {
378
+ broadcast(stamped, filter)
379
+ } else {
380
+ broadcast(stamped)
381
+ }
382
+ }
383
+ } catch (err) {
384
+ const message = err?.message || String(err)
385
+ log.error(`legacy-cli forwarding threw (event=${event}): ${message}${err?.stack ? '\n' + err.stack : ''}`)
386
+ }
387
+ })
388
+ }
389
+
390
+ // Dev server preview: scan tool_result events for localhost server patterns (legacy CLI)
391
+ // #5313 (WP-1.3): safeForward — a throw here must not unwind CliSession's emit().
392
+ cliSession.on('tool_result', safeForward('cli:tool_result', (data) => {
393
+ if (data?.result) {
394
+ devPreview.handleToolResult('__legacy__', data.result)
395
+ }
396
+ }))
397
+ devPreview.on('dev_preview_started', safeForward('cli:dev_preview_started', ({ sessionId, port, url }) => {
398
+ if (sessionId === '__legacy__') {
399
+ broadcast({ type: 'dev_preview', port, url })
400
+ }
401
+ }))
402
+ devPreview.on('dev_preview_stopped', safeForward('cli:dev_preview_stopped', ({ sessionId, port }) => {
403
+ if (sessionId === '__legacy__') {
404
+ broadcast({ type: 'dev_preview_stopped', port })
405
+ }
406
+ }))
407
+ // #5731: same don't-claim-a-clean-stop surfacing on the legacy CLI path — a
408
+ // failed tunnel.stop() must not be silently dropped here either. Global
409
+ // broadcast (CLI is single-session) so the lone client learns the port may
410
+ // still be exposed.
411
+ devPreview.on('dev_preview_stop_failed', safeForward('cli:dev_preview_stop_failed', ({ sessionId, port, error }) => {
412
+ if (sessionId === '__legacy__') {
413
+ broadcast({
414
+ type: 'session_error',
415
+ code: 'DEV_PREVIEW_STOP_FAILED',
416
+ recoverable: true,
417
+ message: `Couldn't fully stop the preview tunnel on port ${port} — it may still be exposed. Check the daemon logs and kill cloudflared manually if needed.${error ? ` (${error})` : ''}`,
418
+ })
419
+ }
420
+ }))
421
+
422
+ // models_updated bypasses normalizer — global broadcast.
423
+ // CLI mode is always a Claude session; include provider so clients can
424
+ // route the model list consistently with the multi-session path. (#2993)
425
+ cliSession.on('models_updated', safeForward('cli:models_updated', (data) => {
426
+ if (data?.models) {
427
+ broadcast({ type: 'available_models', models: data.models, defaultModel: getDefaultModelId(), provider: 'claude-cli' })
428
+ }
429
+ }))
430
+ }
431
+
432
+ /** Execute side effect descriptors returned by the normalizer */
433
+ function executeSideEffects(sideEffects, sessionId, ctx) {
434
+ if (!sideEffects) return
435
+ const { normalizer, sessionManager, pushManager, broadcast, broadcastToSession, broadcastSessionList } = ctx
436
+ for (const effect of sideEffects) {
437
+ switch (effect.type) {
438
+ case 'session_list':
439
+ if (sessionManager) {
440
+ if (broadcastSessionList) {
441
+ broadcastSessionList()
442
+ } else {
443
+ broadcast({ type: 'session_list', sessions: sessionManager.listSessions() })
444
+ }
445
+ }
446
+ break
447
+ case 'refresh_context':
448
+ if (sessionManager) {
449
+ sessionManager.getSessionContext(effect.sessionId || sessionId).then((ctxData) => {
450
+ if (ctxData) broadcastToSession(effect.sessionId || sessionId, { type: 'session_context', ...ctxData })
451
+ }).catch((err) => {
452
+ log.warn(`Failed to refresh session context for ${effect.sessionId || sessionId}: ${err.message} (non-critical, stale context)`)
453
+ })
454
+ }
455
+ break
456
+ case 'push':
457
+ if (pushManager) {
458
+ // #5702 (8d): settle the fire-and-forget send so a failed delivery /
459
+ // dispatch error is logged (named), not silently dropped.
460
+ settlePush(
461
+ pushManager.send(effect.category, effect.title, effect.body, effect.data, effect.channelId),
462
+ `effect: ${effect.category}`,
463
+ log,
464
+ )
465
+ }
466
+ break
467
+ case 'flush_deltas': {
468
+ const sid = effect.sessionId ?? sessionId
469
+ const entries = normalizer.flushSession(sid)
470
+ for (const { sessionId: eSid, messageId, delta, emitMonoMs } of entries) {
471
+ recordEmitToBroadcast(emitMonoMs)
472
+ if (eSid) {
473
+ broadcastToSession(eSid, withServerTs({ type: 'stream_delta', messageId, delta }))
474
+ } else {
475
+ broadcast(withServerTs({ type: 'stream_delta', messageId, delta }))
476
+ }
477
+ }
478
+ break
479
+ }
480
+ case 'log':
481
+ log.info(effect.message)
482
+ break
483
+ }
484
+ }
485
+ }
486
+
487
+ /** Execute registration descriptors returned by the normalizer */
488
+ function executeRegistrations(registrations, sessionId, ctx) {
489
+ if (!registrations) return
490
+ const { permissionSessionMap, questionSessionMap, registerQuestionRoute, registerPermissionRoute } = ctx
491
+ for (const reg of registrations) {
492
+ // #3736: registrations support an explicit action ('set' | 'delete'),
493
+ // defaulting to 'set' for backwards compatibility. The delete action is
494
+ // emitted by EVENT_MAP.permission_resolved so the routing map is pruned
495
+ // on every resolution path (including internal auto-resolves: timeout,
496
+ // aborted, auto_mode, cleared) where no user response ever arrives to
497
+ // trigger the message-handler-level delete. Without this the map grows
498
+ // unbounded until session destroy.
499
+ const action = reg.action ?? 'set'
500
+ if (reg.map === 'permission') {
501
+ if (action === 'delete') {
502
+ permissionSessionMap.delete(reg.key)
503
+ } else {
504
+ const mappedSessionId = reg.value ?? sessionId
505
+ // #4798: prefer the WsServer-provided helper so dispatch also auto-
506
+ // subscribes eligible clients to the permission's session — keeps the
507
+ // settings-handler's subscription guard symmetric with
508
+ // _broadcastToSession's recipient filter. Falls back to a bare Map.set
509
+ // when ctx doesn't carry the helper (legacy unit tests that wire
510
+ // setupForwarding directly without a WsServer).
511
+ if (typeof registerPermissionRoute === 'function') {
512
+ registerPermissionRoute(reg.key, mappedSessionId)
513
+ } else {
514
+ permissionSessionMap.set(reg.key, mappedSessionId)
515
+ }
516
+ // Diagnostic correlation log for #2832 — paired with
517
+ // [session-binding-resend] and [session-binding-reject]. Allows
518
+ // grepping the origin session for any requestId that later gets
519
+ // rejected as SESSION_TOKEN_MISMATCH. Gated at debug level (#2854)
520
+ // to avoid spamming prod logs for sessions with heavy permission
521
+ // traffic (auto/accept-all). Enable with `LOG_LEVEL=debug`.
522
+ log.debug(`[session-binding-create] permission ${reg.key} created (sessionId=${mappedSessionId})`)
523
+ }
524
+ } else if (reg.map === 'question') {
525
+ if (action === 'delete') {
526
+ questionSessionMap.delete(reg.key)
527
+ } else {
528
+ const mappedSessionId = reg.value ?? sessionId
529
+ // #4788 Wave 2: prefer the WsServer-provided helper so dispatch also
530
+ // auto-subscribes eligible clients to the question's session — keeps
531
+ // the input-handler's subscription guard symmetric with
532
+ // _broadcastToSession's recipient filter. Falls back to a bare Map.set
533
+ // when ctx doesn't carry the helper (legacy unit tests that wire
534
+ // setupForwarding directly without a WsServer).
535
+ if (typeof registerQuestionRoute === 'function') {
536
+ registerQuestionRoute(reg.key, mappedSessionId)
537
+ } else {
538
+ questionSessionMap.set(reg.key, mappedSessionId)
539
+ }
540
+ }
541
+ }
542
+ }
543
+ }