@reticlehq/engine 3.8.0 → 3.8.2

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.
@@ -197,8 +197,13 @@ function appliedAfter(events, loser, all) {
197
197
  // A reaction belongs to the completion nearest it. The slack lets a render stamped a moment
198
198
  // early count, and so it also took in the NEWER response's own render landing just before the
199
199
  // loser: a correct app that dropped the loser was accused (seen intermittently on a bench twin).
200
+ // It also belongs to a request being ISSUED nearer it: an action's own write ("loading", the
201
+ // requested value) lands with its request, and a fast burst of clicks puts the next one a few
202
+ // ms after a slow loser lands (seen 1 run in 2 on a correctly guarded quote desk).
200
203
  const own = Math.abs(event.t - settledAt);
201
- return reacts && !all.some((f) => f.id !== loser.id && Math.abs(event.t - f.settledAt) < own);
204
+ return (reacts &&
205
+ !all.some((f) => f.id !== loser.id &&
206
+ (Math.abs(event.t - f.settledAt) < own || Math.abs(event.t - f.issuedAt) < own)));
202
207
  });
203
208
  }
204
209
  export function findStaleResponses(events) {
@@ -13,6 +13,7 @@
13
13
  * does not check whether it applies. A wrong remedy is worse than none, because it is followed.
14
14
  */
15
15
  import { skippedBodyRemedy } from '../question/predicate/predicate-eval.js';
16
+ import { BODY_CAPTURE_DEFAULTS } from '../question/predicate/predicate-request-body.js';
16
17
  /** The earliest SDK release whose observer can capture network bodies at all. */
17
18
  export const BODY_CAPTURE_MIN_VERSION = '2.4.0';
18
19
  /**
@@ -39,7 +40,8 @@ function isAtLeast(version, minimum) {
39
40
  return true;
40
41
  }
41
42
  /** The sentence naming the setting — only ever produced for an SDK that HAS it. */
42
- const ENABLE_IT = 'Turn it on where your app calls connect(): `reticle.connect({ captureNetworkBodies: true })`, ' +
43
+ const ENABLE_IT = `${BODY_CAPTURE_DEFAULTS} ` +
44
+ 'Turn it on where your app calls connect(): `reticle.connect({ captureNetworkBodies: true })`, ' +
43
45
  'or for the Vite plugin `reticle({ captureNetworkBodies: true })` / VITE_RETICLE_CAPTURE_BODIES=1. ' +
44
46
  'Before bodies are kept, built-in rules redact keys such as `password`, `apiKey` and ' +
45
47
  '`authorization`, selected token keys, and known secret shapes. Other credential fields may ' +
@@ -0,0 +1,19 @@
1
+ import type { EvalResult } from './question/predicate/predicate-eval-kit.js';
2
+ /**
3
+ * Exact cardinality, once, for every channel that can count its matches.
4
+ *
5
+ * `net` and `signal` are the same assertion over different evidence — "this happened EXACTLY n
6
+ * times" — and the interesting half is the same on both: an over-count is `decided`, because a
7
+ * window only accumulates and a count cannot come back down, so waiting out the rest of the budget
8
+ * to report a double-fire buys nothing but latency.
9
+ *
10
+ * `noun` names the population in prose ("network call(s)", "signal(s)"), `filter` is the matcher as
11
+ * applied, and `assertion` is the oracle that judged it.
12
+ */
13
+ export declare function evalExactCount(args: {
14
+ matched: number;
15
+ want: number;
16
+ noun: string;
17
+ filter: string;
18
+ assertion: string;
19
+ }): EvalResult;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Exact cardinality, once, for every channel that can count its matches.
3
+ *
4
+ * `net` and `signal` are the same assertion over different evidence — "this happened EXACTLY n
5
+ * times" — and the interesting half is the same on both: an over-count is `decided`, because a
6
+ * window only accumulates and a count cannot come back down, so waiting out the rest of the budget
7
+ * to report a double-fire buys nothing but latency.
8
+ *
9
+ * `noun` names the population in prose ("network call(s)", "signal(s)"), `filter` is the matcher as
10
+ * applied, and `assertion` is the oracle that judged it.
11
+ */
12
+ export function evalExactCount(args) {
13
+ const { matched, want, noun, filter, assertion } = args;
14
+ if (matched === want) {
15
+ return { pass: true, evidence: { matched } };
16
+ }
17
+ return {
18
+ pass: false,
19
+ ...(matched > want ? { decided: true } : {}),
20
+ failureReason: `expected ${String(want)} ${noun} matching ${filter}, saw ${String(matched)}`,
21
+ observed: `${String(matched)} matching ${noun}`,
22
+ expected: `exactly ${String(want)} matching ${filter}`,
23
+ assertion,
24
+ };
25
+ }
@@ -12,8 +12,7 @@ import { parseJsonObject, readField, redactedOnPath, str, } from './predicate-ev
12
12
  import { evalElement, joinedText } from './predicate-element.js';
13
13
  import { evalState } from './predicate-state.js';
14
14
  import { skippedBodyRemedy } from './predicate-eval.js';
15
- import { requestBodySkipRemedy } from './predicate-request-body.js';
16
- const REMEDY_BODY_CAPTURE = 'enable it where the app calls connect(): reticle({ captureNetworkBodies: true })';
15
+ import { REMEDY_BODY_CAPTURE, requestBodySkipRemedy } from './predicate-request-body.js';
17
16
  function unknown(reason) {
18
17
  return { result: { pass: false, failureReason: reason, inconclusive: reason } };
19
18
  }
@@ -2,10 +2,12 @@ import { EventType, NetInitiator, PredicateKind, ResponseBodyReason, SettledChan
2
2
  import { isReticleVoice } from '../../state-bookkeeping.js';
3
3
  import { describeObserved } from './observed-in-window.js';
4
4
  import { netEvidence } from './net-evidence.js';
5
- import { checkRequestBody, newRequestBodyState, requestBodyVerdict, } from './predicate-request-body.js';
5
+ import { mergeNetworkDetail } from '../../window/network-detail-merge.js';
6
+ import { checkRequestBody, REMEDY_BODY_CAPTURE, newRequestBodyState, requestBodyVerdict, } from './predicate-request-body.js';
6
7
  export { evalConsole } from './predicate-console.js';
7
8
  import { clipBody, dataMatches, describeBodyFieldMiss, describeFieldMiss, describeNetFilter, matchJsonBody, num, redactedOnPath, str, } from './predicate-eval-kit.js';
8
9
  import { keyFragmentOnly } from './body-key-fragment.js';
10
+ import { evalExactCount } from '../../exact-count.js';
9
11
  import { PRE_ATTACH_CAVEAT, nativeDownloadReason, targetsNativeDownload, targetsUnobservedChannel, unobservedChannelReason, } from './net-blind-spots.js';
10
12
  export { clipBody, dataMatches, describeNetFilter, matchValue, str, } from './predicate-eval-kit.js';
11
13
  /** The oracle a net body clause reports, so an agent can branch on which one decided. */
@@ -33,8 +35,9 @@ export * from './predicate-schema.js';
33
35
  * This exists so an agent can assert on the OUTCOME rather than on a number Reticle invented.
34
36
  */
35
37
  function callSucceeded(data) {
36
- if ('boolean' === typeof data['ok'])
38
+ if ('boolean' === typeof data['ok']) {
37
39
  return data['ok'];
40
+ }
38
41
  const status = num(data['status']);
39
42
  return status === undefined || status < 400;
40
43
  }
@@ -62,8 +65,9 @@ const REDACTED_PATH_HINT = 'this path segment was redacted — the literal you m
62
65
  function observedNetCalls(events, urlContains) {
63
66
  const calls = events.filter((e) => e.type === EventType.NET_REQUEST);
64
67
  const base = describeObserved('calls', calls.map(describeCall));
65
- if (urlContains === undefined)
68
+ if (urlContains === undefined) {
66
69
  return base;
70
+ }
67
71
  const encoded = encodeURIComponent(REDACTED_VALUE);
68
72
  const redacted = calls.some((e) => {
69
73
  const url = str(e.data['url']) ?? '';
@@ -76,33 +80,10 @@ function describeSignalFilter(p) {
76
80
  const { kind: _kind, count: _count, since: _since, ...filter } = p;
77
81
  return JSON.stringify(filter);
78
82
  }
79
- /**
80
- * Exact cardinality, once, for every channel that can count its matches.
81
- *
82
- * `net` and `signal` are the same assertion over different evidence — "this happened EXACTLY n
83
- * times" — and the interesting half is the same on both: an over-count is `decided`, because a
84
- * window only accumulates and a count cannot come back down, so waiting out the rest of the budget
85
- * to report a double-fire buys nothing but latency.
86
- *
87
- * `noun` names the population in prose ("network call(s)", "signal(s)"), `filter` is the matcher as
88
- * applied, and `assertion` is the oracle that judged it.
89
- */
90
- function evalExactCount(args) {
91
- const { matched, want, noun, filter, assertion } = args;
92
- if (matched === want)
93
- return { pass: true, evidence: { matched } };
94
- return {
95
- pass: false,
96
- ...(matched > want ? { decided: true } : {}),
97
- failureReason: `expected ${String(want)} ${noun} matching ${filter}, saw ${String(matched)}`,
98
- observed: `${String(matched)} matching ${noun}`,
99
- expected: `exactly ${String(want)} matching ${filter}`,
100
- assertion,
101
- };
102
- }
103
83
  function nativeDownloadMiss(events, p) {
104
- if (!targetsNativeDownload(p.urlContains))
84
+ if (!targetsNativeDownload(p.urlContains)) {
105
85
  return undefined;
86
+ }
106
87
  const reason = nativeDownloadReason(describeNetFilter(p));
107
88
  return {
108
89
  pass: false,
@@ -134,8 +115,9 @@ const DOCUMENT_INITIATORS = new Set([
134
115
  * IPC. The capsule's blast radius uses it to keep a page load out of "what this action also did".
135
116
  */
136
117
  export function isDocumentInitiated(event) {
137
- if (event.type !== EventType.NET_REQUEST)
118
+ if (event.type !== EventType.NET_REQUEST) {
138
119
  return false;
120
+ }
139
121
  const initiator = str(event.data['initiator']);
140
122
  return initiator !== undefined && DOCUMENT_INITIATORS.has(initiator);
141
123
  }
@@ -172,29 +154,34 @@ function wantedBody(p) {
172
154
  */
173
155
  export function skippedBodyRemedy(reason) {
174
156
  if (ResponseBodyReason.STREAMING === reason) {
175
- return 'The body was streamed (text/event-stream or ndjson): the SDK never reads a stream, because reading it would hang the app, and capture is already on. Assert the result in the DOM or in state instead, or use a non-streaming endpoint.';
157
+ return 'The body was streamed in an unsupported format (such as ndjson), and capture is already on. Assert the result in the DOM or in state instead, or use a non-streaming endpoint.';
176
158
  }
177
159
  if (ResponseBodyReason.NOT_TEXT === reason) {
178
160
  return 'The body is not text (binary, or a content type that is not recorded), and capture is already on. Assert the result in the DOM or in state instead.';
179
161
  }
180
162
  if (ResponseBodyReason.UNREADABLE === reason) {
181
- return 'The body could not be read before the read deadline, and capture is already on. A response that is still streaming does this. Assert the result in the DOM or in state instead.';
163
+ return 'The body is not available yet or could not be read, and capture is already on. SSE capture can take up to 10 seconds. Use wait_for with a sufficient timeout to retry the body assertion. If the body remains unavailable, assert the result in the DOM or in state instead.';
182
164
  }
183
165
  return undefined;
184
166
  }
185
167
  /** The skip reason every one of these calls carries, when they all carry the same one. */
186
168
  export function sharedSkipReason(reasons) {
187
169
  const [first] = reasons;
188
- if (first === undefined)
170
+ if (first === undefined) {
189
171
  return undefined;
172
+ }
190
173
  return reasons.every((r) => r === first) ? first : undefined;
191
174
  }
192
175
  /** Why a matched call's body could not answer a body clause, and what to do instead (#1520). */
193
176
  function unrecordedBodyReason(p, reason) {
194
177
  const head = `a call matching ${describeNetFilter(p)} was answered, but its body was not recorded, so ${wantedBody(p)} could not be checked, which is not the same as absent.`;
195
- return `${head} ${skippedBodyRemedy(reason) ?? 'Enable it where the app calls connect(): reticle({ captureNetworkBodies: true })'}`;
178
+ return `${head} ${skippedBodyRemedy(reason) ?? REMEDY_BODY_CAPTURE}`;
196
179
  }
197
180
  export function evalNet(events, p) {
181
+ // SSE headers close the request immediately. A later detail supplies its captured body without another call.
182
+ if (p.bodyContains !== undefined || p.bodyMatches !== undefined) {
183
+ events = mergeNetworkDetail(events);
184
+ }
198
185
  const since = p.since ?? 0;
199
186
  /**
200
187
  * Computed once: the gate every zero-match downgrade below reads. True means the resource-timing
@@ -242,8 +229,9 @@ export function evalNet(events, p) {
242
229
  let redactedResponseField;
243
230
  const requestState = newRequestBodyState();
244
231
  const matches = events.filter((e) => {
245
- if (e.type !== EventType.NET_REQUEST || e.t < since)
232
+ if (e.type !== EventType.NET_REQUEST || e.t < since) {
246
233
  return false;
234
+ }
247
235
  const d = e.data;
248
236
  if (p.method !== undefined && str(d['method'])?.toUpperCase() !== p.method.toUpperCase()) {
249
237
  return false;
@@ -261,13 +249,16 @@ export function evalNet(events, p) {
261
249
  unobservableStatus = true;
262
250
  return false;
263
251
  }
264
- if (status !== p.status)
252
+ if (status !== p.status) {
265
253
  return false;
254
+ }
266
255
  }
267
- if (p.ok !== undefined && callSucceeded(d) !== p.ok)
256
+ if (p.ok !== undefined && callSucceeded(d) !== p.ok) {
268
257
  return false;
269
- if (!checkRequestBody(d, p, requestState))
258
+ }
259
+ if (!checkRequestBody(d, p, requestState)) {
270
260
  return false;
261
+ }
271
262
  if (p.bodyContains !== undefined || p.bodyMatches !== undefined) {
272
263
  // The RESPONSE body only, and this is the whole point of these fields. Searching the request
273
264
  // too would let `bodyContains: "1187.01"` pass on the very defect it exists to catch: the app
@@ -289,13 +280,15 @@ export function evalNet(events, p) {
289
280
  truncatedBody ??= response;
290
281
  truncatedClause ??= clause;
291
282
  }
292
- else
283
+ else {
293
284
  bodyMismatch ??= response;
285
+ }
294
286
  return false;
295
287
  };
296
288
  if (p.bodyContains !== undefined) {
297
- if (!response.includes(p.bodyContains))
289
+ if (!response.includes(p.bodyContains)) {
298
290
  return missed(NetBodyAssertion.CONTAINS);
291
+ }
299
292
  const fragment = keyFragmentOnly(response, p.bodyContains);
300
293
  if (fragment !== undefined) {
301
294
  keyFragment ??= { key: fragment, body: response };
@@ -304,8 +297,9 @@ export function evalNet(events, p) {
304
297
  }
305
298
  if (p.bodyMatches !== undefined) {
306
299
  const verdict = matchJsonBody(response, p.bodyMatches);
307
- if ('mismatch' === verdict)
300
+ if ('mismatch' === verdict) {
308
301
  return missed(NetBodyAssertion.MATCHES);
302
+ }
309
303
  if ('match' !== verdict) {
310
304
  redactedResponseField ??= verdict.redacted;
311
305
  return false;
@@ -379,8 +373,9 @@ export function evalNet(events, p) {
379
373
  };
380
374
  }
381
375
  const requestVerdict = requestBodyVerdict(requestState, p, matches.length, bodyMismatch);
382
- if (requestVerdict !== undefined)
376
+ if (requestVerdict !== undefined) {
383
377
  return requestVerdict;
378
+ }
384
379
  if (bodyMismatch !== undefined && 0 === matches.length) {
385
380
  // The call is there and its body is there; only the VALUE differs. Counting it as zero matches
386
381
  // points at the wiring, which is the one place the defect is not. A field clause also names the
@@ -401,8 +396,9 @@ export function evalNet(events, p) {
401
396
  if (p.count !== undefined) {
402
397
  if (0 === matches.length) {
403
398
  const download = nativeDownloadMiss(events, p);
404
- if (download !== undefined)
399
+ if (download !== undefined) {
405
400
  return download;
401
+ }
406
402
  }
407
403
  if (matches.length !== p.count &&
408
404
  0 === matches.length &&
@@ -433,8 +429,9 @@ export function evalNet(events, p) {
433
429
  const hit = matches[0];
434
430
  if (hit === undefined) {
435
431
  const download = nativeDownloadMiss(events, p);
436
- if (download !== undefined)
432
+ if (download !== undefined) {
437
433
  return download;
434
+ }
438
435
  }
439
436
  if (hit === undefined && targetsUnobservedChannel(p.urlContains) && !sawSubresources) {
440
437
  const reason = unobservedChannelReason(describeNetFilter(p));
@@ -462,14 +459,17 @@ export function evalNet(events, p) {
462
459
  export function evalAnimation(events, p) {
463
460
  const wantType = true === p.completed ? EventType.ANIM_END : EventType.ANIM_START;
464
461
  const hit = events.find((e) => {
465
- if (e.type !== wantType)
462
+ if (e.type !== wantType) {
466
463
  return false;
464
+ }
467
465
  const name = str(e.data['name']);
468
466
  // A check with no name asks about the app, so Reticle's own bookkeeping signals do not count.
469
- if (p.name === undefined ? isReticleVoice(name ?? '') : name !== p.name)
467
+ if (p.name === undefined ? isReticleVoice(name ?? '') : name !== p.name) {
470
468
  return false;
471
- if (p.target !== undefined && e.ref !== p.target)
469
+ }
470
+ if (p.target !== undefined && e.ref !== p.target) {
472
471
  return false;
472
+ }
473
473
  return true;
474
474
  });
475
475
  return hit !== undefined
@@ -490,12 +490,14 @@ export function evalSignal(events, p) {
490
490
  */
491
491
  let redactedField;
492
492
  const isMatch = (e) => {
493
- if (e.type !== EventType.SIGNAL)
493
+ if (e.type !== EventType.SIGNAL) {
494
494
  return false;
495
+ }
495
496
  const name = str(e.data['name']);
496
497
  // A check with no name asks about the app, so Reticle's own bookkeeping signals do not count.
497
- if (p.name === undefined ? isReticleVoice(name ?? '') : name !== p.name)
498
+ if (p.name === undefined ? isReticleVoice(name ?? '') : name !== p.name) {
498
499
  return false;
500
+ }
499
501
  if (p.dataMatches !== undefined) {
500
502
  const payload = (e.data['data'] ?? {});
501
503
  const hidden = 'object' === typeof payload
@@ -505,14 +507,16 @@ export function evalSignal(events, p) {
505
507
  redactedField ??= hidden;
506
508
  return false;
507
509
  }
508
- if (!dataMatches(payload, p.dataMatches))
510
+ if (!dataMatches(payload, p.dataMatches)) {
509
511
  return false;
512
+ }
510
513
  }
511
514
  return true;
512
515
  };
513
516
  const redactedVerdict = () => {
514
- if (redactedField === undefined)
517
+ if (redactedField === undefined) {
515
518
  return undefined;
519
+ }
516
520
  const field = JSON.stringify(redactedField);
517
521
  return {
518
522
  pass: false,
@@ -531,8 +535,9 @@ export function evalSignal(events, p) {
531
535
  const matched = events.filter(isMatch).length;
532
536
  // A redacted payload might have been one of the matches, so no count over it is decided.
533
537
  const unjudgeable = redactedVerdict();
534
- if (unjudgeable !== undefined)
538
+ if (unjudgeable !== undefined) {
535
539
  return unjudgeable;
540
+ }
536
541
  return evalExactCount({
537
542
  matched,
538
543
  want: p.count,
@@ -542,12 +547,14 @@ export function evalSignal(events, p) {
542
547
  });
543
548
  }
544
549
  const hit = events.find(isMatch);
545
- if (hit !== undefined)
550
+ if (hit !== undefined) {
546
551
  return { pass: true, evidence: hit.data };
552
+ }
547
553
  // `find` scanned every event to get here, so a redacted payload has been seen if there was one.
548
554
  const unjudgeable = redactedVerdict();
549
- if (unjudgeable !== undefined)
555
+ if (unjudgeable !== undefined) {
550
556
  return unjudgeable;
557
+ }
551
558
  // Near-miss: show signals that fired with the same name (so the agent sees the real data).
552
559
  const sameName = events
553
560
  .filter((e) => e.type === EventType.SIGNAL && (p.name === undefined || str(e.data['name']) === p.name))
@@ -657,8 +664,9 @@ export function evalSettled(allEvents, p, now, scope) {
657
664
  const ignoredForeign = [];
658
665
  const ignoredDepartures = [];
659
666
  const events = allEvents.filter((e) => {
660
- if (!NET_TYPES.has(e.type))
667
+ if (!NET_TYPES.has(e.type)) {
661
668
  return true;
669
+ }
662
670
  // Classified by `urlForMatch`, DISCLOSED by `url`: redaction rewrites sensitive path segments at
663
671
  // emit time (`/auth/token/refresh-context` -> `/auth/token/[REDACTED]`), and a declared
664
672
  // `background` pattern is matched with `String.includes` — so classifying on the displayed URL
@@ -668,20 +676,23 @@ export function evalSettled(allEvents, p, now, scope) {
668
676
  const matchUrl = urlForMatch(e.data);
669
677
  const shown = str(e.data['url']);
670
678
  if (isDevToolingUrl(matchUrl)) {
671
- if (shown !== undefined && !ignoredDevTooling.includes(shown))
679
+ if (shown !== undefined && !ignoredDevTooling.includes(shown)) {
672
680
  ignoredDevTooling.push(shown);
681
+ }
673
682
  return false;
674
683
  }
675
684
  // Departure first: a departure to the app's own origin is still a request whose result nobody
676
685
  // will see, and reporting it as somebody else's host would be the wrong explanation.
677
686
  if (isDeparture(e.data)) {
678
- if (shown !== undefined && !ignoredDepartures.includes(shown))
687
+ if (shown !== undefined && !ignoredDepartures.includes(shown)) {
679
688
  ignoredDepartures.push(shown);
689
+ }
680
690
  return false;
681
691
  }
682
692
  if (isForeignTraffic(matchUrl, scope?.appUrl, scope?.background ?? [])) {
683
- if (shown !== undefined && !ignoredForeign.includes(shown))
693
+ if (shown !== undefined && !ignoredForeign.includes(shown)) {
684
694
  ignoredForeign.push(shown);
695
+ }
685
696
  return false;
686
697
  }
687
698
  return true;
@@ -709,15 +720,18 @@ export function evalSettled(allEvents, p, now, scope) {
709
720
  for (const e of events) {
710
721
  if (e.type === EventType.NET_PENDING) {
711
722
  const id = str(e.data['id']);
712
- if (id === undefined)
723
+ if (id === undefined) {
713
724
  unkeyedPending += 1;
714
- else
725
+ }
726
+ else {
715
727
  pendingById.set(id, (pendingById.get(id) ?? 0) + 1);
728
+ }
716
729
  }
717
730
  else if (e.type === EventType.NET_REQUEST) {
718
731
  const id = str(e.data['id']);
719
- if (id !== undefined)
732
+ if (id !== undefined) {
720
733
  doneById.set(id, (doneById.get(id) ?? 0) + 1);
734
+ }
721
735
  }
722
736
  }
723
737
  let inFlight = unkeyedPending;
@@ -731,27 +745,33 @@ export function evalSettled(allEvents, p, now, scope) {
731
745
  // way as a pending with no completion.
732
746
  const openStreams = new Set();
733
747
  for (const e of events) {
734
- if (e.type !== EventType.NET_STREAM)
748
+ if (e.type !== EventType.NET_STREAM) {
735
749
  continue;
750
+ }
736
751
  const id = str(e.data['id']);
737
- if (id === undefined)
752
+ if (id === undefined) {
738
753
  continue;
754
+ }
739
755
  const direction = str(e.data['direction']);
740
- if (StreamDirection.OPEN === direction)
756
+ if (StreamDirection.OPEN === direction) {
741
757
  openStreams.add(id);
742
- else if (StreamDirection.CLOSE === direction)
758
+ }
759
+ else if (StreamDirection.CLOSE === direction) {
743
760
  openStreams.delete(id);
761
+ }
744
762
  }
745
763
  const streaming = openStreams.size;
746
764
  // Work only the app can see (`reticle.busy`): starts minus ends, in order, never below zero, so an
747
765
  // end whose start fell before this window is not credit against work started inside it.
748
766
  let appBusy = 0;
749
767
  for (const e of events) {
750
- if (e.type !== EventType.SIGNAL || RETICLE_BUSY_SIGNAL !== e.data['name'])
768
+ if (e.type !== EventType.SIGNAL || RETICLE_BUSY_SIGNAL !== e.data['name']) {
751
769
  continue;
770
+ }
752
771
  const delta = e.data['data']?.delta;
753
- if ('number' === typeof delta)
772
+ if ('number' === typeof delta) {
754
773
  appBusy = Math.max(0, appBusy + Math.sign(delta));
774
+ }
755
775
  }
756
776
  if (appBusy > 0 && 0 === inFlight + streaming) {
757
777
  const what = `${String(appBusy)} app task(s) still pending`;
@@ -10,6 +10,6 @@
10
10
  * This wraps it once, so every caller gets the same shape rather than each growing its own catch —
11
11
  * the pattern #108 asks for: name the parameter, say whether anything ran, show a valid call.
12
12
  */
13
- import { z } from 'zod';
13
+ import * as z from 'zod';
14
14
  import { PredicateSchema } from './predicate-eval.js';
15
15
  export declare function parsePredicate(input: unknown): z.infer<typeof PredicateSchema>;
@@ -10,7 +10,7 @@
10
10
  * This wraps it once, so every caller gets the same shape rather than each growing its own catch —
11
11
  * the pattern #108 asks for: name the parameter, say whether anything ran, show a valid call.
12
12
  */
13
- import { z } from 'zod';
13
+ import * as z from 'zod';
14
14
  import { PredicateKind } from '@reticlehq/core';
15
15
  import { PredicateSchema, predicateFieldsFor, predicateNestedFieldsFor } from './predicate-eval.js';
16
16
  /**
@@ -35,6 +35,10 @@ interface RequestBodyState {
35
35
  */
36
36
  redactedField?: string;
37
37
  }
38
+ /** What the SDK keeps with no setting, so an agent does not switch capture on for a body it has. */
39
+ export declare const BODY_CAPTURE_DEFAULTS: string;
40
+ /** The remedy when capture is off: the defaults, then where the setting goes. */
41
+ export declare const REMEDY_BODY_CAPTURE: string;
38
42
  /**
39
43
  * The remedy for a request body the SDK did not record although capture is on, or `undefined`.
40
44
  *
@@ -15,6 +15,13 @@
15
15
  */
16
16
  import { REDACTED_VALUE } from '@reticlehq/core';
17
17
  import { clipBody, describeBodyFieldMiss, describeNetFilter, matchJsonBody, str, } from './predicate-eval-kit.js';
18
+ /** What the SDK keeps with no setting, so an agent does not switch capture on for a body it has. */
19
+ export const BODY_CAPTURE_DEFAULTS = 'A failed response (HTTP 400 and up) keeps its body by default. A request body, and the body of ' +
20
+ 'a successful response, need `captureNetworkBodies: true`.';
21
+ /** The remedy when capture is off: the defaults, then where the setting goes. */
22
+ export const REMEDY_BODY_CAPTURE = `${BODY_CAPTURE_DEFAULTS} Turn it on where the app calls connect(): ` +
23
+ '`reticle.connect({ captureNetworkBodies: true })`, or in the Vite plugin: ' +
24
+ '`reticle({ captureNetworkBodies: true })`.';
18
25
  /**
19
26
  * The remedy for a request body the SDK did not record although capture is on, or `undefined`.
20
27
  *
@@ -96,7 +103,7 @@ export function requestBodyVerdict(state, predicate, matchCount, responseMismatc
96
103
  }
97
104
  if (state.unrecorded) {
98
105
  // Unknown, not different: nothing was read, so nothing says the body did not match (#1520).
99
- const reason = `a call matched but its REQUEST body was not recorded, so the request-body clause could not be checked — ${requestBodySkipRemedy(state.unrecordedType) ?? 'enable it where the app calls connect(): reticle({ captureNetworkBodies: true })'}`;
106
+ const reason = `a call matched but its REQUEST body was not recorded, so the request-body clause could not be checked — ${requestBodySkipRemedy(state.unrecordedType) ?? REMEDY_BODY_CAPTURE}`;
100
107
  return {
101
108
  pass: false,
102
109
  failureReason: reason,
@@ -7,7 +7,7 @@
7
7
  * reads off disk. Core is the contract; this is the reasoning over it. Both halves are re-exported
8
8
  * from here, so every existing importer of this module keeps working unchanged.
9
9
  */
10
- import { z } from 'zod';
10
+ import * as z from 'zod';
11
11
  import { type ElementDescriptor, type ElementQuery } from '@reticlehq/core';
12
12
  export { PredicateSchema } from '@reticlehq/core';
13
13
  export type { Predicate, PropertyAssertion } from '@reticlehq/core';
@@ -7,7 +7,7 @@
7
7
  * reads off disk. Core is the contract; this is the reasoning over it. Both halves are re-exported
8
8
  * from here, so every existing importer of this module keeps working unchanged.
9
9
  */
10
- import { z } from 'zod';
10
+ import * as z from 'zod';
11
11
  import { PredicateKind, PredicateSchema, QueryBy, predicateShapeFor, } from '@reticlehq/core';
12
12
  // One public surface, two packages. A caller asking this module for the shape is asking the right
13
13
  // module; it simply no longer OWNS it.
@@ -317,18 +317,19 @@ export function nestedKeysOf(schema) {
317
317
  return [];
318
318
  return Object.keys(inner.shape);
319
319
  }
320
- /** Peel optional/nullable/default/effects wrappers off a field to reach the schema underneath. */
320
+ /** Peel optional/nullable/default/pipe wrappers off a field to reach the schema underneath. */
321
321
  function unwrapSchema(schema) {
322
322
  let current = schema;
323
323
  for (;;) {
324
324
  if (current instanceof z.ZodOptional ||
325
325
  current instanceof z.ZodNullable ||
326
326
  current instanceof z.ZodDefault) {
327
- current = current._def.innerType;
327
+ current = current.def.innerType;
328
328
  continue;
329
329
  }
330
- if (current instanceof z.ZodEffects) {
331
- current = current._def.schema;
330
+ // A transform is a pipe from the schema into the transform; a preprocess is the other way round.
331
+ if (current instanceof z.ZodPipe) {
332
+ current = (current.in instanceof z.ZodTransform ? current.out : current.in);
332
333
  continue;
333
334
  }
334
335
  return current;
@@ -18,52 +18,54 @@
18
18
  * rejection is a good outcome. It sends input that is entirely VALID and entirely unhelpful, which
19
19
  * is what a real minimal client looks like and what no fixture in this repository resembles.
20
20
  */
21
- import { z } from 'zod';
21
+ import * as z from 'zod';
22
22
  import { EVENT_PAYLOAD_SCHEMAS, EventType } from '@reticlehq/core';
23
23
  /** A value that satisfies a schema while carrying as little as the contract allows. */
24
24
  function barestValue(schema) {
25
- const def = schema._def;
26
- switch (def.typeName) {
27
- // An optional field is the whole point: leave it out.
28
- case 'ZodOptional':
29
- case 'ZodNullable':
30
- return undefined;
31
- case 'ZodDefault':
32
- return undefined;
33
- case 'ZodString': {
34
- // A minimum length is part of the contract, not decoration: `note` and `anchor` on a human
35
- // mark both demand one. The barest string that still parses is one character, not none.
36
- const checks = def.checks ?? [];
37
- const min = checks.find((c) => 'min' === c.kind)?.value ?? 0;
38
- return 'x'.repeat(min);
39
- }
40
- case 'ZodNumber': {
41
- const checks = def.checks ?? [];
42
- return checks.find((c) => 'min' === c.kind)?.value ?? 0;
43
- }
44
- case 'ZodBoolean':
45
- return false;
46
- case 'ZodArray':
47
- return [];
48
- // A tuple has a fixed length, so the barest one still has every item.
49
- case 'ZodTuple':
50
- return (def.items ?? []).map((item) => barestValue(item));
51
- case 'ZodLiteral':
52
- return def.value;
53
- case 'ZodEnum':
54
- return schema.options[0];
55
- case 'ZodNativeEnum':
56
- return Object.values(schema._def.values)[0];
57
- case 'ZodUnion':
58
- return barestValue((def.options ?? [])[0]);
59
- case 'ZodRecord':
60
- return {};
61
- case 'ZodObject':
62
- return barestObject(schema);
63
- default:
64
- // Unknown, any, and anything else the contract does not constrain.
65
- return undefined;
25
+ // An optional field is the whole point: leave it out.
26
+ if (schema instanceof z.ZodOptional ||
27
+ schema instanceof z.ZodNullable ||
28
+ schema instanceof z.ZodDefault) {
29
+ return undefined;
30
+ }
31
+ if (schema instanceof z.ZodString) {
32
+ // A minimum length is part of the contract, not decoration: `note` and `anchor` on a human
33
+ // mark both demand one. The barest string that still parses is one character, not none.
34
+ return 'x'.repeat(schema.minLength ?? 0);
35
+ }
36
+ if (schema instanceof z.ZodNumber) {
37
+ // `.int()` reports the smallest safe integer as its minimum; that is no lower bound to honour.
38
+ const min = schema.minValue;
39
+ const value = null !== min && Number.MIN_SAFE_INTEGER < min ? min : 0;
40
+ return schema.safeParse(value).success ? value : value + 1;
41
+ }
42
+ if (schema instanceof z.ZodBoolean) {
43
+ return false;
44
+ }
45
+ if (schema instanceof z.ZodArray) {
46
+ return [];
47
+ }
48
+ if (schema instanceof z.ZodRecord) {
49
+ return {};
50
+ }
51
+ // A tuple has a fixed length, so the barest one still has every item.
52
+ if (schema instanceof z.ZodTuple) {
53
+ return schema.def.items.map((item) => barestValue(item));
54
+ }
55
+ if (schema instanceof z.ZodLiteral) {
56
+ return schema.value;
57
+ }
58
+ if (schema instanceof z.ZodEnum) {
59
+ return schema.options[0];
60
+ }
61
+ if (schema instanceof z.ZodUnion) {
62
+ return barestValue(schema.options[0]);
63
+ }
64
+ if (schema instanceof z.ZodObject) {
65
+ return barestObject(schema);
66
66
  }
67
+ // Unknown, any, and anything else the contract does not constrain.
68
+ return undefined;
67
69
  }
68
70
  /** The smallest object that still parses: required keys only, each at its barest value. */
69
71
  function barestObject(schema) {
@@ -1,8 +1,7 @@
1
1
  import { type ReticleEvent } from '@reticlehq/core';
2
2
  /**
3
- * Fold each NET_DETAIL onto the matching in-page NET_REQUEST (by method+url), enriching it with the
4
- * authoritative headers/resourceType the page-side wrapper couldn't see — WITHOUT clobbering fields the
5
- * in-page event already carries. A NET_DETAIL with no matching request is kept as its own event (a
6
- * response the wrapper missed is signal, never silently dropped). Pure over the event list.
3
+ * Fold wire details by method+url, and SDK response bodies by request id plus method+url.
4
+ * SDK body details finish background capture without adding another request to counts or settle.
5
+ * Keep unmatched details rather than attaching them to another request. Pure over the event list.
7
6
  */
8
7
  export declare function mergeNetworkDetail(events: readonly ReticleEvent[]): ReticleEvent[];
@@ -28,28 +28,55 @@ function keyOf(data) {
28
28
  return `${m} ${urlForMatch(data)}`;
29
29
  }
30
30
  /**
31
- * Fold each NET_DETAIL onto the matching in-page NET_REQUEST (by method+url), enriching it with the
32
- * authoritative headers/resourceType the page-side wrapper couldn't see — WITHOUT clobbering fields the
33
- * in-page event already carries. A NET_DETAIL with no matching request is kept as its own event (a
34
- * response the wrapper missed is signal, never silently dropped). Pure over the event list.
31
+ * Fold wire details by method+url, and SDK response bodies by request id plus method+url.
32
+ * SDK body details finish background capture without adding another request to counts or settle.
33
+ * Keep unmatched details rather than attaching them to another request. Pure over the event list.
35
34
  */
36
35
  export function mergeNetworkDetail(events) {
37
36
  const requestByKey = new Map();
37
+ const requestById = new Map();
38
38
  for (const e of events) {
39
- if (e.type === EventType.NET_REQUEST)
40
- requestByKey.set(keyOf(e.data), e);
39
+ if (e.type !== EventType.NET_REQUEST) {
40
+ continue;
41
+ }
42
+ requestByKey.set(keyOf(e.data), e);
43
+ if ('string' === typeof e.data['id']) {
44
+ requestById.set(e.data['id'], e);
45
+ }
41
46
  }
42
47
  const out = [];
43
48
  const enriched = new Map();
44
49
  for (const e of events) {
45
- if (e.type === EventType.NET_DETAIL) {
46
- const match = requestByKey.get(keyOf(e.data));
47
- if (match === undefined) {
50
+ if (e.type === EventType.NET_DETAIL || e.type === EventType.NET_RESPONSE_BODY) {
51
+ const sdkBody = e.type === EventType.NET_RESPONSE_BODY;
52
+ const responseBody = e.data['responseBody'];
53
+ const id = e.data['id'];
54
+ // SDK body details carry the page's request id. URL alone mixes concurrent streams at one endpoint.
55
+ let match;
56
+ if (sdkBody) {
57
+ if ('string' === typeof id) {
58
+ match = requestById.get(id);
59
+ }
60
+ }
61
+ else {
62
+ match = requestByKey.get(keyOf(e.data));
63
+ }
64
+ if (match === undefined || keyOf(match.data) !== keyOf(e.data)) {
48
65
  out.push(e); // unmatched detail survives on its own
49
66
  continue;
50
67
  }
51
68
  const base = enriched.get(match) ?? match;
52
69
  const data = { ...base.data };
70
+ if (sdkBody && 'string' === typeof responseBody) {
71
+ data['responseBody'] = responseBody;
72
+ if (true === e.data['responseBodyTruncated']) {
73
+ data['responseBodyTruncated'] = true;
74
+ }
75
+ else {
76
+ delete data['responseBodyTruncated'];
77
+ }
78
+ delete data['responseBodyReason'];
79
+ }
53
80
  if (data['headers'] === undefined && e.data['headers'] !== undefined) {
54
81
  data['headers'] = e.data['headers'];
55
82
  }
@@ -71,18 +98,21 @@ export function mergeNetworkDetail(events) {
71
98
  // rather than fills a gap. Carried over when the wire body was cut, deleted when it was not:
72
99
  // a stale `true` from the page capture would caveat a body that is now whole, and a missing
73
100
  // one would let a cut body read as complete.
74
- if (true === e.data['requestBodyTruncated'])
101
+ if (true === e.data['requestBodyTruncated']) {
75
102
  data['requestBodyTruncated'] = true;
76
- else
103
+ }
104
+ else {
77
105
  delete data['requestBodyTruncated'];
106
+ }
78
107
  }
79
108
  enriched.set(match, { ...base, data });
80
109
  continue; // the detail is absorbed into the request
81
110
  }
82
111
  }
83
112
  for (const e of events) {
84
- if (e.type === EventType.NET_DETAIL)
85
- continue; // handled above
113
+ if (e.type === EventType.NET_DETAIL || e.type === EventType.NET_RESPONSE_BODY) {
114
+ continue;
115
+ } // handled above
86
116
  out.push(enriched.get(e) ?? e);
87
117
  }
88
118
  return out;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reticlehq/engine",
3
- "version": "3.8.0",
3
+ "version": "3.8.2",
4
4
  "description": "The rules that decide a verdict: read what happened in a running app and say whether the declared consequence held. No browser, no daemon, no command line - an implementation of the OpenVerification specification you can use on its own.",
5
5
  "keywords": [
6
6
  "verification",
@@ -56,9 +56,9 @@
56
56
  "access": "public"
57
57
  },
58
58
  "dependencies": {
59
- "zod": "^3.24.1",
60
- "@reticlehq/core": "3.8.0",
61
- "open-verification": "1.0.0"
59
+ "zod": "^4.6.6",
60
+ "open-verification": "1.1.0",
61
+ "@reticlehq/core": "3.8.2"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "tsc -b && node ../scripts/alias-dist.mjs",