@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
@@ -8,7 +8,7 @@ import { getProvider, getProviderAuthInfo, DEFAULT_PROVIDER } from './providers.
8
8
  import { isClaudeProvider } from './models.js'
9
9
  import { billingClassForProvider, BILLING_CLASSES } from './billing-class.js'
10
10
  import { MonthlyProgrammaticBudgetManager } from './billing-budget.js'
11
- import { runProviderPreflight, ProviderBinaryNotFoundError, ProviderCredentialMissingError } from './utils/preflight.js'
11
+ import { runProviderPreflight, ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, ProviderBinaryProvenanceError, ProviderCredentialMissingError } from './utils/preflight.js'
12
12
  import { GIT } from './git.js'
13
13
  import { sweepOrphanChroxyWorktrees } from './worktree-gc.js'
14
14
  import { resolveJsonlPath, readConversationHistoryAsync } from './jsonl-reader.js'
@@ -19,15 +19,25 @@ import { CostBudgetManager } from './cost-budget-manager.js'
19
19
  import { SessionStatePersistence } from './session-state-persistence.js'
20
20
  import { SessionTimeoutManager, formatIdleDuration } from './session-timeout-manager.js'
21
21
  import { SessionMessageHistory } from './session-message-history.js'
22
+ import { generateSessionTitle, DEFAULT_SEMANTIC_TITLE_MODEL, DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS } from './session-title.js'
23
+ // NB: the default one-shot title runner (defaultRunOneShot) lives in
24
+ // summarize-session.js, which statically imports the Agent SDK. It is loaded
25
+ // LAZILY (dynamic import inside _generateSemanticTitle) so the core
26
+ // SessionManager module — imported by nearly every test — never pulls the SDK
27
+ // into its graph unless the semantic-title feature actually fires a model call.
22
28
  import { SkillsUsageRecorder } from './skills-usage.js'
23
29
  import { resolveSessionPreset, foldPreamble } from './session-preset.js'
24
30
  import { SessionPresetTrustStore } from './session-preset-trust.js'
31
+ import { BinaryProvenanceLedger } from './binary-provenance-trust.js'
32
+ import { PermissionRuleStore } from './permission-rule-store.js'
33
+ import { ScheduledTaskStore, defaultScheduledTasksPath } from './scheduled-task-store.js'
25
34
  import { createLogger } from './logger.js'
26
35
  import { ExternalSessionRegistry } from './external-session-registry.js'
27
36
  import { metrics } from './metrics.js'
28
37
  import { auditShellDestroy } from './shell-audit.js'
29
38
  import { recordShell, forgetShell, reapOrphanShells } from './user-shell-registry.js'
30
39
  import { getErrorMessage } from './utils/error-message.js'
