agent-sanitizer 2.68.0 → 2.69.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,7 +25,7 @@ import { readFileSync } from "node:fs";
25
25
  import { relative, resolve } from "node:path";
26
26
  import {
27
27
  awaitLazyDependency,
28
- emitHookResponse,
28
+ createEnvelopeBuffer,
29
29
  safeErrMessage,
30
30
  hookgateMarkerPath,
31
31
  HookEvent,
@@ -38,6 +38,7 @@ import {
38
38
  readStdinJson,
39
39
  } from "./lib/hook-io.mjs";
40
40
  import {
41
+ advisoryParts,
41
42
  registerFaultPolicy,
42
43
  hookFaultOutcome,
43
44
  writeFaultOutcome,
@@ -157,36 +158,67 @@ function faultLine(ctx) {
157
158
  );
158
159
  }
159
160
 
160
- // This hook's entry in the one posture table (lib/hook-fault.mjs). It has no
161
- // stdout verdict channel — SessionStart cannot deny — so BOTH arms are stated
162
- // explicitly rather than taking the shared additionalContext default: the only
163
- // enforcement a SessionStart hook can reach is the cross-hook alert, which makes
164
- // the PreToolUse gate ask once on the next tool call.
161
+ /**
162
+ * The open-posture parts for instruction files the scan could not READ, or null
163
+ * when the fault is anything else.
164
+ * @param {import("./lib/hook-fault.mjs").FaultContext} ctx
165
+ * @returns {import("./lib/hook-fault.mjs").FaultParts | null}
166
+ */
167
+ function openGapParts(ctx) {
168
+ if (ctx.gapNotice === undefined) return null;
169
+ return advisoryParts(
170
+ HookEvent.SESSION_START,
171
+ `${ctx.gapNotice}\n${HOOK_NAME}: failing open — nothing is blocked. Set ` +
172
+ "AGENT_SANITIZER_FAIL_OPEN=0 to have the next tool call ask instead.",
173
+ );
174
+ }
175
+
176
+ // This hook's entry in the one posture table (lib/hook-fault.mjs). SessionStart
177
+ // cannot deny, so the only enforcement either arm can reach is the cross-hook
178
+ // alert, which makes the PreToolUse gate ask once on the next tool call — and
179
+ // only the CLOSED arm arms it. An unreadable instruction file (`gapNotice`) is
180
+ // rendered here too: the scan worked, but whether a gap may stop the session is
181
+ // the same operator choice a fault is.
165
182
  registerFaultPolicy(HOOK_NAME, {
166
183
  event: HookEvent.SESSION_START,
167
184
  guarded: "instruction files",
168
- open: (ctx) => ({
169
- stderr: `${faultLine(ctx)} Passing through unguarded; set AGENT_SANITIZER_FAIL_OPEN=0 to arm the tool-call gate instead.\n`,
170
- exitCode: 1,
171
- }),
185
+ open: (ctx) =>
186
+ openGapParts(ctx) ??
187
+ advisoryParts(
188
+ HookEvent.SESSION_START,
189
+ `${faultLine(ctx)} Passing through unguarded; set AGENT_SANITIZER_FAIL_OPEN=0 to arm the tool-call gate instead.`,
190
+ ),
172
191
  closed: (ctx) => ({
173
- stderr: `${faultLine(ctx)} Arming the tool-call gate (AGENT_SANITIZER_FAIL_OPEN=0).\n`,
174
- exitCode: 1,
192
+ ...advisoryParts(
193
+ HookEvent.SESSION_START,
194
+ ctx.gapNotice === undefined
195
+ ? `${faultLine(ctx)} Arming the tool-call gate (AGENT_SANITIZER_FAIL_OPEN=0).`
196
+ : `${ctx.gapNotice}\n${HOOK_NAME}: the next tool call asks first (AGENT_SANITIZER_FAIL_OPEN=0).`,
197
+ ),
175
198
  armAlert: true,
176
199
  }),
177
200
  });
178
201
 
179
202
  /**
180
- * Render this hook's fault under the declared posture, and return the text (if
181
- * any) that must ride in the cross-hook alert so a later gate carries the
182
- * posture this hook cannot express itself.
203
+ * Render this hook's fault (or, with `gapNotice`, its unreadable-file report)
204
+ * under the declared posture, and return the text (if any) that must ride in
205
+ * the cross-hook alert so a later gate carries the posture this hook cannot
206
+ * express itself.
183
207
  * @param {unknown} err
208
+ * @param {string | undefined} gapNotice the {@link formatSkipped} report
209
+ * @param {import("./lib/hook-io.mjs").EnvelopeBuffer} out this run's one stdout
210
+ * buffer
184
211
  * @returns {string[]}
185
212
  */
186
- function reportFault(err) {
187
- const outcome = hookFaultOutcome(HOOK_NAME, err);
188
- process.exitCode = writeFaultOutcome(outcome);
189
- return outcome.armAlert ? [/** @type {string} */ (outcome.stderr)] : [];
213
+ function reportFault(err, gapNotice, out) {
214
+ const outcome = hookFaultOutcome(HOOK_NAME, err, { gapNotice });
215
+ // Buffered, not written: the timing wrapper may still owe stdout a slow-hook
216
+ // notice, and two envelopes on one stdout are invalid hook output.
217
+ process.exitCode = writeFaultOutcome(outcome, (chunk) =>
218
+ out.add(JSON.parse(chunk)),
219
+ );
220
+ if (!outcome.armAlert) return [];
221
+ return [gapNotice ?? /** @type {string} */ (outcome.stderr)];
190
222
  }
191
223
 
192
224
  /**
@@ -331,9 +363,9 @@ export function scanProject(dir = PROJECT_DIR) {
331
363
  }
332
364
 
333
365
  /**
334
- * The report for targets the scan could not read. Rendered into the alert the
335
- * PreToolUse gate surfaces, so an incomplete scan reaches the operator as a
336
- * checkpoint rather than as silence.
366
+ * The report for targets the scan could not read: a SessionStart warning under
367
+ * the open posture, and the alert the PreToolUse gate surfaces under the closed
368
+ * one — either way an incomplete scan reaches the operator rather than silence.
337
369
  * @param {Array<{file: string, reason: string}>} skipped
338
370
  * @returns {string}
339
371
  */
@@ -383,12 +415,15 @@ export async function cliMain(opts = {}) {
383
415
  // reporting an overrun in band is what turned a 30-second scan from a rumor
384
416
  // into a bug report (see lib/hook-timing.mjs).
385
417
  const timer = startHookTimer();
418
+ // One stdout document per run: the scan's own envelope (a fault or the
419
+ // unreadable-file notice) and the slow-hook notice below fold into it.
420
+ const out = createEnvelopeBuffer();
386
421
  try {
387
422
  // Charged to provisioning when the session's setup is installing THROUGHOUT
388
423
  // this run: that install saturates the machine, and a scan that merely
389
424
  // waited it out has no per-call cost to report (see hook-timing.mjs).
390
425
  await excludeConcurrentProvisioning(
391
- () => runScanCli(opts),
426
+ () => runScanCli(opts, out),
392
427
  () => setupRunning(hookgateMarkerPath()),
393
428
  );
394
429
  } finally {
@@ -396,7 +431,7 @@ export async function cliMain(opts = {}) {
396
431
  HOOK_NAME,
397
432
  timer.wallMs(),
398
433
  HookEvent.SESSION_START,
399
- emitHookResponse,
434
+ out.emit,
400
435
  undefined,
401
436
  // All four windows, including the two this scan normally leaves empty: a
402
437
  // measured 0 rules a window OUT, where an omitted one leaves the notice
@@ -407,6 +442,7 @@ export async function cliMain(opts = {}) {
407
442
  hostMs: timer.hostMs(),
408
443
  },
409
444
  );
445
+ out.flush();
410
446
  }
411
447
  }
412
448
 
@@ -419,9 +455,10 @@ export async function cliMain(opts = {}) {
419
455
  * scan?: () => ReturnType<typeof scanProject>,
420
456
  * sessionId?: string,
421
457
  * }} opts see {@link cliMain}
458
+ * @param {import("./lib/hook-io.mjs").EnvelopeBuffer} out see {@link cliMain}
422
459
  * @returns {Promise<void>}
423
460
  */
424
- async function runScanCli({ trace: sink, scan: runScan, sessionId }) {
461
+ async function runScanCli({ trace: sink, scan: runScan, sessionId }, out) {
425
462
  // Bound best-effort: the announcements below run BEFORE the auto-clean and
426
463
  // the alert write, with no catch above them, so a throwing host sink would
427
464
  // abort the scan silently (see hookTrace).
@@ -452,24 +489,19 @@ async function runScanCli({ trace: sink, scan: runScan, sessionId }) {
452
489
  "agent-sanitizer failed to load (node deps not installed and " +
453
490
  "session-setup did not finish in time); run `pnpm install`",
454
491
  ),
492
+ undefined,
493
+ out,
455
494
  ),
456
495
  );
457
496
  persistAlert(alertParts, sessionId);
458
- process.exit(1);
497
+ // process.exit skips cliMain's `finally`, which would otherwise flush. No
498
+ // code: the exit is the one reportFault set from the posture table.
499
+ out.flush();
500
+ process.exit();
459
501
  }
