@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
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Agent-principal management over WebSocket (agent-principals.md §3.1 "Management
3
+ * surface"): `principal_admin_grant`, `principal_admin_list`, `principal_admin_revoke`.
4
+ *
5
+ * Each is STRICT-PRIMARY and LOOPBACK-ONLY, and the gate is the FIRST statement of the
6
+ * handler: `isPrimaryToken === true`, no session binding, no principal stamp, and an
7
+ * upgrade request that still passes `isLoopbackPeer`. A pairing token, a bound token and
8
+ * a principal are all refused, and every other gate in this module sits behind that one.
9
+ * The daemon is the only writer of the principal store; the CLI asks the daemon.
10
+ *
11
+ * `grant` REFUSES ("agent principals not yet enabled") until the audit writer and kill
12
+ * switch land (§12 landing order). There is no mint path behind the refusal.
13
+ *
14
+ * `revoke` and `disable` follow the §10.2 order: flip in memory, persist durably (file
15
+ * fsync, rename, directory fsync), acknowledge, then end the affected principals'
16
+ * connections with `credential_invalidated` and close code 4401, then drain their queued
17
+ * work with one `dropped:<reason>` audit line per entry.
18
+ *
19
+ * `disable` is a safety brake: it proceeds even when the audit write fails (its line is
20
+ * best effort). `enable` is the permissive direction: it REFUSES when the audit line
21
+ * cannot be written, and is never automatic.
22
+ */
23
+ import { createLogger } from '../logger.js'
24
+ import { isLoopbackPeer } from '../connection-locality.js'
25
+ import { PRINCIPALS_NOT_ENABLED_MESSAGE, PRINCIPAL_LABEL_PATTERN } from '../principal-store.js'
26
+ import { principalAuditor } from '../principal-audit.js'
27
+
28
+ const log = createLogger('principal-admin')
29
+
30
+ function reply(ws, ctx, msg, op, fields) {
31
+ ctx.transport.send(ws, {
32
+ type: 'principal_admin_result',
33
+ requestId: typeof msg?.requestId === 'string' ? msg.requestId : null,
34
+ op,
35
+ ...fields,
36
+ })
37
+ }
38
+
39
+ /** The strict-primary, unbound, non-principal, loopback gate. True when the caller may proceed. */
40
+ function mayAdminister(client) {
41
+ return client?.isPrimaryToken === true && !client.boundSessionId && !client.principal &&
42
+ isLoopbackPeer(client._upgradeReq)
43
+ }
44
+
45
+ function refuseUnauthorized(ws, client, msg, ctx, op) {
46
+ log.warn(`Denied ${op} from ${client?.id ?? 'a client'} (NOT_AUTHORIZED)`)
47
+ reply(ws, ctx, msg, op, { ok: false, code: 'NOT_AUTHORIZED', message: 'Managing agent principals requires the primary token from this machine.' })
48
+ }
49
+
50
+ function handlePrincipalAdminGrant(ws, client, msg, ctx) {
51
+ if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'grant')
52
+ reply(ws, ctx, msg, 'grant', { ok: false, code: 'PRINCIPALS_NOT_ENABLED', message: PRINCIPALS_NOT_ENABLED_MESSAGE })
53
+ }
54
+
55
+ function handlePrincipalAdminList(ws, client, msg, ctx) {
56
+ if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'list')
57
+ const store = ctx.services?.principalStore
58
+ if (!store) {
59
+ reply(ws, ctx, msg, 'list', { ok: false, code: 'UNAVAILABLE', message: 'The principal store is not available on this server.' })
60
+ return
61
+ }
62
+ const { health, principals } = store.list()
63
+ reply(ws, ctx, msg, 'list', {
64
+ ok: true,
65
+ health: { ok: health.ok, status: health.status, reason: health.reason },
66
+ principals,
67
+ })
68
+ }
69
+
70
+ function handlePrincipalAdminRevoke(ws, client, msg, ctx) {
71
+ if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'revoke')
72
+ const store = ctx.services?.principalStore
73
+ if (!store) {
74
+ reply(ws, ctx, msg, 'revoke', { ok: false, code: 'UNAVAILABLE', message: 'The principal store is not available on this server.' })
75
+ return
76
+ }
77
+ const selector = typeof msg.principalId === 'string' && msg.principalId.length > 0
78
+ ? { principalId: msg.principalId }
79
+ : (typeof msg.label === 'string' && msg.label.length > 0 ? { label: msg.label } : null)
80
+ if (selector === null) {
81
+ reply(ws, ctx, msg, 'revoke', { ok: false, code: 'BAD_REQUEST', message: 'Name a principal by principalId or label.' })
82
+ return
83
+ }
84
+ // Memory first, then the durable write (inside store.revoke), then the verdict.
85
+ const out = store.revoke(selector)
86
+ if (!out.found) {
87
+ reply(ws, ctx, msg, 'revoke', { ok: false, code: 'NOT_FOUND', message: 'No such live principal.' })
88
+ return
89
+ }
90
+ log.warn(`Principal ${out.principalId} revoked by client ${client.id} (durable=${out.durable})`)
91
+ // A revoke is a brake too: its outcome line is best effort and never blocks it.
92
+ auditorOf(ctx).outcome({ principalId: out.principalId, label: out.label }, { action: 'revoke', requestId: msg.requestId }, 'revoked', out.durable ? 'durable' : 'not_durable')
93
+ reply(ws, ctx, msg, 'revoke', {
94
+ ok: true,
95
+ principalId: out.principalId,
96
+ alreadyRevoked: out.alreadyRevoked,
97
+ durable: out.durable,
98
+ ...(out.durable ? {} : { message: 'Revoked in this process but NOT durable: a restart before a successful write can revive it. Revoke again once the store is writable.' }),
99
+ })
100
+ // The revoke is acknowledged; now cut the principal's connections.
101
+ ctx.services?.endPrincipalConnections?.(out.principalId, 'revoked')
102
+ dropQueuedWork(ctx, { principalId: out.principalId }, 'revoked')
103
+ }
104
+
105
+ /** `{ all: true }` or `{ label }`, never both, never neither; a label must be well formed. */
106
+ function parseSwitchSelector(msg) {
107
+ const hasAll = msg?.all === true
108
+ const hasLabel = typeof msg?.label === 'string' && msg.label.length > 0
109
+ if (hasAll === hasLabel) return null
110
+ if (hasAll) return { all: true }
111
+ return PRINCIPAL_LABEL_PATTERN.test(msg.label) ? { label: msg.label } : null
112
+ }
113
+
114
+ function auditorOf(ctx) {
115
+ return ctx.services?.principalAuditor ?? principalAuditor
116
+ }
117
+
118
+ /**
119
+ * Drain principal-tagged queued work (the S9 queue, absent on this build: the hook
120
+ * returns nothing) and write one `dropped:<reason>` outcome line per dropped entry. A
121
+ * failing drain is logged and never blocks the brake: the credential is already dead
122
+ * and a queue's delivery path must re-check it (contract 6.5).
123
+ */
124
+ function dropQueuedWork(ctx, selector, reason) {
125
+ let dropped = []
126
+ try {
127
+ const out = ctx.services?.drainPrincipalQueues?.(selector)
128
+ dropped = Array.isArray(out) ? out : []
129
+ } catch (err) {
130
+ log.error(`Draining principal queues failed: ${err?.message || err}`)
131
+ }
132
+ const auditor = auditorOf(ctx)
133
+ for (const entry of dropped) {
134
+ auditor.outcome({ principalId: entry?.principalId, label: entry?.label }, { action: 'enqueue', ...entry, text: undefined }, `dropped:${reason}`, reason)
135
+ }
136
+ return dropped.length
137
+ }
138
+
139
+ function describeSelector(selector) {
140
+ return selector.all === true ? 'all agent principals' : `label ${selector.label}`
141
+ }
142
+
143
+ function handlePrincipalAdminDisable(ws, client, msg, ctx) {
144
+ if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'disable')
145
+ const sw = ctx.services?.principalStore?.brakes?.killSwitch
146
+ if (!sw) {
147
+ reply(ws, ctx, msg, 'disable', { ok: false, code: 'UNAVAILABLE', message: 'The agent kill switch is not available on this server.' })
148
+ return
149
+ }
150
+ const selector = parseSwitchSelector(msg)
151
+ if (selector === null) {
152
+ reply(ws, ctx, msg, 'disable', { ok: false, code: 'BAD_REQUEST', message: 'Name exactly one of all: true or a label.' })
153
+ return
154
+ }
155
+ // 1. Memory first (inside disable): from here principal auth and every principal frame
156
+ // are refused. 2. Then the durable write (file fsync, rename, directory fsync).
157
+ const out = sw.disable(selector)
158
+ if (!out.ok) {
159
+ reply(ws, ctx, msg, 'disable', { ok: false, code: out.code, message: out.code === 'TOO_MANY_LABELS' ? 'Too many disabled labels: nothing was changed. Use --all to disable every agent.' : 'Could not apply the request.' })
160
+ return
161
+ }
162
+ // The kill is a SAFETY BRAKE: it proceeds whether or not this line can be written
163
+ // (the writer's verdict is deliberately ignored here), unlike `enable`.
164
+ auditorOf(ctx).outcome(null, { action: 'disable', requestId: msg.requestId, ...(selector.label ? { label: selector.label } : {}) }, 'killed', selector.all === true ? 'all' : 'label')
165
+ log.warn(`Agent principals disabled (${describeSelector(selector)}) by client ${client.id} (durable=${out.durable})`)
166
+ // 3. Ack, carrying the durability verdict. Memory stays disabled when it is false.
167
+ reply(ws, ctx, msg, 'disable', {
168
+ ok: true,
169
+ durable: out.durable,
170
+ disabled: out.state,
171
+ ...(out.durable ? {} : { message: 'Disabled in this process but NOT durable: a restart before a successful write can revive the principals. Disable again once the config directory is writable.' }),
172
+ })
173
+ // 4. Cut the affected connections (4401). 5. Drain their queued work. 6. Leases: none exist
174
+ // yet (S8), which releases them when it lands.
175
+ ctx.services?.endPrincipalConnections?.(selector, 'disabled')
176
+ dropQueuedWork(ctx, selector, 'killed')
177
+ }
178
+
179
+ const ENABLE_REFUSAL_MESSAGES = {
180
+ ALL_DISABLED: 'Every agent is disabled: re-enable with --all.',
181
+ PERSIST_UNCONFIRMED: 'The enable was not confirmed on disk, so the daemon stays disabled. The file may already read "enabled", so a restart could apply it: run enable again once the disk is healthy, or run disable to make the disabled state durable.',
182
+ }
183
+
184
+ function handlePrincipalAdminEnable(ws, client, msg, ctx) {
185
+ if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'enable')
186
+ const sw = ctx.services?.principalStore?.brakes?.killSwitch
187
+ if (!sw) {
188
+ reply(ws, ctx, msg, 'enable', { ok: false, code: 'UNAVAILABLE', message: 'The agent kill switch is not available on this server.' })
189
+ return
190
+ }
191
+ const selector = parseSwitchSelector(msg)
192
+ if (selector === null) {
193
+ reply(ws, ctx, msg, 'enable', { ok: false, code: 'BAD_REQUEST', message: 'Name exactly one of all: true or a label.' })
194
+ return
195
+ }
196
+ // Permissive direction: the audit attempt line must be written BEFORE anything changes.
197
+ const descriptor = { action: 'enable', requestId: msg.requestId, ...(selector.label ? { label: selector.label } : {}) }
198
+ const auditor = auditorOf(ctx)
199
+ if (auditor.attempt(null, descriptor).ok !== true) {
200
+ log.warn(`Refused enable (${describeSelector(selector)}): the audit log is unavailable`)
201
+ reply(ws, ctx, msg, 'enable', { ok: false, code: 'AUDIT_UNAVAILABLE', message: 'Re-enabling agents requires a writable audit log, and it is not available.' })
202
+ return
203
+ }
204
+ const out = sw.enable(selector)
205
+ if (!out.ok) {
206
+ reply(ws, ctx, msg, 'enable', {
207
+ ok: false,
208
+ code: out.code,
209
+ message: ENABLE_REFUSAL_MESSAGES[out.code] ?? 'Could not re-enable: the switch file could not be written, so agents stay disabled.',
210
+ })
211
+ return
212
+ }
213
+ auditor.outcome(null, descriptor, 'enabled', out.durable ? 'durable' : 'not_durable')
214
+ log.warn(`Agent principals enabled (${describeSelector(selector)}) by client ${client.id} (durable=${out.durable})`)
215
+ reply(ws, ctx, msg, 'enable', {
216
+ ok: true,
217
+ durable: out.durable,
218
+ disabled: out.state,
219
+ ...(out.durable ? {} : { message: 'Enabled in this process but NOT durable: a restart before a successful write brings the previous state back.' }),
220
+ })
221
+ }
222
+
223
+ export const principalAdminHandlers = {
224
+ principal_admin_grant: handlePrincipalAdminGrant,
225
+ principal_admin_list: handlePrincipalAdminList,
226
+ principal_admin_revoke: handlePrincipalAdminRevoke,
227
+ principal_admin_disable: handlePrincipalAdminDisable,
228
+ principal_admin_enable: handlePrincipalAdminEnable,
229
+ }
@@ -0,0 +1,262 @@
1
+ /**
2
+ * The agent principal's read path over WebSocket (docs/security/agent-principals.md
3
+ * sections 7.1 and 7.2; #9118, S3 of #9112): `principal_subscribe`,
4
+ * `principal_unsubscribe` and `principal_events_read`, and (#9119, S4) the pending-permission
5
+ * snapshot `principal_pending_permissions` (section 7.3) and (#9120, S5) the session roster
6
+ * snapshot `principal_sessions_snapshot`.
7
+ *
8
+ * All three are OBSERVE tier. Dispatch has already checked the type, the tier and the
9
+ * closed envelope (principal-policy.js); each handler then resolves EVERY session id
10
+ * through `principalMaySee(..., 'observe')` from the explicit ids in the message (never
11
+ * the active session) and refuses the whole request `scope_denied` when any one is not
12
+ * granted. A session that does not exist and a session that is not granted fail the same
13
+ * check with the same reply, so a principal cannot probe which ids exist, and a multi-id
14
+ * subscribe is all-or-nothing: nothing is subscribed unless every id is granted.
15
+ *
16
+ * A client that is not a principal has no use for these types (they exist for the
17
+ * `principal_*` family) and is refused without touching the journal.
18
+ */
19
+ import { PRINCIPAL_ENVELOPES, isPrincipalClient, principalMaySee, principalPolicyOptsFromCtx, sendPrincipalRefusal } from '../principal-policy.js'
20
+ import { collectPendingPermissions } from '../principal-pending-permissions.js'
21
+ import { collectSessionsSnapshot } from '../principal-sessions-snapshot.js'
22
+
23
+ export const PRINCIPAL_READ_DEFAULT_LIMIT = 50
24
+ export const PRINCIPAL_READ_MAX_LIMIT = 200
25
+
26
+ // The protocol schemas' caps for a snapshot request (PrincipalPendingPermissionsSchema and
27
+ // PrincipalSessionsSnapshotSchema in @chroxy/protocol). The handler checks them itself because
28
+ // the Zod layer is not the only way in; tests/principal-handlers.test.js pins these equal to
29
+ // the schemas' own boundaries.
30
+ export const PRINCIPAL_SNAPSHOT_REQUEST_ID_MAX = 128
31
+ export const PRINCIPAL_SNAPSHOT_SESSION_IDS_MAX = 32
32
+ export const PRINCIPAL_SNAPSHOT_SESSION_ID_MAX = 128
33
+
34
+ /** Not a principal: the journal is for principals only. Reveals nothing about any session. */
35
+ function refuseNonPrincipal(ws, msg, ctx) {
36
+ ctx.transport.send(ws, {
37
+ type: 'session_error',
38
+ code: 'scope_denied',
39
+ message: 'Not permitted for this credential',
40
+ ...(typeof msg?.type === 'string' && msg.type.length <= 128 ? { requestType: msg.type } : {}),
41
+ ...(typeof msg?.requestId === 'string' && msg.requestId.length <= 128 ? { requestId: msg.requestId } : {}),
42
+ })
43
+ }
44
+
45
+ /** Every id granted at observe tier, or false. Evaluated for ALL ids, in order. */
46
+ function allGranted(client, ids, ctx) {
47
+ if (!Array.isArray(ids) || ids.length === 0) return false
48
+ const opts = principalPolicyOptsFromCtx(ctx)
49
+ let ok = true
50
+ for (const id of ids) {
51
+ if (!principalMaySee(client, id, 'observe', opts).ok) ok = false
52
+ }
53
+ return ok
54
+ }
55
+
56
+ function sessionIdList(value) {
57
+ if (!Array.isArray(value) || value.length === 0) return null
58
+ const out = []
59
+ for (const id of value) {
60
+ if (typeof id !== 'string' || id.length === 0 || out.includes(id)) return null
61
+ out.push(id)
62
+ }
63
+ return out
64
+ }
65
+
66
+ function handlePrincipalSubscribe(ws, client, msg, ctx) {
67
+ if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
68
+ const ids = sessionIdList(msg?.sessionIds)
69
+ if (ids === null || typeof msg.requestId !== 'string' || msg.requestId.length === 0) {
70
+ return sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
71
+ }
72
+ // ALL-OR-NOTHING: one id that is not granted (or not there) refuses the whole request.
73
+ if (!allGranted(client, ids, ctx)) return sendPrincipalRefusal(ws, client, msg, ctx, 'scope')
74
+ const cursors = new Map()
75
+ for (const c of Array.isArray(msg.cursors) ? msg.cursors : []) {
76
+ // A cursor names a session the request names; a second one for it, or one for another
77
+ // session, is a malformed request.
78
+ if (c === null || typeof c !== 'object' || !ids.includes(c.sessionId) || cursors.has(c.sessionId)) {
79
+ return sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
80
+ }
81
+ cursors.set(c.sessionId, c)
82
+ }
83
+ const subs = ctx.services?.principalSubscriptions
84
+ if (!subs) return sendPrincipalRefusal(ws, client, msg, ctx, 'not_available')
85
+ subs.subscribe({
86
+ ws, client, requestId: msg.requestId,
87
+ sessions: ids.map((sessionId) => ({ sessionId, cursor: cursors.get(sessionId) ?? null })),
88
+ })
89
+ }
90
+
91
+ function handlePrincipalUnsubscribe(ws, client, msg, ctx) {
92
+ if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
93
+ const subs = ctx.services?.principalSubscriptions
94
+ if (!subs) return
95
+ // Only the caller's own subscriptions can be named, so no grant check is needed and none
96
+ // can leak: an id that is not subscribed is simply a no-op.
97
+ let ids = null
98
+ if (msg?.sessionIds !== undefined) {
99
+ ids = Array.isArray(msg.sessionIds) ? msg.sessionIds.filter((id) => typeof id === 'string') : null
100
+ if (ids === null) return sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
101
+ }
102
+ subs.unsubscribe(client, ids)
103
+ }
104
+
105
+ function handlePrincipalEventsRead(ws, client, msg, ctx) {
106
+ if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
107
+ if (typeof msg?.sessionId !== 'string' || typeof msg.requestId !== 'string' || msg.requestId.length === 0) {
108
+ return sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
109
+ }
110
+ if (!allGranted(client, [msg.sessionId], ctx)) return sendPrincipalRefusal(ws, client, msg, ctx, 'scope')
111
+ const journal = ctx.services?.principalJournal
112
+ if (!journal) return sendPrincipalRefusal(ws, client, msg, ctx, 'not_available')
113
+ const requested = Number.isSafeInteger(msg.limit) ? msg.limit : PRINCIPAL_READ_DEFAULT_LIMIT
114
+ const limit = Math.min(Math.max(1, requested), PRINCIPAL_READ_MAX_LIMIT)
115
+ const resolved = journal.resolveCursor(msg.sessionId, msg.cursor ?? null)
116
+ const read = journal.readFrom(msg.sessionId, resolved.afterSeq, limit)
117
+ // The first unavailable range after the cursor is the gap the cursor itself ran into; a
118
+ // range met while reading on from there is the read's own.
119
+ const gap = resolved.gap && read.gap
120
+ ? { reason: resolved.gap.reason, fromSeq: resolved.gap.fromSeq, toSeq: read.gap.toSeq }
121
+ : (resolved.gap ?? read.gap)
122
+ ctx.transport.send(ws, {
123
+ type: 'principal_events_page',
124
+ requestId: msg.requestId,
125
+ sessionId: msg.sessionId,
126
+ journalId: resolved.journalId,
127
+ events: read.events.map((e) => ({
128
+ seq: e.seq, ts: e.ts, eventType: e.type, data: e.data, ...(e.truncated === true ? { truncated: true } : {}),
129
+ })),
130
+ headSeq: read.headSeq,
131
+ cursor: { sessionId: msg.sessionId, journalId: resolved.journalId, seq: read.lastSeq },
132
+ more: read.lastSeq < read.headSeq,
133
+ ...(gap ? { gap } : {}),
134
+ })
135
+ }
136
+
137
+ /**
138
+ * `principal_pending_permissions`: a snapshot of what is waiting for a decision on the
139
+ * principal's granted sessions, read from the canonical state of both permission pipelines
140
+ * (principal-pending-permissions.js). OBSERVE tier and READ ONLY: seeing a request is not
141
+ * being able to answer it, and nothing here touches a pending request.
142
+ *
143
+ * With `sessionIds`, EVERY id goes through `principalMaySee(..., 'observe')` and one that is
144
+ * not granted (or not there) refuses the whole request `scope_denied`, replying exactly as
145
+ * for a session that does not exist. Without it, the reply covers the sessions the principal
146
+ * may see, which is a filter, not a refusal: an empty grant gets an empty snapshot.
147
+ */
148
+ function handlePrincipalPendingPermissions(ws, client, msg, ctx) {
149
+ if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
150
+ const ids = resolveSnapshotSessionIds(ws, client, msg, ctx)
151
+ if (ids === null) return
152
+ const snapshot = collectPendingPermissions({
153
+ sessionIds: ids,
154
+ sessionManager: ctx.sessions?.sessionManager ?? null,
155
+ pendingPermissions: ctx.permissions?.pendingPermissions,
156
+ permissionSessionMap: ctx.permissions?.permissionSessionMap,
157
+ })
158
+ ctx.transport.send(ws, {
159
+ type: 'principal_pending_permissions_result',
160
+ requestId: msg.requestId,
161
+ generatedAt: snapshot.generatedAt,
162
+ permissions: snapshot.permissions,
163
+ truncated: snapshot.truncated,
164
+ })
165
+ }
166
+
167
+ /**
168
+ * Is this request inside its type's closed envelope (principal-policy.js's table) with a
169
+ * well-formed `requestId` and `sessionIds`? Independent of dispatch and of the Zod layer.
170
+ */
171
+ function snapshotEnvelopeOk(msg) {
172
+ const envelope = typeof msg?.type === 'string' && Object.hasOwn(PRINCIPAL_ENVELOPES, msg.type) ? PRINCIPAL_ENVELOPES[msg.type] : null
173
+ if (envelope === null || msg === null || typeof msg !== 'object' || Array.isArray(msg)) return false
174
+ for (const key of Object.keys(msg)) {
175
+ if (!envelope.fields.includes(key)) return false
176
+ }
177
+ if (typeof msg.requestId !== 'string' || msg.requestId.length === 0 || msg.requestId.length > PRINCIPAL_SNAPSHOT_REQUEST_ID_MAX) return false
178
+ if (msg.sessionIds !== undefined) {
179
+ const ids = msg.sessionIds
180
+ if (!Array.isArray(ids) || ids.length === 0 || ids.length > PRINCIPAL_SNAPSHOT_SESSION_IDS_MAX) return false
181
+ if (!ids.every((id) => typeof id === 'string' && id.length > 0 && id.length <= PRINCIPAL_SNAPSHOT_SESSION_ID_MAX)) return false
182
+ }
183
+ return true
184
+ }
185
+
186
+ /**
187
+ * The session ids a snapshot request covers, or null after the request was refused. With
188
+ * `sessionIds`, EVERY id goes through `principalMaySee(..., 'observe')` and one that is not
189
+ * granted (or not there) refuses the whole request `scope_denied`, replying exactly as for a
190
+ * session that does not exist. Without it, the ids are the sessions the principal may see,
191
+ * which is a filter, not a refusal: an empty grant gets an empty snapshot.
192
+ */
193
+ function resolveSnapshotSessionIds(ws, client, msg, ctx) {
194
+ // Contract 4.1.1: the closed envelope holds at the handler as well as at dispatch, so a
195
+ // handler reached any other way refuses the same way (the same refusal, byte for byte).
196
+ if (!snapshotEnvelopeOk(msg)) {
197
+ sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
198
+ return null
199
+ }
200
+ if (msg.sessionIds !== undefined) {
201
+ const ids = sessionIdList(msg.sessionIds)
202
+ // The envelope check passed, so only a DUPLICATE id can still make the list null.
203
+ if (ids === null) { sendPrincipalRefusal(ws, client, msg, ctx, 'envelope'); return null }
204
+ // ALL-OR-NOTHING, evaluated for every id (no early exit that would time differently).
205
+ if (!allGranted(client, ids, ctx)) { sendPrincipalRefusal(ws, client, msg, ctx, 'scope'); return null }
206
+ return ids
207
+ }
208
+ const opts = principalPolicyOptsFromCtx(ctx)
209
+ // Ids only: the full listing runs provider getters for EVERY session, so one the principal
210
+ // is not granted could change this reply.
211
+ const listed = ctx.sessions?.sessionManager?.listSessionIds?.() ?? []
212
+ const ids = []
213
+ for (const id of Array.isArray(listed) ? listed : []) {
214
+ if (typeof id === 'string' && !ids.includes(id) && principalMaySee(client, id, 'observe', opts).ok) ids.push(id)
215
+ }
216
+ return ids
217
+ }
218
+
219
+ /**
220
+ * Does the prompt evaluator hold a draft for this session? The WS layer's answer, which
221
+ * `SessionManager.getHandoffBlockers` cannot see and asks its caller for: input-handlers
222
+ * takes the per-session lock `runtime.pendingEvaluatorAwaits` before it awaits the skip
223
+ * decision and holds it until the evaluator settles (released in a `finally`). When the map
224
+ * is not there the answer is UNKNOWN, and unknown reads as pending: a blocker that is not
225
+ * real is safe, a missing one is not.
226
+ */
227
+ function evaluatorPendingFor(ctx) {
228
+ const awaits = ctx.runtime?.pendingEvaluatorAwaits
229
+ return awaits instanceof Map ? (id) => awaits.has(id) : () => true
230
+ }
231
+
232
+ /**
233
+ * `principal_sessions_snapshot`: a roster of the principal's granted sessions with observed
234
+ * and declared status, handoff blockers and the model requested and observed
235
+ * (principal-sessions-snapshot.js; section 7.3). OBSERVE tier and READ ONLY. Same id rules as
236
+ * `principal_pending_permissions`.
237
+ */
238
+ function handlePrincipalSessionsSnapshot(ws, client, msg, ctx) {
239
+ if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
240
+ const ids = resolveSnapshotSessionIds(ws, client, msg, ctx)
241
+ if (ids === null) return
242
+ const snapshot = collectSessionsSnapshot({
243
+ sessionIds: ids,
244
+ sessionManager: ctx.sessions?.sessionManager ?? null,
245
+ evaluatorPending: evaluatorPendingFor(ctx),
246
+ })
247
+ ctx.transport.send(ws, {
248
+ type: 'principal_sessions_snapshot_result',
249
+ requestId: msg.requestId,
250
+ generatedAt: snapshot.generatedAt,
251
+ sessions: snapshot.sessions,
252
+ truncated: snapshot.truncated,
253
+ })
254
+ }
255
+
256
+ export const principalHandlers = {
257
+ principal_pending_permissions: handlePrincipalPendingPermissions,
258
+ principal_sessions_snapshot: handlePrincipalSessionsSnapshot,
259
+ principal_subscribe: handlePrincipalSubscribe,
260
+ principal_unsubscribe: handlePrincipalUnsubscribe,
261
+ principal_events_read: handlePrincipalEventsRead,
262
+ }
@@ -249,7 +249,7 @@ function projectLastRun(lastRun) {
249
249
  * registry, and the panel now surfaces that as a readable snapshot error rather
250
250
  * than hanging.
251
251
  */
252
- function projectTask(task, ctx, quarantinedIds) {
252
+ function projectTask(task, ctx, quarantinedIds, daemonDefault) {
253
253
  const provider = effectiveProvider(task, ctx)
254
254
  const requestedMode = task?.target?.permissionMode
255
255
  const effectiveMode = resolveScheduledPermissionMode(requestedMode)
@@ -264,7 +264,7 @@ function projectTask(task, ctx, quarantinedIds) {
264
264
  lastRun: projectLastRun(task.lastRun),
265
265
  createdAt: Number.isFinite(task.createdAt) ? task.createdAt : 0,
266
266
  updatedAt: Number.isFinite(task.updatedAt) ? task.updatedAt : 0,
267
- providerRefusal: clampWire(scheduledProviderRefusalReason(provider), 2048),
267
+ providerRefusal: clampWire(scheduledProviderRefusalReason(provider, undefined, daemonDefault), 2048),
268
268
  effectiveProvider: clampWire(provider, 128),
269
269
  effectivePermissionMode: clampWire(effectiveMode, 64),
270
270
  // True only when the task ASKED for something and got clamped — an absent
@@ -303,7 +303,7 @@ function buildSnapshot(ctx, requestId, { error = null } = {}) {
303
303
  let tasks = []
304
304
  if (store && !error) {
305
305
  try {
306
- tasks = store.list().map((t) => projectTask(t, ctx, quarantinedIds))
306
+ tasks = store.list().map((t) => projectTask(t, ctx, quarantinedIds, effectiveProvider(null, ctx)))
307
307
  } catch (err) {
308
308
  // Degrade to a structurally valid empty snapshot + error, the same posture
309
309
  // the Control Room surveys use — never a dead/unparseable reply.
@@ -342,7 +342,7 @@ function buildSnapshot(ctx, requestId, { error = null } = {}) {
342
342
  },
343
343
  schedulableProviders: listSchedulableProviders().slice(0, SCHEDULABLE_PROVIDERS_MAX),
344
344
  defaultProvider,
345
- defaultProviderRefusal: scheduledProviderRefusalReason(defaultProvider),
345
+ defaultProviderRefusal: scheduledProviderRefusalReason(defaultProvider, undefined, defaultProvider),
346
346
  tasks,
347
347
  unreadableCount,
348
348
  unreadable,
@@ -7,6 +7,7 @@
7
7
  import { USER_SHELL_PROVIDER } from '@chroxy/protocol'
8
8
  import { authorizedFor } from '../connection-authority.js'
9
9
  import { isBoundClient } from '../environments/authority.js'
10
+ import { isPrincipalClient, refusePrincipalHandler } from '../principal-policy.js'
10
11
  import { auditShellCreate } from '../shell-audit.js'
11
12
  import { validateCwdAllowed, broadcastFocusChanged, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError, isSessionViewer, isUserShellSession, ALLOWED_PERMISSION_MODE_IDS } from '../handler-utils.js'
12
13
  import { getRegistryForProvider, resolveRosterProvider } from '../models.js'
@@ -116,6 +117,10 @@ function handleCreateSession(ws, client, msg, ctx) {
116
117
  const requestId = (typeof msg.requestId === 'string' && msg.requestId) ? msg.requestId : undefined
117
118
  const rid = requestId !== undefined ? { requestId } : {}
118
119
  const sendError = (message) => ctx.transport.send(ws, { type: 'session_error', message, ...rid })
120
+ // Principal branch, BEFORE the bound refusal below (a principal carries a
121
+ // sentinel binding, so it would otherwise be refused as a bound client). It
122
+ // never falls into the host path and never touches the active session.
123
+ if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, null)
119
124
  if (client.boundSessionId) {
120
125
  // Enrich the error with the bound session's name so the client can render
121
126
  // a remediation hint ("This device is paired to session X — disconnect to
@@ -253,7 +258,9 @@ function handleCreateSession(ws, client, msg, ctx) {
253
258
 
254
259
  // #6277 — build the create options + audit identity ONCE; both the synchronous
255
260
  // path and the host-approval deferred path replay the identical create.
256
- const createOptions = { name, cwd, provider, connectionId, model, permissionMode, worktree, sandbox, codexSandbox, skipPermissions, agentCommId, ...envOpts }
261
+ // `requestId` doubles as the naming idempotency key: a retried create (same id) is answered
262
+ // with the same reserved project number instead of burning another one.
263
+ const createOptions = { name, cwd, provider, connectionId, model, permissionMode, worktree, sandbox, codexSandbox, skipPermissions, agentCommId, ...(requestId !== undefined ? { nameIdempotencyKey: requestId } : {}), ...envOpts }
257
264
  const isUserShell = provider === USER_SHELL_PROVIDER
258
265
  // Capture the audit identity at REQUEST time: the deferred (approved) path may
259
266
  // run after the requesting socket is gone, so it can't read a live `client`.
@@ -380,6 +387,8 @@ export function finalizeShellCreate(ws, client, createOptions, ctx, audit) {
380
387
  }
381
388
 
382
389
  async function handleDestroySession(ws, client, msg, ctx) {
390
+ // Principal branch: the target resolves through principalMaySee, never the host path.
391
+ if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, 'drive')
383
392
  const targetId = msg.sessionId
384
393
 
385
394
  if (client.boundSessionId && client.boundSessionId !== targetId) {