@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
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "ws",
3
+ "version": "8.20.0",
4
+ "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
5
+ "keywords": [
6
+ "HyBi",
7
+ "Push",
8
+ "RFC-6455",
9
+ "WebSocket",
10
+ "WebSockets",
11
+ "real-time"
12
+ ],
13
+ "homepage": "https://github.com/websockets/ws",
14
+ "bugs": "https://github.com/websockets/ws/issues",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/websockets/ws.git"
18
+ },
19
+ "author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
20
+ "license": "MIT",
21
+ "main": "index.js",
22
+ "exports": {
23
+ ".": {
24
+ "browser": "./browser.js",
25
+ "import": "./wrapper.mjs",
26
+ "require": "./index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "browser": "browser.js",
31
+ "engines": {
32
+ "node": ">=10.0.0"
33
+ },
34
+ "files": [
35
+ "browser.js",
36
+ "index.js",
37
+ "lib/*.js",
38
+ "wrapper.mjs"
39
+ ],
40
+ "scripts": {
41
+ "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
42
+ "integration": "mocha --throw-deprecation test/*.integration.js",
43
+ "lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
44
+ },
45
+ "peerDependencies": {
46
+ "bufferutil": "^4.0.1",
47
+ "utf-8-validate": ">=5.0.2"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "bufferutil": {
51
+ "optional": true
52
+ },
53
+ "utf-8-validate": {
54
+ "optional": true
55
+ }
56
+ },
57
+ "devDependencies": {
58
+ "@eslint/js": "^10.0.1",
59
+ "benchmark": "^2.1.4",
60
+ "bufferutil": "^4.0.1",
61
+ "eslint": "^10.0.1",
62
+ "eslint-config-prettier": "^10.0.1",
63
+ "eslint-plugin-prettier": "^5.0.0",
64
+ "globals": "^17.0.0",
65
+ "mocha": "^8.4.0",
66
+ "nyc": "^15.0.0",
67
+ "prettier": "^3.0.0",
68
+ "utf-8-validate": "^6.0.0"
69
+ }
70
+ }
@@ -0,0 +1,21 @@
1
+ import createWebSocketStream from './lib/stream.js';
2
+ import extension from './lib/extension.js';
3
+ import PerMessageDeflate from './lib/permessage-deflate.js';
4
+ import Receiver from './lib/receiver.js';
5
+ import Sender from './lib/sender.js';
6
+ import subprotocol from './lib/subprotocol.js';
7
+ import WebSocket from './lib/websocket.js';
8
+ import WebSocketServer from './lib/websocket-server.js';
9
+
10
+ export {
11
+ createWebSocketStream,
12
+ extension,
13
+ PerMessageDeflate,
14
+ Receiver,
15
+ Sender,
16
+ subprotocol,
17
+ WebSocket,
18
+ WebSocketServer
19
+ };
20
+
21
+ export default WebSocket;
@@ -134,6 +134,7 @@ export const BASE_SESSION_OPT_KEYS = [
134
134
  'hardTimeoutMs',
135
135
  'streamStallTimeoutMs',
136
136
  'backgroundShellHardQuiesceMs',
137
+ 'permissionRuleStore',
137
138
  ]
138
139
 
139
140
  // #5367: pick the BaseSession opts out of a subclass's full opts bag and merge
@@ -183,6 +184,63 @@ function _coerceSessionPreambleOpt(value) {
183
184
  return trimmed
184
185
  }
185
186
 
187
+ /**
188
+ * #7095 — normalise `result.duration` to a whole, non-negative number of milliseconds.
189
+ *
190
+ * Applied on BaseSession's `emit()` override, the one method every `result` passes
191
+ * through (see the override's own note: a prior review missed 3 of 8 direct-emit
192
+ * sites). That placement is what makes this cover BOTH consumers — the live wire path
193
+ * in `event-normalizer.js` and the persisted `session-message-history.js` replay path,
194
+ * which read the same emitted object.
195
+ *
196
+ * Needed because four producers hand through values nothing guarantees:
197
+ * - cli-session.js `data.duration_ms` (Claude CLI stream-json)
198
+ * - sdk-session.js `msg.duration_ms` (Agent SDK)
199
+ * - codex-app-server-session.js `turn?.durationMs`
200
+ * - byok-session.js `Date.now() - turnStartedAt` (NEGATIVE on a backwards clock jump)
201
+ *
202
+ * #7083 closed only the CONFIG route into this field (`sdk-session.js`'s stall-timeout
203
+ * fallback); the three third-party routes stayed open. Without this, adding
204
+ * `.int().nonnegative()` to `ServerResultSchema` would make a real provider frame
205
+ * wire-illegal — the exact trade #7093 deliberately refused to make blind.
206
+ *
207
+ * `Math.round`, not `Math.trunc`: this is a MEASURED elapsed time, so the nearest whole
208
+ * ms is the faithful value. (#7083 chose truncation for CONFIG values, where the risk
209
+ * was rounding an out-of-range value UP into legality — a different problem.)
210
+ *
211
+ * `null` and absent pass through untouched — the field is nullable on the wire.
212
+ * Non-finite and past-2^53 values become `null`: both are unrepresentable, and `null`
213
+ * ("unknown") is honest where a clamped number would be a precise-looking lie.
214
+ *
215
+ * @param {unknown} payload
216
+ * @returns {unknown} the payload, or a copy with `duration` normalised
217
+ */
218
+ function normalizeResultDuration(payload) {
219
+ if (!payload || typeof payload !== 'object') return payload
220
+ const { duration } = payload
221
+ if (typeof duration !== 'number' || !Number.isFinite(duration)) {
222
+ // Non-finite: emit null rather than passing through. JSON.stringify turns
223
+ // Infinity/NaN into `null` on the wire and on disk ANYWAY, so passing them
224
+ // through does not preserve a visible failure — it just leaves the in-process
225
+ // object disagreeing with what every consumer actually receives. Doing it here
226
+ // makes the two agree.
227
+ if (typeof duration === 'number') return { ...payload, duration: null }
228
+ return payload
229
+ }
230
+ if (duration < 0) return { ...payload, duration: 0 }
231
+ const rounded = Math.round(duration)
232
+ // Math.round preserves Number.isInteger but NOT Number.isSafeInteger, and Zod's
233
+ // `.int()` enforces the SAFE-integer range. Rounding can even manufacture the
234
+ // problem: 9007199254740991.5 rounds UP to 2^53, which is an integer and is
235
+ // wire-illegal. A duration past 2^53 ms is ~285,000 years, i.e. garbage from a
236
+ // broken clock or a provider bug — so null ("unknown", the field is nullable) is
237
+ // the honest answer. Clamping to MAX_SAFE_INTEGER would render a precise-looking
238
+ // 285,000-year turn, which is the #7081 lesson: an absent value beats a false one.
239
+ if (!Number.isSafeInteger(rounded)) return { ...payload, duration: null }
240
+ if (rounded === duration) return payload
241
+ return { ...payload, duration: rounded }
242
+ }
243
+
186
244
  export class BaseSession extends EventEmitter {
187
245
  /**
188
246
  * Custom event names emitted by this provider class that should be proxied
@@ -287,9 +345,19 @@ export class BaseSession extends EventEmitter {
287
345
  // BACKGROUND_SHELL_HARD_QUIESCE_MS (4h); 0 disables hard-reaping (revert
288
346
  // to #5247 advisory-only). Forwarded from config via SessionManager.
289
347
  backgroundShellHardQuiesceMs,
348
+ // #6771 — the daemon-wide durable PermissionRuleStore (persistent per-project
349
+ // "always allow / deny"). A runtime handle (not serialized), forwarded from
350
+ // SessionManager; the in-process permission providers (SDK / BYOK / codex)
351
+ // hand it to their PermissionManager so an `allowAlways` decision persists a
352
+ // project-scoped rule and new sessions in the same cwd seed from it.
353
+ permissionRuleStore,
290
354
  } = {}) {
291
355
  super()
292
356
  this.cwd = cwd || process.cwd()
357
+ // #6771 — durable per-project permission rule store (see the opt doc above).
358
+ // Read by the in-process permission providers when they build their
359
+ // PermissionManager; null on providers/tests that don't wire it.
360
+ this._permissionRuleStore = permissionRuleStore || null
293
361
  this.model = model || null
294
362
  // Actual model the underlying CLI/SDK reports at init time. May differ
295
363
  // from `this.model` (the user's requested override) when no override
@@ -389,6 +457,22 @@ export class BaseSession extends EventEmitter {
389
457
  emit: (event, payload) => this.emit(event, payload),
390
458
  })
391
459
  this._setupActivityRegistry()
460
+ // #6832: `mcp_servers` is a transient event (sdk/cli parse it off the live
461
+ // stream-json `system/init`; claude-tui re-derives the CONFIGURED list on
462
+ // warmup/respawn — see claude-tui-session.js `_emitConfiguredMcpServers`,
463
+ // #6820/#6831) — forwarded to currently-connected clients but never
464
+ // recorded in history. A client that subscribes to an already-warmed
465
+ // session (dashboard reconnect, second client joining a shared session)
466
+ // never received the list until the NEXT emission. Cache the last payload
467
+ // here — self-listening on the session's own emit, so every provider that
468
+ // emits `mcp_servers` through `this.emit(...)` feeds this for free, same
469
+ // as `_setupActivityRegistry` above — and expose it via
470
+ // `getMcpServersSnapshot()` so `ws-history.sendSessionInfo`'s snapshot-on-
471
+ // subscribe can replay it, mirroring the `activity_snapshot` /
472
+ // `permission_rules_updated` late-join pattern. Cleared on full teardown
473
+ // (see `removeAllListeners` below).
474
+ this._lastMcpServers = null
475
+ this.on('mcp_servers', (data) => { this._lastMcpServers = data })
392
476
  this._messageCounter = 0
393
477
  // Boot-unique prefix mixed into every emitted messageId (#3700).
394
478
  // The dashboard caches up to 100 messages per session in localStorage
@@ -839,6 +923,11 @@ export class BaseSession extends EventEmitter {
839
923
  // shape with the right argument count.
840
924
  if (eventName === undefined) {
841
925
  this._activity.clear()
926
+ // #6832: clear the cached mcp_servers snapshot on full teardown too —
927
+ // a destroyed session must not replay a stale server list to a client
928
+ // that later subscribes to a NEW session that happens to reuse the id
929
+ // (or to any lingering reference to this now-dead session object).
930
+ this._lastMcpServers = null
842
931
  // #5177: stop the background-shell sweep on full teardown too. Most
843
932
  // providers (cli/jsonl/gemini/codex) destroy via removeAllListeners()
844
933
  // and never call _destroyPendingBackgroundShells, so this is the
@@ -868,6 +957,21 @@ export class BaseSession extends EventEmitter {
868
957
  return this._activity.getSnapshotMessage()
869
958
  }
870
959
 
960
+ /**
961
+ * #6832: last-known `mcp_servers` payload, wrapped as the wire message
962
+ * shape (`{ type: 'mcp_servers', servers }`). Served to a fresh subscriber
963
+ * (snapshot-on-subscribe, via `ws-history.sendSessionInfo`) so a client
964
+ * that joins an already-warmed session sees the current list without
965
+ * waiting on the next emission — mirroring `getActivitySnapshot()` above.
966
+ * Returns `null` when this session has never emitted `mcp_servers` (no
967
+ * snapshot to replay; nothing to send).
968
+ * @returns {{type: 'mcp_servers', servers: object[]} | null}
969
+ */
970
+ getMcpServersSnapshot() {
971
+ if (!this._lastMcpServers) return null
972
+ return { type: 'mcp_servers', servers: this._lastMcpServers.servers }
973
+ }
974
+
871
975
  /**
872
976
  * #5269 (Control Room Phase 2a): cancel a single in-flight activity node by
873
977
  * its `activityId` (an `activity_snapshot`/`activity_delta` entry id).
@@ -1442,21 +1546,62 @@ export class BaseSession extends EventEmitter {
1442
1546
  }
1443
1547
 
1444
1548
  /**
1445
- * #4628: emit `result` after sweeping any in-flight tool_starts. All
1446
- * provider sessions should route through this rather than calling
1447
- * `this.emit('result', ...)` directly, so orphan tool_starts get
1448
- * paired with a synthetic tool_result BEFORE the result fires (and
1449
- * BEFORE state is persisted, since session-message-history listens
1450
- * for both events).
1549
+ * #4628: emit `result` after sweeping any in-flight tool_starts. Provider
1550
+ * sessions should route through this WHEN they need the orphan sweep, so
1551
+ * orphan tool_starts get paired with a synthetic tool_result BEFORE the
1552
+ * result fires (and BEFORE state is persisted, since session-message-history
1553
+ * listens for both events). Some providers deliberately emit `this.emit(
1554
+ * 'result', ...)` directly (they don't want the sweep); the queueLength stamp
1555
+ * is applied to those too via the emit() override below.
1451
1556
  *
1452
1557
  * @param {object} payload — the result event payload ({cost, duration, usage, sessionId})
1453
1558
  * @param {string} [sweepReason] — optional override for the sweep reason
1454
1559
  */
1455
1560
  _emitResult(payload, sweepReason = 'stream_completed_without_result') {
1456
1561
  this._sweepUnresolvedToolStarts(sweepReason)
1562
+ // queueLength is stamped centrally in the emit() override below (#6627/#6706).
1457
1563
  this.emit('result', payload)
1458
1564
  }
1459
1565
 
1566
+ /**
1567
+ * #6627 / #6706: single choke point for the turn-boundary queue-length stamp.
1568
+ *
1569
+ * Every `result` event carries the session's authoritative outgoing-queue
1570
+ * length so clients reconcile a stale "Queued" bubble on a turn boundary — a
1571
+ * dropped/late `message_dequeued` no longer leaves a stale badge until the
1572
+ * next queue event. The count is pre-flush (the imminent dequeue emits its own
1573
+ * event); `reconcileQueueLength` only trims confirmed orphans, never a live
1574
+ * entry, so it is safe to stamp on every result.
1575
+ *
1576
+ * Stamping here (rather than at each call site) is deliberate: `_emitResult`
1577
+ * is NOT the only emitter — several providers emit `result` directly (CLI /
1578
+ * exec-codex / gemini / byok / stall fallbacks) because they don't want the
1579
+ * orphan sweep, and the #6705 review missed 3 of the 8 sites. Centralizing on
1580
+ * the one method every `result` passes through makes the self-heal uniform
1581
+ * and un-forgettable for future emit sites too.
1582
+ *
1583
+ * Idempotent: a payload that already carries `queueLength` (none today, but a
1584
+ * caller could pre-stamp) is left untouched. `_outgoingQueue` is a BaseSession
1585
+ * field initialized before any subclass method can run; the `?` guard is
1586
+ * belt-and-braces and yields 0 for the should-never-happen case of a subclass
1587
+ * emitting `result` inside `super()` before the field is set.
1588
+ *
1589
+ * @param {string} event
1590
+ * @param {...any} args
1591
+ * @returns {boolean} whether the event had listeners (EventEmitter contract)
1592
+ */
1593
+ emit(event, ...args) {
1594
+ if (event === 'result') {
1595
+ let payload = args[0]
1596
+ if (payload && typeof payload === 'object' && payload.queueLength === undefined) {
1597
+ payload = { ...payload, queueLength: this._outgoingQueue ? this._outgoingQueue.length : 0 }
1598
+ }
1599
+ payload = normalizeResultDuration(payload)
1600
+ if (payload !== args[0]) args[0] = payload
1601
+ }
1602
+ return super.emit(event, ...args)
1603
+ }
1604
+
1460
1605
  _clearMessageState() {
1461
1606
  this._isBusy = false
1462
1607
  this._currentMessageId = null
@@ -17,6 +17,7 @@
17
17
 
18
18
  import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync } from 'node:fs'
19
19
  import { dirname } from 'node:path'
20
+ import { toWireCount } from './utils/wire-counters.js'
20
21
 
21
22
  /** Per-tier monthly programmatic-credit caps (USD), per Anthropic's 2026-06-15 change. */
22
23
  export const CREDIT_TIER_BUDGETS_USD = Object.freeze({
@@ -101,7 +102,10 @@ export class MonthlyProgrammaticBudgetManager {
101
102
  this._state = {
102
103
  month: raw.month,
103
104
  spentUsd: Number.isFinite(raw.spentUsd) ? raw.spentUsd : 0,
104
- turnsBilled: Number.isFinite(raw.turnsBilled) && raw.turnsBilled >= 0 ? raw.turnsBilled : 0,
105
+ // #7082: `.int().nonnegative()` on the wire — the finite+sign guard let a
106
+ // fractional or past-2^53 value through from a hand-edited state file.
107
+ // `spentUsd` above is deliberately untouched: USD, no `.int()`.
108
+ turnsBilled: toWireCount(raw.turnsBilled),
105
109
  warnNotified: raw.warnNotified === true,
106
110
  exceededNotified: raw.exceededNotified === true,
107
111
  }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Provider-binary provenance trust ledger (#6858).
3
+ *
4
+ * Pins the SHA-256 hash of every spawned provider binary (`claude`, `codex`,
5
+ * `gemini`, `cloudflared`) the daemon has seen. A later change to a pinned hash
6
+ * re-gates the binary (warn / block) — catching an in-place binary swap
7
+ * regardless of code signature or macOS quarantine state. See
8
+ * `utils/verify-provenance.js` for the verification logic and
9
+ * `docs/security/spawned-binary-provenance.md` for the threat model.
10
+ *
11
+ * Storage shape (sidecar JSON file, next to skills-trust.json / session-preset-
12
+ * trust.json):
13
+ *
14
+ * {
15
+ * "binaries": {
16
+ * "/opt/homebrew/bin/codex": {
17
+ * "sha256": "<64 hex chars>", // the binary's CONTENT hash
18
+ * "firstSeen": "2026-07-22T12:34:56.000Z",
19
+ * "approvedAt": "2026-07-22T12:34:56.000Z"
20
+ * }
21
+ * }
22
+ * }
23
+ *
24
+ * A path is TRUSTED only when its stored `sha256` equals the hash of the
25
+ * currently-resolved binary. First sight (no record) → pin + allow
26
+ * (trust-on-first-use). A changed hash → re-gated. The operator re-approves the
27
+ * CURRENT hash via `approve(path, hash)`; `revoke(path)` drops the record.
28
+ *
29
+ * Since #5580 the ledger mechanics (load/isTrusted/approve/revoke/getRecord +
30
+ * atomic 0600 persist + fail-open) live in `PathHashTrustLedger`; this class is
31
+ * a thin subclass that pins the `binaries` wrapper key and the `approvedAt`
32
+ * timestamp field. Best-effort flush (a read-only $HOME must never break
33
+ * spawning — provenance is a defence-in-depth layer, not a hard dependency).
34
+ */
35
+ import { existsSync } from 'fs'
36
+ import { homedir } from 'os'
37
+ import { join } from 'path'
38
+ import { createLogger } from './logger.js'
39
+ import { PathHashTrustLedger } from './path-hash-trust-ledger.js'
40
+
41
+ const log = createLogger('binary-provenance-trust')
42
+
43
+ export const DEFAULT_BINARY_TRUST_FILE = join(homedir(), '.chroxy', 'binary-trust.json')
44
+
45
+ /**
46
+ * Normalise a ledger key for storage / lookup. On case-insensitive filesystems
47
+ * (macOS APFS, Windows NTFS) the same binary can resolve to different casings,
48
+ * so keys are lowercased there; on case-sensitive Linux the key is kept verbatim.
49
+ * Mirrors the skills/preset stores' normaliser (kept local per the base-ledger
50
+ * convention that each subclass owns its own key hook).
51
+ *
52
+ * @param {string} absPath
53
+ * @returns {string}
54
+ */
55
+ export function _normalizeKey(absPath) {
56
+ if (typeof absPath !== 'string') return ''
57
+ return (process.platform === 'darwin' || process.platform === 'win32')
58
+ ? absPath.toLowerCase()
59
+ : absPath
60
+ }
61
+
62
+ /**
63
+ * In-memory + on-disk pin ledger for spawned provider binaries. One instance per
64
+ * daemon, constructed by SessionManager; that SAME instance is threaded into the
65
+ * tunnel config (server-cli.js → `binaryProvenance.ledger`) so the cloudflared
66
+ * gate and the provider spawns share one ledger and one set of pins — no second
67
+ * instance. Tests pass an explicit `filePath` so they never touch the real ledger.
68
+ */
69
+ export class BinaryProvenanceLedger extends PathHashTrustLedger {
70
+ /**
71
+ * @param {{ filePath?: string }} [opts]
72
+ */
73
+ constructor({ filePath } = {}) {
74
+ super({
75
+ filePath: filePath || DEFAULT_BINARY_TRUST_FILE,
76
+ log,
77
+ normalizeKey: _normalizeKey,
78
+ approvalField: 'approvedAt',
79
+ wrapperKey: 'binaries',
80
+ throwOnFlushError: false, // best-effort: a read-only $HOME never breaks spawning
81
+ })
82
+ const loaded = this._loadRecords()
83
+ this._records = loaded.records
84
+ this._dirty = false
85
+ }
86
+ }
87
+
88
+ // Helper so tests / callers can confirm the ledger file exists.
89
+ export function binaryTrustFileExists(filePath) {
90
+ try {
91
+ return existsSync(filePath)
92
+ } catch {
93
+ return false
94
+ }
95
+ }
@@ -7,9 +7,10 @@
7
7
  * Edit — string-replace with strict-uniqueness check unless `replaceAll`
8
8
  *
9
9
  * Path-safety is the caller's responsibility — by the time we reach here
10
- * the BYOK tool executor has already run validatePathWithinCwd() from
11
- * ws-file-ops/common.js to defeat symlink escape attempts. These helpers
12
- * receive realpaths that are known to be inside the session cwd.
10
+ * the BYOK tool executor has already run validateRawPathWithinCwd() from
11
+ * ws-file-ops/common.js to defeat symlink escape attempts (including a `..`
12
+ * after a symlinked component, #6923). These helpers receive realpaths that
13
+ * are known to be inside the session cwd.
13
14
  *
14
15
  * Each function returns `{ ok: true, ... }` on success or
15
16
  * `{ ok: false, code, message }` on a recoverable error (file not found,
@@ -118,7 +119,7 @@ export async function writeFileTool({ filePath, content, mode = 0o644 } = {}) {
118
119
 
119
120
  // Ensure parent directory exists. recursive:true is a no-op when the
120
121
  // directory already exists, so this is safe to call unconditionally.
121
- // Path safety was already enforced by the caller (validatePathWithinCwd
122
+ // Path safety was already enforced by the caller (validateRawPathWithinCwd
122
123
  // in byok-tool-executor.js), so the dirname is guaranteed to be
123
124
  // inside the workspace cwd.
124
125
  if (!existedBefore) {