@chroxy/server 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +411 -14
- package/hooks/permission-hook.sh +253 -3
- package/package.json +8 -15
- package/sidecar/node_modules/.package-lock.json +29 -0
- package/sidecar/node_modules/ws/LICENSE +20 -0
- package/sidecar/node_modules/ws/README.md +548 -0
- package/sidecar/node_modules/ws/browser.js +8 -0
- package/sidecar/node_modules/ws/index.js +22 -0
- package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
- package/sidecar/node_modules/ws/lib/constants.js +19 -0
- package/sidecar/node_modules/ws/lib/event-target.js +292 -0
- package/sidecar/node_modules/ws/lib/extension.js +203 -0
- package/sidecar/node_modules/ws/lib/limiter.js +55 -0
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/sidecar/node_modules/ws/lib/receiver.js +706 -0
- package/sidecar/node_modules/ws/lib/sender.js +602 -0
- package/sidecar/node_modules/ws/lib/stream.js +161 -0
- package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
- package/sidecar/node_modules/ws/lib/validation.js +152 -0
- package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
- package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
- package/sidecar/node_modules/ws/package.json +70 -0
- package/sidecar/node_modules/ws/wrapper.mjs +21 -0
- package/src/base-session.js +151 -6
- package/src/billing-budget.js +5 -1
- package/src/binary-provenance-trust.js +95 -0
- package/src/built-in-tools/file-ops.js +5 -4
- package/src/byok-mcp-client.js +1061 -13
- package/src/byok-mcp-config.js +1201 -4
- package/src/byok-mcp-fleet.js +374 -29
- package/src/byok-mcp-oauth-store.js +327 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +254 -37
- package/src/byok-session.js +789 -13
- package/src/byok-tool-executor.js +20 -13
- package/src/checkpoint-manager.js +33 -6
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-stream-parser.js +56 -0
- package/src/claude-tui/pty-driver.js +54 -14
- package/src/claude-tui-session.js +106 -7
- package/src/cli/config-cmd.js +2 -2
- package/src/cli/deploy-cmd.js +1 -1
- package/src/cli/init-cmd.js +1 -1
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +775 -0
- package/src/cli/server-cmd.js +16 -1
- package/src/cli/service-cmd.js +39 -19
- package/src/cli/shared.js +7 -4
- package/src/cli/tokens-cmd.js +213 -0
- package/src/cli/tunnel-cmd.js +1 -1
- package/src/cli-session.js +66 -10
- package/src/cli.js +4 -0
- package/src/codex-app-server-session.js +671 -39
- package/src/codex-session.js +121 -18
- package/src/config.js +453 -27
- package/src/control-room/integrations.js +16 -10
- package/src/control-room/skills-inventory.js +6 -1
- package/src/control-room/survey.js +32 -0
- package/src/credential-store.js +256 -10
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
- package/src/diagnostics.js +3 -0
- package/src/docker-sdk-session.js +16 -1
- package/src/docker-session.js +9 -0
- package/src/doctor.js +19 -8
- package/src/environments/backends/docker.js +8 -0
- package/src/environments/backends/k8s.js +9 -0
- package/src/event-ingest.js +19 -1
- package/src/event-normalizer.js +354 -19
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +19 -2
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +42 -8
- package/src/handlers/checkpoint-handlers.js +126 -19
- package/src/handlers/control-room-handlers.js +48 -18
- package/src/handlers/conversation-handlers.js +127 -2
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/file-handlers.js +47 -3
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +4 -0
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +510 -0
- package/src/handlers/session-handlers.js +10 -2
- package/src/handlers/settings-handlers.js +510 -11
- package/src/handlers/token-handlers.js +11 -2
- package/src/http-routes.js +159 -0
- package/src/jsonl-reader.js +60 -6
- package/src/jsonl-subprocess-session.js +35 -6
- package/src/keychain.js +159 -12
- package/src/logger.js +182 -19
- package/src/notification-prefs.js +88 -6
- package/src/notifications/discord-webhook-sink.js +30 -1
- package/src/orchestration/build-manager.js +56 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +347 -0
- package/src/orchestration/orchestration-manager.js +1295 -0
- package/src/orchestration/permission-gate.js +109 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +205 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +398 -0
- package/src/pairing.js +146 -1
- package/src/permission-audit.js +79 -3
- package/src/permission-floor.js +455 -0
- package/src/permission-manager.js +492 -40
- package/src/permission-resolver.js +55 -7
- package/src/permission-rule-store.js +411 -0
- package/src/platform.js +367 -23
- package/src/providers.js +21 -2
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +653 -0
- package/src/scheduler.js +1029 -0
- package/src/sdk-session.js +338 -5
- package/src/server-cli/server-orchestrator.js +23 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli.js +238 -26
- package/src/server-identity.js +28 -4
- package/src/service.js +291 -33
- package/src/session-manager.js +417 -25
- package/src/session-message-history.js +27 -21
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +60 -35
- package/src/skills-usage.js +20 -2
- package/src/statusline.js +584 -0
- package/src/subagent-counter.js +9 -1
- package/src/supervisor.js +77 -27
- package/src/token-manager.js +39 -9
- package/src/transcript-tasks.js +41 -6
- package/src/tunnel/cloudflare.js +115 -8
- package/src/tunnel/index.js +4 -1
- package/src/tunnel-check.js +1 -1
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +118 -0
- package/src/user-shell-session.js +98 -32
- package/src/utils/componentwise-resolver.js +205 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/preflight.js +140 -28
- package/src/utils/spawn-env.js +8 -2
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +241 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/worktree-gc.js +4 -1
- package/src/ws-file-ops/browser.js +42 -11
- package/src/ws-file-ops/common.js +68 -1
- package/src/ws-file-ops/git.js +221 -3
- package/src/ws-file-ops/index.js +5 -0
- package/src/ws-file-ops/memory.js +358 -0
- package/src/ws-file-ops/reader.js +124 -0
- package/src/ws-forwarding.js +44 -16
- package/src/ws-handler-context.js +19 -0
- package/src/ws-history.js +84 -11
- package/src/ws-message-handlers.js +6 -0
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +285 -4
- package/src/ws-schemas.js +1 -0
- package/src/ws-server.js +301 -17
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TurnDriver (engine foundations, epic #6691, step E-1) — the single primitive
|
|
3
|
+
* for driving one turn of a Chroxy session and getting its final text back.
|
|
4
|
+
* The orchestration engine never touches sessions directly; it drives them
|
|
5
|
+
* through here.
|
|
6
|
+
*
|
|
7
|
+
* Mechanics (design §4.2):
|
|
8
|
+
* - One `session_event` listener on the SessionManager; per-session FIFO mutex
|
|
9
|
+
* so at most one driven turn runs per session (committee reviews serialize on
|
|
10
|
+
* the architect session).
|
|
11
|
+
* - Epoch guard: events that arrive before our send, or a stray `result` with
|
|
12
|
+
* no active turn, are ignored. That guard only protects a QUEUED turn because
|
|
13
|
+
* the mutex handoff is deferred past the end of the current synchronous frame —
|
|
14
|
+
* see _scheduleNext.
|
|
15
|
+
* - Text is accumulated live from `stream_delta` (per messageId) + non-streamed
|
|
16
|
+
* `message {type:'response'}` events, bounded to MAX_ACCUM_BYTES with an
|
|
17
|
+
* explicit truncation marker (the decision parser scans from the tail).
|
|
18
|
+
* - SUCCESS keys ONLY off the `result` event (isRunning can stay true on
|
|
19
|
+
* pending background shells). `error` is turn-terminal → TurnError.
|
|
20
|
+
* - `stopped` is turn-terminal too → TURN_STOPPED (#7009). Every provider that
|
|
21
|
+
* emits `stopped` does so ONLY on its intentional-stop path (`wasIntentionalStop`:
|
|
22
|
+
* see sdk-session.js, cli-session.js, jsonl-subprocess-session.js,
|
|
23
|
+
* codex-app-server-session.js — #4881), i.e. someone called interrupt();
|
|
24
|
+
* claude-tui and claude-byok never emit it at all. Such a turn produces NO
|
|
25
|
+
* `result` and NO `error`, so without this the caller's promise hung until the
|
|
26
|
+
* watchdog fired. It gets its OWN code, never a success: an interrupted turn did
|
|
27
|
+
* not do the work it was asked to do.
|
|
28
|
+
* This settle deliberately does NOT drain, unlike the timeout path: `stopped` is
|
|
29
|
+
* the very event _endDrain keys off, so draining on it would always burn the full
|
|
30
|
+
* drainTimeoutMs. Trailing events are handled by dropping the ctx from `_active`
|
|
31
|
+
* at once and deferring the handoff instead (next bullet).
|
|
32
|
+
* - Mutex handoff crosses a tick. A queued turn is NEVER started from inside a
|
|
33
|
+
* session-event callback (_scheduleNext). Providers emit a turn's terminal
|
|
34
|
+
* events from ONE synchronous frame — CliSession._handleChildClose emits
|
|
35
|
+
* `stream_end` + a synthetic `result` and THEN `stopped`; _handleHardTimeout /
|
|
36
|
+
* _handleStreamStall emit `result` then `error`; jsonl-subprocess's child-close
|
|
37
|
+
* and codex's _failTurn are the same shape — so starting the queued turn
|
|
38
|
+
* synchronously on the FIRST of them handed the rest of that frame to the wrong
|
|
39
|
+
* turn: the epoch guard could not drop those events because a fresh live ctx was
|
|
40
|
+
* already registered. That is #6723's cross-turn misattribution through the door
|
|
41
|
+
* the post-timeout drain does not cover (it is the result/error/stopped path that
|
|
42
|
+
* releases the mutex, not the timeout path).
|
|
43
|
+
* RESIDUAL: `stopped` carries no turn id, so a provider that emitted a turn's
|
|
44
|
+
* terminal event and THEN `stopped` in a LATER macrotask would still settle the
|
|
45
|
+
* following turn. No in-tree provider does that (every emit site listed above is
|
|
46
|
+
* a single synchronous frame); closing it by construction needs a provider-side
|
|
47
|
+
* turn id on the event payload.
|
|
48
|
+
* - PARTLY closed (#7036) — be precise about which half.
|
|
49
|
+
* CliSession emits its synthetic interrupted `result` (cost:null, load-bearing
|
|
50
|
+
* for clearing the dashboard spinner) BEFORE `stopped`. Two harms follow: the
|
|
51
|
+
* turn settles as a SUCCESS on the `result`, and (since #7033) the trailing
|
|
52
|
+
* `stopped` lands on the NEXT queued turn and kills it.
|
|
53
|
+
*
|
|
54
|
+
* The QUEUED-TURN KILL is now closed by construction: only claude-cli emits
|
|
55
|
+
* `result` then `stopped` for one interrupt, and claude-cli cannot enter
|
|
56
|
+
* TurnDriver by ANY route — the scheduler requires
|
|
57
|
+
* capabilities.inProcessPermissions (cli-session sets it false), the
|
|
58
|
+
* orchestration WORKER roles are gated on AUDIT/IMPLEMENT_ELIGIBLE_PROVIDERS,
|
|
59
|
+
* and the ARCHITECT role is now gated on ARCHITECT_ELIGIBLE_PROVIDERS.
|
|
60
|
+
*
|
|
61
|
+
* The FALSE SUCCESS is NOT closed, and eligibility does not imply immunity:
|
|
62
|
+
* claude-byok can fall through to a normal `result` when an interrupt lands in
|
|
63
|
+
* the tool phase, and claude-sdk's stream-stall path emits `result` then
|
|
64
|
+
* `error` (this driver settles on the `result`; the epoch guard drops the
|
|
65
|
+
* `error`). Codex app-server depends on what the binary answers to
|
|
66
|
+
* `turn/interrupt`, which is unverified here. Closing that needs the
|
|
67
|
+
* provider-side `interrupted: true` flag so a terminal-looking result can be
|
|
68
|
+
* marked terminal-but-NOT-successful — a cross-provider wire change, not
|
|
69
|
+
* something a provider allowlist can express.
|
|
70
|
+
* - Watchdog: on timeout, interrupt() the session and reject TURN_TIMEOUT.
|
|
71
|
+
* - `session_destroyed` mid-turn → SESSION_GONE.
|
|
72
|
+
*/
|
|
73
|
+
|
|
74
|
+
export const MAX_ACCUM_BYTES = 2 * 1024 * 1024
|
|
75
|
+
export const DEFAULT_TURN_TIMEOUT_MS = 30 * 60 * 1000
|
|
76
|
+
// After a timeout+interrupt the mutex is held in a "draining" state until the
|
|
77
|
+
// session confirms it stopped (a trailing result/error/stopped), so a late
|
|
78
|
+
// event from the interrupted turn can't be misattributed to the next turn.
|
|
79
|
+
// This bounds how long we wait for that confirmation before releasing anyway.
|
|
80
|
+
export const DEFAULT_DRAIN_TIMEOUT_MS = 10 * 1000
|
|
81
|
+
const TRUNCATION_MARKER = '\n…[chroxy-orch: output truncated at 2MB]…\n'
|
|
82
|
+
|
|
83
|
+
export class TurnError extends Error {
|
|
84
|
+
constructor(code, message, { partialText = '' } = {}) {
|
|
85
|
+
super(message || code)
|
|
86
|
+
this.name = 'TurnError'
|
|
87
|
+
this.code = code // TURN_ERROR | TURN_TIMEOUT | TURN_STOPPED | SESSION_GONE | SEND_FAILED
|
|
88
|
+
this.partialText = partialText
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export class TurnDriver {
|
|
93
|
+
/**
|
|
94
|
+
* @param {{ sessionManager: import('node:events').EventEmitter, log?: object,
|
|
95
|
+
* defaultTimeoutMs?: number }} opts
|
|
96
|
+
*/
|
|
97
|
+
constructor({ sessionManager, log = null, defaultTimeoutMs = DEFAULT_TURN_TIMEOUT_MS, drainTimeoutMs = DEFAULT_DRAIN_TIMEOUT_MS }) {
|
|
98
|
+
if (!sessionManager || typeof sessionManager.on !== 'function') {
|
|
99
|
+
throw new Error('TurnDriver requires a sessionManager EventEmitter')
|
|
100
|
+
}
|
|
101
|
+
this._sm = sessionManager
|
|
102
|
+
this._log = log
|
|
103
|
+
this._defaultTimeoutMs = defaultTimeoutMs
|
|
104
|
+
this._drainTimeoutMs = drainTimeoutMs
|
|
105
|
+
this._active = new Map() // sessionId -> active turn context
|
|
106
|
+
this._occupied = new Set() // sessionId -> has a turn running or reserved
|
|
107
|
+
this._waiters = new Map() // sessionId -> FIFO array of { start, reject }
|
|
108
|
+
this._handoff = new Set() // sessionId -> a deferred _startNext is already queued
|
|
109
|
+
this._onSessionEvent = this._handleSessionEvent.bind(this)
|
|
110
|
+
this._onSessionDestroyed = this._handleSessionDestroyed.bind(this)
|
|
111
|
+
this._sm.on('session_event', this._onSessionEvent)
|
|
112
|
+
this._sm.on('session_destroyed', this._onSessionDestroyed)
|
|
113
|
+
this._disposed = false
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
dispose() {
|
|
117
|
+
this._disposed = true
|
|
118
|
+
this._sm.off?.('session_event', this._onSessionEvent)
|
|
119
|
+
this._sm.off?.('session_destroyed', this._onSessionDestroyed)
|
|
120
|
+
// Reject queued (never-started) turns so their promises settle instead of
|
|
121
|
+
// hanging forever, then reject in-flight ones. Snapshot before mutating.
|
|
122
|
+
const waiters = [...this._waiters.values()].flat()
|
|
123
|
+
const active = [...this._active.values()]
|
|
124
|
+
this._waiters.clear()
|
|
125
|
+
this._active.clear()
|
|
126
|
+
this._occupied.clear()
|
|
127
|
+
this._handoff.clear()
|
|
128
|
+
for (const w of waiters) {
|
|
129
|
+
try { w.reject(new TurnError('SESSION_GONE', 'TurnDriver disposed')) } catch { /* ignore */ }
|
|
130
|
+
}
|
|
131
|
+
for (const ctx of active) {
|
|
132
|
+
if (ctx.drainTimer) { clearTimeout(ctx.drainTimer); ctx.drainTimer = null }
|
|
133
|
+
if (ctx.settled) continue
|
|
134
|
+
ctx.settled = true
|
|
135
|
+
if (ctx.timer) { clearTimeout(ctx.timer); ctx.timer = null }
|
|
136
|
+
ctx.reject(new TurnError('SESSION_GONE', 'TurnDriver disposed', { partialText: ctx.text() }))
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Drive one turn: send `prompt`, accumulate output, resolve on `result`.
|
|
142
|
+
* The turn's context is registered SYNCHRONOUSLY with its send, so no event can
|
|
143
|
+
* arrive before the accumulator exists (a fast provider can emit before the
|
|
144
|
+
* returned promise is even awaited). Contended turns queue FIFO and start on the
|
|
145
|
+
* tick after the prior turn releases — never inside the frame that released it
|
|
146
|
+
* (_scheduleNext).
|
|
147
|
+
* @returns {Promise<{ text: string, result: { cost, duration, usage, modelUsage, model, numTurns, apiDurationMs } }>}
|
|
148
|
+
* @throws {TurnError}
|
|
149
|
+
*/
|
|
150
|
+
driveTurn(sessionId, prompt, { label = null, timeoutMs = null } = {}) {
|
|
151
|
+
if (this._disposed) return Promise.reject(new TurnError('SESSION_GONE', 'TurnDriver disposed'))
|
|
152
|
+
const entry = this._sm.getSession?.(sessionId)
|
|
153
|
+
if (!entry || !entry.session) return Promise.reject(new TurnError('SESSION_GONE', `session ${sessionId} not found`))
|
|
154
|
+
|
|
155
|
+
return new Promise((resolve, reject) => {
|
|
156
|
+
const start = () => this._beginTurn(sessionId, prompt, { label, timeoutMs }, resolve, reject)
|
|
157
|
+
if (!this._occupied.has(sessionId)) {
|
|
158
|
+
this._occupied.add(sessionId)
|
|
159
|
+
start()
|
|
160
|
+
} else {
|
|
161
|
+
const q = this._waiters.get(sessionId) || []
|
|
162
|
+
q.push({ start, reject })
|
|
163
|
+
this._waiters.set(sessionId, q)
|
|
164
|
+
}
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
_beginTurn(sessionId, prompt, { label, timeoutMs }, resolve, reject) {
|
|
169
|
+
// Re-fetch the session at START time, not at driveTurn() time: a queued turn
|
|
170
|
+
// may have waited behind the mutex while its session was destroyed/replaced.
|
|
171
|
+
const entry = this._sm.getSession?.(sessionId)
|
|
172
|
+
if (!entry || !entry.session) {
|
|
173
|
+
reject(new TurnError('SESSION_GONE', `session ${sessionId} gone before its turn started`))
|
|
174
|
+
this._scheduleNext(sessionId)
|
|
175
|
+
return
|
|
176
|
+
}
|
|
177
|
+
const ctx = {
|
|
178
|
+
sessionId,
|
|
179
|
+
label,
|
|
180
|
+
buffers: new Map(), // messageId -> streamed text
|
|
181
|
+
order: [], // {kind:'buf',mid} | {kind:'resp',text} in arrival order
|
|
182
|
+
bytes: 0,
|
|
183
|
+
truncated: false,
|
|
184
|
+
settled: false,
|
|
185
|
+
timer: null,
|
|
186
|
+
resolve,
|
|
187
|
+
reject,
|
|
188
|
+
}
|
|
189
|
+
ctx.text = () => this._assembleText(ctx)
|
|
190
|
+
this._active.set(sessionId, ctx)
|
|
191
|
+
|
|
192
|
+
const ms = Number.isFinite(timeoutMs) ? timeoutMs : this._defaultTimeoutMs
|
|
193
|
+
// NOT unref'd: an in-flight orchestration turn is real work that should hold
|
|
194
|
+
// the process open, and the timer is always cleared on turn completion /
|
|
195
|
+
// dispose (so it never leaks — cf. the #6027 leaked-handle family).
|
|
196
|
+
ctx.timer = setTimeout(() => {
|
|
197
|
+
try { entry.session.interrupt?.() } catch { /* best-effort */ }
|
|
198
|
+
// Drain: settle the caller now, but HOLD the mutex until the interrupted
|
|
199
|
+
// session confirms it stopped, so its trailing events don't leak into the
|
|
200
|
+
// next turn (finding #6723).
|
|
201
|
+
this._finishTurn(ctx, () => ctx.reject(new TurnError('TURN_TIMEOUT', `turn timed out after ${ms}ms`, { partialText: ctx.text() })), { drain: true })
|
|
202
|
+
}, ms)
|
|
203
|
+
|
|
204
|
+
// Fire-and-forget send; a rejection (closing socket, etc.) is SEND_FAILED —
|
|
205
|
+
// NEVER leave it unhandled (an unhandled rejection crashes the daemon).
|
|
206
|
+
try {
|
|
207
|
+
const ret = entry.session.sendMessage(prompt, [], { clientMessageId: `orch-${label || 'turn'}` })
|
|
208
|
+
if (ret && typeof ret.then === 'function') {
|
|
209
|
+
ret.catch((err) => {
|
|
210
|
+
this._finishTurn(ctx, () => ctx.reject(new TurnError('SEND_FAILED', (err && err.message) || 'sendMessage rejected', { partialText: ctx.text() })))
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
} catch (err) {
|
|
214
|
+
this._finishTurn(ctx, () => ctx.reject(new TurnError('SEND_FAILED', (err && err.message) || 'sendMessage threw', { partialText: ctx.text() })))
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Hand the per-session mutex to the next queued turn — but never from inside the
|
|
220
|
+
* frame that released it. A provider emits a turn's terminal events (`stream_end`
|
|
221
|
+
* + a synthetic `result` + `stopped`, or `result` + `error`) from ONE synchronous
|
|
222
|
+
* frame; starting the queued turn on the first of them registered a live ctx that
|
|
223
|
+
* the REST of the frame then landed on, which is how a finished turn's trailing
|
|
224
|
+
* `stopped` came to reject the next turn (#7033 review). Deferring to
|
|
225
|
+
* process.nextTick puts the ctx removal in _finishTurn and the next ctx's
|
|
226
|
+
* registration on opposite sides of the frame boundary, so the epoch guard in
|
|
227
|
+
* _handleSessionEvent drops those trailing events instead of misattributing them.
|
|
228
|
+
*
|
|
229
|
+
* `_occupied` stays set across the gap, so a driveTurn() landing inside it queues
|
|
230
|
+
* rather than racing ahead. At most ONE handoff may be pending per session: two
|
|
231
|
+
* would each shift a waiter off the FIFO and start it, breaking the mutex.
|
|
232
|
+
*/
|
|
233
|
+
_scheduleNext(sessionId) {
|
|
234
|
+
if (this._handoff.has(sessionId)) return
|
|
235
|
+
this._handoff.add(sessionId)
|
|
236
|
+
process.nextTick(() => {
|
|
237
|
+
this._handoff.delete(sessionId)
|
|
238
|
+
if (this._disposed) return
|
|
239
|
+
this._startNext(sessionId)
|
|
240
|
+
})
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
_startNext(sessionId) {
|
|
244
|
+
const q = this._waiters.get(sessionId)
|
|
245
|
+
if (q && q.length > 0) {
|
|
246
|
+
const next = q.shift() // stays occupied — hand the slot to the next turn
|
|
247
|
+
next.start()
|
|
248
|
+
} else {
|
|
249
|
+
this._occupied.delete(sessionId)
|
|
250
|
+
this._waiters.delete(sessionId)
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
_handleSessionEvent({ sessionId, event, data } = {}) {
|
|
255
|
+
const ctx = this._active.get(sessionId)
|
|
256
|
+
if (!ctx) return // epoch guard: no active/draining turn for this session → drop
|
|
257
|
+
if (ctx.draining) {
|
|
258
|
+
// A settled-but-draining turn (post-timeout). Swallow its trailing output;
|
|
259
|
+
// a terminal event confirms the session stopped → release the mutex.
|
|
260
|
+
if (event === 'result' || event === 'error' || event === 'stopped' || event === 'stream_end') {
|
|
261
|
+
this._endDrain(ctx)
|
|
262
|
+
}
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
if (ctx.settled) return
|
|
266
|
+
switch (event) {
|
|
267
|
+
case 'stream_delta': {
|
|
268
|
+
const mid = data?.messageId ?? '_'
|
|
269
|
+
const delta = typeof data?.delta === 'string' ? data.delta : ''
|
|
270
|
+
if (!delta) break
|
|
271
|
+
if (!ctx.buffers.has(mid)) { ctx.buffers.set(mid, ''); ctx.order.push({ kind: 'buf', mid }) }
|
|
272
|
+
ctx.buffers.set(mid, ctx.buffers.get(mid) + this._boundedAccept(ctx, delta))
|
|
273
|
+
break
|
|
274
|
+
}
|
|
275
|
+
case 'message': {
|
|
276
|
+
if (data?.type === 'response' && typeof data.content === 'string' && data.content.length) {
|
|
277
|
+
const accepted = this._boundedAccept(ctx, data.content)
|
|
278
|
+
if (accepted.length) ctx.order.push({ kind: 'resp', text: accepted })
|
|
279
|
+
}
|
|
280
|
+
break
|
|
281
|
+
}
|
|
282
|
+
case 'result': {
|
|
283
|
+
// Forward the FULL terminal usage payload, not just cost/duration/usage:
|
|
284
|
+
// the ledger's recordTurnUsage keys off modelUsage/model/numTurns/
|
|
285
|
+
// apiDurationMs for per-model attribution (#6692). Dropping them here
|
|
286
|
+
// would silently collapse every metered run to a single unknown model.
|
|
287
|
+
const result = {
|
|
288
|
+
cost: data?.cost ?? null,
|
|
289
|
+
duration: data?.duration ?? null,
|
|
290
|
+
usage: data?.usage ?? null,
|
|
291
|
+
modelUsage: data?.modelUsage ?? null,
|
|
292
|
+
model: data?.model ?? null,
|
|
293
|
+
numTurns: Number.isFinite(data?.numTurns) ? data.numTurns : null,
|
|
294
|
+
apiDurationMs: Number.isFinite(data?.apiDurationMs) ? data.apiDurationMs : null,
|
|
295
|
+
}
|
|
296
|
+
const text = this._assembleText(ctx)
|
|
297
|
+
this._finishTurn(ctx, () => ctx.resolve({ text, result }))
|
|
298
|
+
break
|
|
299
|
+
}
|
|
300
|
+
case 'error': {
|
|
301
|
+
this._finishTurn(ctx, () => ctx.reject(new TurnError('TURN_ERROR', (data && data.message) || 'session error', { partialText: this._assembleText(ctx) })))
|
|
302
|
+
break
|
|
303
|
+
}
|
|
304
|
+
case 'stopped': {
|
|
305
|
+
// #7009 — someone interrupted this turn (the scheduler denying a
|
|
306
|
+
// permission prompt, an operator pressing Stop, an orchestration cancel).
|
|
307
|
+
// Providers emit `stopped` INSTEAD of `result`/`error` on that path
|
|
308
|
+
// (#4881), so ignoring it left driveTurn pending until the watchdog —
|
|
309
|
+
// 15 minutes of a held concurrency slot in the scheduler.
|
|
310
|
+
//
|
|
311
|
+
// Deliberately a REJECTION with its own code, never a resolve: the turn
|
|
312
|
+
// is over but its work did not complete, and resolving here would report
|
|
313
|
+
// an interrupted turn as a finished one. partialText carries whatever the
|
|
314
|
+
// turn managed to produce so the caller can still inspect it.
|
|
315
|
+
//
|
|
316
|
+
// This can only be THIS turn's `stopped`: a `stopped` trailing a turn that
|
|
317
|
+
// already settled arrives in the same synchronous frame as that settle, and
|
|
318
|
+
// the queued turn is not started until the next tick (_scheduleNext), so it
|
|
319
|
+
// hits the epoch guard with no active ctx. No drain here — `stopped` is the
|
|
320
|
+
// event _endDrain waits for, so draining on it would burn drainTimeoutMs
|
|
321
|
+
// every time.
|
|
322
|
+
this._finishTurn(ctx, () => ctx.reject(new TurnError('TURN_STOPPED', 'turn interrupted before completing', { partialText: this._assembleText(ctx) })))
|
|
323
|
+
break
|
|
324
|
+
}
|
|
325
|
+
default:
|
|
326
|
+
break
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
_handleSessionDestroyed({ sessionId } = {}) {
|
|
331
|
+
const ctx = this._active.get(sessionId)
|
|
332
|
+
if (!ctx || ctx.settled) return
|
|
333
|
+
this._finishTurn(ctx, () => ctx.reject(new TurnError('SESSION_GONE', `session ${sessionId} destroyed mid-turn`, { partialText: this._assembleText(ctx) })))
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// Accept as much of `str` as fits under the 2MB accumulator budget; returns
|
|
337
|
+
// the accepted text (with a truncation marker appended once, on the crossing).
|
|
338
|
+
// Pure w.r.t. `order` — the caller decides where the accepted text lands.
|
|
339
|
+
_boundedAccept(ctx, str) {
|
|
340
|
+
if (ctx.truncated) return ''
|
|
341
|
+
const room = MAX_ACCUM_BYTES - ctx.bytes
|
|
342
|
+
const bytes = Buffer.byteLength(str, 'utf8')
|
|
343
|
+
if (bytes <= room) {
|
|
344
|
+
ctx.bytes += bytes
|
|
345
|
+
return str
|
|
346
|
+
}
|
|
347
|
+
// over budget — take the codepoints that fit (stream decode drops a trailing
|
|
348
|
+
// partial sequence), then mark truncated so later output is ignored.
|
|
349
|
+
const slice = new TextDecoder('utf8').decode(Buffer.from(str, 'utf8').subarray(0, Math.max(0, room)), { stream: true })
|
|
350
|
+
ctx.bytes = MAX_ACCUM_BYTES
|
|
351
|
+
ctx.truncated = true
|
|
352
|
+
return slice + TRUNCATION_MARKER
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
_assembleText(ctx) {
|
|
356
|
+
// Concatenate in arrival order: streamed buffers by messageId + inline
|
|
357
|
+
// response strings. Falls back to nothing if empty (caller may read history).
|
|
358
|
+
const parts = []
|
|
359
|
+
for (const item of ctx.order) {
|
|
360
|
+
if (item.kind === 'buf') parts.push(ctx.buffers.get(item.mid) || '')
|
|
361
|
+
else parts.push(item.text)
|
|
362
|
+
}
|
|
363
|
+
return parts.join('')
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
_finishTurn(ctx, settle, { drain = false } = {}) {
|
|
367
|
+
if (ctx.settled) return
|
|
368
|
+
ctx.settled = true
|
|
369
|
+
if (ctx.timer) { clearTimeout(ctx.timer); ctx.timer = null }
|
|
370
|
+
// Settle the caller's promise immediately either way.
|
|
371
|
+
try { settle() } catch { /* settle should not throw */ }
|
|
372
|
+
if (drain) {
|
|
373
|
+
// Keep the ctx in _active (marked draining) so the mutex stays held and
|
|
374
|
+
// this session's trailing events are swallowed until it confirms it
|
|
375
|
+
// stopped or the drain watchdog fires.
|
|
376
|
+
ctx.draining = true
|
|
377
|
+
// unref'd: the caller's promise is already settled, so nothing awaited
|
|
378
|
+
// depends on this; it's just a grace period before releasing the mutex,
|
|
379
|
+
// and the process shouldn't stay alive for it. Normally a trailing
|
|
380
|
+
// terminal event ends the drain well before this fires.
|
|
381
|
+
ctx.drainTimer = setTimeout(() => this._endDrain(ctx), this._drainTimeoutMs)
|
|
382
|
+
if (typeof ctx.drainTimer.unref === 'function') ctx.drainTimer.unref()
|
|
383
|
+
} else {
|
|
384
|
+
// Drop the ctx NOW so every remaining event in this frame hits the epoch
|
|
385
|
+
// guard, and hand the mutex over on the next tick (see _scheduleNext).
|
|
386
|
+
this._active.delete(ctx.sessionId)
|
|
387
|
+
this._scheduleNext(ctx.sessionId)
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
_endDrain(ctx) {
|
|
392
|
+
if (ctx.drainTimer) { clearTimeout(ctx.drainTimer); ctx.drainTimer = null }
|
|
393
|
+
if (this._active.get(ctx.sessionId) === ctx) {
|
|
394
|
+
this._active.delete(ctx.sessionId)
|
|
395
|
+
this._scheduleNext(ctx.sessionId)
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
package/src/pairing.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* Recently-refreshed IDs remain valid until their TTL expires (grace period).
|
|
9
9
|
*/
|
|
10
10
|
import { EventEmitter } from 'events'
|
|
11
|
-
import { randomBytes, timingSafeEqual } from 'crypto'
|
|
11
|
+
import { randomBytes, timingSafeEqual, createHash } from 'crypto'
|
|
12
12
|
import { createLogger } from './logger.js'
|
|
13
13
|
|
|
14
14
|
const log = createLogger('pairing')
|
|
@@ -412,6 +412,107 @@ export class PairingManager extends EventEmitter {
|
|
|
412
412
|
return meta ? (meta.sessionId || null) : null
|
|
413
413
|
}
|
|
414
414
|
|
|
415
|
+
/**
|
|
416
|
+
* A stable, non-reversible identifier for a session token, safe to put on the
|
|
417
|
+
* wire — the operator UI needs a handle to name a device for revoke, but the
|
|
418
|
+
* token itself must never leave the daemon (#6678). Deterministic (so a
|
|
419
|
+
* list → revoke round-trip resolves the same token) and one-way (a SHA-256
|
|
420
|
+
* digest discloses nothing about the token). 16 hex chars ≈ 64 bits — no
|
|
421
|
+
* collision risk across the ≤100-token cap.
|
|
422
|
+
* @param {string} token
|
|
423
|
+
* @returns {string}
|
|
424
|
+
*/
|
|
425
|
+
_deviceIdForToken(token) {
|
|
426
|
+
return createHash('sha256').update(token).digest('hex').slice(0, 16)
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Live snapshot of the paired-device session tokens for an operator surface
|
|
431
|
+
* (#6678 — the dashboard Paired Devices panel). Sweeps expired tokens first so
|
|
432
|
+
* the roster is current, then maps each surviving token to a wire-safe view:
|
|
433
|
+
* a stable non-reversible id (NEVER the token itself), its bound sessionId
|
|
434
|
+
* (null = unbound / full-access, like a linking-mode QR pairing), when it was
|
|
435
|
+
* minted or last refreshed (createdAt slides on each connect), the derived age,
|
|
436
|
+
* and an optional device label (not captured yet — the deviceName follow-up).
|
|
437
|
+
* @returns {Array<{ id: string, sessionId: string|null, createdAt: number|null, ageMs: number|null, deviceName: string|null }>}
|
|
438
|
+
*/
|
|
439
|
+
listSessionTokens() {
|
|
440
|
+
this._sweepSessionTokens()
|
|
441
|
+
const now = Date.now()
|
|
442
|
+
const out = []
|
|
443
|
+
for (const [token, meta] of this._sessionTokens) {
|
|
444
|
+
const createdAt = typeof meta.createdAt === 'number' ? meta.createdAt : null
|
|
445
|
+
out.push({
|
|
446
|
+
id: this._deviceIdForToken(token),
|
|
447
|
+
sessionId: (typeof meta.sessionId === 'string' && meta.sessionId) || null,
|
|
448
|
+
createdAt,
|
|
449
|
+
ageMs: createdAt !== null ? now - createdAt : null,
|
|
450
|
+
deviceName: typeof meta.deviceName === 'string' ? meta.deviceName : null,
|
|
451
|
+
})
|
|
452
|
+
}
|
|
453
|
+
return out
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Live-revoke a single paired device by its wire id (from listSessionTokens).
|
|
458
|
+
* Drops the token from the RUNNING daemon's in-memory map and persists, so the
|
|
459
|
+
* device's next auth fails immediately — no restart required. This closes the
|
|
460
|
+
* gap the `chroxy tokens revoke` CLI left (it edits the persisted store only,
|
|
461
|
+
* which a running daemon overwrites from memory until restarted). Comparing
|
|
462
|
+
* derived ids (not the token) needs no constant-time guard — the id is not
|
|
463
|
+
* secret.
|
|
464
|
+
*
|
|
465
|
+
* #6902: durably persist the POST-removal snapshot BEFORE dropping the token
|
|
466
|
+
* from memory, so a crash between the two can never resurrect the revoked token
|
|
467
|
+
* on the next start (fail-CLOSED, mirroring how mint is fail-safe). If the
|
|
468
|
+
* durable write fails, the token stays valid AND persisted (memory + disk
|
|
469
|
+
* agree) and we report `persistFailed` rather than a false success — the
|
|
470
|
+
* operator can retry instead of believing a revoke that a crash would undo.
|
|
471
|
+
*
|
|
472
|
+
* @param {string} id
|
|
473
|
+
* @returns {{ revoked: number, persistFailed?: boolean }} `revoked` is 1 on
|
|
474
|
+
* success, 0 if no device matched OR the durable write failed; `persistFailed`
|
|
475
|
+
* is set only in the write-failed case (the device exists but stays valid).
|
|
476
|
+
*/
|
|
477
|
+
revokeSessionTokenById(id) {
|
|
478
|
+
if (this._destroyed || typeof id !== 'string' || id.length === 0) return { revoked: 0 }
|
|
479
|
+
for (const token of this._sessionTokens.keys()) {
|
|
480
|
+
if (this._deviceIdForToken(token) === id) {
|
|
481
|
+
// Persist the map WITHOUT this token first; only drop it from memory once
|
|
482
|
+
// that durable write has landed (see _persistSessionTokensSnapshot).
|
|
483
|
+
const remaining = [...this._sessionTokens.entries()].filter(([t]) => t !== token)
|
|
484
|
+
if (!this._persistSessionTokensSnapshot(remaining)) return { revoked: 0, persistFailed: true }
|
|
485
|
+
this._sessionTokens.delete(token)
|
|
486
|
+
return { revoked: 1 }
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return { revoked: 0 }
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Live-revoke EVERY paired device — the operator panic button (#6678). Clears
|
|
494
|
+
* the in-memory map and persists, so all paired devices must re-pair; effective
|
|
495
|
+
* on the running daemon (their next auth fails), no restart.
|
|
496
|
+
*
|
|
497
|
+
* #6902: durably persist the EMPTIED snapshot BEFORE clearing memory, so a
|
|
498
|
+
* crash mid-revoke can't resurrect the whole roster on restart (fail-CLOSED).
|
|
499
|
+
* If the durable write fails, every token stays valid (memory + disk agree) and
|
|
500
|
+
* we report `persistFailed` rather than a false success.
|
|
501
|
+
*
|
|
502
|
+
* @returns {{ revoked: number, persistFailed?: boolean }} `revoked` is the count
|
|
503
|
+
* removed (0 when nothing was paired OR the durable write failed);
|
|
504
|
+
* `persistFailed` is set only in the write-failed case (all tokens stay valid).
|
|
505
|
+
*/
|
|
506
|
+
revokeAllSessionTokens() {
|
|
507
|
+
if (this._destroyed) return { revoked: 0 }
|
|
508
|
+
const n = this._sessionTokens.size
|
|
509
|
+
if (n === 0) return { revoked: 0 }
|
|
510
|
+
// Persist the emptied store first; only clear memory once it has landed.
|
|
511
|
+
if (!this._persistSessionTokensSnapshot([])) return { revoked: 0, persistFailed: true }
|
|
512
|
+
this._sessionTokens.clear()
|
|
513
|
+
return { revoked: n }
|
|
514
|
+
}
|
|
515
|
+
|
|
415
516
|
/**
|
|
416
517
|
* Look up a session token using constant-time comparison.
|
|
417
518
|
* Prunes expired tokens on access.
|
|
@@ -480,6 +581,50 @@ export class PairingManager extends EventEmitter {
|
|
|
480
581
|
} catch { /* store logs; a failed persist just means a restart may re-pair */ }
|
|
481
582
|
}
|
|
482
583
|
|
|
584
|
+
/**
|
|
585
|
+
* #6902: persist an explicit entries SNAPSHOT and REPORT whether the durable
|
|
586
|
+
* write succeeded. This is the fail-CLOSED counterpart to `_persistSessionTokens`
|
|
587
|
+
* (fire-and-forget, used for the fail-SAFE structural changes — mint / sweep /
|
|
588
|
+
* slide — where a lost persist merely forces a harmless re-pair).
|
|
589
|
+
*
|
|
590
|
+
* A REVOKE is the asymmetric case: dropping the token from the in-memory map
|
|
591
|
+
* FIRST and persisting best-effort is fail-OPEN — a crash between the in-memory
|
|
592
|
+
* delete and the durable write leaves the revoked token in `session-tokens.json`,
|
|
593
|
+
* so it RESURRECTS and authenticates on the next start. The revoke callers use
|
|
594
|
+
* this helper to persist the post-removal snapshot BEFORE they mutate the map,
|
|
595
|
+
* and only proceed if it durably landed — so a crash at any point either keeps
|
|
596
|
+
* the token fully valid (memory + disk agree, operator can retry) or leaves it
|
|
597
|
+
* revoked on disk. It can never resurrect.
|
|
598
|
+
*
|
|
599
|
+
* The store's `save()` is atomic (temp file + rename via `writeFileRestricted`),
|
|
600
|
+
* so the on-disk file is always either the pre- or the post-removal state, never
|
|
601
|
+
* a torn write; here it is also DURABLE (#6914) — `save(entries, { durable: true })`
|
|
602
|
+
* fsyncs the temp file before the rename and the directory after, so a power
|
|
603
|
+
* loss / kernel panic within the OS writeback window cannot roll the revoked-out
|
|
604
|
+
* snapshot back after we reported success. With no store configured (in-memory-only mode) there is no
|
|
605
|
+
* durability to lose — a restart wipes every token regardless — so we report
|
|
606
|
+
* success and let the caller mutate memory.
|
|
607
|
+
*
|
|
608
|
+
* @param {Array<[string, object]>} entries - the target `[token, meta]` snapshot
|
|
609
|
+
* @returns {boolean} true iff the snapshot is durably persisted (or no store)
|
|
610
|
+
*/
|
|
611
|
+
_persistSessionTokensSnapshot(entries) {
|
|
612
|
+
if (!this._sessionTokenStore) return true
|
|
613
|
+
try {
|
|
614
|
+
// #6914: DURABLE write — fsync the store before reporting success, so a
|
|
615
|
+
// power loss / kernel panic within the OS writeback window can't roll the
|
|
616
|
+
// revoked-out snapshot back to its pre-removal state after the operator was
|
|
617
|
+
// told the revoke landed. This is the one persist path that opts in; the
|
|
618
|
+
// fire-and-forget `_persistSessionTokens` (mint / slide / sweep) is
|
|
619
|
+
// fail-SAFE and stays non-durable to avoid an fsync per token issuance.
|
|
620
|
+
return this._sessionTokenStore.save(entries, { durable: true }) === true
|
|
621
|
+
} catch {
|
|
622
|
+
// A store whose save() throws (rather than returning false) is a failed
|
|
623
|
+
// persist just the same — report it so the revoke reports failure.
|
|
624
|
+
return false
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
483
628
|
/**
|
|
484
629
|
* #6598: persist a sliding-expiry refresh, throttled to at most once per
|
|
485
630
|
* SLIDE_PERSIST_THROTTLE_MS so a reconnect-happy client doesn't churn the disk.
|
package/src/permission-audit.js
CHANGED
|
@@ -55,18 +55,34 @@ export class PermissionAuditLog {
|
|
|
55
55
|
* @param {string|null} params.clientId - Identifies the responder. Three states:
|
|
56
56
|
* - WS-origin user response: the connection's synthetic id (e.g. an 8-char hex)
|
|
57
57
|
* - HTTP-origin user response: the literal string 'http' (#3059)
|
|
58
|
-
* - Auto-deny paths (timeout / aborted / cleared)
|
|
58
|
+
* - Auto-deny paths (timeout / aborted / cleared) and rule-driven
|
|
59
|
+
* auto-approvals (#6830): null (no human responder)
|
|
59
60
|
* @param {string|null} params.sessionId - Session the permission belongs to,
|
|
60
61
|
* or null for genuinely unmapped legacy HTTP requests (see ws-permissions.js
|
|
61
62
|
* legacy branch — pendingPermissions entry with no permissionSessionMap entry).
|
|
62
63
|
* @param {string} params.requestId - The permission request ID
|
|
63
|
-
* @param {string} params.decision - 'allow' or '
|
|
64
|
+
* @param {string} params.decision - 'allow', 'deny', or 'allowAlways'
|
|
64
65
|
* @param {string} [params.reason] - How the permission was resolved.
|
|
65
66
|
* Defaults to 'user' for backwards compatibility with the inline WS-path
|
|
66
67
|
* audit. Auto-deny paths pass 'timeout' | 'aborted' | 'cleared' so
|
|
67
68
|
* forensic queries can distinguish user denies from auto-denies (#3057).
|
|
69
|
+
* (Persisted-rule auto-approves do NOT go through this method — they use
|
|
70
|
+
* the coalescing {@link logPersistedRuleApproval}, #6830.)
|
|
71
|
+
* @param {string|null} [params.tool] - The tool the decision applied to
|
|
72
|
+
* (#6830). Without this, `_lastPermissionData` (which carries the tool
|
|
73
|
+
* name) is already deleted by the time an auditor queries the log, so a
|
|
74
|
+
* `requestId -> tool` lookup is impossible from the audit trail alone.
|
|
75
|
+
* Defaults to null so pre-#6830 callers keep working.
|
|
76
|
+
* @param {string|null} [params.persist] - `'project'` when this decision
|
|
77
|
+
* resulted in (or matched) a DURABLE project-scoped rule (#6771/#6830) —
|
|
78
|
+
* set on an `allowAlways` that the rule store actually persisted, and on
|
|
79
|
+
* a `reason:'persisted_rule'` auto-approve. Null otherwise (a one-shot
|
|
80
|
+
* allow/deny, or an `allowAlways` on a NEVER_AUTO_ALLOW / non-eligible
|
|
81
|
+
* tool that degrades to a one-time allow with nothing persisted).
|
|
82
|
+
* @param {string|null} [params.projectKey] - The normalized project cwd the
|
|
83
|
+
* persisted rule is scoped to (present only alongside `persist:'project'`).
|
|
68
84
|
*/
|
|
69
|
-
logDecision({ clientId, sessionId, requestId, decision, reason = 'user' }) {
|
|
85
|
+
logDecision({ clientId, sessionId, requestId, decision, reason = 'user', tool = null, persist = null, projectKey = null }) {
|
|
70
86
|
this._append({
|
|
71
87
|
type: 'decision',
|
|
72
88
|
clientId,
|
|
@@ -74,6 +90,66 @@ export class PermissionAuditLog {
|
|
|
74
90
|
requestId,
|
|
75
91
|
decision,
|
|
76
92
|
reason,
|
|
93
|
+
tool,
|
|
94
|
+
persist,
|
|
95
|
+
projectKey,
|
|
96
|
+
timestamp: Date.now(),
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* #6830 (PR #6842 review) — record a persisted (project-scoped) rule
|
|
102
|
+
* silently auto-approving a tool call, COALESCED per
|
|
103
|
+
* `(sessionId, tool, projectKey)`.
|
|
104
|
+
*
|
|
105
|
+
* Why coalesced: a convenience rule (always-allow Read / Write / Grep …)
|
|
106
|
+
* matches at machine speed in an agentic session — one raw entry per
|
|
107
|
+
* matched tool call would flood the 500-entry no-dedup ring and evict
|
|
108
|
+
* exactly the high-value entries (#6830's whole point: whitelist changes,
|
|
109
|
+
* user allow/deny decisions, mode changes) an auditor needs kept.
|
|
110
|
+
*
|
|
111
|
+
* Coalescing shape — "one live entry per key, with a running count":
|
|
112
|
+
* repeated approvals for the same key UPDATE the existing entry
|
|
113
|
+
* (`count`++, `timestamp` = now, `firstAt` preserved) and MOVE it to the
|
|
114
|
+
* ring tail so the query contract ("most recent entries = tail") stays
|
|
115
|
+
* true. Distinct sessions / tools / project keys keep distinct entries.
|
|
116
|
+
* There is deliberately no `requestId` and no `clientId` responder: no
|
|
117
|
+
* prompt was ever minted and no human answered — the rule did.
|
|
118
|
+
*
|
|
119
|
+
* @param {object} params
|
|
120
|
+
* @param {string|null} params.sessionId - Session whose tool call was auto-approved
|
|
121
|
+
* @param {string} params.tool - The auto-approved tool
|
|
122
|
+
* @param {string|null} [params.projectKey] - The NORMALIZED project cwd the
|
|
123
|
+
* durable rule is scoped to (permission-rule-store.js normalizeProjectKey —
|
|
124
|
+
* callers normalize before logging so the entry correlates with the
|
|
125
|
+
* persisted rule's key in permission-rules.json, #6842 review)
|
|
126
|
+
*/
|
|
127
|
+
logPersistedRuleApproval({ sessionId, tool, projectKey = null }) {
|
|
128
|
+
const idx = this._entries.findIndex((e) =>
|
|
129
|
+
e.type === 'decision'
|
|
130
|
+
&& e.reason === 'persisted_rule'
|
|
131
|
+
&& e.sessionId === sessionId
|
|
132
|
+
&& e.tool === tool
|
|
133
|
+
&& e.projectKey === projectKey,
|
|
134
|
+
)
|
|
135
|
+
if (idx >= 0) {
|
|
136
|
+
const [existing] = this._entries.splice(idx, 1)
|
|
137
|
+
existing.count = (existing.count || 1) + 1
|
|
138
|
+
existing.timestamp = Date.now()
|
|
139
|
+
this._entries.push(existing)
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
this._append({
|
|
143
|
+
type: 'decision',
|
|
144
|
+
clientId: null,
|
|
145
|
+
sessionId,
|
|
146
|
+
decision: 'allow',
|
|
147
|
+
reason: 'persisted_rule',
|
|
148
|
+
tool,
|
|
149
|
+
persist: 'project',
|
|
150
|
+
projectKey,
|
|
151
|
+
count: 1,
|
|
152
|
+
firstAt: Date.now(),
|
|
77
153
|
timestamp: Date.now(),
|
|
78
154
|
})
|
|
79
155
|
}
|