@jini-ai/diagnostics 0.7.2 → 0.7.3-next.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.
Files changed (65) hide show
  1. package/CHANGELOG.md +2 -8
  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 +1 -1
  20. package/dist/observability/hooks.d.ts +2 -1
  21. package/dist/observability/hooks.js +1 -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 +54 -6
  64. package/dist/observability/noop.d.ts +0 -7
  65. package/dist/observability/noop.js +0 -27
@@ -0,0 +1,200 @@
1
+ import { hasControlCharacter } from "@jini-ai/core/contracts/server/verified-origin";
2
+ /**
3
+ * @file The path guard for tools that fetch a route of the host's OWN site: a caller-supplied
4
+ * path is validated allowlist-style, then resolved against an origin the host minted, so no input
5
+ * can steer the request to another host. The host's own pathname policy (which surfaces are
6
+ * reserved) is injected as `checkPathname`; nothing here names a surface.
7
+ *
8
+ * Not the same as `resolveSameOriginUrl` in `same-origin.ts`, which only joins a normalized path
9
+ * onto a verified base for the headless-browser collector. This one is the stricter, error-class
10
+ * raising check for a request the host sends itself.
11
+ */
12
+ /** Longest path string accepted before validation even begins. */
13
+ export const MAX_PATH_LENGTH = 2_048;
14
+ /**
15
+ * Raised when `path` is not a fetchable same-origin path. Its own class so a tool layer can
16
+ * publish the input schema back with it: every rejection here is one a DIFFERENT `path` would fix.
17
+ */
18
+ export class SameOriginPathError extends Error {
19
+ constructor({ message }) {
20
+ super(message);
21
+ this.name = "SameOriginPathError";
22
+ }
23
+ }
24
+ /**
25
+ * Refuses any `..` segment in a raw path, before and after ONE percent-decode.
26
+ *
27
+ * Runs on the RAW string rather than a parsed `URL.pathname` because `new URL()` resolves `..`
28
+ * away silently — see the call site's own comment. One decode pass is the right depth: a
29
+ * double-encoded `%252e%252e` decodes to the literal text `%2e%2e`, which a static-file handler
30
+ * treats as a filename, not as traversal.
31
+ *
32
+ * @param required.pathOnly - The raw path with any query string already removed.
33
+ * @param required.raw - The caller's original string, for the error message.
34
+ * @throws {SameOriginPathError} On a raw or singly-encoded `..` segment, or on a malformed
35
+ * percent-encoding (which cannot be decoded and therefore cannot be cleared).
36
+ * @complexity O(L) in the path length.
37
+ * @example assertNoTraversalSegment({ pathOnly: "/a/%2e%2e/b", raw: "/a/%2e%2e/b" }); // throws
38
+ */
39
+ export function assertNoTraversalSegment({ pathOnly, raw }, _optional = {}) {
40
+ for (const segment of pathOnly.split("/")) {
41
+ if (segment === "..") {
42
+ throw new SameOriginPathError({ message: `path must not contain a '..' segment (encoded or not): '${raw}'.` });
43
+ }
44
+ if (!segment.includes("%"))
45
+ continue;
46
+ let decoded;
47
+ try {
48
+ decoded = decodeURIComponent(segment);
49
+ }
50
+ catch {
51
+ throw new SameOriginPathError({ message: `path contains a malformed percent-encoding: '${raw}'.` });
52
+ }
53
+ if (decoded === "..") {
54
+ throw new SameOriginPathError({ message: `path must not contain a '..' segment (encoded or not): '${raw}'.` });
55
+ }
56
+ }
57
+ }
58
+ /**
59
+ * The syntactic rejections that operate on the raw caller value, before any URL parsing happens.
60
+ * Split out of {@link resolveSameOriginPath} purely to keep that function's own complexity below
61
+ * the repo's gate — the checks, their order, and every message are unchanged.
62
+ *
63
+ * @throws {SameOriginPathError} On the first rule `raw` fails.
64
+ * @returns `raw`, narrowed to `string`, once every rule has passed.
65
+ */
66
+ export function assertRawPathShape({ raw }, _optional = {}) {
67
+ if (typeof raw !== "string" || raw.length === 0) {
68
+ throw new SameOriginPathError({ message: "path must be a non-empty string, e.g. '/' or '/blog/hello'." });
69
+ }
70
+ if (raw.length > MAX_PATH_LENGTH) {
71
+ throw new SameOriginPathError({ message: `path must be at most ${MAX_PATH_LENGTH} characters, got ${raw.length}.` });
72
+ }
73
+ if (!raw.startsWith("/")) {
74
+ throw new SameOriginPathError({ message: `path must start with '/' — this tool fetches a route on THIS site and never accepts a full URL or a remote host. Got '${raw}'.` });
75
+ }
76
+ if (raw.startsWith("//")) {
77
+ throw new SameOriginPathError({ message: "path must not start with '//' — a protocol-relative path resolves to a different host, which this tool never fetches." });
78
+ }
79
+ if (raw.includes("\\")) {
80
+ throw new SameOriginPathError({ message: "path must not contain a backslash — URL parsers treat '\\' as '/'." });
81
+ }
82
+ if (hasControlCharacter({ value: raw })) {
83
+ throw new SameOriginPathError({ message: "path must not contain control characters (including CR/LF)." });
84
+ }
85
+ // BEFORE `new URL()`, because the URL parser RESOLVES `..` away rather than reporting it:
86
+ // `new URL("/a/../../etc/passwd", base).pathname` is already `/etc/passwd`, so a check on the
87
+ // parsed pathname sees nothing to reject. Silent normalization is exactly the "rewrite rather
88
+ // than refuse" behavior this validator must not have — a caller that wrote `..` gets told so.
89
+ const queryStart = raw.indexOf("?");
90
+ assertNoTraversalSegment({ pathOnly: queryStart === -1 ? raw : raw.slice(0, queryStart), raw });
91
+ return raw;
92
+ }
93
+ /**
94
+ * Parses `raw` against `base` and asserts the result stayed on `base`'s origin. Split out of
95
+ * {@link resolveSameOriginPath} purely to keep that function's own complexity below the repo's
96
+ * gate — the structural same-origin assertion itself is unchanged.
97
+ *
98
+ * @throws {SameOriginPathError} If `raw` does not parse, or parses off-origin.
99
+ */
100
+ export function resolveWithinOrigin({ raw, base }, _optional = {}) {
101
+ const baseUrl = new URL(base);
102
+ let resolved;
103
+ try {
104
+ resolved = new URL(raw, baseUrl);
105
+ }
106
+ catch {
107
+ throw new SameOriginPathError({ message: `path is not a valid URL path: '${raw}'.` });
108
+ }
109
+ if (resolved.origin !== baseUrl.origin) {
110
+ throw new SameOriginPathError({ message: `path resolved off-origin (to '${resolved.origin}') — this tool only fetches routes on this site.` });
111
+ }
112
+ return resolved;
113
+ }
114
+ /**
115
+ * Why a resolved pathname was refused, phrased for this module's caller.
116
+ *
117
+ * Split out of {@link assertNoDisallowedDecodedForm} so the wording lives next to the verdict
118
+ * union it exhausts: with an explicit `string | null` return type and no `default` arm, a future
119
+ * case added to `PathnameVerdict` is a compile error here rather than a silent fall-through to
120
+ * "allowed".
121
+ *
122
+ * The reserved-surface rule itself is deliberately NOT restated here: the host owns it, and a
123
+ * second copy of a denylist is how one of them ends up a decode or a case-fold behind the other.
124
+ *
125
+ * @param required.check - The verdict from the host's pathname policy.
126
+ * @param required.raw - The original caller-supplied path, for the error message only.
127
+ * @returns The refusal message, or `null` when the path is allowed.
128
+ * @complexity O(1).
129
+ */
130
+ function disallowedFormReason({ check, raw }, _optional = {}) {
131
+ switch (check.kind) {
132
+ case "ok":
133
+ return null;
134
+ case "malformed-encoding":
135
+ return `path contains a malformed percent-encoding: '${raw}'.`;
136
+ case "disallowed-character":
137
+ return "path decodes to a backslash or control character, which is refused.";
138
+ case "refused":
139
+ return check.reason;
140
+ default: {
141
+ const unhandled = check;
142
+ throw new TypeError(`Unknown site path verdict: ${String(unhandled)}`);
143
+ }
144
+ }
145
+ }
146
+ /**
147
+ * Applies the host's pathname policy to the resolved pathname and maps its verdict onto this
148
+ * module's own error type. Split out purely to keep {@link resolveSameOriginPath} below the repo's
149
+ * complexity gate.
150
+ *
151
+ * @throws {SameOriginPathError} On a malformed encoding, a decoded backslash/control character,
152
+ * or a pathname the host policy refuses.
153
+ */
154
+ function assertNoDisallowedDecodedForm({ resolved, raw, checkPathname }, _optional = {}) {
155
+ const reason = disallowedFormReason({ check: checkPathname({ url: resolved }), raw });
156
+ if (reason !== null)
157
+ throw new SameOriginPathError({ message: reason });
158
+ }
159
+ /**
160
+ * Validates and canonicalizes a caller-supplied site path against the loopback origin this module
161
+ * minted, following canonicalize-then-validate order.
162
+ *
163
+ * Each rule closes a specific hole rather than being defensive in general:
164
+ * - **must be a non-empty string within {@link MAX_PATH_LENGTH}** — bounds the work every later
165
+ * check does.
166
+ * - **must start with `/`** — rejects an absolute URL (`http://evil.example/x`) and a bare relative
167
+ * path, both of which would resolve somewhere other than this site's root.
168
+ * - **must not start with `//`** — a protocol-relative URL resolves to a DIFFERENT HOST while still
169
+ * starting with a slash. This is the single most commonly missed same-origin bypass.
170
+ * - **no backslash anywhere** — `\` is treated as `/` by URL parsers and browsers, so `/\evil.com`
171
+ * is a protocol-relative URL wearing a disguise.
172
+ * - **no C0/C1 control characters** — CR/LF in a request target is HTTP request splitting; NUL and
173
+ * friends are path-truncation tricks.
174
+ * - **`new URL(raw, base)` must keep `base`'s origin** — the structural assertion. Everything above
175
+ * is belt; this is braces, and it compares against the origin this process minted rather than
176
+ * against a pattern someone has to keep correct.
177
+ * - **no `..` segment after ONE percent-decode** — blocks `%2e%2e` and its double-encoded variants
178
+ * from reaching a static-file handler. `..` cannot escape the origin, but it can escape a
179
+ * directory, and a single decode pass is enough because the check runs on the decoded form and
180
+ * rejects a remaining `%` sequence that decodes to a traversal.
181
+ * - **the host's pathname policy** (`checkPathname`) — the resolved pathname is handed to the policy the
182
+ * caller injects. This module does not know which surfaces a host reserves; see
183
+ * `site-path-policy.ts` for this site's rule and why it exists.
184
+ *
185
+ * @param raw - The caller's path, untrusted.
186
+ * @param base - The loopback origin this call minted, e.g. `http://127.0.0.1:53142`.
187
+ * @param checkPathname - The host's pathname policy, run on the resolved URL.
188
+ * @returns The canonical `pathname + search` to request, re-encoded by the URL parser.
189
+ * @throws {SameOriginPathError} With a message naming the specific rule that rejected it, so the
190
+ * model can fix the input in one turn instead of guessing.
191
+ * @complexity O(L) in the path length, bounded by {@link MAX_PATH_LENGTH}.
192
+ * @example resolveSameOriginPath({ raw: "/blog/hello", base: "http://127.0.0.1:53142", checkPathname: () => ({ kind: "ok" }) }); // => "/blog/hello"
193
+ */
194
+ export function resolveSameOriginPath({ raw, base, checkPathname }, _optional = {}) {
195
+ const path = assertRawPathShape({ raw });
196
+ const resolved = resolveWithinOrigin({ raw: path, base });
197
+ assertNoDisallowedDecodedForm({ resolved, raw: path, checkPathname });
198
+ return `${resolved.pathname}${resolved.search}`;
199
+ }
200
+ //# sourceMappingURL=path-guard.js.map
@@ -82,21 +82,7 @@ class PlaywrightSiteEvidenceBrowser {
82
82
  timeoutMs: request.timeoutMs, originBaseUrl: request.originBaseUrl,
83
83
  // Consent evidence must stay pre-consent until the operator's explicit selector is clicked.
84
84
  dismissCookieBanners: false, loadWaitMs: 5_000,
85
- onRequest: ({ route, blocked }) => {
86
- const pending = route.request();
87
- const requestIndex = requests.length;
88
- recordRequest(requests, request, {
89
- method: pending.method().toUpperCase(), url: pending.url(), resourceType: pending.resourceType(), phase,
90
- ...(blocked ? { blockedReason: "aborted: this tool never sends a non-GET request, so no form, consent preference, or " +
91
- "analytics beacon it observes is ever actually submitted. Off-origin navigation is also refused." } : {}),
92
- });
93
- // Preserve the phase of the attempt even if a DNS/transport refusal finishes after consent.
94
- return ({ reason }) => {
95
- const observed = requests[requestIndex];
96
- if (observed)
97
- requests[requestIndex] = { ...observed, blockedReason: reason };
98
- };
99
- },
85
+ onRequest: createRequestRecorder(requests, request, () => phase),
100
86
  });
