refactor(observation): retain complete tool results

This commit is contained in:
morluto
2026-09-29 12:42:08 +08:00
parent 34d00fd323
commit fa2b6c5a61
37 changed files with 425 additions and 701 deletions
+8 -14
View File
@@ -11,7 +11,7 @@ import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
const origin = "https://app.example.test";
describe("CDP document capture", () => {
it("walks deeply nested frame trees iteratively and retains a bounded prefix", () => {
it("walks deeply nested frame trees and returns every frame and resource", () => {
let frameTree: Record<string, unknown> = {
frame: { id: "frame-0", url: `${origin}/0` },
resources: [{ url: `${origin}/0.js`, type: "Script" }],
@@ -27,12 +27,10 @@ describe("CDP document capture", () => {
};
}
const result = { frameTree };
const frames = captureFrames(result, new Set([origin]), 3);
const resources = captureResources(result, new Set([origin]), 2);
expect(frames).toMatchObject({ total: 2_000 });
expect(frames.items).toHaveLength(3);
expect(resources).toMatchObject({ total: 2_000 });
expect(resources.items).toHaveLength(2);
const frames = captureFrames(result, new Set([origin]));
const resources = captureResources(result, new Set([origin]));
expect(frames.items).toHaveLength(2_000);
expect(resources.items).toHaveLength(2_000);
});
it("rebases parent indexes when allowed DOM documents are combined", () => {
@@ -91,25 +89,23 @@ describe("CDP document capture", () => {
],
},
],
10,
{
includeText: true,
maximumFieldBytes: 4,
maximumTotalBytes: 7,
},
);
expect(capture.nodes[0]).toMatchObject({
name: "😀",
description: "é",
description: "éé",
states: [{ name: "disabled", value: true }],
});
expect(capture.treeIncomplete).toBe(true);
expect(capture.textCapture).toEqual({
status: "truncated",
retained_bytes: 6,
retained_bytes: 8,
excluded_fields: 0,
truncated_fields: 2,
truncated_fields: 1,
});
});
@@ -126,11 +122,9 @@ describe("CDP document capture", () => {
],
},
],
10,
{
includeText: false,
maximumFieldBytes: 1_024,
maximumTotalBytes: 64 * 1_024,
},
);
+20 -46
View File
@@ -20,20 +20,18 @@ export type CapturedResource = Omit<
"resource_key"
> & { readonly rawUrl: string };
/** Normalize allowed frames while retaining a bounded prefix and total count. */
/** Normalize every allowed frame, optionally selecting a leading frame. */
export const captureFrames = (
result: unknown,
allowedOrigins: ReadonlySet<string>,
maximum: number,
maximum?: number,
completeness?: CdpCaptureCompleteness,
): {
readonly total: number;
readonly items: WebPageInspection["frames"];
} => {
const root = recordValue(requiredRecord(result).frameTree);
if (root === undefined) return { total: 0, items: [] };
if (root === undefined) return { items: [] };
const items: WebPageInspection["frames"] = [];
let total = 0;
for (const tree of walkFrameTrees(root)) {
const frame = recordValue(tree.frame);
const frameId = stringValue(frame?.id);
@@ -49,8 +47,7 @@ export const captureFrames = (
);
continue;
}
total += 1;
if (items.length >= maximum) continue;
if (maximum !== undefined && items.length >= maximum) continue;
items.push({
frame_id: frameId,
parent_frame_id:
@@ -59,7 +56,7 @@ export const captureFrames = (
origin: sanitized.origin,
});
}
return { total, items };
return { items };
};
/** Read the current main-frame URL from an untrusted Page.getFrameTree result. */
@@ -68,20 +65,17 @@ export const mainFrameUrl = (result: unknown): string | undefined =>
recordValue(recordValue(requiredRecord(result).frameTree)?.frame)?.url,
);
/** Normalize allowed resources while retaining a bounded prefix and total count. */
/** Normalize every allowed resource. */
export const captureResources = (
result: unknown,
allowedOrigins: ReadonlySet<string>,
maximum: number,
completeness?: CdpCaptureCompleteness,
): {
readonly total: number;
readonly items: readonly CapturedResource[];
} => {
const root = recordValue(requiredRecord(result).frameTree);
if (root === undefined) return { total: 0, items: [] };
if (root === undefined) return { items: [] };
const items: CapturedResource[] = [];
let total = 0;
for (const tree of walkFrameTrees(root)) {
for (const resource of recordsValue(tree.resources)) {
const url = allowedSanitizedUrl(resource.url, allowedOrigins);
@@ -92,8 +86,6 @@ export const captureResources = (
);
continue;
}
total += 1;
if (items.length >= maximum) continue;
const contentSize = numberValue(resource.contentSize);
items.push({
rawUrl: stringValue(resource.url) ?? "",
@@ -106,7 +98,7 @@ export const captureResources = (
});
}
}
return { total, items };
return { items };
};
const walkFrameTrees = function* (
@@ -163,11 +155,7 @@ export const captureDom = (
: [];
const baseIndex = nodes.length;
total += nodeTypes.length;
for (
let index = 0;
index < nodeTypes.length && nodes.length < input.limits.max_dom_nodes;
index += 1
) {
for (let index = 0; index < nodeTypes.length; index += 1) {
const attributeIndexes = numberArray(attributes[index]);
const parent = Math.trunc(parents[index] ?? -1);
const nodeIndex = nodes.length;
@@ -180,8 +168,7 @@ export const captureDom = (
node_value_length: indexedString(strings, nodeValues[index]).length,
attribute_names: attributeIndexes
.filter((_value, attributeIndex) => attributeIndex % 2 === 0)
.map((value) => indexedString(strings, value).slice(0, 256))
.slice(0, 200),
.map((value) => indexedString(strings, value).slice(0, 256)),
});
const metadata = domMetadata({
strings,
@@ -192,10 +179,6 @@ export const captureDom = (
allowedOrigins,
});
for (const url of metadata.urls) {
if (urls.length >= input.limits.max_resources) {
completeness?.truncate("metadata");
continue;
}
urls.push(url);
if (url.destination_scope !== "approved") {
excludedUrls += 1;
@@ -214,18 +197,16 @@ export const captureDom = (
total,
nodes,
urls,
agentHints: agentHints.slice(0, input.limits.max_resources),
agentHints,
excludedUrls,
};
};
export const captureAccessibility = (
results: readonly unknown[],
maximum: number,
options: {
readonly includeText: boolean;
readonly maximumFieldBytes: number;
readonly maximumTotalBytes: number;
readonly unavailable?: boolean;
},
): {
@@ -243,10 +224,9 @@ export const captureAccessibility = (
return nodeId === undefined ? [] : [nodeId];
}),
);
let retainedBytes = 0;
let excludedFields = 0;
let truncatedFields = 0;
const nodes = all.slice(0, maximum).map((node) => {
const nodes = all.map((node) => {
const captureText = (value: unknown): string | null => {
const raw = stringValue(recordValue(value)?.value);
if (raw === undefined) return null;
@@ -254,12 +234,7 @@ export const captureAccessibility = (
excludedFields += 1;
return null;
}
const available = Math.max(0, options.maximumTotalBytes - retainedBytes);
const captured = boundedUtf8(
raw,
Math.min(options.maximumFieldBytes, available),
);
retainedBytes += captured.bytes;
const captured = boundedUtf8(raw, options.maximumFieldBytes);
if (captured.truncated) {
truncatedFields += 1;
if (captured.text === "" && raw !== "") {
@@ -279,13 +254,6 @@ export const captureAccessibility = (
states: accessibilityStates(node.properties),
};
});
for (const node of all.slice(maximum)) {
for (const value of [node.name, node.description]) {
if (stringValue(recordValue(value)?.value) === undefined) continue;
excludedFields += 1;
if (options.includeText) truncatedFields += 1;
}
}
return {
total: all.length,
nodes,
@@ -305,7 +273,13 @@ export const captureAccessibility = (
: truncatedFields > 0
? "truncated"
: "included",
retained_bytes: retainedBytes,
retained_bytes: nodes.reduce(
(total, node) =>
total +
Buffer.byteLength(node.name ?? "") +
Buffer.byteLength(node.description ?? ""),
0,
),
excluded_fields: excludedFields,
truncated_fields: truncatedFields,
},
+1 -4
View File
@@ -80,13 +80,10 @@ const inferBodyShape = (
text: string,
): { readonly shape: JsonShape | null; readonly truncated: boolean } => {
const bytes = Buffer.byteLength(text);
const remaining =
state.input.limits.max_total_json_body_bytes - state.jsonBodyBytes;
if (bytes > state.input.limits.max_json_body_bytes || bytes > remaining) {
if (bytes > state.input.limits.max_json_body_bytes) {
state.completeness.truncate("json_body_shapes");
return { shape: null, truncated: true };
}
state.jsonBodyBytes += bytes;
const shape = inferJsonShape(text, {
maximumBytes: state.input.limits.max_json_body_bytes,
maximumNodes: state.input.limits.max_json_shape_nodes,
+5 -61
View File
@@ -40,13 +40,6 @@ export const handleExecutionContextCreated = (
)
return;
const key = String(identifier);
if (
state.executionContextFrames.size >= state.input.limits.max_scripts &&
!state.executionContextFrames.has(key)
) {
state.completeness.truncate("scripts");
return;
}
state.executionContextFrames.set(key, frameId);
};
@@ -73,13 +66,6 @@ export const handleScriptParsed = (
state.completeness.exclude("scripts", exclusionReasonForUrl(rawUrl));
return;
}
if (
state.scripts.size >= state.input.limits.max_scripts &&
!state.scripts.has(scriptId)
) {
state.completeness.drop("scripts");
return;
}
const sourceMap = sourceMapForScript(params.sourceMapURL, rawUrl, state);
const script: CapturedScript = {
scriptId,
@@ -148,13 +134,6 @@ export const handleRequestWillBeSent = (
state.network.delete(requestId);
return;
}
if (
state.network.size >= state.input.limits.max_network_events &&
!state.network.has(requestId)
) {
state.completeness.drop("network_requests");
return;
}
const initiator = recordValue(params.initiator);
const initiatorFrame = initiatorLocation(initiator);
const rawInitiatorUrl = stringValue(initiatorFrame?.url);
@@ -214,10 +193,6 @@ export const handleResponseReceived = (
status: numberValue(response.status) ?? null,
mime_type: boundedText(response.mimeType, 256),
});
if (state.responseMetadata.length >= state.input.limits.max_network_events) {
state.completeness.truncate("metadata");
return;
}
const metadata = safeResponseMetadata(
requestId,
sanitized.url,
@@ -262,19 +237,13 @@ export const handleConsoleAPICalled = (
);
return;
}
if (state.console.length >= state.input.limits.max_console_events) {
state.completeness.drop("console_events");
return;
}
const arguments_ = recordsValue(params.args);
state.console.push({
type: (stringValue(params.type) ?? "unknown").slice(0, 100),
timestamp: numberValue(params.timestamp) ?? 0,
argument_types: arguments_
.map((argument) =>
(stringValue(argument.type) ?? "unknown").slice(0, 100),
)
.slice(0, 100),
argument_types: arguments_.map((argument) =>
(stringValue(argument.type) ?? "unknown").slice(0, 100),
),
url: source.url,
line: integerOrNull(frame.lineNumber),
column: integerOrNull(frame.columnNumber),
@@ -300,15 +269,9 @@ const captureConsoleText = (
for (const [argumentIndex, argument] of arguments_.entries()) {
const primitive = consolePrimitive(argument);
if (primitive === undefined) continue;
const remaining =
state.input.limits.max_total_console_text_bytes - state.consoleTextBytes;
if (remaining <= 0) {
truncatedValues += 1;
continue;
}
const bounded = boundedSensitiveText(
primitive.text,
Math.min(state.input.limits.max_console_text_field_bytes, remaining),
state.input.limits.max_console_text_field_bytes,
);
values.push({
argument_index: argumentIndex,
@@ -316,7 +279,6 @@ const captureConsoleText = (
text: bounded.text,
});
retainedBytes += bounded.bytes;
state.consoleTextBytes += bounded.bytes;
if (bounded.truncated) truncatedValues += 1;
}
if (truncatedValues > 0) state.completeness.truncate("console_text");
@@ -340,10 +302,6 @@ export const handleWebSocketFrame = (
(!state.network.has(requestId) && !state.allowedWebSockets.has(requestId))
)
return;
if (state.websockets.length >= state.input.limits.max_websocket_events) {
state.completeness.drop("websocket_frames");
return;
}
const response = recordValue(params.response);
const payload = stringValue(response?.payloadData) ?? "";
const opcode = Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0));
@@ -369,17 +327,10 @@ const captureWebSocketShape = (
if (opcode !== 1)
return { format: "binary", json_shape: null, truncated: false };
const bytes = Buffer.byteLength(payload);
const remaining =
state.input.limits.max_total_websocket_shape_bytes -
state.websocketShapeBytes;
if (
bytes > state.input.limits.max_websocket_shape_bytes ||
bytes > remaining
) {
if (bytes > state.input.limits.max_websocket_shape_bytes) {
state.completeness.truncate("websocket_shapes");
return { format: "text", json_shape: null, truncated: true };
}
state.websocketShapeBytes += bytes;
const shape = inferJsonShape(payload, {
maximumBytes: state.input.limits.max_websocket_shape_bytes,
maximumNodes: state.input.limits.max_json_shape_nodes,
@@ -431,13 +382,6 @@ export const handleWebSocketCreated = (
state.completeness.exclude("websocket_connections", "disallowed_origin");
return;
}
if (
!state.allowedWebSockets.has(requestId) &&
state.allowedWebSockets.size >= state.input.limits.max_websocket_events
) {
state.completeness.drop("websocket_connections");
return;
}
state.allowedWebSockets.add(requestId);
};
-3
View File
@@ -20,7 +20,4 @@ export interface CdpCaptureEventsState {
originViolation: boolean;
navigationDuringCapture: boolean;
mainFrameId: string | undefined;
consoleTextBytes: number;
jsonBodyBytes: number;
websocketShapeBytes: number;
}
+1 -7
View File
@@ -13,7 +13,7 @@ import { recordValue } from "./CdpCaptureValues.js";
export { type CapturedScript } from "./CdpCaptureEventTypes.js";
/** Bounded event accumulator that drops payload values at ingestion time. */
/** Event accumulator that validates and normalizes payloads at ingestion. */
export class CdpCaptureEvents implements CdpCaptureEventsState {
readonly scripts = new Map<string, CapturedScript>();
readonly executionContextFrames = new Map<string, string>();
@@ -33,9 +33,6 @@ export class CdpCaptureEvents implements CdpCaptureEventsState {
originViolation = false;
navigationDuringCapture = false;
mainFrameId: string | undefined = undefined;
consoleTextBytes = 0;
jsonBodyBytes = 0;
websocketShapeBytes = 0;
readonly input: InspectWebPageInput;
readonly allowedOrigins: ReadonlySet<string>;
@@ -57,9 +54,6 @@ export class CdpCaptureEvents implements CdpCaptureEventsState {
this.websockets.length = 0;
this.responseMetadata.length = 0;
this.agentHints.length = 0;
this.consoleTextBytes = 0;
this.jsonBodyBytes = 0;
this.websocketShapeBytes = 0;
this.completeness.reset();
if (!this.input.include_console_text)
this.completeness.exclude("console_text", "not_approved", null);
+9 -25
View File
@@ -16,7 +16,7 @@ import {
stringValue,
} from "./CdpCaptureValues.js";
/** Capture redacted, bounded storage metadata for one authorized origin. */
/** Capture redacted storage metadata for one authorized origin. */
export const captureStorage = async (
context: {
readonly connection: CdpConnection;
@@ -28,7 +28,6 @@ export const captureStorage = async (
limitations: string[],
): Promise<{
readonly value: WebPageInspection["storage"];
readonly truncated: boolean;
}> => {
const quota = recordValue(
await optionalCdpCommand(
@@ -64,22 +63,17 @@ export const captureStorage = async (
: undefined;
const cacheValues = recordsValue(recordValue(cacheRaw)?.caches);
const caches = capturedCaches(cacheValues);
const maximum = context.input.limits.max_storage_keys;
const fingerprints = context.input.include_storage_fingerprints
? await captureStorageFingerprints({
context,
origin,
local,
session,
indexedDbNames: indexed.slice(0, maximum),
caches: caches.slice(0, maximum),
indexedDbNames: indexed,
caches,
limitations,
})
: { items: [], complete: false as const, truncated: false };
const truncated =
[local.items, session.items, indexed, caches].some(
(items) => items.length > maximum,
) || fingerprints.truncated;
: { items: [], complete: false };
const structuredStorageComplete =
indexedRaw !== undefined &&
Array.isArray(indexedValues) &&
@@ -91,25 +85,15 @@ export const captureStorage = async (
origin,
usage_bytes: numberValue(quota?.usage) ?? null,
quota_bytes: numberValue(quota?.quota) ?? null,
local_storage_keys: local.items
.map(({ key }) => key.slice(0, 1_024))
.slice(0, maximum),
session_storage_keys: session.items
.map(({ key }) => key.slice(0, 1_024))
.slice(0, maximum),
indexed_db_names: indexed
.map((name) => name.slice(0, 1_024))
.slice(0, maximum),
cache_names: caches
.map(({ name }) => name.slice(0, 1_024))
.slice(0, maximum),
local_storage_keys: local.items.map(({ key }) => key.slice(0, 1_024)),
session_storage_keys: session.items.map(({ key }) => key.slice(0, 1_024)),
indexed_db_names: indexed.map((name) => name.slice(0, 1_024)),
cache_names: caches.map(({ name }) => name.slice(0, 1_024)),
content_fingerprints: [...fingerprints.items],
fingerprint_algorithm: "sha256",
fingerprints_complete:
fingerprints.complete && structuredStorageComplete && !truncated,
fingerprints_complete: fingerprints.complete && structuredStorageComplete,
values_redacted: true,
},
truncated,
};
};
+97 -102
View File
@@ -37,9 +37,7 @@ interface StorageFingerprintContext {
interface FingerprintState {
readonly items: StorageFingerprint[];
readonly maximum: number;
complete: boolean;
truncated: boolean;
}
interface FingerprintRun {
@@ -60,10 +58,8 @@ interface CaptureStorageFingerprintInput {
type StorageFingerprintCapture = {
readonly items: readonly StorageFingerprint[];
} & (
| { readonly complete: true; readonly truncated: false }
| { readonly complete: false; readonly truncated: boolean }
);
readonly complete: boolean;
};
/** Capture stable hashes of approved storage content without returning values. */
export const captureStorageFingerprints = async ({
@@ -77,9 +73,7 @@ export const captureStorageFingerprints = async ({
}: CaptureStorageFingerprintInput): Promise<StorageFingerprintCapture> => {
const state: FingerprintState = {
items: [],
maximum: context.input.limits.max_storage_keys,
complete: local.complete && session.complete,
truncated: false,
};
const run = { context, limitations, state };
addStorageItems(state, "local_storage", local.items);
@@ -94,16 +88,8 @@ export const captureStorageFingerprints = async ({
),
);
const complete =
state.complete &&
!state.truncated &&
state.items.every(({ complete }) => complete);
return complete
? { items: state.items, complete: true, truncated: false }
: {
items: state.items,
complete: false,
truncated: state.truncated,
};
state.complete && state.items.every(({ complete }) => complete);
return { items: state.items, complete };
};
const addStorageItems = (
@@ -175,10 +161,6 @@ const addIndexedDb = async (
names: readonly string[],
): Promise<void> => {
for (const databaseName of names) {
if (run.state.items.length >= run.state.maximum) {
run.state.truncated = true;
return;
}
const raw = await optionalCdpCommand(
run.context,
"IndexedDB.requestDatabase",
@@ -261,57 +243,62 @@ const addIndexedDbRecords = async (
readonly objectStoreName: string;
},
): Promise<void> => {
const remaining = run.state.maximum - run.state.items.length;
if (remaining <= 0) {
run.state.truncated = true;
return;
}
const raw = await optionalCdpCommand(
run.context,
"IndexedDB.requestData",
{
securityOrigin: input.origin,
databaseName: input.databaseName,
objectStoreName: input.objectStoreName,
indexName: "",
skipCount: 0,
pageSize: remaining,
},
run.limitations,
);
const result = recordValue(raw);
if (raw === undefined || result === undefined) {
run.state.complete = false;
return;
}
if (
!Array.isArray(result.objectStoreDataEntries) ||
typeof result.hasMore !== "boolean"
) {
run.state.complete = false;
return;
}
const entries = recordsValue(result.objectStoreDataEntries);
if (entries.length !== result.objectStoreDataEntries.length)
run.state.complete = false;
for (const entry of entries) {
const key = stableValue(entry.key);
const primaryKey = stableValue(entry.primaryKey);
const value = stableValue(entry.value);
addFingerprint(run.state, {
scope: "indexed_db_record",
identity: {
database: input.databaseName,
store: input.objectStoreName,
key,
primaryKey,
let skipCount = 0;
while (true) {
const raw = await optionalCdpCommand(
run.context,
"IndexedDB.requestData",
{
securityOrigin: input.origin,
databaseName: input.databaseName,
objectStoreName: input.objectStoreName,
indexName: "",
skipCount,
pageSize: STORAGE_ENTRY_PAGE_SIZE,
},
value,
complete: remoteObjectComplete(entry.value),
});
run.limitations,
);
const result = recordValue(raw);
if (raw === undefined || result === undefined) {
run.state.complete = false;
return;
}
if (
!Array.isArray(result.objectStoreDataEntries) ||
typeof result.hasMore !== "boolean"
) {
run.state.complete = false;
return;
}
const entries = recordsValue(result.objectStoreDataEntries);
if (entries.length !== result.objectStoreDataEntries.length)
run.state.complete = false;
for (const entry of entries) {
const key = stableValue(entry.key);
const primaryKey = stableValue(entry.primaryKey);
const value = stableValue(entry.value);
addFingerprint(run.state, {
scope: "indexed_db_record",
identity: {
database: input.databaseName,
store: input.objectStoreName,
key,
primaryKey,
},
value,
complete: remoteObjectComplete(entry.value),
});
}
if (result.hasMore !== true) return;
if (
entries.length === 0 ||
skipCount > Number.MAX_SAFE_INTEGER - entries.length
) {
run.state.complete = false;
return;
}
skipCount += entries.length;
}
if (result.hasMore === true || entries.length > remaining)
run.state.truncated = true;
};
const addCaches = async (
@@ -319,34 +306,44 @@ const addCaches = async (
caches: readonly CapturedCache[],
): Promise<void> => {
for (const cache of caches) {
const remaining = run.state.maximum - run.state.items.length;
if (remaining <= 0) {
run.state.truncated = true;
return;
let skipCount = 0;
let returnCount: number | undefined;
while (returnCount === undefined || skipCount < returnCount) {
const raw = await optionalCdpCommand(
run.context,
"CacheStorage.requestEntries",
{ cacheId: cache.id, skipCount, pageSize: STORAGE_ENTRY_PAGE_SIZE },
run.limitations,
);
const result = recordValue(raw);
if (raw === undefined || result === undefined) {
run.state.complete = false;
break;
}
if (
!Array.isArray(result.cacheDataEntries) ||
typeof result.returnCount !== "number" ||
!Number.isSafeInteger(result.returnCount) ||
result.returnCount < 0
) {
run.state.complete = false;
break;
}
const entries = recordsValue(result.cacheDataEntries);
if (entries.length !== result.cacheDataEntries.length)
run.state.complete = false;
for (const entry of entries) await addCacheEntry(run, cache, entry);
returnCount = result.returnCount;
if (skipCount + entries.length >= returnCount) break;
if (
entries.length === 0 ||
skipCount > Number.MAX_SAFE_INTEGER - entries.length
) {
run.state.complete = false;
break;
}
skipCount += entries.length;
}
const raw = await optionalCdpCommand(
run.context,
"CacheStorage.requestEntries",
{ cacheId: cache.id, skipCount: 0, pageSize: remaining },
run.limitations,
);
const result = recordValue(raw);
if (raw === undefined || result === undefined) {
run.state.complete = false;
continue;
}
if (
!Array.isArray(result.cacheDataEntries) ||
typeof result.returnCount !== "number"
) {
run.state.complete = false;
continue;
}
const entries = recordsValue(result.cacheDataEntries);
if (entries.length !== result.cacheDataEntries.length)
run.state.complete = false;
for (const entry of entries) await addCacheEntry(run, cache, entry);
if (result.returnCount > entries.length) run.state.truncated = true;
}
};
@@ -406,10 +403,6 @@ const addFingerprint = (
readonly complete: boolean;
},
): void => {
if (state.items.length >= state.maximum) {
state.truncated = true;
return;
}
state.items.push({
scope: input.scope,
identity_sha256: digest(input.identity),
@@ -421,6 +414,8 @@ const addFingerprint = (
});
};
const STORAGE_ENTRY_PAGE_SIZE = 1_000;
const digest = (value: unknown): string =>
createHash("sha256").update(encodedValue(value)).digest("hex");
+10 -28
View File
@@ -84,7 +84,7 @@ export const capturePage = async (
allowedOrigins,
limitations: [
"Observation starts when REA attaches; prior network and console activity is unavailable.",
"Raw network headers, bodies, cookies, storage values, console objects, and WebSocket payloads are never retained; separately approved captures retain only bounded redacted text or value-free shapes.",
"Raw network headers, bodies, cookies, storage values, console objects, and WebSocket payloads are never retained; separately approved captures retain only redacted text or value-free shapes.",
"Source maps are reported only as declarative URLs and are not fetched.",
"URL-less scripts and console events without an allowed source URL are excluded because their origin cannot be proven.",
],
@@ -109,12 +109,10 @@ const captureAuthorizedPage = async (
const frameCapture = captureFrames(
frameResult,
allowedOrigins,
input.limits.max_frames,
undefined,
state.events.completeness,
);
const frames = frameCapture.items;
if (frameCapture.total > frames.length)
state.events.completeness.truncate("frames");
const captureFrame = frames[0];
if (captureFrame === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
@@ -122,19 +120,13 @@ const captureAuthorizedPage = async (
const resourceCapture = captureResources(
await connection.send("Page.getResourceTree", {}, sessionId, signal),
allowedOrigins,
input.limits.max_resources,
state.events.completeness,
);
if (resourceCapture.total > resourceCapture.items.length)
state.events.completeness.truncate("resources");
const resources = stableWebResources(
resourceCapture.items.map(publicResource),
);
const dom = await capturePageDom(state);
if (dom.total > dom.nodes.length) state.events.completeness.truncate("dom");
const accessibility = await accessibilityForFrames(state, frames);
if (accessibility.total > accessibility.nodes.length)
state.events.completeness.truncate("accessibility");
const scripts = await captureScripts({
context,
events: state.events,
@@ -142,19 +134,15 @@ const captureAuthorizedPage = async (
resources,
frameIds: new Set(frames.map((frame) => frame.frame_id)),
});
const workerCapture = await captureWorkers(
const workers = await captureWorkers(
{ context, allowedOrigins, limitations, events: state.events },
new Set(frames.map((frame) => frame.frame_id)),
);
if (workerCapture.total > workerCapture.items.length)
state.events.completeness.truncate("workers");
const storageCapture = await captureStorage(
context,
frames[0]?.origin ?? new URL(attachedUrl).origin,
limitations,
);
if (storageCapture.truncated)
state.events.completeness.truncate("storage_keys");
if (!input.include_storage_keys)
state.events.completeness.exclude("storage_keys", "not_approved", null);
const completedFrameResult = await authorizedFrameTree(
@@ -175,7 +163,7 @@ const captureAuthorizedPage = async (
accessibility,
scripts: scripts.inventory,
resources,
workers: workerCapture.items,
workers,
storage: storageCapture.value,
}),
sourceMapRequests: scripts.sourceMapRequests,
@@ -213,8 +201,7 @@ const authorizeObservationWindow = async (
await report(context.progress, 1, "Enabling passive CDP domains");
await connection.send("Page.enable", {}, sessionId, signal);
const initialFrameResult = await authorizedFrameTree(context, allowedOrigins);
const mainFrame = captureFrames(initialFrameResult, allowedOrigins, 1)
.items[0];
const mainFrame = captureFrames(initialFrameResult, allowedOrigins).items[0];
if (mainFrame === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
events.beginAuthorizedFrame(mainFrame.frame_id);
@@ -367,16 +354,11 @@ const accessibilityForFrames = async (
else results.push(result);
}
if (unavailable) events.completeness.unavailable("accessibility");
const capture = captureAccessibility(
results,
context.input.limits.max_ax_nodes,
{
includeText: context.input.include_accessibility_text,
maximumFieldBytes: context.input.limits.max_ax_text_field_bytes,
maximumTotalBytes: context.input.limits.max_total_ax_text_bytes,
...(results.length === 0 && unavailable ? { unavailable: true } : {}),
},
);
const capture = captureAccessibility(results, {
includeText: context.input.include_accessibility_text,
maximumFieldBytes: context.input.limits.max_ax_text_field_bytes,
...(results.length === 0 && unavailable ? { unavailable: true } : {}),
});
if (!context.input.include_accessibility_text)
events.completeness.exclude(
"accessibility",
+2 -16
View File
@@ -34,7 +34,6 @@ interface ScriptDraftState {
readonly frameIds: ReadonlySet<string>;
readonly rawResources: readonly CapturedResource[];
readonly resources: WebPageInspection["resources"];
totalSourceBytes: number;
}
type ScriptDraftItem = Omit<
@@ -52,7 +51,6 @@ export const captureScripts = async (
frameIds,
rawResources,
resources,
totalSourceBytes: 0,
};
const drafts: {
readonly item: ScriptDraftItem;
@@ -113,13 +111,6 @@ const captureScriptSource = async (
events.completeness.truncate("script_sources");
return sourceExcluded("declared script length exceeds per-script limit");
}
if (
state.totalSourceBytes + script.length >
context.input.limits.max_total_script_source_bytes
) {
events.completeness.truncate("script_sources");
return sourceExcluded("total script source limit reached");
}
const result = requiredRecord(
await context.connection.send(
"Debugger.getScriptSource",
@@ -130,15 +121,10 @@ const captureScriptSource = async (
);
const content = stringValue(result.scriptSource) ?? "";
const bytes = Buffer.byteLength(content);
if (
bytes > context.input.limits.max_script_source_bytes ||
state.totalSourceBytes + bytes >
context.input.limits.max_total_script_source_bytes
) {
if (bytes > context.input.limits.max_script_source_bytes) {
events.completeness.truncate("script_sources");
return sourceExcluded("actual source exceeds configured byte limits");
return sourceExcluded("actual source exceeds the per-script byte limit");
}
state.totalSourceBytes += bytes;
return sourceResult(content);
};
+2 -8
View File
@@ -21,10 +21,7 @@ interface CaptureWorkersInput {
export const captureWorkers = async (
input: CaptureWorkersInput,
frameIds: ReadonlySet<string>,
): Promise<{
readonly total: number;
readonly items: WebPageInspection["workers"];
}> => {
): Promise<WebPageInspection["workers"]> => {
const { context, allowedOrigins, limitations, events } = input;
const completeness = events.completeness;
const result = await optionalCdpCommand(
@@ -34,7 +31,6 @@ export const captureWorkers = async (
limitations,
);
const items: WebPageInspection["workers"] = [];
let total = 0;
if (result === undefined) completeness.unavailable("workers");
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
const type = stringValue(target.type) ?? "";
@@ -60,8 +56,6 @@ export const captureWorkers = async (
);
continue;
}
total += 1;
if (items.length >= context.input.limits.max_workers) continue;
items.push({
target_id: (stringValue(target.targetId) ?? "").slice(0, 256),
type: type.slice(0, 100),
@@ -72,5 +66,5 @@ export const captureWorkers = async (
parent_frame_id: boundedText(target.parentFrameId, 256) ?? null,
});
}
return { total, items };
return items;
};
+15 -15
View File
@@ -58,7 +58,12 @@ export const discoverWebMcp = async (
const initialUrl = mainFrameUrl(frameTree);
if (allowedSanitizedUrl(initialUrl, origins) === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
const frames = captureFrames(frameTree, origins, 1_000, completeness).items;
const frames = captureFrames(
frameTree,
origins,
undefined,
completeness,
).items;
const frameUrls = new Map(
frames.map((frame) => [
frame.frame_id,
@@ -263,10 +268,6 @@ const ingestWebMcpEvent = (options: WebMcpIngestOptions): void => {
for (const declared of recordsValue(params.tools)) {
const normalized = normalizeTool(declared, input, frames, completeness);
if (normalized === undefined) continue;
if (!tools.has(normalized.tool_key) && tools.size >= input.max_tools) {
completeness.drop("webmcp_tools");
continue;
}
tools.set(normalized.tool_key, normalized);
}
};
@@ -308,7 +309,7 @@ const normalizeTool = (
numberValue(value.backendNodeId) === undefined
? "imperative"
: "declarative",
input_schema_shape: schemaShape(value.inputSchema, input, completeness),
input_schema_shape: schemaShape(value.inputSchema),
annotations: {
read_only: booleanOrNull(annotations?.readOnly),
untrusted_content: booleanOrNull(annotations?.untrustedContent),
@@ -322,19 +323,18 @@ const normalizeTool = (
};
};
const schemaShape = (
value: unknown,
input: DiscoverWebMcpToolsInput,
completeness: CdpCaptureCompleteness,
) => {
const schemaShape = (value: unknown) => {
if (recordValue(value) === undefined) return null;
const encoded = JSON.stringify(value);
const shape = inferJsonShape(encoded, {
maximumBytes: input.max_schema_bytes,
maximumNodes: input.max_schema_nodes,
maximumDepth: input.max_schema_depth,
maximumBytes: 256 * 1_024,
maximumNodes: 5_000,
maximumDepth: 20,
});
if (shape === null || shape.truncated) completeness.truncate("webmcp_tools");
if (shape === null)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
if (shape.truncated)
throw new BrowserObservationError("inspect_web_page", "payload_limit");
return shape;
};