@chroxy/server 0.11.10 → 0.11.11

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 (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
@@ -6,6 +6,7 @@ import { terminalMirrorRecipient } from './handler-utils.js'
6
6
  import { isBoundClient } from './environments/authority.js'
7
7
  import { broadcastRosterPerRecipient } from './roster-broadcast.js'
8
8
  import { getProviderRuntimeInfo } from './providers.js'
9
+ import { buildFolderTrustStateMessageForDisplay, noteFolderTrustFrame } from './folder-trust-wire.js'
9
10
  import { MODEL_UNSUPPORTED_CODE } from './codex-model-rejections.js'
10
11
 
11
12
  const log = createLogger('ws-forwarding')
@@ -358,9 +359,12 @@ function setupSessionForwarding(normalizer, ctx) {
358
359
  // `result`. Both clients leave busy on `agent_idle` / `session_activity`,
359
360
  // which only a `result` produced, so those sessions stayed busy for good.
360
361
  // Announcing idle here covers every provider at the one place they all meet
361
- // the wire, and `stopped` stays the quiet confirmation: no `result` is
362
- // minted, so no marker or chip can follow. Skipped when the same turn end
363
- // already went idle through a `result`.
362
+ // the wire, and `stopped` stays the quiet confirmation. #9241: BaseSession.emit
363
+ // now mints a `result` carrying the `stopped_before_output` marker ahead of a
364
+ // `stopped` for a Stop that came before any output, and that result idles the
365
+ // client first (`idledByResultThisTick`); every other requested Stop still has no
366
+ // `result`, so no chip. Skipped when the same turn end already went idle through
367
+ // a `result`.
364
368
  let announceIdle = false
365
369
  if (event === 'stopped' && !idledByResultThisTick.has(sessionId)) {
366
370
  announceIdle = true
@@ -795,6 +799,22 @@ function executeSideEffects(sideEffects, sessionId, ctx) {
795
799
  }
796
800
  break
797
801
  }
802
+ case 'folder_trust_refresh': {
803
+ // A `ready` that found no fresh cached trust state: send the frame when the
804
+ // scan resolves, unless the session is gone by then. Display only.
805
+ const sid = effect.sessionId ?? sessionId
806
+ const entry = sessionManager?.getSession(sid)
807
+ if (entry && broadcastToSession) {
808
+ buildFolderTrustStateMessageForDisplay(sid, entry).then((frame) => {
809
+ if (!frame || !sessionManager.getSession(sid)) return
810
+ noteFolderTrustFrame(sessionManager, frame)
811
+ broadcastToSession(sid, withServerTs(frame))
812
+ }).catch((err) => {
813
+ log.debug(`folder trust refresh failed for ${sid}: ${err?.message || err}`)
814
+ })
815
+ }
816
+ break
817
+ }
798
818
  case 'log':
799
819
  log.info(effect.message)
800
820
  break
@@ -89,6 +89,11 @@
89
89
  * @property {object|null} schedulerEngine - #6871 scheduled-task engine; null when scheduling is off.
90
90
  * @property {object|null} sessionCiWatcher - #7427 SessionCiWatcher, so an on-demand PR survey can arm the watch; null when `sessionCi.watch` is off.
91
91
  * @property {object|null} daemonUpdate - #8331 DaemonUpdateStatus (pending-update banner + restart-now / postpone request files); null when not wired.
92
+ * @property {object|null} principalStore - #9116: the agent-principal store (principal-store.js) behind the strict-primary `principal_admin_*` handlers. Null where none was built.
93
+ * @property {object|null} principalJournal - #9118: the daemon-side normalized event journal (principal-journal.js) behind `principal_events_read`. Null where none was built.
94
+ * @property {object|null} principalSubscriptions - #9118: the per-client journal subscriptions (principal-subscriptions.js) behind `principal_subscribe`. Null where none was built.
95
+ * @property {(selector: string | { principalId?: string, label?: string, all?: true }, reason?: string) => void} endPrincipalConnections - #9116: end every connection of the principal(s) a selector names (a principalId, or S11's label / all) (credential_invalidated + close 4401); called after a revoke is acknowledged.
96
+ * @property {(selector: { principalId?: string, label?: string, all?: true }) => object[]} drainPrincipalQueues - S11: drop principal-tagged queued work for a selector and return the dropped entries (empty until S9 builds the queue); the revoke and disable paths write one `dropped:<reason>` audit line per entry.
92
97
  *
93
98
  * @typedef {Object} WsHandlerRuntime
94
99
  * @property {boolean} draining - True while the server is draining for shutdown.
@@ -211,6 +216,19 @@ export const CTX_NAMESPACES = {
211
216
  // not build one; the `daemon_update_action` handler reports that as
212
217
  // UNAVAILABLE rather than pretending an update can be applied.
213
218
  'daemonUpdate',
219
+ // #9116: the agent-principal store (principal-store.js) behind the strict-primary
220
+ // `principal_admin_*` handlers, and the call that ends a revoked principal's
221
+ // connections (4401). Null / absent where server-cli built no store.
222
+ 'principalStore',
223
+ 'endPrincipalConnections',
224
+ // S11: drops principal-tagged queued work for a selector and returns the dropped
225
+ // entries (empty until S9 builds the queue); the revoke / disable paths audit each one.
226
+ 'drainPrincipalQueues',
227
+ // #9118: the agent principal's read path (S3): the event journal and the per-client
228
+ // subscriptions to it. Null where server-cli built none; the `principal_*` read
229
+ // handlers then refuse rather than pretend there is history.
230
+ 'principalJournal',
231
+ 'principalSubscriptions',
214
232
  ],
215
233
  runtime: [
216
234
  'draining',
package/src/ws-history.js CHANGED
@@ -7,9 +7,11 @@
7
7
  import { toShortModelId, getRegistryForProvider, resolveRosterProvider } from './models.js'
8
8
  import { getPermissionModes } from './handler-utils.js'
9
9
  import { buildThinkingLevelChanged } from './thinking-level-wire.js'
10
+ import { buildFolderTrustStateMessageForDisplay, noteFolderTrustFrame } from './folder-trust-wire.js'
10
11
  import { listProviders, getProvider, getProviderRuntimeInfo, resolveDaemonDefaultProvider } from './providers.js'
11
12
  import { createLogger } from './logger.js'
12
13
  import { isBoundClient } from './environments/authority.js'
14
+ import { sendRawTransport, isPrincipalClient } from './principal-policy.js'
13
15
  import { streamKindOf, permissionOutcomeDecision } from './session-message-history.js'
14
16
  import { createKeyPair, deriveSharedKey, deriveConnectionKey, signExchangeKey } from '@chroxy/store-core/crypto'
15
17
  import { DEFAULT_RESULT_TIMEOUT_MS, DEFAULT_HARD_TIMEOUT_MS, DEFAULT_STREAM_STALL_TIMEOUT_MS } from './base-session.js'
@@ -347,6 +349,21 @@ export const CAPABILITY_HISTORY_QUESTION_SUPERSEDED = 'history_question_supersed
347
349
  */
348
350
  export const CAPABILITY_HISTORY_INFLIGHT_REPLY = 'history_inflight_reply_v1'
349
351
 
352
+ /**
353
+ * #8415: the client capability that says "I can apply a `tool_input_backfill` frame". A
354
+ * delta replay starts after the client's cursor, so the input the server learned for a
355
+ * tool card the client already holds (recorded without it) never reached it. A client
356
+ * that advertises this is sent that input as a reconcile-only frame; an older build does
357
+ * not know the frame and is sent nothing.
358
+ */
359
+ export const CAPABILITY_HISTORY_TOOL_INPUT_BACKFILL = 'history_tool_input_backfill_v1'
360
+
361
+ // #8415: private tag on a replay-slice item that is a `tool_input_backfill` frame, not
362
+ // a history entry. It lets the frames ride the same chunked, backpressure-aware,
363
+ // abort-guarded loop as the entries without passing through `sendHistoryEntry`
364
+ // (which would stamp `historySeq` on them).
365
+ const TOOL_INPUT_BACKFILL_FRAME = Symbol('toolInputBackfillFrame')
366
+
350
367
  /**
351
368
  * Write ONE history entry to a client, the way BOTH replay paths must.
352
369
  *
@@ -384,11 +401,18 @@ export const CAPABILITY_HISTORY_INFLIGHT_REPLY = 'history_inflight_reply_v1'
384
401
  * @param {WebSocket} ws
385
402
  * @param {string} sessionId
386
403
  * @param {object} entry - A ring-buffer entry, possibly carrying `_seq`.
387
- * @param {{clientCapabilities?: Set<string>}|null} [client] - The client RECORD
388
- * (`clients.get(ws)`), which is where the auth handshake stores the capabilities
389
- * it advertised. NOT `ws`: that is the raw socket and carries none (#8374).
404
+ * @param {{clientCapabilities?: Set<string>}|null} client - REQUIRED. The client
405
+ * RECORD (`clients.get(ws)`), which is where the auth handshake stores the
406
+ * capabilities it advertised. NOT `ws`: that is the raw socket and carries none
407
+ * (#8374). Omitting it (`undefined`) throws: a caller that forgot it used to
408
+ * downgrade every client to the older shape without a sound (#8431). `null` is
409
+ * the explicit, deliberate "no record, no capabilities" and is the only way to
410
+ * ask for that.
390
411
  */
391
- export function sendHistoryEntry(send, ws, sessionId, entry, client = null, isSessionBusy = () => false) {
412
+ export function sendHistoryEntry(send, ws, sessionId, entry, client, isSessionBusy = () => false) {
413
+ if (client === undefined) {
414
+ throw new TypeError('sendHistoryEntry: `client` is required (pass clients.get(ws), or null for a deliberately capability-less replay)')
415
+ }
392
416
  // #6630: a recorded error goes only to a client that said it can take one in a
393
417
  // replay (see CAPABILITY_HISTORY_ERROR_REPLAY). Skipped, not downgraded: there is
394
418
  // no older shape of an error bubble that is safe. Nothing else about the entry
@@ -518,6 +542,11 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
518
542
  // disable Auto in their mode pickers and say why. Optional — absent →
519
543
  // false (fail-closed) for old callers / test harnesses.
520
544
  autoPermissionModeAllowed,
545
+ // Whether this daemon names an unnamed new session after its project ("chroxy 7"),
546
+ // i.e. SessionManager runs with sessionNaming 'project'. Surfaced as the
547
+ // `projectSessionNames` capability so a client can stop prefilling/requiring a name.
548
+ // Optional — absent → false (fail-closed): an older daemon keeps today's client behaviour.
549
+ projectSessionNames,
521
550
  // #6006: whether the server has a rotating TokenManager (i.e. auth is on),
522
551
  // so the operator panic button (`revoke_token`) can fire. Surfaced as the
523
552
  // `tokenRevoke` capability, gated to primary-token clients below. Optional —
@@ -773,6 +802,8 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
773
802
  // a client only whether the config gate would admit a switch, so it can
774
803
  // disable Auto with the real reason instead of a generic tooltip.
775
804
  autoPermissionMode: autoPermissionModeAllowed === true,
805
+ // Unnamed sessions are named after their project by this daemon (sessionNaming 'project').
806
+ projectSessionNames: projectSessionNames === true,
776
807
  // #6871 (epic #6784): this server has the scheduled-tasks WS surface
777
808
  // (scheduled_tasks_request / scheduled_task_action / set_scheduler_enabled +
778
809
  // the `scheduled_tasks` snapshot). CONSTANT true — deliberately NOT tied to
@@ -872,11 +903,12 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
872
903
  // different one is stale. Omitted (not null) when no dist is built.
873
904
  ...(dashboardBuildId ? { dashboardBuildId } : {}),
874
905
  serverCommit: gitInfo.commit,
875
- cwd: sessionInfo.cwd,
906
+ // A principal is told nothing about any session or peer at the source (#9116).
907
+ cwd: isPrincipalClient(client) ? null : sessionInfo.cwd,
876
908
  // A session-scoped connection is told about its own session only: not the
877
909
  // host's default working directory, and only the peers sharing its session.
878
910
  defaultCwd: isBoundClient(client) ? null : (sessionManager?.defaultCwd || null),
879
- connectedClients: getConnectedClientList(client),
911
+ connectedClients: isPrincipalClient(client) ? [] : getConnectedClientList(client),
880
912
  encryption: requireEncryption ? 'required' : 'disabled',
881
913
  protocolVersion,
882
914
  minProtocolVersion,
@@ -964,7 +996,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
964
996
  client.encryptionPending = false
965
997
  client.postAuthQueue = null
966
998
  try {
967
- ws.send(JSON.stringify({ type: 'server_error', message: 'Encryption required but key exchange timed out. Please reconnect.', recoverable: false }))
999
+ sendRawTransport(ws, client, { type: 'server_error', message: 'Encryption required but key exchange timed out. Please reconnect.', recoverable: false })
968
1000
  } catch (_) {}
969
1001
  // Guard close() too: if the socket is already CLOSING/CLOSED when this
970
1002
  // timer fires (a race with a concurrent client disconnect), a bare
@@ -977,6 +1009,13 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
977
1009
  }, keyExchangeTimeoutMs)
978
1010
  }
979
1011
 
1012
+ // #9116: an agent principal's bootstrap ENDS at auth_ok (plus the key exchange it
1013
+ // gates). It is sent no session list, no replay and none of the host-wide burst below:
1014
+ // its reads are the `principal_*` family, and what it may see is decided per frame at
1015
+ // the outgoing choke point. Stopping here also keeps the sentinel binding out of every
1016
+ // bound-session lookup that follows.
1017
+ if (isPrincipalClient(client)) return
1018
+
980
1019
  // Confirm the credential through the completed transport independently of catalogs.
981
1020
  if (extra.sessionToken && client.clientCapabilities?.has('paired_credential_confirmation_v1')) {
982
1021
  send(ws, { type: 'auth_bootstrap', credentialConfirmation: true, sessionToken: extra.sessionToken })
@@ -1534,6 +1573,18 @@ export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
1534
1573
  }
1535
1574
  }
1536
1575
 
1576
+ // Whether the session folder's project settings are loaded, so the banner
1577
+ // shows on a switch or a fresh subscribe and not only after the next turn.
1578
+ // The scan runs on a worker thread, so it neither delays nor reorders any frame
1579
+ // above or below; the frame itself is sent strictly after them.
1580
+ buildFolderTrustStateMessageForDisplay(sessionId, entry)
1581
+ .then((trustMsg) => {
1582
+ if (!trustMsg) return
1583
+ noteFolderTrustFrame(ctx.sessionManager, trustMsg)
1584
+ send(ws, trustMsg)
1585
+ })
1586
+ .catch((err) => { log.debug?.(`folder trust state failed: ${err?.message}`) })
1587
+
1537
1588
  // #5731 T5 / #5623 / #5613: re-sync the session's primary owner so the
1538
1589
  // presence badge ("Observing" / "Take over" / driver name) doesn't go
1539
1590
  // stale across a reconnect or tab switch. `session_role` is otherwise only
@@ -1892,7 +1943,7 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1892
1943
  // replay would re-send (and, with mismatched ids, duplicate) them. Forcing a
1893
1944
  // full rebuild on switch keeps the long-standing authoritative-replace
1894
1945
  // semantics and the atomic swap (#5555.4) hides the rebuild with no flash.
1895
- const client = clients && typeof clients.get === 'function' ? clients.get(ws) : null
1946
+ const client = (clients && typeof clients.get === 'function' ? clients.get(ws) : null) ?? null
1896
1947
  const lastSeq = opts.forceFull ? undefined : client?.historyCursors?.[sessionId]
1897
1948
 
1898
1949
  // `latestSeq` rides the start frame so the client can advance its cursor even
@@ -1970,11 +2021,24 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1970
2021
  const pending = client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_INFLIGHT_REPLY)
