@jini-ai/diagnostics 0.7.3-next.1 → 0.7.3-next.3

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 (69) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +41 -0
  3. package/dist/browser-diagnostics.d.ts +43 -0
  4. package/dist/browser-diagnostics.js +92 -0
  5. package/dist/console-tee.d.ts +21 -6
  6. package/dist/console-tee.js +16 -4
  7. package/dist/domain-dns/index.d.ts +6 -14
  8. package/dist/domain-dns/index.js +4 -6
  9. package/dist/local-text.d.ts +4 -1
  10. package/dist/local-text.js +3 -2
  11. package/dist/observability/error-events.d.ts +32 -0
  12. package/dist/observability/error-events.js +32 -0
  13. package/dist/observability/fanout.js +23 -1
  14. package/dist/observability/hooks.js +1 -0
  15. package/dist/observability/index.d.ts +2 -1
  16. package/dist/observability/index.js +1 -0
  17. package/dist/observability/report-error.d.ts +9 -4
  18. package/dist/observability/report-error.js +7 -6
  19. package/dist/observability/telemetry-test.d.ts +1 -1
  20. package/dist/observability/tool-registrations.d.ts +21 -0
  21. package/dist/observability/tool-registrations.js +38 -0
  22. package/dist/observability/tracker-noop.d.ts +1 -1
  23. package/dist/observability/tracker-types.d.ts +2 -57
  24. package/dist/observability/tracker.d.ts +2 -1
  25. package/dist/observability/tracker.js +5 -1
  26. package/dist/redaction/repo-secret-scan.d.ts +48 -0
  27. package/dist/redaction/repo-secret-scan.js +77 -0
  28. package/dist/redaction/repo-secret-scan.node.d.ts +56 -0
  29. package/dist/redaction/repo-secret-scan.node.js +174 -0
  30. package/dist/redaction/secret-scan.d.ts +15 -0
  31. package/dist/redaction/secret-scan.js +18 -0
  32. package/dist/redaction/secrets-only.d.ts +1 -0
  33. package/dist/redaction/secrets-only.js +2 -0
  34. package/dist/redaction.d.ts +6 -0
  35. package/dist/redaction.js +9 -5
  36. package/dist/server-logs/agent-tools.d.ts +34 -0
  37. package/dist/server-logs/agent-tools.js +19 -0
  38. package/dist/server-logs/read-server-logs.d.ts +49 -0
  39. package/dist/server-logs/read-server-logs.js +90 -0
  40. package/dist/server-logs/tool-registrations.d.ts +25 -0
  41. package/dist/server-logs/tool-registrations.js +39 -0
  42. package/dist/tool-audit/repo.d.ts +107 -0
  43. package/dist/tool-audit/repo.js +117 -0
  44. package/dist/tool-audit/repo.memory.d.ts +31 -0
  45. package/dist/tool-audit/repo.memory.js +30 -0
  46. package/dist/tool-audit/repo.rows.d.ts +19 -0
  47. package/dist/tool-audit/repo.rows.js +2 -0
  48. package/dist/tool-audit/tool-gaps.repo.d.ts +22 -0
  49. package/dist/tool-audit/tool-gaps.repo.js +36 -0
  50. package/dist/web-evidence/agent-tools.d.ts +31 -0
  51. package/dist/web-evidence/agent-tools.js +61 -0
  52. package/dist/web-evidence/capture-budget.d.ts +3 -10
  53. package/dist/web-evidence/live-url.d.ts +86 -0
  54. package/dist/web-evidence/live-url.js +191 -0
  55. package/dist/web-evidence/page-performance-script.js +30 -32
  56. package/dist/web-evidence/playwright-browser.d.ts +2 -0
  57. package/dist/web-evidence/playwright-page-capture.d.ts +129 -0
  58. package/dist/web-evidence/playwright-page-capture.js +226 -0
  59. package/dist/web-evidence/public-page.d.ts +2 -1
  60. package/dist/web-evidence/published-page.d.ts +180 -0
  61. package/dist/web-evidence/published-page.js +172 -0
  62. package/dist/web-evidence/request-guard.d.ts +1 -31
  63. package/dist/web-evidence/site-path-policy.d.ts +20 -0
  64. package/dist/web-evidence/site-path-policy.js +54 -0
  65. package/dist/web-evidence/web-screenshot/agent-tools.d.ts +28 -0
  66. package/dist/web-evidence/web-screenshot/agent-tools.js +34 -0
  67. package/dist/web-evidence/web-screenshot/tool-registrations.d.ts +79 -0
  68. package/dist/web-evidence/web-screenshot/tool-registrations.js +47 -0
  69. package/package.json +115 -7