40
+ import { toWireCount } from './utils/wire-counters.js'
31
41
  import {
32
42
  forwardPerSessionSettingsToProviderOpts,
33
43
  serializePerSessionSettings,
@@ -167,9 +177,10 @@ const DEFAULT_WORKTREE_BASE = join(homedir(), '.chroxy', 'worktrees')
167
177
  export { formatIdleDuration }
168
178
 
169
179
  // Re-export preflight errors so call sites that catch createSession() failures
170
- // can detect/branch on PROVIDER_BINARY_NOT_FOUND / PROVIDER_CREDENTIAL_MISSING
171
- // without taking a separate dependency on utils/preflight.js.
172
- export { ProviderBinaryNotFoundError, ProviderCredentialMissingError }
180
+ // can detect/branch on PROVIDER_BINARY_NOT_FOUND / PROVIDER_BINARY_QUARANTINED /
181
+ // PROVIDER_BINARY_PROVENANCE / PROVIDER_CREDENTIAL_MISSING without taking a
182
+ // separate dependency on utils/preflight.js.
183
+ export { ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, ProviderBinaryProvenanceError, ProviderCredentialMissingError }
173
184
 
174
185
  /**
175
186
  * @typedef {Object} SessionManagerConfig
@@ -209,11 +220,30 @@ export { ProviderBinaryNotFoundError, ProviderCredentialMissingError }
209
220
  * @property {number} [maxMessages=1000] - Max history messages per session (alias: maxHistory)
210
221
  * @property {number} [maxHistory] - Legacy alias for maxMessages
211
222
  */
223
+
224
+ // #6944 / #6952 review: process-lifetime dedup for the general unknown-ctor-opt
225
+ // warning below — keyed by the unrecognized option name so a given typo warns
226
+ // at most once no matter how many SessionManager instances get constructed.
227
+ // Module-level (not per-instance) is intentional: the warning is a one-time
228
+ // "you have a bug" signal, not per-instance telemetry.
229
+ const warnedUnknownCtorOptKeys = new Set()
230
+
212
231
  export class SessionManager extends EventEmitter {
213
232
  /**
214
- * @param {SessionManagerConfig} config
233
+ * @param {SessionManagerConfig} opts
215
234
  */
216
- constructor({
235
+ constructor(opts = {}) {
236
+ super()
237
+
238
+ // #6952 review: destructure the raw `opts` object here (instead of in the
239
+ // parameter list) so `opts` itself stays addressable below — needed to
240
+ // tell "providerType explicitly passed" apart from "providerType defaulted"
241
+ // (see providerTypeIsExplicit) without a parallel hand-maintained key list.
242
+ // `let` (not `const`): parameter destructuring made every one of these an
243
+ // independently mutable local binding, and `providerType` in particular is
244
+ // reassigned below when the `provider` alias resolves onto it — a `const`
245
+ // destructure would throw "Assignment to constant variable" at that point.
246
+ let {
217
247
  // Server identity
218
248
  port,
219
249
  apiToken,
@@ -328,10 +358,52 @@ export class SessionManager extends EventEmitter {
328
358
  // this at a temp config.json; production uses the default ~/.chroxy/config.json.
329
359
  presetConfigPath,
330
360
 
361
+ // #6858: opt-in provenance verification for spawned provider binaries.
362
+ // `binaryProvenanceMode` ('off'|'warn'|'block') drives the SHA-256 pin
363
+ // ledger; `binarySignatureGate` toggles the macOS `spctl` gate. Both wired
364
+ // from `resolveBinaryProvenanceMode` / `isBinarySignatureGateEnabled` in
365
+ // server-cli. Off by default → the gate is skipped and preflight behaviour is
366
+ // identical to #6708. Tests pass their own temp-pathed `binaryProvenanceLedger`
367
+ // (like presetTrustStore) so a temp stateFilePath keeps the ledger out of the
368
+ // real ~/.chroxy.
369
+ binaryProvenanceMode = 'off',
370
+ binarySignatureGate = false,
371
+ binaryProvenanceLedger,
372
+ // #6771: durable per-project permission rule store (persistent "always
373
+ // allow / deny"). Tests pass their own temp-pathed store; production wires a
374
+ // default whose file (permission-rules.json) sits next to the session-state
375
+ // file so a temp stateFilePath keeps it out of the real ~/.chroxy.
376
+ permissionRuleStore,
377
+
378
+ // #6862: durable scheduled-task registry (standing schedules that run on a
379
+ // future/recurring cadence — SEPARATE from live session state and from the
380
+ // intra-session ScheduleWakeup). Tests pass their own temp-pathed store;
381
+ // production wires a default whose file (scheduled-tasks.json) sits next to
382
+ // the session-state file so a temp stateFilePath keeps it out of the real
383
+ // ~/.chroxy. No firing here — the engine is a sibling slice (#6865).
384
+ scheduledTaskStore,
385
+
331
386
  // Message history
332
387
  maxMessages,
333
388
  maxHistory,
334
389
 
390
+ // #6764: opt-in semantic session titles. When enabled, the first user turn's
391
+ // auto-label is upgraded from a raw truncation to a short model-generated
392
+ // title via a cheap one-shot (Haiku) call, fired at most once per session and
393
+ // fully async (never blocks the turn). Wired from `isSemanticTitlesEnabled` /
394
+ // `resolveSemanticTitleModel` in server-cli. `titleRunOneShot` is a test seam
395
+ // that injects the model runner; production falls through to the SDK one-shot.
396
+ semanticTitlesEnabled = false,
397
+ semanticTitleModel = null,
398
+ // #6764: hard timeout (ms) for the fire-and-forget one-shot title call. The
399
+ // call MUST be abortable — a stalled provider stream otherwise leaves the
400
+ // detached promise pending forever, retaining `this`, the first message, and
401
+ // the sessionId (an unbounded per-session leak) and never tearing the one-shot
402
+ // subprocess down. `_generateSemanticTitle` turns this into an
403
+ // `AbortSignal.timeout(...)`; null → the DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS.
404
+ semanticTitleTimeoutMs = null,
405
+ titleRunOneShot = null,
406
+
335
407
  // #5859 (audit P1-7): opt-in boot-time sweep of orphaned chroxy session
336
408
  // worktrees (dirs under the worktree base whose session id is no longer
337
409
  // live). Off by default — server-cli enables it from config.worktreeGc.autoReap,
@@ -341,8 +413,76 @@ export class SessionManager extends EventEmitter {
341
413
  // Test-only: skip preflight checks (binary + credential). Production must
342
414
  // leave this false so missing providers surface cleanly at createSession.
343
415
  skipPreflight = false,
344
- } = {}) {
345
- super()
416
+
417
+ // #6944: object-rest captures every option key NOT destructured above.
418
+ // The destructure itself is the single source of truth for "known" keys —
419
+ // no parallel allow-list to drift. Anything landing here is a misnamed or
420
+ // unrecognized ctor option; the guard below surfaces it instead of letting
421
+ // it be silently swallowed (which is how `provider` — the createSession()
422
+ // opt, not the ctor's `providerType` — fell through to a claude-tui PTY
423
+ // spawn and hung CI, #6933).
424
+ ...unknownCtorOpts
425
+ } = opts
426
+
427
+ // #6944: surface misnamed / unknown constructor options. Never throws — a
428
+ // production caller must not crash on a friendly alias — but it refuses to
429
+ // silently ignore a key.
430
+ const unknownOptKeys = Object.keys(unknownCtorOpts)
431
+ if (unknownOptKeys.length > 0) {
432
+ // Targeted alias: `provider` is the classic typo for `providerType` (the
433
+ // former is the createSession() option, the latter the ctor's). When only
434
+ // `provider` was supplied as a usable string, map it onto `providerType`
435
+ // so the caller gets the provider they intended rather than a silent
436
+ // DEFAULT_PROVIDER (claude-tui) PTY spawn. If `providerType` was ALSO set
437
+ // explicitly, or `provider` is not a usable string (undefined/null/''),
438
+ // keep the resolved `providerType` and just warn that `provider` is
439
+ // ignored — never overwrite a good default with a bad alias value.
440
+ if (Object.prototype.hasOwnProperty.call(unknownCtorOpts, 'provider')) {
441
+ const providerAlias = unknownCtorOpts.provider
442
+ // #6952 review: explicitness must come from the ORIGINAL `opts` object,
443
+ // not from comparing the (already-defaulted) `providerType` binding to
444
+ // DEFAULT_PROVIDER. A caller passing BOTH `provider` and an explicit
445
+ // `providerType` that happens to equal DEFAULT_PROVIDER (e.g.
446
+ // `providerType: 'claude-tui'`) is indistinguishable from omitting
447
+ // providerType entirely under the old check — the alias would
448
+ // incorrectly win. `'providerType' in opts` reflects what the caller
449
+ // actually passed, independent of its value.
450
+ const providerTypeIsExplicit = Object.prototype.hasOwnProperty.call(opts, 'providerType')
451
+ if (!providerTypeIsExplicit && typeof providerAlias === 'string' && providerAlias.length > 0) {
452
+ log.warn(`SessionManager: 'provider' is not a constructor option — did you mean 'providerType'? Treating provider=${JSON.stringify(providerAlias)} as providerType (createSession() uses 'provider'; the constructor uses 'providerType').`)
453
+ providerType = providerAlias
454
+ } else {
455
+ const reason = providerTypeIsExplicit
456
+ ? `providerType=${JSON.stringify(providerType)} is already set`
457
+ : `provider=${JSON.stringify(providerAlias)} is not a usable provider id`
458
+ log.warn(`SessionManager: ignoring constructor option 'provider' (use 'providerType') — ${reason}.`)
459
+ }
460
+ }
461
+ // The rest of the class: warn on any other unrecognized key. #6952 review:
462
+ // this used to be gated on `process.env.NODE_ENV === 'test'`, but nothing
463
+ // in the harness/CI ever sets NODE_ENV=test, so the safety net never fired
464
+ // outside of someone manually exporting it — the whole-key-class catch
465
+ // (e.g. `persistenceDebounceMs` typo'd for `persistDebounceMs`) was dead.
466
+ // Always-on is safe for production: SessionManager's sole prod caller
467
+ // (server-cli.js) constructs it from a fixed set of destructured keys, so
468
+ // `unknownCtorOpts` is empty there and this never fires. The module-level
469
+ // dedup Set bounds repeat warnings to once per distinct key for the life
470
+ // of the process, so it can't spam a long-lived daemon log even if some
471
+ // future caller does pass an unknown key repeatedly (e.g. in a loop).
472
+ // CHROXY_DEBUG_CTOR_OPTS='1' bypasses the dedup for extra verbosity when
473
+ // actively debugging a ctor-opt issue (every occurrence re-warns).
474
+ const otherUnknown = unknownOptKeys.filter((k) => k !== 'provider')
475
+ if (otherUnknown.length > 0) {
476
+ const verbose = process.env.CHROXY_DEBUG_CTOR_OPTS === '1'
477
+ const toWarn = verbose
478
+ ? otherUnknown
479
+ : otherUnknown.filter((k) => !warnedUnknownCtorOptKeys.has(k))
480
+ if (toWarn.length > 0) {
481
+ toWarn.forEach((k) => warnedUnknownCtorOptKeys.add(k))
482
+ log.warn(`SessionManager: ignoring unrecognized constructor option(s): ${toWarn.join(', ')}. Check for a misnamed option.`)
483
+ }
484
+ }
485
+ }
346
486
 
347
487
  // Server identity
348
488
  this._port = port || null
@@ -507,9 +647,45 @@ export class SessionManager extends EventEmitter {
507
647
  // file so a test's temp stateFilePath keeps the ledger out of the real home.
508
648
  this.presetTrustStore = presetTrustStore
509
649
  || new SessionPresetTrustStore({ filePath: join(dirname(this._stateFilePath), 'session-preset-trust.json') })
650
+ // #6858: opt-in provider-binary provenance. The pin ledger's default file
651
+ // sits next to the session-state file (same temp-redirect reasoning as the
652
+ // sidecars above) so a test's temp stateFilePath keeps it out of the real
653
+ // home. Constructing the ledger is read-only (it only writes on a first-sight
654
+ // pin / approve), so it is always constructed; the MODE decides whether the
655
+ // gate actually runs at createSession. Anything but 'warn'/'block' → 'off'.
656
+ this._binaryProvenanceMode = (binaryProvenanceMode === 'warn' || binaryProvenanceMode === 'block')
657
+ ? binaryProvenanceMode
658
+ : 'off'
659
+ this._binarySignatureGate = binarySignatureGate === true
660
+ this.binaryProvenanceLedger = binaryProvenanceLedger
661
+ || new BinaryProvenanceLedger({ filePath: join(dirname(this._stateFilePath), 'binary-trust.json') })
510
662
  // Config path the preset resolver reads the daemon override map from.
511
663
  // Defaults to undefined → resolveSessionPreset uses its own DEFAULT_CONFIG_PATH.
512
664
  this.presetConfigPath = typeof presetConfigPath === 'string' ? presetConfigPath : null
665
+ // #6771: durable per-project permission rule store. Same temp-redirect logic
666
+ // as the sidecars above — the default file sits next to the session-state
667
+ // file so a test's temp stateFilePath keeps the rules out of the real home.
668
+ // Only the DEFAULT store is loaded here (so restored + newly-created sessions
669
+ // in a known cwd seed their persistent rules from prior grants); a
670
+ // caller-supplied store owns its own load() lifecycle.
671
+ if (permissionRuleStore) {
672
+ this.permissionRuleStore = permissionRuleStore
673
+ } else {
674
+ this.permissionRuleStore = new PermissionRuleStore({ filePath: join(dirname(this._stateFilePath), 'permission-rules.json') })
675
+ this.permissionRuleStore.load()
676
+ }
677
+ // #6862: durable scheduled-task registry. Same temp-redirect logic as the
678
+ // sidecars above — the default file sits next to the session-state file so a
679
+ // test's temp stateFilePath keeps schedules out of the real home. Loaded once
680
+ // here on daemon start; a caller-supplied store owns its own load() lifecycle.
681
+ // Nothing fires it — the store just persists tasks + computes next-run; the
682
+ // engine slice (#6865) reads it off `sessionManager.scheduledTaskStore`.
683
+ if (scheduledTaskStore) {
684
+ this.scheduledTaskStore = scheduledTaskStore
685
+ } else {
686
+ this.scheduledTaskStore = new ScheduledTaskStore({ filePath: defaultScheduledTasksPath(this._stateFilePath) })
687
+ this.scheduledTaskStore.load()
688
+ }
513
689
  Object.defineProperty(this, '_persistTimer', {
514
690
  get: () => this._persistence._persistTimer,
515
691
  set: (v) => { this._persistence._persistTimer = v },
@@ -525,9 +701,33 @@ export class SessionManager extends EventEmitter {
525
701
  this._pendingStreams = this._history.pendingStreams
526
702
  this._historyTruncated = this._history._historyTruncated
527
703
 
528
- // Wire auto_label events from history to session_updated emissions
529
- this._history.on('auto_label', ({ sessionId, label }) => {
704
+ // #6764: semantic-title feature gate + one-shot model runner. When enabled,
705
+ // the truncation auto-label is asynchronously upgraded to a short model-
706
+ // generated title. `_titleRunOneShot` is the injectable seam (tests stub the
707
+ // model call); production uses the SDK one-shot shared with the #5547
708
+ // summarizer, so no Anthropic client / API key is hardcoded here.
709
+ this._semanticTitlesEnabled = semanticTitlesEnabled === true
710
+ this._semanticTitleModel = typeof semanticTitleModel === 'string' && semanticTitleModel
711
+ ? semanticTitleModel
712
+ : DEFAULT_SEMANTIC_TITLE_MODEL
713
+ // Hard timeout for the one-shot title call (#6764) — see the ctor opt above.
714
+ // Positive finite ms only; anything else falls back to the default.
715
+ this._semanticTitleTimeoutMs = typeof semanticTitleTimeoutMs === 'number'
716
+ && Number.isFinite(semanticTitleTimeoutMs) && semanticTitleTimeoutMs > 0
717
+ ? semanticTitleTimeoutMs
718
+ : DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS
719
+ // null → resolve the default SDK one-shot lazily on first use (see above).
720
+ this._titleRunOneShot = typeof titleRunOneShot === 'function' ? titleRunOneShot : null
721
+
722
+ // Wire auto_label events from history to session_updated emissions. The
723
+ // synchronous truncation label is broadcast immediately (never blocked), then
724
+ // — when the feature is on — an async cheap-model call may upgrade it to a
725
+ // semantic title (#6764). Firing off auto_label means the upgrade inherits the
726
+ // once-per-session + default-name + manual-rename guards already enforced by
727
+ // SessionMessageHistory._autoLabelSession.
728
+ this._history.on('auto_label', ({ sessionId, label, text }) => {
530
729
  this.emit('session_updated', { sessionId, name: label })
730
+ this._maybeGenerateSemanticTitle(sessionId, text, label)
531
731
  })
532
732
 
533
733
  // Internal state
@@ -864,7 +1064,17 @@ export class SessionManager extends EventEmitter {
864
1064
  throw new UserShellDisabledError()
865
1065
  }
866
1066
  if (!this._skipPreflight) {
867
- runProviderPreflight(PreflightProviderClass)
1067
+ // #6858: opt-in provenance gate. Only build the provenance bag when the
1068
+ // operator opted in (mode warn/block or the signature gate); otherwise pass
1069
+ // null so runProviderPreflight skips the step entirely (unchanged behaviour).
1070
+ const provenance = (this._binaryProvenanceMode !== 'off' || this._binarySignatureGate)
1071
+ ? {
1072
+ mode: this._binaryProvenanceMode,
1073
+ signatureGate: this._binarySignatureGate,
1074
+ ledger: this.binaryProvenanceLedger,
1075
+ }
1076
+ : null
1077
+ runProviderPreflight(PreflightProviderClass, { provenance })
868
1078
  }
869
1079
  // #6378: a provider opted into `config.providers.allowAnyModel` skips static
870
1080
  // allowlist validation entirely — the model id passes through verbatim and
@@ -1108,9 +1318,15 @@ export class SessionManager extends EventEmitter {
1108
1318
  * handler preserves the restored history + worktree (registers a failed-restore)
1109
1319
  * instead of fully destroying the session. Fresh sessions omit it and take the
1110
1320
  * full-destroy path on start failure.
1321
+ * @param {object|null} [options.metadata] - #6691 (E-4): opaque per-session annotations
1322
+ * set by an in-process caller (the orchestration engine tags its sessions with
1323
+ * `{ orchestrationRunId, orchestrationRole }`, surfaced as optional session-list badge
1324
+ * fields). NOT settable over the wire (the create_session handler whitelists its
1325
+ * fields), and NOT persisted — in-memory only in v1; restart-reconcile re-establishes
1326
+ * it (#6743).
1111
1327
  * @returns {string} sessionId
1112
1328
  */
1113
- createSession({ name, cwd, model, permissionMode, resumeSessionId, provider, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sandbox, containerId, containerUser, containerCliPath, promptEvaluator, promptEvaluatorSkipPattern, chroxyContextHint, sessionPreamble, stdinForwardingDisabled, bootedModel, messageCounter, skipPermissions, agentCommId, skipPersist = false, preserveId, isRestore = false } = {}) {
1329
+ createSession({ name, cwd, model, permissionMode, resumeSessionId, provider, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sandbox, codexSandbox, containerId, containerUser, containerCliPath, promptEvaluator, promptEvaluatorSkipPattern, chroxyContextHint, sessionPreamble, stdinForwardingDisabled, disabledMcpServers, bootedModel, messageCounter, skipPermissions, agentCommId, metadata = null, skipPersist = false, preserveId, isRestore = false } = {}) {
1114
1330
  // #6036 — front-half SRP extraction: preflight + isolation + provider/preset
1115
1331
  // resolution (incl. the limit guard, cwd check, id/name, #2962 preflight,
1116
1332
  // #5985 user-shell gate, #3403 model fallback, worktree create/restore, and
@@ -1160,6 +1376,10 @@ export class SessionManager extends EventEmitter {
1160
1376
  // ProviderClass via getProvider() — the registry key.
1161
1377
  provider: resolvedProvider,
1162
1378
  }
1379
+ // #6638: per-session codex sandbox mode (read-only / workspace-write /
1380
+ // danger-full-access). Codex-specific opt read directly by CodexAppServerSession;
1381
+ // ignored by other providers.
1382
+ if (codexSandbox) providerOpts.codexSandbox = codexSandbox
1163
1383
  if (this._maxToolInput) providerOpts.maxToolInput = this._maxToolInput
1164
1384
  if (this._resultTimeoutMs != null) providerOpts.resultTimeoutMs = this._resultTimeoutMs
1165
1385
  if (this._hardTimeoutMs != null) providerOpts.hardTimeoutMs = this._hardTimeoutMs
@@ -1236,6 +1456,15 @@ export class SessionManager extends EventEmitter {
1236
1456
  if (stdinForwardingDisabled === true) {
1237
1457
  providerOpts.stdinForwardingDisabled = true
1238
1458
  }
1459
+ // #6824: per-session parked (disabled) MCP server names. Byok-local opt —
1460
+ // forwarded only when it's a non-empty array of strings so non-BYOK
1461
+ // providers (which ignore the unknown key via the opt picker) never see a
1462
+ // meaningless value, and older state files (no field) restore cleanly. The
1463
+ // BYOK session filters this against its own config, so a stale name is a
1464
+ // harmless no-op.
1465
+ if (Array.isArray(disabledMcpServers) && disabledMcpServers.length > 0) {
1466
+ providerOpts.disabledMcpServers = disabledMcpServers.filter((n) => typeof n === 'string')
1467
+ }
1239
1468
  // #4208 / #4209: per-session skipPermissions, with the server-wide
1240
1469
  // default as fallback. Only forwarded when truthy so non-TUI providers
1241
1470
  // never see a `skipPermissions: false` key they have to destructure
@@ -1253,6 +1482,11 @@ export class SessionManager extends EventEmitter {
1253
1482
  if (containerId) providerOpts.containerId = containerId
1254
1483
  if (containerUser) providerOpts.containerUser = containerUser
1255
1484
  if (containerCliPath) providerOpts.containerCliPath = containerCliPath
1485
+ // #6771: hand the durable per-project permission rule store to the session so
1486
+ // its PermissionManager (SDK / BYOK / codex-app-server) can seed persistent
1487
+ // rules for this cwd and persist an `allowAlways` decision. A runtime handle,
1488
+ // forwarded via BASE_SESSION_OPT_KEYS.
1489
+ providerOpts.permissionRuleStore = this.permissionRuleStore
1256
1490
  const session = new ProviderClass(providerOpts)
1257
1491
  // Pre-seed `bootedModel` from a restored snapshot so the dashboard can
1258
1492
  // surface the session's actual model immediately on reconnect, without
@@ -1308,6 +1542,11 @@ export class SessionManager extends EventEmitter {
1308
1542
  // editable into the new session's composer. Not persisted — it is
1309
1543
  // re-resolved from disk on every fresh create, and restores skip folding.
1310
1544
  sessionPreset: presetDescriptor,
1545
+ // #6691 (E-4): opaque per-session annotations set by the caller (the
1546
+ // orchestration engine tags its sessions with { orchestrationRunId,
1547
+ // orchestrationRole } for the session-list badges). In-memory only in v1 —
1548
+ // not persisted; a restart-reconcile re-establishes it (E-3 part 3).
1549
+ metadata: metadata || null,
1311
1550
  }
1312
1551
 
1313
1552
  this._sessions.set(sessionId, entry)
@@ -1669,6 +1908,21 @@ export class SessionManager extends EventEmitter {
1669
1908
  worktree: entry.worktreePath != null,
1670
1909
  repoCwd: entry.worktreeRepoDir || null,
1671
1910
  isolation: entry.isolation || 'none',
1911
+ // #6691 (E-4): orchestration badges — present only for engine-owned
1912
+ // sessions (architect / worker.*), absent otherwise. Optional on the wire
1913
+ // (ServerSessionListEntry), so a plain session omits them entirely.
1914
+ ...(entry.metadata?.orchestrationRunId ? { orchestrationRunId: entry.metadata.orchestrationRunId } : {}),
1915
+ ...(entry.metadata?.orchestrationRole ? { orchestrationRole: entry.metadata.orchestrationRole } : {}),
1916
+ // #6901: surface the active/resolved Codex sandbox mode for a running
1917
+ // codex session so a client can DISPLAY it (the optional half of #6689).
1918
+ // Only the codex session classes expose `getCodexSandbox()`, so this is a
1919
+ // provider-agnostic gate — non-codex sessions omit the field entirely
1920
+ // (mirrors the orchestration-badge spread above). Display-only: a mid-
1921
+ // session sandbox change needs a new session (Codex applies it once at
1922
+ // thread start — docs/design/codex-permission-model.md §5).
1923
+ ...(typeof entry.session.getCodexSandbox === 'function'
1924
+ ? { codexSandbox: entry.session.getCodexSandbox() }
1925
+ : {}),
1672
1926
  // #4664: per-session toggle/string settings (promptEvaluator,
1673
1927
  // chroxyContextHint, sessionPreamble) surface through the
1674
1928
  // registry so the dashboard can hydrate every knob's current
@@ -1824,6 +2078,100 @@ export class SessionManager extends EventEmitter {
1824
2078
  return true
1825
2079
  }
1826
2080
 
2081
+ /**
2082
+ * #6764 — kick off the async semantic-title upgrade for a session that was
2083
+ * just truncation-auto-labeled. Fire-and-forget: it MUST NOT block or delay the
2084
+ * first turn, so it returns immediately after guarding + scheduling the model
2085
+ * call. The once-per-session guard (`_semanticTitlePending`) is belt-and-braces
2086
+ * — `auto_label` already fires at most once per session — so a reconnect or a
2087
+ * second turn never re-triggers the call.
2088
+ *
2089
+ * @param {string} sessionId
2090
+ * @param {string} firstMessage - the untruncated first user message.
2091
+ * @param {string} fallbackLabel - the truncation label already applied.
2092
+ */
2093
+ _maybeGenerateSemanticTitle(sessionId, firstMessage, fallbackLabel) {
2094
+ if (!this._semanticTitlesEnabled) return
2095
+ const entry = this._sessions.get(sessionId)
2096
+ if (!entry) return
2097
+ if (entry._semanticTitlePending || entry._semanticTitleDone) return
2098
+ if (typeof firstMessage !== 'string' || !firstMessage.trim()) return
2099
+ entry._semanticTitlePending = true
2100
+ // Detach from the caller (the auto_label handler / the first-turn record
2101
+ // path). Errors are swallowed into a fallback inside generateSessionTitle;
2102
+ // the .catch here only guards against an unexpected throw in the apply step.
2103
+ this._generateSemanticTitle(sessionId, firstMessage, fallbackLabel).catch((err) => {
2104
+ log.warn(`Semantic title generation failed for ${sessionId}: ${getErrorMessage(err, 'unknown error')}`)
2105
+ })
2106
+ }
2107
+
2108
+ /**
2109
+ * #6764 — run the one-shot title call and, only if it yields a MODEL title,
2110
+ * replace the truncation label and broadcast the update. The truncation label
2111
+ * is already applied, so a truncation result here is a no-op. A manual rename
2112
+ * that lands while the call is in flight is respected: if the session name has
2113
+ * moved away from the truncation label we set, we leave it alone.
2114
+ *
2115
+ * @param {string} sessionId
2116
+ * @param {string} firstMessage
2117
+ * @param {string} fallbackLabel
2118
+ */
2119
+ async _generateSemanticTitle(sessionId, firstMessage, fallbackLabel) {
2120
+ try {
2121
+ // Default runner is the SDK one-shot shared with the #5547 summarizer; loaded
2122
+ // lazily so the SDK stays out of SessionManager's static import graph. Tests
2123
+ // inject `titleRunOneShot`, short-circuiting the import entirely.
2124
+ const runOneShot = this._titleRunOneShot
2125
+ || (await import('./summarize-session.js')).defaultRunOneShot
2126
+
2127
+ // Hard-bound the fire-and-forget call: AbortSignal.timeout fires after
2128
+ // _semanticTitleTimeoutMs, which threads to defaultRunOneShot →
2129
+ // query({ abortController }) so a stalled provider stream is torn down (not
2130
+ // just abandoned). generateSessionTitle catches the resulting abort rejection
2131
+ // and fails open to the truncation label. Without this the detached promise
2132
+ // could stay pending forever, leaking `this` + the first message (#6764).
2133
+ const signal = AbortSignal.timeout(this._semanticTitleTimeoutMs)
2134
+
2135
+ const { title, source } = await generateSessionTitle({
2136
+ firstUserMessage: firstMessage,
2137
+ enabled: true,
2138
+ model: this._semanticTitleModel,
2139
+ cwd: this._sessions.get(sessionId)?.cwd,
2140
+ runOneShot,
2141
+ signal,
2142
+ fallback: fallbackLabel,
2143
+ })
2144
+
2145
+ // Only a model-generated title is worth replacing the truncation with.
2146
+ if (source !== 'model' || typeof title !== 'string' || !title) return
2147
+
2148
+ const current = this._sessions.get(sessionId)
2149
+ if (!current) return // session was destroyed while the call was in flight
2150
+ current._semanticTitleDone = true
2151
+ // Respect a manual rename (or any other label change) that landed mid-flight:
2152
+ // only upgrade when the name is still exactly the truncation we applied.
2153
+ if (current.name !== fallbackLabel) return
2154
+ if (current.name === title) return // identical — nothing to broadcast
2155
+
2156
+ current.name = title
2157
+ current._autoLabeled = true
2158
+ log.info(`Semantic-titled session ${sessionId} to "${title}"`)
2159
+ this.emit('session_updated', { sessionId, name: title })
2160
+ this._flushPersistOrWarn(sessionId, title)
2161
+ } finally {
2162
+ // #6886 — clear the once-per-session in-flight guard on EVERY exit path
2163
+ // (success, the truncation/no-usable-title early return above, or a
2164
+ // thrown error), not just the success branch. Previously a failed or
2165
+ // timed-out title call left `_semanticTitlePending` stuck `true` for
2166
+ // the session's lifetime — harmless today (`auto_label` fires at most
2167
+ // once per session, so nothing re-checks the flag) but a latent trap
2168
+ // for any future retry logic keyed on it. Not persisted
2169
+ // (`_serializeSessionEntry` is field-explicit) — purely in-memory hygiene.
2170
+ const current = this._sessions.get(sessionId)
2171
+ if (current) current._semanticTitlePending = false
2172
+ }
2173
+ }
2174
+
1827
2175
  /**
1828
2176
  * Destroy a specific session.
1829
2177
  * Sets _destroying = true at the start so concurrent getSession() calls
@@ -1990,6 +2338,20 @@ export class SessionManager extends EventEmitter {
1990
2338
  return this._defaultCwd
1991
2339
  }
1992
2340
 
2341
+ /**
2342
+ * The provider id createSession falls back to when its `provider` option is
2343
+ * omitted (i.e. this daemon's configured default, DEFAULT_PROVIDER unless the
2344
+ * operator changed it). Exposed so callers that must reason about the provider a
2345
+ * session WOULD use — before creating it — resolve it the same way createSession
2346
+ * does instead of guessing. The scheduler's provider-capability gate (#6865)
2347
+ * needs exactly this: it refuses to fire an unattended run on a provider whose
2348
+ * permission prompts it cannot answer.
2349
+ * @returns {string}
2350
+ */
2351
+ get providerType() {
2352
+ return this._providerType
2353
+ }
2354
+
1993
2355
  /**
1994
2356
  * Current max messages per session (from SessionMessageHistory).
1995
2357
  * @returns {number}
@@ -2117,6 +2479,15 @@ export class SessionManager extends EventEmitter {
2117
2479
  // was not replayed. Strict-boolean coerce so non-Sdk providers
2118
2480
  // (which never set this field) round-trip as `false`.
2119
2481
  stdinForwardingDisabled: !!entry.session._stdinForwardingDisabled,
2482
+ // #6824: persist the per-session parked (disabled) MCP server set so a
2483
+ // respawn skips starting those servers. Only the BYOK lane exposes the
2484
+ // getter; other providers round-trip as [] (their MCP config is owned
2485
+ // by the claude binary, not toggleable here). Older state files (no
2486
+ // field) restore as [] → nothing parked.
2487
+ disabledMcpServers:
2488
+ typeof entry.session.getDisabledMcpServers === 'function'
2489
+ ? entry.session.getDisabledMcpServers()
2490
+ : [],
2120
2491
  // #4089: persist cumulativeUsage so the dashboard sidebar badge
2121
2492
  // (#4073) and mobile session-header badge (#4074) survive a
2122
2493
  // server restart. Without this, the badge resets to $0 on
@@ -2228,6 +2599,13 @@ export class SessionManager extends EventEmitter {
2228
2599
  // ensures no warn/error is re-emitted on restore — clients
2229
2600
  // observe the disabled state via session_list metadata.
2230
2601
  stdinForwardingDisabled: saved.stdinForwardingDisabled === true ? true : undefined,
2602
+ // #6824: forward the persisted parked MCP server set so the respawned
2603
+ // BYOK fleet skips starting them. Non-array / empty values are
2604
+ // dropped (createSession only forwards a non-empty string array), so
2605
+ // older state files restore with nothing parked.
2606
+ disabledMcpServers: Array.isArray(saved.disabledMcpServers) && saved.disabledMcpServers.length > 0
2607
+ ? saved.disabledMcpServers.filter((n) => typeof n === 'string')
2608
+ : undefined,
2231
2609
  // Restore the previously-booted model (#3700b) so the dashboard
2232
2610
  // dropdown shows the real model on reconnect, not the registry
2233
2611
  // fallback. createSession() ignores non-string / empty values so
@@ -2268,17 +2646,21 @@ export class SessionManager extends EventEmitter {
2268
2646
  // - costUsd accepts negatives per #4099 (refund / credit
2269
2647
  // adjustments). Only non-finite values fall back to 0.
2270
2648
  const restoredEntry = this._sessions.get(sessionId)
2271
- const nonNegFinite = (v) => (Number.isFinite(v) && v >= 0 ? v : 0)
2649
+ // #7082: the restore path reads ~/.chroxy/session-state.json, so a hand-edited
2650
+ // or corrupt file can carry a fractional / past-2^53 / negative counter straight
2651
+ // into the live snapshot. Same coercion as the accumulate path above.
2272
2652
  if (restoredEntry) {
2273
2653
  if (saved.cumulativeUsage && typeof saved.cumulativeUsage === 'object') {
2274
2654
  const u = saved.cumulativeUsage
2275
2655
  restoredEntry.cumulativeUsage = {
2276
- inputTokens: nonNegFinite(u.inputTokens),
2277
- outputTokens: nonNegFinite(u.outputTokens),
2278
- cacheReadTokens: nonNegFinite(u.cacheReadTokens),
2279
- cacheCreationTokens: nonNegFinite(u.cacheCreationTokens),
2656
+ inputTokens: toWireCount(u.inputTokens),
2657
+ outputTokens: toWireCount(u.outputTokens),
2658
+ cacheReadTokens: toWireCount(u.cacheReadTokens),
2659
+ cacheCreationTokens: toWireCount(u.cacheCreationTokens),
2660
+ // costUsd is NOT coerced: `z.number().finite()` with no `.int()`, and
2661
+ // legitimately negative for a refund / credit adjustment (#4099).
2280
2662
  costUsd: Number.isFinite(u.costUsd) ? u.costUsd : 0,
2281
- turnsBilled: nonNegFinite(u.turnsBilled),
2663
+ turnsBilled: toWireCount(u.turnsBilled),
2282
2664
  }
2283
2665
  }
2284
2666
  if (saved.costThresholdNotified === true) {
@@ -2873,6 +3255,12 @@ export class SessionManager extends EventEmitter {
2873
3255
  // activity tree (ActivityRegistry on BaseSession). Transient — not
2874
3256
  // replayed from history; a reconnecting client gets the full tree from
2875
3257
  // the snapshot-on-subscribe in ws-history.sendSessionInfo.
3258
+ // #6832: `mcp_servers` (sdk/cli parse it off the live stream-json
3259
+ // `system/init`; claude-tui re-derives the CONFIGURED list on warmup /
3260
+ // respawn, #6820/#6831) is likewise transient — not recorded in history —
3261
+ // but a reconnecting/late-joining client still gets the current server
3262
+ // list via BaseSession's cached last payload, replayed in
3263
+ // ws-history.sendSessionInfo's snapshot-on-subscribe (getMcpServersSnapshot).
2876
3264
  // #5936: message_queued / message_dequeued mirror the server-authoritative
2877
3265
  // outgoing-message queue (BaseSession `_outgoingQueue`). Transient (like
2878
3266
  // activity_delta) — they are delta events, NOT replayed from history. This
@@ -3017,7 +3405,7 @@ export class SessionManager extends EventEmitter {
3017
3405
  // criteria and #4088.
3018
3406
  //
3019
3407
  // Per-field coercion mirrors the restore-time clamp (restoreState's
3020
- // `nonNegFinite`) and CumulativeUsageSchema (@chroxy/protocol):
3408
+ // `toWireCount`) and CumulativeUsageSchema (@chroxy/protocol):
3021
3409
  // - Token fields are monotonic NON-NEGATIVE integer counters. A
3022
3410
  // negative provider delta (bug) would drive them below zero and
3023
3411
  // violate the schema's `.nonnegative()` contract, so drop any delta
@@ -3025,14 +3413,18 @@ export class SessionManager extends EventEmitter {
3025
3413
  // - costUsd is finite but intentionally SIGNED — a refund / credit
3026
3414
  // adjustment turn (#4099) legitimately subtracts — so only reject
3027
3415
  // a non-finite cost.
3028
- const tokenDelta = (x) => (Number.isFinite(x) && x >= 0 ? x : 0)
3416
+ // #7082: `toWireCount` adds the `.int()` half these comments always claimed to
3417
+ // mirror — the guards enforced finite + non-negative and let a fractional or
3418
+ // past-2^53 value through, both of which the schema refuses. Applied to the RUNNING
3419
+ // TOTAL, not just the delta: integer deltas keep the sum integral, but a long-lived
3420
+ // session can still accumulate past the safe-integer ceiling.
3029
3421
  const finiteCost = (x) => (Number.isFinite(x) ? x : 0)
3030
- acc.inputTokens += tokenDelta(Number(u.input_tokens))
3031
- acc.outputTokens += tokenDelta(Number(u.output_tokens))
3032
- acc.cacheReadTokens += tokenDelta(Number(u.cache_read_input_tokens))
3033
- acc.cacheCreationTokens += tokenDelta(Number(u.cache_creation_input_tokens))
3422
+ acc.inputTokens = toWireCount(acc.inputTokens + toWireCount(u.input_tokens))
3423
+ acc.outputTokens = toWireCount(acc.outputTokens + toWireCount(u.output_tokens))
3424
+ acc.cacheReadTokens = toWireCount(acc.cacheReadTokens + toWireCount(u.cache_read_input_tokens))
3425
+ acc.cacheCreationTokens = toWireCount(acc.cacheCreationTokens + toWireCount(u.cache_creation_input_tokens))
3034
3426
  acc.costUsd += finiteCost(Number(resultData?.cost))
3035
- acc.turnsBilled += 1
3427
+ acc.turnsBilled = toWireCount(acc.turnsBilled + 1)
3036
3428
  // #5630/#5629: carry the per-session billing class on the live usage
3037
3429
  // event so a client that joined before the first session_list (or after a
3038
3430
  // mid-session era flip) labels the cost row correctly without a refetch.