dsh-taskbridge 0.0.0-stage → 1.3.1

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 (74) hide show
  1. package/CHANGELOG.md +754 -0
  2. package/LICENSE +21 -0
  3. package/README.md +624 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-delegate.toml +245 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +32 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +922 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +293 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +220 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +135 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3260 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +454 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3609 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/mcp/server.js +1820 -0
  55. package/src/mcp/wait.js +536 -0
  56. package/src/model/connectivity.js +371 -0
  57. package/src/model/discovery.js +582 -0
  58. package/src/model/native-catalog.js +68 -0
  59. package/src/model/openai-adapter.js +671 -0
  60. package/src/model/probe.js +264 -0
  61. package/src/model/providers.js +756 -0
  62. package/src/model/routing.js +321 -0
  63. package/src/review/preset.js +868 -0
  64. package/src/review/prompts.js +126 -0
  65. package/src/review/reviewer.js +933 -0
  66. package/src/runtime/agent-runner.js +1738 -0
  67. package/src/runtime/endpoint-discovery.js +118 -0
  68. package/src/runtime/permissions.js +1429 -0
  69. package/src/runtime/sandbox.js +358 -0
  70. package/src/runtime/session-placement.js +1103 -0
  71. package/src/workspace/audit.js +775 -0
  72. package/src/workspace/locks.js +167 -0
  73. package/src/workspace/preflight.js +424 -0
  74. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,1429 @@