@@ -0,0 +1,61 @@
1
+ export const SITE_EVIDENCE_TOOL_ID = "site_collect_page_evidence";
2
+ export const siteEvidenceAgentToolCatalog = [
3
+ {
4
+ name: SITE_EVIDENCE_TOOL_ID,
5
+ description: "Loads pages of THIS site in a real headless browser and reports what was actually observed: " +
6
+ "cookies set (names, domains, flags — never values), network requests attempted (method, host, " +
7
+ "path, resource type, and whether they fired before or after a consent click), response headers, " +
8
+ "the page title/lang/text, and the rendered accessibility structure (landmarks, heading outline, " +
9
+ "image alt text, form-control label associations, and colour-contrast samples) — each with the CSS " +
10
+ "selector it came from. Use it for anything a configuration snapshot cannot prove: whether a " +
11
+ "tracking cookie fires before consent, whether a consent banner actually renders, whether a " +
12
+ "privacy policy page is reachable or is still placeholder text, whether headings and labels are " +
13
+ "really there in the published output. Set collectPerformance=true ONLY when the user asks for performance diagnosis: " +
14
+ "adds heap, DOM, mounted hidden panels, iframes, long tasks and plain-language suspects. " +
15
+ "This is a fresh anonymous page, not the operator's open admin tab or restored chat. " +
16
+ "SCOPE: this site's own origin only — it takes site-relative paths, never URLs, and will not " +
17
+ "fetch another host. It loads at most 5 pages per call under a 60s budget, never submits a form " +
18
+ "or any non-GET request, and persists nothing. " +
19
+ "IT REPORTS EVIDENCE, NOT VERDICTS: there is no pass/fail, no score, and no compliance " +
20
+ "assessment in the output, and the absence of an observation is never evidence that something " +
21
+ "is absent — a page listed under 'skipped' was not inspected at all.",
22
+ sideEffects: "none",
23
+ authorization: { permission: "content.read" },
24
+ inputSchema: {
25
+ type: "object",
26
+ additionalProperties: false,
27
+ required: ["paths"],
28
+ properties: {
29
+ paths: {
30
+ type: "array",
31
+ minItems: 1,
32
+ maxItems: 5,
33
+ items: {
34
+ type: "string",
35
+ description: "A site-relative path on THIS site, e.g. '/', '/pricing', '/legal/privacy'. Absolute URLs, " +
36
+ "protocol-relative paths, and '..' segments are refused and reported in 'skipped'.",
37
+ },
38
+ description: "Up to 5 site-relative paths to load. Anything past the 5th is returned in 'skipped' with reason 'page-cap'.",
39
+ },
40
+ consentAcceptSelector: {
41
+ type: "string",
42
+ description: "Optional CSS selector for this site's own consent-accept control (ask the operator for it). " +
43
+ "When given, the tool clicks it once after the first observation and marks everything seen " +
44
+ "afterwards with phase 'after', which is the only way to tell gated behaviour from ungated. " +
45
+ "When omitted, every observation is phase 'before' and nothing in the result says what " +
46
+ "changes on acceptance.",
47
+ },
48
+ collectPerformance: {
49
+ type: "boolean",
50
+ description: "On-demand only. Defaults false. Numeric performance sample of a fresh anonymous page; unavailable APIs are explicit. Does not inspect an existing signed-in admin tab.",
51
+ },
52
+ collectAccessibility: {
53
+ type: "boolean",
54
+ description: "Defaults to true. Set false to skip the rendered accessibility walk when only cookie/request " +
55
+ "evidence is wanted — a context-size choice, not a faster page load.",
56
+ },
57
+ },
58
+ },
59
+ },
60
+ ];
61
+ //# sourceMappingURL=agent-tools.js.map
@@ -1,3 +1,6 @@
1
+ import type { CaptureBudgetLimits } from "@jini-ai/core/contracts/site/web-evidence-capture-budget";
2
+ /** Deprecated re-export: import these from `@jini-ai/core/contracts/site/web-evidence-capture-budget`; removed at the next major. */
3
+ export type { CaptureBudgetLimits } from "@jini-ai/core/contracts/site/web-evidence-capture-budget";
1
4
  /** What the caller asked a capture to do. Every field is optional input from a tool call. */
