@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
package/src/ws-server.js CHANGED
@@ -18,8 +18,10 @@ import { createFileOps } from './ws-file-ops/index.js'
18
18
  import { createPermissionHandler } from './ws-permissions.js'
19
19
  import { setupForwarding } from './ws-forwarding.js'
20
20
  import { handleSessionMessage, handleCliMessage } from './ws-message-handlers.js'
21
- import { refuseBoundMessage } from './bound-client-policy.js'
22
- import { handleAuthMessage, handlePairMessage, handlePairRequestMessage, handleKeyExchange, BENIGN_PAIR_WINDOW_MS } from './ws-auth.js'
21
+ import { dispatchPolicyFor, isPrincipalClient, frameForPrincipal, principalMaySee, principalPolicyOptsFromCtx, sendPrincipalRefusal, PRINCIPAL_ALLOWED_MESSAGE_TYPES } from './principal-policy.js'
22
+ import { PrincipalSubscriptions } from './principal-subscriptions.js'
23
+ import { principalAuditor } from './principal-audit.js'
24
+ import { handleAuthMessage, isLoopbackConnection, handlePairMessage, handlePairRequestMessage, handleKeyExchange, BENIGN_PAIR_WINDOW_MS } from './ws-auth.js'
23
25
  import { postPairLinkToDiscord } from './discord-pair-delivery.js'
24
26
  import { sendPostAuthInfo, replayHistory, flushPostAuthQueue, sendSessionInfo, reseedActiveAgents, resendPendingQuestions, resendPendingPermissionsForSession } from './ws-history.js'
25
27
  import { createDevicePreferences } from './device-preferences.js'
@@ -46,7 +48,7 @@ import { assertCtxShape, buildMessageCtx } from './ws-handler-context.js'
46
48
  import { isLoopbackHost } from './bind-host.js'
47
49
  import { getLanIp } from './lan-ip.js'
48
50
  import { deriveWebhookPayloadUrl } from './github-webhook.js'
49
- import { isLocalOrLanPeer } from './connection-locality.js'
51
+ import { isLocalOrLanPeer, isLoopbackPeer } from './connection-locality.js'
50
52
  import { configPath } from './config-dir.js'
51
53
  import { QuestionRouteMap } from './question-route-map.js'
52
54
 