1
+ // Per-call permission bridge for delegated worker sessions.
2
+ //
3
+ // A delegated worker edits files inside its own workspace. DSH confines that with
4
+ // `workspace-write`, and until now the delegate policy also installed the
5
+ // `never` approval stance, because this plugin had no way to answer an approval
6
+ // prompt: any escalation was rejected deterministically and the worker could never
7
+ // ask for anything wider for a single call.
8
+ //
9
+ // This module is the ONE addition that changes that, and it is deliberately the
10
+ // narrowest thing that could: while the commander is actively following a task,
11
+ // a native DSH approval request pauses that exact tool call, is surfaced to the
12
+ // commander through the existing MCP result/status view, and is decided by the
13
+ // NEW bounded tool `delegate_permission_decide` as `allow-once` or `reject`.
14
+ //
15
+ // What it is NOT, stated here because the rest of the product depends on it:
16
+ //
17
+ // * it cannot grant an account, a workspace or a standing policy — the native
18
+ // approval seam already has exactly one grant outcome (`allowed-once`) and the
19
+ // tool contract here exposes only that and `reject`;
20
+ // * it cannot change settings, credentials, the switch, the provider/model, the
21
+ // ISOLATION or the worker's standing sandbox mode (`workspace-write` stays in
22
+ // place for the whole run; nothing here writes `danger-full-access` into a
23
+ // Session);
24
+ // * it cannot approve a FUTURE call. A request is bound to one native
25
+ // `callId`, to one task, to one Session, to one tool name, and to an exact
26
+ // fingerprint of the real tool arguments. It is consumed by the decision, and
27
+ // the next escalation asks again;
28
+ // * it is not a human-click workflow, an automatic allow-all rule, or an
29
+ // LLM/API reviewer. The decision is the commander's, taken by an external
30
+ // bounded call.
31
+ //
32
+ // ## The one native API this is built on (recorded evidence)
33
+ //
34
+ // Both supported DSH shapes expose the same two facts this module uses, verified
35
+ // against the installed sources rather than assumed:
36
+ //
37
+ // * `@deepseek-ai/dsh-user-approval` (`lib/index.js`, `ApprovalService.decide`):
38
+ // the asking tool's arguments are NOT carried on the approval request. The
39
+ // request is `{ agent, toolName, callId?, reason?, displayReason?, signal? }`
40
+ // and the outcome vocabulary is closed:
41
+ // `'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'`. The decision is
42
+ // dispatched as the agent-scoped waterfall `'approval/request'`, and a
43
+ // session whose effective policy is `never` is answered `'rejected'` BEFORE
44
+ // any listener runs — which is exactly why this module writes `ask` only when
45
+ // it is armed, and why an unarmed run keeps `never`.
46
+ // * `@deepseek-ai/dsh-sandbox` `approveEscalation`: a `sandbox_permissions`
47
+ // escalation is resolved through `ctx.approval.request({ agent, toolName,
48
+ // callId, reason, displayReason, signal })` before anything executes, and
49
+ // only `allowed-once` returns the wider mode for that one call.
50
+ //
51
+ // Because the approval request carries no arguments, the REAL operation is read
52
+ // from the native Session log: the requesting tool has already committed its
53
+ // `tool/call` event (`{ turn, step, callId, name, arguments }`) before it asks, so
54
+ // this module looks the call up by `callId` and parses the model's own argument
55
+ // JSON. A model-written `reason` string is never treated as the operation — it is
56
+ // stored beside the fingerprint as a claim, labelled as one.
57
+ //
58
+ // ## Identity, and the honest limit
59
+ //
60
+ // A request is reachable only through the task that armed the bridge: the engine
61
+ // looks the request up BY THE DECIDING CALLER'S OWN TASK, so another task's (or
62
+ // another connection's) pending request is not addressable at all. Within a run,
63
+ // `owns()` requires the EXACT live Agent object the bridge was armed for, so a
64
+ // request with no Agent, a foreign Agent or a look-alike object is never claimed.
65
+ //
66
+ // What this module does NOT claim, in either direction:
67
+ //
68
+ // * It is **not process authentication** against arbitrary code running as the
69
+ // same OS user. The execution plane's switch mode deliberately uses one shared
70
+ // `local-mcp` identity and issues no user-managed token, so any local process
71
+ // may present itself as that commander. The switch is an operator control, not a
72
+ // per-process security boundary, and this module does not pretend otherwise.
73
+ // * The worker's inability to answer its own request is a **tool-surface
74
+ // restriction**, not a security boundary: `delegate_permission_decide` is an MCP
75
+ // tool and is not part of the native worker's preset tool surface, so the
76
+ // worker's model is never handed it. That is a real restriction on what the
77
+ // worker composition exposes — it is NOT a claim that a process running as the
78
+ // same user could not call the execution plane directly. Nothing here relies on
79
+ // a caller-supplied role label either.
80
+ //
81
+ // ## Lifetime
82
+ //
83
+ // Waiting never spends the run's execution budget: the run's deadline is really
84
+ // PAUSED around every wait (its timer is disarmed and the elapsed span charged,
85
+ // so a wait longer than the remaining budget cannot time the run out), and the
86
+ // request has its own bounded deadline ({@link PERMISSION_DEFAULT_TIMEOUT_MS}).
87
+ // Cancellation, switch-off, revocation, disposal and that deadline all settle the
88
+ // outstanding waiter (`cancelled`/`rejected`/`unavailable`) and restore the timer,
89
+ // so a paused call can never outlive the reason it was paused for. A restart begins
90
+ // with no bridge, no request and no decision: an interrupted request is history
91
+ // only and is never replayed into a new call.
92
+
93
+ import { createHash } from 'node:crypto';
94
+
95
+ /** Fixed default lifetime of one permission request, in milliseconds (10 minutes). */
96
+ export const PERMISSION_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
97
+
98
+ /** Hard bound on a request lifetime a test or caller may configure. */
99
+ export const PERMISSION_MAX_TIMEOUT_MS = 30 * 60 * 1000;
100
+
101
+ /** The closed decision vocabulary this plugin's tool accepts. */
102
+ export const PERMISSION_DECISIONS = Object.freeze(['allow-once', 'reject']);
103
+
104
+ /**
105
+ * The closed native outcome vocabulary, mirrored from the approval seam so a
106
+ * non-vocabulary answer can never be interpreted as a grant.
107
+ */
108
+ export const APPROVAL_OUTCOMES = Object.freeze(['allowed-once', 'rejected', 'cancelled', 'unavailable']);
109
+
110
+ /** Stable request states; a request is `pending` until it is settled exactly once. */
111
+ export const PERMISSION_STATES = Object.freeze({
112
+ pending: 'pending',
113
+ decided: 'decided',
114
+ expired: 'expired',
115
+ cancelled: 'cancelled',
116
+ unavailable: 'unavailable',
117
+ });
118
+
119
+ /** Machine codes for a bridge refusal the commander reads. */
120
+ export const PERMISSION_CODES = Object.freeze({
121
+ unknownTask: 'JOB_TASK_NOT_FOUND',
122
+ notFound: 'PERMISSION_REQUEST_NOT_FOUND',
123
+ notPending: 'PERMISSION_REQUEST_NOT_PENDING',
124
+ expired: 'PERMISSION_REQUEST_EXPIRED',
125
+ changed: 'PERMISSION_REQUEST_CHANGED',
126
+ duplicates: 'PERMISSION_DECISION_REFUSED',
127
+ unbound: 'PERMISSION_REQUEST_UNBOUND',
128
+ invalid: 'PERMISSION_DECISION_INVALID',
129
+ // The request's own evidence cannot support an allow: it was shortened by a
130
+ // bound, or its call can no longer be re-verified. `reject` remains available.
131
+ incomplete: 'PERMISSION_EVIDENCE_INCOMPLETE',
132
+ });
133
+
134
+ /** Fixed `details.reason` strings for a native ask refused before it is surfaced. */
135
+ export const PERMISSION_REASONS = Object.freeze({
136
+ notArmed: 'no armed permission bridge for this session',
137
+ noSession: 'the asking agent exposes no session log',
138
+ noCallId: 'the approval request carries no tool call identity',
139
+ callNotFound: 'no tool/call event matches this call identity',
140
+ nameMismatch: 'the recorded tool call names a different tool',
141
+ argumentsUnusable: 'the recorded tool arguments could not be read',
142
+ agentMismatch: 'the approval request names another agent',
143
+ aborted: 'the asking tool withdrew the request',
144
+ disposed: 'the permission bridge was disposed',
145
+ stop: 'the run stopped while the request was pending',
146
+ // -- refusals of a DECISION (not of the ask) --------------------------------
147
+ //
148
+ // Each names a reason an allow cannot be granted, and each is checked at the
149
+ // moment of decision rather than only when the request was created.
150
+ incompleteEvidence: 'the operation was shortened by a bound, so an allow cannot be granted on it',
151
+ noCallSeq: 'the recorded tool call carries no session offset to re-verify',
152
+ callChanged: 'the recorded tool call changed after the request was created',
153
+ callMissing: 'the recorded tool call is no longer in the session log',
154
+ turnClosed: 'the turn that asked for this call has already ended',
155
+ sessionGone: 'the asking session is no longer the one this bridge is bound to',
156
+ fingerprintRequired: 'an allow-once decision must quote the request fingerprint',
157
+ });
158
+
159
+ /**
160
+ * Which evidence problems gate an `allow-once` but NOT a `reject`.
161
+ *
162
+ * `reject` is always safe: it denies the call. Only a grant needs complete,
163
+ * still-current evidence, so the listing lives here in one place and both the
164
+ * bridge and its docs refer to it.
165
+ */
166
+ export const ALLOW_BLOCKING_REASONS = Object.freeze([
167
+ PERMISSION_REASONS.incompleteEvidence,
168
+ PERMISSION_REASONS.noCallSeq,
169
+ PERMISSION_REASONS.callChanged,
170
+ PERMISSION_REASONS.callMissing,
171
+ PERMISSION_REASONS.turnClosed,
172
+ PERMISSION_REASONS.sessionGone,
173
+ PERMISSION_REASONS.fingerprintRequired,
174
+ ]);
175
+
176
+ /**
177
+ * The one refusal this bridge raises as an error instead of an outcome.
178
+ *
179
+ * It exists for the CALLER's path (a binding that cannot be established must fail
180
+ * closed with diagnostics), never for the tool call itself: the approval seam
181
+ * maps any thrown answerer to `'unavailable'`, so the worker sees "no approval
182
+ * channel" rather than a half-understood request.
183
+ */
184
+ export class PermissionError extends Error {
185
+ /**
186
+ * @param {string} code - stable machine code.
187
+ * @param {string} message - bounded operator-facing explanation.
188
+ * @param {object} [details] - non-secret facts.
189
+ */
190
+ constructor(code, message, details = {}) {
191
+ super(message);
192
+ this.name = 'PermissionError';
193
+ this.code = code;
194
+ this.details = details;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Bounds on what one request keeps, so a hostile argument blob cannot become a
200
+ * memory or history problem. Every bound is applied to a REDACTED value.
201
+ */
202
+ export const PERMISSION_BOUNDS = Object.freeze({
203
+ /** Maximum characters retained for the redacted JSON arguments. */
204
+ argumentsChars: 4000,
205
+ /** Maximum characters retained for any single redacted argument scalar. */
206
+ argumentValueChars: 400,
207
+ /** Maximum depth retained when projecting arguments. */
208
+ argumentDepth: 6,
209
+ /** Maximum argument keys retained per object. */
210
+ argumentKeys: 24,
211
+ /** Maximum characters retained for the asker's own claimed reason. */
212
+ reasonChars: 600,
213
+ /** Maximum characters retained for a decision reason. */
214
+ decisionReasonChars: 600,
215
+ });
216
+
217
+ /**
218
+ * The redaction this module applies to every published string.
219
+ *
220
+ * Injected rather than imported so the module stays a leaf with one dependency;
221
+ * the plugin passes `redactText` from `config/redact.js` (the same redaction the
222
+ * MCP result path applies), and a test may pass its own.
223
+ */
224
+ const IDENTITY_REDACTION = /\b(sk|pk|ak)-[A-Za-z0-9_-]{16,}\b/g;
225
+
226
+ /**
227
+ * The default redaction: credential-shaped substrings.
228
+ *
229
+ * `config/redact.js`'s {@link redactText} is what the plugin injects, and this
230
+ * fallback deliberately mirrors its three patterns (bearer tokens, key-like
231
+ * secrets, and `NAME=value` assignments) so a bridge constructed without an
232
+ * injected redaction is not WEAKER than the production one. The module still stays
233
+ * a leaf: this is a local copy of the shape, not an import of the config layer.
234
+ * @param {string} text - untrusted text.
235
+ * @returns {string} text with credential-shaped substrings replaced.
236
+ */
237
+ function defaultRedact(text) {
238
+ if (typeof text !== 'string' || text === '') return '';
239
+ return text
240
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/giu, 'Bearer ••••••••')
241
+ .replace(IDENTITY_REDACTION, '••••••••')
242
+ .replace(
243
+ /\b([A-Za-z0-9_]*(?:API_?KEY|SECRET|TOKEN|PASSWORD)[A-Za-z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/giu,
244
+ (_match, name) => `${name}=••••••••`,
245
+ );
246
+ }
247
+
248
+ /**
249
+ * Keys that may never be assigned through `object[key] = value`.
250
+ *
251
+ * `out['__proto__'] = x` on an ordinary object does not create an own property: it
252
+ * invokes the prototype setter, so the key silently disappears. Two different JSON
253
+ * objects — one carrying `__proto__` and one not — then hash and project
254
+ * identically, which is a real collision between two different operations. Every
255
+ * assignment below therefore goes through {@link setOwn}, which defines an own
256
+ * data property instead.
257
+ */
258
+ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
259
+
260
+ /**
261
+ * Assign an own enumerable data property, including for `__proto__`.
262
+ * @param {object} target - object to write into (created with a null prototype).
263
+ * @param {string} key - property name.
264
+ * @param {unknown} value - property value.
265
+ * @returns {void}
266
+ */
267
+ function setOwn(target, key, value) {
268
+ Object.defineProperty(target, key, {
269
+ value,
270
+ enumerable: true,
271
+ configurable: true,
272
+ writable: true,
273
+ });
274
+ }
275
+
276
+ /**
277
+ * A projection result: the bounded/redacted value AND whether it is complete.
278
+ *
279
+ * Completeness is a first-class fact, not an inference. A truncated value can hide
280
+ * the part of a command that matters (the tail of `bash.command`, the body of a
281
+ * `write`), so a caller must be able to refuse an allow decision on evidence it
282
+ * could not see in full.
283
+ */
284
+ export const PERMISSION_COMPLETENESS = Object.freeze({
285
+ complete: 'complete',
286
+ truncated: 'truncated',
287
+ unbounded: 'unbounded',
288
+ });
289
+
290
+ /**
291
+ * Create a projection context that tracks whether any bound was applied.
292
+ * @param {boolean} redactKeys - whether key names are redacted too.
293
+ * @returns {{ cuts: string[], valueChars: number, keys: number } } mutable counters.
294
+ */
295
+ function newProjectionState() {
296
+ return { cuts: [], valueCuts: 0, keyCuts: 0, depthCuts: 0, itemCuts: 0 };
297
+ }
298
+
299
+ /**
300
+ * Mark one bound as applied, so its kind can be reported.
301
+ * @param {object} state - projection counters.
302
+ * @param {string} cut - cut kind.
303
+ * @param {number} [amount] - how much was dropped.
304
+ * @returns {void}
305
+ */
306
+ function noteCut(state, cut, amount = 1) {
307
+ if (cut === 'value') state.valueCuts += amount;
308
+ else if (cut === 'key') state.keyCuts += amount;
309
+ else if (cut === 'depth') state.depthCuts += amount;
310
+ else if (cut === 'item') state.itemCuts += amount;
311
+ if (state.cuts.length < 8 && !state.cuts.includes(cut)) state.cuts.push(cut);
312
+ }
313
+
314
+ /**
315
+ * Whether a value is a credential-bearing KEY name.
316
+ *
317
+ * This is the key-aware half of redaction, and it is why the projection cannot rely
318
+ * on scalar patterns alone: `{"apiKey":"…"}` carries a secret in its VALUE with no
319
+ * credential-shaped text in it at all. The rule is deliberately the same predicate
320
+ * the redaction module uses for stored documents
321
+ * ({@link import('../config/redact.js').isSecretKey}), injected here through
322
+ * `isSecretKey` so there is exactly one definition of "this key names a secret".
323
+ * @param {string} key - object key.
324
+ * @param {(key: string) => boolean} isSecretKey - the injected predicate.
325
+ * @returns {boolean} true when the value behind this key must be masked.
326
+ */
327
+ function secretKeyName(key, isSecretKey) {
328
+ if (typeof isSecretKey === 'function' && isSecretKey(key) === true) return true;
329
+ // A defence-in-depth fallback for the harness-free default: the same shape the
330
+ // configuration module matches, so a module imported without it is not weaker.
331
+ return typeof key === 'string' && /(api[_-]?key|apikey|secret|token|password|passwd|credential[_-]?value|authorization)/iu.test(key);
332
+ }
333
+
334
+ /**
335
+ * Project one JSON value into a bounded, redacted, JSON-safe copy.
336
+ *
337
+ * Three rules, and every one of them is load-bearing:
338
+ *
339
+ * 1. **Key-aware redaction.** A key whose NAME says it holds a credential has its
340
+ * whole value masked, whatever the value looks like; every remaining string is
341
+ * also passed through the injected {@link redactText}. Scalar patterns alone
342
+ * would publish `{"apiKey":"some-secret"}` verbatim.
343
+ * 2. **Proto-safe keys.** Assignments go through {@link setOwn}, so a JSON key
344
+ * named `__proto__` becomes a real own property instead of vanishing through the
345
+ * prototype setter (R9's collision).
346
+ * 3. **Explicit completeness.** Every bound that fires is COUNTED, so the caller
347
+ * can tell a fully-projected operation from a shortened one and refuse an allow
348
+ * decision on evidence it could not review in full.
349
+ * @param {unknown} value - parsed argument value.
350
+ * @param {object} options - `redact`, `isSecretKey`, `state`, `depth`.
351
+ * @returns {unknown} bounded projection.
352
+ */
353
+ function projectValue(value, options) {
354
+ const redact = typeof options.redact === 'function' ? options.redact : defaultRedact;
355
+ const isSecretKey = options.isSecretKey;
356
+ const state = options.state ?? newProjectionState();
357
+ const depth = options.depth ?? 0;
358
+ const cap = PERMISSION_BOUNDS.argumentValueChars;
359
+ if (value === null || typeof value === 'undefined') return null;
360
+ if (typeof value === 'string') {
361
+ const text = redact(value);
362
+ if (text.length > cap) {
363
+ noteCut(state, 'value', text.length - cap);
364
+ return `${text.slice(0, cap)}…[+${text.length - cap} chars]`;
365
+ }
366
+ return text;
367
+ }
368
+ if (typeof value === 'number') return Number.isFinite(value) ? value : String(value);
369
+ if (typeof value === 'boolean') return value;
370
+ if (depth >= PERMISSION_BOUNDS.argumentDepth) {
371
+ noteCut(state, 'depth');
372
+ return '[depth limit]';
373
+ }
374
+ if (Array.isArray(value)) {
375
+ const keep = value.slice(0, PERMISSION_BOUNDS.argumentKeys);
376
+ if (value.length > keep.length) noteCut(state, 'item', value.length - keep.length);
377
+ const projected = keep.map((entry) => projectValue(entry, { redact, isSecretKey, state, depth: depth + 1 }));
378
+ if (value.length > keep.length) projected.push(`[+${value.length - keep.length} more items]`);
379
+ return projected;
380
+ }
381
+ if (typeof value === 'object') {
382
+ // A null prototype keeps the projection itself free of inherited keys; every
383
+ // assignment still goes through `setOwn` so `__proto__` survives as data.
384
+ const out = Object.create(null);
385
+ const entries = Object.entries(value);
386
+ if (entries.length > PERMISSION_BOUNDS.argumentKeys) {
387
+ noteCut(state, 'key', entries.length - PERMISSION_BOUNDS.argumentKeys);
388
+ }
389
+ for (const [key, entry] of entries.slice(0, PERMISSION_BOUNDS.argumentKeys)) {
390
+ const safeKey = redact(key);
391
+ if (secretKeyName(key, isSecretKey)) {
392
+ // The whole value is masked because its KEY says it is a credential. The key
393
+ // name stays, so an operator can still see WHICH argument was hidden.
394
+ setOwn(out, safeKey, '••••••••');
395
+ // A masked credential is not a truncation: the operation is fully described
396
+ // by "this credential is set".
397
+ continue;
398
+ }
399
+ setOwn(out, safeKey, projectValue(entry, { redact, isSecretKey, state, depth: depth + 1 }));
400
+ }
401
+ if (entries.length > PERMISSION_BOUNDS.argumentKeys) {
402
+ setOwn(out, '…', `[+${entries.length - PERMISSION_BOUNDS.argumentKeys} more keys]`);
403
+ }
404
+ return out;
405
+ }
406
+ return '[not representable]';
407
+ }
408
+
409
+ /**
410
+ * Serialize a projected value to bounded JSON text.
411
+ *
412
+ * The whole-value cap is applied only when the projection still does not fit, and
413
+ * it always REPORTS that it fired (through {@link boundedJsonText.exceeded}) so a
414
+ * caller can refuse an allow decision rather than approve a tail it never saw.
415
+ * @param {unknown} projected - bounded projection.
416
+ * @returns {{ text: string, exceeded: boolean }} JSON text and whether the cap fired.
417
+ */
418
+ function boundedJsonText(projected) {
419
+ let text;
420
+ try {
421
+ text = JSON.stringify(projected);
422
+ } catch {
423
+ return { text: '[unserializable]', exceeded: true };
424
+ }
425
+ if (typeof text !== 'string') return { text: '[unserializable]', exceeded: true };
426
+ const cap = PERMISSION_BOUNDS.argumentsChars;
427
+ if (text.length > cap) {
428
+ return { text: `${text.slice(0, cap)}…[+${text.length - cap} chars omitted]`, exceeded: true };
429
+ }
430
+ return { text, exceeded: false };
431
+ }
432
+
433
+ /**
434
+ * A stable, proto-safe canonical JSON text of an exact value.
435
+ *
436
+ * `JSON.stringify` is not usable on its own here: it uses ordinary assignment
437
+ * internally for the value it returns, but the real problem is the REPLACER an
438
+ * earlier version used — `out[key] = value` silently drops a key named
439
+ * `__proto__`, so `{"__proto__":{"a":1}}` and `{}` produced the same digest and two
440
+ * different operations could be decided by one fingerprint.
441
+ *
442
+ * This serializer builds the text directly: keys are sorted for stability (so key
443
+ * order is not part of the operation), every key is escaped as a JSON string rather
444
+ * than assigned as a property, and nesting is explicit. Two objects are therefore
445
+ * equal here only when they have the same keys and the same values.
446
+ * @param {unknown} value - JSON-compatible value.
447
+ * @returns {string} canonical JSON text.
448
+ */
449
+ export function canonicalJson(value) {
450
+ if (value === null) return 'null';
451
+ if (typeof value === 'string') return JSON.stringify(value);
452
+ if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : 'null';
453
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
454
+ if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(',')}]`;
455
+ if (typeof value === 'object') {
456
+ // `Object.keys` reports own enumerable keys only, including one named
457
+ // `__proto__` created by `JSON.parse` (which defines it as data, not accessor).
458
+ const keys = Object.keys(value).sort();
459
+ const parts = [];
460
+ for (const key of keys) {
461
+ parts.push(`${JSON.stringify(key)}:${canonicalJson(value[key])}`);
462
+ }
463
+ return `{${parts.join(',')}}`;
464
+ }
465
+ return 'null';
466
+ }
467
+
468
+ /**
469
+ * A stable fingerprint of an exact value.
470
+ *
471
+ * The digest is over {@link canonicalJson}, so it depends on the operation and not
472
+ * on key order, and it is a digest rather than the value so the private binding
473
+ * never has to keep (or publish) a second copy of the arguments.
474
+ * @param {unknown} value - JSON-compatible value.
475
+ * @returns {string} `sha256:<hex>` digest.
476
+ */
477
+ export function fingerprintOf(value) {
478
+ return `sha256:${createHash('sha256').update(canonicalJson(value), 'utf8').digest('hex')}`;
479
+ }
480
+
481
+ /**
482
+ * Read the real tool call one approval request is about, from the Session log.
483
+ *
484
+ * The native loop commits `tool/call` before the tool executes, so the arguments
485
+ * are already in the log when the tool asks. The match is:
486
+ *
487
+ * * the event type is `tool/call`;
488
+ * * its `callId` equals the request's `callId` EXACTLY (a missing `callId` is a
489
+ * refusal, not a search);
490
+ * * its `name` equals the request's `toolName` (a mismatch is a refusal: the
491
+ * request and the log disagree about what is being decided);
492
+ * * the newest such event wins if an id were ever repeated (the live one).
493
+ *
494
+ * A Session that exposes no readable log, a log whose reads throw, and a missing
495
+ * match are all refusals with their own bounded reason.
496
+ * @param {object} session - the asking agent's Session.
497
+ * @param {object} request - native approval request (`callId`, `toolName`).
498
+ * @returns {{ ok: true, call: { callId: string, name: string, argumentsText: string, turn: number|null, step: number|null, seq: number|null } }
499
+ * | { ok: false, reason: string }} the located call, or a bounded refusal.
500
+ */
501
+ export function locateToolCall(session, request) {
502
+ const callId = request?.callId;
503
+ if (typeof callId !== 'string' || callId === '') return { ok: false, reason: PERMISSION_REASONS.noCallId };
504
+ if (session === null || typeof session !== 'object') return { ok: false, reason: PERMISSION_REASONS.noSession };
505
+ const seq = typeof session.seq === 'number' && Number.isInteger(session.seq) ? session.seq : null;
506
+ if (seq === null || typeof session.eventAt !== 'function') return { ok: false, reason: PERMISSION_REASONS.noSession };
507
+ const toolName = typeof request?.toolName === 'string' ? request.toolName : null;
508
+ let found = null;
509
+ for (let index = seq - 1; index >= 0; index -= 1) {
510
+ let event;
511
+ try {
512
+ event = session.eventAt(index);
513
+ } catch {
514
+ return { ok: false, reason: PERMISSION_REASONS.callNotFound };
515
+ }
516
+ if (event === null || typeof event !== 'object' || event.type !== 'tool/call') continue;
517
+ const data = event.data ?? {};
518
+ if (data.callId !== callId) continue;
519
+ found = { event, data, index };
520
+ break;
521
+ }
522
+ if (found === null) return { ok: false, reason: PERMISSION_REASONS.callNotFound };
523
+ const name = typeof found.data.name === 'string' ? found.data.name : null;
524
+ if (toolName !== null && name !== toolName) return { ok: false, reason: PERMISSION_REASONS.nameMismatch };
525
+ const argumentsText = typeof found.data.arguments === 'string' ? found.data.arguments : null;
526
+ if (argumentsText === null) return { ok: false, reason: PERMISSION_REASONS.argumentsUnusable };
527
+ return {
528
+ ok: true,
529
+ call: {
530
+ callId,
531
+ name: name ?? toolName ?? null,
532
+ argumentsText,
533
+ turn: Number.isInteger(found.data.turn) ? found.data.turn : null,
534
+ step: Number.isInteger(found.data.step) ? found.data.step : null,
535
+ seq: found.index,
536
+ },
537
+ };
538
+ }
539
+
540
+ /**
541
+ * Whether the Session log is inside an open turn at one offset.
542
+ *
543
+ * This mirrors the native check `ApprovalService.request()` performs before it will
544
+ * answer at all (`hasOpenTurn` in the legacy service, the `turnOpen` projection in
545
+ * the modern one): the last `turn/start`/`turn/end` before the offset decides. It is
546
+ * re-used here because a decision re-verifies the operation at decision time, and a
547
+ * call whose turn has closed is not a call an allow can still apply to.
548
+ * @param {object} session - Session with `eventAt`.
549
+ * @param {number} seq - the tool call's offset.
550
+ * @returns {boolean | null} true/false, or null when the log cannot be read.
551
+ */
552
+ export function turnOpenAt(session, seq) {
553
+ return openTurnAt(session, seq) !== null;
554
+ }
555
+
556
+ /**
557
+ * The turn NUMBER that is open at the CURRENT tail of the log, or `null`.
558
+ *
559
+ * `turnOpenAt` answers "is anything open now"; this answers "WHICH turn is open
560
+ * now". The difference matters: a request asked inside turn 2, then closed and a
561
+ * turn 3 opened, is still "a turn is open" — but it is not the turn that asked. The
562
+ * live-binding check compares this number against the one recorded when the request
563
+ * was created, which is what refuses a close-then-reopen.
564
+ *
565
+ * The scan starts at the END of the log (the live tail) and uses each `turn/start`
566
+ * event's own `turn` field when present, falling back to a running counter so a log
567
+ * that omits the field is still distinguishable across turns.
568
+ * @param {object} session - Session with `eventAt`.
569
+ * @param {number} [fromSeq] - lowest offset to scan back to (the call's offset).
570
+ * @returns {number | null} the open turn number, or null when none is open or the log is unreadable.
571
+ */
572
+ export function openTurnAt(session, fromSeq) {
573
+ if (session === null || typeof session !== 'object' || typeof session.eventAt !== 'function') return null;
574
+ const total = typeof session.seq === 'number' && Number.isInteger(session.seq) ? session.seq : null;
575
+ if (total === null) return null;
576
+ const floor = typeof fromSeq === 'number' && Number.isInteger(fromSeq) && fromSeq >= 0 ? fromSeq : 0;
577
+ try {
578
+ for (let index = total - 1; index >= floor; index -= 1) {
579
+ const event = session.eventAt(index);
580
+ if (event === null || event === undefined || typeof event !== 'object') continue;
581
+ if (event.type === 'turn/end') return null;
582
+ if (event.type !== 'turn/start') continue;
583
+ const declared = event.data?.turn;
584
+ if (typeof declared === 'number' && Number.isInteger(declared)) return declared;
585
+ // No field: identify the turn by its POSITION, which is still a stable and
586
+ // comparable identity for the same log. Negative so it can never be mistaken
587
+ // for a real turn number.
588
+ return -1 - index;
589
+ }
590
+ } catch {
591
+ return null;
592
+ }
593
+ return null;
594
+ }
595
+
596
+ /**
597
+ * The permission bridge for ONE delegated run.
598
+ *
599
+ * One broker per worker run. It is written in the run's own scope, armed before
600
+ * the prompt is delivered and disposed when the run ends, and it answers only
601
+ * requests that name the Agent it was armed for. A request whose identity cannot
602
+ * be established is answered from the fail-closed vocabulary — never allowed.
603
+ */
604
+ export class PermissionBridge {
605
+ /**
606
+ * @param {object} options - `taskId`, `connectionId`, `sessionId`, optional
607
+ * `timeoutMs` (bounded), optional `now`, optional `redact`, optional
608
+ * `isSecretKey` (the key-aware redaction predicate), optional `onPending`,
609
+ * optional `onSettled`, optional `logger`.
610
+ */
611
+ constructor(options) {
612
+ if (typeof options?.taskId !== 'string' || options.taskId === '') {
613
+ throw new TypeError('PermissionBridge needs the taskId it belongs to');
614
+ }
615
+ this.taskId = options.taskId;
616
+ this.connectionId = typeof options.connectionId === 'string' ? options.connectionId : null;
617
+ this.sessionId = typeof options.sessionId === 'string' ? options.sessionId : null;
618
+ this.redact = typeof options.redact === 'function' ? options.redact : defaultRedact;
619
+ // The key-aware half of redaction. Injected so this module and the stored-document
620
+ // redaction agree on ONE definition of "this key names a secret"; the fallback
621
+ // above keeps a harness-free import from being weaker than the plugin.
622
+ this.isSecretKey = typeof options.isSecretKey === 'function' ? options.isSecretKey : null;
623
+ this.now = typeof options.now === 'function' ? options.now : () => Date.now();
624
+ const configured = Number(options.timeoutMs);
625
+ this.timeoutMs = Number.isFinite(configured) && configured > 0
626
+ ? Math.min(configured, PERMISSION_MAX_TIMEOUT_MS)
627
+ : PERMISSION_DEFAULT_TIMEOUT_MS;
628
+ this.onPending = typeof options.onPending === 'function' ? options.onPending : null;
629
+ this.onSettled = typeof options.onSettled === 'function' ? options.onSettled : null;
630
+ this.logger = options.logger ?? null;
631
+ // The lifecycle latch. `armed` is what the policy writer reads: only an armed
632
+ // bridge may have `ask` installed for its Session, and `dispose()` clears it
633
+ // before the policy is restored.
634
+ this.armed = false;
635
+ this.disposed = false;
636
+ this.agent = null;
637
+ this.session = null;
638
+ // At most one outstanding request: a single tool call cannot be asked twice,
639
+ // and "one pending request per task" is what makes the commander's decision
640
+ // unambiguous without a second ordering rule.
641
+ this.pending = null;
642
+ // Every settled request, newest last, bounded. This is the evidence trail the
643
+ // task view and the durable history carry; it never holds an argument value
644
+ // that was not redacted at construction time.
645
+ this.history = [];
646
+ this.sequence = 0;
647
+ // The Session identity the bridge was ARMED for, kept separately from
648
+ // `this.session` so a replaced `agent.session` is detectable rather than silently
649
+ // followed (see {@link liveBindingRefusal}).
650
+ this.boundSessionId = null;
651
+ }
652
+
653
+ /** Maximum settled requests retained on one run. */
654
+ static get HISTORY_BOUND() {
655
+ return 8;
656
+ }
657
+
658
+ /**
659
+ * Bind the bridge to the Agent/Session it will answer for.
660
+ *
661
+ * Called from the run's setup step, AFTER the preset is mounted (so the tool
662
+ * surface is the real one) and BEFORE the prompt (so no turn can ask under an
663
+ * unarmed bridge). Re-arming the same run is idempotent; binding a DIFFERENT
664
+ * Agent is a refusal, because a bridge belongs to one conversation.
665
+ * @param {object} agent - the live native Agent the run will drive.
666
+ * @returns {{ taskId: string, sessionId: string }} what was armed.
667
+ * @throws {PermissionError} when the agent is unusable or is not the bound one.
668
+ */
669
+ arm(agent) {
670
+ if (this.disposed) {
671
+ throw new PermissionError(PERMISSION_CODES.unbound, 'the permission bridge was already disposed', {
672
+ reason: PERMISSION_REASONS.disposed,
673
+ });
674
+ }
675
+ const session = agent?.session ?? null;
676
+ const sessionId = typeof session?.id === 'string' ? session.id : (typeof agent?.id === 'string' ? agent.id : null);
677
+ if (session === null || sessionId === null) {
678
+ throw new PermissionError(PERMISSION_CODES.unbound, 'the delegated agent exposes no session to bind approvals to', {
679
+ reason: PERMISSION_REASONS.noSession,
680
+ });
681
+ }
682
+ if (this.agent !== null && this.agent !== agent) {
683
+ throw new PermissionError(PERMISSION_CODES.unbound, 'the permission bridge is already bound to another agent', {
684
+ reason: PERMISSION_REASONS.agentMismatch,
685
+ });
686
+ }
687
+ this.agent = agent;
688
+ this.session = session;
689
+ this.sessionId = this.sessionId ?? sessionId;
690
+ // Pinned at arm time: the exact Session id this bridge answers for.
691
+ this.boundSessionId = sessionId;
692
+ this.armed = true;
693
+ return { taskId: this.taskId, sessionId: this.sessionId };
694
+ }
695
+
696
+ /**
697
+ * Whether this bridge answers for one native approval request.
698
+ *
699
+ * The rule is EXACT identity, and it is deliberately strict in both directions:
700
+ *
701
+ * * the bridge must be armed, bound, and not disposed;
702
+ * * `request.agent` MUST be present — a request with no agent (`null`,
703
+ * `undefined`) is not "probably mine", it is unidentifiable, and answering it
704
+ * would let any caller that forgets to pass an agent be decided by this bridge;
705
+ * * that agent must be the SAME OBJECT the bridge was armed for. The native
706
+ * approval seam passes the live Agent the requesting tool is running for, so
707
+ * object identity is exactly the question "is this my Agent", and it cannot be
708
+ * forged from data;
709
+ * * when the agent exposes a Session id, it must equal the bound one.
710
+ *
711
+ * A request for a different agent in the same process is not this bridge's
712
+ * business: the listener falls through to the next answerer so the ordinary
713
+ * session keeps whatever prompt it actually has.
714
+ * @param {object} request - native approval request.
715
+ * @returns {boolean} true when this bridge owns the request.
716
+ */
717
+ owns(request) {
718
+ if (this.armed !== true || this.disposed === true) return false;
719
+ if (this.agent === null || this.session === null) return false;
720
+ const agent = request?.agent;
721
+ // No agent at all: unidentifiable, so NOT owned. `?? null` here would have made
722
+ // a missing agent match every bridge, which is the defect this check removes.
723
+ if (agent === null || agent === undefined || typeof agent !== 'object') return false;
724
+ if (agent !== this.agent) return false;
725
+ const sessionId = typeof agent?.session?.id === 'string' ? agent.session.id : null;
726
+ if (sessionId !== null && this.sessionId !== null && sessionId !== this.sessionId) return false;
727
+ return true;
728
+ }
729
+
730
+ /**
731
+ * Re-read the bound operation from the live Session and prove it is unchanged.
732
+ *
733
+ * A decision is not taken against the copy captured when the request was created:
734
+ * the native log is read AGAIN at the moment of decision, and the operation must
735
+ * still be there, still be the same record at the same offset, still carry the
736
+ * same tool name, and still carry byte-identical arguments. It must also still be
737
+ * inside an OPEN turn — a call whose turn has already ended is history, and an
738
+ * allow for it would apply to nothing (or, worse, to whatever reuses the id).
739
+ *
740
+ * This is what makes "the session/tool call/argument snapshot is re-verified at
741
+ * decision" a checked fact rather than an assumption.
742
+ * @param {object} pending - pending record, whose `callId`/`callSeq` pin the call.
743
+ * @returns {string | null} a fixed refusal reason, or null when still exact.
744
+ */
745
+ reverifyOperation(pending) {
746
+ const live = this.liveBindingRefusal();
747
+ if (live !== null) return live;
748
+ const seq = pending?.callSeq;
749
+ if (typeof seq !== 'number' || !Number.isInteger(seq) || seq < 0) {
750
+ return PERMISSION_REASONS.noCallSeq;
751
+ }
752
+ let event;
753
+ try {
754
+ event = this.session.eventAt(seq);
755
+ } catch {
756
+ return PERMISSION_REASONS.callMissing;
757
+ }
758
+ if (event === null || event === undefined || typeof event !== 'object' || event.type !== 'tool/call') {
759
+ return PERMISSION_REASONS.callMissing;
760
+ }
761
+ const data = event.data ?? {};
762
+ if (data.callId !== pending.callId) return PERMISSION_REASONS.callChanged;
763
+ // EXACT name equality. The old `typeof data.name === 'string' && …` guard made a
764
+ // REMOVED name pass, so a record whose tool name had been stripped still allowed.
765
+ if (data.name !== pending.toolName) return PERMISSION_REASONS.callChanged;
766
+ // Turn/step identity, compared exactly when the request pinned one.
767
+ if (pending.turn !== null && data.turn !== pending.turn) return PERMISSION_REASONS.callChanged;
768
+ if (pending.step !== null && data.step !== pending.step) return PERMISSION_REASONS.callChanged;
769
+ if (typeof data.arguments !== 'string' || data.arguments !== pending.exactArguments) {
770
+ // A changed argument string at the SAME offset means the record was mutated
771
+ // or the Session was replaced underneath this bridge. Either way the evidence
772
+ // the commander saw is not the operation any more.
773
+ return PERMISSION_REASONS.callChanged;
774
+ }
775
+ // The SAME originating turn must still be the open one at the CURRENT TAIL.
776
+ // Checking only "is some turn open now" would accept a close-then-reopen: the
777
+ // question was asked in turn N, and a decision taken in turn N+1 is not about the
778
+ // same live step. A closed tail (`null`) never equals a recorded turn number.
779
+ if (openTurnAt(this.session) !== pending.turnAtAsk) return PERMISSION_REASONS.turnClosed;
780
+ return null;
781
+ }
782
+
783
+ /**
784
+ * Prove the bridge is still bound to the LIVE Agent and Session it was armed for.
785
+ *
786
+ * The previous check only looked at `this.session`. That misses the case the audit
787
+ * reproduced: while a request is pending, the Agent's `session` is REPLACED, so the
788
+ * bridge keeps reading the old (frozen, still-open-looking) log while the agent
789
+ * actually drives a different conversation. Both the object identity AND the id are
790
+ * compared, because a replaced session with a recycled id is still a different
791
+ * conversation.
792
+ * @returns {string | null} a fixed refusal reason, or null when still bound.
793
+ */
794
+ liveBindingRefusal() {
795
+ const agent = this.agent;
796
+ if (agent === null || agent === undefined) return PERMISSION_REASONS.sessionGone;
797
+ const liveSession = agent.session;
798
+ if (liveSession === null || liveSession === undefined) return PERMISSION_REASONS.sessionGone;
799
+ if (liveSession !== this.session) return PERMISSION_REASONS.sessionGone;
800
+ if (this.boundSessionId !== null && liveSession.id !== this.boundSessionId) {
801
+ return PERMISSION_REASONS.sessionGone;
802
+ }
803
+ if (this.session === null || typeof this.session.eventAt !== 'function') {
804
+ return PERMISSION_REASONS.sessionGone;
805
+ }
806
+ return null;
807
+ }
808
+
809
+ /**
810
+ * Answer one native approval request.
811
+ *
812
+ * The closed outcomes and their causes:
813
+ *
814
+ * * `unavailable` — the bridge is not armed/disposed, the request is not this
815
+ * bridge's, or a request is already outstanding. Fail closed, because
816
+ * "somebody else's question" and "two questions at once" are both states this
817
+ * plugin cannot decide honestly.
818
+ * * `cancelled` — the asking tool withdrew the request (its own signal), or
819
+ * the run stopped while it was pending.
820
+ * * `rejected` — the deadline expired, the request had no call identity, or no
821
+ * `tool/call` matching it could be read. The operation is refused; the
822
+ * diagnostics say which check failed.
823
+ * * `allowed-once` — ONLY a commander decision that matched this exact
824
+ * fingerprint.
825
+ *
826
+ * @param {object} request - `{ agent, toolName, callId?, reason?, signal? }`.
827
+ * @returns {Promise<string>} one of {@link APPROVAL_OUTCOMES}.
828
+ */
829
+ async answer(request) {
830
+ if (this.armed !== true || this.disposed === true) return 'unavailable';
831
+ if (!this.owns(request)) return 'unavailable';
832
+ if (this.pending !== null) {
833
+ this.logger?.warn?.('dsh-delegate: a second approval request arrived while one was pending; refusing it');
834
+ return 'unavailable';
835
+ }
836
+ const signal = request?.signal;
837
+ if (signal?.aborted === true) return 'cancelled';
838
+ const located = locateToolCall(this.session, request);
839
+ if (located.ok !== true) {
840
+ // An unidentifiable request is a refusal, not a silent wait: nobody could
841
+ // bind a decision to it, so it must not occupy the pending slot.
842
+ this.recordRejectedBinding(request, located.reason);
843
+ return 'rejected';
844
+ }
845
+ const pending = this.createPending(request, located.call);
846
+ if (pending === null) {
847
+ this.recordRejectedBinding(request, PERMISSION_REASONS.argumentsUnusable);
848
+ return 'rejected';
849
+ }
850
+ return await this.waitForDecision(pending, signal);
851
+ }
852
+
853
+ /**
854
+ * Build the pending record for one identified request.
855
+ *
856
+ * The record keeps BOTH halves of the operation:
857
+ *
858
+ * * the exact fingerprint and the exact argument text, which are private and are
859
+ * what a decision is bound to and re-verified against;
860
+ * * the redacted projection and its COMPLETENESS, which is what the commander is
861
+ * shown.
862
+ *
863
+ * The completeness flags are computed here, once, from the real arguments:
864
+ * `argumentsComplete` is false when any bound fired, and `allowBlocked` names the
865
+ * reason an `allow-once` would be refused for it (see {@link allowRefusalReason}).
866
+ * @param {object} request - native approval request.
867
+ * @param {object} call - located `tool/call` facts.
868
+ * @returns {object | null} pending record, or null when it cannot be described.
869
+ */
870
+ createPending(request, call) {
871
+ let parsed;
872
+ try {
873
+ parsed = JSON.parse(call.argumentsText);
874
+ } catch {
875
+ return null;
876
+ }
877
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
878
+ // A tool call whose arguments are not an object cannot be fingerprinted
879
+ // per-key, and every enforcing tool in this composition takes one.
880
+ return null;
881
+ }
882
+ this.sequence += 1;
883
+ const createdAt = this.now();
884
+ const state = newProjectionState();
885
+ const projected = projectValue(parsed, {
886
+ redact: this.redact,
887
+ isSecretKey: this.isSecretKey,
888
+ state,
889
+ });
890
+ const rendered = boundedJsonText(projected);
891
+ if (rendered.exceeded) noteCut(state, 'value');
892
+ const pending = {
893
+ requestId: `permission-${this.taskId}-${this.sequence}`,
894
+ taskId: this.taskId,
895
+ connectionId: this.connectionId,
896
+ sessionId: this.sessionId,
897
+ toolName: call.name,
898
+ callId: call.callId,
899
+ turn: call.turn,
900
+ step: call.step,
901
+ // The Session log offset the operation was read from. A decision re-reads
902
+ // that same offset and refuses if the call is no longer the same record.
903
+ callSeq: call.seq,
904
+ // WHICH turn was open when the question was asked. A decision needs this exact
905
+ // turn to still be the open one; "some turn is open" is not enough, because a
906
+ // close-then-reopen opens a DIFFERENT turn the request never asked in.
907
+ //
908
+ // Read at the TAIL (no lower bound): the seam asks while its call is the newest
909
+ // event, so the tail's open turn IS the asking turn. Passing the call's offset
910
+ // here would start the scan at the `turn/start` behind it and report a turn that
911
+ // a later `turn/end` had already closed.
912
+ turnAtAsk: openTurnAt(this.session),
913
+ // The exact Session object and id the operation was read from.
914
+ boundSessionId: this.boundSessionId,
915
+ // A non-reusable identity: the fingerprint is over the EXACT arguments as
916
+ // the model produced them, so a later call with different arguments can
917
+ // never be decided by this request's evidence.
918
+ fingerprint: fingerprintOf(parsed),
919
+ // The exact argument text, retained PRIVATELY (never published) so a decision
920
+ // can re-compare the operation byte for byte instead of trusting a digest of
921
+ // a record it did not re-read.
922
+ exactArguments: call.argumentsText,
923
+ // Redacted, bounded rendering of the same operation, safe to publish.
924
+ arguments: rendered.text,
925
+ argumentKeys: Object.keys(parsed).slice(0, PERMISSION_BOUNDS.argumentKeys).map((key) => this.redact(key)),
926
+ // Completeness, stated rather than inferred from a trailing marker.
927
+ argumentsComplete: state.cuts.length === 0,
928
+ completeness: state.cuts.length === 0 ? PERMISSION_COMPLETENESS.complete : PERMISSION_COMPLETENESS.truncated,
929
+ omitted: {
930
+ valueChars: state.valueCuts,
931
+ keys: state.keyCuts,
932
+ depth: state.depthCuts,
933
+ items: state.itemCuts,
934
+ },
935
+ // Which bounds fired, in a fixed vocabulary, so the refusal can be explained.
936
+ boundsApplied: [...state.cuts],
937
+ // The asker's own claim about why it asks, labelled as a claim. It is never
938
+ // the operation and never a grant.
939
+ claimedReason: this.boundText(request?.reason, PERMISSION_BOUNDS.reasonChars),
940
+ requestedAccess: this.requestedAccessOf(parsed),
941
+ createdAt,
942
+ deadlineAt: createdAt + this.timeoutMs,
943
+ state: PERMISSION_STATES.pending,
944
+ decision: null,
945
+ decidedAt: null,
946
+ decidedBy: null,
947
+ decisionReason: null,
948
+ settledOutcome: null,
949
+ resolve: null,
950
+ timer: null,
951
+ onExternalAbort: null,
952
+ externalSignal: null,
953
+ };
954
+ pending.allowBlocked = this.allowRefusalReason(pending);
955
+ return pending;
956
+ }
957
+
958
+ /**
959
+ * Why an `allow-once` must be refused for this request, or `null`.
960
+ *
961
+ * The rule is the one the commander's decision depends on: **never allow an
962
+ * operation whose executable material was omitted by a bound.** A truncated
963
+ * `bash.command` can hide the tail that actually runs; a truncated `write.body`
964
+ * can hide what is written. `reject` stays available in every one of these cases,
965
+ * because refusing is always safe — it is the ALLOW that needs complete evidence.
966
+ * @param {object} pending - pending record.
967
+ * @returns {string | null} fixed reason, or null when an allow is decidable.
968
+ */
969
+ allowRefusalReason(pending) {
970
+ if (pending?.argumentsComplete !== true) {
971
+ return PERMISSION_REASONS.incompleteEvidence;
972
+ }
973
+ if (pending?.callSeq === null || pending?.callSeq === undefined) {
974
+ return PERMISSION_REASONS.noCallSeq;
975
+ }
976
+ return null;
977
+ }
978
+
979
+
980
+ /**
981
+ * Describe the access the call asks for, from the REAL arguments.
982
+ *
983
+ * Stated from the operation, never from the asker's prose: a sandbox escalation
984
+ * is `{ mode, requested: true }`, any other asking call is `{ mode: null }`.
985
+ * @param {object} args - parsed arguments.
986
+ * @returns {{ kind: string, mode: string | null }} bounded access fact.
987
+ */
988
+ requestedAccessOf(args) {
989
+ const mode = args?.sandbox_permissions;
990
+ if (typeof mode === 'string' && mode !== '') {
991
+ return { kind: 'sandbox-escalation', mode };
992
+ }
993
+ return { kind: 'tool-call', mode: null };
994
+ }
995
+
996
+ /**
997
+ * Wait, boundedly, for the commander's decision.
998
+ *
999
+ * Two lifetimes race here and both settle the waiter exactly once: the
1000
+ * commander's decision (bound to this request id and fingerprint) and the
1001
+ * request's own deadline. A third, the asking tool's abort signal, pierces the
1002
+ * wait so a cancelled tool call cannot leave a request looking pending.
1003
+ * @param {object} pending - pending record.
1004
+ * @param {AbortSignal | undefined} signal - the asking tool's signal.
1005
+ * @returns {Promise<string>} the closed native outcome.
1006
+ */
1007
+ async waitForDecision(pending, signal) {
1008
+ this.pending = pending;
1009
+ const decision = new Promise((resolvePromise) => {
1010
+ pending.resolve = resolvePromise;
1011
+ });
1012
+ // The deadline is this request's OWN bound: it is independent of the run's
1013
+ // execution budget, which the engine pauses while this is outstanding.
1014
+ pending.timer = setTimeout(() => {
1015
+ pending.timer = null;
1016
+ this.settle(pending, PERMISSION_STATES.expired, 'rejected', {
1017
+ reason: 'the permission request reached its deadline without a decision',
1018
+ decidedBy: 'deadline',
1019
+ });
1020
+ }, this.timeoutMs);
1021
+ pending.timer.unref?.();
1022
+ if (signal !== undefined && signal !== null && typeof signal.addEventListener === 'function') {
1023
+ pending.externalSignal = signal;
1024
+ pending.onExternalAbort = () => {
1025
+ this.settle(pending, PERMISSION_STATES.cancelled, 'cancelled', {
1026
+ reason: PERMISSION_REASONS.aborted,
1027
+ decidedBy: 'asker',
1028
+ });
1029
+ };
1030
+ signal.addEventListener('abort', pending.onExternalAbort, { once: true });
1031
+ }
1032
+ this.emitPending(pending);
1033
+ try {
1034
+ return await decision;
1035
+ } finally {
1036
+ this.clearPending(pending);
1037
+ }
1038
+ }
1039
+
1040
+ /**
1041
+ * Publish one pending request to its observers (the engine records the phase).
1042
+ *
1043
+ * An observer throw is contained: a task view that cannot be updated must not
1044
+ * turn a live approval wait into a failed tool call.
1045
+ * @param {object} pending - pending record.
1046
+ * @returns {void}
1047
+ */
1048
+ emitPending(pending) {
1049
+ if (this.onPending === null) return;
1050
+ try {
1051
+ this.onPending(this.publicView(pending));
1052
+ } catch (error) {
1053
+ this.logger?.warn?.('dsh-delegate: permission observer failed', String(error?.code ?? ''));
1054
+ }
1055
+ }
1056
+
1057
+ /**
1058
+ * Decide one pending request. Called by the engine on behalf of ONE task.
1059
+ *
1060
+ * The order is the whole contract, and each step can refuse. It is deliberately
1061
+ * ordered so the CHEAP identity checks come first and the LIVE re-verification
1062
+ * comes before any grant:
1063
+ *
1064
+ * 1. the decision value must be one of `allow-once`/`reject` (validated before
1065
+ * anything is looked up or mutated);
1066
+ * 2. the request must be THIS bridge's own pending request (`requestId`);
1067
+ * 3. it must still be pending — a second decision, an expired request and a
1068
+ * cancelled one are all refused rather than re-applied;
1069
+ * 4. it must not be past its deadline (by the clock, not only by the timer);
1070
+ * 5. the fingerprint is **mandatory for `allow-once`** and is compared exactly
1071
+ * when supplied for `reject`. An allow must name the operation it grants;
1072
+ * 6. **for an allow only**, the operation is re-read from the LIVE Session and
1073
+ * must be unchanged at the same offset, in the same tool, with byte-identical
1074
+ * arguments, inside a still-open turn; and the projection must have been
1075
+ * COMPLETE (no bound fired). Any failure refuses the allow.
1076
+ *
1077
+ * `reject` deliberately skips 6: refusing is always safe, so a commander can deny
1078
+ * a request whose evidence was shortened or whose call has since changed. An
1079
+ * `allow-once` may not.
1080
+ * @param {object} request - `{ requestId, decision, reason, fingerprint }`.
1081
+ * @returns {object} bounded result: the settled request view.
1082
+ * @throws {PermissionError} on any refusal.
1083
+ */
1084
+ decide(request) {
1085
+ const requestId = typeof request?.requestId === 'string' ? request.requestId : '';
1086
+ if (requestId === '') {
1087
+ throw new PermissionError(PERMISSION_CODES.invalid, 'requestId is required', { field: 'requestId' });
1088
+ }
1089
+ const decision = request?.decision;
1090
+ if (!PERMISSION_DECISIONS.includes(decision)) {
1091
+ throw new PermissionError(PERMISSION_CODES.invalid, 'decision must be allow-once or reject', {
1092
+ field: 'decision',
1093
+ accepted: [...PERMISSION_DECISIONS],
1094
+ });
1095
+ }
1096
+ const allow = decision === 'allow-once';
1097
+ const pending = this.pending;
1098
+ if (pending === null || pending.requestId !== requestId) {
1099
+ // An unknown id, another run's id and an already-settled id are ONE answer:
1100
+ // the caller learns nothing about requests it did not own.
1101
+ const settled = this.history.find((entry) => entry.requestId === requestId) ?? null;
1102
+ if (settled !== null) {
1103
+ throw new PermissionError(PERMISSION_CODES.notPending, 'this permission request is already settled', {
1104
+ requestId,
1105
+ state: settled.state,
1106
+ outcome: settled.settledOutcome,
1107
+ });
1108
+ }
1109
+ throw new PermissionError(PERMISSION_CODES.notFound, 'no pending permission request matches this identity', {
1110
+ requestId,
1111
+ });
1112
+ }
1113
+ if (pending.state !== PERMISSION_STATES.pending) {
1114
+ throw new PermissionError(PERMISSION_CODES.notPending, 'this permission request is already settled', {
1115
+ requestId,
1116
+ state: pending.state,
1117
+ });
1118
+ }
1119
+ if (this.now() >= pending.deadlineAt) {
1120
+ // Expiry is decided by the clock, not only by the timer: a decision that
1121
+ // races the deadline must not resurrect a request nobody may answer.
1122
+ this.settle(pending, PERMISSION_STATES.expired, 'rejected', {
1123
+ reason: 'the permission request reached its deadline',
1124
+ decidedBy: 'deadline',
1125
+ });
1126
+ throw new PermissionError(PERMISSION_CODES.expired, 'the permission request expired before this decision', {
1127
+ requestId,
1128
+ });
1129
+ }
1130
+
1131
+ const supplied = request?.fingerprint;
1132
+ if (allow && (typeof supplied !== 'string' || supplied === '')) {
1133
+ // An allow without a fingerprint would grant "whatever is pending", which is
1134
+ // exactly the substitution this design refuses. The request stays pending so
1135
+ // a correct decision can still be made.
1136
+ throw new PermissionError(
1137
+ PERMISSION_CODES.invalid,
1138
+ 'an allow-once decision must quote the request fingerprint',
1139
+ { requestId, field: 'fingerprint', reason: PERMISSION_REASONS.fingerprintRequired },
1140
+ );
1141
+ }
1142
+ if (typeof supplied === 'string' && supplied !== pending.fingerprint) {
1143
+ // The operation the caller believes it is deciding is not the operation that
1144
+ // is pending. Refused, and the request is left pending for the two parties
1145
+ // that actually know what it is.
1146
+ throw new PermissionError(PERMISSION_CODES.changed, 'the pending operation does not match the fingerprint supplied', {
1147
+ requestId,
1148
+ });
1149
+ }
1150
+
1151
+ if (allow) {
1152
+ // 6a. completeness: never allow an operation whose material was omitted.
1153
+ const blocked = pending.allowBlocked ?? this.allowRefusalReason(pending);
1154
+ if (blocked !== null) {
1155
+ throw new PermissionError(
1156
+ PERMISSION_CODES.incomplete,
1157
+ blocked === PERMISSION_REASONS.incompleteEvidence
1158
+ ? 'the operation was shortened by a bound, so it cannot be allowed; reject it or ask the worker to narrow the call'
1159
+ : 'the recorded tool call cannot be re-verified, so an allow cannot be granted',
1160
+ { requestId, reason: blocked, boundsApplied: [...pending.boundsApplied] },
1161
+ );
1162
+ }
1163
+ // 6b. the operation must still be the SAME live record.
1164
+ const changed = this.reverifyOperation(pending);
1165
+ if (changed !== null) {
1166
+ throw new PermissionError(
1167
+ PERMISSION_CODES.changed,
1168
+ 'the recorded tool call is no longer the exact operation this request was created for',
1169
+ { requestId, reason: changed },
1170
+ );
1171
+ }
1172
+ }
1173
+
1174
+ const reason = this.boundText(request?.reason, PERMISSION_BOUNDS.decisionReasonChars);
1175
+ const outcome = allow ? 'allowed-once' : 'rejected';
1176
+ this.settle(pending, PERMISSION_STATES.decided, outcome, {
1177
+ reason: reason ?? (allow ? 'the commander allowed this call once' : 'the commander rejected this call'),
1178
+ decidedBy: 'commander',
1179
+ // Record which checks the grant passed, so the evidence states WHY an allow
1180
+ // was allowed instead of only that it was.
1181
+ ...(allow
1182
+ ? {
1183
+ verified: {
1184
+ fingerprintQuoted: true,
1185
+ argumentsComplete: pending.argumentsComplete === true,
1186
+ callReread: true,
1187
+ turnOpen: true,
1188
+ boundsApplied: [...pending.boundsApplied],
1189
+ },
1190
+ }
1191
+ : {}),
1192
+ });
1193
+ return this.history.at(-1) ?? null;
1194
+ }
1195
+
1196
+ /**
1197
+ * Settle one pending request exactly once and release its waiter.
1198
+ *
1199
+ * Idempotent by state: the deadline timer, the tool's abort signal, a decision
1200
+ * and a stop can all race, and only the first one is applied. The waiter's
1201
+ * promise is resolved with the OUTCOME, so the paused tool call resumes with
1202
+ * the native vocabulary rather than with this module's own words.
1203
+ * @param {object} pending - pending record.
1204
+ * @param {string} state - `decided`/`expired`/`cancelled`/`unavailable`.
1205
+ * @param {string} outcome - one of {@link APPROVAL_OUTCOMES}.
1206
+ * @param {object} [evidence] - `reason`, `decidedBy`.
1207
+ * @returns {boolean} true when this call settled the request.
1208
+ */
1209
+ settle(pending, state, outcome, evidence = {}) {
1210
+ if (pending === null || pending.state !== PERMISSION_STATES.pending) return false;
1211
+ pending.state = state;
1212
+ pending.settledOutcome = APPROVAL_OUTCOMES.includes(outcome) ? outcome : 'unavailable';
1213
+ pending.decidedAt = this.now();
1214
+ pending.decidedBy = evidence.decidedBy ?? null;
1215
+ pending.decisionReason = typeof evidence.reason === 'string' ? this.redact(evidence.reason).slice(0, PERMISSION_BOUNDS.decisionReasonChars) : null;
1216
+ if (evidence.verified !== undefined && evidence.verified !== null) {
1217
+ pending.verified = evidence.verified;
1218
+ }
1219
+ if (pending.timer !== null) {
1220
+ clearTimeout(pending.timer);
1221
+ pending.timer = null;
1222
+ }
1223
+ if (pending.externalSignal !== null && pending.onExternalAbort !== null) {
1224
+ try {
1225
+ pending.externalSignal.removeEventListener?.('abort', pending.onExternalAbort);
1226
+ } catch {
1227
+ // Removing a listener from a foreign signal is best effort by contract.
1228
+ }
1229
+ pending.onExternalAbort = null;
1230
+ pending.externalSignal = null;
1231
+ }
1232
+ this.history.push(this.publicView(pending));
1233
+ if (this.history.length > PermissionBridge.HISTORY_BOUND) this.history.shift();
1234
+ const resolvePromise = pending.resolve;
1235
+ pending.resolve = null;
1236
+ if (typeof resolvePromise === 'function') resolvePromise(pending.settledOutcome);
1237
+ if (this.pending === pending) this.pending = null;
1238
+ try {
1239
+ this.onSettled?.(this.history.at(-1));
1240
+ } catch (error) {
1241
+ this.logger?.warn?.('dsh-delegate: permission observer failed', String(error?.code ?? ''));
1242
+ }
1243
+ return true;
1244
+ }
1245
+
1246
+ /**
1247
+ * Clear the pending slot of an answered request.
1248
+ * @param {object} pending - pending record.
1249
+ * @returns {void}
1250
+ */
1251
+ clearPending(pending) {
1252
+ if (this.pending === pending) this.pending = null;
1253
+ }
1254
+
1255
+ /**
1256
+ * Record a request that was refused because its identity could not be bound.
1257
+ *
1258
+ * This is evidence, not a decision: nothing was granted, and the record says
1259
+ * which check failed so an operator can act on the tool surface instead of
1260
+ * guessing why a worker was told "no approval channel".
1261
+ * @param {object} request - native approval request.
1262
+ * @param {string} reason - fixed {@link PERMISSION_REASONS} value.
1263
+ * @returns {void}
1264
+ */
1265
+ recordRejectedBinding(request, reason) {
1266
+ this.sequence += 1;
1267
+ const createdAt = this.now();
1268
+ const entry = {
1269
+ requestId: `permission-${this.taskId}-${this.sequence}`,
1270
+ taskId: this.taskId,
1271
+ connectionId: this.connectionId,
1272
+ sessionId: this.sessionId,
1273
+ toolName: this.boundText(request?.toolName, 120),
1274
+ callId: this.boundText(request?.callId, 200),
1275
+ turn: null,
1276
+ step: null,
1277
+ fingerprint: null,
1278
+ arguments: null,
1279
+ argumentKeys: [],
1280
+ claimedReason: this.boundText(request?.reason, PERMISSION_BOUNDS.reasonChars),
1281
+ requestedAccess: { kind: 'unbound', mode: null },
1282
+ createdAt,
1283
+ deadlineAt: createdAt,
1284
+ state: PERMISSION_STATES.unavailable,
1285
+ decision: null,
1286
+ decidedAt: createdAt,
1287
+ decidedBy: 'binding',
1288
+ decisionReason: reason ?? PERMISSION_REASONS.unbound,
1289
+ settledOutcome: 'rejected',
1290
+ bindingReason: reason ?? PERMISSION_REASONS.unbound,
1291
+ };
1292
+ this.history.push(entry);
1293
+ if (this.history.length > PermissionBridge.HISTORY_BOUND) this.history.shift();
1294
+ try {
1295
+ this.onSettled?.(entry);
1296
+ } catch {
1297
+ // The refusal is already recorded; an observer throw cannot change it.
1298
+ }
1299
+ }
1300
+
1301
+ /**
1302
+ * Stop the outstanding request, if any, and restore the policy.
1303
+ *
1304
+ * The outcome is chosen by the caller because the CAUSE differs and the worker
1305
+ * must see the difference: a cancel/stop/switch-off withdraws the question
1306
+ * (`cancelled`), while disposal makes the bridge unusable (`unavailable`).
1307
+ * Either way the paused call resumes immediately with a refusal, the request's
1308
+ * timer and listener are released, and no later decision can apply.
1309
+ * @param {string} state - `cancelled` or `unavailable`.
1310
+ * @param {string} [reason] - fixed reason text.
1311
+ * @returns {boolean} true when a pending request was settled.
1312
+ */
1313
+ stop(state = PERMISSION_STATES.cancelled, reason = PERMISSION_REASONS.stop) {
1314
+ const outcome = state === PERMISSION_STATES.unavailable ? 'unavailable' : 'cancelled';
1315
+ const pending = this.pending;
1316
+ if (pending === null) {
1317
+ return false;
1318
+ }
1319
+ return this.settle(pending, state, outcome, { reason, decidedBy: 'stop' });
1320
+ }
1321
+
1322
+ /**
1323
+ * Disarm the bridge permanently.
1324
+ *
1325
+ * Disposal settles an outstanding request `unavailable` (no decision can be
1326
+ * applied to a bridge that no longer exists), clears `armed` so no policy writer
1327
+ * may keep `ask` installed, and drops the bound Agent so a disposed bridge can
1328
+ * never answer a request that a live Session still holds a reference to.
1329
+ * @returns {void}
1330
+ */
1331
+ dispose() {
1332
+ if (this.disposed) return;
1333
+ this.stop(PERMISSION_STATES.unavailable, PERMISSION_REASONS.disposed);
1334
+ this.armed = false;
1335
+ this.disposed = true;
1336
+ this.agent = null;
1337
+ this.session = null;
1338
+ }
1339
+
1340
+ /**
1341
+ * The public, bounded projection of one request.
1342
+ *
1343
+ * Everything here is either an identifier the caller already holds, a redacted
1344
+ * argument projection, or a timestamp. The exact fingerprint IS published,
1345
+ * because the decision tool accepts it back to bind a decision to exactly this
1346
+ * operation; it is a digest of the arguments, not the arguments.
1347
+ * @param {object} pending - pending or settled record.
1348
+ * @returns {object} redacted view.
1349
+ */
1350
+ publicView(pending) {
1351
+ return {
1352
+ requestId: pending.requestId,
1353
+ taskId: pending.taskId,
1354
+ // Stated, not implied: the commander is told which conversation and which
1355
+ // tool call is paused, so the decision is about an operation it can name.
1356
+ sessionId: pending.sessionId,
1357
+ toolName: pending.toolName,
1358
+ callId: pending.callId,
1359
+ turn: pending.turn,
1360
+ step: pending.step,
1361
+ tool: { name: pending.toolName, callId: pending.callId },
1362
+ state: pending.state,
1363
+ // The asker's own one-line claim, kept apart from the operation itself.
1364
+ reason: pending.claimedReason ?? null,
1365
+ reasonSource: 'asker-claim',
1366
+ requestedAccess: pending.requestedAccess,
1367
+ argumentKeys: pending.argumentKeys,
1368
+ arguments: pending.arguments,
1369
+ argumentsRedacted: true,
1370
+ // Completeness, published so a reader never has to infer it from a trailing
1371
+ // marker in the text: an allow is refused when this is not `complete`.
1372
+ completeness: pending.completeness ?? PERMISSION_COMPLETENESS.complete,
1373
+ argumentsComplete: pending.argumentsComplete !== false,
1374
+ boundsApplied: Array.isArray(pending.boundsApplied) ? [...pending.boundsApplied] : [],
1375
+ omitted: pending.omitted ?? { valueChars: 0, keys: 0, depth: 0, items: 0 },
1376
+ // Why an allow would be refused, or null. Stated so the commander is not left
1377
+ // guessing why `allow-once` came back refused.
1378
+ allowBlocked: pending.allowBlocked ?? null,
1379
+ fingerprint: pending.fingerprint,
1380
+ createdAt: pending.createdAt,
1381
+ deadlineAt: pending.deadlineAt,
1382
+ decision: pending.decision,
1383
+ decidedAt: pending.decidedAt,
1384
+ decidedBy: pending.decidedBy,
1385
+ decisionReason: pending.decisionReason,
1386
+ outcome: pending.settledOutcome,
1387
+ // For a settled allow: which checks the grant actually passed.
1388
+ ...(pending.verified === undefined || pending.verified === null ? {} : { verified: pending.verified }),
1389
+ ...(pending.bindingReason === undefined ? {} : { bindingReason: pending.bindingReason }),
1390
+ // The narrow exception, restated on the evidence itself so no reader has to
1391
+ // infer it: this is one call, decided once, and nothing was granted beyond it.
1392
+ grant: pending.settledOutcome === 'allowed-once'
1393
+ ? { kind: 'allowed-once', appliesTo: 'this-call-only', callId: pending.callId, reusable: false }
1394
+ : null,
1395
+ standingModeUnchanged: true,
1396
+ };
1397
+ }
1398
+
1399
+ /** The pending request's public view, or `null`. */
1400
+ pendingView() {
1401
+ return this.pending === null ? null : this.publicView(this.pending);
1402
+ }
1403
+
1404
+ /** Copy of the settled evidence trail, newest last. */
1405
+ historyView() {
1406
+ return this.history.map((entry) => ({ ...entry }));
1407
+ }
1408
+
1409
+ /**
1410
+ * Redact and bound one free-form string.
1411
+ * @param {unknown} value - untrusted text.
1412
+ * @param {number} cap - character bound.
1413
+ * @returns {string | null} bounded redacted text, or null when empty.
1414
+ */
1415
+ boundText(value, cap) {
1416
+ if (typeof value !== 'string' || value === '') return null;
1417
+ const text = this.redact(value);
1418
+ return text.length > cap ? `${text.slice(0, cap)}…` : text;
1419
+ }
1420
+ }
1421
+
1422
+ /**
1423
+ * Whether a value is an outcome this plugin may act on.
1424
+ * @param {unknown} value - candidate outcome.
1425
+ * @returns {boolean} true for the closed vocabulary.
1426
+ */
1427
+ export function isApprovalOutcome(value) {
1428
+ return typeof value === 'string' && APPROVAL_OUTCOMES.includes(value);
1429
+ }