2
5
  export interface CaptureRequest {
3
6
  /** Settle time in milliseconds. Replaced by `waitForSeconds` when that is given. */
@@ -6,16 +9,6 @@ export interface CaptureRequest {
6
9
  /** The renderer's requested wait, in seconds. */
7
10
  waitForSeconds?: number;
8
11
  }
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
12
  export interface CaptureBudget {
20
13
  totalMs: number;
21
14
  /** `totalMs − reserveMs`: ordinary work must be done by then. */
@@ -0,0 +1,86 @@
1
+ import type { HttpRequest, HttpResponse } from "@jini-ai/core/primitives";
2
+ import { type OriginRegistryPort } from "@jini-ai/core/contracts/server/verified-origin";
3
+ import { type PageBodyOptions } from "./page-body.js";
4
+ import type { PublishedPageResult } from "./published-page.js";
5
+ /** One publish-peer row as far as live-origin selection reads it; `sealed` is null for an unkeyed row. */
6
+ export interface LivePeerRow {
7
+ readonly baseUrl: string;
8
+ readonly sealed: unknown;
9
+ }
10
+ /** The publish-history slice this file reads: distinct live URLs recorded for one workspace. */
11
+ export interface LivePublishHistory {
12
+ listLiveUrls(input: {
13
+ workspaceId: string;
14
+ }): Promise<readonly string[]>;
15
+ }
16
+ /** The peer-repository slice this file reads. */
17
+ export interface LivePeerRepo {
18
+ listByWorkspace(input: {
19
+ workspaceId: string;
20
+ }): Promise<readonly LivePeerRow[]>;
21
+ }
22
+ /**
23
+ * The host's publish-peer rule: which unkeyed row is the connected destination. The returned row is
24
+ * compared by identity against the rows it was handed, so it must be one of them, never a copy.
25
+ */
26
+ export interface LiveOriginPolicy {
27
+ selectConnectedDestination(required: {
28
+ rows: readonly LivePeerRow[];
29
+ }, _optional?: Record<string, never>): LivePeerRow | null;
30
+ }
31
+ /** The guarded HTTP client slice this file calls: one request, one bounded response. */
32
+ export interface LiveHttpClient {
33
+ send(request: HttpRequest): Promise<HttpResponse>;
34
+ }
35
+ /** Recognizes the host egress guard's refusal; only its caller-safe text reaches the model. */
36
+ export type LiveEgressRefusal = (error: unknown) => error is {
37
+ callerSafeMessage: string;
38
+ };
39
+ /** Read ports only; missing ports on a test/older composition do not invent an address. */
40
+ export interface LiveOriginSourceDeps {
41
+ workspaceId: string;
42
+ publishContentPeerRepo?: LivePeerRepo;
43
+ publishHistoryStore?: LivePublishHistory;
44
+ originRegistry?: Pick<OriginRegistryPort, "canonicalOrigin">;
45
+ }
46
+ export interface FetchLiveUrlDeps {
47
+ /** Fresh workspace-scoped reads, never request Host or a caller-supplied arbitrary URL. */
48
+ listKnownOrigins(): Promise<readonly string[]>;
49
+ /** The shared guarded client with redirects disabled and a raw 1 MB ceiling. */
50
+ httpClient: LiveHttpClient;
51
+ /** The host's reserved first path segments (its routing `RESERVED_SEGMENTS`), never fetched live. */
52
+ reservedSegments: ReadonlySet<string>;
53
+ /** The host egress guard's refusal test; a match is projected as a model-visible input error. */
54
+ isEgressRefusal: LiveEgressRefusal;
55
+ /** Optional host instrumentation; receives no body, headers, credentials or query parameters. */
56
+ observeFetch?: (event: {
57
+ origin: string;
58
+ status?: number;
59
+ durationMs: number;
60
+ outcome: "response" | "refused" | "failed";
61
+ }) => void;
62
+ }
63
+ export interface FetchLiveUrlInput extends PageBodyOptions {
64
+ path: string;
65
+ origin?: string | undefined;
66
+ }
67
+ export type LivePageResult = PublishedPageResult & {
68
+ url: string;
69
+ origin: string;
70
+ redirects: string[];
71
+ untrusted: true;
72
+ location?: string;
73
+ };
74
+ /** Reads connected + keyed peers, full-ledger publish URL projection, and the trusted configured origin. */
75
+ export declare function listKnownLiveOrigins(deps: LiveOriginSourceDeps & LiveOriginPolicy, _optional?: {}): Promise<string[]>;
76
+ /**
77
+ * GETs this site's own live copy through the existing pinned-public-peer guard. One 15 s deadline
78
+ * covers origin reads, DNS, redirects and body reads. Cross-origin and fourth redirects are results.
79
+ * @returns Visitor response evidence; third-party text is explicitly untrusted, cookie values omitted.
80
+ * @throws ToolInputError for address selection, unsafe input/egress, or timeout.
81
+ */
82
+ export declare function fetchLiveUrl({ deps, input }: {
83
+ deps: FetchLiveUrlDeps;
84
+ input: FetchLiveUrlInput;
85
+ }, _optional?: {}): Promise<LivePageResult>;
86
+ //# sourceMappingURL=live-url.d.ts.map
@@ -0,0 +1,191 @@
1
+ import { ToolInputError } from "@jini-ai/core";
2
+ import { OriginNotVerifiedError, } from "@jini-ai/core/contracts/server/verified-origin";
3
+ import { readPageBodyOptions, shapePageBody, DEFAULT_MAX_BODY_BYTES, MAX_MAX_BODY_BYTES } from "./page-body.js";
4
+ import { SameOriginPathError as PublishedPagePathError } from "./path-guard.js";
5
+ import { toCookieShapes } from "./cookie-shapes.js";
6
+ import { resolveSitePath } from "./site-path-policy.js";
7
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
8
+ const NO_LIVE_ADDRESS = "fetch_live_url: this site has no known live address yet. Publish it first, or use fetch_published_page to check the local render.";
9
+ const DEADLINE_MESSAGE = "fetch_live_url: fetching the live page exceeded 15000ms. Check the hosting service before retrying.";
10
+ /** Normalizes saved URLs to origins; embedded credentials never become an allowed origin. */
11
+ function liveOrigin({ raw }, _optional = {}) {
12
+ let url;
13
+ try {
14
+ url = new URL(raw);
15
+ }
16
+ catch {
17
+ throw new ToolInputError({ message: "fetch_live_url: a saved live address is invalid. Correct the publishing address and retry." });
18
+ }
19
+ if (url.protocol !== "https:" || url.port !== "" || url.username || url.password)
20
+ throw new ToolInputError({ message: "fetch_live_url: live origins must use HTTPS on port 443 without credentials." });
21
+ return url.origin;
22
+ }
23
+ /** Reads connected + keyed peers, full-ledger publish URL projection, and the trusted configured origin. */
24
+ export async function listKnownLiveOrigins(deps, _optional = {}) {
25
+ const peers = await deps.publishContentPeerRepo?.listByWorkspace({ workspaceId: deps.workspaceId }) ?? [];
26
+ const connected = deps.selectConnectedDestination({ rows: peers });
27
+ const urls = peers.filter(peer => peer.sealed !== null || peer === connected).map(peer => peer.baseUrl);
28
+ const historyUrls = await deps.publishHistoryStore?.listLiveUrls({ workspaceId: deps.workspaceId }) ?? [];
29
+ if (historyUrls.length > 200)
30
+ throw new ToolInputError({ message: "fetch_live_url: more than 200 distinct live addresses are recorded. Review the publish history before fetching." });
31
+ urls.push(...historyUrls);
32
+ urls.push(...await configuredLiveOrigins(deps));
33
+ return [...new Set(urls.map((raw) => liveOrigin({ raw })))].sort();
34
+ }
35
+ /** Reads only explicitly configured trust evidence; absent verification supplies no address. */
36
+ async function configuredLiveOrigins({ originRegistry, workspaceId }, _options = {}) {
37
+ if (!originRegistry)
38
+ return [];
39
+ try {
40
+ const configured = await originRegistry.canonicalOrigin({ workspaceId });
41
+ if (configured.source !== "workspace-setting")
42
+ return [];
43
+ const base = `${configured.scheme}://${configured.host}`;
44
+ const port = configured.port ? `:${configured.port}` : "";
45
+ return [`${base}${port}`];
46
+ }
47
+ catch (error) {
48
+ if (!(error instanceof OriginNotVerifiedError))
49
+ throw error;
50
+ return [];
51
+ }
52
+ }
53
+ /** Only the origin itself is accepted for explicit selection, never a path/userinfo-bearing URL. */
54
+ function selectOrigin({ known, requested }, _optional = {}) {
55
+ const origins = [...new Set(known.map((raw) => liveOrigin({ raw })))].sort();
56
+ if (origins.length === 0)
57
+ throw new ToolInputError({ message: NO_LIVE_ADDRESS });
58
+ if (requested !== undefined) {
59
+ const normalized = liveOrigin({ raw: requested });
60
+ const explicit = new URL(requested);
61
+ if (explicit.pathname !== "/" || explicit.search || explicit.hash)
62
+ throw new ToolInputError({ message: `fetch_live_url: origin is not a known live address. Pass one of: ${origins.join(", ")}.` });
63
+ if (!origins.includes(normalized))
64
+ throw new ToolInputError({ message: `fetch_live_url: origin is not a known live address. Pass one of: ${origins.join(", ")}.` });
65
+ return normalized;
66
+ }
67
+ if (origins.length > 1)
68
+ throw new ToolInputError({ message: `fetch_live_url: several live origins are known. Pass origin as one of: ${origins.join(", ")}.` });
69
+ const origin = origins[0];
70
+ if (origin === undefined)
71
+ throw new ToolInputError({ message: NO_LIVE_ADDRESS });
72
+ return origin;
73
+ }
74
+ /** Reuses the local path boundary while retaining actionable errors at the assistant boundary. */
75
+ function resolveLivePath({ path, origin, reservedSegments }, _optional = {}) {
76
+ try {
77
+ return resolveSitePath({ raw: path, base: origin, reservedSegments });
78
+ }
79
+ catch (error) {
80
+ if (error instanceof PublishedPagePathError)
81
+ throw new ToolInputError({ message: `fetch_live_url: ${error.message}` });
82
+ throw error;
83
+ }
84
+ }
85
+ /** Validates raw and resolved same-origin paths before URL normalization can erase traversal. */
86
+ function redirectTarget({ location, current, origin, reservedSegments }, _optional = {}) {
87
+ let next;
88
+ try {
89
+ next = new URL(location, current);
90
+ }
91
+ catch {
92
+ throw new ToolInputError({ message: "fetch_live_url: the live site returned an invalid redirect address. Check the hosting service before retrying." });
93
+ }
94
+ if (next.origin !== origin)
95
+ return null;
96
+ if (next.username || next.password)
97
+ throw new ToolInputError({ message: "fetch_live_url: redirects with embedded credentials are refused." });
98
+ const rawPath = location.replace(/^(?:[a-z][a-z0-9+.-]*:)?\/\/[^/?#]*/i, "").split("#")[0]; // split always returns a first piece
99
+ resolveLivePath({ path: rawPath.startsWith("/") ? rawPath : "/" + rawPath, origin, reservedSegments });
100
+ resolveLivePath({ path: next.pathname + next.search, origin, reservedSegments });
101
+ next.hash = "";
102
+ return next.href;
103
+ }
104
+ /**
105
+ * GETs this site's own live copy through the existing pinned-public-peer guard. One 15 s deadline
106
+ * covers origin reads, DNS, redirects and body reads. Cross-origin and fourth redirects are results.
107
+ * @returns Visitor response evidence; third-party text is explicitly untrusted, cookie values omitted.
108
+ * @throws ToolInputError for address selection, unsafe input/egress, or timeout.
109
+ */
110
+ export async function fetchLiveUrl({ deps, input }, _optional = {}) {
111
+ const options = readPageBodyOptions({ input: input });
112
+ const deadline = AbortSignal.timeout(15_000);
113
+ return awaitWithDeadline({ work: fetchWithinDeadline({ deps, input, options, deadline }), signal: deadline });
114
+ }
115
+ /** One bounded operation, including slow repositories and time between redirect hops. */
116
+ async function fetchWithinDeadline({ deps, input, options, deadline }, _optional = {}) {
117
+ const started = Date.now();
118
+ const origin = selectOrigin({ known: await deps.listKnownOrigins(), requested: input.origin });
119
+ const path = resolveLivePath({ path: input.path, origin, reservedSegments: deps.reservedSegments });
120
+ const rawReadCap = options.textOnly || options.find !== undefined ? MAX_MAX_BODY_BYTES : options.maxBytes ?? DEFAULT_MAX_BODY_BYTES;
121
+ let url = origin + path;
122
+ const redirects = [];
123
+ for (;;) {
124
+ deadline.throwIfAborted();
125
+ const response = await sendPage({ deps, url, signal: deadline, timeoutMs: Math.max(1, 15_000 - (Date.now() - started)), maxResponseBytes: rawReadCap });
126
+ const headers = pageHeaders(response);
127
+ const location = headers.location;
128
+ if (REDIRECTS.has(response.status) && location && redirects.length < 3) {
129
+ const next = redirectTarget({ location, current: url, origin, reservedSegments: deps.reservedSegments });
130
+ if (next !== null) {
131
+ redirects.push(next);
132
+ url = next;
133
+ continue;
134
+ }
135
+ }
136
+ return livePageResult({ response, headers, options, url, origin, redirects });
137
+ }
138
+ }
139
+ /** Header names are case-insensitive; cookie values are projected separately. */
140
+ function pageHeaders({ headers }, _options = {}) {
141
+ const result = {};
142
+ for (const [key, value] of Object.entries(headers)) {
143
+ if (key.toLowerCase() !== "set-cookie")
144
+ result[key.toLowerCase()] = value;
145
+ }
146
+ return result;
147
+ }
148
+ /** Shapes the final hop, retaining both upstream and local truncation evidence. */
149
+ function livePageResult({ response, headers, options, url, origin, redirects }, _options = {}) {
150
+ const cookies = new Headers();
151
+ for (const cookie of response.setCookies ?? [])
152
+ cookies.append("set-cookie", cookie);
153
+ const raw = Buffer.from(response.bodyText).subarray(0, MAX_MAX_BODY_BYTES).toString("utf8");
154
+ const shaped = shapePageBody({ body: raw }, options);
155
+ const location = headers.location;
156
+ return { path: new URL(url).pathname + new URL(url).search, status: response.status, ok: response.status >= 200 && response.status < 300, headers, cookies: toCookieShapes({ headers: cookies }), ...shaped, truncated: shaped.truncated || response.bodyTruncated === true || Buffer.byteLength(response.bodyText) > MAX_MAX_BODY_BYTES, url, origin, redirects, untrusted: true, ...(REDIRECTS.has(response.status) && location ? { location } : {}) };
157
+ }
158
+ /** Caller-safe egress refusals, following media-import's policy-error projection without leaking IPs. */
159
+ async function sendPage({ deps, url, signal, timeoutMs, maxResponseBytes }, _optional = {}) {
160
+ const started = Date.now();
161
+ try {
162
+ const response = await deps.httpClient.send({ method: "GET", url, headers: {}, timeoutMs, signal, maxResponseBytes });
163
+ deps.observeFetch?.({ origin: new URL(url).origin, status: response.status, durationMs: Date.now() - started, outcome: "response" });
164
+ return response;
165
+ }
166
+ catch (error) {
167
+ deps.observeFetch?.({ origin: new URL(url).origin, durationMs: Date.now() - started, outcome: deps.isEgressRefusal(error) ? "refused" : "failed" });
168
+ if (deps.isEgressRefusal(error))
169
+ throw new ToolInputError({ message: `fetch_live_url: ${error.callerSafeMessage}` });
170
+ if (signal.aborted)
171
+ throw new ToolInputError({ message: DEADLINE_MESSAGE });
172
+ throw error;
173
+ }
174
+ }
175
+ /** Bounds the whole operation while releasing its listener on either completion path. */
176
+ async function awaitWithDeadline({ work, signal }, _optional = {}) {
177
+ let abort;
178
+ try {
179
+ return await Promise.race([work, new Promise((_resolve, reject) => {
180
+ abort = () => reject(new ToolInputError({ message: DEADLINE_MESSAGE }));
181
+ signal.addEventListener("abort", abort, { once: true });
182
+ if (signal.aborted)
183
+ abort();
184
+ })]);
185
+ }
186
+ finally {
187
+ if (abort)
188
+ signal.removeEventListener("abort", abort);
189
+ }
190
+ }
191
+ //# sourceMappingURL=live-url.js.map
@@ -7,26 +7,31 @@
7
7
  */
8
8
  export async function collectPagePerformance(_required, _options = {}) {
9
9
  // Helpers stay nested: only this function's source is serialized into the page.
10
- const maxNodes = 100_000, maxTasks = 200;
11
- const counts = { domNodes: 0, mountedHiddenPanels: 0, hiddenPreElements: 0, hiddenPreTextChars: 0, iframes: 0 };
12
- function countElement(element) {
13
- const hidden = element.getClientRects().length === 0;
14
- if (element.tagName === 'IFRAME')
15
- counts.iframes++;
16
- if (element.matches('details:not([open]),[hidden],[aria-hidden="true"]') ||
17
- (element.getAttribute('role') === 'tabpanel' && hidden))
18
- counts.mountedHiddenPanels++;
19
- if (element.tagName === 'PRE' && hidden)
20
- counts.hiddenPreElements++;
21
- }
22
- function countNode(node) {
23
- if (node.nodeType === Node.ELEMENT_NODE) {
24
- countElement(node);
25
- return;
10
+ function sampleDom() {
11
+ const counts = { mountedHiddenPanels: 0, hiddenPreElements: 0, hiddenPreTextChars: 0, iframes: 0 };
12
+ function countElement(element) {
13
+ const hidden = element.getClientRects().length === 0;
14
+ if (element.tagName === 'IFRAME')
15
+ counts.iframes++;
16
+ if (element.matches('details:not([open]),[hidden],[aria-hidden="true"]') ||
17
+ (element.getAttribute('role') === 'tabpanel' && hidden))
18
+ counts.mountedHiddenPanels++;
19
+ if (element.tagName === 'PRE' && hidden)
20
+ counts.hiddenPreElements++;
26
21
  }
27
- if (node.nodeType === Node.TEXT_NODE && node.parentElement?.closest('pre')?.getClientRects().length === 0) {
28
- // Count text once, without copying hidden output into model context.
29
- counts.hiddenPreTextChars += node.textContent?.length ?? 0;
22
+ // Count text once, without copying hidden output into model context.
23
+ const countText = (node) => { if (node.parentElement?.closest('pre')?.getClientRects().length === 0)
24
+ counts.hiddenPreTextChars += node.textContent?.length ?? 0; };
25
+ const walker = document.createTreeWalker(document, NodeFilter.SHOW_ALL);
26
+ let domNodes = 0;
27
+ for (let node = walker.nextNode();; node = walker.nextNode()) {
28
+ if (!node || domNodes >= 100_000)
29
+ return { domNodes, domTruncated: node !== null, ...counts };
30
+ domNodes++;
31
+ if (node.nodeType === Node.ELEMENT_NODE)
32
+ countElement(node);
33
+ else if (node.nodeType === Node.TEXT_NODE)
34
+ countText(node);
30
35
  }
31
36
  }
32
37
  async function sampleLongTasks() {
@@ -35,7 +40,7 @@ export async function collectPagePerformance(_required, _options = {}) {
35
40
  return longTasks;
36
41
  const observer = new PerformanceObserver(list => {
37
42
  for (const entry of list.getEntries()) {
38
- if (longTasks.count >= maxTasks) {
43
+ if (longTasks.count >= 200) {
39
44
  longTasks.truncated = true;
40
45
  break;
41
46
  }
@@ -54,24 +59,17 @@ export async function collectPagePerformance(_required, _options = {}) {
54
59
  }
55
60
  return longTasks;
56
61
  }
57
- const walker = document.createTreeWalker(document, NodeFilter.SHOW_ALL);
58
- let node = walker.nextNode();
59
- while (node && counts.domNodes < maxNodes) {
60
- counts.domNodes++;
61
- countNode(node);
62
- node = walker.nextNode();
63
- }
62
+ const dom = sampleDom();
64
63
  const memory = performance.memory;
65
64
  const heap = memory ? { usedBytes: memory.usedJSHeapSize, allocatedBytes: memory.totalJSHeapSize, limitBytes: memory.jsHeapSizeLimit } : null;
66
65
  const longTasks = await sampleLongTasks();
67
- const { domNodes, mountedHiddenPanels, hiddenPreElements, hiddenPreTextChars, iframes } = counts;
68
66
  const suspects = [
69
- hiddenPreElements ? `${hiddenPreElements} hidden pre elements remain mounted with ${hiddenPreTextChars} text characters.` : '',
70
- mountedHiddenPanels ? `${mountedHiddenPanels} hidden or collapsed panels remain mounted.` : '',
71
- iframes ? `${iframes} iframes have separate documents; their DOM and heaps are outside this sample.` : '',
67
+ dom.hiddenPreElements ? `${dom.hiddenPreElements} hidden pre elements remain mounted with ${dom.hiddenPreTextChars} text characters.` : '',
68
+ dom.mountedHiddenPanels ? `${dom.mountedHiddenPanels} hidden or collapsed panels remain mounted.` : '',
69
+ dom.iframes ? `${dom.iframes} iframes have separate documents; their DOM and heaps are outside this sample.` : '',
72
70
  longTasks.count ? `${longTasks.count} long tasks were observed; the longest took ${Math.round(longTasks.maxMs)} ms.` : '',
73
71
  ].filter(Boolean);
74
- return { context: 'fresh-isolated-page', heap, domNodes, domTruncated: node !== null, mountedHiddenPanels, hiddenPreElements, hiddenPreTextChars, iframes, longTasks, suspects };
72
+ return { context: 'fresh-isolated-page', heap, ...dom, longTasks, suspects };
75
73
  }
76
74
  /** Use the same local name shim as the existing DOM evidence script so keepNames bundlers work.
77
75
  * @complexity O(script length) for serialization; evaluation is performed only on explicit request.
@@ -4,6 +4,8 @@ export { openPlaywrightRenderBrowser, PUBLIC_RENDER_LAUNCH_OPTIONS } from "./pla
4
4
  export type { PlaywrightLike, PlaywrightAdapterOptions } from "./playwright-runtime.js";
5
5
  export * from "./render-page.js";
6
6
  export { PageWorkTimeout } from "./page-work-budget.js";
7
+ /** Deprecated re-export: import these from `@jini-ai/core/contracts/site/web-evidence-playwright`; removed at the next major. */
8
+ export type { AbortReason, RequestDecision, RequestRouterReport, RoutedRequest } from "@jini-ai/core/contracts/site/web-evidence-playwright";
7
9
  export * from "./request-guard.js";
8
10
  export * from "./lazy-browser.js";
9
11
  /** Evidence facade over the same browser opener and render lifecycle used for public reading. */
@@ -0,0 +1,129 @@
1
+ import type { HttpRequest, HttpResponse } from "@jini-ai/core/primitives";
2
+ import type { PageCaptureFailureFields, PageCapturePort } from "@jini-ai/core/contracts/site/web-screenshot";
3
+ import { type CaptureBudgetLimits } from "./capture-budget.js";
4
+ import { type CaptureClock } from "./capture-clock.js";
5
+ import { type RenderBrowserPool } from "./playwright-browser.js";
6
+ import { type OwnSiteFetch, type RequestRouterOptions, type RouteLike } from "./playwright-browser.js";
7
+ /**
8
+ * @file `web_screenshot_page`'s {@link PageCapturePort}: headless Chromium through Playwright, on the
9
+ * shared lazy-browser core (`createLazyBrowser`, `@jini-ai/diagnostics/web-evidence/playwright`) the Sites card previews use.
10
+ *
11
+ * Isolation, per capture: a FRESH browser context (no cookies, storage or cache from any other
12
+ * call), service workers blocked (so every request reaches the router), downloads refused,
13
+ * WebSockets closed before they connect, and every HTTP request routed through Jini's `request-guard.ts`,
14
+ * which fetches it itself through the egress guard. As defence in depth, Chromium is launched with
15
+ * a dead proxy and no loopback bypass, so any request that somehow escaped routing would fail
16
+ * rather than reach a network, and WebRTC is limited to proxied UDP (none). That proxy is not
17
+ * hypothetical: Playwright does not route the next hop of a fulfilled 3xx, which is why the router
18
+ * never fulfills one and the page's own redirects are followed by {@link renderPage} instead.
19
+ *
20
+ * Unlike the preview capture, Chromium's own sandbox stays ON (`chromiumSandbox: true`): this
21
+ * browser renders arbitrary, untrusted pages. A host that cannot run the sandbox (some containers)
22
+ * gets `unavailable` unless its composition explicitly passes `allowUnsandboxed`.
23
+ *
24
+ * The browser launches on first use and closes after {@link IDLE_CLOSE_MS} without a capture.
25
+ */
26
+ /** The slice of Playwright this adapter drives — structural, so tests pass a fake without mocking modules. */
27
+ export interface CapturePage {
28
+ goto(url: string, options: {
29
+ waitUntil: "domcontentloaded";
30
+ timeout: number;
31
+ }): Promise<{
32
+ status(): number;
33
+ } | null>;
34
+ waitForTimeout(ms: number): Promise<void>;
35
+ waitForLoadState?(state: "load", options: {
36
+ timeout: number;
37
+ }): Promise<void>;
38
+ /** Called with a string expression only, so no page-side function crosses the boundary. */
39
+ evaluate(expression: string): Promise<unknown>;
40
+ title(): Promise<string>;
41
+ url(): string;
42
+ screenshot(options: {
43
+ type: "png";
44
+ fullPage: boolean;
45
+ clip?: {
46
+ x: number;
47
+ y: number;
48
+ width: number;
49
+ height: number;
50
+ };
51
+ timeout: number;
52
+ animations: "disabled";
53
+ }): Promise<Buffer>;
54
+ }
55
+ export interface CaptureContext {
56
+ route(pattern: string, handler: (route: RouteLike) => Promise<void>): Promise<unknown>;
57
+ routeWebSocket(pattern: RegExp, handler: (socket: {
58
+ close(): Promise<void>;
59
+ }) => unknown): Promise<unknown>;
60
+ newPage(): Promise<CapturePage>;
61
+ close(): Promise<void>;
62
+ }
63
+ export interface CaptureContextOptions {
64
+ viewport: {
65
+ width: number;
66
+ height: number;
67
+ };
68
+ deviceScaleFactor: number;
69
+ isMobile: boolean;
70
+ hasTouch: boolean;
71
+ serviceWorkers: "block";
72
+ acceptDownloads: false;
73
+ ignoreHTTPSErrors: false;
74
+ javaScriptEnabled: true;
75
+ }
76
+ export interface CaptureBrowser {
77
+ newContext(options: CaptureContextOptions): Promise<CaptureContext>;
78
+ close(): Promise<void>;
79
+ }
80
+ export interface CaptureLaunchOptions {
81
+ headless: true;
82
+ chromiumSandbox: boolean;
83
+ args: string[];
84
+ }
85
+ export interface CaptureBrowserLauncher {
86
+ launch(options: CaptureLaunchOptions): Promise<CaptureBrowser>;
87
+ }
88
+ export declare const IDLE_CLOSE_MS = 60000;
89
+ /** The slice of the host's guarded HTTP client the router's hops go through (`send(HttpRequest)`). */
90
+ export interface CaptureHttpClient {
91
+ send(request: HttpRequest): Promise<HttpResponse>;
92
+ }
93
+ /** The slice of Playwright's `chromium` the default launcher drives. */
94
+ export interface CaptureChromium {
95
+ launch(options: Record<string, unknown>): Promise<unknown>;
96
+ }
97
+ /** What the host injects: its guarded client, its capture limits, its caller-safe error and its Playwright loader. */
98
+ export interface PlaywrightPageCaptureDeps {
99
+ /** Guarded client built from the host's web-screenshot egress policy; never a raw transport. */
100
+ httpClient: CaptureHttpClient;
101
+ /** The host's capture limits; each request's own total and work deadline are computed from them. */
102
+ limits: CaptureBudgetLimits;
103
+ /** Builds the screenshot service's caller-safe capture failure (the one error its {@link PageCapturePort} throws). */
104
+ createCaptureError: (required: PageCaptureFailureFields, optional?: {}) => Error;
105
+ /** Whether `error` is a capture failure of kind `timeout` built by `createCaptureError`. */
106
+ isCaptureTimeout: (required: {
107
+ error: unknown;
108
+ }, optional?: {}) => boolean;
109
+ /** The host's lazy Playwright `chromium` loader; used only when neither `browserPool` nor `loadLauncher` is given. */
110
+ importPlaywrightChromium: () => Promise<CaptureChromium>;
111
+ }
112
+ export interface PlaywrightPageCaptureOptions {
113
+ loadLauncher?: () => Promise<CaptureBrowserLauncher>;
114
+ /** Host shares this pool with public reading; its composition owns sandbox/loader choices. */
115
+ browserPool?: RenderBrowserPool;
116
+ ownSiteFetch?: OwnSiteFetch;
117
+ routerOptions?: RequestRouterOptions;
118
+ /** Only for hosts that cannot run Chromium's sandbox; never set from env. */
119
+ allowUnsandboxed?: boolean;
120
+ /** One time source for the render's budget, its hard stop and this adapter's outer race; tests pass a fake of it. */
121
+ clock?: CaptureClock;
122
+ idleCloseMs?: number;
123
+ }
124
+ /**
125
+ * @param required.httpClient - Guarded client built from `WEB_SCREENSHOT_EGRESS_POLICY`.
126
+ * @complexity O(1) per capture beyond the page load and screenshot; at most one browser per adapter.
127
+ */
128
+ export declare function createPlaywrightPageCapture({ httpClient, limits, createCaptureError, isCaptureTimeout, importPlaywrightChromium }: PlaywrightPageCaptureDeps, { loadLauncher, ownSiteFetch, routerOptions, allowUnsandboxed, clock, idleCloseMs, browserPool }?: PlaywrightPageCaptureOptions): PageCapturePort;
129
+ //# sourceMappingURL=playwright-page-capture.d.ts.map