dsh-taskbridge 1.7.0 → 1.8.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +21 -21
  3. package/README.md +150 -289
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +31 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +170 -627
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +119 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +13 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/plugin-market.md +30 -30
  17. package/docs/redaction-contract.md +170 -170
  18. package/docs/releases/1.7.0.zh.md +11 -11
  19. package/docs/releases/1.8.0.zh.md +16 -0
  20. package/docs/runtime-compatibility.md +1 -1
  21. package/docs/taskbridge-upgrade.md +28 -28
  22. package/docs/taskdispatch-upgrade.md +25 -25
  23. package/docs/workspace-contract.md +538 -538
  24. package/docs/workspace-grouping.md +126 -126
  25. package/icon.svg +1 -1
  26. package/lib/client.d.ts +733 -699
  27. package/lib/client.js +7 -7
  28. package/locale/en.json +1 -1
  29. package/locale/zh.json +1 -1
  30. package/package.json +149 -144
  31. package/src/antigravity/installer.js +1046 -0
  32. package/src/antigravity/seam.js +142 -0
  33. package/src/auth/fence.js +361 -361
  34. package/src/auth/grants.js +789 -789
  35. package/src/client/api.js +143 -0
  36. package/src/client/index.jsx +113 -3
  37. package/src/client/sidebar.jsx +862 -862
  38. package/src/client/styles.js +624 -624
  39. package/src/client/task-cleanup.js +304 -304
  40. package/src/client/task-records-table.jsx +217 -217
  41. package/src/client/task-view.js +307 -307
  42. package/src/client/workspace-groups.js +482 -482
  43. package/src/client/workspaces-browser.jsx +770 -770
  44. package/src/codex/agent-ownership.js +270 -270
  45. package/src/codex/installer.js +6 -0
  46. package/src/codex/toml.js +784 -784
  47. package/src/config/redact.js +245 -245
  48. package/src/config/store.js +186 -186
  49. package/src/credentials/seam.js +202 -202
  50. package/src/http/respond.js +6 -5
  51. package/src/http/user-plane.js +72 -0
  52. package/src/index.js +25 -0
  53. package/src/jobs/diagnostics.js +15 -15
  54. package/src/jobs/plan-store.js +1020 -1020
  55. package/src/jobs/review-note.js +63 -63
  56. package/src/jobs/task-descriptions.js +82 -82
  57. package/src/jobs/task-display.js +73 -73
  58. package/src/jobs/task-tree.js +786 -786
  59. package/src/jobs/title.js +134 -134
  60. package/src/mcp/continuation.js +317 -317
  61. package/src/mcp/server.js +12 -5
  62. package/src/model/connectivity.js +371 -371
  63. package/src/model/discovery.js +582 -582
  64. package/src/model/native-catalog.js +68 -68
  65. package/src/model/openai-adapter.js +671 -671
  66. package/src/model/probe.js +264 -264
  67. package/src/model/providers.js +756 -756
  68. package/src/model/routing.js +321 -321
  69. package/src/runtime/permissions.js +1619 -1619
  70. package/src/runtime/question-call.js +162 -162
  71. package/src/runtime/questions.js +909 -909
  72. package/src/runtime/worker-prompt.js +60 -53
  73. package/src/workspace/audit.js +775 -775
  74. package/src/workspace/preflight.js +424 -424
  75. package/src/workspace/worktrees.js +679 -679
