strands-darwin 0.0.33 → 0.0.34

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 (87) hide show
  1. package/README.md +3 -1
  2. package/README.zh-CN.md +3 -1
  3. package/dist/src/agent/cache-miss.d.ts +143 -0
  4. package/dist/src/agent/cache-miss.js +182 -0
  5. package/dist/src/agent/cache-miss.js.map +1 -0
  6. package/dist/src/agent/compact.d.ts +28 -0
  7. package/dist/src/agent/compact.js +34 -0
  8. package/dist/src/agent/compact.js.map +1 -1
  9. package/dist/src/agent/context-breakdown.d.ts +109 -0
  10. package/dist/src/agent/context-breakdown.js +116 -0
  11. package/dist/src/agent/context-breakdown.js.map +1 -0
  12. package/dist/src/agent/instructions.d.ts +1 -1
  13. package/dist/src/agent/instructions.js.map +1 -1
  14. package/dist/src/agent/permission-rules.d.ts +81 -2
  15. package/dist/src/agent/permission-rules.js +226 -6
  16. package/dist/src/agent/permission-rules.js.map +1 -1
  17. package/dist/src/agent/permission.d.ts +116 -2
  18. package/dist/src/agent/permission.js +201 -26
  19. package/dist/src/agent/permission.js.map +1 -1
  20. package/dist/src/agent/prompt-cache.d.ts +12 -3
  21. package/dist/src/agent/prompt-cache.js +12 -3
  22. package/dist/src/agent/prompt-cache.js.map +1 -1
  23. package/dist/src/agent/runtime.d.ts +87 -1
  24. package/dist/src/agent/runtime.js +175 -2
  25. package/dist/src/agent/runtime.js.map +1 -1
  26. package/dist/src/agents/child-recipe.d.ts +9 -1
  27. package/dist/src/agents/child-recipe.js +2 -0
  28. package/dist/src/agents/child-recipe.js.map +1 -1
  29. package/dist/src/agents/dispatch-registry.d.ts +18 -0
  30. package/dist/src/agents/dispatch-registry.js +2 -0
  31. package/dist/src/agents/dispatch-registry.js.map +1 -1
  32. package/dist/src/agents/retained-children.d.ts +101 -0
  33. package/dist/src/agents/retained-children.js +101 -0
  34. package/dist/src/agents/retained-children.js.map +1 -0
  35. package/dist/src/agents/subagent-tool.d.ts +50 -1
  36. package/dist/src/agents/subagent-tool.js +147 -9
  37. package/dist/src/agents/subagent-tool.js.map +1 -1
  38. package/dist/src/cli-doctor.js +3 -1
  39. package/dist/src/cli-doctor.js.map +1 -1
  40. package/dist/src/cli-main.js +9 -3
  41. package/dist/src/cli-main.js.map +1 -1
  42. package/dist/src/commands/custom-commands.js +5 -4
  43. package/dist/src/commands/custom-commands.js.map +1 -1
  44. package/dist/src/config.d.ts +44 -6
  45. package/dist/src/config.js +40 -16
  46. package/dist/src/config.js.map +1 -1
  47. package/dist/src/headless-protocol.d.ts +1 -1
  48. package/dist/src/headless-runner.js +7 -2
  49. package/dist/src/headless-runner.js.map +1 -1
  50. package/dist/src/hooks/tool-hooks.js +10 -6
  51. package/dist/src/hooks/tool-hooks.js.map +1 -1
  52. package/dist/src/skills/builtin/self-evolution-research/SKILL.md +14 -1
  53. package/dist/src/skills/prompt.d.ts +17 -0
  54. package/dist/src/skills/prompt.js +20 -0
  55. package/dist/src/skills/prompt.js.map +1 -1
  56. package/dist/src/trajectory/record.d.ts +169 -2
  57. package/dist/src/trajectory/record.js +135 -0
  58. package/dist/src/trajectory/record.js.map +1 -1
  59. package/dist/src/trajectory/replay.d.ts +34 -1
  60. package/dist/src/trajectory/replay.js +134 -4
  61. package/dist/src/trajectory/replay.js.map +1 -1
  62. package/dist/src/trajectory/resume-recap.js +10 -3
  63. package/dist/src/trajectory/resume-recap.js.map +1 -1
  64. package/dist/src/trajectory/spend.d.ts +14 -1
  65. package/dist/src/trajectory/spend.js +40 -6
  66. package/dist/src/trajectory/spend.js.map +1 -1
  67. package/dist/src/trajectory/writer.d.ts +45 -1
  68. package/dist/src/trajectory/writer.js +111 -3
  69. package/dist/src/trajectory/writer.js.map +1 -1
  70. package/dist/src/tui/App.d.ts +8 -4
  71. package/dist/src/tui/App.js +148 -32
  72. package/dist/src/tui/App.js.map +1 -1
  73. package/dist/src/tui/context-format.d.ts +16 -0
  74. package/dist/src/tui/context-format.js +41 -0
  75. package/dist/src/tui/context-format.js.map +1 -1
  76. package/dist/src/tui/status-format.d.ts +35 -16
  77. package/dist/src/tui/status-format.js +67 -8
  78. package/dist/src/tui/status-format.js.map +1 -1
  79. package/dist/src/tui/subagent-format.js +13 -1
  80. package/dist/src/tui/subagent-format.js.map +1 -1
  81. package/dist/src/tui/terminal-notify.d.ts +40 -0
  82. package/dist/src/tui/terminal-notify.js +136 -0
  83. package/dist/src/tui/terminal-notify.js.map +1 -0
  84. package/dist/src/tui/terminal-title.d.ts +94 -0
  85. package/dist/src/tui/terminal-title.js +121 -0
  86. package/dist/src/tui/terminal-title.js.map +1 -0
  87. package/package.json +1 -1