460
502
  /* c8 ignore stop */
461
503
 
462
- // No clear: the store is session-keyed, so this session starts empty by
463
- // construction and cannot inherit a previous session's ack. Age out what past
464
- // sessions left instead — SessionStart is the once-per-session touchpoint the
465
- // sweep belongs on.
466
- sweepStaleSessions(sessionId);
467
- // The other two stores these hooks own (reveal under STATE_ROOT, confirm in
468
- // $TMPDIR). Both are content- or fingerprint-addressed with no natural owner
469
- // to delete them, so without a sweep they grow for the life of the machine;
470
- // SessionStart is the only touchpoint that runs once per session.
471
- sweepStaleReveals();
472
- sweepStaleConfirms();
504
+ sweepStaleStores(sessionId);
473
505
 
474
506
  // Only a non-errno throw reaches here — a bug in the scanner, not a file it
475
507
  // could not read (those are accounted for in `skipped`). It is a fault of THIS
@@ -480,14 +512,14 @@ async function runScanCli({ trace: sink, scan: runScan, sessionId }) {
480
512
  scan = (runScan ?? scanProject)();
481
513
  } catch (err) {
482
514
  emitTrace(TraceEvent.SCAN_INVISIBLE_CHARS_RAN, { outcome: "skipped" });
483
- alertParts.push(...reportFault(err));
515
+ alertParts.push(...reportFault(err, undefined, out));
484
516
  persistAlert(alertParts, sessionId);
485
517
  return;
486
518
  }