101
87
  }
102
88
  catch (error) {
@@ -149,6 +135,23 @@ class PlaywrightSiteEvidenceBrowser {
149
135
  }
150
136
  }
151
137
  }
138
+ function createRequestRecorder(requests, request, readPhase) {
139
+ return ({ route, blocked }) => {
140
+ const pending = route.request();
141
+ const requestIndex = requests.length;
142
+ recordRequest(requests, request, {
143
+ method: pending.method().toUpperCase(), url: pending.url(), resourceType: pending.resourceType(), phase: readPhase(),
144
+ ...(blocked ? { blockedReason: "aborted: this tool never sends a non-GET request, so no form, consent preference, or " +
145
+ "analytics beacon it observes is ever actually submitted. Off-origin navigation is also refused." } : {}),
146
+ });
147
+ // Preserve the phase of the attempt even if a DNS/transport refusal finishes after consent.
148
+ return ({ reason }) => {
149
+ const observed = requests[requestIndex];
150
+ if (observed)
151
+ requests[requestIndex] = { ...observed, blockedReason: reason };
152
+ };
153
+ };
154
+ }
152
155
  /**
153
156
  * Builds the self-contained JavaScript expression that runs `collectPageStructure` inside the page.
154
157
  *
@@ -1,48 +1,3 @@
1
- /**
2
- * @file The one and only module in this repository that touches a real headless browser.
3
- * Implements `SiteEvidenceBrowserPort` (`browser-port.ts`) on Playwright's Chromium.
4
- *
5
- * ---------------------------------------------------------------------------
6
- * Why the import is dynamic, and why the module's types are declared here
7
- * ---------------------------------------------------------------------------
8
- * The host may optionally install `playwright`; this package adds no browser dependency. The BROWSER
9
- * BINARY it drives needs a separate `playwright install chromium` step or an installed system
10
- * Chrome. Installing the module alone does not supply either binary. So both halves can
11
- * legitimately be missing at runtime, independently:
12
- *
13
- * - the module itself, on a deployment that pruned it;
14
- * - both browser binaries, on a deployment that installed the module but neither browser.
15
- *
16
- * Both are caught here and converted into `{ available: false, reason }`, never a thrown error and
17
- * never a boot failure. The tool then reports "no browser in this deployment" and the compliance
18
- * skill is required by its own output contract to downgrade every rendered-truth finding to
19
- * `cannot-determine`. That is the entire reason this adapter must not be a static import: a static
20
- * one would make an optional capability a hard boot dependency for every host install.
21
- *
22
- * {@link PlaywrightLike} and render-page.ts declare, structurally, the browser members this adapter uses.
23
- * That is deliberate rather than importing Playwright's own (very large) `.d.ts`: typechecking this
24
- * repository must not depend on a browser automation library's type surface being resolvable, and
25
- * naming the members used makes the actual coupling one short, reviewable block instead of an
26
- * open-ended import.
27
- *
28
- * ---------------------------------------------------------------------------
29
- * Privacy properties, enforced here rather than promised
30
- * ---------------------------------------------------------------------------
31
- * - **Ephemeral context.** `browser.newContext()` with no `storageState` and no user-data
32
- * directory. Cookies, storage, and cache exist only in memory and die with `close()`. Nothing is
33
- * written to disk by this module.
34
- * - **One context per page.** Each `observe()` call gets a fresh context, so a cookie set by page A
35
- * can never be reported as though page B set it — which would be an outright false citation in a
36
- * pre-consent cookie finding.
37
- * - **No non-GET request ever leaves the process.** Every request is intercepted; anything that is
38
- * not GET or HEAD is aborted and recorded as blocked. This is what makes "never submits forms" a
39
- * structural property instead of a policy: even if a page auto-submits, or a consent widget POSTs
40
- * preferences, the attempt is observed and the bytes do not go out.
41
- * These evidence privacy rules describe SiteEvidenceBrowserPort; public-page.ts separately
42
- * captures explicitly requested, bounded JSON response bodies, without cookies/credentials.
43
- * - **Values are never read.** Cookie values, request bodies, and form-field values are not
44
- * extracted anywhere below, because `browser-port.ts`'s shapes have nowhere to put them.
45
- */
46
1
  import type { RenderBrowser } from "./render-page.js";
