@jini-ai/diagnostics 0.7.2 → 0.7.3-next.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.
Files changed (65) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/dist/agent-logs/amr/index.d.ts +8 -0
  3. package/dist/agent-logs/amr/index.js +16 -0
  4. package/dist/agent-logs/claude/index.d.ts +8 -0
  5. package/dist/agent-logs/claude/index.js +8 -0
  6. package/dist/agent-logs/codex/index.d.ts +8 -0
  7. package/dist/agent-logs/codex/index.js +8 -0
  8. package/dist/agent-logs/opencode/index.d.ts +8 -0
  9. package/dist/agent-logs/opencode/index.js +10 -0
  10. package/dist/agent-logs.js +12 -39
  11. package/dist/console-tee.d.ts +83 -0
  12. package/dist/console-tee.js +108 -0
  13. package/dist/local-text.d.ts +21 -0
  14. package/dist/local-text.js +30 -0
  15. package/dist/observability/delivery.js +4 -3
  16. package/dist/observability/errors.d.ts +4 -1
  17. package/dist/observability/errors.js +2 -2
  18. package/dist/observability/fanout.d.ts +1 -1
  19. package/dist/observability/fanout.js +15 -1
  20. package/dist/observability/hooks.d.ts +2 -1
  21. package/dist/observability/hooks.js +2 -1
  22. package/dist/observability/index.d.ts +2 -12
  23. package/dist/observability/index.js +2 -11
  24. package/dist/observability/instrumentation.d.ts +4 -4
  25. package/dist/observability/instrumentation.js +1 -1
  26. package/dist/observability/node.d.ts +4 -0
  27. package/dist/observability/node.js +2 -0
  28. package/dist/observability/otel.d.ts +19 -25
  29. package/dist/observability/otel.js +20 -195
  30. package/dist/observability/ports.d.ts +1 -184
  31. package/dist/observability/provider-contract.d.ts +22 -0
  32. package/dist/observability/provider-contract.js +19 -0
  33. package/dist/observability/report-error.d.ts +1 -1
  34. package/dist/observability/tracker-types.d.ts +2 -2
  35. package/dist/observability/tracker.js +3 -2
  36. package/dist/sources.js +2 -1
  37. package/dist/web-evidence/bounded-body.d.ts +22 -0
  38. package/dist/web-evidence/bounded-body.js +60 -0
  39. package/dist/web-evidence/capture-budget.d.ts +29 -0
  40. package/dist/web-evidence/capture-budget.js +14 -0
  41. package/dist/web-evidence/capture-clock.d.ts +12 -0
  42. package/dist/web-evidence/capture-clock.js +8 -0
  43. package/dist/web-evidence/cookie-shapes.d.ts +22 -0
  44. package/dist/web-evidence/cookie-shapes.js +26 -0
  45. package/dist/web-evidence/index.d.ts +3 -0
  46. package/dist/web-evidence/index.js +3 -0
  47. package/dist/web-evidence/page-body.d.ts +37 -0
  48. package/dist/web-evidence/page-body.js +112 -0
  49. package/dist/web-evidence/page-work-budget.d.ts +17 -1
  50. package/dist/web-evidence/page-work-budget.js +30 -8
  51. package/dist/web-evidence/path-guard.d.ts +119 -0
  52. package/dist/web-evidence/path-guard.js +200 -0
  53. package/dist/web-evidence/playwright-browser.js +18 -15
  54. package/dist/web-evidence/playwright-runtime.d.ts +0 -45
  55. package/dist/web-evidence/playwright-runtime.js +48 -2
  56. package/dist/web-evidence/render-page.d.ts +14 -0
  57. package/dist/web-evidence/render-page.js +65 -20
  58. package/dist/web-evidence/request-guard.js +19 -15
  59. package/dist/web-evidence/same-origin.d.ts +1 -1
  60. package/dist/web-evidence/same-origin.js +4 -4
  61. package/dist/web-evidence/testing/fake-clock.d.ts +19 -0
  62. package/dist/web-evidence/testing/fake-clock.js +47 -0
  63. package/package.json +55 -7
  64. package/dist/observability/noop.d.ts +0 -7
  65. package/dist/observability/noop.js +0 -27
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Reads at most `maxBytes` from a fetch response body, stopping the stream once the cap is hit.
3
+ *
4
+ * Stops rather than buffering-then-slicing so an unexpectedly large route cannot be used to
5
+ * exhaust memory. Decoding is UTF-8 and non-strict, so a multi-byte character split by the cap
6
+ * degrades to a replacement character instead of throwing.
7
+ *
8
+ * @param required.response - The fetch response.
9
+ * @param required.maxBytes - Cap, already clamped by the caller.
10
+ * @returns The decoded text, how many bytes were read, and whether the cap stopped the read.
11
+ * @complexity O(min(B, maxBytes)) in the response size.
12
+ * @example await readBoundedBody({ response: res, maxBytes: 200_000 });
13
+ */
14
+ export async function readBoundedBody({ response, maxBytes }, _optional = {}) {
15
+ if (!response.body)
16
+ return { body: "", bodyBytes: 0, truncated: false };
17
+ const reader = response.body.getReader();
18
+ const chunks = [];
19
+ let total = 0;
20
+ let truncated = false;
21
+ try {
22
+ let done = false;
23
+ while (!done && !truncated) {
24
+ const next = await reader.read();
25
+ done = next.done === true;
26
+ const value = next.value;
27
+ if (!done && value) {
28
+ const remaining = maxBytes - total;
29
+ truncated = value.byteLength > remaining;
30
+ const size = truncated ? remaining : value.byteLength;
31
+ chunks.push(value.subarray(0, size));
32
+ total += size;
33
+ }
34
+ }
35
+ }
36
+ finally {
37
+ await reader.cancel().catch(() => {
38
+ // The response is already being abandoned; a cancel failure adds nothing the caller can act on.
39
+ });
40
+ }
41
+ return { body: new TextDecoder("utf-8").decode(joinChunks({ chunks, total })), bodyBytes: total, truncated };
42
+ }
43
+ /**
44
+ * Joins already-capped chunks into one byte array. Written against `Uint8Array` alone (not a Node-only
45
+ * byte-buffer type) because this entry is universal and must not reach a Node global.
46
+ *
47
+ * @param required.chunks - The kept slices, in stream order.
48
+ * @param required.total - The sum of their byte lengths, used to size the result once.
49
+ * @complexity O(total) bytes copied once.
50
+ */
51
+ function joinChunks({ chunks, total }, _optional = {}) {
52
+ const joined = new Uint8Array(total);
53
+ let offset = 0;
54
+ for (const chunk of chunks) {
55
+ joined.set(chunk, offset);
56
+ offset += chunk.byteLength;
57
+ }
58
+ return joined;
59
+ }
60
+ //# sourceMappingURL=bounded-body.js.map
@@ -0,0 +1,29 @@
1
+ /** What the caller asked a capture to do. Every field is optional input from a tool call. */
2
+ export interface CaptureRequest {
3
+ /** Settle time in milliseconds. Replaced by `waitForSeconds` when that is given. */
4
+ settleMs?: number;
5
+ fullPage?: boolean;
6
+ /** The renderer's requested wait, in seconds. */
7
+ waitForSeconds?: number;
8
+ }
9
+ /** Host values. There are no defaults on purpose: the cap and the reserve belong to the host. */
10
+ export interface CaptureBudgetLimits {
11
+ baseMs: number;
12
+ /** Extra time a full-page scroll needs. */
13
+ fullPageMs: number;
14
+ /** The total never exceeds this. */
15
+ capMs: number;
16
+ /** Time kept at the end of the capture for the fallback on the current page. */
17
+ reserveMs: number;
18
+ }
19
+ export interface CaptureBudget {
20
+ totalMs: number;
21
+ /** `totalMs − reserveMs`: ordinary work must be done by then. */
22
+ softDeadlineMs: number;
23
+ reserveMs: number;
24
+ }
25
+ /** The time one capture may take: the base, plus what the request itself asks for, up to the cap.
26
+ * @throws RangeError when the reserve is not above 0 and below the total (a host configuration bug).
27
+ * @complexity O(1). */
28
+ export declare function captureBudget({ settleMs, fullPage, waitForSeconds }: CaptureRequest, { baseMs, fullPageMs, capMs, reserveMs }: CaptureBudgetLimits): CaptureBudget;
29
+ //# sourceMappingURL=capture-budget.d.ts.map
@@ -0,0 +1,14 @@
1
+ /** A request value that is not a finite, positive number adds nothing. */
2
+ const extraMs = ({ value, unitMs }) => value !== undefined && Number.isFinite(value) && value > 0 ? value * unitMs : 0;
3
+ /** The time one capture may take: the base, plus what the request itself asks for, up to the cap.
4
+ * @throws RangeError when the reserve is not above 0 and below the total (a host configuration bug).
5
+ * @complexity O(1). */
6
+ export function captureBudget({ settleMs, fullPage, waitForSeconds }, { baseMs, fullPageMs, capMs, reserveMs }) {
7
+ const waitMs = waitForSeconds === undefined ? extraMs({ value: settleMs, unitMs: 1 }) : extraMs({ value: waitForSeconds, unitMs: 1_000 });
8
+ const totalMs = Math.min(capMs, baseMs + waitMs + (fullPage === true ? fullPageMs : 0));
9
+ if (!(reserveMs > 0 && reserveMs < totalMs)) {
10
+ throw new RangeError(`capture reserve ${reserveMs}ms must be above 0 and below the capture total ${totalMs}ms`);
11
+ }
12
+ return { totalMs, softDeadlineMs: totalMs - reserveMs, reserveMs };
13
+ }
14
+ //# sourceMappingURL=capture-budget.js.map
@@ -0,0 +1,12 @@
1
+ /** Time port for one page capture: the work budget, its timers and the hard-stop signal read the same clock,
2
+ * so a test can drive every deadline of a capture from one fake. Defaults to the real functions. */
3
+ export interface CaptureClock {
4
+ now(): number;
5
+ setTimeout(fn: () => void, ms: number): unknown;
6
+ clearTimeout(handle: unknown): void;
7
+ /** A signal that aborts with a TimeoutError after `ms` of this clock. */
8
+ deadlineSignal(ms: number): AbortSignal;
9
+ }
10
+ /** The real clock. Globals are read at call time so fake-timer test setups still apply. */
11
+ export declare const REAL_CAPTURE_CLOCK: CaptureClock;
12
+ //# sourceMappingURL=capture-clock.d.ts.map
@@ -0,0 +1,8 @@
1
+ /** The real clock. Globals are read at call time so fake-timer test setups still apply. */
2
+ export const REAL_CAPTURE_CLOCK = {
3
+ now: () => Date.now(),
4
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
5
+ clearTimeout: handle => clearTimeout(handle),
6
+ deadlineSignal: ms => AbortSignal.timeout(ms),
7
+ };
8
+ //# sourceMappingURL=capture-clock.js.map
@@ -0,0 +1,22 @@
1
+ /** One `Set-Cookie` header, with the value removed. */
2
+ export interface CookieShape {
3
+ name: string;
4
+ /** `Secure`, `HttpOnly`, `SameSite=Lax`, `Path=/`, ... — verbatim, minus the `name=value` pair. */
5
+ attributes: string[];
6
+ }
7
+ /**
8
+ * Strips the value from each `Set-Cookie` header, keeping the name and the attribute list.
9
+ *
10
+ * `Headers.getSetCookie()` is used rather than `headers.get("set-cookie")` because the latter joins
11
+ * multiple cookies with `, `, which is ambiguous (an `Expires` attribute legally contains a comma)
12
+ * and would corrupt the split.
13
+ *
14
+ * @param required.headers - The fetch response's headers.
15
+ * @returns One entry per `Set-Cookie` header, in wire order. Empty array when none were sent.
16
+ * @complexity O(C * A) in cookie count and attributes per cookie — both bounded by the response.
17
+ * @example toCookieShapes({ headers: res.headers }); // => [{ name: "sid", attributes: ["Path=/", "HttpOnly"] }]
18
+ */
19
+ export declare function toCookieShapes({ headers }: {
20
+ headers: Headers;
21
+ }, _optional?: {}): CookieShape[];
22
+ //# sourceMappingURL=cookie-shapes.d.ts.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Strips the value from each `Set-Cookie` header, keeping the name and the attribute list.
3
+ *
4
+ * `Headers.getSetCookie()` is used rather than `headers.get("set-cookie")` because the latter joins
5
+ * multiple cookies with `, `, which is ambiguous (an `Expires` attribute legally contains a comma)
6
+ * and would corrupt the split.
7
+ *
8
+ * @param required.headers - The fetch response's headers.
9
+ * @returns One entry per `Set-Cookie` header, in wire order. Empty array when none were sent.
10
+ * @complexity O(C * A) in cookie count and attributes per cookie — both bounded by the response.
11
+ * @example toCookieShapes({ headers: res.headers }); // => [{ name: "sid", attributes: ["Path=/", "HttpOnly"] }]
12
+ */
13
+ export function toCookieShapes({ headers }, _optional = {}) {
14
+ const raw = typeof headers.getSetCookie === "function" ? headers.getSetCookie() : [];
15
+ return raw.map((cookie) => {
16
+ const parts = cookie.split(";");
17
+ // `split` always yields at least one element, so the `name=value` pair is always present.
18
+ const pair = parts[0];
19
+ const equals = pair.indexOf("=");
20
+ return {
21
+ name: (equals >= 0 ? pair.slice(0, equals) : pair).trim(),
22
+ attributes: parts.slice(1).map((part) => part.trim()).filter((part) => part.length > 0),
23
+ };
24
+ });
25
+ }
26
+ //# sourceMappingURL=cookie-shapes.js.map
@@ -1,6 +1,9 @@
1
1
  export * from "./browser-port.js";