1971
2022
  ? pendingStreamEntries(sessionManager, sessionId)
1972
2023
  : []
1973
- const replayEntries = pending.length > 0
1974
- ? spliceInPendingStreams(history.slice(startOffset), pending)
2024
+ // #8415 -- DELTA replays only: a full replay's `tool_start` entries carry their
2025
+ // input. The frames lead the slice (after `history_replay_start`, before the end).
2026
+ // The typeof guard tolerates stub/test managers. The frames carry the stored input,
2027
+ // already capped by sanitizeToolInput, so there is no second cap here.
2028
+ const backfills = !fullHistory && typeof lastSeq === 'number'
2029
+ && typeof sessionManager.getToolInputBackfills === 'function'
2030
+ && client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_TOOL_INPUT_BACKFILL)
2031
+ ? sessionManager.getToolInputBackfills(sessionId, lastSeq).map((b) => ({
2032
+ [TOOL_INPUT_BACKFILL_FRAME]: { ...b, type: 'tool_input_backfill', sessionId },
2033
+ }))
2034
+ : []
2035
+ const replayEntries = pending.length > 0 || backfills.length > 0
2036
+ ? [...backfills, ...(pending.length > 0
2037
+ ? spliceInPendingStreams(history.slice(startOffset), pending)
2038
+ : history.slice(startOffset))]
1975
2039
  : history
