@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,189 @@
1
+ /**
2
+ * The agent-principal audit trail (docs/security/agent-principals.md section 10.1).
3
+ *
4
+ * Every line is `[AUDIT] [agent-audit] <kind> {json}` written through
5
+ * `auditOrRefuse` (logger.js), the one audit writer that reports whether the line
6
+ * really reached the audit log. Two classes of line:
7
+ *
8
+ * - `attempt`: written BEFORE a principal effect. If it cannot be written the effect
9
+ * does not happen (`withPrincipalEffect`, principal-effect.js). FAIL CLOSED.
10
+ * - `outcome`: one per transition (`delivered | queued | expired | dropped:<reason> |
11
+ * rejected:<reason> | killed | revoked | enabled`). Written after the fact, so it is
12
+ * best effort: it cannot un-do a transition. It reports whether it landed.
13
+ *
14
+ * What a line carries: `ts, principalId, label, action, sessionId, requestId, leaseId,
15
+ * gen, result, reason`, and for any input text ONLY `sha256` and `length`. The text
16
+ * itself is never logged: fields are an allowlist, and `text` is turned into a digest
17
+ * and dropped. The transcript is the content record (contract D7).
18
+ *
19
+ * Repeated identical rejections within a minute collapse into one counter line, written when the window ends (a bounded, unref'd timer),
20
+ * on graceful shutdown, or on the next flush if a write failed.
21
+ */
22
+ import { createHash } from 'node:crypto'
23
+ import { auditOrRefuse as defaultAuditOrRefuse } from './logger.js'
24
+
25
+ export const AUDIT_COMPONENT = 'agent-audit'
26
+
27
+ /** The effect kinds the contract names (section 10.1): each gets an attempt line first. */
28
+ export const PRINCIPAL_EFFECT_KINDS = Object.freeze([
29
+ 'enqueue', 'send', 'interrupt', 'create', 'destroy', 'permission_answer', 'lease_change',
30
+ ])
31
+
32
+ /** The outcome results the contract names. `dropped:` and `rejected:` carry a reason. */
33
+ export const PRINCIPAL_OUTCOME_RESULTS = Object.freeze(['delivered', 'queued', 'expired', 'killed', 'revoked', 'enabled'])
34
+
35
+ export const REJECT_COLLAPSE_WINDOW_MS = 60_000
36
+ const MAX_COLLAPSE_KEYS = 256
37
+ const MAX_FLUSH_FAILURES = 5
38
+
39
+ /** @param {string} text @returns {{ sha256: string, length: number }} */
40
+ export function inputDigest(text) {
41
+ const s = typeof text === 'string' ? text : ''
42
+ return { sha256: createHash('sha256').update(s, 'utf8').digest('hex'), length: s.length }
43
+ }
44
+
45
+ function clip(value, max = 128) {
46
+ return typeof value === 'string' ? value.slice(0, max) : undefined
47
+ }
48
+
49
+ /**
50
+ * Build the audit fields from a descriptor. An ALLOWLIST: an unknown key (a `content`, a
51
+ * `body`, a token) is never copied. `text` becomes `{ sha256, length }`.
52
+ */
53
+ function buildFields(kind, ts, principal, descriptor, extra) {
54
+ const d = descriptor ?? {}
55
+ const fields = {
56
+ ts,
57
+ principalId: clip(principal?.principalId ?? d.principalId),
58
+ label: clip(principal?.label ?? d.label, 64),
59
+ action: clip(d.action, 64),
60
+ sessionId: clip(d.sessionId),
61
+ requestId: clip(d.requestId ?? d.clientMessageId),
62
+ leaseId: clip(d.leaseId),
63
+ gen: Number.isSafeInteger(d.gen) ? d.gen : undefined,
64
+ ...extra,
65
+ }
66
+ if (typeof d.text === 'string') {
67
+ const { sha256, length } = inputDigest(d.text)
68
+ fields.sha256 = sha256
69
+ fields.length = length
70
+ }
71
+ for (const k of Object.keys(fields)) if (fields[k] === undefined) delete fields[k]
72
+ return { kind, fields }
73
+ }
74
+
75
+ /**
76
+ * @param {object} [opts]
77
+ * @param {(component: string, msg: string) => { ok: boolean }} [opts.auditOrRefuse] the writer; injectable
78
+ * @param {() => number} [opts.now]
79
+ * @param {number} [opts.collapseMs]
80
+ */
81
+ export function createPrincipalAuditor({ auditOrRefuse = defaultAuditOrRefuse, now = Date.now, collapseMs = REJECT_COLLAPSE_WINDOW_MS } = {}) {
82
+ /** @type {Map<string, { firstAt: number, suppressed: number, principal: object, descriptor: object, reason: string }>} */
83
+ const rejections = new Map()
84
+
85
+ function write(kind, fields) {
86
+ let verdict
87
+ try {
88
+ verdict = auditOrRefuse(AUDIT_COMPONENT, `${kind} ${JSON.stringify(fields)}`)
89
+ } catch {
90
+ return { ok: false, reason: 'audit_unavailable' }
91
+ }
92
+ // Only the boolean `true` counts as written.
93
+ return verdict?.ok === true ? { ok: true } : { ok: false, reason: 'audit_unavailable' }
94
+ }
95
+
96
+ function drop(key, entry) {
97
+ if (entry.timer) clearTimeout(entry.timer)
98
+ if (rejections.get(key) === entry) rejections.delete(key)
99
+ }
100
+
101
+ /**
102
+ * Write the entry's collapsed count (if any) and retire it. A FAILED counter write keeps
103
+ * the entry, unless `force` (eviction) or the retry budget is spent, so the count is not
104
+ * lost to one bad write. Returns true when the entry was retired.
105
+ */
106
+ function flushCollapsed(key, entry, force = false) {
107
+ if (entry.suppressed > 0) {
108
+ const { kind, fields } = buildFields('outcome', new Date(now()).toISOString(), entry.principal, entry.descriptor, {
109
+ result: `rejected:${entry.reason}`, count: entry.suppressed, collapsed: true,
110
+ })
111
+ if (write(kind, fields).ok !== true && !force && ++entry.failures < MAX_FLUSH_FAILURES) {
112
+ arm(key, entry)
113
+ return false
114
+ }
115
+ }
116
+ drop(key, entry)
117
+ return true
118
+ }
119
+
120
+ /** A bounded, unref'd timer: silence after a burst still records the count. */
121
+ function arm(key, entry) {
122
+ if (entry.timer) clearTimeout(entry.timer)
123
+ entry.timer = setTimeout(() => { entry.timer = null; if (rejections.get(key) === entry) flushCollapsed(key, entry) }, collapseMs)
124
+ entry.timer.unref?.()
125
+ }
126
+
127
+ return {
128
+ /**
129
+ * The pre-effect line. `{ ok: false }` means it was NOT written: do not act.
130
+ * @param {{ principalId?: string, label?: string }} principal
131
+ * @param {{ action: string, sessionId?: string, requestId?: string, leaseId?: string, gen?: number, text?: string }} descriptor
132
+ */
133
+ attempt(principal, descriptor) {
134
+ const { kind, fields } = buildFields('attempt', new Date(now()).toISOString(), principal, descriptor, { result: 'attempt' })
135
+ return write(kind, fields)
136
+ },
137
+
138
+ /**
139
+ * An outcome line, best effort. `result` is one of PRINCIPAL_OUTCOME_RESULTS or
140
+ * `dropped:<reason>` / `rejected:<reason>`; `reason` is free text (a short code).
141
+ * @returns {{ ok: boolean }} whether it landed
142
+ */
143
+ outcome(principal, descriptor, result, reason) {
144
+ const { kind, fields } = buildFields('outcome', new Date(now()).toISOString(), principal, descriptor, {
145
+ result: clip(result, 96), reason: clip(reason, 96),
146
+ })
147
+ return write(kind, fields)
148
+ },
149
+
150
+ /**
151
+ * A refusal line. Identical refusals (same principal, action, reason) inside the
152
+ * collapse window are counted, not logged; the count is written as one line when the
153
+ * window ends (a window-end timer, or `flushRejections` at shutdown). Best effort.
154
+ */
155
+ rejected(principal, descriptor, reason) {
156
+ const r = clip(String(reason ?? 'rejected'), 64)
157
+ const key = `${principal?.principalId ?? descriptor?.principalId ?? ''}\u0000${descriptor?.action ?? ''}\u0000${r}`
158
+ const t = now()
159
+ const existing = rejections.get(key)
160
+ if (existing && t - existing.firstAt < collapseMs) {
161
+ existing.suppressed++
162
+ return { ok: true, collapsed: true }
163
+ }
164
+ if (existing) flushCollapsed(key, existing, true)
165
+ if (rejections.size >= MAX_COLLAPSE_KEYS) {
166
+ const oldest = rejections.keys().next().value
167
+ flushCollapsed(oldest, rejections.get(oldest), true)
168
+ }
169
+ const entry = { firstAt: t, suppressed: 0, failures: 0, timer: null, principal, descriptor, reason: r }
170
+ rejections.set(key, entry)
171
+ arm(key, entry)
172
+ const { kind, fields } = buildFields('outcome', new Date(t).toISOString(), principal, descriptor, { result: `rejected:${r}` })
173
+ return write(kind, fields)
174
+ },
175
+
176
+ /**
177
+ * Write every pending collapsed-count line now (graceful shutdown, tests). A failed write
178
+ * keeps its entry for the next flush.
179
+ * @returns {{ pending: number }} entries still holding an unwritten count
180
+ */
181
+ flushRejections() {
182
+ for (const [key, entry] of [...rejections]) flushCollapsed(key, entry)
183
+ return { pending: [...rejections.values()].filter((e) => e.suppressed > 0).length }
184
+ },
185
+ }
186
+ }
187
+
188
+ /** The process-wide auditor over the real audit log. */
189
+ export const principalAuditor = createPrincipalAuditor()
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The binding a principal connection carries in `client.boundSessionId`.
3
+ *
4
+ * Contract §3.1 item 2: every existing host gate branches on `boundSessionId`, so a
5
+ * principal is stamped with a FIXED, non-empty, opaque value that no creatable
6
+ * session id can equal. Session ids are 32 lowercase hex characters
7
+ * (`session-manager.js`); this value contains characters outside that alphabet, so it
8
+ * can never name a real session, and a gate that compares it to a session id refuses.
9
+ *
10
+ * It is DEFENCE IN DEPTH and it is never serialized: `publicBoundSessionId` is the one
11
+ * place a binding is turned into something a frame may carry, and it answers null for
12
+ * this value.
13
+ */
14
+ export const PRINCIPAL_BINDING_SENTINEL = 'principal-binding:not-a-session'
15
+
16
+ /**
17
+ * The binding as a frame may carry it: the real session id, or null for the sentinel
18
+ * (and for anything that is not a non-empty string).
19
+ * @param {unknown} binding
20
+ * @returns {string|null}
21
+ */
22
+ export function publicBoundSessionId(binding) {
23
+ if (typeof binding !== 'string' || binding.length === 0) return null
24
+ return binding === PRINCIPAL_BINDING_SENTINEL ? null : binding
25
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The production wiring of the agent-principal brakes (agent-principals.md section 10):
3
+ * the persistent kill switch and the "principal access requires file-backed audit
4
+ * logging" gate, handed to the principal store so that `store.state()` (the one choke
5
+ * point every credential check goes through) refuses while either brake is on.
6
+ *
7
+ * Kept apart from principal-store.js so that module does not import the kill switch,
8
+ * which imports the store's label pattern. The daemon attaches them with
9
+ * `store.attachBrakes(createPrincipalBrakes())` right after `createPrincipalStore()`.
10
+ */
11
+ import { PrincipalKillSwitch } from './principal-kill-switch.js'
12
+ import { getAuditLogPath } from './logger.js'
13
+
14
+ /**
15
+ * @param {object} [opts]
16
+ * @param {PrincipalKillSwitch} [opts.killSwitch]
17
+ * @param {() => boolean} [opts.auditAvailable] defaults to "the audit log file is writable-configured"
18
+ */
19
+ export function createPrincipalBrakes({ killSwitch = new PrincipalKillSwitch(), auditAvailable = () => getAuditLogPath() !== null } = {}) {
20
+ return { killSwitch, auditAvailable }
21
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * `withPrincipalEffect` (docs/security/agent-principals.md §3.0 item 3).
3
+ *
4
+ * A principal mutation handler awaits (the session manager, a lease, a disk write)
5
+ * between "the frame was admitted" and "the effect lands". The credential can be revoked,
6
+ * expire or be killed in any of those awaits, and a handler that only checked at entry
7
+ * would still act. This wrapper is the commit point: it runs `check` and then `fn` in
8
+ * the SAME synchronous step, so nothing can interleave between the verdict and the
9
+ * effect. Every principal mutation handler runs its effect inside it; the handlers that
10
+ * need one are S8 and later, and S2's refuse every mutation today.
11
+ *
12
+ * `check` is an injectable function `(client) => { ok: true } | { ok: false, reason }`.
13
+ * `credentialCheck(ctx)` is the default S1 supplies (credential live, not expired, not
14
+ * revoked, loopback origin retained). Later checks (kill switch, "agents off", lease and
15
+ * `gen`) are composed with `allChecks` and refuse in the same way.
16
+ *
17
+ * `check` and `fn` are synchronous on purpose. An async `check` would reopen the very gap
18
+ * this closes, so a thenable verdict is treated as a refusal.
19
+ */
20
+
21
+ import { PRINCIPAL_EFFECT_KINDS } from './principal-audit.js'
22
+
23
+ /** @typedef {{ ok: true } | { ok: false, reason: string }} PrincipalCheckVerdict */
24
+
25
+ /**
26
+ * Re-validate the credential through the transport's own check (the one WsServer wires
27
+ * to `_isConnectionAuthorized`, which ends the connection when the credential is dead).
28
+ * @param {{ transport?: { isConnectionAuthorized?: (client: object) => boolean } }} ctx
29
+ * @returns {(client: object) => PrincipalCheckVerdict}
30
+ */
31
+ export function credentialCheck(ctx) {
32
+ return (client) => (ctx?.transport?.isConnectionAuthorized?.(client) === true
33
+ ? { ok: true }
34
+ : { ok: false, reason: 'credential' })
35
+ }
36
+
37
+ /**
38
+ * The first refusing check wins; all must pass.
39
+ * @param {...(client: object) => PrincipalCheckVerdict} checks
40
+ * @returns {(client: object) => PrincipalCheckVerdict}
41
+ */
42
+ export function allChecks(...checks) {
43
+ return (client) => {
44
+ for (const check of checks) {
45
+ const verdict = check(client)
46
+ if (verdict?.ok !== true) return verdict?.ok === false ? verdict : { ok: false, reason: 'check' }
47
+ }
48
+ return { ok: true }
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Run `fn` only if `check(client)` passes at this instant AND the pre-effect audit
54
+ * attempt line was written (contract section 10.1). The order is fixed: check, then the
55
+ * attempt line, then `fn`, all in one synchronous step. If the line cannot be written
56
+ * (file logging off, ENOSPC, EBADF) there is NO effect and the verdict is
57
+ * `{ ok: false, reason: 'audit_unavailable' }`, which the caller turns into an error ack.
58
+ *
59
+ * `audit` is REQUIRED: a mutation that names no audit descriptor, an unknown effect kind
60
+ * or no auditor is refused (`audit_unavailable` / `bad_effect`), never run unaudited.
61
+ *
62
+ * A refused check writes a (collapsed, best-effort) `rejected` line; an `fn` that throws
63
+ * writes a best-effort `rejected:effect_error` outcome and the throw propagates.
64
+ *
65
+ * @template T
66
+ * @param {object} client
67
+ * @param {(client: object) => PrincipalCheckVerdict} check
68
+ * @param {{ auditor: ReturnType<import('./principal-audit.js').createPrincipalAuditor>, action: string, sessionId?: string, requestId?: string, leaseId?: string, gen?: number, text?: string }} audit
69
+ * @param {() => T} fn the effect; runs synchronously after the verdict and the attempt line
70
+ * @returns {{ ok: true, value: T } | { ok: false, reason: string }}
71
+ */
72
+ export function withPrincipalEffect(client, check, audit, fn) {
73
+ const auditor = audit?.auditor
74
+ const principal = client?.principal ?? null
75
+ let verdict
76
+ try {
77
+ verdict = check(client)
78
+ } catch {
79
+ return { ok: false, reason: 'check_error' }
80
+ }
81
+ if (verdict == null || typeof verdict.then === 'function' || verdict.ok !== true) {
82
+ const reason = typeof verdict?.reason === 'string' ? verdict.reason : 'check'
83
+ try { auditor?.rejected?.(principal, audit, reason) } catch { /* a refusal line is best effort */ }
84
+ return { ok: false, reason }
85
+ }
86
+ if (!PRINCIPAL_EFFECT_KINDS.includes(audit?.action)) return { ok: false, reason: 'bad_effect' }
87
+ if (typeof auditor?.attempt !== 'function') return { ok: false, reason: 'audit_unavailable' }
88
+ let attempt
89
+ try {
90
+ attempt = auditor.attempt(principal, audit)
91
+ } catch {
92
+ attempt = null
93
+ }
94
+ if (attempt?.ok !== true) return { ok: false, reason: 'audit_unavailable' }
95
+ try {
96
+ return { ok: true, value: fn() }
97
+ } catch (err) {
98
+ try { auditor.outcome(principal, audit, 'rejected:effect_error', err?.code || 'error') } catch { /* best effort */ }
99
+ throw err
100
+ }
101
+ }