47
2
  import type { RequestRouter } from "./request-guard.js";
48
3
  export interface PlaywrightLike {
@@ -1,3 +1,49 @@
1
+ /**
2
+ * @file The one and only module in this repository that touches a real headless browser.
3
+ * Implements `SiteEvidenceBrowserPort` (`browser-port.ts`) on Playwright's Chromium.
4
+ *
5
+ * ---------------------------------------------------------------------------
6
+ * Why the import is dynamic, and why the module's types are declared here
7
+ * ---------------------------------------------------------------------------
8
+ * The host may optionally install `playwright`; this package adds no browser dependency. The BROWSER
9
+ * BINARY it drives needs a separate `playwright install chromium` step or an installed system
10
+ * Chrome. Installing the module alone does not supply either binary. So both halves can
11
+ * legitimately be missing at runtime, independently:
12
+ *
13
+ * - the module itself, on a deployment that pruned it;
14
+ * - both browser binaries, on a deployment that installed the module but neither browser.
15
+ *
16
+ * Both are caught here and converted into `{ available: false, reason }`, never a thrown error and
17
+ * never a boot failure. The tool then reports "no browser in this deployment" and the compliance
18
+ * skill is required by its own output contract to downgrade every rendered-truth finding to
19
+ * `cannot-determine`. That is the entire reason this adapter must not be a static import: a static
20
+ * one would make an optional capability a hard boot dependency for every host install.
21
+ *
22
+ * {@link PlaywrightLike} and render-page.ts declare, structurally, the browser members this adapter uses.
23
+ * That is deliberate rather than importing Playwright's own (very large) `.d.ts`: typechecking this
24
+ * repository must not depend on a browser automation library's type surface being resolvable, and
25
+ * naming the members used makes the actual coupling one short, reviewable block instead of an
26
+ * open-ended import.
27
+ *
28
+ * ---------------------------------------------------------------------------
29
+ * Privacy properties, enforced here rather than promised
30
+ * ---------------------------------------------------------------------------
31
+ * - **Ephemeral context.** `browser.newContext()` with no `storageState` and no user-data
32
+ * directory. Cookies, storage, and cache exist only in memory and die with `close()`. Nothing is
33
+ * written to disk by this module.
34
+ * - **One context per page.** Each `observe()` call gets a fresh context, so a cookie set by page A
35
+ * can never be reported as though page B set it — which would be an outright false citation in a
36
+ * pre-consent cookie finding.
37
+ * - **No non-GET request ever leaves the process.** Every request is intercepted; anything that is
38
+ * not GET or HEAD is aborted and recorded as blocked. This is what makes "never submits forms" a
39
+ * structural property instead of a policy: even if a page auto-submits, or a consent widget POSTs
40
+ * preferences, the attempt is observed and the bytes do not go out.
41
+ * These evidence privacy rules describe SiteEvidenceBrowserPort; public-page.ts separately
42
+ * captures explicitly requested, bounded JSON response bodies, without cookies/credentials.
43
+ * - **Values are never read.** Cookie values, request bodies, and form-field values are not
44
+ * extracted anywhere below, because `browser-port.ts`'s shapes have nowhere to put them.
45
+ */
46
+ import { describeErrorForLog } from "@jini-ai/core";
1
47
  /** Default {@link PlaywrightAdapterOptions.moduleLoader}: a real dynamic import by module name, wired
2
48
  * here at the composition edge so the optional `playwright` dependency is only resolved on use. */
3
49
  export const nodeModuleLoader = {
@@ -18,7 +64,7 @@ export async function openPlaywrightRenderBrowser(_required, options = {}) {
18
64
  return {
19
65
  available: false,
20
66
  reason: "the 'playwright' package is not installed in this deployment, so rendered-page behaviour " +
21
- `cannot be observed here (${error instanceof Error ? error.message : String(error)})`,
67
+ `cannot be observed here (${describeErrorForLog({ err: error })}). Install it with 'npm install -D playwright' and then run 'npx playwright install --with-deps chromium'.`,
22
68
  };
23
69
  }
24
70
  let browser;
@@ -35,7 +81,7 @@ export async function openPlaywrightRenderBrowser(_required, options = {}) {
35
81
  return {
36
82
  available: false,
37
83
  reason: "Neither bundled Chromium nor system Chrome could be launched in this deployment — the 'playwright' package is present but the " +
38
- `browser binaries may be missing or the host may not support the configured sandbox (install Chrome or run 'npx playwright install --with-deps chromium'). Underlying error: ${error instanceof Error ? error.message : String(error)}`,
84
+ `browser binaries may be missing or the host may not support the configured sandbox (install Chrome or run 'npx playwright install --with-deps chromium'; launch failed with ${describeErrorForLog({ err: error })}).`,
39
85
  };
40
86
  }
41
87
  return { available: true, browser };
@@ -1,3 +1,4 @@
1
+ import { type CaptureClock } from "./capture-clock.js";
1
2
  import { PageWorkBudget } from "./page-work-budget.js";
2
3
  import { type RequestRouter, type RouteLike } from "./request-guard.js";
3
4
  /** Structural browser ports shared by evidence, public reading and screenshots. No vendor SDK. */
@@ -70,16 +71,29 @@ export interface RenderBrowser {
70
71
  newContext(options?: Record<string, unknown>): Promise<RenderContext>;
71
72
  close(): Promise<void>;
72
73
  }
74
+ /** Where ordinary work was when the soft deadline cut it short (see `RenderPageOptions.softDeadlineMs`). */
75
+ export type TimedOutPhase = "dismiss" | "wait" | "load";
73
76
  export interface RenderSession {
74
77
  page: RenderPage;
75
78
  context: RenderContext;
76
79
  response: RenderResponse | null;
77
80
  finalUrl: string;
78
81
  budget: PageWorkBudget;
82
+ /** Set only when `consume` runs as the fallback: the page committed navigation but this step did not finish. */
83
+ phaseTimedOut?: TimedOutPhase;
79
84
  }
80
85
  export interface RenderPageOptions {
81
86
  timeoutMs?: number;
82
87
  signal?: AbortSignal;
88
+ /** Time source for the budget, its timers and the hard stop; defaults to the real clock. */
89
+ clock?: CaptureClock;
90
+ /** Ordinary work (navigation, wait, load wait, cookie dismissal) must end this many ms after the start; it is
91
+ * above 0 and below `timeoutMs`. If the page has committed navigation by then, `onSoftDeadline` decides what
92
+ * happens; if not, the capture fails with a PageWorkTimeout at this time. A caller cancel never counts as this. */
93
+ softDeadlineMs?: number;
94
+ /** The only action: run `consume` once on the current page with what is left of `timeoutMs`
95
+ * (`session.phaseTimedOut` says which step was cut short). It is what applies when `softDeadlineMs` is set. */
96
+ onSoftDeadline?: "consume-current";
83
97
  /** CSS selector, or settle seconds (0–10). DOM content loaded always precedes this. */
84
98
  waitFor?: string | number;
85
99
  dismissCookieBanners?: boolean;
@@ -1,4 +1,5 @@
1
- import { PageWorkBudget, PageWorkTimeout } from "./page-work-budget.js";
1
+ import { REAL_CAPTURE_CLOCK } from "./capture-clock.js";
2
+ import { PageWorkBudget, PageWorkDeadline, PageWorkTimeout } from "./page-work-budget.js";
2
3
  import { isSameOriginUrl } from "./same-origin.js";
3
4
  import { MAX_REDIRECT_HOPS, isMainFrameNavigation } from "./request-guard.js";
4
5
  /** Stable safe code for a renderer behind a port; no resolved peer or target path is exposed. */
@@ -70,7 +71,7 @@ function assertNavigable(required) {
70
71
  }
71
72
  /** Only viewport/device settings cross into the fresh context. */
72
73
  const CONTEXT_OPTION_KEYS = ["viewport", "deviceScaleFactor", "isMobile", "hasTouch", "javaScriptEnabled"];
73
- async function openContext({ browser, budget, signal, timeoutMs }, { contextOptions = {} }) {
74
+ async function openContext({ browser, budget, signal }, { contextOptions = {} }) {
74
75
  return budget.run({ work: async () => {
75
76
  const allowed = Object.fromEntries(CONTEXT_OPTION_KEYS.filter(key => contextOptions[key] !== undefined).map(key => [key, contextOptions[key]]));
76
77
  // No storageState, recordVideo, recordHar or user-data dir: observed state never reaches disk.
@@ -79,7 +80,7 @@ async function openContext({ browser, budget, signal, timeoutMs }, { contextOpti
79
80
  if (budget.remainingMs() <= 0 || signal.aborted) {
80
81
  void opened.close().catch(() => { });
81
82
  signal.throwIfAborted();
82
- throw new PageWorkTimeout({ timeoutMs });
83
+ throw budget.expiredError();
83
84
  }
84
85
  return opened;
85
86
  } });
@@ -162,11 +163,15 @@ async function waitForSelectorOrDelay({ page, budget, waitFor }) {
162
163
  await budget.run({ work: () => page.waitForSelector(waitFor, { state: "visible", timeout: budget.remainingMs() }) });
163
164
  }
164
165
  /** Cookie dismissal, the selector/settle strategy and the best-effort load wait, all within the page budget. */
165
- async function settlePage({ page, budget, signal }, options) {
166
+ async function settlePage({ page, budget, signal, progress }, options) {
166
167
  const { waitFor = 1.2, dismissCookieBanners: dismiss = false } = options;
168
+ progress.phase = "dismiss";
167
169
  const dismissed = dismiss && await dismissCookieBanners({ page, budget });
170
+ progress.phase = "wait";
168
171
  await waitForSelectorOrDelay({ page, budget, waitFor });
172
+ progress.phase = "load";
169
173
  await waitForLoad({ page, budget, signal }, options);
174
+ progress.phase = "dismiss";
170
175
  // Hydrated consent widgets can arrive during the settle/selector wait.
171
176
  if (dismiss && !dismissed && await dismissCookieBanners({ page, budget })) {
172
177
  await budget.run({ work: () => page.waitForTimeout(200) });
@@ -184,17 +189,56 @@ async function waitForLoad({ page, budget, signal }, { loadWaitMs }) {
184
189
  // A polling or slow resource must not prevent bounded best-effort evidence/capture.
185
190
  }
186
191
  }
192
+ const originPolicyOf = ({ url }, options) => ({ originPolicy: options.originPolicy ?? "same-origin", originBaseUrl: options.originBaseUrl ?? url });
193
+ /** The session for a committed page; its final URL passes the same origin boundary on every path. */
194
+ function sessionOf({ context, budget, committed: { page, response, target } }, policy) {
195
+ const finalUrl = page.url?.() ?? response?.url?.() ?? target;
196
+ assertNavigable({ url: finalUrl, ...policy });
197
+ return { page, context, response, finalUrl, budget };
198
+ }
187
199
  /** Guard, navigate and settle the page; the session's final URL passes the same origin boundary. */
188
- async function openSession({ context, budget, signal, url }, options) {
189
- const policy = { originPolicy: options.originPolicy ?? "same-origin", originBaseUrl: options.originBaseUrl ?? url };
200
+ async function openSession({ context, budget, signal, url, progress }, options) {
201
+ const policy = originPolicyOf({ url }, options);
190
202
  const refusedOrigin = await guardRequests({ context, budget, ...policy }, options);
191
203
  const page = await budget.run({ work: () => context.newPage() });
192
204
  const { target, response } = await navigate({ page, budget, url, refusedOrigin, ...policy }, options);
193
- await settlePage({ page, budget, signal }, options);
205
+ const committed = { page, response, target };
206
+ progress.committed = committed;
207
+ await settlePage({ page, budget, signal, progress }, options);
194
208
  signal.throwIfAborted();
195
- const finalUrl = page.url?.() ?? response?.url?.() ?? target;
196
- assertNavigable({ url: finalUrl, ...policy });
197
- return { page, context, response, finalUrl, budget };
209
+ return sessionOf({ context, budget, committed }, policy);
210
+ }
211
+ /** Open the session. When the work deadline cuts settling short on a page that committed navigation, the
212
+ * session of that page is the fallback; before commit it is a failure. A caller cancel or the hard stop is
213
+ * never a work deadline: it throws, so a cancel can never start fallback work. */
214
+ async function openOrFallBack(args, options) {
215
+ const progress = { phase: "dismiss" };
216
+ try {
217
+ return await openSession({ ...args, progress }, options);
218
+ }
219
+ catch (error) {
220
+ const { committed } = progress;
221
+ if (!(error instanceof PageWorkDeadline) || !committed)
222
+ throw error;
223
+ // A cancel that lands right after the deadline cannot start the fallback: budget.run refuses to start `consume` on an aborted signal.
224
+ const session = sessionOf({ context: args.context, budget: args.budget, committed }, originPolicyOf(args, options));
225
+ return { ...session, phaseTimedOut: progress.phase };
226
+ }
227
+ }
228
+ /** The URL syntax boundary, and the rule that public rendering always runs behind a guarded router. */
229
+ function assertRenderable({ url, timeoutMs }, options) {
230
+ assertHttpUrl({ url });
231
+ if (options.originPolicy === "public" && !options.router)
232
+ throw new Error("Public rendering requires a guarded request router");
233
+ assertSoftDeadline({ timeoutMs }, options);
234
+ }
235
+ /** A soft deadline at or past the hard limit leaves no fallback window: that is a caller bug, not a clamp. */
236
+ function assertSoftDeadline({ timeoutMs }, { softDeadlineMs }) {
237
+ if (softDeadlineMs === undefined)
238
+ return;
239
+ if (!(softDeadlineMs > 0 && softDeadlineMs < timeoutMs)) {
240
+ throw new RangeError(`softDeadlineMs must be above 0 and below timeoutMs (${timeoutMs}), got ${softDeadlineMs}`);
241
+ }
198
242
  }
199
243
  /** Open, guard, wait and consume ONE ephemeral page, always releasing the context.
200
244
  * No network-idle wait: SPAs and polling sites can stay busy forever. DNS decisions are not followed
@@ -205,15 +249,13 @@ async function openSession({ context, budget, signal, url }, options) {
205
249
  * @throws Browser errors, cancellation, PageWorkTimeout, or a refused origin/transport boundary.
206
250
  * @complexity Bounded page I/O plus the consumer; at most six explicit navigation hops. */
207
251
  export async function renderPage({ browser, url, consume }, options = {}) {
208
- const { timeoutMs = 30_000, signal: callerSignal } = options;
209
- assertHttpUrl({ url });
210
- if (options.originPolicy === "public" && !options.router)
211
- throw new Error("Public rendering requires a guarded request router");
252
+ const { timeoutMs = 30_000, signal: callerSignal, clock = REAL_CAPTURE_CLOCK } = options;
253
+ assertRenderable({ url, timeoutMs }, options);
212
254
  // A native total timer remains firm even if the wall clock moves between budgeted steps.
213
- const deadline = AbortSignal.timeout(timeoutMs);
255
+ const deadline = clock.deadlineSignal(timeoutMs);
214
256
  const signal = callerSignal ? AbortSignal.any([callerSignal, deadline]) : deadline;
215
257
  try {
216
- return await consumeOnePage({ browser, url, consume, signal, timeoutMs }, options);
258
+ return await consumeOnePage({ browser, url, consume, signal, timeoutMs, clock }, options);
217
259
  }
218
260
  catch (error) {
219
261
  if (deadline.aborted && !callerSignal?.aborted)
@@ -222,19 +264,22 @@ export async function renderPage({ browser, url, consume }, options = {}) {
222
264
  }
223
265
  }
224
266
  /** The context opened here is closed at once on abort and always released when the call ends. */
225
- async function consumeOnePage({ browser, url, consume, signal, timeoutMs }, options) {
226
- const budget = new PageWorkBudget({ timeoutMs }, { signal });
267
+ async function consumeOnePage({ browser, url, consume, signal, timeoutMs, clock }, options) {
268
+ const { softDeadlineMs } = options;
269
+ const budget = new PageWorkBudget({ timeoutMs }, { signal, clock, ...(softDeadlineMs === undefined ? {} : { workDeadlineMs: softDeadlineMs }) });
227
270
  let context;
228
271
  const onAbort = () => { void context?.close().catch(() => { }); };
229
272
  signal.throwIfAborted();
230
273
  signal.addEventListener("abort", onAbort, { once: true });
231
274
  try {
232
- context = await openContext({ browser, budget, signal, timeoutMs }, options);
233
- const session = await openSession({ context, budget, signal, url }, options);
275
+ context = await openContext({ browser, budget, signal }, options);
276
+ const session = await openOrFallBack({ context, budget, signal, url }, options);
277
+ budget.endWorkPhase();
234
278
  return await budget.run({ work: () => consume(session) });
235
279
  }
236
280
  finally {
237
281
  signal.removeEventListener("abort", onAbort);
282
+ budget.endWorkPhase();
238
283
  if (context)
239
284
  await budget.release({ close: () => context.close().catch(() => { }) });
240
285
  }
@@ -151,21 +151,7 @@ export function createRequestRouter({ httpClient, ownSiteFetch, allowedOrigins,
151
151
  const report = { fulfilled: 0, blocked: 0, navigationRefused: false, bytes: 0 };
152
152
  const fetchHop = createHopFetcher({ httpClient, ownSiteFetch, signal, report }, options);
153
153
  let navigationRedirect;
154
- async function abort(route, reason, isNavigation) {
155
- report.blocked += 1;
156
- onBlocked?.({ url: route.request().url(), resourceType: route.request().resourceType(), reason });
157
- if (reason === "refused" && isNavigation)
158
- report.navigationRefused = true;
159
- // The context may already be closing; a route that is gone has nothing left to abort.
160
- await route.abort(reason === "failed" ? "failed" : "blockedbyclient").catch(() => { });
161
- }
162
- async function fulfill(route, { url, resource }) {
163
- report.fulfilled += 1;
164
- onResponse?.({ url, resourceType: route.request().resourceType(), resource });
165
- await route.fulfill({ status: resource.status, headers: filterHeaders(resource.headers, preserveOwnSiteCookies
166
- ? OWN_SITE_RESPONSE_HEADERS
167
- : DROPPED_RESPONSE_HEADERS), body: resource.body }).catch(() => { });
168
- }
154
+ const { abort, fulfill } = createRouteResponders(report, { preserveOwnSiteCookies, onResponse, onBlocked });
169
155
  /** One hop of one request: decide, fetch, then fulfil, hand a page redirect back, or route the next hop. */
170
156
  async function routeHop({ route, isNavigation }, { hop, url, method, body, headers }) {
171
157
  const request = route.request();
@@ -208,6 +194,24 @@ export function createRequestRouter({ httpClient, ownSiteFetch, allowedOrigins,
208
194
  },
209
195
  };
210
196
  }
197
+ function createRouteResponders(report, { preserveOwnSiteCookies, onResponse, onBlocked }) {
198
+ async function abort(route, reason, isNavigation) {
199
+ report.blocked += 1;
200
+ onBlocked?.({ url: route.request().url(), resourceType: route.request().resourceType(), reason });
201
+ if (reason === "refused" && isNavigation)
202
+ report.navigationRefused = true;
203
+ // The context may already be closing; a route that is gone has nothing left to abort.
204
+ await route.abort(reason === "failed" ? "failed" : "blockedbyclient").catch(() => { });
205
+ }
206
+ async function fulfill(route, { url, resource }) {
207
+ report.fulfilled += 1;
208
+ onResponse?.({ url, resourceType: route.request().resourceType(), resource });
209
+ await route.fulfill({ status: resource.status, headers: filterHeaders(resource.headers, preserveOwnSiteCookies
210
+ ? OWN_SITE_RESPONSE_HEADERS
211
+ : DROPPED_RESPONSE_HEADERS), body: resource.body }).catch(() => { });
212
+ }
213
+ return { abort, fulfill };
214
+ }
211
215
  /** Reads chunks until the stream ends or the next one would pass `maxBytes` (then `truncated`). */
212
216
  async function readCapped(reader, maxBytes) {
213
217
  const chunks = [];
@@ -33,7 +33,7 @@ export type NormalizeSitePathResult = {
33
33
  * keeping it would make two citations of the same evidence look like different pages.
34
34
  *
35
35
  * @throws Nothing — every rejection is returned, matching this codebase's convention for expected
36
- * validation outcomes (`agent-plugins/manifest.ts`, `plugin-runtime/discovery.ts`).
36
+ * validation outcomes (`packages/agent-plugins/src/lifecycle/manifest.ts`, `packages/plugins/src/host/node/discovery.ts`).
37
37
  * @complexity O(n) in the path's own length.
38
38
  */
39
39
  export declare function normalizeSitePath({ raw }: {
@@ -33,10 +33,10 @@ import { trimCharsEnd, trimCharsStart } from "@jini-ai/core/primitives";
33
33
  * pathological input cannot be handed to a browser at all. */
34
34
  const MAX_PATH_LENGTH = 2048;
35
35
  /** Raw C0 controls, DEL, and whitespace — the characters that let a crafted string mean one thing
36
- * to a validator and another to a URL parser. Mirrors `origin/origin.ts`'s
36
+ * to a validator and another to a URL parser. Mirrors `packages/http-kit/src/verified-origin/origin.ts`'s
37
37
  * `normalizeOriginCandidate`, which rejects the same class for the same reason. */
38
- // biome-ignore lint/suspicious/noControlCharactersInRegex: matching control characters is the entire purpose — a raw CR/LF/NUL in a path is exactly the smuggling vector this refuses.
39
- const FORBIDDEN_CHARACTERS = /[\u0000-\u0020\u007f]/;
38
+ // A raw CR/LF/NUL in a path is exactly the smuggling vector this refuses.
39
+ const FORBIDDEN_CHARACTERS = /(?![\u0080-\u009F])[\p{Cc} ]/u;
40
40
  /**
41
41
  * The syntactic rejections that only need the trimmed raw string — every one of these fires before
42
42
  * a fragment is ever stripped or a leading slash ever added. Split out of {@link normalizeSitePath}
@@ -81,7 +81,7 @@ function rejectionForRawPath(trimmed) {
81
81
  * keeping it would make two citations of the same evidence look like different pages.
82
82
  *
83
83
  * @throws Nothing — every rejection is returned, matching this codebase's convention for expected
84
- * validation outcomes (`agent-plugins/manifest.ts`, `plugin-runtime/discovery.ts`).
84
+ * validation outcomes (`packages/agent-plugins/src/lifecycle/manifest.ts`, `packages/plugins/src/host/node/discovery.ts`).
85
85
  * @complexity O(n) in the path's own length.
86
86
  */
87
87
  export function normalizeSitePath({ raw }) {