@@ -353,10 +355,16 @@ function _isSecureRequest(req) {
353
355
  * { type: 'submit_mcp_auth_code', server, code, sessionId?, requestId? } — #6822 submit a pasted OAuth authorization code for a remote MCP server (BYOK lane)
354
356
  * { type: 'add_mcp_server', name, config, scope?, sessionId?, requestId? } — #6974 ADD an MCP server, persisting it to the user's MCP config (BYOK lane; STRICT-PRIMARY gate — any non-primary token is rejected, since a configured server is a command this machine will spawn; #7001)
355
357
  * { type: 'remove_mcp_server', name, scope?, sessionId?, requestId? } — #6974 permanently REMOVE a configured MCP server from the user's MCP config (BYOK lane; same strict-primary gate)
358
+ * { type: 'trust_folder', sessionId, digest, requestId? } — trust the folder of a session so its project settings (.mcp.json, .claude/settings.json, CLAUDE.md, agents, skills, commands) load; the folder comes from the server's session record, never from the message. `digest` is the one from the folder_trust_state the owner reviewed: the daemon rescans and refuses (FOLDER_TRUST_CHANGED, or FOLDER_TRUST_UNTRUSTABLE for a folder that cannot be fully reviewed) when it differs. Tied to the exact content of the listed files: any change makes the folder untrusted again. PRIMARY-ONLY (primary token, not session-bound, no agent principal; others get FOLDER_TRUST_FORBIDDEN). Reply: folder_trust_result, then folder_trust_state to every session in that folder
359
+ * { type: 'untrust_folder', sessionId, requestId? } — stop trusting the folder of a session (same gate and reply as trust_folder)
356
360
  * { type: 'scheduled_tasks_request', requestId? } — #6871 read the standing scheduled-task registry + the scheduler gate state (host-level: a pairing-BOUND client is rejected)
357
361
  * { type: 'scheduled_task_action', action, taskId?, handle?, task?, requestId? } — #6871 create/update/pause/resume/delete a scheduled task, or (#7079) `discard_unreadable` a load-refused stored entry by its opaque server-derived `handle` (UNBOUND-STRICT-PRIMARY gate — a scheduled task makes this machine run an agent session unattended; a pairing-BOUND client is rejected even if it is primary, #7025)
358
362
  * { type: 'set_scheduler_enabled', enabled, requestId? } — #6871 flip the PERSISTED global scheduled-execution gate (features.scheduler); same unbound-strict-primary gate, and a daemon restart is required for it to take effect (reported as scheduler.restartRequired)
359
363
  * { type: 'daemon_update_action', action: 'restart-now'|'postpone', target, confirmBusy?, requestId? } — #8331 apply or hold off the update the idle-only auto-deploy has queued for the daily daemon (STRICT-PRIMARY + UNBOUND gate — restarting kills every live session; a pairing or bound client gets daemon_update_action_result{code:NOT_AUTHORIZED} and nothing is written). restart-now with busy sessions and no confirmBusy replies daemon_update_confirm_required instead of writing
364
+ * { type: 'principal_admin_grant', label, scope, sessionIds?, cwdRoots?, ttlMs?, requestId? } | { type: 'principal_admin_list', requestId? } | { type: 'principal_admin_revoke', principalId?, label?, requestId? } | { type: 'principal_admin_disable', all?: true, label?, requestId? } | { type: 'principal_admin_enable', all?: true, label?, requestId? } — #9116 agent-principal management (S11 adds the kill switch pair: disable persists a flag in the config dir and closes the affected principals' connections 4401; enable is explicit and refused while the audit log is unwritable) (STRICT-PRIMARY + UNBOUND + loopback-only; refused to bound clients and principals at dispatch). grant refuses until S11; reply is principal_admin_result
365
+ * { type: 'principal_subscribe', requestId, sessionIds[], cursors?[{ sessionId, journalId, seq }] } | { type: 'principal_unsubscribe', requestId?, sessionIds? } | { type: 'principal_events_read', requestId, sessionId, cursor?, limit? } — #9118 (S3 of #9112) the agent principal's journal read path (observe tier; every session id must be granted or the whole request is refused scope_denied); refused to every client that is not a principal; replies are principal_subscribed / principal_event / principal_live_fence / principal_gap / principal_events_page
366
+ * { type: 'principal_pending_permissions', requestId, sessionIds? } — #9119 (S4 of #9112) a read-only snapshot of the permission requests still pending on the principal's granted sessions, from the canonical state of both pipelines (observe tier; every explicit session id must be granted or the whole request is refused scope_denied, indistinguishable from a nonexistent session; omitted = every granted session); refused to every client that is not a principal; grants no decision authority; reply is principal_pending_permissions_result
367
+ * { type: 'principal_sessions_snapshot', requestId, sessionIds? } — #9120 (S5 of #9112) a read-only roster of the principal's granted sessions: observed status, declared status, handoff blockers, model requested/observed (observe tier; every explicit session id must be granted or the whole request is refused scope_denied, indistinguishable from a nonexistent session; omitted = every granted session); refused to every client that is not a principal; reply is principal_sessions_snapshot_result
360
368
  * { type: 'set_prompt_evaluator', value: boolean, sessionId? } — toggle the per-session promptEvaluator (#3185)
361
369
  * { type: 'set_prompt_evaluator_skip_pattern', value: string|null, sessionId? } — set the per-session evaluator skip-pattern source (#3639)
362
370
  * { type: 'set_chroxy_context_hint', value: boolean, sessionId? } — toggle the per-session Chroxy context hint (#3805)
@@ -393,18 +401,18 @@ function _isSecureRequest(req) {
393
401
  * { type: 'tunnel_url_changed', url, previousUrl? } — #5555 (sub-item 7): quick-tunnel recovery rotated the public URL; clients repoint their stored endpoint. Best-effort for tunnel-connected clients (their socket rode the now-dead old tunnel); durable recovery is auth_bootstrap.tunnelUrl on reconnect
394
402
  * { type: 'auth_fail', reason: '...' } — auth failed
395
403
  * { type: 'server_mode', mode: 'cli' } — which backend mode is active
396
- * { type: 'message', messageType, content, tool?, options?, timestamp, code?, subtype?, compactMetadata?, mcpPromptExpansion?, attemptedResumeId?, authCause?, stdout?, stderr?, timeoutMs?, retrySafe?, delivery?, kind?, thinkingDurationMs?, thinkingTokens?, thinkingPrecedes?, historySeq? } — parsed chat message
404
+ * { type: 'message', messageType, content, tool?, options?, timestamp, code?, subtype?, compactMetadata?, mcpPromptExpansion?, messageId?, attemptedResumeId?, authCause?, stdout?, stderr?, timeoutMs?, retrySafe?, delivery?, kind?, thinkingDurationMs?, thinkingTokens?, thinkingPrecedes?, splits?, historySeq? } — parsed chat message
397
405
  * { type: 'input_ack', sessionId, clientMessageId, status, delivery, retrySafe, retentionExpiresAt?, dedupScope, acceptedAt?, reason?, message?, context? } — #7822 correlated input validation/queue acceptance; never provider completion
398
406
  * { type: 'stream_start', messageId: '...', serverTs?, thinking?, thinkingPrecedes? } — beginning of streaming response
399
407
  * { type: 'stream_delta', messageId, delta, serverTs?, thinking? } — token-by-token text
400
408
  * { type: 'stream_end', messageId: '...', serverTs?, thinking?, thinkingDurationMs?, thinkingTokens? } — streaming response complete
401
409
  * { type: 'terminal_output', sessionId, data } — #5835 live claude-tui PTY mirror (raw, ANSI-intact, coalesced ~50ms); emitted from ws-forwarding.js to clients that opted in via terminal_subscribe; the remote-viewer / authenticity surface
402
410
  * { type: 'terminal_size', sessionId, cols, rows } — #5835 Phase 2 authoritative live-PTY grid size; sent to a client on terminal_subscribe and broadcast to all terminal subscribers on a primary-driven terminal_resize so observers re-letterbox to the same grid
403
- * { type: 'tool_start', messageId, toolUseId, tool, input, serverName?, historySeq? } — tool invocation (serverName present for MCP tools)
411
+ * { type: 'tool_start', messageId, toolUseId, tool, input, serverName?, timestamp?, historySeq? } — tool invocation (serverName present for MCP tools)
404
412
  * { type: 'tool_input_delta', messageId, toolUseId, partialJson } — #4080/#4081: incremental partial JSON for the streaming tool_use `input`; concatenate per-toolUseId for the live bubble preview
405
- * { type: 'tool_result', toolUseId, result, truncated, images?, isError?, terminatedReason?, input?, historySeq? } — tool result (images: [{mediaType, data}]; #6712 isError flags a failed tool for the error affordance)
413
+ * { type: 'tool_result', toolUseId, result, truncated, images?, isError?, terminatedReason?, input?, timestamp?, historySeq? } — tool result (images: [{mediaType, data}]; #6712 isError flags a failed tool for the error affordance)
406
414
  * { type: 'mcp_servers', servers: [{ name, status, enabled?, canToggle?, authUrl? }] } — configured MCP servers (#6824: enabled + canToggle per-server; BYOK lane sets canToggle:true so clients render the enable/disable toggle; status 'disabled' = parked; #6822: status 'oauth-required' + authUrl surfaces the browser authorization URL a remote server needs)
407
- * { type: 'result', cost?, duration?, usage?, queueLength?, contextOccupancy?, turnOutcome?, timestamp?, historySeq?, replayed? } — query stats; #8965 replayed:true marks a result the server is replaying from history; #7326 turnOutcome? ('completed'|'truncated'|'refused'|'stopped') says how the turn ended, timestamp? is the marker's identity for the marked ones
415
+ * { type: 'result', cost?, duration?, usage?, queueLength?, contextOccupancy?, turnOutcome?, timestamp?, historySeq?, replayed? } — query stats; #8965 replayed:true marks a result the server is replaying from history; #7326 turnOutcome? ('completed'|'truncated'|'refused'|'stopped'|'interrupted'|'stopped_before_output') says how the turn ended, timestamp? is the marker's identity for the marked ones
408
416
  * { type: 'status', connected: true } — connection status
409
417
  * { type: 'claude_ready', backgroundTasks?, scheduledWakeup? } — Claude Code ready for input
410
418
  * { type: 'model_changed', model: '...' } — active model updated
@@ -413,7 +421,7 @@ function _isSecureRequest(req) {
413
421
  * { type: 'permission_input', requestId, found, tool?, input?, error? } — #6543 (IDE P3 feature B) reply to a `get_permission_input` pull: the FULL secret-redacted tool input for a pending permission (the `permission_request` broadcast truncates `input` at ~10K), so a client can build a per-hunk pre-write diff. `found:false` (+ `error`) when the request is unknown / already resolved / owned by another session — the handler is session-bound (a client only gets input for a permission its session owns).
414
422
  * { type: 'permission_audit_result', entries } — #6772 reply to a `query_permission_audit` pull: recent permission audit entries (mode changes / session-rule changes / allow-deny decisions) matching the query's optional sessionId/auditType/since/limit. Consumed by the dashboard's per-session "Permission history" view.
415
423
  * { type: 'permission_request', requestId, tool, description, input, remainingMs, floored, explicitConsent?, nonDelegable?, toolUseId? } — permission prompt and consent policy; `toolUseId` (#8357) is the provider's id for the tool call, sent on a hook-routed prompt whose payload names it, and is the same id the AskUserQuestion `user_question` carries
416
- * { type: 'permission_resolved', decision, requestId?, toolUseId?, reason?, scope?, sessionId? } — a pending permission prompt was resolved (broadcast so every client drops its card). `requestId` names a tool-permission prompt; `toolUseId` instead names a superseded AskUserQuestion (#8470), never both. `reason` says why (#8374: 'stopped' vs a user deny); `scope: 'session'` marks an "Allow for Session" answer (#8517)
424
+ * { type: 'permission_resolved', decision, requestId?, toolUseId?, reason?, scope?, resolvedBy?, sessionId? } — a pending permission prompt was resolved (broadcast so every client drops its card). `requestId` names a tool-permission prompt; `toolUseId` instead names a superseded AskUserQuestion (#8470), never both. `reason` says why (#8374: 'stopped' vs a user deny); `scope: 'session'` marks an "Allow for Session" answer (#8517); `resolvedBy` ({ kind: 'user'|'agent'|'rule'|'timeout'|'auto_mode'|'abort'|'cleared', label? }, #9119) says WHAT resolved it as a class, never a token, client id or device name (`agent`, with the operator's principal label, is reserved for S15 and not produced yet; `rule` resolves before a prompt exists and is not produced either)
417
425
  * { type: 'confirm_permission_mode', mode, warning } — server challenges auto mode (client must re-send with confirmed: true)
418
426
  * { type: 'permission_mode_changed', mode: '...' } — permission mode updated
419
427
  * { type: 'available_permission_modes', modes: [...], provider? } — permission modes for ONE provider (#8224: `provider` names it; clients file the roster under it and derive the active session's picker, so a session of a provider that has no roster yet never inherits another provider's "Plan (unavailable)"). Sent with the connect burst and by `sendSessionInfo` for every session surfaced to a client
@@ -434,11 +442,14 @@ function _isSecureRequest(req) {
434
442
  * { type: 'delete_archived_session_result', ok, deleted, archiveId?, refused?, code?, message? } — reply to delete_archived_session; deleted is the number of records removed. ok:false codes: ARCHIVED_SESSION_NOT_FOUND (no such record), ARCHIVED_SESSION_DELETE_FAILED (the record could not be unlinked and is still on disk), ARCHIVED_SESSIONS_DELETE_PARTIAL (all:true; deleted went, the rest remain). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
435
443
  * { type: 'restore_archived_session_result', archiveId, mode?, ok, sessionId?, seed?{messagesIncluded,messagesTotal,bytes}, refused?, code?, message? } — reply to restore_archived_session; sessionId is the live session (switch to it). seed (new_thread) says how much of the transcript rides with the first message. The roster rows of archived_sessions_list also carry restore{native,nativeReason?,newThread,newThreadReason?} (advisory, cheap checks). ok:false codes: ARCHIVED_SESSION_NOT_FOUND, ARCHIVED_SESSION_INVALID, ARCHIVE_RESTORE_PROVIDER_UNAVAILABLE, ARCHIVE_RESTORE_FORBIDDEN_USER_SHELL, ARCHIVE_RESTORE_CWD_MISSING, ARCHIVE_RESTORE_NATIVE_UNSUPPORTED, ARCHIVE_RESTORE_LOCATOR_MISSING, ARCHIVE_RESTORE_ALREADY_LIVE (sessionId names the live/parked owner of that conversation), ENVIRONMENT_UNAVAILABLE, provider start codes, ARCHIVED_SESSION_FORBIDDEN_BOUND_CLIENT (refused:true). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
436
444
  * { type: 'session_archive_policy_result', ok, policy?{enabled,maxEntries,maxAgeDays,maxMegabytes}, deleted?, requestId?, refused?, code?, message? } — reply to set_session_archive_policy; policy is what is now in force. ok:false codes: SESSION_ARCHIVE_POLICY_INVALID, SESSION_ARCHIVE_POLICY_PERSIST_FAILED (nothing applied), SESSION_ARCHIVE_PURGE_PARTIAL (policy applied, some records could not be removed), SESSION_ARCHIVE_POLICY_FORBIDDEN_BOUND_CLIENT (refused:true). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
437
- * { type: 'session_error', message, category?, sessionId?, recoverable?, code?, reason?, requestId?, boundSessionId?, boundSessionName?, primaryClientId? } — session operation error
445
+ * { type: 'folder_trust_state', sessionId, status, summary?{files,mcpServers,hooks,statusLine,enabledPlugins,counts,warnings,hasCommandBearingFiles,untrustable}, digest?, appliesFrom, launchedWithProject? } — whether the session folder's project settings load: status trusted|untrusted (every folder starts untrusted, one with nothing command-bearing included); summary (commands and args, environment KEYS only) and digest are removed for a session-bound client; appliesFrom next_turn (claude-sdk) | restart (claude-cli, claude-tui, docker variants); a provider that does not run claude gets no frame. launchedWithProject (restart providers only): whether the RUNNING process was launched with project settings, which it keeps until it restarts. Sent when a session is ready, on subscribe/switch, and after a trust change. Handled by both clients.
446
+ * { type: 'folder_trust_result', sessionId, ok, status, error?, requestId? } — reply to trust_folder / untrust_folder to the requester; status is the folder's state after the change. Handled by both clients.
447
+ * { type: 'session_error', message, category?, sessionId?, recoverable?, code?, reason?, requestId?, boundSessionId?, boundSessionName?, primaryClientId?, attemptedSessionId?, activityId? } — session operation error
438
448
  * { type: 'history_replay_start', sessionId, fullHistory?, truncated?, conversationId?, latestSeq? } — beginning of history replay
439
449
  * { type: 'history_replay_end', sessionId, latestSeq? } — end of history replay
450
+ * { type: 'tool_input_backfill', sessionId, messageId, toolUseId?, input } — delta replay only, capability history_tool_input_backfill_v1: the input of a held tool card that has none (no historySeq; reconcile-only)
440
451
  * { type: 'conversation_id', sessionId, conversationId } — SDK conversation ID for session portability
441
- * { type: 'user_question', toolUseId, questions, historySeq?, interrupted?, superseded? } — AskUserQuestion prompt from Claude
452
+ * { type: 'user_question', toolUseId, questions, timestamp?, historySeq?, interrupted?, superseded? } — AskUserQuestion prompt from Claude
442
453
  * { type: 'agent_busy' } — agent started processing (per-session)
443
454
  * { type: 'agent_idle' } — agent finished processing (per-session)
444
455
  * { type: 'plan_started' } — Claude entered plan mode (transient)
@@ -593,6 +604,14 @@ function _isSecureRequest(req) {
593
604
  * { type: 'daemon_update_status', running, pending, lastDeploy, postponedUntil, requestPending, applying } — #8331 the queued daily-daemon update + last deploy result; sent on auth and on change to STRICT-PRIMARY, UNBOUND clients ONLY
594
605
  * { type: 'daemon_update_confirm_required', requestId, target, reasons[], sessions[] } — #8331 reply to restart-now while sessions are busy; nothing was written
595
606
  * { type: 'daemon_update_action_result', requestId, action, ok, force?, postponedUntil?, code?, message? } — #8331 outcome of daemon_update_action (codes: NOT_AUTHORIZED, STALE_TARGET, NO_PENDING_UPDATE, APPLYING, WRITE_FAILED, UNAVAILABLE, UNSUPPORTED_ACTION)
607
+ * { type: 'principal_admin_result', requestId, op: 'grant'|'list'|'revoke'|'disable'|'enable', ok, code?, message?, health?, principals?, principalId?, alreadyRevoked?, durable?, disabled? } — #9116 reply to principal_admin_grant|list|revoke|disable|enable, sent ONLY to the strict-primary, loopback requester (codes: NOT_AUTHORIZED, PRINCIPALS_NOT_ENABLED, UNAVAILABLE, BAD_REQUEST, NOT_FOUND, AUDIT_UNAVAILABLE, ALL_DISABLED, PERSIST_FAILED); `grant` always refuses until the audit writer and kill switch land; `revoke` is acknowledged only after the durable write (durable:false = revoked in memory, not confirmed on disk); carries no token and no hash
608
+ * { type: 'principal_subscribed', requestId, sessions: [{ sessionId, journalId, headSeq, gap? }] } — #9118 (S3 of #9112) reply to principal_subscribe, sent ONLY to the agent principal that asked; `gap` ({ reason, fromSeq?, toSeq? }) says the cursor could not be honored exactly (evicted, journal_reset, restart_loss, unknown_cursor)
609
+ * { type: 'principal_event', requestId?, sessionId, journalId, journalSeq, ts, eventType, data, truncated?, replay? } — #9118 one normalized, redacted journal event for a subscribed principal (never raw PTY, never thinking text); `journalSeq` not `seq`: the transport stamps its own `seq` on every frame; replay:true for a replayed event
610
+ * { type: 'principal_live_fence', requestId, sessionId, journalId, journalSeq } — #9118 end of the replay: every event after this journalSeq is live
611
+ * { type: 'principal_gap', requestId?, sessionId, journalId, reason, fromSeq?, toSeq?, ended } — #9118 events the principal cannot get (reason evicted|journal_reset|restart_loss|unknown_cursor) or, with ended:true, a subscription the daemon ended (held_overflow, backpressure): subscribe again
612
+ * { type: 'principal_events_page', requestId, sessionId, journalId, events[], headSeq, cursor, more, gap? } — #9118 reply to principal_events_read (limit <= 200); `cursor` is what the next read passes
613
+ * { type: 'principal_pending_permissions_result', requestId, generatedAt, permissions[{ requestId, sessionId, tool, floored, explicitConsent, nonDelegable, origin: 'in_process'|'hook', createdAt|null, expiresAt|null, description? }], truncated } — #9119 reply to principal_pending_permissions, sent ONLY to the agent principal that asked; at most 100 requests oldest first (`truncated` says more existed); resolved and expired requests are excluded (`generatedAt` is the freshness); `description` is the bounded, sanitised one and is present ONLY when `floored` is false; NEVER the tool input
614
+ * { type: 'principal_sessions_snapshot_result', requestId, generatedAt, sessions[{ sessionId, name, provider, status: { isBusy, busyReason: 'turn'|'background-shells'|null, starting }|null, declaredStatus: { state, summary, next?, blockedOn?, etaMinutes?, decision?, updatedAt, source }|null, model: { requested, observed }|null, blockers[{ code, detail? }], leaseHolder: null (S8), lastActivityAt|null }], truncated } — #9120 reply to principal_sessions_snapshot, sent ONLY to the agent principal that asked; at most 100 rows in request order (`truncated` says more existed); `blockers` is the #8281 handoff-blocker list (EMPTY means nothing can still act; a row whose read failed carries [{ code: 'unavailable' }], never an empty list); no cwd, history, cost or capability field
596
615
  * { type: 'orchestration_action_ack', requestId?, action, runId, gateId? } — terminal success echo for a mutating orchestration action (#6691)
597
616
  *
598
617
  * Encrypted envelope (bidirectional, wraps any message above after key exchange):
@@ -635,11 +654,26 @@ function _isSecureRequest(req) {
635
654
  * - A session operation failed in an expected, user-facing way → `session_error`
636
655
  */
637
656
  export class WsServer {
638
- constructor({ port, apiToken, cliSession, sessionManager, defaultSessionId, authRequired = true, pushManager = null, maxPayload, noEncrypt, keyExchangeTimeoutMs, localhostBypass, tokenManager, pairingManager, serverIdentity = null, maxPendingConnections, backpressureThreshold, environmentManager, orchestrationManager = null, schedulerEngine = null, sessionCiWatcher = null, daemonUpdate = null, config = null, diagnosticsRateLimit = null, devicePreferences = null, pagesStore = null, pagesRateLimiter } = {}) {
657
+ constructor({ port, apiToken, cliSession, sessionManager, defaultSessionId, authRequired = true, pushManager = null, maxPayload, noEncrypt, keyExchangeTimeoutMs, localhostBypass, tokenManager, pairingManager, serverIdentity = null, maxPendingConnections, backpressureThreshold, environmentManager, orchestrationManager = null, schedulerEngine = null, sessionCiWatcher = null, daemonUpdate = null, config = null, diagnosticsRateLimit = null, devicePreferences = null, pagesStore = null, pagesRateLimiter, principalStore = null, principalTimers = null, principalJournal = null } = {}) {
639
658
  this.port = port
640
659
  this.apiToken = apiToken
641
660
  this._tokenManager = tokenManager || null
642
661
  this._pairingManager = pairingManager || null
662
+ // #9116: the agent-principal credential store (principal-store.js). Null where the
663
+ // caller built none: then no principal can authenticate and every principal
664
+ // connection (there can be none) is treated as invalid. Timers are injectable so a
665
+ // test can drive the per-connection expiry without waiting.
666
+ this._principalStore = principalStore || null
667
+ this._principalTimers = principalTimers || { setTimeout, clearTimeout }
668
+ // #9118: the daemon-side normalized event journal (principal-journal.js) behind the
669
+ // agent principal's read path. Null where the caller built none: then nothing is
670
+ // journaled and `principal_subscribe` / `principal_events_read` refuse.
671
+ this._principalJournal = principalJournal || null
672
+ this._principalSubscriptions = null
673
+ // Journal only sessions the SessionManager currently holds (never a late frame about a gone one)
674
+ if (this._principalJournal && typeof sessionManager?.getSession === 'function') {
675
+ this._principalJournal.setLiveness((id) => sessionManager.getSession(id) != null)
676
+ }
643
677
  // #5536 — long-lived Ed25519 identity keypair. Its secret half signs each
644
678
  // connection's ephemeral exchange public key (eager + discrete paths) so a
645
679
  // pinned client can verify the exchange key came from this daemon. Null when
@@ -836,9 +870,26 @@ export class WsServer {
836
870
  // counts iterate the sessionId→clients index instead of scanning all clients.
837
871
  clientManager: this._clientManager,
838
872
  sendFn,
873
+ // A principal's frames are decided at the delivery point too (the
874
+ // broadcaster's bound-other-session drop would otherwise discard them).
875
+ principalOpts: () => self._principalPolicyOpts(),
876
+ // #9118: every outgoing session-tagged broadcast is offered once to the journal,
877
+ // whoever receives it. The journal decides what is kept.
878
+ journalTap: this._principalJournal ? (msg) => self._principalJournal.record(msg) : undefined,
839
879
  backpressureThreshold: this._backpressureThreshold,
840
880
  backpressureMaxDrops: this._backpressureMaxDrops,
841
881
  })
882
+ if (this._principalJournal) {
883
+ // Delivered by a dedicated per-subscription direct send (principal-subscriptions.js),
884
+ // each frame through `_send` -> `frameForPrincipal`; never by a broadcast.
885
+ this._principalSubscriptions = new PrincipalSubscriptions({
886
+ journal: this._principalJournal,
887
+ send: sendFn,
888
+ maySee: (client, sessionId) => client.authenticated === true &&
889
+ principalMaySee(client, sessionId, 'observe', self._principalPolicyOpts()).ok,
890
+ backpressureBytes: this._backpressureThreshold,
891
+ })
892
+ }
842
893
  const broadcastFn = (msg, filter) => self._broadcast(msg, filter)
843
894
  // Pass explicit workspace root so file ops resolve paths against the
844
895
  // session manager's default cwd instead of falling back to homedir.
@@ -977,6 +1028,13 @@ export class WsServer {
977
1028
  // `revoke_token` handler can fire the operator panic button
978
1029
  // (TokenManager.revoke()). Null when auth is disabled (--no-auth).
979
1030
  get tokenManager() { return self._tokenManager },
1031
+ // #9116: the agent-principal store and the call that ends one principal's
1032
+ // connections (revoke): the strict-primary `principal_admin_*` handlers.
1033
+ get principalStore() { return self._principalStore },
1034
+ get principalJournal() { return self._principalJournal },
1035
+ get principalSubscriptions() { return self._principalSubscriptions },
1036
+ endPrincipalConnections: (selector, reason) => self._endPrincipalConnections(selector, reason),
1037
+ drainPrincipalQueues: (selector) => self._drainPrincipalQueues(selector),
980
1038
  get devPreview() { return self._devPreview },
981
1039
  get webTaskManager() { return self._webTaskManager },
982
1040
  get environmentManager() { return self.environmentManager },
@@ -1128,6 +1186,9 @@ export class WsServer {
1128
1186
  // mode pickers and say WHY. Late-bound getter so a test mutating
1129
1187
  // self.config is seen.
1130
1188
  get autoPermissionModeAllowed() { return self.config?.allowAutoPermissionMode === true },
1189
+ // Truthful by construction: read off the manager that will actually name the session,
1190
+ // not off the config that was meant to configure it. Late-bound like its neighbours.
1191
+ get projectSessionNames() { return self.sessionManager?.sessionNaming === 'project' },
1131
1192
  // #6691: whether the orchestration harness is enabled on THIS server,
1132
1193
  // surfaced as the `orchestration` capability so the dashboard reveals the
1133
1194
  // Runs surface. Server-wide gate, not token-scoped; fail-closed.
@@ -1194,6 +1255,7 @@ export class WsServer {
1194
1255
  get authFailures() { return self._authFailures },
1195
1256
  get benignPairAttempts() { return self._benignPairAttempts },
1196
1257
  get pairingManager() { return self._pairingManager },
1258
+ get principalStore() { return self._principalStore },
1197
1259
  // #5536 — identity keypair for signing the discrete exchange public key.
1198
1260
  get serverIdentity() { return self._serverIdentity },
1199
1261
  get activeSessionId() {
@@ -1212,6 +1274,8 @@ export class WsServer {
1212
1274
  },
1213
1275
  send: sendFn,
1214
1276
  onAuthSuccess: (ws, client) => {
1277
+ // #9116: a principal connection ends at its own expiry even if it never sends.
1278
+ if (client.principal != null) self._armPrincipalExpiry(ws, client)
1215
1279
  // If paired, include sessionToken in auth_ok response
1216
1280
  if (client._sessionToken) {
1217
1281
  self._sendPostAuthInfo(ws, { sessionToken: client._sessionToken })
@@ -1336,6 +1400,14 @@ export class WsServer {
1336
1400
  const entry = sessionManager.getSession(sessionId)
1337
1401
  this._registerSessionHookSecretIfMissing(sessionId, entry)
1338
1402
  this._attachPermissionAuditSink(sessionId, entry)
1403
+ // #9118: every create or restore of an id is a NEW incarnation: a fresh journal
1404
+ try { this._principalJournal?.beginIncarnation(sessionId) } catch (err) { log.warn(`principal journal incarnation failed: ${err?.message || err}`) }
1405
+ }
1406
+ // #9118: canonical removal (every destroy path and the restore-rebind branch; never a
1407
+ // daemon shutdown, which does not pass through `_cleanupSessionMaps`): the principal
1408
+ // journal, its sidecar and its subscriptions go with the session.
1409
+ this._sessionRemovedHandler = ({ sessionId }) => {
1410
+ try { this._principalJournal?.removeSession(sessionId) } catch (err) { log.warn(`principal journal removal failed: ${err?.message || err}`) }
1339
1411
  }
1340
1412
  this._sessionDestroyedHandler = ({ sessionId }) => {
1341
1413
  // Look up the stored secret — the session is already removed from the map
@@ -1415,6 +1487,7 @@ export class WsServer {
1415
1487
  }
1416
1488
  sessionManager.on('session_created', this._sessionCreatedHandler)
1417
1489
  sessionManager.on('session_destroyed', this._sessionDestroyedHandler)
1490
+ sessionManager.on('session_removed', this._sessionRemovedHandler)
1418
1491
  sessionManager.on('session_event', this._sessionEventAuditHandler)
1419
1492
 
1420
1493
  // Retroactively register hook secrets for sessions that already exist
@@ -2307,6 +2380,10 @@ export class WsServer {
2307
2380
  // is safe: an attacker can't strip cloudflared's edge-stamped header to gain
2308
2381
  // the bypass.
2309
2382
  req._chroxyLocalPeer = localPeer
2383
+ // #9116: the strict loopback verdict (socket peer AND no proxy-family hint) taken at
2384
+ // the upgrade. A principal token is accepted only on such a connection; the retained
2385
+ // request is classified again at `auth` (ws-auth.js `isLoopbackConnection`).
2386
+ req._chroxyLoopbackPeer = isLoopbackPeer(req)
2310
2387
  if (localPeer) {
2311
2388
  delete req.headers['sec-websocket-extensions']
2312
2389
  }
@@ -2369,6 +2446,10 @@ export class WsServer {
2369
2446
  // encryption bypass so a tunneled (proxied) connection to socketIp
2370
2447
  // 127.0.0.1 is not treated as trusted-local and still requires E2E.
2371
2448
  localPeer: req._chroxyLocalPeer === true,
2449
+ // #9116: the upgrade request, retained so loopback origin is decided again at
2450
+ // `auth` and on every principal re-check, and the verdict taken at the upgrade.
2451
+ _upgradeReq: req,
2452
+ loopbackAtUpgrade: req._chroxyLoopbackPeer === true,
2372
2453
  // #3404: visible defaults to true; mobile flips to false on backgrounding
2373
2454
  // so completion push notifications fire instead of being suppressed by
2374
2455
  // a still-alive but invisible WS connection.
@@ -2739,6 +2820,17 @@ export class WsServer {
2739
2820
  return
2740
2821
  }
2741
2822
 
2823
+ // #9116: an agent principal is re-checked on EVERY frame before dispatch (credential
2824
+ // live, not expired, not revoked, store trusted, loopback origin retained). Fails
2825
+ // closed: a principal with no store is not live.
2826
+ if (client.principal != null) {
2827
+ const state = this._principalState(client)
2828
+ if (state !== 'live') {
2829
+ this._endCredentialConnection(ws, client, state)
2830
+ return
2831
+ }
2832
+ }
2833
+
2742
2834
  if (msg.type === 'auth') return
2743
2835
 
2744
2836
  // Key exchange for E2E encryption (delegates to ws-auth.js)
@@ -2788,8 +2880,20 @@ export class WsServer {
2788
2880
  // decision is not left to schema validation or to a handler. Applied before
2789
2881
  // both, so a malformed or unknown type is refused, not answered with a
2790
2882
  // schema error. (The dispatcher applies the same gate again.)
2791
- if (isBoundClient(client) &&
2792
- refuseBoundMessage(ws, client, msg, buildMessageCtx(this._handlerCtx, correlationId))) {
2883
+ //
2884
+ // The policy is chosen by ONE selector shared with handleSessionMessage: a
2885
+ // principal is refused by the principal allowlist instead of the bound one,
2886
+ // every other client by `refuseBoundMessage` as before.
2887
+ if ((isBoundClient(client) || isPrincipalClient(client)) &&
2888
+ dispatchPolicyFor(client)(ws, client, msg, buildMessageCtx(this._handlerCtx, correlationId))) {
2889
+ return
2890
+ }
2891
+
2892
+ // An agent principal is refused (not silently dropped) while the daemon drains: every
2893
+ // allowed application operation, permission_response included (the drain exemption
2894
+ // below is for human clients). Transport handling above is unchanged.
2895
+ if (this._draining && isPrincipalClient(client) && Object.hasOwn(PRINCIPAL_ALLOWED_MESSAGE_TYPES, msg?.type)) {
2896
+ sendPrincipalRefusal(ws, client, msg, buildMessageCtx(this._handlerCtx, correlationId), 'draining')
2793
2897
  return
2794
2898
  }
2795
2899
 
@@ -3212,6 +3316,7 @@ export class WsServer {
3212
3316
  _holdsPrimaryCredential(client) {
3213
3317
  if (client.boundSessionId != null) return false
3214
3318
  if (client.pairingCredential != null) return false
3319
+ if (client.principal != null) return false
3215
3320
  return client.isPrimaryToken === true || !this.authRequired
3216
3321
  }
3217
3322
 
@@ -3233,6 +3338,10 @@ export class WsServer {
3233
3338
  if (client.pairingCredential != null) {
3234
3339
  return !!this._pairingManager?.isSessionTokenLive(client.pairingCredential)
3235
3340
  }
3341
+ // #9116: a principal whose credential stopped being valid (revoked, expired, store
3342
+ // untrusted, origin no longer loopback) receives nothing, even if it never sends a
3343
+ // frame; the keepalive sweep and the expiry timer then end the connection.
3344
+ if (client.principal != null) return this._principalState(client) === 'live'
3236
3345
  return true
3237
3346
  }
3238
3347
 
@@ -3252,9 +3361,104 @@ export class WsServer {
3252
3361
  }
3253
3362
  return false
3254
3363
  }
3364
+ if (client.principal != null) {
3365
+ const state = this._principalState(client)
3366
+ if (state !== 'live') {
3367
+ for (const [ws, c] of this.clients) {
3368
+ if (c === client) { this._endCredentialConnection(ws, client, state); break }
3369
+ }
3370
+ return false
3371
+ }
3372
+ }
3255
3373
  return true
3256
3374
  }
3257
3375
 
3376
+ /**
3377
+ * Why a principal connection may not continue: 'live' when it may, otherwise
3378
+ * 'revoked', 'expired', 'disabled' (the kill switch) or 'invalid' (no store, an untrusted
3379
+ * store, an unknown grant, an origin that is no longer loopback, or audit logging down).
3380
+ * Memory only: no disk read per frame.
3381
+ * @param {object} client
3382
+ * @returns {'live'|'revoked'|'expired'|'disabled'|'invalid'}
3383
+ */
3384
+ _principalState(client) {
3385
+ const store = this._principalStore
3386
+ if (!store || client.principal == null) return 'invalid'
3387
+ if (!isLoopbackConnection(client)) return 'invalid'
3388
+ return store.state(client.principal.principalId)
3389
+ }
3390
+
3391
+ /**
3392
+ * Arm the per-connection expiry timer: at the grant's `expiresAt` the connection ends
3393
+ * with `credential_invalidated` and close code 4401, whether or not it sends anything.
3394
+ * Cleared on departure and on end.
3395
+ */
3396
+ _armPrincipalExpiry(ws, client) {
3397
+ this._clearPrincipalExpiry(client)
3398
+ const store = this._principalStore
3399
+ if (!store) return
3400
+ const delay = Math.max(0, client.principal.expiresAt - store.now())
3401
+ const timer = this._principalTimers.setTimeout(() => {
3402
+ client._principalExpiryTimer = null
3403
+ const state = this._principalState(client)
3404
+ if (state !== 'live') this._endCredentialConnection(ws, client, state === 'revoked' || state === 'disabled' ? state : 'expired')
3405
+ // Fired early (the credential is still live): keep watching for the remaining lifetime.
3406
+ else if (client.authenticated) this._armPrincipalExpiry(ws, client)
3407
+ }, delay)
3408
+ timer?.unref?.()
3409
+ client._principalExpiryTimer = timer
3410
+ }
3411
+
3412
+ _clearPrincipalExpiry(client) {
3413
+ if (client._principalExpiryTimer != null) {
3414
+ this._principalTimers.clearTimeout(client._principalExpiryTimer)
3415
+ client._principalExpiryTimer = null
3416
+ }
3417
+ }
3418
+
3419
+ /**
3420
+ * End the connections of the principals a selector names (revoke, kill): each gets
3421
+ * `credential_invalidated` and 4401. The selector is a principalId string, or
3422
+ * `{ principalId }`, `{ label }` or `{ all: true }`.
3423
+ */
3424
+ _endPrincipalConnections(selector, reason = 'revoked') {
3425
+ const sel = typeof selector === 'string' ? { principalId: selector } : (selector ?? {})
3426
+ for (const [ws, client] of [...this.clients]) {
3427
+ const p = client.principal
3428
+ if (p == null) continue
3429
+ if (sel.all === true || (sel.principalId != null && p.principalId === sel.principalId) || (sel.label != null && p.label === sel.label)) {
3430
+ this._endCredentialConnection(ws, client, reason)
3431
+ }
3432
+ }
3433
+ }
3434
+
3435
+ /**
3436
+ * Drop principal-tagged queued work for a selector and return the dropped entries so
3437
+ * the caller can audit each one (`dropped:killed`). There is NO principal queue on
3438
+ * this build (S9 adds it), so there is nothing to drop; the queue S9 builds plugs in
3439
+ * as `this._principalQueues.drain(selector)`.
3440
+ * @returns {object[]}
3441
+ */
3442
+ _drainPrincipalQueues(selector) {
3443
+ const out = this._principalQueues?.drain?.(selector)
3444
+ return Array.isArray(out) ? out : []
3445
+ }
3446
+
3447
+ /**
3448
+ * End every principal connection whose credential is no longer valid. Run by the
3449
+ * keepalive sweep, so a store that became untrusted (deleted, re-moded) or a revoke
3450
+ * made out of band cuts a connection that is sending nothing.
3451
+ */
3452
+ _recheckPrincipals() {
3453
+ const store = this._principalStore
3454
+ if (store) store.refresh()
3455
+ for (const [ws, client] of [...this.clients]) {
3456
+ if (client.principal == null || !client.authenticated) continue
3457
+ const state = this._principalState(client)
3458
+ if (state !== 'live') this._endCredentialConnection(ws, client, state)
3459
+ }
3460
+ }
3461
+
3258
3462
  /**
3259
3463
  * End a connection whose credential is no longer valid. Departure runs first
3260
3464
  * (it reads client state), the client is removed so any frame still in flight
@@ -3284,11 +3488,13 @@ export class WsServer {
3284
3488
  this._send(ws, { type: 'credential_invalidated', reason: known ? reason : 'invalid' })
3285
3489
  }
3286
3490
  if (client._keyExchangeTimeout) clearTimeout(client._keyExchangeTimeout)
3491
+ this._clearPrincipalExpiry(client)
3287
3492
  if (client.authenticated) this._handleClientDeparture(client)
3288
3493
  client.authenticated = false
3289
3494
  client.isPrimaryToken = false
3290
3495
  client.pairingCredential = null
3291
3496
  client.authToken = undefined
3497
+ if (client.principal != null) client.postAuthQueue = null
3292
3498
  this._clientManager.removeClient(ws)
3293
3499
  log.info(`Client ${client.id} ended: credential ${reason}`)
3294
3500
  try { ws.close(WS_CLOSE_CREDENTIAL_INVALID, `credential ${reason}`) } catch { /* already closing */ }
@@ -3313,6 +3519,9 @@ export class WsServer {
3313
3519
  * then `removeClient` updates the index, then we terminate the socket.
3314
3520
  */
3315
3521
  _keepaliveSweep() {
3522
+ // #9116: cut any principal connection whose credential stopped being valid, however
3523
+ // quiet it is (the outbound gate already withholds frames from it).
3524
+ if (this._principalStore || [...this.clients.values()].some((c) => c.principal != null)) this._recheckPrincipals()
3316
3525
  for (const [ws, client] of this.clients) {
3317
3526
  if (!client.authenticated) continue
3318
3527
  if (ws.readyState !== 1) continue
@@ -3340,6 +3549,9 @@ export class WsServer {
3340
3549
 
3341
3550
  /** Handle cleanup when an authenticated client disconnects or is terminated */
3342
3551
  _handleClientDeparture(departingClient) {
3552
+ this._clearPrincipalExpiry(departingClient)
3553
+ // #9118: a departing principal (disconnect, revoke, expiry) keeps no journal subscription.
3554
+ this._principalSubscriptions?.removeClient(departingClient)
3343
3555
  void this._devPreview.closeClient(departingClient.id)
3344
3556
  // #5563: vacate primary for every session this client owned. Promotion
3345
3557
  // policy is NOBODY-UNTIL-CLAIM — we clear the slot (broadcast null) rather
@@ -3526,9 +3738,29 @@ export class WsServer {
3526
3738
  return this._clientManager.hasActiveViewers(sessionId)
3527
3739
  }
3528
3740
 
3741
+ /**
3742
+ * The session lookups `frameForPrincipal` / `principalMaySee` need. The lease
3743
+ * lookup is read from `this._principalLeases` once the lease store exists (S8).
3744
+ */
3745
+ _principalPolicyOpts() {
3746
+ return principalPolicyOptsFromCtx({
3747
+ sessions: { sessionManager: this.sessionManager },
3748
+ services: { principalLeases: this._principalLeases },
3749
+ })
3750
+ }
3751
+
3529
3752
  /** Send JSON to a single client (delegates to extracted ws-client-sender) */
3530
3753
  _send(ws, message) {
3531
3754
  const client = this.clients.get(ws)
3755
+ // An agent principal is handled BEFORE the bound-other-session drop: it
3756
+ // carries a sentinel binding, so that drop would discard every frame a
3757
+ // principal may legitimately receive. Deny by default, session frames only
3758
+ // when the grant covers the session (principal-policy.js).
3759
+ if (client && isPrincipalClient(client)) {
3760
+ const frame = frameForPrincipal(client, message, this._principalPolicyOpts())
3761
+ if (frame === null) return true
3762
+ return this._clientSend(ws, client, frame)
3763
+ }
3532
3764
  // The one outgoing choke point: a session-scoped connection is sent no
3533
3765
  // host-wide frame and has host-wide fields removed from the rest.
3534
3766
  if (client && isBoundClient(client)) {
@@ -3586,6 +3818,12 @@ export class WsServer {
3586
3818
  }
3587
3819
 
3588
3820
  close() {
3821
+ // #9118: flush the journal and mark it cleanly closed, so a restart continues its
3822
+ // seq contiguously. A failure here only leaves it marked unclean (a restart then
3823
+ // treats it as a crash, which is always safe).
3824
+ try { this._principalJournal?.close() } catch (err) { log.warn(`principal journal close failed: ${err?.message || err}`) }
3825
+ // Write any collapsed refusal counts still waiting for their window to end.
3826
+ try { principalAuditor.flushRejections() } catch (err) { log.warn(`principal audit flush failed: ${err?.message || err}`) }
3589
3827
  if (this._daemonUpdate && this._daemonUpdateChangeHandler && typeof this._daemonUpdate.off === 'function') {
3590
3828
  this._daemonUpdate.off('change', this._daemonUpdateChangeHandler)
3591
3829
  this._daemonUpdateChangeHandler = null
@@ -3623,6 +3861,8 @@ export class WsServer {
3623
3861
  }
3624
3862
  if (this._sessionDestroyedHandler) {
3625
3863
  this.sessionManager.off('session_destroyed', this._sessionDestroyedHandler)
3864
+ if (this._sessionRemovedHandler) this.sessionManager.off('session_removed', this._sessionRemovedHandler)
3865
+ this._sessionRemovedHandler = null
3626
3866
  this._sessionDestroyedHandler = null
3627
3867
  }
3628
3868
  if (this._sessionEventAuditHandler) {