refactor(observation): return complete inventories

This commit is contained in:
morluto
2026-09-29 13:02:30 +08:00
parent e80fe414b1
commit c523c38027
18 changed files with 238 additions and 209 deletions
-1
View File
@@ -53,7 +53,6 @@ const parameters = (
target_id: input.target_id,
observation_ms: input.observation_ms,
include_script_sources: input.include_script_sources,
limits: input.limits,
}
: {}),
});
@@ -56,7 +56,6 @@ const parameters = (
? {}
: { runtime_kind: input.runtime_kind }),
observation_ms: input.observation_ms,
limits: input.limits,
}
: {}),
});
+2 -19
View File
@@ -150,12 +150,7 @@ const authorizeInitialFrames = async (
context.sessionId,
context.signal,
);
const frames = await captureFrames(
result,
state.roots,
context.input.limits.max_frames,
state.completeness,
);
const frames = await captureFrames(result, state.roots, state.completeness);
if (frames[0] === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
return frames;
@@ -248,7 +243,6 @@ const navigatedFrameId = (event: CdpEvent): string | undefined => {
const captureFrames = async (
result: unknown,
roots: readonly string[],
maximum: number,
completeness: CdpCaptureCompleteness,
): Promise<ElectronPageInspection["frames"]> => {
const frameTree = recordValue(requiredRecord(result).frameTree);
@@ -272,10 +266,6 @@ const captureFrames = async (
completeness.exclude("frames", "out_of_target_scope");
continue;
}
if (frames.length >= maximum) {
completeness.truncate("frames");
continue;
}
frames.push({
frame_id: frameId.slice(0, 256),
parent_frame_id: current.parent,
@@ -328,10 +318,6 @@ const captureResources = async (
const resourceKey = `electron_resource_${digest(item)}`;
if (seen.has(resourceKey)) continue;
seen.add(resourceKey);
if (resources.length >= context.input.limits.max_resources) {
completeness.truncate("resources");
continue;
}
resources.push({
resource_key: resourceKey,
...item,
@@ -377,7 +363,6 @@ const captureDom = async (
const baseIndex = nodes.length;
total += nodeTypes.length;
for (let index = 0; index < nodeTypes.length; index += 1) {
if (nodes.length >= context.input.limits.max_dom_nodes) continue;
const attributeIndexes = arrayValue(attributes[index]);
const parent = integer(parents[index], -1);
nodes.push({
@@ -390,12 +375,10 @@ const captureDom = async (
),
attribute_names: attributeIndexes
.filter((_value, attributeIndex) => attributeIndex % 2 === 0)
.map((value) => stringAt(strings, value).slice(0, 1_024))
.slice(0, 256),
.map((value) => stringAt(strings, value).slice(0, 1_024)),
});
}
}
if (total > nodes.length) completeness.truncate("dom");
return { total_nodes: total, nodes };
};
+5 -27
View File
@@ -6,6 +6,7 @@ import type {
ElectronPageInspection,
InspectElectronPageInput,
} from "../domain/electronObservation.js";
import { MAX_ELECTRON_SCRIPT_SOURCE_BYTES } from "../domain/electronObservation.js";
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
import type { CdpConnection } from "./CdpConnection.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
@@ -30,7 +31,6 @@ export const captureElectronScripts = async (
input: ElectronScriptCaptureInput,
): Promise<ElectronPageInspection["scripts"]> => {
let total = 0;
let sourceBytes = 0;
const items: ElectronPageInspection["scripts"]["items"] = [];
const seen = new Set<string>();
for (const script of input.scripts) {
@@ -58,16 +58,7 @@ export const captureElectronScripts = async (
if (seen.has(scriptKey)) continue;
seen.add(scriptKey);
total += 1;
if (items.length >= input.request.limits.max_scripts) {
input.completeness.drop("scripts");
continue;
}
const capturedSource = await captureScriptSource(
input,
script,
sourceBytes,
);
sourceBytes += capturedSource.bytes;
const capturedSource = await captureScriptSource(input, script);
items.push({
script_key: scriptKey,
...identity,
@@ -90,10 +81,8 @@ type ElectronScriptSource =
const captureScriptSource = async (
input: ElectronScriptCaptureInput,
script: ElectronScriptDraft,
sourceBytes: number,
): Promise<{
readonly source: ElectronScriptSource;
readonly bytes: number;
}> => {
if (!input.request.include_script_sources)
return {
@@ -101,9 +90,8 @@ const captureScriptSource = async (
included: false,
reason: "source capture was not approved",
},
bytes: 0,
};
if (sourceLimitReached(input.request.limits, script.length, sourceBytes))
if (script.length > MAX_ELECTRON_SCRIPT_SOURCE_BYTES)
return sourceLimitResult(input.completeness);
const result = requiredRecord(
await input.connection.send(
@@ -115,32 +103,22 @@ const captureScriptSource = async (
);
const text = stringValue(result.scriptSource) ?? "";
const bytes = Buffer.byteLength(text);
if (sourceLimitReached(input.request.limits, bytes, sourceBytes))
if (bytes > MAX_ELECTRON_SCRIPT_SOURCE_BYTES)
return sourceLimitResult(input.completeness);
return {
source: {
included: true,
artifact: createWebTextArtifact(text, "text/javascript"),
},
bytes,
};
};
const sourceLimitReached = (
limits: InspectElectronPageInput["limits"],
bytes: number,
previousBytes: number,
): boolean =>
bytes > limits.max_script_source_bytes ||
previousBytes + bytes > limits.max_total_script_source_bytes;
const sourceLimitResult = (
completeness: CdpCaptureCompleteness,
): { readonly source: ElectronScriptSource; readonly bytes: 0 } => {
): { readonly source: ElectronScriptSource } => {
completeness.truncate("script_sources");
return {
source: { included: false, reason: "script source byte limit reached" },
bytes: 0,
};
};
-4
View File
@@ -60,10 +60,6 @@ export const captureElectronWorkers = async (input: {
input.completeness.exclude("workers", "out_of_target_scope");
continue;
}
if (workers.length >= input.request.limits.max_workers) {
input.completeness.truncate("workers");
continue;
}
const targetId = boundedTargetField(target.targetId);
if (targetId === null) {
input.completeness.exclude("workers", "invalid_protocol_value");
+9 -38
View File
@@ -4,6 +4,7 @@ import type {
} from "../application/AnalysisProvider.js";
import type { JavaScriptRuntimeObservationPort } from "../application/JavaScriptRuntimeObservationPort.js";
import {
MAX_JAVASCRIPT_RUNTIME_LOCATION_BYTES,
javascriptRuntimeObservationSchema,
javascriptRuntimeTargetListSchema,
type JavaScriptRuntimeObservation,
@@ -252,17 +253,13 @@ const ingestEvent = (
)
return;
state.eventsObserved += 1;
if (state.eventsObserved > input.limits.max_events) {
drop(state, "max_events");
return;
}
if (event.method === "Debugger.scriptParsed") {
ingestScript(event, input, state);
return;
}
if (event.method === "Debugger.scriptFailedToParse") {
state.invalidScripts += 1;
retainEvent(state, 0, input);
retainEvent(state, 0);
return;
}
ingestContext(event, input, state);
@@ -279,14 +276,10 @@ const ingestScript = (
if (
rawUrl === undefined ||
rawUrl === "" ||
Buffer.byteLength(rawUrl) > input.limits.max_location_bytes
Buffer.byteLength(rawUrl) > MAX_JAVASCRIPT_RUNTIME_LOCATION_BYTES
) {
state.invalidScripts += 1;
retainEvent(state, 0, input);
return;
}
if (state.scripts.length >= input.limits.max_scripts) {
drop(state, "max_scripts");
retainEvent(state, 0);
return;
}
const draft: ScriptDraft = {
@@ -297,7 +290,7 @@ const ingestScript = (
isModule: value?.isModule === true,
};
const bytes = metadataBytes(draft);
if (!retainEvent(state, bytes, input)) return;
retainEvent(state, bytes);
state.scripts.push(draft);
};
@@ -308,7 +301,7 @@ const ingestContext = (
): void => {
if (event.method === "Runtime.executionContextsCleared") {
for (const context of state.contexts.values()) context.state = "cleared";
retainEvent(state, 0, input);
retainEvent(state, 0);
return;
}
const parameters = recordValue(event.params);
@@ -322,14 +315,7 @@ const ingestContext = (
: runtimeContext?.executionContextId,
);
if (key === null) {
retainEvent(state, 0, input);
return;
}
if (
state.contexts.size >= input.limits.max_execution_contexts &&
!state.contexts.has(key)
) {
drop(state, "max_execution_contexts");
retainEvent(state, 0);
return;
}
const origin =
@@ -346,28 +332,13 @@ const ingestContext = (
origin !== null && input.allowed_origins.includes(origin) ? origin : null,
};
const bytes = metadataBytes(draft);
if (!retainEvent(state, bytes, input)) return;
retainEvent(state, bytes);
state.contexts.set(key, draft);
};
const retainEvent = (
state: CaptureState,
bytes: number,
input: ObserveJavaScriptRuntimeInput,
): boolean => {
if (state.metadataBytes + bytes > input.limits.max_total_metadata_bytes) {
drop(state, "max_total_metadata_bytes");
return false;
}
const retainEvent = (state: CaptureState, bytes: number): void => {
state.metadataBytes += bytes;
state.eventsRetained += 1;
return true;
};
const drop = (state: CaptureState, reason: string): void => {
state.eventsDropped += 1;
state.truncated = true;
state.truncationReasons.add(reason);
};
const waitForCapture = async (
+1 -1
View File
@@ -58,7 +58,7 @@ export const electronActiveObservationInputSchema = z.strictObject({
executable_path: absolutePathSchema,
application_path: absolutePathSchema,
application_root: absolutePathSchema,
args: z.array(z.string().max(4_096)).max(32).default([]),
args: z.array(z.string().max(4_096)).default([]),
actions: z.array(actionSchema).default([]),
});
export type ElectronActiveObservationInput = z.infer<
+12 -25
View File
@@ -24,16 +24,8 @@ const approvedElectronInput = {
allowed_file_roots: electronFileRootsSchema,
};
/** Collection bounds for passive Electron capture, applied internally. */
export const DEFAULT_ELECTRON_INSPECTION_LIMITS = {
max_frames: 200,
max_dom_nodes: 2_000,
max_scripts: 500,
max_resources: 2_000,
max_workers: 500,
max_script_source_bytes: 1_024 * 1_024,
max_total_script_source_bytes: 4 * 1_024 * 1_024,
};
/** Per-script source validation bound for passive Electron capture. */
export const MAX_ELECTRON_SCRIPT_SOURCE_BYTES = 1_024 * 1_024;
/** Input for listing root-confined file:// page targets from Electron CDP. */
export const listElectronTargetsInputSchema = z.strictObject({
@@ -49,21 +41,16 @@ const inspectElectronPageFacts = {
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(100),
} as const;
export const inspectElectronPageInputSchema = z
.union([
z.strictObject({
...inspectElectronPageFacts,
include_script_sources: z.literal(false).default(false),
}),
z.strictObject({
...inspectElectronPageFacts,
include_script_sources: z.literal(true),
}),
])
.transform((input) => ({
...input,
limits: DEFAULT_ELECTRON_INSPECTION_LIMITS,
}));
export const inspectElectronPageInputSchema = z.union([
z.strictObject({
...inspectElectronPageFacts,
include_script_sources: z.literal(false).default(false),
}),
z.strictObject({
...inspectElectronPageFacts,
include_script_sources: z.literal(true),
}),
]);
export const inspectElectronPageToolInputSchema = z.union([
z.strictObject({
discovery_evidence_id: z.string().min(1),
+3 -13
View File
@@ -72,14 +72,8 @@ const observedJavaScriptRuntimeKindSchema = javascriptRuntimeKindSchema.or(
z.literal("unknown"),
);
/** Collection bounds for passive V8 Inspector capture, applied internally. */
export const DEFAULT_JAVASCRIPT_RUNTIME_OBSERVATION_LIMITS = {
max_events: 10_000,
max_scripts: 2_000,
max_execution_contexts: 1_000,
max_location_bytes: 16_384,
max_total_metadata_bytes: 4 * 1_024 * 1_024,
};
/** Maximum accepted source location byte length in one inspector event. */
export const MAX_JAVASCRIPT_RUNTIME_LOCATION_BYTES = 16_384;
/** Input for one bounded, attach-only V8 Inspector observation. */
export const observeJavaScriptRuntimeToolInputSchema = z.strictObject({
@@ -97,11 +91,7 @@ export const observeJavaScriptRuntimeInputSchema = z
runtime_kind: javascriptRuntimeKindSchema.optional(),
observation_ms: z.number().int().min(0).max(10_000).default(100),
})
.superRefine(requireRuntimeScope)
.transform((input) => ({
...input,
limits: DEFAULT_JAVASCRIPT_RUNTIME_OBSERVATION_LIMITS,
}));
.superRefine(requireRuntimeScope);
export type ObserveJavaScriptRuntimeInput = z.infer<
typeof observeJavaScriptRuntimeInputSchema
>;