@chroxy/server 0.10.0 → 0.11.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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -1,7 +1,7 @@
1
1
  import { performance } from 'node:perf_hooks'
2
2
  import { toShortModelId } from './models.js'
3
3
  import { createLogger } from './logger.js'
4
- import { buildPermissionRequestMessage } from '@chroxy/protocol'
4
+ import { buildPermissionRequestMessage, MAX_SANE_DURATION_MS } from '@chroxy/protocol'
5
5
 
6
6
  const log = createLogger('event-normalizer')
7
7
 
@@ -35,6 +35,118 @@ const MAX_DELTA_TOTAL_BYTES = 2 * 1024 * 1024 // 2 MB across all streams
35
35
  const DEFLATE_FLUSH_INTERVAL_MS = 25 // any deflate subscriber, multi-client
36
36
  const DEFLATE_SINGLE_CLIENT_FLUSH_INTERVAL_MS = 16 // any deflate subscriber, single client
37
37
 
38
+ /**
39
+ * #6941 review (Copilot) — coerce+bound a footer-stat numeric field
40
+ * (`thinkingDurationMs` / `thinkingTokens`) before forwarding it onto the
41
+ * wire. Mirrors the protocol schema's
42
+ * `z.number().int().nonnegative().finite()[.max(ceiling)]`: floors a stray
43
+ * fractional value (matches store-core's `parseFiniteNonNegIntField`, which
44
+ * re-guards the same field client-side) and OMITS — never clamps — when the
45
+ * value is negative, non-finite, or exceeds an optional ceiling. A clock
46
+ * jump / suspend producing a bogus multi-day duration should vanish from the
47
+ * footer, not render as an incorrect exact-ceiling number.
48
+ *
49
+ * @param {*} value - candidate value straight off the session event.
50
+ * @param {{ max?: number }} [opts] - optional upper bound (inclusive).
51
+ * @returns {number|undefined}
52
+ */
53
+ function boundedNonNegInt(value, { max } = {}) {
54
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return undefined
55
+ const floored = Math.floor(value)
56
+ if (typeof max === 'number' && floored > max) return undefined
57
+ return floored
58
+ }
59
+
60
+ /**
61
+ * #6973 (agent-review on #6970) — coerce+bound `compactMetadata`'s
62
+ * `preTokens`/`postTokens`/`durationMs` sub-fields before forwarding onto
63
+ * the wire, same defense-in-depth as `boundedNonNegInt` above (the #6941
64
+ * thinkingDurationMs pattern) applied field-by-field. Unlike
65
+ * thinkingDurationMs/thinkingTokens (fully optional on the wire), these
66
+ * three sub-fields are `.nullable()` — not `.optional()` — on
67
+ * `ServerCompactMetadataSchema`, so the shape always carries all three keys;
68
+ * an out-of-range/malformed value is coerced to `null` here rather than
69
+ * dropped, matching `parseCompactBoundaryMeta`'s own "null for
70
+ * missing/malformed" convention (claude-stream-parser.js) so a client always
71
+ * gets the stable shape to pattern-match against. `durationMs` is
72
+ * additionally bounded by `MAX_SANE_DURATION_MS` (the same clock-jump guard
73
+ * as `thinkingDurationMs`); `preTokens`/`postTokens` have no documented
74
+ * ceiling — legitimate context windows run into the millions of tokens — so
75
+ * only non-negative-integer coercion applies.
76
+ *
77
+ * @param {{trigger?: *, preTokens?: *, postTokens?: *, durationMs?: *}} meta
78
+ * @returns {{trigger: 'manual'|'auto', preTokens: number|null, postTokens: number|null, durationMs: number|null}}
79
+ */
80
+ function boundedCompactMetadata(meta) {
81
+ const boundedOrNull = (value, opts) => {
82
+ const bounded = boundedNonNegInt(value, opts)
83
+ return bounded === undefined ? null : bounded
84
+ }
85
+ return {
86
+ trigger: meta.trigger === 'manual' ? 'manual' : 'auto',
87
+ preTokens: boundedOrNull(meta.preTokens),
88
+ postTokens: boundedOrNull(meta.postTokens),
89
+ durationMs: boundedOrNull(meta.durationMs, { max: MAX_SANE_DURATION_MS }),
90
+ }
91
+ }
92
+
93
+ // #6845: wire-boundary caps for the MCP-prompt expansion marker. server/prompt
94
+ // mirror ServerMcpPromptExpansionSchema's 256-char names; `text` mirrors its
95
+ // 8192 ceiling. byok-session already caps the display copy (4000 + a
96
+ // truncation marker); this is the defense-in-depth re-bound at the serialization
97
+ // choke point (same posture as boundedCompactMetadata) so a wire-bypassing or
98
+ // malformed producer can't push an unbounded payload onto clients.
99
+ const MCP_PROMPT_EXPANSION_NAME_CAP = 256
100
+ const MCP_PROMPT_EXPANSION_TEXT_CAP = 8192
101
+
102
+ // Thread-2/honesty-nit fix (post-#6845 review): the suffix now says the FULL
103
+ // text still reached the model, matching byok-session.js's display-cap suffix
104
+ // and store-core's client-side re-bound suffix — a reader who only sees the
105
+ // truncated marker (mobile, System tab) must not conclude the model saw less
106
+ // than it did. Sliced-length arithmetic below subtracts THIS string's actual
107
+ // length rather than a hardcoded magic number, so the total (slice + suffix)
108
+ // never exceeds the cap even if the wording changes again later.
109
+ const MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX = '\n…(truncated for display; full text sent to the model)'
110
+
111
+ /**
112
+ * #6845 — coerce+bound the `mcpPromptExpansion` marker fields before forwarding
113
+ * onto the wire. Requires a string `text` (the marker is meaningless without
114
+ * the injected content) — returns `null` when `text` is not a string so the
115
+ * caller skips attaching `subtype`/`mcpPromptExpansion` entirely rather than
116
+ * forwarding a marker with blank/coerced content. This mirrors store-core's
117
+ * `parseMcpPromptExpansion` reject-on-non-string-text contract (post-#6845
118
+ * review thread 1 — the two layers previously disagreed: this function used to
119
+ * silently stringify a non-string `text`, while the client rejected the whole
120
+ * marker; they now agree on reject).
121
+ *
122
+ * `server`/`prompt` are cosmetic provenance labels (not content), so they stay
123
+ * on the more forgiving "coerce" side: a non-string value becomes `''` rather
124
+ * than failing the whole marker, then caps at 256. `text` caps at 8192,
125
+ * appending {@link MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX} when it overflows so
126
+ * the client never silently drops content; `truncated` stays true if EITHER
127
+ * the producer flagged it or this re-bound truncated.
128
+ *
129
+ * @param {{server?: *, prompt?: *, text?: *, truncated?: *}} meta
130
+ * @returns {{server: string, prompt: string, text: string, truncated: boolean} | null}
131
+ */
132
+ function boundedMcpPromptExpansion(meta) {
133
+ if (typeof meta?.text !== 'string') return null
134
+ const asString = (v) => (typeof v === 'string' ? v : '')
135
+ const cap = (s, n) => (s.length > n ? s.slice(0, n) : s)
136
+ const rawText = meta.text
137
+ const overflow = rawText.length > MCP_PROMPT_EXPANSION_TEXT_CAP
138
+ const sliceLen = Math.max(0, MCP_PROMPT_EXPANSION_TEXT_CAP - MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX.length)
139
+ const text = overflow
140
+ ? `${cap(rawText, sliceLen)}${MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX}`
141
+ : rawText
142
+ return {
143
+ server: cap(asString(meta?.server), MCP_PROMPT_EXPANSION_NAME_CAP),
144
+ prompt: cap(asString(meta?.prompt), MCP_PROMPT_EXPANSION_NAME_CAP),
145
+ text,
146
+ truncated: meta?.truncated === true || overflow,
147
+ }
148
+ }
149
+
38
150
  /**
39
151
  * Declarative event-to-WS-message mapping.
40
152
  *
@@ -140,6 +252,16 @@ Object.assign(EVENT_MAP, {
140
252
  },
141
253
 
142
254
  stream_start: (data, ctx) => {
255
+ // #6756 — a thinking stream_start opens a reasoning bubble on a distinct id.
256
+ // Tag the wire message so the client routes it to a `type: 'thinking'`
257
+ // bubble, and skip the agent_busy / session_list churn: the turn's busy
258
+ // state is already owned by the response stream / the client's 'pending'
259
+ // sentinel, so a per-thinking-block session_list refresh would be noise.
260
+ if (data.thinking) {
261
+ return {
262
+ messages: [{ msg: { type: 'stream_start', messageId: data.messageId, thinking: true } }],
263
+ }
264
+ }
143
265
  const messages = [
144
266
  { msg: { type: 'stream_start', messageId: data.messageId } },
145
267
  { msg: { type: 'agent_busy' } },
@@ -154,6 +276,25 @@ Object.assign(EVENT_MAP, {
154
276
  },
155
277
 
156
278
  stream_delta: (data, _ctx) => {
279
+ // #6818 — thinking deltas ALSO coalesce now. Before this, they broadcast
280
+ // IMMEDIATELY (one WS frame per thinking_delta) because the delta buffer
281
+ // reconstructed a bare {messageId, delta} on flush and so couldn't carry the
282
+ // `thinking: true` flag — a frame/bandwidth storm on a high-budget turn
283
+ // (`high` = 32k, `max` = 128k thinking tokens streamed over the tunnel). The
284
+ // buffer now tracks the flag per key and stamps it back onto every flushed
285
+ // frame, so thinking coalesces the same way response text does. A thinking
286
+ // bubble uses a DISTINCT messageId (`<turnId>-thinking-<n>`, see #6756), so
287
+ // its deltas never share a buffer key with the response text — the two
288
+ // coalesce independently and flush as separate frames with distinct flags.
289
+ // The `thinking` flag rides the result so the caller forwards it to
290
+ // bufferDelta (parallel to how it reads messageId/delta off `data`).
291
+ if (data.thinking) {
292
+ return {
293
+ messages: [{ msg: { type: 'stream_delta', messageId: data.messageId, delta: data.delta, thinking: true } }],
294
+ buffer: true, // signal to caller to buffer this delta
295
+ thinking: true, // signal to caller to buffer it as a thinking delta
296
+ }
297
+ }
157
298
  // Delta buffering is handled externally — normalizer returns the raw delta
158
299
  // and the caller decides whether to buffer or flush.
159
300
  return {
@@ -163,6 +304,39 @@ Object.assign(EVENT_MAP, {
163
304
  },
164
305
 
165
306
  stream_end: (data, ctx) => {
307
+ // #6756/#6818 — a thinking stream_end finalises the reasoning bubble's label.
308
+ // Since #6818 thinking deltas ARE buffered (coalesced), so this MUST flush
309
+ // them first — exactly like the response-text path below — or the
310
+ // finalisation frame could overtake the still-buffered thinking deltas and
311
+ // break the "Thinking… → Thought" ordering. flush_deltas runs as a side
312
+ // effect BEFORE the messages broadcast (see ws-forwarding), so the coalesced
313
+ // thinking text is on the wire before this stream_end.
314
+ if (data.thinking) {
315
+ // #6391 footer-stat: forward the session-measured elapsed time (+ token
316
+ // count when a provider supplies one — claude SDK/BYOK do not) so the
317
+ // client renders `thought for Xs · N tokens`. Both optional and additive;
318
+ // the wire schema (ServerStreamEndSchema) validates them. #6941 review
319
+ // (Copilot): a clock jump/suspend on the measuring side could hand us a
320
+ // negative or wildly-oversized duration that would otherwise slip past a
321
+ // bare finite-check and violate the schema's
322
+ // `.int().nonnegative().max(MAX_SANE_DURATION_MS)` contract if a client
323
+ // ever validates leniently. `boundedNonNegInt` enforces that same
324
+ // ceiling here (defense-in-depth) and OMITS the field outright rather
325
+ // than clamping — the deeper monotonic-clock fix is tracked separately
326
+ // (#6943).
327
+ const msg = { type: 'stream_end', messageId: data.messageId, thinking: true }
328
+ const thinkingDurationMs = boundedNonNegInt(data.thinkingDurationMs, { max: MAX_SANE_DURATION_MS })
329
+ if (thinkingDurationMs !== undefined) msg.thinkingDurationMs = thinkingDurationMs
330
+ // thinkingTokens has no protocol ceiling (ThinkingTokensSchema is
331
+ // int().nonnegative().finite() only) — just enforce non-negative int.
332
+ const thinkingTokens = boundedNonNegInt(data.thinkingTokens)
333
+ if (thinkingTokens !== undefined) msg.thinkingTokens = thinkingTokens
334
+ return {
335
+ messages: [{ msg }],
336
+ // #6818: flush the coalesced thinking deltas before this finalisation.
337
+ sideEffects: [{ type: 'flush_deltas', sessionId: ctx.sessionId }],
338
+ }
339
+ }
166
340
  return {
167
341
  messages: [{ msg: { type: 'stream_end', messageId: data.messageId } }],
168
342
  sideEffects: [
@@ -181,6 +355,35 @@ Object.assign(EVENT_MAP, {
181
355
  options: data.options,
182
356
  timestamp: data.timestamp,
183
357
  }
358
+ // #6768: forward the structured compaction-boundary marker fields.
359
+ // Gated strictly on `messageType === 'system'` + the compact_boundary
360
+ // subtype (mirrors the `code`/`attemptedResumeId` gating pattern in the
361
+ // `error:` normalizer below) so a buggy producer can't sneak
362
+ // `compactMetadata` onto an unrelated message type. #6973: the numeric
363
+ // sub-fields are bounded (see `boundedCompactMetadata`) rather than
364
+ // forwarded raw, so a malformed/out-of-range value from the SDK/CLI
365
+ // can't reach the wire unbounded.
366
+ if (data.type === 'system' && data.subtype === 'compact_boundary' && data.compactMetadata) {
367
+ msg.subtype = data.subtype
368
+ msg.compactMetadata = boundedCompactMetadata(data.compactMetadata)
369
+ }
370
+ // #6845: forward the MCP-prompt expansion marker (the honesty surface for a
371
+ // server-controlled `/mcp__server__prompt` expansion injected as the user
372
+ // turn). Gated identically to compact_boundary — `messageType: 'system'` +
373
+ // the `mcp_prompt_expansion` subtype + a present payload — and re-bounded
374
+ // here so a malformed producer can't reach the wire unbounded. Unlike
375
+ // compact_boundary, `boundedMcpPromptExpansion` can return `null` (a
376
+ // non-string `text` — see its doc comment), in which case neither
377
+ // `subtype` nor `mcpPromptExpansion` is attached: the envelope falls back
378
+ // to a plain system message rather than claiming a structured marker it
379
+ // can't honestly populate.
380
+ if (data.type === 'system' && data.subtype === 'mcp_prompt_expansion' && data.mcpPromptExpansion) {
381
+ const bounded = boundedMcpPromptExpansion(data.mcpPromptExpansion)
382
+ if (bounded) {
383
+ msg.subtype = data.subtype
384
+ msg.mcpPromptExpansion = bounded
385
+ }
386
+ }
184
387
  return { messages: [{ msg }] }
185
388
  },
186
389
 
@@ -210,6 +413,11 @@ Object.assign(EVENT_MAP, {
210
413
  tool_result: (data) => {
211
414
  const msg = { type: 'tool_result', toolUseId: data.toolUseId, result: data.result, truncated: data.truncated }
212
415
  if (data.images?.length) msg.images = data.images
416
+ // #6712: forward the failed-tool flag onto the LIVE wire (this normalizer is
417
+ // the serialization choke point for both backends). Without it a failed
418
+ // codex mcpToolCall / orphan-sweep result would render plain live but
419
+ // error-styled after a history replay (which sends the entry raw).
420
+ if (typeof data.isError === 'boolean') msg.isError = data.isError
213
421
  return { messages: [{ msg }] }
214
422
  },
215
423
 
@@ -321,11 +529,22 @@ Object.assign(EVENT_MAP, {
321
529
  }],
322
530
  }),
323
531
 
324
- mcp_servers: (data) => ({
325
- messages: [{
326
- msg: { type: 'mcp_servers', servers: data.servers },
327
- }],
328
- }),
532
+ // #6847: stamp the canonical `ctx.sessionId` so the message routes to the
533
+ // RIGHT session on the client — without it, a client subscribed to sessions
534
+ // A+B with B active would patch A's toggle re-emit onto B (store-core's
535
+ // handleMcpServers falls back to activeSessionId when the field is absent).
536
+ // The field is OMITTED on the legacy-cli path where ctx.sessionId is null,
537
+ // matching the `stopped` builder's convention ("applies to the connected
538
+ // legacy CLI" rather than `sessionId: null`) — mcp_servers is in that path's
539
+ // FORWARDED_EVENTS list, unlike the always-multi-session siblings
540
+ // (message_queued / background_work_changed) that stamp unconditionally.
541
+ mcp_servers: (data, ctx) => {
542
+ const msg = { type: 'mcp_servers', servers: data.servers }
543
+ if (typeof ctx.sessionId === 'string' && ctx.sessionId.length > 0) {
544
+ msg.sessionId = ctx.sessionId
545
+ }
546
+ return { messages: [{ msg }] }
547
+ },
329
548
 
330
549
  // #5936 (epic #5935): outgoing-message queue mirror. The session emits these
331
550
  // when a send-while-busy follow-up enters (`message_queued`) or leaves
@@ -458,7 +677,29 @@ Object.assign(EVENT_MAP, {
458
677
 
459
678
  result: (data, ctx) => {
460
679
  const messages = [
461
- { msg: { type: 'result', cost: data.cost, duration: data.duration, usage: data.usage, sessionId: data.sessionId } },
680
+ {
681
+ msg: {
682
+ type: 'result',
683
+ cost: data.cost,
684
+ duration: data.duration,
685
+ usage: data.usage,
686
+ sessionId: data.sessionId,
687
+ // #6819: the session's authoritative outgoing-queue length, stamped
688
+ // centrally by base-session.js's emit() override (#6627/#6706) onto
689
+ // every `result` payload. Forwarding it lets store-core's
690
+ // result-boundary reconcile self-heal a stale "Queued" bubble left
691
+ // by a dropped/late message_dequeued. Only forwarded when finite —
692
+ // absent/non-finite keeps the field off the wire so older-server
693
+ // semantics (client takes the no-op reconcile path) are preserved.
694
+ ...(Number.isFinite(data.queueLength) ? { queueLength: data.queueLength } : {}),
695
+ // #6769: occupancy snapshot (claude-sdk getContextUsage() / the
696
+ // byok agent loop's final-round prompt, incl. subclasses like
697
+ // ollama whose endpoint reports usage). Only forwarded when the
698
+ // session emitted one — providers with no occupancy signal keep
699
+ // the field off the wire so clients render their honest dash state.
700
+ ...(data.contextOccupancy ? { contextOccupancy: data.contextOccupancy } : {}),
701
+ },
702
+ },
462
703
  { msg: { type: 'agent_idle' } },
463
704
  ]
464
705
  const sideEffects = [{ type: 'session_list' }]
@@ -522,7 +763,14 @@ Object.assign(EVENT_MAP, {
522
763
  category: 'permission',
523
764
  title: 'Permission needed',
524
765
  body: `Claude wants to use: ${data.tool}`,
525
- data: { requestId: data.requestId, tool: data.tool },
766
+ // #6792: carry the triggering sessionId in the push data (data-only,
767
+ // doesn't change the visible notification) so a notification tap can
768
+ // route straight to this session — matches the registration above and
769
+ // the sessionId already carried by the HTTP hook path's push
770
+ // (ws-permissions.js) and the activity_* pushes. #6847 "omit not null":
771
+ // include the key ONLY when truthy so the wire shape matches the HTTP
772
+ // hook path (ws-permissions.js), which omits it for the null-ctx path.
773
+ data: { requestId: data.requestId, tool: data.tool, ...(ctx.sessionId ? { sessionId: ctx.sessionId } : {}) },
526
774
  channelId: 'permission',
527
775
  }],
528
776
  }),
@@ -532,7 +780,15 @@ Object.assign(EVENT_MAP, {
532
780
  msg: {
533
781
  type: 'permission_expired',
534
782
  requestId: data.requestId,
535
- sessionId: ctx.sessionId,
783
+ // #7096: OMIT when absent — do not stamp null. The wire field is
784
+ // `z.string().optional()`, so `undefined` is legal and `null` is not, and the
785
+ // legacy-cli forwarder (ws-forwarding.js) normalises with `sessionId: null`
786
+ // while `permission_expired` IS in its FORWARDED_EVENTS. This mirrors the
787
+ // guarded stamp `mcp_servers` already uses 240 lines above; the unguarded form
788
+ // here was the odd one out among the frames that path can carry.
789
+ ...(typeof ctx.sessionId === 'string' && ctx.sessionId.length > 0
790
+ ? { sessionId: ctx.sessionId }
791
+ : {}),
536
792
  message: data.message,
537
793
  },
538
794
  }],
@@ -789,6 +1045,25 @@ export class EventNormalizer {
789
1045
  // oldest token in a flush spent inside the server (coalescing + forwarding)
790
1046
  // — a true monotonic duration, same process both ends.
791
1047
  this._deltaEmitMono = new Map()
1048
+ // #6818: key -> whether this buffer key holds THINKING deltas (reasoning
1049
+ // content) rather than response text. A thinking stream uses a DISTINCT
1050
+ // messageId (`<turnId>-thinking-<n>`, see #6756), so it never shares a key
1051
+ // with the response text — this map carries the `thinking: true` flag
1052
+ // alongside the coalesced text so each flushed entry can be reconstructed as
1053
+ // a thinking stream_delta instead of a bare response delta. Pruned in every
1054
+ // flush/clear path in lockstep with _deltaBuffer.
1055
+ // #6962: response keys are recorded too, as `false`, so bufferDelta can tell
1056
+ // "never seen" (undefined) apart from "seen as response" and DETECT a
1057
+ // same-key flag conflict. Every flush site reads `=== true`, so a stored
1058
+ // `false` is indistinguishable from an absent key on the wire — response
1059
+ // entries stay byte-identical to pre-#6818.
1060
+ this._deltaThinking = new Map()
1061
+ // #6962: one-shot latch for the key-collision WARN. A provider violating the
1062
+ // distinct-messageId invariant would trip the guard on EVERY delta, so the
1063
+ // WARN is deduped to once per normalizer (one per daemon in production)
1064
+ // rather than tracked per key — a per-key Set would grow unbounded over a
1065
+ // long-lived daemon for no extra signal.
1066
+ this._warnedThinkingKeyCollision = false
792
1067
  this._deltaFlushTimer = null
793
1068
  // #5516: monotonic deadline (performance.now ms) the pending flush timer is
794
1069
  // scheduled to fire at. Lets a later single-client buffer SHORTEN an
@@ -849,7 +1124,9 @@ export class EventNormalizer {
849
1124
 
850
1125
  /**
851
1126
  * Set the flush callback. Called with buffered deltas when the timer fires.
852
- * @param {Function} cb - (entries: Array<{ key, sessionId, messageId, delta }>) => void
1127
+ * @param {Function} cb - (entries: Array<{ key, sessionId, messageId, delta, emitMonoMs, thinking? }>) => void
1128
+ * `thinking` is present (=== true) only on entries that hold reasoning
1129
+ * content (#6818) so the caller stamps `thinking: true` back onto the wire.
853
1130
  */