2
2
  export * from "./collect-page-evidence.js";
3
3
  export * from "./same-origin.js";
4
+ export * from "./path-guard.js";
5
+ export * from "./bounded-body.js";
6
+ export * from "./cookie-shapes.js";
4
7
  export { collectPageStructure, type PageStructureCapture, type PageStructureLimits } from "./page-structure-script.js";
5
8
  export { collectPagePerformance, type PagePerformanceEvidence } from "./page-performance-script.js";
6
9
  //# sourceMappingURL=index.d.ts.map
@@ -1,6 +1,9 @@
1
1
  export * from "./browser-port.js";
2
2
  export * from "./collect-page-evidence.js";
3
3
  export * from "./same-origin.js";
4
+ export * from "./path-guard.js";
5
+ export * from "./bounded-body.js";
6
+ export * from "./cookie-shapes.js";
4
7
  export { collectPageStructure } from "./page-structure-script.js";
5
8
  export { collectPagePerformance } from "./page-performance-script.js";
6
9
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,37 @@
1
+ /** t08: shared HTML/text/find projection. Network producers also enforce a raw 1 MB ceiling. */
2
+ export declare const DEFAULT_MAX_BODY_BYTES = 20000;
3
+ export declare const MAX_MAX_BODY_BYTES = 1000000;
4
+ export interface PageBodyOptions {
5
+ maxBytes?: number | undefined;
6
+ find?: string | undefined;
7
+ textOnly?: boolean | undefined;
8
+ }
9
+ export type ShapedPageBody = {
10
+ bodyBytes: number;
11
+ truncated: boolean;
12
+ } & ({
13
+ body: string;
14
+ matches?: never;
15
+ matchCount?: never;
16
+ } | {
17
+ matches: Array<{
18
+ offset: number;
19
+ snippet: string;
20
+ }>;
21
+ matchCount: number;
22
+ body?: never;
23
+ });
24
+ /** Validates all shared options at the tool boundary; no implicit coercion or silent defaults. */
25
+ export declare function readPageBodyOptions({ input }: {
26
+ input: Record<string, unknown>;
27
+ }, _optional?: Record<string, never>): PageBodyOptions;
28
+ /**
29
+ * Shapes available page text, stripping before capping. With find, offsets are UTF-16 positions in
30
+ * the shaped source; matchCount counts non-overlapping matches in that source, even after the
31
+ * snippet budget is exhausted. Producers OR their raw-read truncation into this flag.
32
+ * @returns Body or matches (never both), source byte count and an explicit truncation flag.
33
+ */
34
+ export declare function shapePageBody({ body }: {
35
+ body: string;
36
+ }, options?: PageBodyOptions): ShapedPageBody;
37
+ //# sourceMappingURL=page-body.d.ts.map
@@ -0,0 +1,112 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { ToolInputError } from "@jini-ai/core";
3
+ import { parse } from "parse5";
4
+ /** t08: shared HTML/text/find projection. Network producers also enforce a raw 1 MB ceiling. */
5
+ export const DEFAULT_MAX_BODY_BYTES = 20_000;
6
+ export const MAX_MAX_BODY_BYTES = 1_000_000;
7
+ /** Validates all shared options at the tool boundary; no implicit coercion or silent defaults. */
8
+ export function readPageBodyOptions({ input }, _optional = {}) {
9
+ const { find, textOnly, maxBytes } = input;
10
+ if (find !== undefined && (typeof find !== "string" || find.length < 1 || find.length > 200))
11
+ throw new ToolInputError({ message: "find must be a string of 1..200 characters." });
12
+ if (textOnly !== undefined && typeof textOnly !== "boolean")
13
+ throw new ToolInputError({ message: "textOnly must be a boolean." });
14
+ assertMaxBodyBytes({ maxBytes });
15
+ return { find: find, textOnly: textOnly, maxBytes: maxBytes };
16
+ }
17
+ /** Keeps the numeric budget validation and its boundary error together. */
18
+ function assertMaxBodyBytes({ maxBytes }, _options = {}) {
19
+ if (maxBytes === undefined)
20
+ return;
21
+ if (typeof maxBytes !== "number" || !Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_MAX_BODY_BYTES)
22
+ throw new ToolInputError({ message: "maxBytes must be an integer of 1..1000000." });
23
+ }
24
+ const OMITTED_ELEMENTS = new Set(["script", "style", "noscript", "template"]);
25
+ const BLOCK_ELEMENTS = new Set(["html", "head", "body", "p", "div", "section", "article", "main", "header", "footer", "nav", "br", "li", "ul", "ol", "table", "tr", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "pre", "blockquote"]);
26
+ /** Iterative traversal avoids stack overflow on deeply nested untrusted HTML. Parser decodes entities. */
27
+ function visibleText({ body }, _optional = {}) {
28
+ const pending = [parse(body)];
29
+ const text = [];
30
+ while (pending.length) {
31
+ appendVisibleNode({ node: pending.pop(), pending, text });
32
+ }
33
+ return text.join("").replace(/\s+/g, " ").trim();
34
+ }
35
+ /** Visits one parsed node, scheduling children in document order and spaces around blocks. */
36
+ function appendVisibleNode({ node, pending, text }, _options = {}) {
37
+ if (typeof node === "string") {
38
+ text.push(node);
39
+ return;
40
+ }
41
+ if ("tagName" in node && OMITTED_ELEMENTS.has(node.tagName))
42
+ return;
43
+ if (node.nodeName === "#text" && "value" in node) {
44
+ text.push(node.value);
45
+ return;
46
+ }
47
+ scheduleVisibleChildren({ node, pending, text });
48
+ }
49
+ /** Schedules children in document order, surrounding blocks with deferred closing spaces. */
50
+ function scheduleVisibleChildren({ node, pending, text }, _options = {}) {
51
+ if (!("childNodes" in node))
52
+ return;
53
+ const block = "tagName" in node && BLOCK_ELEMENTS.has(node.tagName);
54
+ if (block) {
55
+ text.push(" ");
56
+ pending.push(" ");
57
+ }
58
+ for (let i = node.childNodes.length - 1; i >= 0; i--)
59
+ pending.push(node.childNodes[i]);
60
+ }
61
+ /** Cuts at a UTF-8 boundary so shaping does not expand a clipped byte into a replacement character. */
62
+ function capText({ body, maxBytes }, _optional = {}) {
63
+ const bytes = Buffer.from(body);
64
+ if (bytes.length <= maxBytes)
65
+ return body;
66
+ let end = maxBytes;
67
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80)
68
+ end--;
69
+ return bytes.subarray(0, end).toString("utf8");
70
+ }
71
+ /** O(body length + matches); counts the full available source, retains at most 20 bounded snippets. */
72
+ function findMatches({ body, find, maxBytes }, _optional = {}) {
73
+ const pattern = new RegExp(RegExp.escape(find), "giu");
74
+ const matches = [];
75
+ let matchCount = 0;
76
+ let bytesLeft = maxBytes;
77
+ let truncated = false;
78
+ for (const match of body.matchAll(pattern)) {
79
+ matchCount++;
80
+ if (matches.length === 20 || bytesLeft === 0) {
81
+ truncated = true;
82
+ continue;
83
+ }
84
+ const offset = match.index;
85
+ const context = body.slice(Math.max(0, offset - 160), offset + match[0].length + 160);
86
+ const snippet = capText({ body: context, maxBytes: bytesLeft });
87
+ if (snippet !== context)
88
+ truncated = true;
89
+ bytesLeft -= Buffer.byteLength(snippet);
90
+ matches.push({ offset, snippet });
91
+ }
92
+ return { matches, matchCount, bodyBytes: Buffer.byteLength(body), truncated };
93
+ }
94
+ /**
95
+ * Shapes available page text, stripping before capping. With find, offsets are UTF-16 positions in
96
+ * the shaped source; matchCount counts non-overlapping matches in that source, even after the
97
+ * snippet budget is exhausted. Producers OR their raw-read truncation into this flag.
98
+ * @returns Body or matches (never both), source byte count and an explicit truncation flag.
99
+ */
100
+ export function shapePageBody({ body }, options = {}) {
101
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BODY_BYTES;
102
+ const source = options.textOnly ? visibleText({ body }) : body;
103
+ if (options.find !== undefined)
104
+ return findMatches({ body: source, find: options.find, maxBytes });
105
+ // Preserve the existing raw-page decode behavior at a split multibyte character.
106
+ const bytes = Buffer.from(source);
107
+ if (bytes.length <= maxBytes)
108
+ return { body: source, bodyBytes: bytes.length, truncated: false };
109
+ const capped = options.textOnly ? capText({ body: source, maxBytes }) : bytes.subarray(0, maxBytes).toString("utf8");
110
+ return { body: capped, bodyBytes: options.textOnly ? Buffer.byteLength(capped) : maxBytes, truncated: true };
111
+ }
112
+ //# sourceMappingURL=page-body.js.map
@@ -1,20 +1,36 @@
1
+ import { type CaptureClock } from "./capture-clock.js";
1
2
  /** Internal deadline shared by every asynchronous step of one page observation. */