@@ -1,1619 +1,1619 @@
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
- * The two text caps are set from the EVIDENCE, not from a round number. An allow is
203
- * only possible on a complete operation, so any cap that fires turns a legitimate
204
- * one-line request into an unapprovable one. A Windows absolute path plus a
205
- * read-back command is ~400 characters on its own — that size was refused by an
206
- * earlier `argumentValueChars: 400`, and a real platform refusal was the result. The
207
- * caps below hold roughly an 8 KiB command field and a 16 KiB argument object: far
208
- * more than any single tool call this surface reviews, and still a hard, stated
209
- * limit — a value past it is `truncated`, `argumentsComplete: false`, and cannot be
210
- * allowed (see {@link PermissionBridge#allowRefusalReason}). The protection the
211
- * caps provide is the same as before; only the point where a normal request stops
212
- * fitting moved.
213
- */
214
- export const PERMISSION_BOUNDS = Object.freeze({
215
- /** Maximum characters retained for the redacted JSON arguments. */
216
- argumentsChars: 16_384,
217
- /** Maximum characters retained for any single redacted argument scalar. */
218
- argumentValueChars: 8_192,
219
- /** Maximum depth retained when projecting arguments. */
220
- argumentDepth: 6,
221
- /** Maximum argument keys retained per object. */
222
- argumentKeys: 24,
223
- /** Maximum characters retained for the asker's own claimed reason. */
224
- reasonChars: 600,
225
- /** Maximum characters retained for a decision reason. */
226
- decisionReasonChars: 600,
227
- });
228
-
229
- /**
230
- * The redaction this module applies to every published string.
231
- *
232
- * Injected rather than imported so the module stays a leaf with one dependency;
233
- * the plugin passes `redactText` from `config/redact.js` (the same redaction the
234
- * MCP result path applies), and a test may pass its own.
235
- */
236
- const IDENTITY_REDACTION = /\b(sk|pk|ak)-[A-Za-z0-9_-]{16,}\b/g;
237
-
238
- /**
239
- * The default redaction: credential-shaped substrings.
240
- *
241
- * `config/redact.js`'s {@link redactText} is what the plugin injects, and this
242
- * fallback deliberately mirrors its three patterns (bearer tokens, key-like
243
- * secrets, and `NAME=value` assignments) so a bridge constructed without an
244
- * injected redaction is not WEAKER than the production one. The module still stays
245
- * a leaf: this is a local copy of the shape, not an import of the config layer.
246
- * @param {string} text - untrusted text.
247
- * @returns {string} text with credential-shaped substrings replaced.
248
- */
249
- function defaultRedact(text) {
250
- if (typeof text !== 'string' || text === '') return '';
251
- return text
252
- .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/giu, 'Bearer ••••••••')
253
- .replace(IDENTITY_REDACTION, '••••••••')
254
- .replace(
255
- /\b([A-Za-z0-9_]*(?:API_?KEY|SECRET|TOKEN|PASSWORD)[A-Za-z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/giu,
256
- (_match, name) => `${name}=••••••••`,
257
- );
258
- }
259
-
260
- /**
261
- * Keys that may never be assigned through `object[key] = value`.
262
- *
263
- * `out['__proto__'] = x` on an ordinary object does not create an own property: it
264
- * invokes the prototype setter, so the key silently disappears. Two different JSON
265
- * objects — one carrying `__proto__` and one not — then hash and project
266
- * identically, which is a real collision between two different operations. Every
267
- * assignment below therefore goes through {@link setOwn}, which defines an own
268
- * data property instead.
269
- */
270
- const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
271
-
272
- /**
273
- * Assign an own enumerable data property, including for `__proto__`.
274
- * @param {object} target - object to write into (created with a null prototype).
275
- * @param {string} key - property name.
276
- * @param {unknown} value - property value.
277
- * @returns {void}
278
- */
279
- function setOwn(target, key, value) {
280
- Object.defineProperty(target, key, {
281
- value,
282
- enumerable: true,
283
- configurable: true,
284
- writable: true,
285
- });
286
- }
287
-
288
- /**
289
- * A projection result: the bounded/redacted value AND whether it is complete.
290
- *
291
- * Completeness is a first-class fact, not an inference. A truncated value can hide
292
- * the part of a command that matters (the tail of `bash.command`, the body of a
293
- * `write`), so a caller must be able to refuse an allow decision on evidence it
294
- * could not see in full.
295
- */
296
- export const PERMISSION_COMPLETENESS = Object.freeze({
297
- complete: 'complete',
298
- truncated: 'truncated',
299
- unbounded: 'unbounded',
300
- });
301
-
302
- /**
303
- * Create a projection context that tracks whether any bound was applied.
304
- * @param {boolean} redactKeys - whether key names are redacted too.
305
- * @returns {{ cuts: string[], valueChars: number, keys: number } } mutable counters.
306
- */
307
- function newProjectionState() {
308
- return { cuts: [], valueCuts: 0, keyCuts: 0, depthCuts: 0, itemCuts: 0 };
309
- }
310
-
311
- /**
312
- * Mark one bound as applied, so its kind can be reported.
313
- * @param {object} state - projection counters.
314
- * @param {string} cut - cut kind.
315
- * @param {number} [amount] - how much was dropped.
316
- * @returns {void}
317
- */
318
- function noteCut(state, cut, amount = 1) {
319
- if (cut === 'value') state.valueCuts += amount;
320
- else if (cut === 'key') state.keyCuts += amount;
321
- else if (cut === 'depth') state.depthCuts += amount;
322
- else if (cut === 'item') state.itemCuts += amount;
323
- if (state.cuts.length < 8 && !state.cuts.includes(cut)) state.cuts.push(cut);
324
- }
325
-
326
- /**
327
- * Whether a value is a credential-bearing KEY name.
328
- *
329
- * This is the key-aware half of redaction, and it is why the projection cannot rely
330
- * on scalar patterns alone: `{"apiKey":"…"}` carries a secret in its VALUE with no
331
- * credential-shaped text in it at all. The rule is deliberately the same predicate
332
- * the redaction module uses for stored documents
333
- * ({@link import('../config/redact.js').isSecretKey}), injected here through
334
- * `isSecretKey` so there is exactly one definition of "this key names a secret".
335
- * @param {string} key - object key.
336
- * @param {(key: string) => boolean} isSecretKey - the injected predicate.
337
- * @returns {boolean} true when the value behind this key must be masked.
338
- */
339
- function secretKeyName(key, isSecretKey) {
340
- if (typeof isSecretKey === 'function' && isSecretKey(key) === true) return true;
341
- // A defence-in-depth fallback for the harness-free default: the same shape the
342
- // configuration module matches, so a module imported without it is not weaker.
343
- return typeof key === 'string' && /(api[_-]?key|apikey|secret|token|password|passwd|credential[_-]?value|authorization)/iu.test(key);
344
- }
345
-
346
- /**
347
- * Project one JSON value into a bounded, redacted, JSON-safe copy.
348
- *
349
- * Three rules, and every one of them is load-bearing:
350
- *
351
- * 1. **Key-aware redaction.** A key whose NAME says it holds a credential has its
352
- * whole value masked, whatever the value looks like; every remaining string is
353
- * also passed through the injected {@link redactText}. Scalar patterns alone
354
- * would publish `{"apiKey":"some-secret"}` verbatim.
355
- * 2. **Proto-safe keys.** Assignments go through {@link setOwn}, so a JSON key
356
- * named `__proto__` becomes a real own property instead of vanishing through the
357
- * prototype setter (R9's collision).
358
- * 3. **Explicit completeness.** Every bound that fires is COUNTED, so the caller
359
- * can tell a fully-projected operation from a shortened one and refuse an allow
360
- * decision on evidence it could not review in full.
361
- * @param {unknown} value - parsed argument value.
362
- * @param {object} options - `redact`, `isSecretKey`, `state`, `depth`.
363
- * @returns {unknown} bounded projection.
364
- */
365
- function projectValue(value, options) {
366
- const redact = typeof options.redact === 'function' ? options.redact : defaultRedact;
367
- const isSecretKey = options.isSecretKey;
368
- const state = options.state ?? newProjectionState();
369
- const depth = options.depth ?? 0;
370
- const cap = PERMISSION_BOUNDS.argumentValueChars;
371
- if (value === null || typeof value === 'undefined') return null;
372
- if (typeof value === 'string') {
373
- const text = redact(value);
374
- if (text.length > cap) {
375
- noteCut(state, 'value', text.length - cap);
376
- return `${text.slice(0, cap)}…[+${text.length - cap} chars]`;
377
- }
378
- return text;
379
- }
380
- if (typeof value === 'number') return Number.isFinite(value) ? value : String(value);
381
- if (typeof value === 'boolean') return value;
382
- if (depth >= PERMISSION_BOUNDS.argumentDepth) {
383
- noteCut(state, 'depth');
384
- return '[depth limit]';
385
- }
386
- if (Array.isArray(value)) {
387
- const keep = value.slice(0, PERMISSION_BOUNDS.argumentKeys);
388
- if (value.length > keep.length) noteCut(state, 'item', value.length - keep.length);
389
- const projected = keep.map((entry) => projectValue(entry, { redact, isSecretKey, state, depth: depth + 1 }));
390
- if (value.length > keep.length) projected.push(`[+${value.length - keep.length} more items]`);
391
- return projected;
392
- }
393
- if (typeof value === 'object') {
394
- // A null prototype keeps the projection itself free of inherited keys; every
395
- // assignment still goes through `setOwn` so `__proto__` survives as data.
396
- const out = Object.create(null);
397
- const entries = Object.entries(value);
398
- if (entries.length > PERMISSION_BOUNDS.argumentKeys) {
399
- noteCut(state, 'key', entries.length - PERMISSION_BOUNDS.argumentKeys);
400
- }
401
- for (const [key, entry] of entries.slice(0, PERMISSION_BOUNDS.argumentKeys)) {
402
- const safeKey = redact(key);
403
- if (secretKeyName(key, isSecretKey)) {
404
- // The whole value is masked because its KEY says it is a credential. The key
405
- // name stays, so an operator can still see WHICH argument was hidden.
406
- setOwn(out, safeKey, '••••••••');
407
- // A masked credential is not a truncation: the operation is fully described
408
- // by "this credential is set".
409
- continue;
410
- }
411
- setOwn(out, safeKey, projectValue(entry, { redact, isSecretKey, state, depth: depth + 1 }));
412
- }
413
- if (entries.length > PERMISSION_BOUNDS.argumentKeys) {
414
- setOwn(out, '…', `[+${entries.length - PERMISSION_BOUNDS.argumentKeys} more keys]`);
415
- }
416
- return out;
417
- }
418
- return '[not representable]';
419
- }
420
-
421
- /**
422
- * Serialize a projected value to bounded JSON text.
423
- *
424
- * The whole-value cap is applied only when the projection still does not fit, and
425
- * it always REPORTS that it fired (through {@link boundedJsonText.exceeded}) so a
426
- * caller can refuse an allow decision rather than approve a tail it never saw.
427
- * @param {unknown} projected - bounded projection.
428
- * @returns {{ text: string, exceeded: boolean }} JSON text and whether the cap fired.
429
- */
430
- function boundedJsonText(projected) {
431
- let text;
432
- try {
433
- text = JSON.stringify(projected);
434
- } catch {
435
- return { text: '[unserializable]', exceeded: true };
436
- }
437
- if (typeof text !== 'string') return { text: '[unserializable]', exceeded: true };
438
- const cap = PERMISSION_BOUNDS.argumentsChars;
439
- if (text.length > cap) {
440
- return { text: `${text.slice(0, cap)}…[+${text.length - cap} chars omitted]`, exceeded: true };
441
- }
442
- return { text, exceeded: false };
443
- }
444
-
445
- /**
446
- * A stable, proto-safe canonical JSON text of an exact value.
447
- *
448
- * `JSON.stringify` is not usable on its own here: it uses ordinary assignment
449
- * internally for the value it returns, but the real problem is the REPLACER an
450
- * earlier version used — `out[key] = value` silently drops a key named
451
- * `__proto__`, so `{"__proto__":{"a":1}}` and `{}` produced the same digest and two
452
- * different operations could be decided by one fingerprint.
453
- *
454
- * This serializer builds the text directly: keys are sorted for stability (so key
455
- * order is not part of the operation), every key is escaped as a JSON string rather
456
- * than assigned as a property, and nesting is explicit. Two objects are therefore
457
- * equal here only when they have the same keys and the same values.
458
- * @param {unknown} value - JSON-compatible value.
459
- * @returns {string} canonical JSON text.
460
- */
461
- export function canonicalJson(value) {
462
- if (value === null) return 'null';
463
- if (typeof value === 'string') return JSON.stringify(value);
464
- if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : 'null';
465
- if (typeof value === 'boolean') return value ? 'true' : 'false';
466
- if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(',')}]`;
467
- if (typeof value === 'object') {
468
- // `Object.keys` reports own enumerable keys only, including one named
469
- // `__proto__` created by `JSON.parse` (which defines it as data, not accessor).
470
- const keys = Object.keys(value).sort();
471
- const parts = [];
472
- for (const key of keys) {
473
- parts.push(`${JSON.stringify(key)}:${canonicalJson(value[key])}`);
474
- }
475
- return `{${parts.join(',')}}`;
476
- }
477
- return 'null';
478
- }
479
-
480
- /**
481
- * A stable fingerprint of an exact value.
482
- *
483
- * The digest is over {@link canonicalJson}, so it depends on the operation and not
484
- * on key order, and it is a digest rather than the value so the private binding
485
- * never has to keep (or publish) a second copy of the arguments.
486
- * @param {unknown} value - JSON-compatible value.
487
- * @returns {string} `sha256:<hex>` digest.
488
- */
489
- export function fingerprintOf(value) {
490
- return `sha256:${createHash('sha256').update(canonicalJson(value), 'utf8').digest('hex')}`;
491
- }
492
-
493
- /**
494
- * Read the real tool call one approval request is about, from the Session log.
495
- *
496
- * The native loop commits `tool/call` before the tool executes, so the arguments
497
- * are already in the log when the tool asks. The match is:
498
- *
499
- * * the event type is `tool/call`;
500
- * * its `callId` equals the request's `callId` EXACTLY (a missing `callId` is a
501
- * refusal, not a search);
502
- * * its `name` equals the request's `toolName` (a mismatch is a refusal: the
503
- * request and the log disagree about what is being decided);
504
- * * the newest such event wins if an id were ever repeated (the live one).
505
- *
506
- * A Session that exposes no readable log, a log whose reads throw, and a missing
507
- * match are all refusals with their own bounded reason.
508
- * @param {object} session - the asking agent's Session.
509
- * @param {object} request - native approval request (`callId`, `toolName`).
510
- * @returns {{ ok: true, call: { callId: string, name: string, argumentsText: string, turn: number|null, step: number|null, seq: number|null } }
511
- * | { ok: false, reason: string }} the located call, or a bounded refusal.
512
- */
513
- export function locateToolCall(session, request) {
514
- const callId = request?.callId;
515
- if (typeof callId !== 'string' || callId === '') return { ok: false, reason: PERMISSION_REASONS.noCallId };
516
- if (session === null || typeof session !== 'object') return { ok: false, reason: PERMISSION_REASONS.noSession };
517
- const seq = typeof session.seq === 'number' && Number.isInteger(session.seq) ? session.seq : null;
518
- if (seq === null || typeof session.eventAt !== 'function') return { ok: false, reason: PERMISSION_REASONS.noSession };
519
- const toolName = typeof request?.toolName === 'string' ? request.toolName : null;
520
- let found = null;
521
- for (let index = seq - 1; index >= 0; index -= 1) {
522
- let event;
523
- try {
524
- event = session.eventAt(index);
525
- } catch {
526
- return { ok: false, reason: PERMISSION_REASONS.callNotFound };
527
- }
528
- if (event === null || typeof event !== 'object' || event.type !== 'tool/call') continue;
529
- const data = event.data ?? {};
530
- if (data.callId !== callId) continue;
531
- found = { event, data, index };
532
- break;
533
- }
534
- if (found === null) return { ok: false, reason: PERMISSION_REASONS.callNotFound };
535
- const name = typeof found.data.name === 'string' ? found.data.name : null;
536
- if (toolName !== null && name !== toolName) return { ok: false, reason: PERMISSION_REASONS.nameMismatch };
537
- const argumentsText = typeof found.data.arguments === 'string' ? found.data.arguments : null;
538
- if (argumentsText === null) return { ok: false, reason: PERMISSION_REASONS.argumentsUnusable };
539
- return {
540
- ok: true,
541
- call: {
542
- callId,
543
- name: name ?? toolName ?? null,
544
- argumentsText,
545
- turn: Number.isInteger(found.data.turn) ? found.data.turn : null,
546
- step: Number.isInteger(found.data.step) ? found.data.step : null,
547
- seq: found.index,
548
- },
549
- };
550
- }
551
-
552
- /**
553
- * Whether the Session log is inside an open turn at one offset.
554
- *
555
- * This mirrors the native check `ApprovalService.request()` performs before it will
556
- * answer at all (`hasOpenTurn` in the legacy service, the `turnOpen` projection in
557
- * the modern one): the last `turn/start`/`turn/end` before the offset decides. It is
558
- * re-used here because a decision re-verifies the operation at decision time, and a
559
- * call whose turn has closed is not a call an allow can still apply to.
560
- * @param {object} session - Session with `eventAt`.
561
- * @param {number} seq - the tool call's offset.
562
- * @returns {boolean | null} true/false, or null when the log cannot be read.
563
- */
564
- export function turnOpenAt(session, seq) {
565
- return openTurnAt(session, seq) !== null;
566
- }
567
-
568
- /**
569
- * The turn NUMBER that is open at the CURRENT tail of the log, or `null`.
570
- *
571
- * `turnOpenAt` answers "is anything open now"; this answers "WHICH turn is open
572
- * now". The difference matters: a request asked inside turn 2, then closed and a
573
- * turn 3 opened, is still "a turn is open" — but it is not the turn that asked. The
574
- * live-binding check compares this number against the one recorded when the request
575
- * was created, which is what refuses a close-then-reopen.
576
- *
577
- * The scan starts at the END of the log (the live tail) and uses each `turn/start`
578
- * event's own `turn` field when present, falling back to a running counter so a log
579
- * that omits the field is still distinguishable across turns.
580
- * @param {object} session - Session with `eventAt`.
581
- * @param {number} [fromSeq] - lowest offset to scan back to (the call's offset).
582
- * @returns {number | null} the open turn number, or null when none is open or the log is unreadable.
583
- */
584
- export function openTurnAt(session, fromSeq) {
585
- if (session === null || typeof session !== 'object' || typeof session.eventAt !== 'function') return null;
586
- const total = typeof session.seq === 'number' && Number.isInteger(session.seq) ? session.seq : null;
587
- if (total === null) return null;
588
- const floor = typeof fromSeq === 'number' && Number.isInteger(fromSeq) && fromSeq >= 0 ? fromSeq : 0;
589
- try {
590
- for (let index = total - 1; index >= floor; index -= 1) {
591
- const event = session.eventAt(index);
592
- if (event === null || event === undefined || typeof event !== 'object') continue;
593
- if (event.type === 'turn/end') return null;
594
- if (event.type !== 'turn/start') continue;
595
- const declared = event.data?.turn;
596
- if (typeof declared === 'number' && Number.isInteger(declared)) return declared;
597
- // No field: identify the turn by its POSITION, which is still a stable and
598
- // comparable identity for the same log. Negative so it can never be mistaken
599
- // for a real turn number.
600
- return -1 - index;
601
- }
602
- } catch {
603
- return null;
604
- }
605
- return null;
606
- }
607
-
608
- /**
609
- * The text sent back into the worker after its call was rejected.
610
- *
611
- * It is written for the MODEL, not for a log, and every sentence is load-bearing:
612
- *
613
- * * the decision is final — the call was rejected and stays rejected;
614
- * * nothing was widened — not the sandbox, not the grant, not the mode;
615
- * * the note is not an authorization — a later attempt needs its own approval;
616
- * * what to do: rewrite the operation to fit the stated reason and ask again.
617
- *
618
- * The reason is already redacted and bounded by the caller, so this function only
619
- * composes. The operation is named by tool and call id so the worker can tell WHICH
620
- * call was refused when several are in flight.
621
- * @param {object} pending - the settled request.
622
- * @param {string} reason - the commander's reason, redacted and bounded.
623
- * @returns {string} the message body.
624
- */
625
- export function rejectionFeedbackText(pending, reason) {
626
- const tool = typeof pending?.toolName === 'string' && pending.toolName !== '' ? pending.toolName : 'the requested tool call';
627
- const callId = typeof pending?.callId === 'string' && pending.callId !== '' ? pending.callId : 'unknown';
628
- const requestId = typeof pending?.requestId === 'string' && pending.requestId !== '' ? pending.requestId : 'unknown';
629
- const taskId = typeof pending?.taskId === 'string' && pending.taskId !== '' ? pending.taskId : 'unknown';
630
- const stated = typeof reason === 'string' && reason.trim() !== ''
631
- ? reason.trim()
632
- : 'no reason was given';
633
- return [
634
- `The commander REJECTED your ${tool} call (task ${taskId}, request ${requestId}, call id ${callId}).`,
635
- `Reason for rejecting this one operation: ${stated}`,
636
- 'The rejection stands: this call was not approved and will not run.',
637
- 'Nothing was granted or widened. Sandbox permissions, the delegation switch, the session policy and your standing sandbox mode are unchanged.',
638
- 'This note is NOT a new authorization and grants nothing by itself. If you still need the operation, change it to fit the reason above and request approval again; the new request will be decided on its own.',
639
- ].join(' ');
640
- }
641
-
642
- /**
643
- * The message shape an Agent's inbox accepts, built without the native LLM package.
644
- *
645
- * `agent.inject()` takes a user message object; the native helper is `createUserMessage`
646
- * from `@deepseek-ai/dsh-llm`, which this module deliberately does not import (the stdio
647
- * executable links it). This default therefore produces the same minimum shape, and the
648
- * plugin's own composition injects the REAL factory so production never depends on it.
649
- *
650
- * The source kind is `'user-approval'` — the value the native approval service already
651
- * uses for its own policy notices — so the message is a recognised producer's message, not
652
- * an invented source. Nothing here claims to be a user instruction.
653
- * @param {string} text - message body.
654
- * @returns {{ role: 'user', content: { type: 'text', text: string }[], source: { kind: string } }} message.
655
- */
656
- export function defaultUserMessage(text) {
657
- return {
658
- role: 'user',
659
- content: [{ type: 'text', text }],
660
- source: { kind: 'user-approval' },
661
- };
662
- }
663
-
664
- /**
665
- * The permission bridge for ONE delegated run.
666
- *
667
- * One broker per worker run. It is written in the run's own scope, armed before
668
- * the prompt is delivered and disposed when the run ends, and it answers only
669
- * requests that name the Agent it was armed for. A request whose identity cannot
670
- * be established is answered from the fail-closed vocabulary — never allowed.
671
- */
672
- export class PermissionBridge {
673
- /**
674
- * @param {object} options - `taskId`, `connectionId`, `sessionId`, optional
675
- * `timeoutMs` (bounded), optional `now`, optional `redact`, optional
676
- * `isSecretKey` (the key-aware redaction predicate), optional `onPending`,
677
- * optional `onSettled`, optional `logger`.
678
- */
679
- constructor(options) {
680
- if (typeof options?.taskId !== 'string' || options.taskId === '') {
681
- throw new TypeError('PermissionBridge needs the taskId it belongs to');
682
- }
683
- this.taskId = options.taskId;
684
- this.connectionId = typeof options.connectionId === 'string' ? options.connectionId : null;
685
- this.sessionId = typeof options.sessionId === 'string' ? options.sessionId : null;
686
- this.redact = typeof options.redact === 'function' ? options.redact : defaultRedact;
687
- // The key-aware half of redaction. Injected so this module and the stored-document
688
- // redaction agree on ONE definition of "this key names a secret"; the fallback
689
- // above keeps a harness-free import from being weaker than the plugin.
690
- this.isSecretKey = typeof options.isSecretKey === 'function' ? options.isSecretKey : null;
691
- this.now = typeof options.now === 'function' ? options.now : () => Date.now();
692
- const configured = Number(options.timeoutMs);
693
- this.timeoutMs = Number.isFinite(configured) && configured > 0
694
- ? Math.min(configured, PERMISSION_MAX_TIMEOUT_MS)
695
- : PERMISSION_DEFAULT_TIMEOUT_MS;
696
- this.onPending = typeof options.onPending === 'function' ? options.onPending : null;
697
- this.onSettled = typeof options.onSettled === 'function' ? options.onSettled : null;
698
- this.logger = options.logger ?? null;
699
- // The lifecycle latch. `armed` is what the policy writer reads: only an armed
700
- // bridge may have `ask` installed for its Session, and `dispose()` clears it
701
- // before the policy is restored.
702
- this.armed = false;
703
- this.disposed = false;
704
- this.agent = null;
705
- this.session = null;
706
- // At most one outstanding request: a single tool call cannot be asked twice,
707
- // and "one pending request per task" is what makes the commander's decision
708
- // unambiguous without a second ordering rule.
709
- this.pending = null;
710
- // Every settled request, newest last, bounded. This is the evidence trail the
711
- // task view and the durable history carry; it never holds an argument value
712
- // that was not redacted at construction time.
713
- this.history = [];
714
- this.sequence = 0;
715
- // The Session identity the bridge was ARMED for, kept separately from
716
- // `this.session` so a replaced `agent.session` is detectable rather than silently
717
- // followed (see {@link liveBindingRefusal}).
718
- this.boundSessionId = null;
719
- // Request id -> the id of the message that carried its rejection reason. One entry
720
- // per delivered note, so a repeated reject, a retried decision or a restart cannot
721
- // deliver the same feedback twice.
722
- this.feedbackSent = new Map();
723
- // The message factory. Injected so this module stays free of a hard dependency on the
724
- // native LLM package (the stdio executable imports this file); the plugin passes the
725
- // real `createUserMessage`, and the default below builds the same shape.
726
- this.createMessage = typeof options.createUserMessage === 'function'
727
- ? options.createUserMessage
728
- : defaultUserMessage;
729
- }
730
-
731
- /** Maximum settled requests retained on one run. */
732
- static get HISTORY_BOUND() {
733
- return 8;
734
- }
735
-
736
- /**
737
- * Bind the bridge to the Agent/Session it will answer for.
738
- *
739
- * Called from the run's setup step, AFTER the preset is mounted (so the tool
740
- * surface is the real one) and BEFORE the prompt (so no turn can ask under an
741
- * unarmed bridge). Re-arming the same run is idempotent; binding a DIFFERENT
742
- * Agent is a refusal, because a bridge belongs to one conversation.
743
- * @param {object} agent - the live native Agent the run will drive.
744
- * @returns {{ taskId: string, sessionId: string }} what was armed.
745
- * @throws {PermissionError} when the agent is unusable or is not the bound one.
746
- */
747
- arm(agent) {
748
- if (this.disposed) {
749
- throw new PermissionError(PERMISSION_CODES.unbound, 'the permission bridge was already disposed', {
750
- reason: PERMISSION_REASONS.disposed,
751
- });
752
- }
753
- const session = agent?.session ?? null;
754
- const sessionId = typeof session?.id === 'string' ? session.id : (typeof agent?.id === 'string' ? agent.id : null);
755
- if (session === null || sessionId === null) {
756
- throw new PermissionError(PERMISSION_CODES.unbound, 'the delegated agent exposes no session to bind approvals to', {
757
- reason: PERMISSION_REASONS.noSession,
758
- });
759
- }
760
- if (this.agent !== null && this.agent !== agent) {
761
- throw new PermissionError(PERMISSION_CODES.unbound, 'the permission bridge is already bound to another agent', {
762
- reason: PERMISSION_REASONS.agentMismatch,
763
- });
764
- }
765
- this.agent = agent;
766
- this.session = session;
767
- this.sessionId = this.sessionId ?? sessionId;
768
- // Pinned at arm time: the exact Session id this bridge answers for.
769
- this.boundSessionId = sessionId;
770
- this.armed = true;
771
- return { taskId: this.taskId, sessionId: this.sessionId };
772
- }
773
-
774
- /**
775
- * Whether this bridge answers for one native approval request.
776
- *
777
- * The rule is EXACT identity, and it is deliberately strict in both directions:
778
- *
779
- * * the bridge must be armed, bound, and not disposed;
780
- * * `request.agent` MUST be present — a request with no agent (`null`,
781
- * `undefined`) is not "probably mine", it is unidentifiable, and answering it
782
- * would let any caller that forgets to pass an agent be decided by this bridge;
783
- * * that agent must be the SAME OBJECT the bridge was armed for. The native
784
- * approval seam passes the live Agent the requesting tool is running for, so
785
- * object identity is exactly the question "is this my Agent", and it cannot be
786
- * forged from data;
787
- * * when the agent exposes a Session id, it must equal the bound one.
788
- *
789
- * A request for a different agent in the same process is not this bridge's
790
- * business: the listener falls through to the next answerer so the ordinary
791
- * session keeps whatever prompt it actually has.
792
- * @param {object} request - native approval request.
793
- * @returns {boolean} true when this bridge owns the request.
794
- */
795
- owns(request) {
796
- if (this.armed !== true || this.disposed === true) return false;
797
- if (this.agent === null || this.session === null) return false;
798
- const agent = request?.agent;
799
- // No agent at all: unidentifiable, so NOT owned. `?? null` here would have made
800
- // a missing agent match every bridge, which is the defect this check removes.
801
- if (agent === null || agent === undefined || typeof agent !== 'object') return false;
802
- if (agent !== this.agent) return false;
803
- const sessionId = typeof agent?.session?.id === 'string' ? agent.session.id : null;
804
- if (sessionId !== null && this.sessionId !== null && sessionId !== this.sessionId) return false;
805
- return true;
806
- }
807
-
808
- /**
809
- * Re-read the bound operation from the live Session and prove it is unchanged.
810
- *
811
- * A decision is not taken against the copy captured when the request was created:
812
- * the native log is read AGAIN at the moment of decision, and the operation must
813
- * still be there, still be the same record at the same offset, still carry the
814
- * same tool name, and still carry byte-identical arguments. It must also still be
815
- * inside an OPEN turn — a call whose turn has already ended is history, and an
816
- * allow for it would apply to nothing (or, worse, to whatever reuses the id).
817
- *
818
- * This is what makes "the session/tool call/argument snapshot is re-verified at
819
- * decision" a checked fact rather than an assumption.
820
- * @param {object} pending - pending record, whose `callId`/`callSeq` pin the call.
821
- * @returns {string | null} a fixed refusal reason, or null when still exact.
822
- */
823
- reverifyOperation(pending) {
824
- const live = this.liveBindingRefusal();
825
- if (live !== null) return live;
826
- const seq = pending?.callSeq;
827
- if (typeof seq !== 'number' || !Number.isInteger(seq) || seq < 0) {
828
- return PERMISSION_REASONS.noCallSeq;
829
- }
830
- let event;
831
- try {
832
- event = this.session.eventAt(seq);
833
- } catch {
834
- return PERMISSION_REASONS.callMissing;
835
- }
836
- if (event === null || event === undefined || typeof event !== 'object' || event.type !== 'tool/call') {
837
- return PERMISSION_REASONS.callMissing;
838
- }
839
- const data = event.data ?? {};
840
- if (data.callId !== pending.callId) return PERMISSION_REASONS.callChanged;
841
- // EXACT name equality. The old `typeof data.name === 'string' && …` guard made a
842
- // REMOVED name pass, so a record whose tool name had been stripped still allowed.
843
- if (data.name !== pending.toolName) return PERMISSION_REASONS.callChanged;
844
- // Turn/step identity, compared exactly when the request pinned one.
845
- if (pending.turn !== null && data.turn !== pending.turn) return PERMISSION_REASONS.callChanged;
846
- if (pending.step !== null && data.step !== pending.step) return PERMISSION_REASONS.callChanged;
847
- if (typeof data.arguments !== 'string' || data.arguments !== pending.exactArguments) {
848
- // A changed argument string at the SAME offset means the record was mutated
849
- // or the Session was replaced underneath this bridge. Either way the evidence
850
- // the commander saw is not the operation any more.
851
- return PERMISSION_REASONS.callChanged;
852
- }
853
- // The SAME originating turn must still be the open one at the CURRENT TAIL.
854
- // Checking only "is some turn open now" would accept a close-then-reopen: the
855
- // question was asked in turn N, and a decision taken in turn N+1 is not about the
856
- // same live step. A closed tail (`null`) never equals a recorded turn number.
857
- if (openTurnAt(this.session) !== pending.turnAtAsk) return PERMISSION_REASONS.turnClosed;
858
- return null;
859
- }
860
-
861
- /**
862
- * Prove the bridge is still bound to the LIVE Agent and Session it was armed for.
863
- *
864
- * The previous check only looked at `this.session`. That misses the case the audit
865
- * reproduced: while a request is pending, the Agent's `session` is REPLACED, so the
866
- * bridge keeps reading the old (frozen, still-open-looking) log while the agent
867
- * actually drives a different conversation. Both the object identity AND the id are
868
- * compared, because a replaced session with a recycled id is still a different
869
- * conversation.
870
- * @returns {string | null} a fixed refusal reason, or null when still bound.
871
- */
872
- liveBindingRefusal() {
873
- const agent = this.agent;
874
- if (agent === null || agent === undefined) return PERMISSION_REASONS.sessionGone;
875
- const liveSession = agent.session;
876
- if (liveSession === null || liveSession === undefined) return PERMISSION_REASONS.sessionGone;
877
- if (liveSession !== this.session) return PERMISSION_REASONS.sessionGone;
878
- if (this.boundSessionId !== null && liveSession.id !== this.boundSessionId) {
879
- return PERMISSION_REASONS.sessionGone;
880
- }
881
- if (this.session === null || typeof this.session.eventAt !== 'function') {
882
- return PERMISSION_REASONS.sessionGone;
883
- }
884
- return null;
885
- }
886
-
887
- /**
888
- * Answer one native approval request.
889
- *
890
- * The closed outcomes and their causes:
891
- *
892
- * * `unavailable` — the bridge is not armed/disposed, the request is not this
893
- * bridge's, or a request is already outstanding. Fail closed, because
894
- * "somebody else's question" and "two questions at once" are both states this
895
- * plugin cannot decide honestly.
896
- * * `cancelled` — the asking tool withdrew the request (its own signal), or
897
- * the run stopped while it was pending.
898
- * * `rejected` — the deadline expired, the request had no call identity, or no
899
- * `tool/call` matching it could be read. The operation is refused; the
900
- * diagnostics say which check failed.
901
- * * `allowed-once` — ONLY a commander decision that matched this exact
902
- * fingerprint.
903
- *
904
- * @param {object} request - `{ agent, toolName, callId?, reason?, signal? }`.
905
- * @returns {Promise<string>} one of {@link APPROVAL_OUTCOMES}.
906
- */
907
- async answer(request) {
908
- if (this.armed !== true || this.disposed === true) return 'unavailable';
909
- if (!this.owns(request)) return 'unavailable';
910
- if (this.pending !== null) {
911
- this.logger?.warn?.('dsh-delegate: a second approval request arrived while one was pending; refusing it');
912
- return 'unavailable';
913
- }
914
- const signal = request?.signal;
915
- if (signal?.aborted === true) return 'cancelled';
916
- const located = locateToolCall(this.session, request);
917
- if (located.ok !== true) {
918
- // An unidentifiable request is a refusal, not a silent wait: nobody could
919
- // bind a decision to it, so it must not occupy the pending slot.
920
- this.recordRejectedBinding(request, located.reason);
921
- return 'rejected';
922
- }
923
- const pending = this.createPending(request, located.call);
924
- if (pending === null) {
925
- this.recordRejectedBinding(request, PERMISSION_REASONS.argumentsUnusable);
926
- return 'rejected';
927
- }
928
- return await this.waitForDecision(pending, signal);
929
- }
930
-
931
- /**
932
- * Build the pending record for one identified request.
933
- *
934
- * The record keeps BOTH halves of the operation:
935
- *
936
- * * the exact fingerprint and the exact argument text, which are private and are
937
- * what a decision is bound to and re-verified against;
938
- * * the redacted projection and its COMPLETENESS, which is what the commander is
939
- * shown.
940
- *
941
- * The completeness flags are computed here, once, from the real arguments:
942
- * `argumentsComplete` is false when any bound fired, and `allowBlocked` names the
943
- * reason an `allow-once` would be refused for it (see {@link allowRefusalReason}).
944
- * @param {object} request - native approval request.
945
- * @param {object} call - located `tool/call` facts.
946
- * @returns {object | null} pending record, or null when it cannot be described.
947
- */
948
- createPending(request, call) {
949
- let parsed;
950
- try {
951
- parsed = JSON.parse(call.argumentsText);
952
- } catch {
953
- return null;
954
- }
955
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
956
- // A tool call whose arguments are not an object cannot be fingerprinted
957
- // per-key, and every enforcing tool in this composition takes one.
958
- return null;
959
- }
960
- this.sequence += 1;
961
- const createdAt = this.now();
962
- const state = newProjectionState();
963
- const projected = projectValue(parsed, {
964
- redact: this.redact,
965
- isSecretKey: this.isSecretKey,
966
- state,
967
- });
968
- const rendered = boundedJsonText(projected);
969
- if (rendered.exceeded) noteCut(state, 'value');
970
- const pending = {
971
- requestId: `permission-${this.taskId}-${this.sequence}`,
972
- taskId: this.taskId,
973
- connectionId: this.connectionId,
974
- sessionId: this.sessionId,
975
- toolName: call.name,
976
- callId: call.callId,
977
- turn: call.turn,
978
- step: call.step,
979
- // The Session log offset the operation was read from. A decision re-reads
980
- // that same offset and refuses if the call is no longer the same record.
981
- callSeq: call.seq,
982
- // WHICH turn was open when the question was asked. A decision needs this exact
983
- // turn to still be the open one; "some turn is open" is not enough, because a
984
- // close-then-reopen opens a DIFFERENT turn the request never asked in.
985
- //
986
- // Read at the TAIL (no lower bound): the seam asks while its call is the newest
987
- // event, so the tail's open turn IS the asking turn. Passing the call's offset
988
- // here would start the scan at the `turn/start` behind it and report a turn that
989
- // a later `turn/end` had already closed.
990
- turnAtAsk: openTurnAt(this.session),
991
- // The exact Session object and id the operation was read from.
992
- boundSessionId: this.boundSessionId,
993
- // A non-reusable identity: the fingerprint is over the EXACT arguments as
994
- // the model produced them, so a later call with different arguments can
995
- // never be decided by this request's evidence.
996
- fingerprint: fingerprintOf(parsed),
997
- // The exact argument text, retained PRIVATELY (never published) so a decision
998
- // can re-compare the operation byte for byte instead of trusting a digest of
999
- // a record it did not re-read.
1000
- exactArguments: call.argumentsText,
1001
- // Redacted, bounded rendering of the same operation, safe to publish.
1002
- arguments: rendered.text,
1003
- argumentKeys: Object.keys(parsed).slice(0, PERMISSION_BOUNDS.argumentKeys).map((key) => this.redact(key)),
1004
- // Completeness, stated rather than inferred from a trailing marker.
1005
- argumentsComplete: state.cuts.length === 0,
1006
- completeness: state.cuts.length === 0 ? PERMISSION_COMPLETENESS.complete : PERMISSION_COMPLETENESS.truncated,
1007
- omitted: {
1008
- valueChars: state.valueCuts,
1009
- keys: state.keyCuts,
1010
- depth: state.depthCuts,
1011
- items: state.itemCuts,
1012
- },
1013
- // Which bounds fired, in a fixed vocabulary, so the refusal can be explained.
1014
- boundsApplied: [...state.cuts],
1015
- // The asker's own claim about why it asks, labelled as a claim. It is never
1016
- // the operation and never a grant.
1017
- claimedReason: this.boundText(request?.reason, PERMISSION_BOUNDS.reasonChars),
1018
- requestedAccess: this.requestedAccessOf(parsed),
1019
- createdAt,
1020
- deadlineAt: createdAt + this.timeoutMs,
1021
- state: PERMISSION_STATES.pending,
1022
- decision: null,
1023
- decidedAt: null,
1024
- decidedBy: null,
1025
- decisionReason: null,
1026
- settledOutcome: null,
1027
- resolve: null,
1028
- timer: null,
1029
- onExternalAbort: null,
1030
- externalSignal: null,
1031
- };
1032
- pending.allowBlocked = this.allowRefusalReason(pending);
1033
- return pending;
1034
- }
1035
-
1036
- /**
1037
- * Why an `allow-once` must be refused for this request, or `null`.
1038
- *
1039
- * The rule is the one the commander's decision depends on: **never allow an
1040
- * operation whose executable material was omitted by a bound.** A truncated
1041
- * `bash.command` can hide the tail that actually runs; a truncated `write.body`
1042
- * can hide what is written. `reject` stays available in every one of these cases,
1043
- * because refusing is always safe — it is the ALLOW that needs complete evidence.
1044
- * @param {object} pending - pending record.
1045
- * @returns {string | null} fixed reason, or null when an allow is decidable.
1046
- */
1047
- allowRefusalReason(pending) {
1048
- if (pending?.argumentsComplete !== true) {
1049
- return PERMISSION_REASONS.incompleteEvidence;
1050
- }
1051
- if (pending?.callSeq === null || pending?.callSeq === undefined) {
1052
- return PERMISSION_REASONS.noCallSeq;
1053
- }
1054
- return null;
1055
- }
1056
-
1057
-
1058
- /**
1059
- * Describe the access the call asks for, from the REAL arguments.
1060
- *
1061
- * Stated from the operation, never from the asker's prose: a sandbox escalation
1062
- * is `{ mode, requested: true }`, any other asking call is `{ mode: null }`.
1063
- * @param {object} args - parsed arguments.
1064
- * @returns {{ kind: string, mode: string | null }} bounded access fact.
1065
- */
1066
- requestedAccessOf(args) {
1067
- const mode = args?.sandbox_permissions;
1068
- if (typeof mode === 'string' && mode !== '') {
1069
- return { kind: 'sandbox-escalation', mode };
1070
- }
1071
- return { kind: 'tool-call', mode: null };
1072
- }
1073
-
1074
- /**
1075
- * Wait, boundedly, for the commander's decision.
1076
- *
1077
- * Two lifetimes race here and both settle the waiter exactly once: the
1078
- * commander's decision (bound to this request id and fingerprint) and the
1079
- * request's own deadline. A third, the asking tool's abort signal, pierces the
1080
- * wait so a cancelled tool call cannot leave a request looking pending.
1081
- * @param {object} pending - pending record.
1082
- * @param {AbortSignal | undefined} signal - the asking tool's signal.
1083
- * @returns {Promise<string>} the closed native outcome.
1084
- */
1085
- async waitForDecision(pending, signal) {
1086
- this.pending = pending;
1087
- const decision = new Promise((resolvePromise) => {
1088
- pending.resolve = resolvePromise;
1089
- });
1090
- // The deadline is this request's OWN bound: it is independent of the run's
1091
- // execution budget, which the engine pauses while this is outstanding.
1092
- pending.timer = setTimeout(() => {
1093
- pending.timer = null;
1094
- this.settle(pending, PERMISSION_STATES.expired, 'rejected', {
1095
- reason: 'the permission request reached its deadline without a decision',
1096
- decidedBy: 'deadline',
1097
- });
1098
- }, this.timeoutMs);
1099
- pending.timer.unref?.();
1100
- if (signal !== undefined && signal !== null && typeof signal.addEventListener === 'function') {
1101
- pending.externalSignal = signal;
1102
- pending.onExternalAbort = () => {
1103
- this.settle(pending, PERMISSION_STATES.cancelled, 'cancelled', {
1104
- reason: PERMISSION_REASONS.aborted,
1105
- decidedBy: 'asker',
1106
- });
1107
- };
1108
- signal.addEventListener('abort', pending.onExternalAbort, { once: true });
1109
- }
1110
- this.emitPending(pending);
1111
- try {
1112
- return await decision;
1113
- } finally {
1114
- this.clearPending(pending);
1115
- }
1116
- }
1117
-
1118
- /**
1119
- * Publish one pending request to its observers (the engine records the phase).
1120
- *
1121
- * An observer throw is contained: a task view that cannot be updated must not
1122
- * turn a live approval wait into a failed tool call.
1123
- * @param {object} pending - pending record.
1124
- * @returns {void}
1125
- */
1126
- emitPending(pending) {
1127
- if (this.onPending === null) return;
1128
- try {
1129
- this.onPending(this.publicView(pending));
1130
- } catch (error) {
1131
- this.logger?.warn?.('dsh-delegate: permission observer failed', String(error?.code ?? ''));
1132
- }
1133
- }
1134
-
1135
- /**
1136
- * Decide one pending request. Called by the engine on behalf of ONE task.
1137
- *
1138
- * The order is the whole contract, and each step can refuse. It is deliberately
1139
- * ordered so the CHEAP identity checks come first and the LIVE re-verification
1140
- * comes before any grant:
1141
- *
1142
- * 1. the decision value must be one of `allow-once`/`reject` (validated before
1143
- * anything is looked up or mutated);
1144
- * 2. the request must be THIS bridge's own pending request (`requestId`);
1145
- * 3. it must still be pending — a second decision, an expired request and a
1146
- * cancelled one are all refused rather than re-applied;
1147
- * 4. it must not be past its deadline (by the clock, not only by the timer);
1148
- * 5. the fingerprint is **mandatory for `allow-once`** and is compared exactly
1149
- * when supplied for `reject`. An allow must name the operation it grants;
1150
- * 6. **for an allow only**, the operation is re-read from the LIVE Session and
1151
- * must be unchanged at the same offset, in the same tool, with byte-identical
1152
- * arguments, inside a still-open turn; and the projection must have been
1153
- * COMPLETE (no bound fired). Any failure refuses the allow.
1154
- *
1155
- * `reject` deliberately skips 6: refusing is always safe, so a commander can deny
1156
- * a request whose evidence was shortened or whose call has since changed. An
1157
- * `allow-once` may not.
1158
- * @param {object} request - `{ requestId, decision, reason, fingerprint }`.
1159
- * @returns {object} bounded result: the settled request view.
1160
- * @throws {PermissionError} on any refusal.
1161
- */
1162
- decide(request) {
1163
- const requestId = typeof request?.requestId === 'string' ? request.requestId : '';
1164
- if (requestId === '') {
1165
- throw new PermissionError(PERMISSION_CODES.invalid, 'requestId is required', { field: 'requestId' });
1166
- }
1167
- const decision = request?.decision;
1168
- if (!PERMISSION_DECISIONS.includes(decision)) {
1169
- throw new PermissionError(PERMISSION_CODES.invalid, 'decision must be allow-once or reject', {
1170
- field: 'decision',
1171
- accepted: [...PERMISSION_DECISIONS],
1172
- });
1173
- }
1174
- const allow = decision === 'allow-once';
1175
- const pending = this.pending;
1176
- if (pending === null || pending.requestId !== requestId) {
1177
- // An unknown id, another run's id and an already-settled id are ONE answer:
1178
- // the caller learns nothing about requests it did not own.
1179
- const settled = this.history.find((entry) => entry.requestId === requestId) ?? null;
1180
- if (settled !== null) {
1181
- throw new PermissionError(PERMISSION_CODES.notPending, 'this permission request is already settled', {
1182
- requestId,
1183
- state: settled.state,
1184
- outcome: settled.settledOutcome,
1185
- });
1186
- }
1187
- throw new PermissionError(PERMISSION_CODES.notFound, 'no pending permission request matches this identity', {
1188
- requestId,
1189
- });
1190
- }
1191
- if (pending.state !== PERMISSION_STATES.pending) {
1192
- throw new PermissionError(PERMISSION_CODES.notPending, 'this permission request is already settled', {
1193
- requestId,
1194
- state: pending.state,
1195
- });
1196
- }
1197
- if (this.now() >= pending.deadlineAt) {
1198
- // Expiry is decided by the clock, not only by the timer: a decision that
1199
- // races the deadline must not resurrect a request nobody may answer.
1200
- this.settle(pending, PERMISSION_STATES.expired, 'rejected', {
1201
- reason: 'the permission request reached its deadline',
1202
- decidedBy: 'deadline',
1203
- });
1204
- throw new PermissionError(PERMISSION_CODES.expired, 'the permission request expired before this decision', {
1205
- requestId,
1206
- });
1207
- }
1208
-
1209
- const supplied = request?.fingerprint;
1210
- if (allow && (typeof supplied !== 'string' || supplied === '')) {
1211
- // An allow without a fingerprint would grant "whatever is pending", which is
1212
- // exactly the substitution this design refuses. The request stays pending so
1213
- // a correct decision can still be made.
1214
- throw new PermissionError(
1215
- PERMISSION_CODES.invalid,
1216
- 'an allow-once decision must quote the request fingerprint',
1217
- { requestId, field: 'fingerprint', reason: PERMISSION_REASONS.fingerprintRequired },
1218
- );
1219
- }
1220
- if (typeof supplied === 'string' && supplied !== pending.fingerprint) {
1221
- // The operation the caller believes it is deciding is not the operation that
1222
- // is pending. Refused, and the request is left pending for the two parties
1223
- // that actually know what it is.
1224
- throw new PermissionError(PERMISSION_CODES.changed, 'the pending operation does not match the fingerprint supplied', {
1225
- requestId,
1226
- });
1227
- }
1228
-
1229
- if (allow) {
1230
- // 6a. completeness: never allow an operation whose material was omitted.
1231
- const blocked = pending.allowBlocked ?? this.allowRefusalReason(pending);
1232
- if (blocked !== null) {
1233
- throw new PermissionError(
1234
- PERMISSION_CODES.incomplete,
1235
- blocked === PERMISSION_REASONS.incompleteEvidence
1236
- ? 'the operation was shortened by a bound, so it cannot be allowed; reject it or ask the worker to narrow the call'
1237
- : 'the recorded tool call cannot be re-verified, so an allow cannot be granted',
1238
- { requestId, reason: blocked, boundsApplied: [...pending.boundsApplied] },
1239
- );
1240
- }
1241
- // 6b. the operation must still be the SAME live record.
1242
- const changed = this.reverifyOperation(pending);
1243
- if (changed !== null) {
1244
- throw new PermissionError(
1245
- PERMISSION_CODES.changed,
1246
- 'the recorded tool call is no longer the exact operation this request was created for',
1247
- { requestId, reason: changed },
1248
- );
1249
- }
1250
- }
1251
-
1252
- const reason = this.boundText(request?.reason, PERMISSION_BOUNDS.decisionReasonChars);
1253
- const outcome = allow ? 'allowed-once' : 'rejected';
1254
- this.settle(pending, PERMISSION_STATES.decided, outcome, {
1255
- reason: reason ?? (allow ? 'the commander allowed this call once' : 'the commander rejected this call'),
1256
- decidedBy: 'commander',
1257
- // Record which checks the grant passed, so the evidence states WHY an allow
1258
- // was allowed instead of only that it was.
1259
- ...(allow
1260
- ? {
1261
- verified: {
1262
- fingerprintQuoted: true,
1263
- argumentsComplete: pending.argumentsComplete === true,
1264
- callReread: true,
1265
- turnOpen: true,
1266
- boundsApplied: [...pending.boundsApplied],
1267
- },
1268
- }
1269
- : {}),
1270
- });
1271
- return this.history.at(-1) ?? null;
1272
- }
1273
-
1274
- /**
1275
- * Settle one pending request exactly once and release its waiter.
1276
- *
1277
- * Idempotent by state: the deadline timer, the tool's abort signal, a decision
1278
- * and a stop can all race, and only the first one is applied. The waiter's
1279
- * promise is resolved with the OUTCOME, so the paused tool call resumes with
1280
- * the native vocabulary rather than with this module's own words.
1281
- * @param {object} pending - pending record.
1282
- * @param {string} state - `decided`/`expired`/`cancelled`/`unavailable`.
1283
- * @param {string} outcome - one of {@link APPROVAL_OUTCOMES}.
1284
- * @param {object} [evidence] - `reason`, `decidedBy`.
1285
- * @returns {boolean} true when this call settled the request.
1286
- */
1287
- settle(pending, state, outcome, evidence = {}) {
1288
- if (pending === null || pending.state !== PERMISSION_STATES.pending) return false;
1289
- pending.state = state;
1290
- pending.settledOutcome = APPROVAL_OUTCOMES.includes(outcome) ? outcome : 'unavailable';
1291
- pending.decidedAt = this.now();
1292
- pending.decidedBy = evidence.decidedBy ?? null;
1293
- pending.decisionReason = typeof evidence.reason === 'string' ? this.redact(evidence.reason).slice(0, PERMISSION_BOUNDS.decisionReasonChars) : null;
1294
- if (evidence.verified !== undefined && evidence.verified !== null) {
1295
- pending.verified = evidence.verified;
1296
- }
1297
- if (pending.timer !== null) {
1298
- clearTimeout(pending.timer);
1299
- pending.timer = null;
1300
- }
1301
- if (pending.externalSignal !== null && pending.onExternalAbort !== null) {
1302
- try {
1303
- pending.externalSignal.removeEventListener?.('abort', pending.onExternalAbort);
1304
- } catch {
1305
- // Removing a listener from a foreign signal is best effort by contract.
1306
- }
1307
- pending.onExternalAbort = null;
1308
- pending.externalSignal = null;
1309
- }
1310
- this.history.push(this.publicView(pending));
1311
- if (this.history.length > PermissionBridge.HISTORY_BOUND) this.history.shift();
1312
- // The reason is delivered to the worker BEFORE the paused tool call is released, so
1313
- // the note is already in the Agent's inbox by the time the model can take its next
1314
- // step. It is delivered only for a REJECT: an allow needs no explanation, and a
1315
- // cancellation is not a decision about the operation.
1316
- let feedback = null;
1317
- if (pending.settledOutcome === 'rejected' && pending.decidedBy === 'commander') {
1318
- feedback = this.deliverRejectionFeedback(pending, pending.decisionReason);
1319
- // Recorded on the settled view as a verified fact, so "the worker was told why" is
1320
- // never claimed merely because a reason was stored.
1321
- const last = this.history.at(-1);
1322
- if (last !== null && last !== undefined) last.rejectionFeedback = feedback;
1323
- pending.rejectionFeedback = feedback;
1324
- }
1325
- const resolvePromise = pending.resolve;
1326
- pending.resolve = null;
1327
- if (typeof resolvePromise === 'function') resolvePromise(pending.settledOutcome);
1328
- if (this.pending === pending) this.pending = null;
1329
- try {
1330
- this.onSettled?.(this.history.at(-1));
1331
- } catch (error) {
1332
- this.logger?.warn?.('dsh-delegate: permission observer failed', String(error?.code ?? ''));
1333
- }
1334
- return true;
1335
- }
1336
-
1337
- /**
1338
- * Send the commander's REJECTION REASON back into the same Agent.
1339
- *
1340
- * The native approval protocol cannot carry prose: `ApprovalService.request()`
1341
- * resolves one of four closed outcomes, so the reason a commander typed never reached
1342
- * the worker — it was recorded in history and the tool received a bare `rejected`.
1343
- * The acceptance report is exactly that: the worker could not know it should narrow
1344
- * its request and ask again.
1345
- *
1346
- * The real channel for prose is the Agent's own inbox. The native approval service
1347
- * itself uses it for its policy notices
1348
- * (`agent.inject(createUserMessage({ content, source }))`), and `dsh-user-questions`
1349
- * uses the same call to steer a late answer. So this method injects ONE user message
1350
- * describing the rejection.
1351
- *
1352
- * What the message says, and what it must never be read as:
1353
- *
1354
- * * WHY this one call was rejected, quoted from the decision;
1355
- * * that the rejection STANDS — the call is not approved, and nothing was widened;
1356
- * * that this is NOT a new authorization and grants nothing by itself;
1357
- * * what to do next: rewrite the operation to fit and request approval again.
1358
- *
1359
- * The reason is redacted and bounded before it is sent, by the same rules the stored
1360
- * evidence uses. A send failure is returned as a bounded outcome and NEVER changes the
1361
- * settlement: `rejected` already happened, and reporting a failed notice as success,
1362
- * or un-rejecting the call because the notice failed, would both be lies.
1363
- *
1364
- * Delivery is tracked per request id so a repeated reject, a retried decision or a
1365
- * plugin restart cannot deliver the same feedback twice. Only an ACTUAL injection on
1366
- * the bound Agent counts as delivered; anything else stays `not-sent` and is reported.
1367
- * @param {object} pending - the request that was just settled.
1368
- * @param {string} reason - the commander's decision reason (already redacted and bounded).
1369
- * @returns {{ delivered: boolean, requestId: string, callId: string | null,
1370
- * messageId: string | null, reason: string }} the outcome, never a rejection.
1371
- */
1372
- deliverRejectionFeedback(pending, reason) {
1373
- const requestId = typeof pending?.requestId === 'string' ? pending.requestId : '';
1374
- // One delivery per request, ever. A duplicate reject and a restart both land here.
1375
- if (this.feedbackSent.has(requestId)) {
1376
- return {
1377
- delivered: false,
1378
- requestId,
1379
- callId: typeof pending?.callId === 'string' ? pending.callId : null,
1380
- messageId: this.feedbackSent.get(requestId),
1381
- reason: 'already-delivered',
1382
- };
1383
- }
1384
- const agent = this.agent;
1385
- const sessionRefusal = this.liveBindingRefusal();
1386
- if (agent === null || typeof agent?.inject !== 'function' || sessionRefusal !== null) {
1387
- return {
1388
- delivered: false,
1389
- requestId,
1390
- callId: typeof pending?.callId === 'string' ? pending.callId : null,
1391
- messageId: null,
1392
- reason: sessionRefusal ?? 'no-injectable-agent',
1393
- };
1394
- }
1395
- const text = rejectionFeedbackText(pending, reason);
1396
- let message;
1397
- try {
1398
- message = this.createMessage(text);
1399
- } catch (error) {
1400
- return {
1401
- delivered: false,
1402
- requestId,
1403
- callId: typeof pending?.callId === 'string' ? pending.callId : null,
1404
- messageId: null,
1405
- reason: typeof error?.code === 'string' ? error.code : 'message-unavailable',
1406
- };
1407
- }
1408
- try {
1409
- agent.inject(message);
1410
- } catch (error) {
1411
- // The rejection is already in force. This only reports that the NOTE did not reach
1412
- // the worker, which is a different, smaller fact than the decision itself.
1413
- this.logger?.warn?.('dsh-delegate: the rejection reason could not be delivered', String(error?.code ?? ''));
1414
- return {
1415
- delivered: false,
1416
- requestId,
1417
- callId: typeof pending?.callId === 'string' ? pending.callId : null,
1418
- messageId: null,
1419
- reason: 'inject-failed',
1420
- };
1421
- }
1422
- const messageId = typeof message?.id === 'string' ? message.id : null;
1423
- this.feedbackSent.set(requestId, messageId);
1424
- return {
1425
- delivered: true,
1426
- requestId,
1427
- callId: typeof pending?.callId === 'string' ? pending.callId : null,
1428
- messageId,
1429
- reason: 'delivered',
1430
- // The record states what was said, so "feedback happened" is auditable rather than
1431
- // claimed: the exact text is the evidence.
1432
- text,
1433
- };
1434
- }
1435
-
1436
- /**
1437
- * Clear the pending slot of an answered request.
1438
- * @param {object} pending - pending record.
1439
- * @returns {void}
1440
- */
1441
- clearPending(pending) {
1442
- if (this.pending === pending) this.pending = null;
1443
- }
1444
-
1445
- /**
1446
- * Record a request that was refused because its identity could not be bound.
1447
- *
1448
- * This is evidence, not a decision: nothing was granted, and the record says
1449
- * which check failed so an operator can act on the tool surface instead of
1450
- * guessing why a worker was told "no approval channel".
1451
- * @param {object} request - native approval request.
1452
- * @param {string} reason - fixed {@link PERMISSION_REASONS} value.
1453
- * @returns {void}
1454
- */
1455
- recordRejectedBinding(request, reason) {
1456
- this.sequence += 1;
1457
- const createdAt = this.now();
1458
- const entry = {
1459
- requestId: `permission-${this.taskId}-${this.sequence}`,
1460
- taskId: this.taskId,
1461
- connectionId: this.connectionId,
1462
- sessionId: this.sessionId,
1463
- toolName: this.boundText(request?.toolName, 120),
1464
- callId: this.boundText(request?.callId, 200),
1465
- turn: null,
1466
- step: null,
1467
- fingerprint: null,
1468
- arguments: null,
1469
- argumentKeys: [],
1470
- claimedReason: this.boundText(request?.reason, PERMISSION_BOUNDS.reasonChars),
1471
- requestedAccess: { kind: 'unbound', mode: null },
1472
- createdAt,
1473
- deadlineAt: createdAt,
1474
- state: PERMISSION_STATES.unavailable,
1475
- decision: null,
1476
- decidedAt: createdAt,
1477
- decidedBy: 'binding',
1478
- decisionReason: reason ?? PERMISSION_REASONS.unbound,
1479
- settledOutcome: 'rejected',
1480
- bindingReason: reason ?? PERMISSION_REASONS.unbound,
1481
- };
1482
- this.history.push(entry);
1483
- if (this.history.length > PermissionBridge.HISTORY_BOUND) this.history.shift();
1484
- try {
1485
- this.onSettled?.(entry);
1486
- } catch {
1487
- // The refusal is already recorded; an observer throw cannot change it.
1488
- }
1489
- }
1490
-
1491
- /**
1492
- * Stop the outstanding request, if any, and restore the policy.
1493
- *
1494
- * The outcome is chosen by the caller because the CAUSE differs and the worker
1495
- * must see the difference: a cancel/stop/switch-off withdraws the question
1496
- * (`cancelled`), while disposal makes the bridge unusable (`unavailable`).
1497
- * Either way the paused call resumes immediately with a refusal, the request's
1498
- * timer and listener are released, and no later decision can apply.
1499
- * @param {string} state - `cancelled` or `unavailable`.
1500
- * @param {string} [reason] - fixed reason text.
1501
- * @returns {boolean} true when a pending request was settled.
1502
- */
1503
- stop(state = PERMISSION_STATES.cancelled, reason = PERMISSION_REASONS.stop) {
1504
- const outcome = state === PERMISSION_STATES.unavailable ? 'unavailable' : 'cancelled';
1505
- const pending = this.pending;
1506
- if (pending === null) {
1507
- return false;
1508
- }
1509
- return this.settle(pending, state, outcome, { reason, decidedBy: 'stop' });
1510
- }
1511
-
1512
- /**
1513
- * Disarm the bridge permanently.
1514
- *
1515
- * Disposal settles an outstanding request `unavailable` (no decision can be
1516
- * applied to a bridge that no longer exists), clears `armed` so no policy writer
1517
- * may keep `ask` installed, and drops the bound Agent so a disposed bridge can
1518
- * never answer a request that a live Session still holds a reference to.
1519
- * @returns {void}
1520
- */
1521
- dispose() {
1522
- if (this.disposed) return;
1523
- this.stop(PERMISSION_STATES.unavailable, PERMISSION_REASONS.disposed);
1524
- this.armed = false;
1525
- this.disposed = true;
1526
- this.agent = null;
1527
- this.session = null;
1528
- }
1529
-
1530
- /**
1531
- * The public, bounded projection of one request.
1532
- *
1533
- * Everything here is either an identifier the caller already holds, a redacted
1534
- * argument projection, or a timestamp. The exact fingerprint IS published,
1535
- * because the decision tool accepts it back to bind a decision to exactly this
1536
- * operation; it is a digest of the arguments, not the arguments.
1537
- * @param {object} pending - pending or settled record.
1538
- * @returns {object} redacted view.
1539
- */
1540
- publicView(pending) {
1541
- return {
1542
- requestId: pending.requestId,
1543
- taskId: pending.taskId,
1544
- // Stated, not implied: the commander is told which conversation and which
1545
- // tool call is paused, so the decision is about an operation it can name.
1546
- sessionId: pending.sessionId,
1547
- toolName: pending.toolName,
1548
- callId: pending.callId,
1549
- turn: pending.turn,
1550
- step: pending.step,
1551
- tool: { name: pending.toolName, callId: pending.callId },
1552
- state: pending.state,
1553
- // The asker's own one-line claim, kept apart from the operation itself.
1554
- reason: pending.claimedReason ?? null,
1555
- reasonSource: 'asker-claim',
1556
- requestedAccess: pending.requestedAccess,
1557
- argumentKeys: pending.argumentKeys,
1558
- arguments: pending.arguments,
1559
- argumentsRedacted: true,
1560
- // Completeness, published so a reader never has to infer it from a trailing
1561
- // marker in the text: an allow is refused when this is not `complete`.
1562
- completeness: pending.completeness ?? PERMISSION_COMPLETENESS.complete,
1563
- argumentsComplete: pending.argumentsComplete !== false,
1564
- boundsApplied: Array.isArray(pending.boundsApplied) ? [...pending.boundsApplied] : [],
1565
- omitted: pending.omitted ?? { valueChars: 0, keys: 0, depth: 0, items: 0 },
1566
- // Why an allow would be refused, or null. Stated so the commander is not left
1567
- // guessing why `allow-once` came back refused.
1568
- allowBlocked: pending.allowBlocked ?? null,
1569
- fingerprint: pending.fingerprint,
1570
- createdAt: pending.createdAt,
1571
- deadlineAt: pending.deadlineAt,
1572
- decision: pending.decision,
1573
- decidedAt: pending.decidedAt,
1574
- decidedBy: pending.decidedBy,
1575
- decisionReason: pending.decisionReason,
1576
- outcome: pending.settledOutcome,
1577
- // For a settled allow: which checks the grant actually passed.
1578
- ...(pending.verified === undefined || pending.verified === null ? {} : { verified: pending.verified }),
1579
- ...(pending.bindingReason === undefined ? {} : { bindingReason: pending.bindingReason }),
1580
- // The narrow exception, restated on the evidence itself so no reader has to
1581
- // infer it: this is one call, decided once, and nothing was granted beyond it.
1582
- grant: pending.settledOutcome === 'allowed-once'
1583
- ? { kind: 'allowed-once', appliesTo: 'this-call-only', callId: pending.callId, reusable: false }
1584
- : null,
1585
- standingModeUnchanged: true,
1586
- };
1587
- }
1588
-
1589
- /** The pending request's public view, or `null`. */
1590
- pendingView() {
1591
- return this.pending === null ? null : this.publicView(this.pending);
1592
- }
1593
-
1594
- /** Copy of the settled evidence trail, newest last. */
1595
- historyView() {
1596
- return this.history.map((entry) => ({ ...entry }));
1597
- }
1598
-
1599
- /**
1600
- * Redact and bound one free-form string.
1601
- * @param {unknown} value - untrusted text.
1602
- * @param {number} cap - character bound.
1603
- * @returns {string | null} bounded redacted text, or null when empty.
1604
- */
1605
- boundText(value, cap) {
1606
- if (typeof value !== 'string' || value === '') return null;
1607
- const text = this.redact(value);
1608
- return text.length > cap ? `${text.slice(0, cap)}…` : text;
1609
- }
1610
- }
1611
-
1612
- /**
1613
- * Whether a value is an outcome this plugin may act on.
1614
- * @param {unknown} value - candidate outcome.
1615
- * @returns {boolean} true for the closed vocabulary.
1616
- */
1617
- export function isApprovalOutcome(value) {
1618
- return typeof value === 'string' && APPROVAL_OUTCOMES.includes(value);
1619
- }
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
+ * The two text caps are set from the EVIDENCE, not from a round number. An allow is
203
+ * only possible on a complete operation, so any cap that fires turns a legitimate
204
+ * one-line request into an unapprovable one. A Windows absolute path plus a
205
+ * read-back command is ~400 characters on its own — that size was refused by an
206
+ * earlier `argumentValueChars: 400`, and a real platform refusal was the result. The
207
+ * caps below hold roughly an 8 KiB command field and a 16 KiB argument object: far
208
+ * more than any single tool call this surface reviews, and still a hard, stated
209
+ * limit — a value past it is `truncated`, `argumentsComplete: false`, and cannot be
210
+ * allowed (see {@link PermissionBridge#allowRefusalReason}). The protection the
211
+ * caps provide is the same as before; only the point where a normal request stops
212
+ * fitting moved.
213
+ */
214
+ export const PERMISSION_BOUNDS = Object.freeze({
215
+ /** Maximum characters retained for the redacted JSON arguments. */
216
+ argumentsChars: 16_384,
217
+ /** Maximum characters retained for any single redacted argument scalar. */
218
+ argumentValueChars: 8_192,
219
+ /** Maximum depth retained when projecting arguments. */
220
+ argumentDepth: 6,
221
+ /** Maximum argument keys retained per object. */
222
+ argumentKeys: 24,
223
+ /** Maximum characters retained for the asker's own claimed reason. */
224
+ reasonChars: 600,
225
+ /** Maximum characters retained for a decision reason. */
226
+ decisionReasonChars: 600,
227
+ });
228
+
229
+ /**
230
+ * The redaction this module applies to every published string.
231
+ *
232
+ * Injected rather than imported so the module stays a leaf with one dependency;
233
+ * the plugin passes `redactText` from `config/redact.js` (the same redaction the
234
+ * MCP result path applies), and a test may pass its own.
235
+ */
236
+ const IDENTITY_REDACTION = /\b(sk|pk|ak)-[A-Za-z0-9_-]{16,}\b/g;
237
+
238
+ /**
239
+ * The default redaction: credential-shaped substrings.
240
+ *
241
+ * `config/redact.js`'s {@link redactText} is what the plugin injects, and this
242
+ * fallback deliberately mirrors its three patterns (bearer tokens, key-like
243
+ * secrets, and `NAME=value` assignments) so a bridge constructed without an
244
+ * injected redaction is not WEAKER than the production one. The module still stays
245
+ * a leaf: this is a local copy of the shape, not an import of the config layer.
246
+ * @param {string} text - untrusted text.
247
+ * @returns {string} text with credential-shaped substrings replaced.
248
+ */
249
+ function defaultRedact(text) {
250
+ if (typeof text !== 'string' || text === '') return '';
251
+ return text
252
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/giu, 'Bearer ••••••••')
253
+ .replace(IDENTITY_REDACTION, '••••••••')
254
+ .replace(
255
+ /\b([A-Za-z0-9_]*(?:API_?KEY|SECRET|TOKEN|PASSWORD)[A-Za-z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/giu,
256
+ (_match, name) => `${name}=••••••••`,
257
+ );
258
+ }
259
+
260
+ /**
261
+ * Keys that may never be assigned through `object[key] = value`.
262
+ *
263
+ * `out['__proto__'] = x` on an ordinary object does not create an own property: it
264
+ * invokes the prototype setter, so the key silently disappears. Two different JSON
265
+ * objects — one carrying `__proto__` and one not — then hash and project
266
+ * identically, which is a real collision between two different operations. Every
267
+ * assignment below therefore goes through {@link setOwn}, which defines an own
268
+ * data property instead.
269
+ */
270
+ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
271
+
272
+ /**
273
+ * Assign an own enumerable data property, including for `__proto__`.
274
+ * @param {object} target - object to write into (created with a null prototype).
275
+ * @param {string} key - property name.
276
+ * @param {unknown} value - property value.
277
+ * @returns {void}
278
+ */
279
+ function setOwn(target, key, value) {
280
+ Object.defineProperty(target, key, {
281
+ value,
282
+ enumerable: true,
283
+ configurable: true,
284
+ writable: true,
285
+ });
286
+ }
287
+
288
+ /**
289
+ * A projection result: the bounded/redacted value AND whether it is complete.
290
+ *
291
+ * Completeness is a first-class fact, not an inference. A truncated value can hide
292
+ * the part of a command that matters (the tail of `bash.command`, the body of a
293
+ * `write`), so a caller must be able to refuse an allow decision on evidence it
294
+ * could not see in full.
295
+ */
296
+ export const PERMISSION_COMPLETENESS = Object.freeze({
297
+ complete: 'complete',
298
+ truncated: 'truncated',
299
+ unbounded: 'unbounded',
300
+ });
301
+
302
+ /**
303
+ * Create a projection context that tracks whether any bound was applied.
304
+ * @param {boolean} redactKeys - whether key names are redacted too.
305
+ * @returns {{ cuts: string[], valueChars: number, keys: number } } mutable counters.
306
+ */
307
+ function newProjectionState() {
308
+ return { cuts: [], valueCuts: 0, keyCuts: 0, depthCuts: 0, itemCuts: 0 };
309
+ }
310
+
311
+ /**
312
+ * Mark one bound as applied, so its kind can be reported.
313
+ * @param {object} state - projection counters.
314
+ * @param {string} cut - cut kind.
315
+ * @param {number} [amount] - how much was dropped.
316
+ * @returns {void}
317
+ */
318
+ function noteCut(state, cut, amount = 1) {
319
+ if (cut === 'value') state.valueCuts += amount;
320
+ else if (cut === 'key') state.keyCuts += amount;
321
+ else if (cut === 'depth') state.depthCuts += amount;
322
+ else if (cut === 'item') state.itemCuts += amount;
323
+ if (state.cuts.length < 8 && !state.cuts.includes(cut)) state.cuts.push(cut);
324
+ }
325
+
326
+ /**
327
+ * Whether a value is a credential-bearing KEY name.
328
+ *
329
+ * This is the key-aware half of redaction, and it is why the projection cannot rely
330
+ * on scalar patterns alone: `{"apiKey":"…"}` carries a secret in its VALUE with no
331
+ * credential-shaped text in it at all. The rule is deliberately the same predicate
332
+ * the redaction module uses for stored documents
333
+ * ({@link import('../config/redact.js').isSecretKey}), injected here through
334
+ * `isSecretKey` so there is exactly one definition of "this key names a secret".
335
+ * @param {string} key - object key.
336
+ * @param {(key: string) => boolean} isSecretKey - the injected predicate.
337
+ * @returns {boolean} true when the value behind this key must be masked.
338
+ */
339
+ function secretKeyName(key, isSecretKey) {
340
+ if (typeof isSecretKey === 'function' && isSecretKey(key) === true) return true;
341
+ // A defence-in-depth fallback for the harness-free default: the same shape the
342
+ // configuration module matches, so a module imported without it is not weaker.
343
+ return typeof key === 'string' && /(api[_-]?key|apikey|secret|token|password|passwd|credential[_-]?value|authorization)/iu.test(key);
344
+ }
345
+
346
+ /**
347
+ * Project one JSON value into a bounded, redacted, JSON-safe copy.
348
+ *
349
+ * Three rules, and every one of them is load-bearing:
350
+ *
351
+ * 1. **Key-aware redaction.** A key whose NAME says it holds a credential has its
352
+ * whole value masked, whatever the value looks like; every remaining string is
353
+ * also passed through the injected {@link redactText}. Scalar patterns alone
354
+ * would publish `{"apiKey":"some-secret"}` verbatim.
355
+ * 2. **Proto-safe keys.** Assignments go through {@link setOwn}, so a JSON key
356
+ * named `__proto__` becomes a real own property instead of vanishing through the
357
+ * prototype setter (R9's collision).
358
+ * 3. **Explicit completeness.** Every bound that fires is COUNTED, so the caller
359
+ * can tell a fully-projected operation from a shortened one and refuse an allow
360
+ * decision on evidence it could not review in full.
361
+ * @param {unknown} value - parsed argument value.
362
+ * @param {object} options - `redact`, `isSecretKey`, `state`, `depth`.
363
+ * @returns {unknown} bounded projection.
364
+ */
365
+ function projectValue(value, options) {
366
+ const redact = typeof options.redact === 'function' ? options.redact : defaultRedact;
367
+ const isSecretKey = options.isSecretKey;
368
+ const state = options.state ?? newProjectionState();
369
+ const depth = options.depth ?? 0;
370
+ const cap = PERMISSION_BOUNDS.argumentValueChars;
371
+ if (value === null || typeof value === 'undefined') return null;
372
+ if (typeof value === 'string') {
373
+ const text = redact(value);
374
+ if (text.length > cap) {
375
+ noteCut(state, 'value', text.length - cap);
376
+ return `${text.slice(0, cap)}…[+${text.length - cap} chars]`;
377
+ }
378
+ return text;
379
+ }
380
+ if (typeof value === 'number') return Number.isFinite(value) ? value : String(value);
381
+ if (typeof value === 'boolean') return value;
382
+ if (depth >= PERMISSION_BOUNDS.argumentDepth) {
383
+ noteCut(state, 'depth');
384
+ return '[depth limit]';
385
+ }
386
+ if (Array.isArray(value)) {
387
+ const keep = value.slice(0, PERMISSION_BOUNDS.argumentKeys);
388
+ if (value.length > keep.length) noteCut(state, 'item', value.length - keep.length);
389
+ const projected = keep.map((entry) => projectValue(entry, { redact, isSecretKey, state, depth: depth + 1 }));
390
+ if (value.length > keep.length) projected.push(`[+${value.length - keep.length} more items]`);
391
+ return projected;
392
+ }
393
+ if (typeof value === 'object') {
394
+ // A null prototype keeps the projection itself free of inherited keys; every
395
+ // assignment still goes through `setOwn` so `__proto__` survives as data.
396
+ const out = Object.create(null);
397
+ const entries = Object.entries(value);
398
+ if (entries.length > PERMISSION_BOUNDS.argumentKeys) {
399
+ noteCut(state, 'key', entries.length - PERMISSION_BOUNDS.argumentKeys);
400
+ }
401
+ for (const [key, entry] of entries.slice(0, PERMISSION_BOUNDS.argumentKeys)) {
402
+ const safeKey = redact(key);
403
+ if (secretKeyName(key, isSecretKey)) {
404
+ // The whole value is masked because its KEY says it is a credential. The key
405
+ // name stays, so an operator can still see WHICH argument was hidden.
406
+ setOwn(out, safeKey, '••••••••');
407
+ // A masked credential is not a truncation: the operation is fully described
408
+ // by "this credential is set".
409
+ continue;
410
+ }
411
+ setOwn(out, safeKey, projectValue(entry, { redact, isSecretKey, state, depth: depth + 1 }));
412
+ }
413
+ if (entries.length > PERMISSION_BOUNDS.argumentKeys) {
414
+ setOwn(out, '…', `[+${entries.length - PERMISSION_BOUNDS.argumentKeys} more keys]`);
415
+ }
416
+ return out;
417
+ }
418
+ return '[not representable]';
419
+ }
420
+
421
+ /**
422
+ * Serialize a projected value to bounded JSON text.
423
+ *
424
+ * The whole-value cap is applied only when the projection still does not fit, and
425
+ * it always REPORTS that it fired (through {@link boundedJsonText.exceeded}) so a
426
+ * caller can refuse an allow decision rather than approve a tail it never saw.
427
+ * @param {unknown} projected - bounded projection.
428
+ * @returns {{ text: string, exceeded: boolean }} JSON text and whether the cap fired.
429
+ */
430
+ function boundedJsonText(projected) {
431
+ let text;
432
+ try {
433
+ text = JSON.stringify(projected);
434
+ } catch {
435
+ return { text: '[unserializable]', exceeded: true };
436
+ }
437
+ if (typeof text !== 'string') return { text: '[unserializable]', exceeded: true };
438
+ const cap = PERMISSION_BOUNDS.argumentsChars;
439
+ if (text.length > cap) {
440
+ return { text: `${text.slice(0, cap)}…[+${text.length - cap} chars omitted]`, exceeded: true };
441
+ }
442
+ return { text, exceeded: false };
443
+ }
444
+
445
+ /**
446
+ * A stable, proto-safe canonical JSON text of an exact value.
447
+ *
448
+ * `JSON.stringify` is not usable on its own here: it uses ordinary assignment
449
+ * internally for the value it returns, but the real problem is the REPLACER an
450
+ * earlier version used — `out[key] = value` silently drops a key named
451
+ * `__proto__`, so `{"__proto__":{"a":1}}` and `{}` produced the same digest and two
452
+ * different operations could be decided by one fingerprint.
453
+ *
454
+ * This serializer builds the text directly: keys are sorted for stability (so key
455
+ * order is not part of the operation), every key is escaped as a JSON string rather
456
+ * than assigned as a property, and nesting is explicit. Two objects are therefore
457
+ * equal here only when they have the same keys and the same values.
458
+ * @param {unknown} value - JSON-compatible value.
459
+ * @returns {string} canonical JSON text.
460
+ */
461
+ export function canonicalJson(value) {
462
+ if (value === null) return 'null';
463
+ if (typeof value === 'string') return JSON.stringify(value);
464
+ if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : 'null';
465
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
466
+ if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(',')}]`;
467
+ if (typeof value === 'object') {
468
+ // `Object.keys` reports own enumerable keys only, including one named
469
+ // `__proto__` created by `JSON.parse` (which defines it as data, not accessor).
470
+ const keys = Object.keys(value).sort();
471
+ const parts = [];
472
+ for (const key of keys) {
473
+ parts.push(`${JSON.stringify(key)}:${canonicalJson(value[key])}`);
474
+ }
475
+ return `{${parts.join(',')}}`;
476
+ }
477
+ return 'null';
478
+ }
479
+
480
+ /**
481
+ * A stable fingerprint of an exact value.
482
+ *
483
+ * The digest is over {@link canonicalJson}, so it depends on the operation and not
484
+ * on key order, and it is a digest rather than the value so the private binding
485
+ * never has to keep (or publish) a second copy of the arguments.
486
+ * @param {unknown} value - JSON-compatible value.
487
+ * @returns {string} `sha256:<hex>` digest.
488
+ */
489
+ export function fingerprintOf(value) {
490
+ return `sha256:${createHash('sha256').update(canonicalJson(value), 'utf8').digest('hex')}`;
491
+ }
492
+
493
+ /**
494
+ * Read the real tool call one approval request is about, from the Session log.
495
+ *
496
+ * The native loop commits `tool/call` before the tool executes, so the arguments
497
+ * are already in the log when the tool asks. The match is:
498
+ *
499
+ * * the event type is `tool/call`;
500
+ * * its `callId` equals the request's `callId` EXACTLY (a missing `callId` is a
501
+ * refusal, not a search);
502
+ * * its `name` equals the request's `toolName` (a mismatch is a refusal: the
503
+ * request and the log disagree about what is being decided);
504
+ * * the newest such event wins if an id were ever repeated (the live one).
505
+ *
506
+ * A Session that exposes no readable log, a log whose reads throw, and a missing
507
+ * match are all refusals with their own bounded reason.
508
+ * @param {object} session - the asking agent's Session.
509
+ * @param {object} request - native approval request (`callId`, `toolName`).
510
+ * @returns {{ ok: true, call: { callId: string, name: string, argumentsText: string, turn: number|null, step: number|null, seq: number|null } }
511
+ * | { ok: false, reason: string }} the located call, or a bounded refusal.
512
+ */
513
+ export function locateToolCall(session, request) {
514
+ const callId = request?.callId;
515
+ if (typeof callId !== 'string' || callId === '') return { ok: false, reason: PERMISSION_REASONS.noCallId };
516
+ if (session === null || typeof session !== 'object') return { ok: false, reason: PERMISSION_REASONS.noSession };
517
+ const seq = typeof session.seq === 'number' && Number.isInteger(session.seq) ? session.seq : null;
518
+ if (seq === null || typeof session.eventAt !== 'function') return { ok: false, reason: PERMISSION_REASONS.noSession };
519
+ const toolName = typeof request?.toolName === 'string' ? request.toolName : null;
520
+ let found = null;
521
+ for (let index = seq - 1; index >= 0; index -= 1) {
522
+ let event;
523
+ try {
524
+ event = session.eventAt(index);
525
+ } catch {
526
+ return { ok: false, reason: PERMISSION_REASONS.callNotFound };
527
+ }
528
+ if (event === null || typeof event !== 'object' || event.type !== 'tool/call') continue;
529
+ const data = event.data ?? {};
530
+ if (data.callId !== callId) continue;
531
+ found = { event, data, index };
532
+ break;
533
+ }
534
+ if (found === null) return { ok: false, reason: PERMISSION_REASONS.callNotFound };
535
+ const name = typeof found.data.name === 'string' ? found.data.name : null;
536
+ if (toolName !== null && name !== toolName) return { ok: false, reason: PERMISSION_REASONS.nameMismatch };
537
+ const argumentsText = typeof found.data.arguments === 'string' ? found.data.arguments : null;
538
+ if (argumentsText === null) return { ok: false, reason: PERMISSION_REASONS.argumentsUnusable };
539
+ return {
540
+ ok: true,
541
+ call: {
542
+ callId,
543
+ name: name ?? toolName ?? null,
544
+ argumentsText,
545
+ turn: Number.isInteger(found.data.turn) ? found.data.turn : null,
546
+ step: Number.isInteger(found.data.step) ? found.data.step : null,
547
+ seq: found.index,
548
+ },
549
+ };
550
+ }
551
+
552
+ /**
553
+ * Whether the Session log is inside an open turn at one offset.
554
+ *
555
+ * This mirrors the native check `ApprovalService.request()` performs before it will
556
+ * answer at all (`hasOpenTurn` in the legacy service, the `turnOpen` projection in
557
+ * the modern one): the last `turn/start`/`turn/end` before the offset decides. It is
558
+ * re-used here because a decision re-verifies the operation at decision time, and a
559
+ * call whose turn has closed is not a call an allow can still apply to.
560
+ * @param {object} session - Session with `eventAt`.
561
+ * @param {number} seq - the tool call's offset.
562
+ * @returns {boolean | null} true/false, or null when the log cannot be read.
563
+ */
564
+ export function turnOpenAt(session, seq) {
565
+ return openTurnAt(session, seq) !== null;
566
+ }
567
+
568
+ /**
569
+ * The turn NUMBER that is open at the CURRENT tail of the log, or `null`.
570
+ *
571
+ * `turnOpenAt` answers "is anything open now"; this answers "WHICH turn is open
572
+ * now". The difference matters: a request asked inside turn 2, then closed and a
573
+ * turn 3 opened, is still "a turn is open" — but it is not the turn that asked. The
574
+ * live-binding check compares this number against the one recorded when the request
575
+ * was created, which is what refuses a close-then-reopen.
576
+ *
577
+ * The scan starts at the END of the log (the live tail) and uses each `turn/start`
578
+ * event's own `turn` field when present, falling back to a running counter so a log
579
+ * that omits the field is still distinguishable across turns.
580
+ * @param {object} session - Session with `eventAt`.
581
+ * @param {number} [fromSeq] - lowest offset to scan back to (the call's offset).
582
+ * @returns {number | null} the open turn number, or null when none is open or the log is unreadable.
583
+ */
584
+ export function openTurnAt(session, fromSeq) {
585
+ if (session === null || typeof session !== 'object' || typeof session.eventAt !== 'function') return null;
586
+ const total = typeof session.seq === 'number' && Number.isInteger(session.seq) ? session.seq : null;
587
+ if (total === null) return null;
588
+ const floor = typeof fromSeq === 'number' && Number.isInteger(fromSeq) && fromSeq >= 0 ? fromSeq : 0;
589
+ try {
590
+ for (let index = total - 1; index >= floor; index -= 1) {
591
+ const event = session.eventAt(index);
592
+ if (event === null || event === undefined || typeof event !== 'object') continue;
593
+ if (event.type === 'turn/end') return null;
594
+ if (event.type !== 'turn/start') continue;
595
+ const declared = event.data?.turn;
596
+ if (typeof declared === 'number' && Number.isInteger(declared)) return declared;
597
+ // No field: identify the turn by its POSITION, which is still a stable and
598
+ // comparable identity for the same log. Negative so it can never be mistaken
599
+ // for a real turn number.
600
+ return -1 - index;
601
+ }
602
+ } catch {
603
+ return null;
604
+ }
605
+ return null;
606
+ }
607
+
608
+ /**
609
+ * The text sent back into the worker after its call was rejected.
610
+ *
611
+ * It is written for the MODEL, not for a log, and every sentence is load-bearing:
612
+ *
613
+ * * the decision is final — the call was rejected and stays rejected;
614
+ * * nothing was widened — not the sandbox, not the grant, not the mode;
615
+ * * the note is not an authorization — a later attempt needs its own approval;
616
+ * * what to do: rewrite the operation to fit the stated reason and ask again.
617
+ *
618
+ * The reason is already redacted and bounded by the caller, so this function only
619
+ * composes. The operation is named by tool and call id so the worker can tell WHICH
620
+ * call was refused when several are in flight.
621
+ * @param {object} pending - the settled request.
622
+ * @param {string} reason - the commander's reason, redacted and bounded.
623
+ * @returns {string} the message body.
624
+ */
625
+ export function rejectionFeedbackText(pending, reason) {
626
+ const tool = typeof pending?.toolName === 'string' && pending.toolName !== '' ? pending.toolName : 'the requested tool call';
627
+ const callId = typeof pending?.callId === 'string' && pending.callId !== '' ? pending.callId : 'unknown';
628
+ const requestId = typeof pending?.requestId === 'string' && pending.requestId !== '' ? pending.requestId : 'unknown';
629
+ const taskId = typeof pending?.taskId === 'string' && pending.taskId !== '' ? pending.taskId : 'unknown';
630
+ const stated = typeof reason === 'string' && reason.trim() !== ''
631
+ ? reason.trim()
632
+ : 'no reason was given';
633
+ return [
634
+ `The commander REJECTED your ${tool} call (task ${taskId}, request ${requestId}, call id ${callId}).`,
635
+ `Reason for rejecting this one operation: ${stated}`,
636
+ 'The rejection stands: this call was not approved and will not run.',
637
+ 'Nothing was granted or widened. Sandbox permissions, the delegation switch, the session policy and your standing sandbox mode are unchanged.',
638
+ 'This note is NOT a new authorization and grants nothing by itself. If you still need the operation, change it to fit the reason above and request approval again; the new request will be decided on its own.',
639
+ ].join(' ');
640
+ }
641
+
642
+ /**
643
+ * The message shape an Agent's inbox accepts, built without the native LLM package.
644
+ *
645
+ * `agent.inject()` takes a user message object; the native helper is `createUserMessage`
646
+ * from `@deepseek-ai/dsh-llm`, which this module deliberately does not import (the stdio
647
+ * executable links it). This default therefore produces the same minimum shape, and the
648
+ * plugin's own composition injects the REAL factory so production never depends on it.
649
+ *
650
+ * The source kind is `'user-approval'` — the value the native approval service already
651
+ * uses for its own policy notices — so the message is a recognised producer's message, not
652
+ * an invented source. Nothing here claims to be a user instruction.
653
+ * @param {string} text - message body.
654
+ * @returns {{ role: 'user', content: { type: 'text', text: string }[], source: { kind: string } }} message.
655
+ */
656
+ export function defaultUserMessage(text) {
657
+ return {
658
+ role: 'user',
659
+ content: [{ type: 'text', text }],
660
+ source: { kind: 'user-approval' },
661
+ };
662
+ }
663
+
664
+ /**
665
+ * The permission bridge for ONE delegated run.
666
+ *
667
+ * One broker per worker run. It is written in the run's own scope, armed before
668
+ * the prompt is delivered and disposed when the run ends, and it answers only
669
+ * requests that name the Agent it was armed for. A request whose identity cannot
670
+ * be established is answered from the fail-closed vocabulary — never allowed.
671
+ */
672
+ export class PermissionBridge {
673
+ /**
674
+ * @param {object} options - `taskId`, `connectionId`, `sessionId`, optional
675
+ * `timeoutMs` (bounded), optional `now`, optional `redact`, optional
676
+ * `isSecretKey` (the key-aware redaction predicate), optional `onPending`,
677
+ * optional `onSettled`, optional `logger`.
678
+ */
679
+ constructor(options) {
680
+ if (typeof options?.taskId !== 'string' || options.taskId === '') {
681
+ throw new TypeError('PermissionBridge needs the taskId it belongs to');
682
+ }
683
+ this.taskId = options.taskId;
684
+ this.connectionId = typeof options.connectionId === 'string' ? options.connectionId : null;
685
+ this.sessionId = typeof options.sessionId === 'string' ? options.sessionId : null;
686
+ this.redact = typeof options.redact === 'function' ? options.redact : defaultRedact;
687
+ // The key-aware half of redaction. Injected so this module and the stored-document
688
+ // redaction agree on ONE definition of "this key names a secret"; the fallback
689
+ // above keeps a harness-free import from being weaker than the plugin.
690
+ this.isSecretKey = typeof options.isSecretKey === 'function' ? options.isSecretKey : null;
691
+ this.now = typeof options.now === 'function' ? options.now : () => Date.now();
692
+ const configured = Number(options.timeoutMs);
693
+ this.timeoutMs = Number.isFinite(configured) && configured > 0
694
+ ? Math.min(configured, PERMISSION_MAX_TIMEOUT_MS)
695
+ : PERMISSION_DEFAULT_TIMEOUT_MS;
696
+ this.onPending = typeof options.onPending === 'function' ? options.onPending : null;
697
+ this.onSettled = typeof options.onSettled === 'function' ? options.onSettled : null;
698
+ this.logger = options.logger ?? null;
699
+ // The lifecycle latch. `armed` is what the policy writer reads: only an armed
700
+ // bridge may have `ask` installed for its Session, and `dispose()` clears it
701
+ // before the policy is restored.
702
+ this.armed = false;
703
+ this.disposed = false;
704
+ this.agent = null;
705
+ this.session = null;
706
+ // At most one outstanding request: a single tool call cannot be asked twice,
707
+ // and "one pending request per task" is what makes the commander's decision
708
+ // unambiguous without a second ordering rule.
709
+ this.pending = null;
710
+ // Every settled request, newest last, bounded. This is the evidence trail the
711
+ // task view and the durable history carry; it never holds an argument value
712
+ // that was not redacted at construction time.
713
+ this.history = [];
714
+ this.sequence = 0;
715
+ // The Session identity the bridge was ARMED for, kept separately from
716
+ // `this.session` so a replaced `agent.session` is detectable rather than silently
717
+ // followed (see {@link liveBindingRefusal}).
718
+ this.boundSessionId = null;
719
+ // Request id -> the id of the message that carried its rejection reason. One entry
720
+ // per delivered note, so a repeated reject, a retried decision or a restart cannot
721
+ // deliver the same feedback twice.
722
+ this.feedbackSent = new Map();
723
+ // The message factory. Injected so this module stays free of a hard dependency on the
724
+ // native LLM package (the stdio executable imports this file); the plugin passes the
725
+ // real `createUserMessage`, and the default below builds the same shape.
726
+ this.createMessage = typeof options.createUserMessage === 'function'
727
+ ? options.createUserMessage
728
+ : defaultUserMessage;
729
+ }
730
+
731
+ /** Maximum settled requests retained on one run. */
732
+ static get HISTORY_BOUND() {
733
+ return 8;
734
+ }
735
+
736
+ /**
737
+ * Bind the bridge to the Agent/Session it will answer for.
738
+ *
739
+ * Called from the run's setup step, AFTER the preset is mounted (so the tool
740
+ * surface is the real one) and BEFORE the prompt (so no turn can ask under an
741
+ * unarmed bridge). Re-arming the same run is idempotent; binding a DIFFERENT
742
+ * Agent is a refusal, because a bridge belongs to one conversation.
743
+ * @param {object} agent - the live native Agent the run will drive.
744
+ * @returns {{ taskId: string, sessionId: string }} what was armed.
745
+ * @throws {PermissionError} when the agent is unusable or is not the bound one.
746
+ */
747
+ arm(agent) {
748
+ if (this.disposed) {
749
+ throw new PermissionError(PERMISSION_CODES.unbound, 'the permission bridge was already disposed', {
750
+ reason: PERMISSION_REASONS.disposed,
751
+ });
752
+ }
753
+ const session = agent?.session ?? null;
754
+ const sessionId = typeof session?.id === 'string' ? session.id : (typeof agent?.id === 'string' ? agent.id : null);
755
+ if (session === null || sessionId === null) {
756
+ throw new PermissionError(PERMISSION_CODES.unbound, 'the delegated agent exposes no session to bind approvals to', {
757
+ reason: PERMISSION_REASONS.noSession,
758
+ });
759
+ }
760
+ if (this.agent !== null && this.agent !== agent) {
761
+ throw new PermissionError(PERMISSION_CODES.unbound, 'the permission bridge is already bound to another agent', {
762
+ reason: PERMISSION_REASONS.agentMismatch,
763
+ });
764
+ }
765
+ this.agent = agent;
766
+ this.session = session;
767
+ this.sessionId = this.sessionId ?? sessionId;
768
+ // Pinned at arm time: the exact Session id this bridge answers for.
769
+ this.boundSessionId = sessionId;
770
+ this.armed = true;
771
+ return { taskId: this.taskId, sessionId: this.sessionId };
772
+ }
773
+
774
+ /**
775
+ * Whether this bridge answers for one native approval request.
776
+ *
777
+ * The rule is EXACT identity, and it is deliberately strict in both directions:
778
+ *
779
+ * * the bridge must be armed, bound, and not disposed;
780
+ * * `request.agent` MUST be present — a request with no agent (`null`,
781
+ * `undefined`) is not "probably mine", it is unidentifiable, and answering it
782
+ * would let any caller that forgets to pass an agent be decided by this bridge;
783
+ * * that agent must be the SAME OBJECT the bridge was armed for. The native
784
+ * approval seam passes the live Agent the requesting tool is running for, so
785
+ * object identity is exactly the question "is this my Agent", and it cannot be
786
+ * forged from data;
787
+ * * when the agent exposes a Session id, it must equal the bound one.
788
+ *
789
+ * A request for a different agent in the same process is not this bridge's
790
+ * business: the listener falls through to the next answerer so the ordinary
791
+ * session keeps whatever prompt it actually has.
792
+ * @param {object} request - native approval request.
793
+ * @returns {boolean} true when this bridge owns the request.
794
+ */
795
+ owns(request) {
796
+ if (this.armed !== true || this.disposed === true) return false;
797
+ if (this.agent === null || this.session === null) return false;
798
+ const agent = request?.agent;
799
+ // No agent at all: unidentifiable, so NOT owned. `?? null` here would have made
800
+ // a missing agent match every bridge, which is the defect this check removes.
801
+ if (agent === null || agent === undefined || typeof agent !== 'object') return false;
802
+ if (agent !== this.agent) return false;
803
+ const sessionId = typeof agent?.session?.id === 'string' ? agent.session.id : null;
804
+ if (sessionId !== null && this.sessionId !== null && sessionId !== this.sessionId) return false;
805
+ return true;
806
+ }
807
+
808
+ /**
809
+ * Re-read the bound operation from the live Session and prove it is unchanged.
810
+ *
811
+ * A decision is not taken against the copy captured when the request was created:
812
+ * the native log is read AGAIN at the moment of decision, and the operation must
813
+ * still be there, still be the same record at the same offset, still carry the
814
+ * same tool name, and still carry byte-identical arguments. It must also still be
815
+ * inside an OPEN turn — a call whose turn has already ended is history, and an
816
+ * allow for it would apply to nothing (or, worse, to whatever reuses the id).
817
+ *
818
+ * This is what makes "the session/tool call/argument snapshot is re-verified at
819
+ * decision" a checked fact rather than an assumption.
820
+ * @param {object} pending - pending record, whose `callId`/`callSeq` pin the call.
821
+ * @returns {string | null} a fixed refusal reason, or null when still exact.
822
+ */
823
+ reverifyOperation(pending) {
824
+ const live = this.liveBindingRefusal();
825
+ if (live !== null) return live;
826
+ const seq = pending?.callSeq;
827
+ if (typeof seq !== 'number' || !Number.isInteger(seq) || seq < 0) {
828
+ return PERMISSION_REASONS.noCallSeq;
829
+ }
830
+ let event;
831
+ try {
832
+ event = this.session.eventAt(seq);
833
+ } catch {
834
+ return PERMISSION_REASONS.callMissing;
835
+ }
836
+ if (event === null || event === undefined || typeof event !== 'object' || event.type !== 'tool/call') {
837
+ return PERMISSION_REASONS.callMissing;
838
+ }
839
+ const data = event.data ?? {};
840
+ if (data.callId !== pending.callId) return PERMISSION_REASONS.callChanged;
841
+ // EXACT name equality. The old `typeof data.name === 'string' && …` guard made a
842
+ // REMOVED name pass, so a record whose tool name had been stripped still allowed.
843
+ if (data.name !== pending.toolName) return PERMISSION_REASONS.callChanged;
844
+ // Turn/step identity, compared exactly when the request pinned one.
845
+ if (pending.turn !== null && data.turn !== pending.turn) return PERMISSION_REASONS.callChanged;
846
+ if (pending.step !== null && data.step !== pending.step) return PERMISSION_REASONS.callChanged;
847
+ if (typeof data.arguments !== 'string' || data.arguments !== pending.exactArguments) {
848
+ // A changed argument string at the SAME offset means the record was mutated
849
+ // or the Session was replaced underneath this bridge. Either way the evidence
850
+ // the commander saw is not the operation any more.
851
+ return PERMISSION_REASONS.callChanged;
852
+ }
853
+ // The SAME originating turn must still be the open one at the CURRENT TAIL.
854
+ // Checking only "is some turn open now" would accept a close-then-reopen: the
855
+ // question was asked in turn N, and a decision taken in turn N+1 is not about the
856
+ // same live step. A closed tail (`null`) never equals a recorded turn number.
857
+ if (openTurnAt(this.session) !== pending.turnAtAsk) return PERMISSION_REASONS.turnClosed;
858
+ return null;
859
+ }
860
+
861
+ /**
862
+ * Prove the bridge is still bound to the LIVE Agent and Session it was armed for.
863
+ *
864
+ * The previous check only looked at `this.session`. That misses the case the audit
865
+ * reproduced: while a request is pending, the Agent's `session` is REPLACED, so the
866
+ * bridge keeps reading the old (frozen, still-open-looking) log while the agent
867
+ * actually drives a different conversation. Both the object identity AND the id are
868
+ * compared, because a replaced session with a recycled id is still a different
869
+ * conversation.
870
+ * @returns {string | null} a fixed refusal reason, or null when still bound.
871
+ */
872
+ liveBindingRefusal() {
873
+ const agent = this.agent;
874
+ if (agent === null || agent === undefined) return PERMISSION_REASONS.sessionGone;
875
+ const liveSession = agent.session;
876
+ if (liveSession === null || liveSession === undefined) return PERMISSION_REASONS.sessionGone;
877
+ if (liveSession !== this.session) return PERMISSION_REASONS.sessionGone;
878
+ if (this.boundSessionId !== null && liveSession.id !== this.boundSessionId) {
879
+ return PERMISSION_REASONS.sessionGone;
880
+ }
881
+ if (this.session === null || typeof this.session.eventAt !== 'function') {
882
+ return PERMISSION_REASONS.sessionGone;
883
+ }
884
+ return null;
885
+ }
886
+
887
+ /**
888
+ * Answer one native approval request.
889
+ *
890
+ * The closed outcomes and their causes:
891
+ *
892
+ * * `unavailable` — the bridge is not armed/disposed, the request is not this
893
+ * bridge's, or a request is already outstanding. Fail closed, because
894
+ * "somebody else's question" and "two questions at once" are both states this
895
+ * plugin cannot decide honestly.
896
+ * * `cancelled` — the asking tool withdrew the request (its own signal), or
897
+ * the run stopped while it was pending.
898
+ * * `rejected` — the deadline expired, the request had no call identity, or no
899
+ * `tool/call` matching it could be read. The operation is refused; the
900
+ * diagnostics say which check failed.
901
+ * * `allowed-once` — ONLY a commander decision that matched this exact
902
+ * fingerprint.
903
+ *
904
+ * @param {object} request - `{ agent, toolName, callId?, reason?, signal? }`.
905
+ * @returns {Promise<string>} one of {@link APPROVAL_OUTCOMES}.
906
+ */
907
+ async answer(request) {
908
+ if (this.armed !== true || this.disposed === true) return 'unavailable';
909
+ if (!this.owns(request)) return 'unavailable';
910
+ if (this.pending !== null) {
911
+ this.logger?.warn?.('dsh-delegate: a second approval request arrived while one was pending; refusing it');
912
+ return 'unavailable';
913
+ }
914
+ const signal = request?.signal;
915
+ if (signal?.aborted === true) return 'cancelled';
916
+ const located = locateToolCall(this.session, request);
917
+ if (located.ok !== true) {
918
+ // An unidentifiable request is a refusal, not a silent wait: nobody could
919
+ // bind a decision to it, so it must not occupy the pending slot.
920
+ this.recordRejectedBinding(request, located.reason);
921
+ return 'rejected';
922
+ }
923
+ const pending = this.createPending(request, located.call);
924
+ if (pending === null) {
925
+ this.recordRejectedBinding(request, PERMISSION_REASONS.argumentsUnusable);
926
+ return 'rejected';
927
+ }
928
+ return await this.waitForDecision(pending, signal);
929
+ }
930
+
931
+ /**
932
+ * Build the pending record for one identified request.
933
+ *
934
+ * The record keeps BOTH halves of the operation:
935
+ *
936
+ * * the exact fingerprint and the exact argument text, which are private and are
937
+ * what a decision is bound to and re-verified against;
938
+ * * the redacted projection and its COMPLETENESS, which is what the commander is
939
+ * shown.
940
+ *
941
+ * The completeness flags are computed here, once, from the real arguments:
942
+ * `argumentsComplete` is false when any bound fired, and `allowBlocked` names the
943
+ * reason an `allow-once` would be refused for it (see {@link allowRefusalReason}).
944
+ * @param {object} request - native approval request.
945
+ * @param {object} call - located `tool/call` facts.
946
+ * @returns {object | null} pending record, or null when it cannot be described.
947
+ */
948
+ createPending(request, call) {
949
+ let parsed;
950
+ try {
951
+ parsed = JSON.parse(call.argumentsText);
952
+ } catch {
953
+ return null;
954
+ }
955
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
956
+ // A tool call whose arguments are not an object cannot be fingerprinted
957
+ // per-key, and every enforcing tool in this composition takes one.
958
+ return null;
959
+ }
960
+ this.sequence += 1;
961
+ const createdAt = this.now();
962
+ const state = newProjectionState();
963
+ const projected = projectValue(parsed, {
964
+ redact: this.redact,
965
+ isSecretKey: this.isSecretKey,
966
+ state,
967
+ });
968
+ const rendered = boundedJsonText(projected);
969
+ if (rendered.exceeded) noteCut(state, 'value');
970
+ const pending = {
971
+ requestId: `permission-${this.taskId}-${this.sequence}`,
972
+ taskId: this.taskId,
973
+ connectionId: this.connectionId,
974
+ sessionId: this.sessionId,
975
+ toolName: call.name,
976
+ callId: call.callId,
977
+ turn: call.turn,
978
+ step: call.step,
979
+ // The Session log offset the operation was read from. A decision re-reads
980
+ // that same offset and refuses if the call is no longer the same record.
981
+ callSeq: call.seq,
982
+ // WHICH turn was open when the question was asked. A decision needs this exact
983
+ // turn to still be the open one; "some turn is open" is not enough, because a
984
+ // close-then-reopen opens a DIFFERENT turn the request never asked in.
985
+ //
986
+ // Read at the TAIL (no lower bound): the seam asks while its call is the newest
987
+ // event, so the tail's open turn IS the asking turn. Passing the call's offset
988
+ // here would start the scan at the `turn/start` behind it and report a turn that
989
+ // a later `turn/end` had already closed.
990
+ turnAtAsk: openTurnAt(this.session),
991
+ // The exact Session object and id the operation was read from.
992
+ boundSessionId: this.boundSessionId,
993
+ // A non-reusable identity: the fingerprint is over the EXACT arguments as
994
+ // the model produced them, so a later call with different arguments can
995
+ // never be decided by this request's evidence.
996
+ fingerprint: fingerprintOf(parsed),
997
+ // The exact argument text, retained PRIVATELY (never published) so a decision
998
+ // can re-compare the operation byte for byte instead of trusting a digest of
999
+ // a record it did not re-read.
1000
+ exactArguments: call.argumentsText,
1001
+ // Redacted, bounded rendering of the same operation, safe to publish.
1002
+ arguments: rendered.text,
1003
+ argumentKeys: Object.keys(parsed).slice(0, PERMISSION_BOUNDS.argumentKeys).map((key) => this.redact(key)),
1004
+ // Completeness, stated rather than inferred from a trailing marker.
1005
+ argumentsComplete: state.cuts.length === 0,
1006
+ completeness: state.cuts.length === 0 ? PERMISSION_COMPLETENESS.complete : PERMISSION_COMPLETENESS.truncated,
1007
+ omitted: {
1008
+ valueChars: state.valueCuts,
1009
+ keys: state.keyCuts,
1010
+ depth: state.depthCuts,
1011
+ items: state.itemCuts,
1012
+ },
1013
+ // Which bounds fired, in a fixed vocabulary, so the refusal can be explained.
1014
+ boundsApplied: [...state.cuts],
1015
+ // The asker's own claim about why it asks, labelled as a claim. It is never
1016
+ // the operation and never a grant.
1017
+ claimedReason: this.boundText(request?.reason, PERMISSION_BOUNDS.reasonChars),
1018
+ requestedAccess: this.requestedAccessOf(parsed),
1019
+ createdAt,
1020
+ deadlineAt: createdAt + this.timeoutMs,
1021
+ state: PERMISSION_STATES.pending,
1022
+ decision: null,
1023
+ decidedAt: null,
1024
+ decidedBy: null,
1025
+ decisionReason: null,
1026
+ settledOutcome: null,
1027
+ resolve: null,
1028
+ timer: null,
1029
+ onExternalAbort: null,
1030
+ externalSignal: null,
1031
+ };
1032
+ pending.allowBlocked = this.allowRefusalReason(pending);
1033
+ return pending;
1034
+ }
1035
+
1036
+ /**
1037
+ * Why an `allow-once` must be refused for this request, or `null`.
1038
+ *
1039
+ * The rule is the one the commander's decision depends on: **never allow an
1040
+ * operation whose executable material was omitted by a bound.** A truncated
1041
+ * `bash.command` can hide the tail that actually runs; a truncated `write.body`
1042
+ * can hide what is written. `reject` stays available in every one of these cases,
1043
+ * because refusing is always safe — it is the ALLOW that needs complete evidence.
1044
+ * @param {object} pending - pending record.
1045
+ * @returns {string | null} fixed reason, or null when an allow is decidable.
1046
+ */
1047
+ allowRefusalReason(pending) {
1048
+ if (pending?.argumentsComplete !== true) {
1049
+ return PERMISSION_REASONS.incompleteEvidence;
1050
+ }
1051
+ if (pending?.callSeq === null || pending?.callSeq === undefined) {
1052
+ return PERMISSION_REASONS.noCallSeq;
1053
+ }
1054
+ return null;
1055
+ }
1056
+
1057
+
1058
+ /**
1059
+ * Describe the access the call asks for, from the REAL arguments.
1060
+ *
1061
+ * Stated from the operation, never from the asker's prose: a sandbox escalation
1062
+ * is `{ mode, requested: true }`, any other asking call is `{ mode: null }`.
1063
+ * @param {object} args - parsed arguments.
1064
+ * @returns {{ kind: string, mode: string | null }} bounded access fact.
1065
+ */
1066
+ requestedAccessOf(args) {
1067
+ const mode = args?.sandbox_permissions;
1068
+ if (typeof mode === 'string' && mode !== '') {
1069
+ return { kind: 'sandbox-escalation', mode };
1070
+ }
1071
+ return { kind: 'tool-call', mode: null };
1072
+ }
1073
+
1074
+ /**
1075
+ * Wait, boundedly, for the commander's decision.
1076
+ *
1077
+ * Two lifetimes race here and both settle the waiter exactly once: the
1078
+ * commander's decision (bound to this request id and fingerprint) and the
1079
+ * request's own deadline. A third, the asking tool's abort signal, pierces the
1080
+ * wait so a cancelled tool call cannot leave a request looking pending.
1081
+ * @param {object} pending - pending record.
1082
+ * @param {AbortSignal | undefined} signal - the asking tool's signal.
1083
+ * @returns {Promise<string>} the closed native outcome.
1084
+ */
1085
+ async waitForDecision(pending, signal) {
1086
+ this.pending = pending;
1087
+ const decision = new Promise((resolvePromise) => {
1088
+ pending.resolve = resolvePromise;
1089
+ });
1090
+ // The deadline is this request's OWN bound: it is independent of the run's
1091
+ // execution budget, which the engine pauses while this is outstanding.
1092
+ pending.timer = setTimeout(() => {
1093
+ pending.timer = null;
1094
+ this.settle(pending, PERMISSION_STATES.expired, 'rejected', {
1095
+ reason: 'the permission request reached its deadline without a decision',
1096
+ decidedBy: 'deadline',
1097
+ });
1098
+ }, this.timeoutMs);
1099
+ pending.timer.unref?.();
1100
+ if (signal !== undefined && signal !== null && typeof signal.addEventListener === 'function') {
1101
+ pending.externalSignal = signal;
1102
+ pending.onExternalAbort = () => {
1103
+ this.settle(pending, PERMISSION_STATES.cancelled, 'cancelled', {
1104
+ reason: PERMISSION_REASONS.aborted,
1105
+ decidedBy: 'asker',
1106
+ });
1107
+ };
1108
+ signal.addEventListener('abort', pending.onExternalAbort, { once: true });
1109
+ }
1110
+ this.emitPending(pending);
1111
+ try {
1112
+ return await decision;
1113
+ } finally {
1114
+ this.clearPending(pending);
1115
+ }
1116
+ }
1117
+
1118
+ /**
1119
+ * Publish one pending request to its observers (the engine records the phase).
1120
+ *
1121
+ * An observer throw is contained: a task view that cannot be updated must not
1122
+ * turn a live approval wait into a failed tool call.
1123
+ * @param {object} pending - pending record.
1124
+ * @returns {void}
1125
+ */
1126
+ emitPending(pending) {
1127
+ if (this.onPending === null) return;
1128
+ try {
1129
+ this.onPending(this.publicView(pending));
1130
+ } catch (error) {
1131
+ this.logger?.warn?.('dsh-delegate: permission observer failed', String(error?.code ?? ''));
1132
+ }
1133
+ }
1134
+
1135
+ /**
1136
+ * Decide one pending request. Called by the engine on behalf of ONE task.
1137
+ *
1138
+ * The order is the whole contract, and each step can refuse. It is deliberately
1139
+ * ordered so the CHEAP identity checks come first and the LIVE re-verification
1140
+ * comes before any grant:
1141
+ *
1142
+ * 1. the decision value must be one of `allow-once`/`reject` (validated before
1143
+ * anything is looked up or mutated);
1144
+ * 2. the request must be THIS bridge's own pending request (`requestId`);
1145
+ * 3. it must still be pending — a second decision, an expired request and a
1146
+ * cancelled one are all refused rather than re-applied;
1147
+ * 4. it must not be past its deadline (by the clock, not only by the timer);
1148
+ * 5. the fingerprint is **mandatory for `allow-once`** and is compared exactly
1149
+ * when supplied for `reject`. An allow must name the operation it grants;
1150
+ * 6. **for an allow only**, the operation is re-read from the LIVE Session and
1151
+ * must be unchanged at the same offset, in the same tool, with byte-identical
1152
+ * arguments, inside a still-open turn; and the projection must have been
1153
+ * COMPLETE (no bound fired). Any failure refuses the allow.
1154
+ *
1155
+ * `reject` deliberately skips 6: refusing is always safe, so a commander can deny
1156
+ * a request whose evidence was shortened or whose call has since changed. An
1157
+ * `allow-once` may not.
1158
+ * @param {object} request - `{ requestId, decision, reason, fingerprint }`.
1159
+ * @returns {object} bounded result: the settled request view.
1160
+ * @throws {PermissionError} on any refusal.
1161
+ */
1162
+ decide(request) {
1163
+ const requestId = typeof request?.requestId === 'string' ? request.requestId : '';
1164
+ if (requestId === '') {
1165
+ throw new PermissionError(PERMISSION_CODES.invalid, 'requestId is required', { field: 'requestId' });
1166
+ }
1167
+ const decision = request?.decision;
1168
+ if (!PERMISSION_DECISIONS.includes(decision)) {
1169
+ throw new PermissionError(PERMISSION_CODES.invalid, 'decision must be allow-once or reject', {
1170
+ field: 'decision',
1171
+ accepted: [...PERMISSION_DECISIONS],
1172
+ });
1173
+ }
1174
+ const allow = decision === 'allow-once';
1175
+ const pending = this.pending;
1176
+ if (pending === null || pending.requestId !== requestId) {
1177
+ // An unknown id, another run's id and an already-settled id are ONE answer:
1178
+ // the caller learns nothing about requests it did not own.
1179
+ const settled = this.history.find((entry) => entry.requestId === requestId) ?? null;
1180
+ if (settled !== null) {
1181
+ throw new PermissionError(PERMISSION_CODES.notPending, 'this permission request is already settled', {
1182
+ requestId,
1183
+ state: settled.state,
1184
+ outcome: settled.settledOutcome,
1185
+ });
1186
+ }
1187
+ throw new PermissionError(PERMISSION_CODES.notFound, 'no pending permission request matches this identity', {
1188
+ requestId,
1189
+ });
1190
+ }
1191
+ if (pending.state !== PERMISSION_STATES.pending) {
1192
+ throw new PermissionError(PERMISSION_CODES.notPending, 'this permission request is already settled', {
1193
+ requestId,
1194
+ state: pending.state,
1195
+ });
1196
+ }
1197
+ if (this.now() >= pending.deadlineAt) {
1198
+ // Expiry is decided by the clock, not only by the timer: a decision that
1199
+ // races the deadline must not resurrect a request nobody may answer.
1200
+ this.settle(pending, PERMISSION_STATES.expired, 'rejected', {
1201
+ reason: 'the permission request reached its deadline',
1202
+ decidedBy: 'deadline',
1203
+ });
1204
+ throw new PermissionError(PERMISSION_CODES.expired, 'the permission request expired before this decision', {
1205
+ requestId,
1206
+ });
1207
+ }
1208
+
1209
+ const supplied = request?.fingerprint;
1210
+ if (allow && (typeof supplied !== 'string' || supplied === '')) {
1211
+ // An allow without a fingerprint would grant "whatever is pending", which is
1212
+ // exactly the substitution this design refuses. The request stays pending so
1213
+ // a correct decision can still be made.
1214
+ throw new PermissionError(
1215
+ PERMISSION_CODES.invalid,
1216
+ 'an allow-once decision must quote the request fingerprint',
1217
+ { requestId, field: 'fingerprint', reason: PERMISSION_REASONS.fingerprintRequired },
1218
+ );
1219
+ }
1220
+ if (typeof supplied === 'string' && supplied !== pending.fingerprint) {
1221
+ // The operation the caller believes it is deciding is not the operation that
1222
+ // is pending. Refused, and the request is left pending for the two parties
1223
+ // that actually know what it is.
1224
+ throw new PermissionError(PERMISSION_CODES.changed, 'the pending operation does not match the fingerprint supplied', {
1225
+ requestId,
1226
+ });
1227
+ }
1228
+
1229
+ if (allow) {
1230
+ // 6a. completeness: never allow an operation whose material was omitted.
1231
+ const blocked = pending.allowBlocked ?? this.allowRefusalReason(pending);
1232
+ if (blocked !== null) {
1233
+ throw new PermissionError(
1234
+ PERMISSION_CODES.incomplete,
1235
+ blocked === PERMISSION_REASONS.incompleteEvidence
1236
+ ? 'the operation was shortened by a bound, so it cannot be allowed; reject it or ask the worker to narrow the call'
1237
+ : 'the recorded tool call cannot be re-verified, so an allow cannot be granted',
1238
+ { requestId, reason: blocked, boundsApplied: [...pending.boundsApplied] },
1239
+ );
1240
+ }
1241
+ // 6b. the operation must still be the SAME live record.
1242
+ const changed = this.reverifyOperation(pending);
1243
+ if (changed !== null) {
1244
+ throw new PermissionError(
1245
+ PERMISSION_CODES.changed,
1246
+ 'the recorded tool call is no longer the exact operation this request was created for',
1247
+ { requestId, reason: changed },
1248
+ );
1249
+ }
1250
+ }
1251
+
1252
+ const reason = this.boundText(request?.reason, PERMISSION_BOUNDS.decisionReasonChars);
1253
+ const outcome = allow ? 'allowed-once' : 'rejected';
1254
+ this.settle(pending, PERMISSION_STATES.decided, outcome, {
1255
+ reason: reason ?? (allow ? 'the commander allowed this call once' : 'the commander rejected this call'),
1256
+ decidedBy: 'commander',
1257
+ // Record which checks the grant passed, so the evidence states WHY an allow
1258
+ // was allowed instead of only that it was.
1259
+ ...(allow
1260
+ ? {
1261
+ verified: {
1262
+ fingerprintQuoted: true,
1263
+ argumentsComplete: pending.argumentsComplete === true,
1264
+ callReread: true,
1265
+ turnOpen: true,
1266
+ boundsApplied: [...pending.boundsApplied],
1267
+ },
1268
+ }
1269
+ : {}),
1270
+ });
1271
+ return this.history.at(-1) ?? null;
1272
+ }
1273
+
1274
+ /**
1275
+ * Settle one pending request exactly once and release its waiter.
1276
+ *
1277
+ * Idempotent by state: the deadline timer, the tool's abort signal, a decision
1278
+ * and a stop can all race, and only the first one is applied. The waiter's
1279
+ * promise is resolved with the OUTCOME, so the paused tool call resumes with
1280
+ * the native vocabulary rather than with this module's own words.
1281
+ * @param {object} pending - pending record.
1282
+ * @param {string} state - `decided`/`expired`/`cancelled`/`unavailable`.
1283
+ * @param {string} outcome - one of {@link APPROVAL_OUTCOMES}.
1284
+ * @param {object} [evidence] - `reason`, `decidedBy`.
1285
+ * @returns {boolean} true when this call settled the request.
1286
+ */
1287
+ settle(pending, state, outcome, evidence = {}) {
1288
+ if (pending === null || pending.state !== PERMISSION_STATES.pending) return false;
1289
+ pending.state = state;
1290
+ pending.settledOutcome = APPROVAL_OUTCOMES.includes(outcome) ? outcome : 'unavailable';
1291
+ pending.decidedAt = this.now();
1292
+ pending.decidedBy = evidence.decidedBy ?? null;
1293
+ pending.decisionReason = typeof evidence.reason === 'string' ? this.redact(evidence.reason).slice(0, PERMISSION_BOUNDS.decisionReasonChars) : null;
1294
+ if (evidence.verified !== undefined && evidence.verified !== null) {
1295
+ pending.verified = evidence.verified;
1296
+ }
1297
+ if (pending.timer !== null) {
1298
+ clearTimeout(pending.timer);
1299
+ pending.timer = null;
1300
+ }
1301
+ if (pending.externalSignal !== null && pending.onExternalAbort !== null) {
1302
+ try {
1303
+ pending.externalSignal.removeEventListener?.('abort', pending.onExternalAbort);
1304
+ } catch {
1305
+ // Removing a listener from a foreign signal is best effort by contract.
1306
+ }
1307
+ pending.onExternalAbort = null;
1308
+ pending.externalSignal = null;
1309
+ }
1310
+ this.history.push(this.publicView(pending));
1311
+ if (this.history.length > PermissionBridge.HISTORY_BOUND) this.history.shift();
1312
+ // The reason is delivered to the worker BEFORE the paused tool call is released, so
1313
+ // the note is already in the Agent's inbox by the time the model can take its next
1314
+ // step. It is delivered only for a REJECT: an allow needs no explanation, and a
1315
+ // cancellation is not a decision about the operation.
1316
+ let feedback = null;
1317
+ if (pending.settledOutcome === 'rejected' && pending.decidedBy === 'commander') {
1318
+ feedback = this.deliverRejectionFeedback(pending, pending.decisionReason);
1319
+ // Recorded on the settled view as a verified fact, so "the worker was told why" is
1320
+ // never claimed merely because a reason was stored.
1321
+ const last = this.history.at(-1);
1322
+ if (last !== null && last !== undefined) last.rejectionFeedback = feedback;
1323
+ pending.rejectionFeedback = feedback;
1324
+ }
1325
+ const resolvePromise = pending.resolve;
1326
+ pending.resolve = null;
1327
+ if (typeof resolvePromise === 'function') resolvePromise(pending.settledOutcome);
1328
+ if (this.pending === pending) this.pending = null;
1329
+ try {
1330
+ this.onSettled?.(this.history.at(-1));
1331
+ } catch (error) {
1332
+ this.logger?.warn?.('dsh-delegate: permission observer failed', String(error?.code ?? ''));
1333
+ }
1334
+ return true;
1335
+ }
1336
+
1337
+ /**
1338
+ * Send the commander's REJECTION REASON back into the same Agent.
1339
+ *
1340
+ * The native approval protocol cannot carry prose: `ApprovalService.request()`
1341
+ * resolves one of four closed outcomes, so the reason a commander typed never reached
1342
+ * the worker — it was recorded in history and the tool received a bare `rejected`.
1343
+ * The acceptance report is exactly that: the worker could not know it should narrow
1344
+ * its request and ask again.
1345
+ *
1346
+ * The real channel for prose is the Agent's own inbox. The native approval service
1347
+ * itself uses it for its policy notices
1348
+ * (`agent.inject(createUserMessage({ content, source }))`), and `dsh-user-questions`
1349
+ * uses the same call to steer a late answer. So this method injects ONE user message
1350
+ * describing the rejection.
1351
+ *
1352
+ * What the message says, and what it must never be read as:
1353
+ *
1354
+ * * WHY this one call was rejected, quoted from the decision;
1355
+ * * that the rejection STANDS — the call is not approved, and nothing was widened;
1356
+ * * that this is NOT a new authorization and grants nothing by itself;
1357
+ * * what to do next: rewrite the operation to fit and request approval again.
1358
+ *
1359
+ * The reason is redacted and bounded before it is sent, by the same rules the stored
1360
+ * evidence uses. A send failure is returned as a bounded outcome and NEVER changes the
1361
+ * settlement: `rejected` already happened, and reporting a failed notice as success,
1362
+ * or un-rejecting the call because the notice failed, would both be lies.
1363
+ *
1364
+ * Delivery is tracked per request id so a repeated reject, a retried decision or a
1365
+ * plugin restart cannot deliver the same feedback twice. Only an ACTUAL injection on
1366
+ * the bound Agent counts as delivered; anything else stays `not-sent` and is reported.
1367
+ * @param {object} pending - the request that was just settled.
1368
+ * @param {string} reason - the commander's decision reason (already redacted and bounded).
1369
+ * @returns {{ delivered: boolean, requestId: string, callId: string | null,
1370
+ * messageId: string | null, reason: string }} the outcome, never a rejection.
1371
+ */
1372
+ deliverRejectionFeedback(pending, reason) {
1373
+ const requestId = typeof pending?.requestId === 'string' ? pending.requestId : '';
1374
+ // One delivery per request, ever. A duplicate reject and a restart both land here.
1375
+ if (this.feedbackSent.has(requestId)) {
1376
+ return {
1377
+ delivered: false,
1378
+ requestId,
1379
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1380
+ messageId: this.feedbackSent.get(requestId),
1381
+ reason: 'already-delivered',
1382
+ };
1383
+ }
1384
+ const agent = this.agent;
1385
+ const sessionRefusal = this.liveBindingRefusal();
1386
+ if (agent === null || typeof agent?.inject !== 'function' || sessionRefusal !== null) {
1387
+ return {
1388
+ delivered: false,
1389
+ requestId,
1390
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1391
+ messageId: null,
1392
+ reason: sessionRefusal ?? 'no-injectable-agent',
1393
+ };
1394
+ }
1395
+ const text = rejectionFeedbackText(pending, reason);
1396
+ let message;
1397
+ try {
1398
+ message = this.createMessage(text);
1399
+ } catch (error) {
1400
+ return {
1401
+ delivered: false,
1402
+ requestId,
1403
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1404
+ messageId: null,
1405
+ reason: typeof error?.code === 'string' ? error.code : 'message-unavailable',
1406
+ };
1407
+ }
1408
+ try {
1409
+ agent.inject(message);
1410
+ } catch (error) {
1411
+ // The rejection is already in force. This only reports that the NOTE did not reach
1412
+ // the worker, which is a different, smaller fact than the decision itself.
1413
+ this.logger?.warn?.('dsh-delegate: the rejection reason could not be delivered', String(error?.code ?? ''));
1414
+ return {
1415
+ delivered: false,
1416
+ requestId,
1417
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1418
+ messageId: null,
1419
+ reason: 'inject-failed',
1420
+ };
1421
+ }
1422
+ const messageId = typeof message?.id === 'string' ? message.id : null;
1423
+ this.feedbackSent.set(requestId, messageId);
1424
+ return {
1425
+ delivered: true,
1426
+ requestId,
1427
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1428
+ messageId,
1429
+ reason: 'delivered',
1430
+ // The record states what was said, so "feedback happened" is auditable rather than
1431
+ // claimed: the exact text is the evidence.
1432
+ text,
1433
+ };
1434
+ }
1435
+
1436
+ /**
1437
+ * Clear the pending slot of an answered request.
1438
+ * @param {object} pending - pending record.
1439
+ * @returns {void}
1440
+ */
1441
+ clearPending(pending) {
1442
+ if (this.pending === pending) this.pending = null;
1443
+ }
1444
+
1445
+ /**
1446
+ * Record a request that was refused because its identity could not be bound.
1447
+ *
1448
+ * This is evidence, not a decision: nothing was granted, and the record says
1449
+ * which check failed so an operator can act on the tool surface instead of
1450
+ * guessing why a worker was told "no approval channel".
1451
+ * @param {object} request - native approval request.
1452
+ * @param {string} reason - fixed {@link PERMISSION_REASONS} value.
1453
+ * @returns {void}
1454
+ */
1455
+ recordRejectedBinding(request, reason) {
1456
+ this.sequence += 1;
1457
+ const createdAt = this.now();
1458
+ const entry = {
1459
+ requestId: `permission-${this.taskId}-${this.sequence}`,
1460
+ taskId: this.taskId,
1461
+ connectionId: this.connectionId,
1462
+ sessionId: this.sessionId,
1463
+ toolName: this.boundText(request?.toolName, 120),
1464
+ callId: this.boundText(request?.callId, 200),
1465
+ turn: null,
1466
+ step: null,
1467
+ fingerprint: null,
1468
+ arguments: null,
1469
+ argumentKeys: [],
1470
+ claimedReason: this.boundText(request?.reason, PERMISSION_BOUNDS.reasonChars),
1471
+ requestedAccess: { kind: 'unbound', mode: null },
1472
+ createdAt,
1473
+ deadlineAt: createdAt,
1474
+ state: PERMISSION_STATES.unavailable,
1475
+ decision: null,
1476
+ decidedAt: createdAt,
1477
+ decidedBy: 'binding',
1478
+ decisionReason: reason ?? PERMISSION_REASONS.unbound,
1479
+ settledOutcome: 'rejected',
1480
+ bindingReason: reason ?? PERMISSION_REASONS.unbound,
1481
+ };
1482
+ this.history.push(entry);
1483
+ if (this.history.length > PermissionBridge.HISTORY_BOUND) this.history.shift();
1484
+ try {
1485
+ this.onSettled?.(entry);
1486
+ } catch {
1487
+ // The refusal is already recorded; an observer throw cannot change it.
1488
+ }
1489
+ }
1490
+
1491
+ /**
1492
+ * Stop the outstanding request, if any, and restore the policy.
1493
+ *
1494
+ * The outcome is chosen by the caller because the CAUSE differs and the worker
1495
+ * must see the difference: a cancel/stop/switch-off withdraws the question
1496
+ * (`cancelled`), while disposal makes the bridge unusable (`unavailable`).
1497
+ * Either way the paused call resumes immediately with a refusal, the request's
1498
+ * timer and listener are released, and no later decision can apply.
1499
+ * @param {string} state - `cancelled` or `unavailable`.
1500
+ * @param {string} [reason] - fixed reason text.
1501
+ * @returns {boolean} true when a pending request was settled.
1502
+ */
1503
+ stop(state = PERMISSION_STATES.cancelled, reason = PERMISSION_REASONS.stop) {
1504
+ const outcome = state === PERMISSION_STATES.unavailable ? 'unavailable' : 'cancelled';
1505
+ const pending = this.pending;
1506
+ if (pending === null) {
1507
+ return false;
1508
+ }
1509
+ return this.settle(pending, state, outcome, { reason, decidedBy: 'stop' });
1510
+ }
1511
+
1512
+ /**
1513
+ * Disarm the bridge permanently.
1514
+ *
1515
+ * Disposal settles an outstanding request `unavailable` (no decision can be
1516
+ * applied to a bridge that no longer exists), clears `armed` so no policy writer
1517
+ * may keep `ask` installed, and drops the bound Agent so a disposed bridge can
1518
+ * never answer a request that a live Session still holds a reference to.
1519
+ * @returns {void}
1520
+ */
1521
+ dispose() {
1522
+ if (this.disposed) return;
1523
+ this.stop(PERMISSION_STATES.unavailable, PERMISSION_REASONS.disposed);
1524
+ this.armed = false;
1525
+ this.disposed = true;
1526
+ this.agent = null;
1527
+ this.session = null;
1528
+ }
1529
+
1530
+ /**
1531
+ * The public, bounded projection of one request.
1532
+ *
1533
+ * Everything here is either an identifier the caller already holds, a redacted
1534
+ * argument projection, or a timestamp. The exact fingerprint IS published,
1535
+ * because the decision tool accepts it back to bind a decision to exactly this
1536
+ * operation; it is a digest of the arguments, not the arguments.
1537
+ * @param {object} pending - pending or settled record.
1538
+ * @returns {object} redacted view.
1539
+ */
1540
+ publicView(pending) {
1541
+ return {
1542
+ requestId: pending.requestId,
1543
+ taskId: pending.taskId,
1544
+ // Stated, not implied: the commander is told which conversation and which
1545
+ // tool call is paused, so the decision is about an operation it can name.
1546
+ sessionId: pending.sessionId,
1547
+ toolName: pending.toolName,
1548
+ callId: pending.callId,
1549
+ turn: pending.turn,
1550
+ step: pending.step,
1551
+ tool: { name: pending.toolName, callId: pending.callId },
1552
+ state: pending.state,
1553
+ // The asker's own one-line claim, kept apart from the operation itself.
1554
+ reason: pending.claimedReason ?? null,
1555
+ reasonSource: 'asker-claim',
1556
+ requestedAccess: pending.requestedAccess,
1557
+ argumentKeys: pending.argumentKeys,
1558
+ arguments: pending.arguments,
1559
+ argumentsRedacted: true,
1560
+ // Completeness, published so a reader never has to infer it from a trailing
1561
+ // marker in the text: an allow is refused when this is not `complete`.
1562
+ completeness: pending.completeness ?? PERMISSION_COMPLETENESS.complete,
1563
+ argumentsComplete: pending.argumentsComplete !== false,
1564
+ boundsApplied: Array.isArray(pending.boundsApplied) ? [...pending.boundsApplied] : [],
1565
+ omitted: pending.omitted ?? { valueChars: 0, keys: 0, depth: 0, items: 0 },
1566
+ // Why an allow would be refused, or null. Stated so the commander is not left
1567
+ // guessing why `allow-once` came back refused.
1568
+ allowBlocked: pending.allowBlocked ?? null,
1569
+ fingerprint: pending.fingerprint,
1570
+ createdAt: pending.createdAt,
1571
+ deadlineAt: pending.deadlineAt,
1572
+ decision: pending.decision,
1573
+ decidedAt: pending.decidedAt,
1574
+ decidedBy: pending.decidedBy,
1575
+ decisionReason: pending.decisionReason,
1576
+ outcome: pending.settledOutcome,
1577
+ // For a settled allow: which checks the grant actually passed.
1578
+ ...(pending.verified === undefined || pending.verified === null ? {} : { verified: pending.verified }),
1579
+ ...(pending.bindingReason === undefined ? {} : { bindingReason: pending.bindingReason }),
1580
+ // The narrow exception, restated on the evidence itself so no reader has to
1581
+ // infer it: this is one call, decided once, and nothing was granted beyond it.
1582
+ grant: pending.settledOutcome === 'allowed-once'
1583
+ ? { kind: 'allowed-once', appliesTo: 'this-call-only', callId: pending.callId, reusable: false }
1584
+ : null,
1585
+ standingModeUnchanged: true,
1586
+ };
1587
+ }
1588
+
1589
+ /** The pending request's public view, or `null`. */
1590
+ pendingView() {
1591
+ return this.pending === null ? null : this.publicView(this.pending);
1592
+ }
1593
+
1594
+ /** Copy of the settled evidence trail, newest last. */
1595
+ historyView() {
1596
+ return this.history.map((entry) => ({ ...entry }));
1597
+ }
1598
+
1599
+ /**
1600
+ * Redact and bound one free-form string.
1601
+ * @param {unknown} value - untrusted text.
1602
+ * @param {number} cap - character bound.
1603
+ * @returns {string | null} bounded redacted text, or null when empty.
1604
+ */
1605
+ boundText(value, cap) {
1606
+ if (typeof value !== 'string' || value === '') return null;
1607
+ const text = this.redact(value);
1608
+ return text.length > cap ? `${text.slice(0, cap)}…` : text;
1609
+ }
1610
+ }
1611
+
1612
+ /**
1613
+ * Whether a value is an outcome this plugin may act on.
1614
+ * @param {unknown} value - candidate outcome.
1615
+ * @returns {boolean} true for the closed vocabulary.
1616
+ */
1617
+ export function isApprovalOutcome(value) {
1618
+ return typeof value === 'string' && APPROVAL_OUTCOMES.includes(value);
1619
+ }