1976
2040
  sendChunkedWithBackpressure(ws, replayEntries, {
1977
- startOffset: pending.length > 0 ? 0 : startOffset,
2041
+ startOffset: pending.length > 0 || backfills.length > 0 ? 0 : startOffset,
1978
2042
  // #9015: a throwing entry ABORTS the replay and never claims completion (no
1979
2043
  // `history_replay_end` carrying `latestSeq` — the client would commit a
1980
2044
  // partial transcript and its cursor). Permission recovery is independent of
@@ -1983,7 +2047,8 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1983
2047
  // stops and `finishReplay` never runs) and then rethrows, as before.
1984
2048
  emit: (entry) => {
1985
2049
  try {
1986
- sendHistoryEntry(send, ws, sessionId, entry, client, isSessionBusy)
2050
+ if (entry[TOOL_INPUT_BACKFILL_FRAME]) send(ws, entry[TOOL_INPUT_BACKFILL_FRAME])
2051
+ else sendHistoryEntry(send, ws, sessionId, entry, client, isSessionBusy)
1987
2052
  } catch (err) {
1988
2053
  try {
1989
2054
  resendPendingPermissionsForSession(ctx, ws, sessionId)
@@ -2022,6 +2087,8 @@ function pendingStreamEntries(sessionManager, sessionId) {
2022
2087
  messageType: 'response',
2023
2088
  content: s.content,
2024
2089
  messageId: s.messageId,
2090
+ // #9024: where tool calls have interrupted it so far, as the closing entry will say.
2091
+ ...(s.splits?.length ? { splits: s.splits } : {}),
2025
2092
  timestamp: now,
2026
2093
  },
2027
2094
  }))
@@ -8,7 +8,7 @@
8
8
  * (or create a new one) and add the import here.
9
9
  */
10
10
  import { createLogger } from './logger.js'
11
- import { refuseBoundMessage } from './bound-client-policy.js'
11
+ import { dispatchPolicyFor } from './principal-policy.js'
12
12
  import { inputHandlers } from './handlers/input-handlers.js'
13
13
  import { sessionHandlers } from './handlers/session-handlers.js'
14
14
  import { settingsHandlers } from './handlers/settings-handlers.js'
@@ -29,6 +29,8 @@ import { schedulerHandlers } from './handlers/scheduler-handlers.js'
29
29
  import { sessionPrStatusHandlers } from './handlers/session-pr-status-handlers.js'
30
30
  import { sessionPrThreadsHandlers } from './handlers/session-pr-threads-handlers.js'
31
31
  import { daemonUpdateHandlers } from './handlers/daemon-update-handlers.js'
32
+ import { principalAdminHandlers } from './handlers/principal-admin-handlers.js'
33
+ import { principalHandlers } from './handlers/principal-handlers.js'
32
34
 
33
35
  const log = createLogger('ws')
34
36
 
@@ -54,6 +56,8 @@ const handlerRegistry = new Map([
54
56
  ...Object.entries(sessionPrStatusHandlers),
55
57
  ...Object.entries(sessionPrThreadsHandlers),
56
58
  ...Object.entries(daemonUpdateHandlers),
59
+ ...Object.entries(principalAdminHandlers),
60
+ ...Object.entries(principalHandlers),
57
61
  ])
58
62
 
59
63
  /**
@@ -108,7 +112,11 @@ export async function handleSessionMessage(ws, client, msg, ctx) {
108
112
  // Applied here, before the handler is even looked up, so a handler cannot be
109
113
  // reached by forgetting a check of its own — including one registered at
110
114
  // runtime through registerMessageHandler.
111
- if (refuseBoundMessage(ws, client, msg, ctx)) return
115
+ //
116
+ // One selector, shared with the pre-schema gate in ws-server.js: a principal
117
+ // goes to the principal allowlist INSTEAD of the bound one (never both), every
118
+ // other client keeps `refuseBoundMessage` unchanged (principal-policy.js).
119
+ if (dispatchPolicyFor(client)(ws, client, msg, ctx)) return
112
120
  const handler = handlerRegistry.get(msg.type)
113
121
  if (handler) {
114
122
  // Errors propagate to _handleMessage in ws-server.js, which emits a