@@ -6,7 +6,7 @@ import { type RuleSuggestion } from './permission-rules.js';
6
6
  * `./interventions` has no subpath export, so derive it from the base class.
7
7
  */
8
8
  type InterventionAction = Awaited<ReturnType<InterventionHandler['beforeToolCall']>>;
9
- /** How a tool call is classified. `read` calls run without asking. */
9
+ /** How a tool call is classified. `read` calls run without asking unless they target a sensitive path. */
10
10
  export type PermissionKind = 'read' | 'write' | 'execute';
11
11
  /**
12
12
  * How much confirmation the gate demands.
@@ -36,6 +36,12 @@ export interface RiskAssessment {
36
36
  risk: PermissionRisk;
37
37
  /** Human-readable, shown in the confirmation prompt. */
38
38
  riskReason: string;
39
+ /**
40
+ * Set only by the sensitive-read branch (SER-071): the one `dangerous` class
41
+ * `auto` must hand to the user without consulting the classifier, because a
42
+ * credential read is a question of consent, not of harmlessness.
43
+ */
44
+ sensitiveRead?: true;
39
45
  }
40
46
  /**
41
47
  * What the UI needs to render a confirmation. `summary` is a one-line headline;
@@ -171,6 +177,42 @@ export interface SafetyVerdict {
171
177
  * bounds it with a timeout and treats any failure as "not safe".
172
178
  */
173
179
  export type SafetyClassifier = (request: AssessedPermissionRequest) => Promise<SafetyVerdict>;