487
519
  const { findings: allFindings, skipped, absent, scanned } = scan;
488
520
 
489
521
  // The three buckets of classifyReadFailure, rendered: only `skipped` may
490
- // withhold "clean" and arm the gate.
522
+ // withhold "clean", and it arms the gate only under the closed posture.
491
523
  if (skipped.length > 0) {
492
524
  emitTrace(TraceEvent.SCAN_INVISIBLE_CHARS_RAN, {
493
525
  outcome: "partial",
@@ -496,9 +528,13 @@ async function runScanCli({ trace: sink, scan: runScan, sessionId }) {
496
528
  absent: absent.length,
497
529
  files: allFindings.length,
498
530
  });
499
- const notice = formatSkipped(skipped);
500
- process.stderr.write(notice + "\n");
501
- alertParts.push(notice);
531
+ alertParts.push(
532
+ ...reportFault(
533
+ new Error(`${skipped.length} instruction file(s) could not be read`),
534
+ formatSkipped(skipped),
535
+ out,
536
+ ),
537
+ );
502
538
  } else if (allFindings.length === 0) {
503
539
  emitTrace(TraceEvent.SCAN_INVISIBLE_CHARS_RAN, {
504
540
  outcome: "clean",
@@ -518,6 +554,46 @@ async function runScanCli({ trace: sink, scan: runScan, sessionId }) {
518
554
  persistAlert(alertParts, sessionId);
519
555
  }
520
556
 
557
+ /**
558
+ * Age out what past sessions left in the three stores these hooks own: the
559
+ * session-keyed alert store, and the reveal and confirm stores, which are
560
+ * content- or fingerprint-addressed with no natural owner to delete them.
561
+ * SessionStart is the one touchpoint that runs once per session. The alert
562
+ * store needs no clear: it is session-keyed, so this session starts empty and
563
+ * cannot inherit a past session's ack.
564
+ *
565
+ * An I/O error here is reported and the scan still runs. A sweep that fails
566
+ * leaves stale files behind and costs no coverage, but a throw would abort the
567
+ * scan before the posture table sees it: the bundle dies, and under
568
+ * AGENT_SANITIZER_FAIL_OPEN=0 nothing arms the gate. A non-errno throw is a bug
569
+ * in the sweep and propagates.
570
+ * @param {string} [sessionId]
571
+ * @returns {void}
572
+ */
573
+ function sweepStaleStores(sessionId) {
574
+ /** @type {string[]} */
575
+ const failed = [];
576
+ for (const sweep of [
577
+ () => sweepStaleSessions(sessionId),
578
+ sweepStaleReveals,
579
+ sweepStaleConfirms,
580
+ ]) {
581
+ try {
582
+ sweep();
583
+ } catch (err) {
584
+ const code = /** @type {NodeJS.ErrnoException} */ (err).code;
585
+ if (typeof code !== "string") throw err;
586
+ failed.push(code);
587
+ }
588
+ }
589
+ if (failed.length === 0) return;
590
+ // errno codes only: the error messages embed paths under a shared $TMPDIR.
591
+ const codes = [...new Set(failed)].join(", ");
592
+ process.stderr.write(
593
+ `${HOOK_NAME}: could not age out stale session state (${codes}); scanning anyway.\n`,
594
+ );
595
+ }
596
+
521
597
  /**
522
598
  * Auto-clean the contaminated files so the session proceeds without blocking
523
599
  * every tool call, and return the alert text for whatever could not be cleaned
@@ -19,7 +19,7 @@
19
19
  */
20
20
  import { readFileSync } from "node:fs";
21
21
  import {
22
- emitHookResponse,
22
+ createEnvelopeBuffer,
23
23
  EmptyStdinError,
24
24
  hookgateMarkerPath,
25
25
  HookEvent,
@@ -31,6 +31,7 @@ import {
31
31
  setupRunning,
32
32
  } from "./lib/hook-io.mjs";
33
33
  import {
34
+ advisoryParts,
34
35
  registerFaultPolicy,
35
36
  hookFaultOutcome,
36
37
  writeFaultOutcome,
@@ -104,18 +105,17 @@ function faultLine(ctx) {
104
105
  */
105
106
  function emptyPayloadParts(ctx) {
106
107
  if (!(ctx.err instanceof EmptyStdinError)) return null;
107
- return {
108
- stderr:
109
- `${HOOK_NAME} hook error: ${ctx.message}. No instruction file was named, so nothing ` +
108
+ return advisoryParts(
109
+ HookEvent.INSTRUCTIONS_LOADED,
110
+ `${HOOK_NAME} hook error: ${ctx.message}. No instruction file was named, so nothing ` +
110
111
  "was scanned and nothing was left unguarded. Check how this hook is invoked: it reads " +
111
112
  "its InstructionsLoaded event as JSON on stdin, and one wired to a channel that " +
112
- "delivers nothing scans nothing for the whole session.\n",
113
- exitCode: 1,
114
- };
113
+ "delivers nothing scans nothing for the whole session.",
114
+ );
115
115
  }
116
116
 
117
117
  // This hook's entry in the one posture table (lib/hook-fault.mjs). Like
118
- // scan-invisible-chars it has no stdout verdict channel — InstructionsLoaded
118
+ // scan-invisible-chars it has no verdict to give — InstructionsLoaded
119
119
  // cannot block, and its exit code is ignored — so both arms are stated
120
120
  // explicitly and the only enforcement either can reach is the cross-hook alert,
121
121
  // which makes the PreToolUse gate ask once on the next tool call.
@@ -123,14 +123,17 @@ registerFaultPolicy(HOOK_NAME, {
123
123
  event: HookEvent.INSTRUCTIONS_LOADED,
124
124
  guarded: "a loaded instruction file",
125
125
  open: (ctx) =>
126
- emptyPayloadParts(ctx) ?? {
127
- stderr: `${faultLine(ctx)} Passing through unguarded; set AGENT_SANITIZER_FAIL_OPEN=0 to arm the tool-call gate instead.\n`,
128
- exitCode: 1,
129
- },
126
+ emptyPayloadParts(ctx) ??
127
+ advisoryParts(
128
+ HookEvent.INSTRUCTIONS_LOADED,
129
+ `${faultLine(ctx)} Passing through unguarded; set AGENT_SANITIZER_FAIL_OPEN=0 to arm the tool-call gate instead.`,
130
+ ),
130
131
  closed: (ctx) =>
131
132
  emptyPayloadParts(ctx) ?? {
132
- stderr: `${faultLine(ctx)} Arming the tool-call gate (AGENT_SANITIZER_FAIL_OPEN=0).\n`,
133
- exitCode: 1,
133
+ ...advisoryParts(
134
+ HookEvent.INSTRUCTIONS_LOADED,
135
+ `${faultLine(ctx)} Arming the tool-call gate (AGENT_SANITIZER_FAIL_OPEN=0).`,
136
+ ),
134
137
  armAlert: true,
135
138
  },
136
139
  });
@@ -268,12 +271,15 @@ export { HOOK_NAME };
268
271
  export async function cliMain({ trace: sink } = {}) {
269
272
  const timer = startHookTimer();
270
273
  const emitTrace = hookTrace(sink);
274
+ // One stdout document per run: the finding/fault envelope and the slow-hook
275
+ // notice below fold into it, never written as two.
276
+ const out = createEnvelopeBuffer();
271
277
  try {
272
278
  // Charged to provisioning when the session's setup is installing THROUGHOUT
273
279
  // this run: that install saturates the machine, and a scan that merely
274
280
  // waited it out has no per-call cost to report (see hook-timing.mjs).
275
281
  await excludeConcurrentProvisioning(
276
- () => runLoadedScanCli(emitTrace),
282
+ () => runLoadedScanCli(emitTrace, out),
277
283
  () => setupRunning(hookgateMarkerPath()),
278
284
  );
279
285
  } finally {
@@ -281,7 +287,7 @@ export async function cliMain({ trace: sink } = {}) {
281
287
  HOOK_NAME,
282
288
  timer.wallMs(),
283
289
  HookEvent.INSTRUCTIONS_LOADED,
284
- emitHookResponse,
290
+ out.emit,
285
291
  undefined,
286
292
  // All four windows, including the two this scan normally leaves empty: a
287
293
  // measured 0 rules a window OUT, where an omitted one leaves the notice
@@ -292,6 +298,7 @@ export async function cliMain({ trace: sink } = {}) {
292
298
  hostMs: timer.hostMs(),
293
299
  },
294
300
  );
301
+ out.flush();
295
302
  }
296
303
  }
297
304
 
@@ -300,9 +307,11 @@ export async function cliMain({ trace: sink } = {}) {
300
307
  * single call to bracket — every early return here is an exit that wrapper must
301
308
  * still measure.
302
309
  * @param {import("./lib/trace.mjs").TraceFn} emitTrace
310
+ * @param {import("./lib/hook-io.mjs").EnvelopeBuffer} out this run's one stdout
311
+ * buffer
303
312
  * @returns {Promise<void>}
304
313
  */
305
- async function runLoadedScanCli(emitTrace) {
314
+ async function runLoadedScanCli(emitTrace, out) {
306
315
  /** @type {string | undefined} */
307
316
  let sessionId;
308
317
  try {
@@ -340,19 +349,19 @@ async function runLoadedScanCli(emitTrace) {
340
349
  // systemMessage reaches the user, additionalContext the model. Both, because
341
350
  // this hook cannot block and the file is already loaded: the user is the one
342
351
  // who can act on it, and the model is the one currently reading it.
343
- process.stdout.write(
344
- JSON.stringify({
345
- systemMessage: message,
346
- hookSpecificOutput: {
347
- hookEventName: HookEvent.INSTRUCTIONS_LOADED,
348
- additionalContext: message,
349
- },
350
- }),
351
- );
352
+ out.add({
353
+ systemMessage: message,
354
+ hookSpecificOutput: {
355
+ hookEventName: HookEvent.INSTRUCTIONS_LOADED,
356
+ additionalContext: message,
357
+ },
358
+ });
352
359
  } catch (err) {
353
360
  emitTrace(TraceEvent.SCAN_LOADED_INSTRUCTIONS_RAN, { outcome: "skipped" });
354
361
  const outcome = hookFaultOutcome(HOOK_NAME, err);
355
- process.exitCode = writeFaultOutcome(outcome);
362
+ process.exitCode = writeFaultOutcome(outcome, (chunk) =>
363
+ out.add(JSON.parse(chunk)),
364
+ );
356
365
  // `sessionId`, captured before the throw: a payload read that itself failed
357
366
  // leaves it undefined, and the fault then lands in the shared fallback store
358
367
  // rather than in no store at all.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-sanitizer",
3
- "version": "2.68.0",
3
+ "version": "2.69.1",
4
4
  "description": "Defend an agent against hidden-content injection: strip payload-capable invisible Unicode and ANSI, splice out human-invisible HTML, and flag data-exfil URLs in untrusted text before any model sees it.",
5
5
  "type": "module",
6
6
  "repository": {
package/src/html.mjs CHANGED
@@ -1592,16 +1592,17 @@ function isSelfClosedForeign(tagName, value) {
1592
1592
  // under fragment parsing (scripting disabled) parse5 parses its content as
1593
1593
  // normal markup, so scanning it is correct. Once `plaintext` opens it runs to
1594
1594
  // EOF and never closes.
1595
- const RAW_TEXT_ELEMENTS = new Set([
1596
- "script",
1597
- "style",
1598
- "textarea",
1599
- "title",
1600
- "xmp",
1601
- "iframe",
1602
- "noembed",
1603
- "noframes",
1604
- "plaintext",
1595
+ // Each end-tag matcher is spelled per tag, so none compiles a document's text.
1596
+ const RAW_TEXT_END_TAGS = new Map([
1597
+ ["script", /<\/script(?![a-z0-9-])/i],
1598
+ ["style", /<\/style(?![a-z0-9-])/i],
1599
+ ["textarea", /<\/textarea(?![a-z0-9-])/i],
1600
+ ["title", /<\/title(?![a-z0-9-])/i],
1601
+ ["xmp", /<\/xmp(?![a-z0-9-])/i],
1602
+ ["iframe", /<\/iframe(?![a-z0-9-])/i],
1603
+ ["noembed", /<\/noembed(?![a-z0-9-])/i],
1604
+ ["noframes", /<\/noframes(?![a-z0-9-])/i],
1605
+ ["plaintext", /<\/plaintext(?![a-z0-9-])/i],
1605
1606
  ]);
1606
1607
 
1607
1608
  // Keywords that take the parent's value of an inherited property: `revert`
@@ -2608,9 +2609,9 @@ function scanInlineChildren(node, text, ranges, warned) {
2608
2609
  // "Inside an unterminated tag / bogus comment" — parse5 absorbs following
2609
2610
  // markup into it until the next `>`.
2610
2611
  let absorbing = false;
2611
- // Non-null while inside a raw-text element (its lowercased tag name); content
2612
- // is opaque until the matching end tag.
2613
- let rawText = /** @type {string | null} */ (null);
2612
+ // Non-null while inside a raw-text element (the matcher for its end tag);
2613
+ // content is opaque until that end tag.
2614
+ let rawTextEnd = /** @type {RegExp | null} */ (null);
2614
2615
  // End offset of the last html node processed; the raw slice from here to the
2615
2616
  // next html node is what parse5 tokenizes between them.
2616
2617
  let prevEnd = node.position.start.offset;
@@ -2622,10 +2623,9 @@ function scanInlineChildren(node, text, ranges, warned) {
2622
2623
  // into the absorb state before deciding what to do with this html node.
2623
2624
  absorbing = foldAbsorb(absorbing, text.slice(prevEnd, base));
2624
2625
 
2625
- if (rawText) {
2626
+ if (rawTextEnd) {
2626
2627
  // Raw-text content is opaque; only the matching end tag ends the region.
2627
- if (new RegExp(`</${rawText}(?![a-z0-9-])`, "i").test(value))
2628
- rawText = null;
2628
+ if (rawTextEnd.test(value)) rawTextEnd = null;
2629
2629
  } else if (state.depth > 0) {
2630
2630
  updateHiddenState(state, value, end, ranges);
2631
2631
  } else if (!absorbing) {
@@ -2655,7 +2655,7 @@ function scanInlineChildren(node, text, ranges, warned) {
2655
2655
  if (el) {
2656
2656
  // A raw-text open tag starts an opaque region (a self-closing `/>`
2657
2657
  // does not apply to these in HTML — they always open).
2658
- if (RAW_TEXT_ELEMENTS.has(el.tagName)) rawText = el.tagName;
2658
+ rawTextEnd = RAW_TEXT_END_TAGS.get(el.tagName) ?? null;
2659
2659
  // `el` is one tag parsed alone, so a `<template>` inside an inline
2660
2660
  // `<svg>`/`<math>` reads as HTML here and is reported, where the
2661
2661
  // source branch, which sees the namespace, does not: this errs toward
package/src/output.mjs CHANGED
@@ -365,8 +365,9 @@ function processLayer1(text, sgrCarveOut) {
365
365
  * Refuse to START a parse with no budget left. Each of Layers 2/3 parses the
366
366
  * whole document in ONE synchronous call, so nothing interrupts it, and a host
367
367
  * that kills the overrun hook shows the RAW text. Called before EACH parse, and
368
- * only after a pre-gate passed, so a declined call costs no time. Fails closed,
369
- * as Layer 4 does.
368
+ * only after a pre-gate passed, so a declined call costs no time. Throws, as
369
+ * Layer 4 does: whether the unchecked text then passes or is withheld is the
370
+ * caller's fault posture, never this layer's.
370
371
  * @param {Deadline | undefined} deadline
371
372
  * @returns {void}
372
373
  */
@@ -374,8 +375,8 @@ function refuseIfSpent(deadline) {
374
375
  if (deadline && deadline.remainingMs() <= 0)
375
376
  throw new Error(
376
377
  "CRITICAL: the sanitization time budget ran out before the hidden-HTML " +
377
- "and exfil-URL layers finished, so this text was not fully checked. " +
378
- "Failing closed — tool output suppressed.",
378
+ "and exfil-URL layers finished, so this text was not fully checked " +
379
+ "and must be treated as UNSANITIZED.",
379
380
  );
380
381
  }
381
382
 
package/src/rehydrate.mjs CHANGED
@@ -823,6 +823,12 @@ function isCandidate(tool, ti) {
823
823
  * there is nothing to do. Throws only on internal error (the caller fails
824
824
  * closed).
825
825
  *
826
+ * A deny carrying `fault` is not a verdict on the input but this module being
827
+ * unable to do its job (an unreadable target, a redactor map that fails
828
+ * validation): `fault` states what proceeding un-rehydrated would write, and the
829
+ * caller's failure posture decides whether the deny stands. A deny without it
830
+ * is a verdict and stands in every posture.
831
+ *
826
832
  * `io` is the injected I/O (file read + redactor map/plain). `hint` is the
827
833
  * redaction-placeholder prefix (defaults to {@link DEFAULT_HINT}); override it
828
834
  * only if the injected redactor emits a different placeholder shape.
@@ -830,7 +836,7 @@ function isCandidate(tool, ti) {
830
836
  * @param {any} toolInput
831
837
  * @param {RehydrateIo} io
832
838
  * @param {{ hint?: string }} [options]
833
- * @returns {Promise<{updatedInput: any, context: string} | {deny: string} | null>}
839
+ * @returns {Promise<{updatedInput: any, context: string} | {deny: string, fault?: string} | null>}
834
840
  */
835
841
  export async function rehydrateRedacted(
836
842
  tool,
@@ -911,12 +917,17 @@ export async function rehydrateRedacted(
911
917
  if (tool !== "Write") throw err;
912
918
  return null;
913
919
  }
920
+ const cause = nodeErr?.code ?? nodeErr?.message;
914
921
  return {
915
922
  deny:
916
923
  `could not read ${toolInput.file_path} to rehydrate its secrets ` +
917
- `(${nodeErr?.code ?? nodeErr?.message}); the file likely still exists, so writing ` +
924
+ `(${cause}); the file likely still exists, so writing ` +
918
925
  `the placeholder text as-is risks overwriting a real secret. Retry the read, or ` +
919
926
  `ask the user to make this change directly`,
927
+ fault:
928
+ `${toolInput.file_path} could not be read (${cause}) to rehydrate its ` +
929
+ `secrets, so this call is not rehydrated and its ${hint}…] placeholder ` +
930
+ `text is written to the file literally`,
920
931
  };
921
932
  }
922
933
  const { layer1Cleaned, cleaned } = layer1View(content);
@@ -949,8 +960,14 @@ export async function rehydrateRedacted(
949
960
  // reaches its own resolver-backed pass-through.
950
961
  if (tool === "MultiEdit") return multiEditDeny(toolInput.file_path);
951
962
  if (!hinted) return null;
963
+ // A verdict, not a fault: the file itself defeats mapping on every call, so
964
+ // a released re-issue would overwrite the real secret with its placeholder.
965
+ // The escape is to stop writing the placeholder, which the reason names.
952
966
  return {
953
- deny: `cannot resolve redaction placeholders in ${toolInput.file_path}: ${mapped.unmappable}`,
967
+ deny:
968
+ `cannot resolve redaction placeholders in ${toolInput.file_path}: ` +
969
+ `${mapped.unmappable}. Leave every ${hint}…] placeholder out of this ` +
970
+ `call (edit around it), or ask the user to make this change`,
954
971
  };
955
972
  }
956
973
  // The redactor emits code-point offsets; the offset machinery below works in
@@ -970,9 +987,8 @@ export async function rehydrateRedacted(
970
987
  // before acting: construction re-checks range/ordering (the throws in
971
988
  // assertPairsOrdered and pairsToUtf16), viewMapDefect proves the view
972
989
  // reconstructs `cleaned` exactly. A defective map DENIES for every tool and
973
- // hint state, and is deliberately NOT allowed to throw out of this module: a
974
- // throw lands in the host's failure posture, whose shipped default is fail
975
- // OPEN, i.e. the unsanitized placeholder write this module exists to prevent.
990
+ // hint state with a `fault`, never a throw: the deny lets the caller refuse
991
+ // the call once and name what proceeding writes, which a throw cannot.
976
992
  let view = null;
977
993
  let mapDefect = null;
978
994
  try {
@@ -993,14 +1009,25 @@ export async function rehydrateRedacted(
993
1009
  // Reaching this line at all means the fast pass-through did not fire — the
994
1010
  // file provably holds redacted content or diverges from its view — so an
995
1011
  // unhinted pass-through here would hand the real Edit bytes inside spans
996
- // nothing can vet (the R1 hidden-span oracle). Deny everything until the
997
- // redactor is fixed.
1012
+ // nothing can vet (the R1 hidden-span oracle). Deny, as a fault: the
1013
+ // engine, not the input, is what is wrong.
998
1014
  if (tool === "MultiEdit") return multiEditDeny(toolInput.file_path);
1015
+ // A Write replaces the whole file, and the secret-drop guard reads this
1016
+ // same broken map, so the loss it would name has to be named here instead.
1017
+ const dropped =
1018
+ tool === "Write"
1019
+ ? `; it replaces the whole file, so any redacted secret it does not ` +
1020
+ `reproduce is removed, and which secrets those are cannot be checked`
1021
+ : "";
999
1022
  return {
1000
1023
  deny:
1001
1024
  `cannot safely edit ${toolInput.file_path}: ${mapDefect}; the file holds ` +
1002
1025
  `redacted content whose location cannot be trusted, so no edit can be ` +
1003
- `verified. Retry later, or ask the user to make this change`,
1026
+ `verified${dropped}. Retry later, or ask the user to make this change`,
1027
+ fault:
1028
+ `${mapDefect} for ${toolInput.file_path}, so this call is not ` +
1029
+ `rehydrated: any ${hint}…] placeholder text in it is written to the ` +
1030
+ `file literally, and it is applied without the redacted-span checks${dropped}`,
1004
1031
  };
1005
1032
  }
1006
1033
  // View identical to disk: any placeholders in an Edit's old_string are
@@ -29,6 +29,18 @@ export function faultPolicy(hook: string): FaultPolicy;
29
29
  * @returns {FaultParts}
30
30
  */
31
31
  export function defaultOpen(ctx: FaultContext): FaultParts;
32
+ /**
33
+ * The parts of a warning for an event that cannot block (SessionStart,
34
+ * InstructionsLoaded): `text` goes to the operator's stderr, the user
35
+ * (`systemMessage`) and the model (`additionalContext`), and the hook exits 0.
36
+ * Exit 0 because the hook ran and reached its answer. A non-zero exit with no
37
+ * envelope reads to the launcher as a bundle that died, which it reports as
38
+ * "reinstall the plugin".
39
+ * @param {string} event the hook's event name
40
+ * @param {string} text
41
+ * @returns {FaultParts}
42
+ */
43
+ export function advisoryParts(event: string, text: string): FaultParts;
32
44
  /**
33
45
  * Resolve `hook`'s response to its own failure under the caller's posture. This
34
46
  * is the ONLY place {@link failOpenEnabled} is consulted on a hook fault, so the
@@ -110,8 +122,10 @@ export type FaultContext = Record<string, any> & {
110
122
  /**
111
123
  * A hook's declared posture. There is deliberately no way for a policy to pin
112
124
  * the CLOSED arm: AGENT_SANITIZER_FAIL_OPEN alone decides, so no hook fault can
113
- * withhold a tool output or block a prompt unless the operator set the knob to
114
- * `0`. A pin turns any bug in the guarded layer into every tool call failing.
125
+ * withhold a tool output, block a prompt, or hold a tool call for good unless the
126
+ * operator set the knob to `0` (an open arm may refuse a call once, releasing the
127
+ * exact re-issue). A pin turns any bug in the guarded layer into every tool call
128
+ * failing.
115
129
  */
116
130
  export type FaultPolicy = {
117
131
  event: string | null;