854
1131
  set onFlush(cb) {
855
1132
  this._onFlush = cb
@@ -877,9 +1154,46 @@ export class EventNormalizer {
877
1154
  * @param {number} [emitMonoMs] - #5515: monotonic ms the provider emitted this
878
1155
  * delta. First-write-wins per flush window so the flushed entry reports how
879
1156
  * long the OLDEST coalesced token waited inside the server.
1157
+ * @param {boolean} [thinking] - #6818: true when this is a reasoning
1158
+ * (extended-thinking) delta. Recorded per key so the flushed entry carries
1159
+ * the `thinking` flag and the caller reconstructs a thinking stream_delta.
1160
+ * Thinking uses a distinct messageId (#6756), so the flag is constant per
1161
+ * key. #6962: that constancy is now ENFORCED here rather than assumed — a
1162
+ * same-key flag conflict WARNs and splits the frame (see below).
880
1163
  */
881
- bufferDelta(sessionId, messageId, delta, emitMonoMs) {
1164
+ bufferDelta(sessionId, messageId, delta, emitMonoMs, thinking) {
882
1165
  const key = sessionId ? `${sessionId}:${messageId}` : messageId
1166
+ // #6962: enforce the distinct-messageId invariant #6818 rests on. Thinking
1167
+ // deltas and response text of the same turn must never share a buffer key —
1168
+ // every provider today builds the thinking messageId as
1169
+ // `<turnId>-thinking-<n>` (#6756), but that is an unenforced CROSS-FILE
1170
+ // convention, exactly the shape of bug the BaseSession opt-forwarding trap
1171
+ // (#4797/#5367) turned out to be. A future provider reusing the bare
1172
+ // response messageId for a thinking delta would otherwise concatenate
1173
+ // reasoning into the answer and ship it under one (necessarily wrong) flag,
1174
+ // silently. So: detect the conflict BEFORE touching any buffer state, WARN
1175
+ // once, and CONTAIN it by force-flushing what is already buffered under its
1176
+ // ORIGINAL flag. The conflicting delta then re-buffers fresh behind it with
1177
+ // its own flag — same order-preserving mechanism the #5555 residency caps
1178
+ // use — so no frame ever mixes reasoning and response text. We warn rather
1179
+ // than throw because bufferDelta runs synchronously under the provider's
1180
+ // event emit; a throw here escapes into that emit and can take the daemon
1181
+ // down over one malformed stream (same reasoning as the onFlush containment
1182
+ // in _flushDeltas).
1183
+ const isThinking = thinking === true
1184
+ const priorThinking = this._deltaThinking.get(key)
1185
+ if (priorThinking !== undefined && priorThinking !== isThinking) {
1186
+ if (!this._warnedThinkingKeyCollision) {
1187
+ this._warnedThinkingKeyCollision = true
1188
+ log.warn(
1189
+ `Delta buffer invariant violation (#6962): key '${key}' received a thinking=${isThinking} delta ` +
1190
+ `after thinking=${priorThinking}. Thinking and response deltas of one turn MUST use distinct ` +
1191
+ `messageIds (\`<turnId>-thinking-<n>\`, #6756). Splitting the frame so the coalesced text is not ` +
1192
+ `corrupted; fix the provider emitting this messageId. Further collisions are not logged.`
1193
+ )
1194
+ }
1195
+ this._forceFlushKey(key)
1196
+ }
883
1197
  // #5555: coerce a non-string delta to its string form ONCE and use that for
884
1198
  // both the buffer concat AND the byte count. A bare `existing + delta` would
885
1199
  // string-coerce a non-string into the buffer (real residency) while a
@@ -893,6 +1207,14 @@ export class EventNormalizer {
893
1207
  if (typeof emitMonoMs === 'number' && !this._deltaEmitMono.has(key)) {
894
1208
  this._deltaEmitMono.set(key, emitMonoMs)
895
1209
  }
1210
+ // #6818: record the thinking flag once per key (constant per key — thinking
1211
+ // uses a distinct messageId). #6962: response keys are recorded as `false`
1212
+ // instead of left absent so the conflict check above can distinguish them
1213
+ // from an unseen key; every flush site tests `=== true`, so a stored `false`
1214
+ // still produces an entry byte-identical to pre-#6818.
1215
+ if (!this._deltaThinking.has(key)) {
1216
+ this._deltaThinking.set(key, isThinking)
1217
+ }
896
1218
  // #5555: maintain byte-size counters incrementally (UTF-8) — no
897
1219
  // re-serialization on the hot path. `text` is the only new content, so its
898
1220
  // byte length is the per-call growth for both the key total and the global
@@ -958,8 +1280,10 @@ export class EventNormalizer {
958
1280
  if (!this._deltaBuffer.has(key)) return
959
1281
  const delta = this._deltaBuffer.get(key)
960
1282
  const emitMonoMs = this._deltaEmitMono.get(key)
1283
+ const thinking = this._deltaThinking.get(key) === true
961
1284
  this._deltaBuffer.delete(key)
962
1285
  this._deltaEmitMono.delete(key)
1286
+ this._deltaThinking.delete(key)
963
1287
  this._deltaTotalBytes -= this._deltaKeyBytes.get(key) || 0
964
1288
  this._deltaKeyBytes.delete(key)
965
1289
  if (this._deltaTotalBytes < 0) this._deltaTotalBytes = 0
@@ -968,6 +1292,7 @@ export class EventNormalizer {
968
1292
  const entry = sepIdx !== -1
969
1293
  ? { key, sessionId: key.slice(0, sepIdx), messageId: key.slice(sepIdx + 1), delta, emitMonoMs }
970
1294
  : { key, sessionId: null, messageId: key, delta, emitMonoMs }
1295
+ if (thinking) entry.thinking = true
971
1296
  // Mirror _flushDeltas' containment: a throwing broadcast must not escape
972
1297
  // the buffer hot path (which runs under the provider's event emit).
973
1298
  try {
@@ -983,7 +1308,8 @@ export class EventNormalizer {
983
1308
  * Flush all buffered deltas for a specific session (called before stream_end).
984
1309
  * Returns the flushed entries so the caller can broadcast them.
985
1310
  * @param {string|null} sessionId - Session to flush (null = flush all)
986
- * @returns {Array<{ key, sessionId, messageId, delta, emitMonoMs }>}
1311
+ * @returns {Array<{ key, sessionId, messageId, delta, emitMonoMs, thinking? }>}
1312
+ * `thinking` is present (=== true) only on reasoning entries (#6818).
987
1313
  */
988
1314
  flushSession(sessionId) {
989
1315
  const entries = []
@@ -992,9 +1318,12 @@ export class EventNormalizer {
992
1318
  for (const [key, delta] of this._deltaBuffer) {
993
1319
  if (key.startsWith(prefix)) {
994
1320
  const messageId = key.slice(prefix.length)
995
- entries.push({ key, sessionId, messageId, delta, emitMonoMs: this._deltaEmitMono.get(key) })
1321
+ const entry = { key, sessionId, messageId, delta, emitMonoMs: this._deltaEmitMono.get(key) }
1322
+ if (this._deltaThinking.get(key) === true) entry.thinking = true
1323
+ entries.push(entry)
996
1324
  this._deltaBuffer.delete(key)
997
1325
  this._deltaEmitMono.delete(key)
1326
+ this._deltaThinking.delete(key)
998
1327
  // #5555: keep residency counters in sync as keys leave the buffer.
999
1328
  this._deltaTotalBytes -= this._deltaKeyBytes.get(key) || 0
1000
1329
  this._deltaKeyBytes.delete(key)
@@ -1004,10 +1333,13 @@ export class EventNormalizer {
1004
1333
  } else {
1005
1334
  // Legacy mode: flush everything
1006
1335
  for (const [key, delta] of this._deltaBuffer) {
1007
- entries.push({ key, sessionId: null, messageId: key, delta, emitMonoMs: this._deltaEmitMono.get(key) })
1336
+ const entry = { key, sessionId: null, messageId: key, delta, emitMonoMs: this._deltaEmitMono.get(key) }
1337
+ if (this._deltaThinking.get(key) === true) entry.thinking = true
1338
+ entries.push(entry)
1008
1339
  }
1009
1340
  this._deltaBuffer.clear()
1010
1341
  this._deltaEmitMono.clear()
1342
+ this._deltaThinking.clear()
1011
1343
  this._deltaKeyBytes.clear()
1012
1344
  this._deltaTotalBytes = 0
1013
1345
  }
@@ -1032,11 +1364,11 @@ export class EventNormalizer {
1032
1364
  for (const [key, delta] of this._deltaBuffer) {
1033
1365
  const emitMonoMs = this._deltaEmitMono.get(key)
1034
1366
  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
- }
1367
+ const entry = sepIdx !== -1
1368
+ ? { key, sessionId: key.slice(0, sepIdx), messageId: key.slice(sepIdx + 1), delta, emitMonoMs }
1369
+ : { key, sessionId: null, messageId: key, delta, emitMonoMs }
1370
+ if (this._deltaThinking.get(key) === true) entry.thinking = true
1371
+ entries.push(entry)
1040
1372
  }
1041
1373
  // #5313 (WP-1.3): _onFlush is a broadcast callback invoked from a
1042
1374
  // setTimeout. A throw here escapes the timer → uncaughtException →
@@ -1052,6 +1384,7 @@ export class EventNormalizer {
1052
1384
  } finally {
1053
1385
  this._deltaBuffer.clear()
1054
1386
  this._deltaEmitMono.clear()
1387
+ this._deltaThinking.clear()
1055
1388
  this._deltaKeyBytes.clear()
1056
1389
  this._deltaTotalBytes = 0
1057
1390
  }
@@ -1059,6 +1392,7 @@ export class EventNormalizer {
1059
1392
  }
1060
1393
  this._deltaBuffer.clear()
1061
1394
  this._deltaEmitMono.clear()
1395
+ this._deltaThinking.clear()
1062
1396
  this._deltaKeyBytes.clear()
1063
1397
  this._deltaTotalBytes = 0
1064
1398
  }
@@ -1074,6 +1408,7 @@ export class EventNormalizer {
1074
1408
  this._deltaFlushDeadline = 0
1075
1409
  this._deltaBuffer.clear()
1076
1410
  this._deltaEmitMono.clear()
1411
+ this._deltaThinking.clear()
1077
1412
  this._deltaKeyBytes.clear()
1078
1413
  this._deltaTotalBytes = 0
1079
1414
  }
Binary file
@@ -1,5 +1,6 @@
1
1
  import { JsonlSubprocessSession } from './jsonl-subprocess-session.js'
2
2
  import { buildBaseSessionOpts } from './base-session.js'
3
+ import { synthesizeModelUsage } from './usage-normalize.js'
3
4
  import { homedir } from 'os'
4
5
  import { join } from 'path'
5
6
  import { resolveBinary } from './utils/resolve-binary.js'
@@ -48,7 +49,10 @@ const BINARY_CANDIDATES = [
48
49
  join(homedir(), '.npm-global/bin/gemini'),
49
50
  ]
50
51
 
51
- const GEMINI = resolveBinary('gemini', BINARY_CANDIDATES)
52
+ // NOTE: the gemini binary is intentionally NOT cached in a module-load const.
53
+ // A frozen path is spawned even after the binary is quarantined/moved out from
54
+ // under a long-running daemon (#6708 defect #3); the `resolvedBinary` getter
55
+ // re-resolves fresh per access instead.
52
56
 
53
57
  // Per-provider model metadata — #2956.
54
58
  // Context windows come from the Gemini model docs. Kept explicit here so the
@@ -121,7 +125,10 @@ export class GeminiSession extends JsonlSubprocessSession {
121
125
  }
122
126
 
123
127
  static get resolvedBinary() {
124
- return GEMINI
128
+ // Re-resolve fresh on every access (NOT a frozen module-load const) so a
129
+ // binary quarantined / moved / reinstalled after daemon start is spawned
130
+ // from its CURRENT path — and matches what preflight verified (#6708).
131
+ return resolveBinary('gemini', BINARY_CANDIDATES)
125
132
  }
126
133
 
127
134
  static get apiKeyEnv() {
@@ -418,6 +425,11 @@ export class GeminiSession extends JsonlSubprocessSession {
418
425
  input_tokens: inputTokens,
419
426
  output_tokens: outputTokens,
420
427
  },
428
+ // #6692: single-model split (gemini reports no cache/cost fields)
429
+ modelUsage: synthesizeModelUsage(this.model, {
430
+ input_tokens: inputTokens,
431
+ output_tokens: outputTokens,
432
+ }),
421
433
  sessionId: null,
422
434
  })
423
435
  break
@@ -485,6 +497,11 @@ export class GeminiSession extends JsonlSubprocessSession {
485
497
  input_tokens: usage.input_tokens || 0,
486
498
  output_tokens: usage.output_tokens || 0,
487
499
  },
500
+ // #6692: keep the legacy/test path shape-identical to production
501
+ modelUsage: synthesizeModelUsage(this.model, {
502
+ input_tokens: usage.input_tokens || 0,
503
+ output_tokens: usage.output_tokens || 0,
504
+ }),
488
505
  sessionId: null,
489
506
  })
490
507
  break