180
+ /**
181
+ * Which stage of the gate settled a call (SER-079). One name per `proceed`/`deny`
182
+ * return in the decision path, in the order the stages run:
183
+ *
184
+ * - `write-scope-denied`: a `workflow` node's declared `writeScopes` (SER-065);
185
+ * - `deny-rule`: a configured deny-rule (SER-076);
186
+ * - `plan-denied`: plan mode refusing a write/execute;
187
+ * - `yolo`, `safe`, `allow-rule`, `classifier`: the four silent approvals;
188
+ * - `user-approved`, `user-denied`: what the bridge answered;
189
+ * - `restart-limit-denied`: {@link MAX_MODE_CHANGE_RESTARTS} reached.
190
+ */
191
+ export type PermissionOutcome = 'write-scope-denied' | 'deny-rule' | 'plan-denied' | 'yolo' | 'safe' | 'allow-rule' | 'classifier' | 'user-approved' | 'user-denied' | 'restart-limit-denied';
192
+ /**
193
+ * One settled decision, as the gate publishes it to {@link PermissionGateOptions.onDecision}.
194
+ *
195
+ * Deliberately **never** the tool input or any argument text: the recorded
196
+ * `beforeToolCallEvent` under the same `toolUseId` already carries it, and an audit
197
+ * line that repeated a command or a file body would be a second copy of the one thing
198
+ * the record already bounds. Plain strings and booleans only, frozen, so an observer
199
+ * cannot relabel a decision another observer will read.
200
+ */
201
+ export interface PermissionDecisionRecord {
202
+ toolUseId: string;
203
+ toolName: string;
204
+ kind: PermissionKind;
205
+ risk: PermissionRisk;
206
+ /** The mode in force when the decision settled. */
207
+ mode: ApprovalMode;
208
+ /** `PermissionSource.label`: `parent`, or `<agent>#<dispatchId>` for a child. */
209
+ source: string;
210
+ outcome: PermissionOutcome;
211
+ /** The deny-rule or allow-rule that matched, or the rule granted at the prompt. */
212
+ rule?: string;
213
+ /** True only when the bridge was actually asked for this call (a withdrawn prompt counts). */
214
+ promptedUser: boolean;
215
+ }
174
216
  export interface PermissionGateOptions {
175
217
  /** Where enforcement starts. `PermissionGate.setMode` moves it, user-only. */
176
218
  mode: ApprovalMode;
@@ -179,6 +221,13 @@ export interface PermissionGateOptions {
179
221
  ask: PermissionBridge;
180
222
  /** Wildcard allow-rules from the config; see `./permission-rules.ts`. */
181
223
  allowRules?: readonly string[];
224
+ /**
225
+ * Wildcard deny-rules from the config (SER-076), same grammar. Judged before
226
+ * the mode, the static `safe` check, allow-rules and the classifier, so a deny
227
+ * holds in every mode — `yolo` included — and for every child sharing the gate.
228
+ * Configured only: nothing in the session can add or remove one.
229
+ */
230
+ denyRules?: readonly string[];
182
231
  /** Consulted for dangerous calls in `auto` mode; ignored otherwise. */
183
232
  classifier?: SafetyClassifier;
184
233
  /** How long `auto` waits for the classifier before falling back to asking. */
@@ -188,6 +237,14 @@ export interface PermissionGateOptions {
188
237
  * reads as the parent's, which is only true for a runtime with no delegation.
189
238
  */
190
239
  dispatchSource?: DispatchSourceResolver;
240
+ /**
241
+ * Observes every settled decision (SER-079): called exactly once per tool call
242
+ * the gate judged, after the outcome is final — a `WITHDRAWN` restart is not an
243
+ * outcome. Publication only: the object is frozen and carries no input, and a
244
+ * throwing observer is swallowed, so nothing here can change or delay what the
245
+ * model gets. The runtime points it at the trajectory recorder.
246
+ */
247
+ onDecision?: (decision: PermissionDecisionRecord) => void;
191
248
  }
192
249
  /**
193
250
  * Where a live allow-rule came from. `configured` means it was loaded from the
@@ -225,6 +282,12 @@ export declare class PermissionGate extends InterventionHandler {
225
282
  * (`matchesAnyRule`) reads the plain strings and must stay unchanged.
226
283
  */
227
284
  private readonly ruleOrigins;
285
+ /**
286
+ * Configured deny-rules (SER-076). Frozen: there is no grant, revoke or
287
+ * suggestion path for a deny — the rules file is the only way one changes,
288
+ * and it is read at startup only.
289
+ */
290
+ private readonly denyRuleList;
228
291
  /**
229
292
  * Live enforcement policy, not `options.mode`: `/mode` moves it mid-session and
230
293
  * every decision — parent and child, since they share this instance — reads it
@@ -279,6 +342,13 @@ export declare class PermissionGate extends InterventionHandler {
279
342
  * the enforcement surface.
280
343
  */
281
344
  listAllowRules(): AllowRuleEntry[];
345
+ /**
346
+ * The configured deny-rules, in the order they are consulted (SER-076). Every
347
+ * one is `configured` by construction — there is no session origin to state —
348
+ * and the array is frozen, so `/permissions` can show it but nothing can edit
349
+ * the enforcement surface through it.
350
+ */
351
+ get denyRules(): readonly string[];
282
352
  /**
283
353
  * Denies plan-mode mutation before hooks, rules, classifiers, or prompts can
284
354
  * have side effects. Undefined means the ordinary permission flow still owns
@@ -288,12 +358,27 @@ export declare class PermissionGate extends InterventionHandler {
288
358
  * and leaving it stops guarding immediately.
289
359
  */
290
360
  planGuard(toolName: string, input: unknown): InterventionAction | undefined;
361
+ /**
362
+ * The two guards the hook wrapper runs ahead of any `PreToolUse` shell — deny-rule,
363
+ * then plan — as one call that also **publishes** the denial (SER-079). Undefined
364
+ * means the ordinary flow owns the call and nothing was published.
365
+ *
366
+ * This is what keeps the audit at one record per tool call: the wrapper returns a
367
+ * denial from here without ever reaching {@link beforeToolCall}, so that path never
368
+ * sees the call; a call that passes here and is later denied by the same guards
369
+ * inside {@link beforeToolCall} (the mode moved to `plan` while Pre hooks ran) is
370
+ * published there instead. {@link denyRuleGuard} and {@link planGuard} themselves
371
+ * stay pure and unpublished, so calling them directly (tests, other callers)
372
+ * records nothing.
373
+ */
374
+ guardBeforeHooks(event: BeforeToolCallEvent): InterventionAction | undefined;
291
375
  /**
292
376
  * Decides one call, restarting whenever the user changes the mode underneath it.
293
377
  *
294
378
  * The loop is the whole in-flight contract: a withdrawn decision is discarded,
295
379
  * never applied, and the call is judged again from the top — plan guard first —
296
- * by whatever mode is in force now.
380
+ * by whatever mode is in force now. Whatever settles it — a pass, or the restart
381
+ * limit — is published exactly once, after it is final.
297
382
  */
298
383
  beforeToolCall(event: BeforeToolCallEvent): Promise<InterventionAction>;
299
384
  /**
@@ -305,12 +390,41 @@ export declare class PermissionGate extends InterventionHandler {
305
390
  * re-checks `aborted` after the promise settles.
306
391
  */
307
392
  private decideOnce;
393
+ /**
394
+ * The deny-rule and plan guards as one settled denial, or undefined when neither
395
+ * applies. Shared by {@link guardBeforeHooks} and {@link decideOnce} so the two
396
+ * cannot disagree about which stage a call fell at.
397
+ */
398
+ private earlyDenial;
399
+ /**
400
+ * Hands one settled decision to the observer (SER-079). Publication only: the
401
+ * object is composed from what the gate already knows — never the input — and
402
+ * frozen, and an observer that throws costs nothing but its own record. `kind`
403
+ * and `risk` are re-derived here because the early guards settle a call before
404
+ * the request exists; `classify`/`assessRisk` are pure, so the reading is the one
405
+ * the decision path would have made.
406
+ */
407
+ private publish;
308
408
  /**
309
409
  * Who is asking. A tracked dispatch resolves to its child label; anything else
310
410
  * is the parent, because the runtime assembles exactly one `Agent` and every
311
411
  * other agent in the process is a dispatch this resolver knows about.
312
412
  */
313
413
  private sourceOf;
414
+ /**
415
+ * Denies a call a configured deny-rule forbids (SER-076). Undefined means the
416
+ * ordinary flow owns the call. The reason names the rule so the model can
417
+ * report it precisely, and says in so many words not to retry or route around
418
+ * it: a deny is the user's standing instruction, not a transient failure. The
419
+ * rule text is bounded because it reaches the model verbatim.
420
+ *
421
+ * Public like {@link planGuard} and for the same reason: the hook wrapper runs
422
+ * it before any `PreToolUse` shell, so a forbidden call cannot trigger a policy
423
+ * hook either. Idempotent and side-effect free, so running it twice is safe.
424
+ */
425
+ denyRuleGuard(toolName: string, input: unknown): InterventionAction | undefined;
426
+ /** The first configured deny-rule the call matches, or undefined. Pure. */
427
+ private matchedDenyRule;
314
428
  /**
315
429
  * Denies a scoped `workflow` node's `fileEditor` write that lands outside every
316
430
  * declared scope. Undefined means the ordinary flow owns the call — including
@@ -13,7 +13,7 @@ import path from 'node:path';
13
13
  import { isSensitiveDarwinPath } from '../paths.js';
14
14
  import { InterventionActions, InterventionHandler } from '@strands-agents/sdk';
15
15
  import { MANAGE_BACKGROUND_TASK_TOOL_NAME } from './background-delegation.js';
16
- import { hasShellMetacharacters, matchesAnyRule, splitBashSegments, suggestRules, } from './permission-rules.js';
16
+ import { hasShellMetacharacters, matchesAnyDenyRule, matchesAnyRule, sensitiveReadPath, splitBashSegments, suggestRules, } from './permission-rules.js';
17
17
  export const APPROVAL_MODES = ['default', 'auto', 'plan', 'yolo'];
18
18
  export function isApprovalMode(value) {
19
19
  return typeof value === 'string' && APPROVAL_MODES.includes(value);
@@ -73,6 +73,12 @@ export class PermissionGate extends InterventionHandler {
73
73
  * (`matchesAnyRule`) reads the plain strings and must stay unchanged.
74
74
  */
75
75
  ruleOrigins = new Map();
76
+ /**
77
+ * Configured deny-rules (SER-076). Frozen: there is no grant, revoke or
78
+ * suggestion path for a deny — the rules file is the only way one changes,
79
+ * and it is read at startup only.
80
+ */
81
+ denyRuleList;
76
82
  /**
77
83
  * Live enforcement policy, not `options.mode`: `/mode` moves it mid-session and
78
84
  * every decision — parent and child, since they share this instance — reads it
@@ -90,6 +96,7 @@ export class PermissionGate extends InterventionHandler {
90
96
  this.rules = [...(options.allowRules ?? [])];
91
97
  for (const rule of this.rules)
92
98
  this.ruleOrigins.set(rule, 'configured');
99
+ this.denyRuleList = Object.freeze([...(options.denyRules ?? [])]);
93
100
  this.currentMode = options.mode;
94
101
  }
95
102
  /** The mode enforcing right now. */
@@ -163,6 +170,15 @@ export class PermissionGate extends InterventionHandler {
163
170
  listAllowRules() {
164
171
  return this.rules.map((rule) => ({ rule, origin: this.ruleOrigins.get(rule) ?? 'session' }));
165
172
  }
173
+ /**
174
+ * The configured deny-rules, in the order they are consulted (SER-076). Every
175
+ * one is `configured` by construction — there is no session origin to state —
176
+ * and the array is frozen, so `/permissions` can show it but nothing can edit
177
+ * the enforcement surface through it.
178
+ */
179
+ get denyRules() {
180
+ return this.denyRuleList;
181
+ }
166
182
  /**
167
183
  * Denies plan-mode mutation before hooks, rules, classifiers, or prompts can
168
184
  * have side effects. Undefined means the ordinary permission flow still owns
@@ -181,30 +197,64 @@ export class PermissionGate extends InterventionHandler {
181
197
  `Continue with read-only inspection, or ask the user to run outside plan mode ` +
182
198
  `(they can leave it with /mode default) before changing or executing anything.`);
183
199
  }
200
+ /**
201
+ * The two guards the hook wrapper runs ahead of any `PreToolUse` shell — deny-rule,
202
+ * then plan — as one call that also **publishes** the denial (SER-079). Undefined
203
+ * means the ordinary flow owns the call and nothing was published.
204
+ *
205
+ * This is what keeps the audit at one record per tool call: the wrapper returns a
206
+ * denial from here without ever reaching {@link beforeToolCall}, so that path never
207
+ * sees the call; a call that passes here and is later denied by the same guards
208
+ * inside {@link beforeToolCall} (the mode moved to `plan` while Pre hooks ran) is
209
+ * published there instead. {@link denyRuleGuard} and {@link planGuard} themselves
210
+ * stay pure and unpublished, so calling them directly (tests, other callers)
211
+ * records nothing.
212
+ */
213
+ guardBeforeHooks(event) {
214
+ const { name, input } = event.toolUse;
215
+ const denied = this.earlyDenial(name, input);
216
+ if (denied === undefined)
217
+ return undefined;
218
+ this.publish(event, this.sourceOf(event.agent.id), denied, false);
219
+ return denied.action;
220
+ }
184
221
  /**
185
222
  * Decides one call, restarting whenever the user changes the mode underneath it.
186
223
  *
187
224
  * The loop is the whole in-flight contract: a withdrawn decision is discarded,
188
225
  * never applied, and the call is judged again from the top — plan guard first —
189
- * by whatever mode is in force now.
226
+ * by whatever mode is in force now. Whatever settles it — a pass, or the restart
227
+ * limit — is published exactly once, after it is final.
190
228
  */
191
229
  async beforeToolCall(event) {
192
230
  const promptIdentity = {};
231
+ const audit = { prompted: false };
232
+ // Resolved for every call, not only the ones that prompt: a classifier or a
233
+ // bridge that wants to know whose work it is judging should not have to
234
+ // reconstruct it from the tool input.
235
+ const source = this.sourceOf(event.agent.id);
193
236
  for (let attempt = 1;; attempt += 1) {
194
237
  const withdrawal = new AbortController();
195
238
  this.waiting.add(withdrawal);
196
- let action;
239
+ let settled;
197
240
  try {
198
- action = await this.decideOnce(event, withdrawal.signal, promptIdentity);
241
+ settled = await this.decideOnce(event, source, withdrawal.signal, promptIdentity, audit);
199
242
  }
200
243
  finally {
201
244
  this.waiting.delete(withdrawal);
202
245
  }
203
- if (action !== WITHDRAWN)
204
- return action;
246
+ if (settled !== WITHDRAWN) {
247
+ this.publish(event, source, settled, audit.prompted);
248
+ return settled.action;
249
+ }
205
250
  if (attempt >= MAX_MODE_CHANGE_RESTARTS) {
206
- return InterventionActions.deny(`The permission mode changed ${attempt} times while ${event.toolUse.name} was waiting for a decision, ` +
207
- `so darwin stopped re-asking. Tell the user, and try again once they have settled on a mode.`);
251
+ const limit = {
252
+ outcome: 'restart-limit-denied',
253
+ action: InterventionActions.deny(`The permission mode changed ${attempt} times while ${event.toolUse.name} was waiting for a decision, ` +
254
+ `so darwin stopped re-asking. Tell the user, and try again once they have settled on a mode.`),
255
+ };
256
+ this.publish(event, source, limit, audit.prompted);
257
+ return limit.action;
208
258
  }
209
259
  }
210
260
  }
@@ -216,21 +266,25 @@ export class PermissionGate extends InterventionHandler {
216
266
  * where the answer and the change land in the same tick, which is why the race
217
267
  * re-checks `aborted` after the promise settles.
218
268
  */
219
- async decideOnce(event, withdrawn, promptIdentity) {
220
- // Resolved for every call, not only the ones that prompt: a classifier or a
221
- // bridge that wants to know whose work it is judging should not have to
222
- // reconstruct it from the tool input.
223
- const source = this.sourceOf(event.agent.id);
269
+ async decideOnce(event, source, withdrawn, promptIdentity, audit) {
224
270
  // A `workflow` node's declared write scopes (SER-065) are judged first: they
225
271
  // are a structural fact of the DAG the parent declared, not a confirmation
226
272
  // policy, so they hold in every mode (yolo included), never prompt, and are
227
273
  // not something a rule or a classifier verdict can widen.
228
274
  const scoped = this.writeScopeGuard(event.toolUse.name, event.toolUse.input, source);
229
275
  if (scoped !== undefined)
230
- return scoped;
231
- const guarded = this.planGuard(event.toolUse.name, event.toolUse.input);
232
- if (guarded !== undefined)
233
- return guarded;
276
+ return { action: scoped, outcome: 'write-scope-denied' };
277
+ // A deny-rule (SER-076) is judged next — before the plan guard, before
278
+ // `yolo`, before the static `safe` check, allow-rules and the classifier.
279
+ // It is the one stage a user-written prohibition can win at, so nothing
280
+ // that widens (a mode, a matching allow rule, a verdict, an approval) may
281
+ // run first, and children share the gate so it binds them identically.
282
+ // The plan guard follows. Both are the pair `guardBeforeHooks` already ran
283
+ // for the wrapper; judging them again here is harmless and covers the mode
284
+ // moving while Pre hooks were running.
285
+ const early = this.earlyDenial(event.toolUse.name, event.toolUse.input);
286
+ if (early !== undefined)
287
+ return early;
234
288
  const base = classify(event.toolUse.name, event.toolUse.input);
235
289
  const request = {
236
290
  ...base,
@@ -241,31 +295,46 @@ export class PermissionGate extends InterventionHandler {
241
295
  withdrawn,
242
296
  };
243
297
  if (this.currentMode === 'yolo') {
244
- return InterventionActions.proceed({ reason: 'yolo mode approves everything' });
298
+ return { action: InterventionActions.proceed({ reason: 'yolo mode approves everything' }), outcome: 'yolo' };
245
299
  }
246
300
  if (request.risk === 'safe') {
247
- return InterventionActions.proceed({ reason: request.riskReason });
301
+ return { action: InterventionActions.proceed({ reason: request.riskReason }), outcome: 'safe' };
248
302
  }
249
303
  // Before the classifier, not after: a rule the user wrote down should save the
250
304
  // model call too, not just the prompt.
251
305
  const matched = matchesAnyRule(this.rules, base, this.options.projectRoot);
252
306
  if (matched !== undefined) {
253
- return InterventionActions.proceed({ reason: `allowed by rule ${matched}` });
307
+ return {
308
+ action: InterventionActions.proceed({ reason: `allowed by rule ${matched}` }),
309
+ outcome: 'allow-rule',
310
+ rule: matched,
311
+ };
254
312
  }
255
- if (this.currentMode === 'auto') {
313
+ // A sensitive read (SER-071) skips the classifier: `auto` may only skip the
314
+ // *prompt* for calls a model judges harmless, and whether the user consents
315
+ // to a credential path being read is not that kind of question. Scoped to
316
+ // this one flag — `.env*`/config writes and `memory_save` keep the ordinary
317
+ // auto flow. No `Classifier` row is added, because there was no verdict.
318
+ if (this.currentMode === 'auto' && request.sensitiveRead !== true) {
256
319
  const verdict = await raceWithdrawal(this.classifierVerdict(request), withdrawn);
257
320
  // The verdict answers "may auto mode skip the prompt", so a mode change
258
321
  // makes it moot — discarded, exactly as the peer product documents.
259
322
  if (verdict === WITHDRAWN)
260
323
  return WITHDRAWN;
261
324
  if (verdict.safe) {
262
- return InterventionActions.proceed({ reason: `classifier: ${verdict.reason}` });
325
+ return {
326
+ action: InterventionActions.proceed({ reason: `classifier: ${verdict.reason}` }),
327
+ outcome: 'classifier',
328
+ };
263
329
  }
264
330
  // Escalating to the human: show them why the classifier balked. The details
265
331
  // array is our own copy (classify builds a fresh one per call), so pushing
266
332
  // here cannot leak into other renders of the same tool call.
267
333
  request.details.push({ label: 'Classifier', value: verdict.reason });
268
334
  }
335
+ // Marked before the await, not after: a prompt the user saw and the mode
336
+ // change withdrew was still a prompt.
337
+ audit.prompted = true;
269
338
  const decision = await raceWithdrawal(this.options.ask(request), withdrawn);
270
339
  if (decision === WITHDRAWN)
271
340
  return WITHDRAWN;
@@ -273,15 +342,67 @@ export class PermissionGate extends InterventionHandler {
273
342
  // Only on approval: a rule attached to a refusal would be a contradiction.
274
343
  if (decision.rule !== undefined)
275
344
  this.addAllowRule(decision.rule);
276
- return InterventionActions.proceed({ reason: 'approved by user' });
345
+ return {
346
+ action: InterventionActions.proceed({ reason: 'approved by user' }),
347
+ outcome: 'user-approved',
348
+ ...(decision.rule === undefined ? {} : { rule: decision.rule }),
349
+ };
277
350
  }
278
351
  // deny() rather than confirm(): a rejected confirm reaches the model as
279
352
  // `CONFIRMATION_FAILED: <prompt>`, which models misread as a system failure
280
353
  // and retry. deny() controls the wording, and the SDK turns it into an error
281
354
  // tool result that ends up in history as `DENIED: <reason>`.
282
- return InterventionActions.deny(`The user denied permission to run ${request.toolName}. ` +
283
- `Do not retry it or attempt the same action another way. ` +
284
- `Tell the user what you wanted to do and ask how to proceed.`);
355
+ return {
356
+ outcome: 'user-denied',
357
+ action: InterventionActions.deny(`The user denied permission to run ${request.toolName}. ` +
358
+ `Do not retry it or attempt the same action another way. ` +
359
+ `Tell the user what you wanted to do and ask how to proceed.`),
360
+ };
361
+ }
362
+ /**
363
+ * The deny-rule and plan guards as one settled denial, or undefined when neither
364
+ * applies. Shared by {@link guardBeforeHooks} and {@link decideOnce} so the two
365
+ * cannot disagree about which stage a call fell at.
366
+ */
367
+ earlyDenial(toolName, input) {
368
+ const rule = this.matchedDenyRule(toolName, input);
369
+ if (rule !== undefined)
370
+ return { action: denyRuleAction(rule, toolName), outcome: 'deny-rule', rule };
371
+ const guarded = this.planGuard(toolName, input);
372
+ if (guarded !== undefined)
373
+ return { action: guarded, outcome: 'plan-denied' };
374
+ return undefined;
375
+ }
376
+ /**
377
+ * Hands one settled decision to the observer (SER-079). Publication only: the
378
+ * object is composed from what the gate already knows — never the input — and
379
+ * frozen, and an observer that throws costs nothing but its own record. `kind`
380
+ * and `risk` are re-derived here because the early guards settle a call before
381
+ * the request exists; `classify`/`assessRisk` are pure, so the reading is the one
382
+ * the decision path would have made.
383
+ */
384
+ publish(event, source, settled, promptedUser) {
385
+ const observer = this.options.onDecision;
386
+ if (observer === undefined)
387
+ return;
388
+ try {
389
+ const base = classify(event.toolUse.name, event.toolUse.input);
390
+ const decision = Object.freeze({
391
+ toolUseId: event.toolUse.toolUseId,
392
+ toolName: event.toolUse.name,
393
+ kind: base.kind,
394
+ risk: assessRisk(base, this.options.projectRoot).risk,
395
+ mode: this.currentMode,
396
+ source: source.label,
397
+ outcome: settled.outcome,
398
+ ...(settled.rule === undefined ? {} : { rule: settled.rule }),
399
+ promptedUser,
400
+ });
401
+ observer(decision);
402
+ }
403
+ catch {
404
+ // An observer must never become a second way a decision changes or fails.
405
+ }
285
406
  }
286
407
  /**
287
408
  * Who is asking. A tracked dispatch resolves to its child label; anything else
@@ -300,6 +421,27 @@ export class PermissionGate extends InterventionHandler {
300
421
  ...(dispatch.writeScopes === undefined ? {} : { writeScopes: dispatch.writeScopes }),
301
422
  };
302
423
  }
424
+ /**
425
+ * Denies a call a configured deny-rule forbids (SER-076). Undefined means the
426
+ * ordinary flow owns the call. The reason names the rule so the model can
427
+ * report it precisely, and says in so many words not to retry or route around
428
+ * it: a deny is the user's standing instruction, not a transient failure. The
429
+ * rule text is bounded because it reaches the model verbatim.
430
+ *
431
+ * Public like {@link planGuard} and for the same reason: the hook wrapper runs
432
+ * it before any `PreToolUse` shell, so a forbidden call cannot trigger a policy
433
+ * hook either. Idempotent and side-effect free, so running it twice is safe.
434
+ */
435
+ denyRuleGuard(toolName, input) {
436
+ const rule = this.matchedDenyRule(toolName, input);
437
+ return rule === undefined ? undefined : denyRuleAction(rule, toolName);
438
+ }
439
+ /** The first configured deny-rule the call matches, or undefined. Pure. */
440
+ matchedDenyRule(toolName, input) {
441
+ if (this.denyRuleList.length === 0)
442
+ return undefined;
443
+ return matchesAnyDenyRule(this.denyRuleList, { toolName, input }, this.options.projectRoot);
444
+ }
303
445
  /**
304
446
  * Denies a scoped `workflow` node's `fileEditor` write that lands outside every
305
447
  * declared scope. Undefined means the ordinary flow owns the call — including
@@ -337,6 +479,23 @@ export class PermissionGate extends InterventionHandler {
337
479
  }
338
480
  }
339
481
  }
482
+ /**
483
+ * Longest deny-rule text the model-facing reason carries. A rule is one line the
484
+ * user typed, so this is unreachable in practice; it exists so the error is
485
+ * bounded by construction rather than by an argument about config files.
486
+ */
487
+ const MAX_RULE_REASON_CHARS = 200;
488
+ function clipRule(rule) {
489
+ const chars = [...rule];
490
+ return chars.length <= MAX_RULE_REASON_CHARS ? rule : `${chars.slice(0, MAX_RULE_REASON_CHARS - 1).join('')}…`;
491
+ }
492
+ /** The model-facing denial for a matched deny-rule; wording shared by every caller. */
493
+ function denyRuleAction(rule, toolName) {
494
+ return InterventionActions.deny(`blocked by deny rule ${clipRule(rule)}: the user forbade this ${toolName} call in their ` +
495
+ `project's permission rules, and the rule holds in every permission mode. ` +
496
+ `Do not retry it, and do not attempt the same action another way. ` +
497
+ `Tell the user what you wanted to do and let them decide.`);
498
+ }
340
499
  /**
341
500
  * Resolves with {@link WITHDRAWN} as soon as the mode changes, and — the part that
342
501
  * matters — also when the promise settles in the same tick as the change. A
@@ -635,6 +794,22 @@ const ENV_FILE = /^\.env(\..+)?$/;
635
794
  * — including every unknown and MCP tool.
636
795
  */
637
796
  export function assessRisk(request, projectRoot) {
797
+ // Before the read short-circuit (SER-071): a read into the sensitive set is
798
+ // `dangerous` whatever its kind, so `cat ~/.ssh/id_rsa` (execute) and
799
+ // `fileEditor view ~/.aws/credentials` (read) both reach the prompt. The kind
800
+ // itself is untouched, which is what lets plan mode prompt instead of deny.
801
+ // `sensitive` is the path as the model wrote it, plus a bounded
802
+ // ` (searches above …)` note when a recursive `grep`/`rg` starts from an
803
+ // ancestor of a credential location.
804
+ const sensitive = sensitiveReadPath(request.toolName, request.input, projectRoot);
805
+ if (sensitive !== undefined) {
806
+ const shown = firstLine(sensitive);
807
+ return {
808
+ risk: 'dangerous',
809
+ riskReason: `reads a sensitive path: ${shown.length > SCOPE_PATH_DISPLAY_LIMIT ? `${shown.slice(0, SCOPE_PATH_DISPLAY_LIMIT)}…` : shown}`,
810
+ sensitiveRead: true,
811
+ };
812
+ }
638
813
  if (request.kind === 'read') {
639
814
  return { risk: 'safe', riskReason: `${request.toolName} is read-only` };
640
815
  }