2
3
  export declare class PageWorkTimeout extends Error {
3
4
  constructor({ timeoutMs }: {
4
5
  timeoutMs: number;
5
6
  });
6
7
  }
8
+ /** The ordinary-work limit of a capture that keeps a fallback reserve. It is a PageWorkTimeout, so every
9
+ * existing handler that lets a page timeout through keeps doing so; the renderer alone tells it apart. */
10
+ export declare class PageWorkDeadline extends PageWorkTimeout {
11
+ }
7
12
  /** A timeout is a budget for the whole page, not a fresh allowance for each browser operation. */
8
13
  export declare class PageWorkBudget {
9
14
  private readonly expiresAt;
10
15
  private readonly timeoutMs;
11
16
  private readonly signal;
17
+ private readonly clock;
18
+ private readonly workDeadlineMs;
19
+ private workEndsAt;
20
+ /** `workDeadlineMs` ends the ordinary-work phase early; `endWorkPhase()` then lifts it for the fallback window. */
12
21
  constructor({ timeoutMs }: {
13
22
  timeoutMs: number;
14
- }, { signal }?: {
23
+ }, { signal, clock, workDeadlineMs }?: {
15
24
  signal?: AbortSignal;
25
+ clock?: CaptureClock;
26
+ workDeadlineMs?: number;
16
27
  });
28
+ /** Time left to the limit that applies now: the work deadline during the work phase, else the total. */
17
29
  remainingMs(): number;
30
+ /** From now on only the total budget limits work (the fallback window). Safe to call more than once. */
31
+ endWorkPhase(): void;
32
+ /** The error for hitting the limit that applies now. */
33
+ expiredError(): PageWorkTimeout;
18
34
  /** Races even APIs without native timeouts (evaluation/cookies) and never starts expired work.
19
35
  * @complexity O(1) time and space apart from the injected operation. */
20
36
  run<T>({ work }: {
@@ -1,3 +1,5 @@
1
+ import { observed } from "@jini-ai/core/errors/idioms";
2
+ import { REAL_CAPTURE_CLOCK } from "./capture-clock.js";
1
3
  /** Internal deadline shared by every asynchronous step of one page observation. */
2
4
  export class PageWorkTimeout extends Error {
3
5
  constructor({ timeoutMs }) {
@@ -5,24 +7,44 @@ export class PageWorkTimeout extends Error {
5
7
  this.name = "PageWorkTimeout";
6
8
  }
7
9
  }
10
+ /** The ordinary-work limit of a capture that keeps a fallback reserve. It is a PageWorkTimeout, so every
11
+ * existing handler that lets a page timeout through keeps doing so; the renderer alone tells it apart. */
12
+ export class PageWorkDeadline extends PageWorkTimeout {
13
+ }
8
14
  /** A timeout is a budget for the whole page, not a fresh allowance for each browser operation. */
9
15
  export class PageWorkBudget {
10
16
  expiresAt;
11
17
  timeoutMs;
12
18
  signal;
13
- constructor({ timeoutMs }, { signal } = {}) {
19
+ clock;
20
+ workDeadlineMs;
21
+ workEndsAt;
22
+ /** `workDeadlineMs` ends the ordinary-work phase early; `endWorkPhase()` then lifts it for the fallback window. */
23
+ constructor({ timeoutMs }, { signal, clock = REAL_CAPTURE_CLOCK, workDeadlineMs } = {}) {
14
24
  this.signal = signal;
15
25
  this.timeoutMs = timeoutMs;
16
- this.expiresAt = Date.now() + timeoutMs;
26
+ this.clock = clock;
27
+ this.expiresAt = clock.now() + timeoutMs;
28
+ this.workDeadlineMs = workDeadlineMs;
29
+ this.workEndsAt = workDeadlineMs === undefined ? undefined : clock.now() + workDeadlineMs;
30
+ }
31
+ /** Time left to the limit that applies now: the work deadline during the work phase, else the total. */
32
+ remainingMs() { return Math.max(0, (this.workEndsAt ?? this.expiresAt) - this.clock.now()); }
33
+ /** From now on only the total budget limits work (the fallback window). Safe to call more than once. */
34
+ endWorkPhase() { this.workEndsAt = undefined; }
35
+ /** The error for hitting the limit that applies now. */
36
+ expiredError() {
37
+ return this.workDeadlineMs !== undefined && this.workEndsAt !== undefined
38
+ ? new PageWorkDeadline({ timeoutMs: this.workDeadlineMs })
39
+ : new PageWorkTimeout({ timeoutMs: this.timeoutMs });
17
40
  }
18
- remainingMs() { return Math.max(0, this.expiresAt - Date.now()); }
19
41
  /** Races even APIs without native timeouts (evaluation/cookies) and never starts expired work.
20
42
  * @complexity O(1) time and space apart from the injected operation. */
21
43
  async run({ work }) {
22
44
  this.signal?.throwIfAborted();
23
45
  const remaining = this.remainingMs();
24
46
  if (remaining <= 0)
25
- throw new PageWorkTimeout({ timeoutMs: this.timeoutMs });
47
+ throw this.expiredError();
26
48
  let timer;
27
49
  let onAbort;
28
50
  try {
@@ -35,12 +57,12 @@ export class PageWorkBudget {
35
57
  onAbort();
36
58
  })] : []),
37
59
  new Promise((_resolve, reject) => {
38
- timer = setTimeout(() => reject(new PageWorkTimeout({ timeoutMs: this.timeoutMs })), remaining);
60
+ timer = this.clock.setTimeout(() => reject(this.expiredError()), remaining);
39
61
  }),
40
62
  ]);
41
63
  }
42
64
  finally {
43
- clearTimeout(timer);
65
+ this.clock.clearTimeout(timer);
44
66
  if (onAbort)
45
67
  this.signal?.removeEventListener("abort", onAbort);
46
68
  }
@@ -51,11 +73,11 @@ export class PageWorkBudget {
51
73
  async release({ close }) {
52
74
  const closing = close();
53
75
  if (this.remainingMs() <= 0 || this.signal?.aborted) {
54
- void closing.catch(() => { });
76
+ observed({ promise: closing });
55
77
  return;
56
78
  }
57
79
  try {
58
- await new PageWorkBudget({ timeoutMs: this.remainingMs() }, this.signal ? { signal: this.signal } : {}).run({ work: () => closing });
80
+ await new PageWorkBudget({ timeoutMs: this.remainingMs() }, { clock: this.clock, ...(this.signal ? { signal: this.signal } : {}) }).run({ work: () => closing });
59
81
  }
60
82
  catch (error) {
61
83
  if (!(error instanceof PageWorkTimeout) && !this.signal?.aborted)
@@ -0,0 +1,119 @@
1
+ /**
2
+ * @file The path guard for tools that fetch a route of the host's OWN site: a caller-supplied
3
+ * path is validated allowlist-style, then resolved against an origin the host minted, so no input
4
+ * can steer the request to another host. The host's own pathname policy (which surfaces are
5
+ * reserved) is injected as `checkPathname`; nothing here names a surface.
6
+ *
7
+ * Not the same as `resolveSameOriginUrl` in `same-origin.ts`, which only joins a normalized path
8
+ * onto a verified base for the headless-browser collector. This one is the stricter, error-class
9
+ * raising check for a request the host sends itself.
10
+ */
11
+ /** Longest path string accepted before validation even begins. */
12
+ export declare const MAX_PATH_LENGTH = 2048;
13
+ /**
14
+ * Raised when `path` is not a fetchable same-origin path. Its own class so a tool layer can
15
+ * publish the input schema back with it: every rejection here is one a DIFFERENT `path` would fix.
16
+ */
17
+ export declare class SameOriginPathError extends Error {
18
+ constructor({ message }: {
19
+ message: string;
20
+ });
21
+ }
22
+ /**
23
+ * Refuses any `..` segment in a raw path, before and after ONE percent-decode.
24
+ *
25
+ * Runs on the RAW string rather than a parsed `URL.pathname` because `new URL()` resolves `..`
26
+ * away silently — see the call site's own comment. One decode pass is the right depth: a
27
+ * double-encoded `%252e%252e` decodes to the literal text `%2e%2e`, which a static-file handler
28
+ * treats as a filename, not as traversal.
29
+ *
30
+ * @param required.pathOnly - The raw path with any query string already removed.
31
+ * @param required.raw - The caller's original string, for the error message.
32
+ * @throws {SameOriginPathError} On a raw or singly-encoded `..` segment, or on a malformed
33
+ * percent-encoding (which cannot be decoded and therefore cannot be cleared).
34
+ * @complexity O(L) in the path length.
35
+ * @example assertNoTraversalSegment({ pathOnly: "/a/%2e%2e/b", raw: "/a/%2e%2e/b" }); // throws
36
+ */
37
+ export declare function assertNoTraversalSegment({ pathOnly, raw }: {
38
+ pathOnly: string;
39
+ raw: string;
40
+ }, _optional?: {}): void;
41
+ /**
42
+ * The syntactic rejections that operate on the raw caller value, before any URL parsing happens.
43
+ * Split out of {@link resolveSameOriginPath} purely to keep that function's own complexity below
44
+ * the repo's gate — the checks, their order, and every message are unchanged.
45
+ *
46
+ * @throws {SameOriginPathError} On the first rule `raw` fails.
47
+ * @returns `raw`, narrowed to `string`, once every rule has passed.
48
+ */
49
+ export declare function assertRawPathShape({ raw }: {
50
+ raw: unknown;
51
+ }, _optional?: {}): string;
52
+ /**
53
+ * Parses `raw` against `base` and asserts the result stayed on `base`'s origin. Split out of
54
+ * {@link resolveSameOriginPath} purely to keep that function's own complexity below the repo's
55
+ * gate — the structural same-origin assertion itself is unchanged.
56
+ *
57
+ * @throws {SameOriginPathError} If `raw` does not parse, or parses off-origin.
58
+ */
59
+ export declare function resolveWithinOrigin({ raw, base }: {
60
+ raw: string;
61
+ base: string;
62
+ }, _optional?: {}): URL;
63
+ /**
64
+ * What the host's pathname policy says about a resolved pathname. `refused` carries the host's own
65
+ * complete refusal sentence (for example a reserved surface), so this module never names a surface.
66
+ */
67
+ export type PathnameVerdict = {
68
+ kind: "ok";
69
+ } | {
70
+ kind: "malformed-encoding";
71
+ } | {
72
+ kind: "disallowed-character";
73
+ } | {
74
+ kind: "refused";
75
+ reason: string;
76
+ };
77
+ /**
78
+ * Validates and canonicalizes a caller-supplied site path against the loopback origin this module
79
+ * minted, following canonicalize-then-validate order.
80
+ *
81
+ * Each rule closes a specific hole rather than being defensive in general:
82
+ * - **must be a non-empty string within {@link MAX_PATH_LENGTH}** — bounds the work every later
83
+ * check does.
84
+ * - **must start with `/`** — rejects an absolute URL (`http://evil.example/x`) and a bare relative
85
+ * path, both of which would resolve somewhere other than this site's root.
86
+ * - **must not start with `//`** — a protocol-relative URL resolves to a DIFFERENT HOST while still
87
+ * starting with a slash. This is the single most commonly missed same-origin bypass.
88
+ * - **no backslash anywhere** — `\` is treated as `/` by URL parsers and browsers, so `/\evil.com`
89
+ * is a protocol-relative URL wearing a disguise.
90
+ * - **no C0/C1 control characters** — CR/LF in a request target is HTTP request splitting; NUL and
91
+ * friends are path-truncation tricks.
92
+ * - **`new URL(raw, base)` must keep `base`'s origin** — the structural assertion. Everything above
93
+ * is belt; this is braces, and it compares against the origin this process minted rather than
94
+ * against a pattern someone has to keep correct.
95
+ * - **no `..` segment after ONE percent-decode** — blocks `%2e%2e` and its double-encoded variants
96
+ * from reaching a static-file handler. `..` cannot escape the origin, but it can escape a
97
+ * directory, and a single decode pass is enough because the check runs on the decoded form and
98
+ * rejects a remaining `%` sequence that decodes to a traversal.
99
+ * - **the host's pathname policy** (`checkPathname`) — the resolved pathname is handed to the policy the
100
+ * caller injects. This module does not know which surfaces a host reserves; see
101
+ * `site-path-policy.ts` for this site's rule and why it exists.
102
+ *
103
+ * @param raw - The caller's path, untrusted.
104
+ * @param base - The loopback origin this call minted, e.g. `http://127.0.0.1:53142`.
105
+ * @param checkPathname - The host's pathname policy, run on the resolved URL.
106
+ * @returns The canonical `pathname + search` to request, re-encoded by the URL parser.
107
+ * @throws {SameOriginPathError} With a message naming the specific rule that rejected it, so the
108
+ * model can fix the input in one turn instead of guessing.
109
+ * @complexity O(L) in the path length, bounded by {@link MAX_PATH_LENGTH}.
110
+ * @example resolveSameOriginPath({ raw: "/blog/hello", base: "http://127.0.0.1:53142", checkPathname: () => ({ kind: "ok" }) }); // => "/blog/hello"
111
+ */
112
+ export declare function resolveSameOriginPath({ raw, base, checkPathname }: {
113
+ raw: unknown;
114
+ base: string;
115
+ checkPathname: (required: {
116
+ url: URL;
117
+ }) => PathnameVerdict;
118
+ }, _optional?: {}): string;
119
+ //# sourceMappingURL=path-guard.d.ts.map