feat(browser): attribute native execution and listener sources (#917)

* feat(browser): attribute native execution and listener sources

Integrate finite native precise-coverage windows and direct DOM listener inspection through shared CLI/MCP workflows, exact session script identities, inline source evidence and owned instrumentation cleanup.

Refs #881, #774

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

* fix(browser): preserve runtime identity and settle fixture cleanup

Retain complete reported initiator objects, reject changing loader availability, propagate the selected operation through main-frame authorization and complete effect/help inventories. Close only the synthetic owned Chrome via its native endpoint, await process-group settlement and preserve primary verification errors during cleanup.

Refs #881

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

* fix(browser): settle invalid events and preserve document evidence

Accept same-document URL changes with proven stable loader identity, retain metadata without inventing ownership, terminate malformed event collection immediately, and sanitize known transport URLs without erasing sourceURL declarations.

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

* fix(browser): end detached target windows and sanitize coverage identities

Reuse the existing flat-session event matcher, retain prearming termination, and apply the source identity policy to coverage URLs. Add real MCP target-close verification and producer regressions for detachment orderings.

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

* fix(browser): retain final sample metadata and settle fatal protocol failures

Keep source inventory open through the resetting sample, propagate fatal wire failures without outstanding commands, and check listener collection failures after final document validation.

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)

Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

* fix(browser): require default execution worlds for website attribution

Preserve native context and world metadata without treating same-frame isolated or unknown contexts as website sources. Verify actual Chrome isolated function execution before excluding its coverage, and cover ambiguous world metadata with producer regressions.

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)

Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

* fix(browser): revalidate runtime source joins and selector failures

Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Ysopwnable
2026-10-07 21:45:07 +08:00
committed by GitHub
co-authored by morluto
parent ef1a0cc65a
commit b5afa5f91e
82 changed files with 5392 additions and 85 deletions
+6
View File
@@ -189,6 +189,12 @@ export const buildCapabilityInventory = (
};
const availabilityFor = (context: AvailabilityContext): Availability => {
// These built-in workflows accept a caller-selected endpoint; they do not load the optional passive provider.
if (
context.name === "observe_web_execution" ||
context.name === "inspect_web_event_listeners"
)
return { reason: "available", remediation: null };
if (context.name === "get_navigation_context")
return navigationContextAvailability(context.descriptors);
const javascriptApplication = javascriptApplicationAvailability(context);
+24
View File
@@ -0,0 +1,24 @@
import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Result } from "../domain/result.js";
import type {
ObserveWebExecutionInput,
WebExecution,
} from "../domain/webExecution.js";
import type {
InspectWebEventListenersInput,
WebEventListeners,
} from "../domain/webEventListeners.js";
/** Provider-neutral live source attribution operations with distinct instrumentation authority. */
export interface WebRuntimePort {
identity(): ProviderIdentity;
observeExecution(
input: ObserveWebExecutionInput,
options?: ExecutionOptions,
): Promise<Result<WebExecution, AnalysisError>>;
inspectEventListeners(
input: InspectWebEventListenersInput,
options?: ExecutionOptions,
): Promise<Result<WebEventListeners, AnalysisError>>;
}
@@ -0,0 +1,90 @@
import type { WebRuntimePort } from "./WebRuntimePort.js";
import { ok } from "../domain/result.js";
import type { WebExecution } from "../domain/webExecution.js";
import type { WebEventListeners } from "../domain/webEventListeners.js";
const browser = {
product: "RecordingChrome/1",
protocol_version: "1.3",
revision: "fixture",
user_agent: "fixture",
js_version: "fixture",
};
const target = {
target_id: "selected-page",
initial_url: "http://127.0.0.1:9222/app",
origin: "http://127.0.0.1:9222",
frame_id: "main-frame",
loader_id: "fixture-document",
};
const at = "2026-01-01T00:00:00.000Z";
/** Immutable application-port result; it makes no real browser or socket claim. */
export const webExecutionFixture = (
targetId = target.target_id,
duration = 5,
): WebExecution => ({
browser,
target: { ...target, target_id: targetId },
window: {
armed_at: at,
ended_at: at,
requested_ms: duration,
end_reason: "window_elapsed",
producer_started_seconds: 1,
producer_sampled_seconds: 2,
},
coverage: {
state: "captured",
reason: null,
offset_units: "utf16-code-units",
end_offset: "exclusive",
scripts: [],
excluded_scripts: 0,
},
requests: [],
excluded_requests: 0,
sources: [],
script_inventory: {
main_document_scripts: 0,
not_reported_script_ids: [],
coverage_absence: "unknown",
},
instrumentation: {
resets_execution_counters: true,
disables_optimized_execution: true,
takes_one_resetting_sample: true,
executes_selected_code: false,
cleanup: "confirmed",
page_ownership: "external",
},
limitations: ["Recording port fixture, not real browser evidence."],
});
/** Immutable listener port result for application and SDK schema boundaries. */
export const webListenersFixture = (
targetId = target.target_id,
selector = "#selected",
): WebEventListeners => ({
browser,
target: { ...target, target_id: targetId },
inspected_at: at,
selected_node: { selector, match: "found", backend_node_id: 22 },
listeners: [],
sources: [],
cleanup: "confirmed",
limitations: ["Recording port fixture, not real listener evidence."],
});
/** Provider-neutral recording seam preserves the exact parsed caller target and window. */
export const recordingWebRuntimePort = (): WebRuntimePort => ({
identity: () => ({
id: "runtime-recording",
name: "Runtime recording fixture",
version: "1",
}),
observeExecution: async (input) =>
ok(webExecutionFixture(input.target_id, input.observation_ms)),
inspectEventListeners: async (input) =>
ok(webListenersFixture(input.target_id, input.selector)),
});
+61
View File
@@ -0,0 +1,61 @@
import { expect, it } from "vitest";
import { WebRuntimeService } from "./WebRuntimeService.js";
import {
recordingWebRuntimePort,
webListenersFixture,
} from "./WebRuntimeService.fixture.js";
import { err, ok } from "../domain/result.js";
import { AnalysisTimeoutError } from "../domain/analysisErrorCore.js";
it("rejects malformed input and prior cancellation without calling a provider", async () => {
const provider = recordingWebRuntimePort();
const service = new WebRuntimeService({
identity: () => provider.identity(),
observeExecution: () => {
throw new Error("Provider must not be called");
},
inspectEventListeners: () => {
throw new Error("Provider must not be called");
},
});
const malformed = await service.observe({
cdp_endpoint: "https://remote.example",
target_id: "page",
});
if (malformed.ok)
throw new Error("Invalid endpoint must fail before execution");
expect(malformed.error._tag).toBe("AnalysisInputError");
const cancelled = await service.inspect({}, { signal: AbortSignal.abort() });
if (cancelled.ok)
throw new Error("Prior cancellation must fail before inspection");
expect(cancelled.error._tag).toBe("AnalysisCancelledError");
});
it("preserves actual provider failures and rejects changed target/selector identities", async () => {
const provider = recordingWebRuntimePort();
const args = {
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "selected-page",
selector: "#selected",
};
const captured = webListenersFixture();
const timeout = new AnalysisTimeoutError("observe_web_execution", 20_000);
const service = new WebRuntimeService({
identity: () => provider.identity(),
observeExecution: async () => err(timeout),
inspectEventListeners: async () =>
ok({
...captured,
selected_node: { ...captured.selected_node, selector: "#different" },
}),
});
const failed = await service.observe({
cdp_endpoint: args.cdp_endpoint,
target_id: args.target_id,
observation_ms: 5,
});
expect(failed).toEqual(err(timeout));
const changed = await service.inspect(args);
if (changed.ok) throw new Error("Changed selection must be rejected");
expect(changed.error._tag).toBe("AnalysisOutputError");
});
+146
View File
@@ -0,0 +1,146 @@
import { z } from "zod";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { WebRuntimePort } from "./WebRuntimePort.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonObjectSchema, jsonValueSchema } from "../domain/jsonValue.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../domain/result.js";
import {
observeWebExecutionInputSchema,
webExecutionSchema,
} from "../domain/webExecution.js";
import {
inspectWebEventListenersInputSchema,
webEventListenersSchema,
} from "../domain/webEventListeners.js";
/** Shared public workflows keep instrumentation and listener inspection independently selectable. */
export class WebRuntimeService {
constructor(readonly provider: WebRuntimePort) {}
/** Observe externally triggered execution; selection authorizes the declared instrumentation. */
async observe(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
const operation = "observe_web_execution";
const parsed = parseInput(
observeWebExecutionInputSchema,
rawInput,
operation,
options,
);
if (!parsed.ok) return parsed;
const result = await this.provider.observeExecution(parsed.value, options);
if (!result.ok) return result;
const verified = webExecutionSchema.safeParse(result.value);
if (!verified.success)
return err(new AnalysisOutputError(operation, verified.error.message));
if (
verified.data.target.target_id !== parsed.value.target_id ||
verified.data.window.requested_ms !== parsed.value.observation_ms
)
return err(
new AnalysisOutputError(
operation,
"Provider changed the selected target or requested window.",
),
);
return this.evidence(operation, parsed.value, verified.data, options);
}
/** Inspect one selected node's listener declarations without dispatching an event. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
const operation = "inspect_web_event_listeners";
const parsed = parseInput(
inspectWebEventListenersInputSchema,
rawInput,
operation,
options,
);
if (!parsed.ok) return parsed;
const result = await this.provider.inspectEventListeners(
parsed.value,
options,
);
if (!result.ok) return result;
const verified = webEventListenersSchema.safeParse(result.value);
if (!verified.success)
return err(new AnalysisOutputError(operation, verified.error.message));
if (
verified.data.target.target_id !== parsed.value.target_id ||
verified.data.selected_node.selector !== parsed.value.selector
)
return err(
new AnalysisOutputError(
operation,
"Provider changed the selected target or node selector.",
),
);
return this.evidence(operation, parsed.value, verified.data, options);
}
private evidence(
operation: string,
input:
| z.infer<typeof observeWebExecutionInputSchema>
| z.infer<typeof inspectWebEventListenersInputSchema>,
result:
| z.infer<typeof webExecutionSchema>
| z.infer<typeof webEventListenersSchema>,
options?: ExecutionOptions,
): Result<Evidence, AnalysisError> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
if (
input.allowed_origins.length > 0 &&
!input.allowed_origins.includes(result.target.origin)
)
return err(
new AnalysisOutputError(
operation,
"Provider returned a document outside the selected origin scope.",
),
);
return ok(
createEvidence(undefined, this.provider.identity(), {
predicateType: `rea.${operation.replaceAll("_", "-")}`,
operation,
parameters: jsonObjectSchema.parse(input),
result: jsonValueSchema.parse(result),
confidence: "observed",
authority: "external-service",
limitations: result.limitations,
}),
);
}
}
const parseInput = <T>(
schema: z.ZodType<T>,
rawInput: unknown,
operation: string,
options: ExecutionOptions | undefined,
): Result<T, AnalysisError> => {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
const parsed = schema.safeParse(rawInput);
return parsed.success
? ok(parsed.data)
: err(
new AnalysisInputError(
operation,
{ cause: parsed.error },
projectInputIssues(parsed.error.issues, rawInput),
),
);
};
+5 -8
View File
@@ -13,7 +13,7 @@ interface AuthorizedMainFrameOptions {
readonly sessionId: string | undefined;
readonly signal: AbortSignal | undefined;
readonly allowedOrigins: ReadonlySet<string>;
readonly delayOperation: BrowserObservationOperation;
readonly operation: BrowserObservationOperation;
}
/** Wait for the attached target's main frame to enter its approved origin. */
@@ -22,7 +22,7 @@ export const authorizedMainFrame = async ({
sessionId,
signal,
allowedOrigins,
delayOperation,
operation,
}: AuthorizedMainFrameOptions): Promise<unknown> => {
for (let attempt = 0; attempt < 80; attempt += 1) {
const result = await connection.send(
@@ -34,11 +34,8 @@ export const authorizedMainFrame = async ({
const url = mainFrameUrl(result);
if (allowedSanitizedUrl(url, allowedOrigins) !== undefined) return result;
if (isHttpUrl(url))
throw new BrowserObservationError(
"inspect_web_page",
"target_not_allowed",
);
await delayWithCancellation(25, delayOperation, signal);
throw new BrowserObservationError(operation, "target_not_allowed");
await delayWithCancellation(25, operation, signal);
}
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
throw new BrowserObservationError(operation, "target_not_allowed");
};
+41
View File
@@ -0,0 +1,41 @@
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
/** Select one page target and derive its origin scope before opening a CDP session. */
export const authorizeCdpTarget = (
discovery: CdpEndpointDiscovery,
input: {
readonly target_id: string;
readonly allowed_origins: readonly string[];
},
operation: BrowserObservationOperation,
): {
readonly target: CdpEndpointTarget;
readonly allowedOrigins: ReadonlySet<string>;
} => {
const target = discovery.targets.find(
(candidate) => candidate.id === input.target_id,
);
if (target === undefined)
throw new BrowserObservationError(operation, "target_not_found", {
detail: `Target ${input.target_id} was not found at the selected endpoint.`,
});
const origin = sanitizeBrowserUrl(target.url).origin;
if (
target.type !== "page" ||
origin === null ||
(input.allowed_origins.length > 0 &&
!input.allowed_origins.includes(origin))
)
throw new BrowserObservationError(operation, "target_not_allowed", {
detail: `Target ${input.target_id} must be an HTTP(S) page in the selected origin scope.`,
});
return {
target,
allowedOrigins: new Set(
input.allowed_origins.length > 0 ? input.allowed_origins : [origin],
),
};
};
+2 -14
View File
@@ -58,6 +58,7 @@ import {
} from "./CdpTargetSession.js";
import { capturePage, type CapturedPage } from "./CdpPageCapture.js";
import { fetchWebSourceMaps } from "./WebSourceMapFetcher.js";
import { authorizeCdpTarget } from "./CdpAuthorizedTarget.js";
import { observeCdpSession } from "./CdpObservationSession.js";
import { discoverWebMcp } from "./CdpWebMcpDiscovery.js";
import { captureCdpScreenshot } from "./CdpScreenshot.js";
@@ -417,20 +418,7 @@ const authorizeTarget = (
discovery: CdpEndpointDiscovery,
input: Pick<InspectWebPageInput, "target_id" | "allowed_origins">,
): CdpEndpointTarget => {
const target = discovery.targets.find(
(candidate) => candidate.id === input.target_id,
);
if (target === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_found");
const origin = sanitizeBrowserUrl(target.url).origin;
if (
target.type !== "page" ||
origin === null ||
(input.allowed_origins.length > 0 &&
!input.allowed_origins.includes(origin))
)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
return target;
return authorizeCdpTarget(discovery, input, "inspect_web_page").target;
};
const scopeToTargetOrigin = <T extends { allowed_origins: readonly string[] }>(
+19
View File
@@ -0,0 +1,19 @@
import { BrowserObservationError } from "../domain/browserObservationError.js";
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
/** Preserve a producer's command rejection independently from fatal transport parsing errors. */
export class CdpCommandRejection extends BrowserObservationError {
constructor(
operation: BrowserObservationOperation,
readonly command: string,
readonly code: number | null,
readonly reportedMessage: string | null,
) {
super(operation, "protocol_error", {
detail:
reportedMessage === null
? "CDP returned a malformed command error."
: `CDP ${command} failed (${code === null ? "unknown code" : String(code)}): ${reportedMessage}`,
});
}
}
+71 -10
View File
@@ -3,6 +3,7 @@ import WebSocket, { type RawData } from "ws";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import { CdpCommandRejection } from "./CdpCommandRejection.js";
import { type BrowserObservationOperation } from "../domain/browserObservationErrors.js";
import { safeParseJson } from "../domain/safeJson.js";
@@ -13,6 +14,7 @@ export interface CdpEvent {
}
interface PendingCommand {
readonly method: string;
readonly resolve: (value: unknown) => void;
readonly reject: (error: AnalysisError) => void;
readonly removeAbort: () => void;
@@ -23,17 +25,28 @@ export class CdpConnection {
readonly #pending = new Map<number, PendingCommand>();
readonly #listeners = new Set<(event: CdpEvent) => void>();
readonly #disconnectListeners = new Set<() => void>();
readonly #protocolFailureListeners = new Set<
(error: BrowserObservationError) => void
>();
#nextId = 1;
#closed = false;
#protocolFailed = false;
#transportFailure: "disconnected" | "payload_limit" = "disconnected";
private constructor(
private readonly socket: WebSocket,
private readonly operation: BrowserObservationOperation,
private readonly maxPayloadBytes: number,
) {
socket.on("message", (data) => this.#receive(data));
socket.on("close", () => this.#disconnect());
socket.on("error", () => this.#disconnect());
socket.on("error", (cause) =>
this.#disconnect(
isRecord(cause) && cause.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
? "payload_limit"
: "disconnected",
),
);
}
/** Connect to one already-validated loopback CDP WebSocket. */
@@ -41,15 +54,16 @@ export class CdpConnection {
url: string,
operation: BrowserObservationOperation,
signal?: AbortSignal,
limits?: { readonly maxPayloadBytes: number },
): Promise<CdpConnection> {
if (signal?.aborted === true) throw new AnalysisCancelledError(operation);
const socket = new WebSocket(url, {
handshakeTimeout: 0,
maxPayload: 0,
maxPayload: limits?.maxPayloadBytes ?? 0,
perMessageDeflate: false,
});
await waitForOpen(socket, operation, signal);
return new CdpConnection(socket, operation);
return new CdpConnection(socket, operation, limits?.maxPayloadBytes ?? 0);
}
/** Subscribe to validated CDP event envelopes. */
@@ -68,6 +82,18 @@ export class CdpConnection {
return () => this.#disconnectListeners.delete(listener);
}
/** Notify fatal wire parsing failure even when no command is outstanding. */
onProtocolFailure(
listener: (error: BrowserObservationError) => void,
): () => void {
if (this.#protocolFailed) {
listener(this.#transportError("protocol_error"));
return () => undefined;
}
this.#protocolFailureListeners.add(listener);
return () => this.#protocolFailureListeners.delete(listener);
}
/** Execute one command, optionally within a flat target session. */
async send(
method: string,
@@ -78,7 +104,7 @@ export class CdpConnection {
if (this.#protocolFailed)
throw new BrowserObservationError(this.operation, "protocol_error");
if (this.#closed || this.socket.readyState !== WebSocket.OPEN)
throw new BrowserObservationError(this.operation, "disconnected");
throw this.#transportError(this.#transportFailure);
if (signal?.aborted === true)
throw new AnalysisCancelledError(this.operation);
const id = this.#nextId;
@@ -93,6 +119,7 @@ export class CdpConnection {
};
signal?.addEventListener("abort", onAbort, { once: true });
this.#pending.set(id, {
method,
resolve,
reject,
removeAbort: () => signal?.removeEventListener("abort", onAbort),
@@ -139,6 +166,7 @@ export class CdpConnection {
}
#receive(data: RawData): void {
if (this.#closed || this.#protocolFailed) return;
const parsed = safeParseJson(rawText(data));
if (!parsed.ok) {
this.#failPending("protocol_error");
@@ -185,8 +213,18 @@ export class CdpConnection {
if (pending === undefined) return;
this.#complete(id, pending);
if ("error" in message) {
const reported = message.error;
pending.reject(
new BrowserObservationError(this.operation, "protocol_error"),
new CdpCommandRejection(
this.operation,
pending.method,
isRecord(reported) && typeof reported.code === "number"
? reported.code
: null,
isRecord(reported) && typeof reported.message === "string"
? reported.message
: null,
),
);
return;
}
@@ -198,22 +236,45 @@ export class CdpConnection {
this.#pending.delete(id);
}
#failPending(reason: "disconnected" | "protocol_error"): void {
if (reason === "disconnected") this.#closed = true;
#failPending(
reason: "disconnected" | "protocol_error" | "payload_limit",
): void {
const wasProtocolFailed = this.#protocolFailed;
if (reason !== "protocol_error") this.#closed = true;
else this.#protocolFailed = true;
for (const [id, pending] of this.#pending) {
this.#complete(id, pending);
pending.reject(new BrowserObservationError(this.operation, reason));
pending.reject(this.#transportError(reason));
}
if (reason === "protocol_error" && !wasProtocolFailed) {
const error = this.#transportError(reason);
for (const listener of this.#protocolFailureListeners) listener(error);
this.#protocolFailureListeners.clear();
}
}
#disconnect(): void {
#disconnect(reason: "disconnected" | "payload_limit" = "disconnected"): void {
const wasClosed = this.#closed;
this.#failPending("disconnected");
if (!wasClosed) this.#transportFailure = reason;
this.#failPending(reason);
if (wasClosed) return;
for (const listener of this.#disconnectListeners) listener();
this.#disconnectListeners.clear();
}
#transportError(
reason: "disconnected" | "protocol_error" | "payload_limit",
): BrowserObservationError {
return new BrowserObservationError(
this.operation,
reason,
reason === "payload_limit"
? {
detail: `CDP message exceeded the selected ${String(this.maxPayloadBytes)} byte protocol budget.`,
}
: undefined,
);
}
}
const rawText = (data: RawData): string =>
+3 -15
View File
@@ -19,6 +19,7 @@ import {
} from "./CdpCaptureValues.js";
import { mainFrameUrl } from "./CdpCaptureDocuments.js";
import { isMainFrameNavigation } from "./CdpCaptureEventHelpers.js";
import { cdpTargetEventMatches } from "./CdpTargetEvents.js";
interface ObservationContext {
readonly connection: CdpConnection;
@@ -51,7 +52,7 @@ export const observeCdpSession = async (
sessionId: context.sessionId,
signal: context.signal,
allowedOrigins,
delayOperation: "observe_web_session",
operation: "observe_web_session",
});
const initialUrl = mainFrameUrl(initial) ?? "";
const mainFrameId = frameId(initial);
@@ -59,8 +60,7 @@ export const observeCdpSession = async (
throw new BrowserObservationError("inspect_web_page", "protocol_error");
const capture = new TimelineCapture(allowedOrigins, mainFrameId, initialUrl);
const removeListener = context.connection.onEvent((event) => {
if (observationEventMatches(event, context.sessionId))
capture.ingest(event);
if (cdpTargetEventMatches(event, context.sessionId)) capture.ingest(event);
});
const removeDisconnectListener = context.connection.onDisconnect(() =>
capture.targetTerminated(),
@@ -336,18 +336,6 @@ class TimelineCapture {
}
}
const observationEventMatches = (
event: CdpEvent,
sessionId: string | undefined,
): boolean => {
if (event.method !== "Target.detachedFromTarget")
return event.sessionId === sessionId;
return (
sessionId !== undefined &&
cdpStringValue(recordValue(event.params)?.sessionId) === sessionId
);
};
const waitForWindow = async (
durationMs: number,
capture: TimelineCapture,
+3 -3
View File
@@ -107,7 +107,7 @@ const captureAuthorizedPage = async (
sessionId: context.sessionId,
signal: context.signal,
allowedOrigins,
delayOperation: context.operation,
operation: context.operation,
});
const attachedUrl = mainFrameUrl(frameResult) ?? "";
const frameCapture = captureFrames(
@@ -154,7 +154,7 @@ const captureAuthorizedPage = async (
sessionId: context.sessionId,
signal: context.signal,
allowedOrigins,
delayOperation: context.operation,
operation: context.operation,
});
const completedUrl = mainFrameUrl(completedFrameResult) ?? "";
if (state.events.originViolation)
@@ -212,7 +212,7 @@ const authorizeObservationWindow = async (
sessionId: context.sessionId,
signal: context.signal,
allowedOrigins,
delayOperation: context.operation,
operation: context.operation,
});
const mainFrame = captureFrames(initialFrameResult, allowedOrigins).items[0];
if (mainFrame === undefined)
+15
View File
@@ -0,0 +1,15 @@
import type { CdpEvent } from "./CdpConnection.js";
import { cdpStringValue, recordValue } from "./CdpCaptureValues.js";
/** Match ordinary session envelopes and root detachment's parameter-scoped session identity. */
export const cdpTargetEventMatches = (
event: CdpEvent,
sessionId: string | undefined,
): boolean => {
if (event.method !== "Target.detachedFromTarget")
return event.sessionId === sessionId;
return (
sessionId !== undefined &&
cdpStringValue(recordValue(event.params)?.sessionId) === sessionId
);
};
+2
View File
@@ -19,12 +19,14 @@ export const openCdpTargetSession = async (
target: CdpEndpointTarget,
operation: BrowserObservationOperation,
signal?: AbortSignal,
limits?: { readonly maxPayloadBytes: number },
): Promise<CdpTargetSession> => {
const webSocket = cdpTargetWebSocket(discovery, target, operation);
const connection = await CdpConnection.connect(
webSocket.url,
operation,
signal,
limits,
);
if (webSocket.scope === "page") return { connection, sessionId: undefined };
try {
+111
View File
@@ -0,0 +1,111 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import type {
InspectWebEventListenersInput,
WebEventListeners,
} from "../../domain/webEventListeners.js";
import type { CdpRuntimeSources } from "./CdpRuntimeSources.js";
import { runtimeListenersSchema } from "./CdpRuntimeProtocol.js";
import { queryListenerSelector } from "./CdpListenerSelector.js";
/** Inspect native DOM listener descriptors without evaluating JavaScript or invoking handlers. */
export const captureWebEventListeners = async (
input: InspectWebEventListenersInput,
sources: CdpRuntimeSources,
group: string,
): Promise<WebEventListeners> => {
const session = sources.session;
session.beginCompletion();
const unsubscribe = session.transport.connection.onEvent((event) =>
sources.ingest(event),
);
try {
for (const domain of ["Page", "Runtime", "Debugger", "DOM"])
await session.enable(domain);
await session.assertDocument();
const document = z
.object({ root: z.object({ nodeId: z.number().int().min(1) }) })
.parse(await session.command("DOM.getDocument", { depth: 0 }));
const selected = z
.object({ nodeId: z.number().int().min(0) })
.parse(
await queryListenerSelector(
session,
document.root.nodeId,
input.selector,
),
);
let backendNodeId: number | null = null;
let descriptors: z.infer<typeof runtimeListenersSchema>["listeners"] = [];
if (selected.nodeId !== 0) {
const described = z
.object({ node: z.object({ backendNodeId: z.number().int().min(1) }) })
.parse(
await session.command("DOM.describeNode", {
nodeId: selected.nodeId,
}),
);
backendNodeId = described.node.backendNodeId;
const resolved = z
.object({ object: z.object({ objectId: z.string().min(1) }) })
.parse(
await session.command("DOM.resolveNode", {
nodeId: selected.nodeId,
objectGroup: group,
}),
);
descriptors = runtimeListenersSchema.parse(
await session.command("DOMDebugger.getEventListeners", {
objectId: resolved.object.objectId,
depth: 0,
pierce: false,
}),
).listeners;
}
const retained = await sources.read(
descriptors
.map((listener) => listener.scriptId)
.filter((id) => id.length > 0),
);
await session.assertDocument();
sources.check();
return {
browser: session.discovery.version,
target: session.target,
inspected_at: new Date().toISOString(),
selected_node: {
selector: input.selector,
match: selected.nodeId === 0 ? "not_found" : "found",
backend_node_id: backendNodeId,
},
listeners: descriptors.map((listener) => ({
type: listener.type,
use_capture: listener.useCapture,
passive: listener.passive,
once: listener.once,
location: sources.location(
listener.scriptId,
sources.scripts.get(listener.scriptId)?.url ?? null,
listener.lineNumber,
listener.columnNumber,
),
execution: "unknown",
})),
sources: retained,
cleanup: "confirmed",
limitations: [
"Inspects listeners registered directly on the first native CSS match in the selected main document. Delegated ancestor listeners, descendants, closed shadow roots and framework registries are not enumerated.",
"Native CDP listener descriptors report callback locations; registration time, dispatch history and UI causality remain unknown. REA does not dispatch an event, evaluate JavaScript or invoke a handler.",
"Source identity uses this session's script ID and proven main-frame default-world metadata. Isolated or unknown worlds cannot establish website callback/source joins. A URL or sourceURL declaration never establishes identity or execution.",
"Source text is retained inline with its independently computed UTF-8 digest; the producer hash is preserved separately. Missing source ownership or collected scripts remain explicit.",
"REA releases its remote object group, disables enabled domains and detaches its transport; the externally owned page remains open.",
],
};
} finally {
unsubscribe();
}
};
/** Use an owned remote object namespace so cleanup does not release caller objects. */
export const eventListenerObjectGroup = (): string =>
`rea-listeners-${randomUUID()}`;
@@ -0,0 +1,161 @@
import { z } from "zod";
import { BrowserObservationError } from "../../domain/browserObservationError.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import type {
ObserveWebExecutionInput,
WebExecution,
} from "../../domain/webExecution.js";
import { CdpExecutionCollection } from "./CdpExecutionCollection.js";
import { preciseCoverageSchema } from "./CdpRuntimeProtocol.js";
import { normalizePreciseCoverage } from "./CdpPreciseCoverage.js";
import type { CdpRuntimeSources } from "./CdpRuntimeSources.js";
/** Capture one explicit resetting coverage sample and its request-source relationships. */
export const captureWebExecution = async (
input: ObserveWebExecutionInput,
sources: CdpRuntimeSources,
): Promise<WebExecution> => {
const session = sources.session;
const collection = new CdpExecutionCollection(sources);
const { window, requests } = collection;
try {
for (const domain of ["Page", "Runtime", "Debugger", "Network", "Profiler"])
await session.enable(domain);
await session.assertDocument();
sources.check();
session.preciseCoverageMayBeActive = true;
const started = z.object({ timestamp: z.number().min(0) }).parse(
await session.command("Profiler.startPreciseCoverage", {
callCount: true,
detailed: true,
allowTriggeredUpdates: false,
}),
);
sources.check();
window.check();
if (window.reason !== undefined)
throw new BrowserObservationError(session.operation, "target_changed", {
detail: `Selected target ${session.target.target_id} ended with ${window.reason} before execution observation could be armed.`,
});
const waiting = window.start(input.observation_ms);
// Cancellation may arrive while asynchronous progress is being delivered.
void waiting.catch(() => undefined);
await session.options.progress?.report({
phase: "browser_execution",
completed: 1,
total: 2,
message:
"Browser execution observation armed; perform the requested action now",
});
const reason = await waiting;
session.beginCompletion();
if (session.options.signal?.aborted)
throw new AnalysisCancelledError(session.operation);
sources.check();
requests.check();
let raw: unknown;
if (reason === "window_elapsed") {
await session.assertDocument();
raw = await session.command("Profiler.takePreciseCoverage");
}
collection.freezeMetadata();
await session.command("Profiler.stopPreciseCoverage");
session.preciseCoverageMayBeActive = false;
const requestItems = requests.result();
const parsed =
raw === undefined ? undefined : preciseCoverageSchema.safeParse(raw);
if (parsed !== undefined && !parsed.success)
throw new AnalysisOutputError(
session.operation,
`Malformed precise coverage: ${parsed.error.message}`,
);
const mainScripts = [...sources.scripts.keys()].filter((id) =>
sources.belongsToDocument(id),
);
const reportedIds = new Set(
parsed?.success === true
? parsed.data.result.map((script) => script.scriptId)
: [],
);
const ids = [
...mainScripts,
...requestItems
.flatMap((request) => request.callsites.map((site) => site.script_id))
.filter((id) => id.length > 0),
];
const retained = await sources.read(ids);
if (reason === "window_elapsed") await session.assertDocument();
sources.check();
const verifiedRequests = requests.result();
const verifiedMainScripts = mainScripts.filter((id) =>
sources.belongsToDocument(id),
);
const sample =
raw === undefined
? undefined
: normalizePreciseCoverage(raw, sources, retained);
await session.options.progress?.report({
phase: "browser_execution",
completed: 2,
total: 2,
message: "Browser execution observation ended",
terminal: true,
});
return {
browser: session.discovery.version,
target: session.target,
window: {
armed_at: window.armedAt ?? new Date().toISOString(),
ended_at: window.endedAt ?? new Date().toISOString(),
requested_ms: input.observation_ms,
end_reason: reason,
producer_started_seconds: started.timestamp,
producer_sampled_seconds: sample?.timestamp ?? null,
},
coverage: sample?.coverage ?? {
state: "unavailable",
reason: `The observation ended with ${reason}; no complete final precise-coverage sample was retained.`,
offset_units: "utf16-code-units",
end_offset: "exclusive",
scripts: [],
excluded_scripts: 0,
},
requests: verifiedRequests,
excluded_requests: requests.excluded,
script_inventory: {
main_document_scripts: verifiedMainScripts.length,
not_reported_script_ids: verifiedMainScripts.filter(
(id) => !reportedIds.has(id),
),
coverage_absence: "unknown",
},
sources: retained,
instrumentation: {
resets_execution_counters: true,
disables_optimized_execution: true,
takes_one_resetting_sample: sample !== undefined,
executes_selected_code: false,
cleanup: "confirmed",
page_ownership: "external",
},
limitations: [
"Website source ownership requires the selected main frame and a proven default execution world. Isolated, worker and unknown worlds are excluded from coverage/source joins; referenced producer context metadata is retained.",
"Precise coverage resets counters, retains execution records and prevents optimized execution until stopped. Timing and JIT behavior are affected.",
"Only the selected main document's proven frame/context scripts are attributed. Child frames, workers, service workers, WebAssembly and scripts without ownership metadata remain outside this operation.",
"V8 reports nested function/block ranges and counts, not a chronological trace. Counts must not be summed across overlapping ranges; zero counts concern this instrumented window only.",
"Previously parsed scripts may be absent from a precise sample. Their source inventory is retained, but missing coverage never means zero execution or an unexecuted function.",
"A detailed-coverage request does not guarantee block granularity for already compiled functions. When is_block_coverage is false, branch execution is unknown; REA preserves the function-only producer ranges.",
"The local armed/end clock and backend coverage timestamps are distinct clocks. Counters start when the backend accepts instrumentation, before the armed receipt, and end at the resetting sample after the requested window. Counts may include execution during those command intervals; requests are restricted to the locally armed window.",
"Source metadata is collected through the final resetting sample, then frozen for source joins. Known identities remain checked during asynchronous source completion; newly parsed scripts after that cutoff are outside this evidence.",
"Request callsites are producer-reported initiators associated by session script ID; they do not establish UI causality. Unresolved asynchronous parent IDs are retained without fetching their stacks.",
"Producer hashes and UTF-8 digests of retained text are distinct identities. Inline script locations use reported resource offsets; anonymous/eval/sourceURL names are declarations.",
"Metadata has an 8 MiB script budget and 8 MiB request budget; complete retained sources have a 32 MiB budget. Resource failures return no partial success. The externally owned browser's CPU and memory are not controlled by REA.",
],
};
} finally {
collection.close();
}
};
@@ -0,0 +1,64 @@
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { cdpTargetEventMatches } from "../CdpTargetEvents.js";
import { CdpExecutionWindow } from "./CdpExecutionWindow.js";
import { CdpRuntimeRequests } from "./CdpRuntimeRequests.js";
import type { CdpRuntimeSources } from "./CdpRuntimeSources.js";
/** Own source/request collection and failure subscriptions through a precise-sample cutoff. */
export class CdpExecutionCollection {
readonly window: CdpExecutionWindow;
readonly requests: CdpRuntimeRequests;
readonly #unsubscribers: readonly (() => void)[];
#metadataOpen = true;
constructor(readonly sources: CdpRuntimeSources) {
const session = sources.session;
this.window = new CdpExecutionWindow(session);
this.requests = new CdpRuntimeRequests(sources);
this.#unsubscribers = [
session.transport.connection.onEvent((event) => {
if (!cdpTargetEventMatches(event, session.transport.sessionId)) return;
try {
if (
this.#metadataOpen &&
(this.window.reason === undefined ||
this.window.reason === "window_elapsed")
)
sources.ingest(event);
else if (this.window.reason === "window_elapsed")
sources.verifyKnownIdentity(event);
if (this.window.active) this.requests.ingest(event);
sources.check();
this.requests.check();
} catch (cause: unknown) {
this.window.fail(
cause instanceof AnalysisError
? cause
: new AnalysisOutputError(session.operation, String(cause)),
);
}
this.window.ingest(event);
}),
session.transport.connection.onDisconnect(() =>
this.window.end("target_terminated"),
),
session.transport.connection.onProtocolFailure((error) =>
this.window.fail(error),
),
];
}
/** Freeze metadata after receiving the final sample so source joins use one fixed inventory. */
freezeMetadata(): void {
this.#metadataOpen = false;
this.sources.check();
}
/** Remove every owned subscription and local timer on success, cancellation or failure. */
close(): void {
this.#metadataOpen = false;
this.window.dispose();
for (const unsubscribe of this.#unsubscribers) unsubscribe();
}
}
@@ -0,0 +1,55 @@
import { expect, it, vi } from "vitest";
import { CdpExecutionWindow } from "./CdpExecutionWindow.js";
it("settles an already lost transport without arming a timer that cannot resolve", async () => {
const window = new CdpExecutionWindow({
target: { frame_id: "selected-main" },
operation: "observe_web_execution",
options: {},
});
window.end("target_terminated");
await expect(window.start(30_000)).resolves.toBe("target_terminated");
expect(window.active).toBe(false);
});
it("ends the actual armed window at its selected duration and disposes its timer", async () => {
vi.useFakeTimers();
const window = new CdpExecutionWindow({
target: { frame_id: "selected-main" },
operation: "observe_web_execution",
options: {},
});
try {
const result = window.start(10);
expect(window.active).toBe(true);
vi.advanceTimersByTime(10);
await expect(result).resolves.toBe("window_elapsed");
expect(window.active).toBe(false);
expect(vi.getTimerCount()).toBe(0);
} finally {
window.dispose();
vi.useRealTimers();
}
});
it("settles caller cancellation and removes its local timer", async () => {
vi.useFakeTimers();
const controller = new AbortController();
const window = new CdpExecutionWindow({
target: { frame_id: "selected-main" },
operation: "observe_web_execution",
options: { signal: controller.signal },
});
try {
const assertion = expect(window.start(30_000)).rejects.toMatchObject({
_tag: "AnalysisCancelledError",
});
controller.abort();
await assertion;
expect(window.active).toBe(false);
expect(vi.getTimerCount()).toBe(0);
} finally {
window.dispose();
vi.useRealTimers();
}
});
+110
View File
@@ -0,0 +1,110 @@
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { WebExecution } from "../../domain/webExecution.js";
import type { CdpEvent } from "../CdpConnection.js";
import type { CdpRuntimeSession } from "./CdpRuntimeSession.js";
type EndReason = WebExecution["window"]["end_reason"];
/** One finite document-scoped window, with an actual armed point and event-driven termination. */
export class CdpExecutionWindow {
armedAt: string | undefined;
endedAt: string | undefined;
reason: EndReason | undefined;
#timer: NodeJS.Timeout | undefined;
#resolve: ((reason: EndReason) => void) | undefined;
#reject: ((error: AnalysisError) => void) | undefined;
#failure: AnalysisError | undefined;
#removeAbort: (() => void) | undefined;
constructor(
readonly session: Pick<CdpRuntimeSession, "operation" | "options"> & {
readonly target: { readonly frame_id: string };
},
) {}
/** Collection ends on a main-document replacement, never follows source URLs into another context. */
ingest(event: CdpEvent): void {
if (
event.method === "Target.detachedFromTarget" ||
event.method === "Inspector.targetCrashed"
) {
this.end("target_terminated");
return;
}
if (!this.active) return;
if (event.method === "Runtime.executionContextsCleared")
this.end("document_changed");
if (
event.method === "Page.frameNavigated" &&
typeof event.params === "object" &&
event.params !== null &&
"frame" in event.params
) {
const frame = event.params.frame;
if (typeof frame === "object" && frame !== null && !("parentId" in frame))
this.end("document_changed");
}
if (
event.method === "Page.frameDetached" &&
typeof event.params === "object" &&
event.params !== null &&
"frameId" in event.params &&
event.params.frameId === this.session.target.frame_id
)
this.end("document_changed");
}
/** Metadata before arming is inventory; request events outside the window are excluded. */
get active(): boolean {
return (
this.armedAt !== undefined &&
this.reason === undefined &&
this.endedAt === undefined
);
}
/** The timer starts at arming, before progress delivery can delay the external action. */
start(duration: number): Promise<EndReason> {
this.armedAt = new Date().toISOString();
if (this.#failure !== undefined) return Promise.reject(this.#failure);
if (this.reason !== undefined) return Promise.resolve(this.reason);
return new Promise((resolve, reject) => {
this.#resolve = resolve;
this.#reject = reject;
this.#timer = setTimeout(() => this.end("window_elapsed"), duration);
const signal = this.session.options.signal;
const abort = (): void => {
this.endedAt = new Date().toISOString();
this.dispose();
this.#reject?.(new AnalysisCancelledError(this.session.operation));
};
this.#removeAbort = () => signal?.removeEventListener("abort", abort);
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) abort();
});
}
/** Transport loss ends the window; instrumentation cleanup still requires confirmation. */
end(reason: EndReason): void {
if (this.reason !== undefined || this.#failure !== undefined) return;
this.reason = reason;
this.endedAt = new Date().toISOString();
this.dispose();
this.#resolve?.(reason);
}
/** Invalid producer data ends instrumentation immediately with its original failure. */
fail(error: AnalysisError): void {
if (this.reason !== undefined || this.#failure !== undefined) return;
this.#failure = error;
this.endedAt = new Date().toISOString();
this.dispose();
this.#reject?.(error);
}
/** Surface a failure recorded before local arming without emitting misleading progress. */
check(): void {
if (this.#failure !== undefined) throw this.#failure;
}
/** Release local timer and abort listener on every setup/failure path. */
dispose(): void {
if (this.#timer !== undefined) clearTimeout(this.#timer);
this.#removeAbort?.();
}
}
@@ -0,0 +1,29 @@
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { CdpCommandRejection } from "../CdpCommandRejection.js";
import type { CdpRuntimeSession } from "./CdpRuntimeSession.js";
/** Classify Chromium's selector syntax rejection without changing other command/transport failures. */
export const queryListenerSelector = async (
session: CdpRuntimeSession,
nodeId: number,
selector: string,
): Promise<unknown> => {
try {
return await session.command("DOM.querySelector", { nodeId, selector });
} catch (cause: unknown) {
if (
cause instanceof CdpCommandRejection &&
cause.command === "DOM.querySelector" &&
cause.code === -32000 &&
cause.reportedMessage === "DOM Error while querying"
)
throw new AnalysisInputError(session.operation, { cause }, [
{
path: ["selector"],
reason: "invalid_format",
message: `Chromium rejected the CSS selector syntax for target ${session.target.target_id}: ${selector}. ${cause.userMessage ?? cause.message}`,
},
]);
throw cause;
}
};
@@ -0,0 +1,70 @@
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import type { WebExecution } from "../../domain/webExecution.js";
import type { WebRuntimeSource } from "../../domain/webRuntime.js";
import { preciseCoverageSchema } from "./CdpRuntimeProtocol.js";
import type { CdpRuntimeSources } from "./CdpRuntimeSources.js";
/** Validate source-range bounds against exact retained UTF-16 text without flattening nested counts. */
export const normalizePreciseCoverage = (
raw: unknown,
sources: CdpRuntimeSources,
retained: readonly WebRuntimeSource[],
): {
readonly coverage: WebExecution["coverage"];
readonly timestamp: number;
} => {
const parsed = preciseCoverageSchema.safeParse(raw);
if (!parsed.success)
throw new AnalysisOutputError(
sources.session.operation,
`Malformed precise coverage: ${parsed.error.message}`,
);
const scripts: WebExecution["coverage"]["scripts"] = [];
let excluded = 0;
for (const script of parsed.data.result) {
if (!sources.belongsToDocument(script.scriptId)) {
excluded += 1;
continue;
}
const source = retained.find(
(item) => item.script_id === script.scriptId,
)?.source;
scripts.push({
script_id: script.scriptId,
reported_url: sources.sourceUrl(script.scriptId, script.url),
functions: script.functions.map((fn) => ({
name: fn.functionName,
is_block_coverage: fn.isBlockCoverage,
ranges: fn.ranges.map((range) => {
if (
range.endOffset < range.startOffset ||
(source?.state === "captured" &&
range.endOffset > source.utf16_units)
)
throw new AnalysisOutputError(
sources.session.operation,
`Script ${script.scriptId} coverage range ${range.startOffset}:${range.endOffset} is outside retained source bounds.`,
);
return {
start_offset: range.startOffset,
end_offset: range.endOffset,
count: range.count,
source_bounds:
source?.state === "captured" ? "verified" : "unknown",
};
}),
})),
});
}
return {
timestamp: parsed.data.timestamp,
coverage: {
state: "captured",
reason: null,
offset_units: "utf16-code-units",
end_offset: "exclusive",
scripts,
excluded_scripts: excluded,
},
};
};
@@ -0,0 +1,29 @@
import type { WebExecution } from "../../domain/webExecution.js";
import { sanitizeBrowserUrl } from "../../domain/browserObservation.js";
import type { CdpRuntimeSources } from "./CdpRuntimeSources.js";
type Initiator = WebExecution["requests"][number]["reported_initiator"];
const isObject = (value: Initiator[string] | undefined): value is Initiator =>
typeof value === "object" && value !== null && !Array.isArray(value);
/** Sanitize known transport fields while retaining declarations and every unknown producer field. */
export const sanitizeRuntimeInitiator = (
initiator: Initiator,
sources: CdpRuntimeSources,
): Initiator => {
if (typeof initiator.url === "string")
initiator.url = sanitizeBrowserUrl(initiator.url).url;
let stack = initiator.stack;
while (isObject(stack)) {
if (Array.isArray(stack.callFrames))
for (const frame of stack.callFrames)
if (
isObject(frame) &&
typeof frame.url === "string" &&
typeof frame.scriptId === "string"
)
frame.url = sources.sourceUrl(frame.scriptId, frame.url);
stack = stack.parent;
}
return initiator;
};
+115
View File
@@ -0,0 +1,115 @@
import { z } from "zod";
const integer = z.number().int().min(0);
const contextAuxDataSchema = z
.object({
frameId: z.string().optional(),
isDefault: z.boolean().optional(),
type: z.string().optional(),
})
.passthrough();
/** Validated producer script metadata; optional declarations remain unknown when absent. */
export const runtimeScriptParsedSchema = z.object({
scriptId: z.string().min(1),
url: z.string(),
executionContextId: integer,
startLine: integer,
startColumn: integer,
endLine: integer,
endColumn: integer,
hash: z.string().optional(),
sourceMapURL: z.string().optional(),
hasSourceURL: z.boolean().optional(),
scriptLanguage: z.string().optional(),
executionContextAuxData: contextAuxDataSchema.optional(),
});
/** Frame ownership is taken from producer context metadata, independently of source URLs. */
export const runtimeContextSchema = z.object({
context: z
.object({
id: integer,
origin: z.string().optional(),
name: z.string().optional(),
uniqueId: z.string().optional(),
auxData: contextAuxDataSchema.optional(),
})
.passthrough(),
});
const range = z.object({
startOffset: integer,
endOffset: integer,
count: integer,
});
/** CDP precise coverage preserves every nested producer range. */
export const preciseCoverageSchema = z.object({
timestamp: z.number().min(0),
result: z.array(
z.object({
scriptId: z.string().min(1),
url: z.string(),
functions: z.array(
z.object({
functionName: z.string(),
isBlockCoverage: z.boolean(),
ranges: z.array(range),
}),
),
}),
),
});
/** The full reported synchronous and embedded asynchronous stack is retained. */
export const runtimeStackSchema = z.object({
callFrames: z.array(
z.object({
scriptId: z.string(),
url: z.string(),
lineNumber: integer,
columnNumber: integer,
functionName: z.string(),
}),
),
parent: z.unknown().optional(),
parentId: z
.object({ id: z.string(), debuggerId: z.string().optional() })
.optional(),
});
/** Request evidence contains metadata and producer initiators; bodies and headers are outside this tool. */
export const runtimeRequestSchema = z.object({
requestId: z.string().min(1),
frameId: z.string().optional(),
timestamp: z.number().min(0),
request: z.object({ url: z.string(), method: z.string() }),
initiator: z
.object({
type: z.string(),
stack: z.unknown().optional(),
url: z.string().optional(),
lineNumber: integer.optional(),
columnNumber: integer.optional(),
})
.passthrough(),
});
/** Native listener descriptors omit live remote handles from portable evidence. */
export const runtimeListenersSchema = z.object({
listeners: z.array(
z.object({
type: z.string(),
useCapture: z.boolean(),
passive: z.boolean(),
once: z.boolean(),
scriptId: z.string(),
lineNumber: integer,
columnNumber: integer,
}),
),
});
/** Current main frame identity protects same-URL reloads as well as URL changes. */
export const runtimeFrameTreeSchema = z.object({
frameTree: z.object({
frame: z.object({
id: z.string().min(1),
url: z.string(),
loaderId: z.string().optional(),
}),
}),
});
+125
View File
@@ -0,0 +1,125 @@
import type { WebExecution } from "../../domain/webExecution.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { sanitizeBrowserUrl } from "../../domain/browserObservation.js";
import { jsonObjectSchema } from "../../domain/jsonValue.js";
import { WEB_RUNTIME_LIMITS } from "../../domain/webRuntime.js";
import type { CdpEvent } from "../CdpConnection.js";
import {
runtimeRequestSchema,
runtimeStackSchema,
} from "./CdpRuntimeProtocol.js";
import type { CdpRuntimeSources } from "./CdpRuntimeSources.js";
import { sanitizeRuntimeInitiator } from "./CdpRuntimeInitiator.js";
/** Join producer initiators by script ID while preserving unresolved async parent identities. */
export class CdpRuntimeRequests {
readonly items: WebExecution["requests"] = [];
excluded = 0;
#bytes = 0;
#failure: AnalysisOutputError | undefined;
constructor(readonly sources: CdpRuntimeSources) {}
/** Retain only armed-window requests from the selected main frame and selected origins. */
ingest(event: CdpEvent): void {
if (
event.method !== "Network.requestWillBeSent" ||
this.#failure !== undefined
)
return;
try {
const request = runtimeRequestSchema.parse(event.params);
const url = sanitizeBrowserUrl(request.request.url);
if (
request.frameId !== this.sources.session.target.frame_id ||
url.origin === null ||
!this.sources.session.allowedOrigins.has(url.origin)
) {
this.excluded += 1;
return;
}
this.#bytes += Buffer.byteLength(JSON.stringify(event.params));
if (this.#bytes > WEB_RUNTIME_LIMITS.retainedEventBytes)
throw new Error(
"Request initiator evidence exceeds its complete 8 MiB event budget.",
);
const callsites: WebExecution["requests"][number]["callsites"] = [];
const parents: WebExecution["requests"][number]["async_parent_ids"] = [];
let current: unknown = request.initiator.stack;
while (current !== undefined) {
const stack = runtimeStackSchema.parse(current);
for (const frame of stack.callFrames)
callsites.push(
this.sources.location(
frame.scriptId,
frame.url,
frame.lineNumber,
frame.columnNumber,
frame.functionName,
),
);
if (stack.parentId !== undefined)
parents.push({
id: stack.parentId.id,
debugger_id: stack.parentId.debuggerId ?? null,
});
current = stack.parent;
}
if (
request.initiator.url !== undefined &&
request.initiator.lineNumber !== undefined
)
callsites.push(
this.sources.location(
"",
sanitizeBrowserUrl(request.initiator.url).url,
request.initiator.lineNumber,
request.initiator.columnNumber ?? null,
),
);
this.items.push({
request_id: request.requestId,
url: url.url,
method: request.request.method,
timestamp_seconds: request.timestamp,
initiator_type: request.initiator.type,
reported_initiator: sanitizeRuntimeInitiator(
jsonObjectSchema.parse(request.initiator),
this.sources,
),
callsites,
async_parent_ids: parents,
causal_attribution: "unknown",
});
} catch (cause: unknown) {
this.#failure = new AnalysisOutputError(
this.sources.session.operation,
cause instanceof Error ? cause.message : String(cause),
);
}
}
/** Preserve all repeated/redirect requests and bind callsites after metadata collection ends. */
result(): WebExecution["requests"] {
this.check();
return this.items.map((request) => ({
...request,
reported_initiator: sanitizeRuntimeInitiator(
jsonObjectSchema.parse(request.reported_initiator),
this.sources,
),
callsites: request.callsites.map((site) =>
this.sources.location(
site.script_id,
site.url,
site.line_number,
site.column_number,
site.function_name,
),
),
}));
}
/** Report malformed or oversized producer evidence without partial success. */
check(): void {
if (this.#failure !== undefined) throw this.#failure;
}
}
+268
View File
@@ -0,0 +1,268 @@
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisTimeoutError } from "../../domain/analysisErrorCore.js";
import { BrowserObservationError } from "../../domain/browserObservationError.js";
import type { BrowserObservationOperation } from "../../domain/browserObservationErrors.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { sanitizeBrowserUrl } from "../../domain/browserObservation.js";
import {
WEB_RUNTIME_LIMITS,
type webRuntimeTargetSchema,
} from "../../domain/webRuntime.js";
import type { z } from "zod";
import { authorizeCdpTarget } from "../CdpAuthorizedTarget.js";
import { authorizedMainFrame } from "../CdpAuthorizedMainFrame.js";
import {
discoverCdpEndpoint,
type CdpEndpointDiscovery,
} from "../CdpEndpoint.js";
import {
openCdpTargetSession,
type CdpTargetSession,
} from "../CdpTargetSession.js";
import { runtimeFrameTreeSchema } from "./CdpRuntimeProtocol.js";
type Scope = {
readonly cdp_endpoint: string;
readonly target_id: string;
readonly allowed_origins: readonly string[];
};
/** Owned transport and instrumentation; the selected browser/page remain externally owned. */
export class CdpRuntimeSession {
readonly enabledDomains: string[] = [];
preciseCoverageMayBeActive = false;
#completion: AbortController | undefined;
#completionTimer: NodeJS.Timeout | undefined;
constructor(
readonly transport: CdpTargetSession,
readonly discovery: CdpEndpointDiscovery,
readonly target: z.infer<typeof webRuntimeTargetSchema>,
readonly allowedOrigins: ReadonlySet<string>,
readonly operation: BrowserObservationOperation,
readonly options: ExecutionOptions,
) {}
/** Acquire a validated target; failed setup releases its owned socket. */
static async open(
input: Scope,
operation: BrowserObservationOperation,
options: ExecutionOptions,
): Promise<CdpRuntimeSession> {
return runtimeDeadline(operation, options.signal, async (signal) => {
const discovery = await discoverCdpEndpoint(
input.cdp_endpoint,
operation,
signal,
);
const { target, allowedOrigins } = authorizeCdpTarget(
discovery,
input,
operation,
);
const transport = await openCdpTargetSession(
discovery,
target,
operation,
signal,
{ maxPayloadBytes: WEB_RUNTIME_LIMITS.protocolBytes },
);
try {
const tree = runtimeFrameTreeSchema.parse(
await authorizedMainFrame({
...transport,
allowedOrigins,
signal,
operation,
}),
);
const frame = tree.frameTree.frame;
const url = sanitizeBrowserUrl(frame.url);
if (url.origin === null)
throw new BrowserObservationError(operation, "target_not_allowed");
return new CdpRuntimeSession(
transport,
discovery,
{
target_id: target.id,
initial_url: url.url,
origin: url.origin,
frame_id: frame.id,
loader_id: frame.loaderId ?? null,
},
allowedOrigins,
operation,
options,
);
} catch (cause: unknown) {
await transport.connection.close();
throw cause;
}
});
}
/** Bound each command separately from the caller-selected observation duration. */
async command(
method: string,
params: Readonly<Record<string, unknown>> = {},
): Promise<unknown> {
const signals = [this.options.signal, this.#completion?.signal].filter(
(signal): signal is AbortSignal => signal !== undefined,
);
try {
return await runtimeDeadline(
this.operation,
signals.length === 0 ? undefined : AbortSignal.any(signals),
(signal) =>
this.transport.connection.send(
method,
params,
this.transport.sessionId,
signal,
),
);
} catch (cause: unknown) {
if (this.#completion?.signal.aborted && !this.options.signal?.aborted)
throw new AnalysisTimeoutError(
this.operation,
WEB_RUNTIME_LIMITS.commandTimeoutMs,
);
throw cause;
}
}
/** Bound the complete inspection/source-join phase as well as each individual command. */
beginCompletion(): void {
if (this.#completion !== undefined) return;
this.#completion = new AbortController();
this.#completionTimer = setTimeout(
() => this.#completion?.abort(),
WEB_RUNTIME_LIMITS.commandTimeoutMs,
);
}
/** Register cleanup before sending: cancellation can occur after producer acceptance. */
async enable(domain: string): Promise<void> {
this.enabledDomains.push(domain);
await this.command(`${domain}.enable`);
}
/** Check document identity before joining any live node or final coverage evidence. */
async assertDocument(): Promise<void> {
const frame = runtimeFrameTreeSchema.parse(
await this.command("Page.getFrameTree"),
).frameTree.frame;
const url = sanitizeBrowserUrl(frame.url);
if (
frame.id !== this.target.frame_id ||
(frame.loaderId ?? null) !== this.target.loader_id ||
(this.target.loader_id === null && url.url !== this.target.initial_url)
)
throw new BrowserObservationError(this.operation, "target_changed", {
detail: `Selected target ${this.target.target_id} changed document during ${this.operation}.`,
});
if (url.origin === null || !this.allowedOrigins.has(url.origin))
throw new BrowserObservationError(this.operation, "target_not_allowed", {
detail: `Selected target ${this.target.target_id} moved to an unselected origin during ${this.operation}.`,
});
}
/** Cleanup uses its own deadline after caller cancellation, then closes REA's transport. */
async close(
previousError: AnalysisError | undefined,
objectGroup?: string,
): Promise<ProviderCleanupError | undefined> {
if (this.#completionTimer !== undefined)
clearTimeout(this.#completionTimer);
const controller = new AbortController();
const timer = setTimeout(
() => controller.abort(),
WEB_RUNTIME_LIMITS.cleanupTimeoutMs,
);
const failures: string[] = [];
const send = async (
method: string,
params: Readonly<Record<string, unknown>> = {},
): Promise<void> => {
try {
await this.transport.connection.send(
method,
params,
this.transport.sessionId,
controller.signal,
);
} catch (cause: unknown) {
failures.push(
`${method}: ${cause instanceof AnalysisError ? (cause.userMessage ?? cause.message) : cause instanceof Error ? cause.message : String(cause)}`,
);
}
};
try {
if (this.preciseCoverageMayBeActive)
await send("Profiler.stopPreciseCoverage");
if (objectGroup !== undefined)
await send("Runtime.releaseObjectGroup", { objectGroup });
for (const domain of [...this.enabledDomains].reverse())
await send(`${domain}.disable`);
if (this.transport.sessionId !== undefined) {
try {
await this.transport.connection.send(
"Target.detachFromTarget",
{ sessionId: this.transport.sessionId },
undefined,
controller.signal,
);
} catch (cause: unknown) {
failures.push(
`Target.detachFromTarget: ${cause instanceof AnalysisError ? (cause.userMessage ?? cause.message) : cause instanceof Error ? cause.message : String(cause)}`,
);
}
}
} finally {
clearTimeout(timer);
await this.transport.connection.close();
}
return failures.length === 0
? undefined
: new ProviderCleanupError(
"rea-cdp-browser",
[this.target.target_id, "runtime-instrumentation"],
{
target_id: this.target.target_id,
cleanup_failures: failures,
previous_error:
previousError?.userMessage ?? previousError?.message ?? null,
},
{ operation: this.operation },
);
}
}
/** Apply a disposable command deadline without turning timeout into caller cancellation. */
export const runtimeDeadline = async <T>(
operation: BrowserObservationOperation,
signal: AbortSignal | undefined,
run: (signal: AbortSignal) => Promise<T>,
): Promise<T> => {
const controller = new AbortController();
const timer = setTimeout(
() => controller.abort(),
WEB_RUNTIME_LIMITS.commandTimeoutMs,
);
try {
return await run(
signal === undefined
? controller.signal
: AbortSignal.any([signal, controller.signal]),
);
} catch (cause: unknown) {
if (controller.signal.aborted && signal?.aborted !== true)
throw new AnalysisTimeoutError(
operation,
WEB_RUNTIME_LIMITS.commandTimeoutMs,
);
throw cause;
} finally {
clearTimeout(timer);
}
};
+280
View File
@@ -0,0 +1,280 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { sanitizeBrowserUrl } from "../../domain/browserObservation.js";
import { jsonObjectSchema } from "../../domain/jsonValue.js";
import {
WEB_RUNTIME_LIMITS,
type WebRuntimeSource,
type webRuntimeLocationSchema,
} from "../../domain/webRuntime.js";
import type { CdpEvent } from "../CdpConnection.js";
import type { CdpRuntimeSession } from "./CdpRuntimeSession.js";
import {
runtimeContextSchema,
runtimeScriptParsedSchema,
} from "./CdpRuntimeProtocol.js";
const scriptIdentitySchema = runtimeScriptParsedSchema.pick({ scriptId: true });
const contextIdentitySchema = z.object({
context: runtimeContextSchema.shape.context.pick({ id: true }),
});
/** Source ownership is proven by execution context/frame metadata, independently of URL aliases. */
export class CdpRuntimeSources {
readonly scripts = new Map<
string,
z.infer<typeof runtimeScriptParsedSchema>
>();
readonly #contexts = new Map<
number,
z.infer<typeof runtimeContextSchema>["context"]
>();
readonly #changed = new Set<string>();
readonly #changedContexts = new Set<number>();
readonly #sources = new Map<string, WebRuntimeSource>();
#retainedBytes = 0;
#sourceBytes = 0;
#failure: AnalysisError | undefined;
constructor(readonly session: CdpRuntimeSession) {}
/** Subscribe before enabling Debugger; existing uncollected scripts are replayed by the producer. */
ingest(event: CdpEvent, retainNewMetadata = true): void {
if (
event.sessionId !== this.session.transport.sessionId ||
this.#failure !== undefined
)
return;
try {
if (event.method === "Runtime.executionContextCreated") {
this.#retainedBytes += Buffer.byteLength(JSON.stringify(event.params));
if (this.#retainedBytes > WEB_RUNTIME_LIMITS.retainedEventBytes)
throw new Error(
"Context/script metadata exceeds the complete 8 MiB event budget.",
);
const context = runtimeContextSchema.parse(event.params).context;
const previous = this.#contexts.get(context.id);
if (
previous !== undefined &&
JSON.stringify(previous) !== JSON.stringify(context)
) {
this.#changedContexts.add(context.id);
for (const item of this.#sources.values())
if (item.execution_context_id === context.id) this.revalidate(item);
}
if (retainNewMetadata) this.#contexts.set(context.id, context);
} else if (event.method === "Debugger.scriptParsed") {
this.#retainedBytes += Buffer.byteLength(JSON.stringify(event.params));
if (this.#retainedBytes > WEB_RUNTIME_LIMITS.retainedEventBytes)
throw new Error(
"Script metadata exceeds the complete 8 MiB event budget.",
);
const script = runtimeScriptParsedSchema.parse(event.params);
const previous = this.scripts.get(script.scriptId);
if (
previous !== undefined &&
JSON.stringify(previous) !== JSON.stringify(script)
) {
this.#changed.add(script.scriptId);
const retained = this.#sources.get(script.scriptId);
if (retained !== undefined) this.revalidate(retained);
}
if (retainNewMetadata) this.scripts.set(script.scriptId, script);
}
} catch (cause: unknown) {
this.#failure = new AnalysisOutputError(
this.session.operation,
cause instanceof Error ? cause.message : String(cause),
);
}
}
/** Producer parse/resource failures are surfaced outside the transport event callback. */
check(): void {
if (this.#failure !== undefined) throw this.#failure;
}
/** Frozen inventories still monitor known identities through asynchronous source reads. */
verifyKnownIdentity(event: CdpEvent): void {
if (event.method === "Debugger.scriptParsed") {
const id = scriptIdentitySchema.safeParse(event.params);
if (id.success && this.scripts.has(id.data.scriptId))
this.ingest(event, false);
} else if (event.method === "Runtime.executionContextCreated") {
const id = contextIdentitySchema.safeParse(event.params);
if (id.success && this.#contexts.has(id.data.context.id))
this.ingest(event, false);
}
}
/** Only proven default worlds of the selected main frame establish website source ownership. */
belongsToDocument(scriptId: string): boolean {
const script = this.scripts.get(scriptId);
if (
script === undefined ||
this.#changed.has(scriptId) ||
this.#changedContexts.has(script.executionContextId)
)
return false;
const scriptContext = script.executionContextAuxData;
const context = this.#contexts.get(script.executionContextId)?.auxData;
const worlds = [scriptContext, context];
if (
worlds.some(
(world) =>
world?.isDefault === false ||
(world?.type !== undefined && world.type !== "default"),
) ||
!worlds.some(
(world) => world?.isDefault === true || world?.type === "default",
)
)
return false;
const reported = scriptContext?.frameId;
const contextFrame = context?.frameId;
return (
(reported === undefined ||
contextFrame === undefined ||
reported === contextFrame) &&
(reported ?? contextFrame) === this.session.target.frame_id
);
}
/** Retain complete script text and compute a digest distinct from the producer hash. */
async read(scriptIds: Iterable<string>): Promise<WebRuntimeSource[]> {
this.check();
for (const scriptId of new Set(scriptIds)) {
if (this.#sources.has(scriptId)) continue;
const script = this.scripts.get(scriptId);
const owned = this.belongsToDocument(scriptId);
const context =
script === undefined
? undefined
: this.#contexts.get(script.executionContextId);
const item: WebRuntimeSource = {
script_id: scriptId,
url: this.sourceUrl(scriptId, script?.url ?? ""),
execution_context_id: script?.executionContextId ?? null,
reported_execution_context:
context === undefined ? null : jsonObjectSchema.parse(context),
reported_script_context_aux_data:
script?.executionContextAuxData === undefined
? null
: jsonObjectSchema.parse(script.executionContextAuxData),
frame_id: owned ? this.session.target.frame_id : null,
producer_hash: script?.hash ?? null,
source_map_url: script?.sourceMapURL ?? null,
has_source_url: script?.hasSourceURL ?? null,
language: script?.scriptLanguage ?? null,
resource_start:
script !== undefined
? {
line_number: script.startLine,
column_number: script.startColumn,
}
: null,
source: {
state: "excluded",
reason: this.#changed.has(scriptId)
? "The script changed identity during observation; source attribution is unknown."
: "Selected main-document default-world ownership was not established.",
},
};
if (owned && script?.scriptLanguage !== "WebAssembly")
item.source = await this.capture(scriptId);
else if (owned)
item.source = {
state: "excluded",
reason:
"WebAssembly bytecode is outside this JavaScript source operation.",
};
this.revalidate(item);
this.#sources.set(scriptId, item);
}
this.check();
return [...this.#sources.values()];
}
/** Resolve an exact producer script ID; URL equality is never an identity fallback. */
location(
scriptId: string,
url: string | null,
line: number,
column: number | null,
functionName: string | null = null,
): z.infer<typeof webRuntimeLocationSchema> {
return {
script_id: scriptId,
url: url === null ? null : this.sourceUrl(scriptId, url),
line_number: line,
column_number: column,
function_name: functionName,
source_association: this.belongsToDocument(scriptId)
? "script_id"
: "unknown",
};
}
/** Declared script names are inert evidence; known resource URLs omit transport userinfo. */
sourceUrl(scriptId: string, url: string): string {
return !this.#changed.has(scriptId) &&
this.scripts.get(scriptId)?.hasSourceURL === false
? sanitizeBrowserUrl(url).url
: url;
}
private revalidate(item: WebRuntimeSource): void {
if (item.frame_id === null || this.belongsToDocument(item.script_id))
return;
const previous =
item.source.state === "unavailable"
? ` Previous source read failure: ${item.source.reason}`
: "";
item.frame_id = null;
item.source = {
state: "excluded",
reason: `The script or context changed identity during source collection; attribution is unknown.${previous}`,
};
}
private async capture(scriptId: string): Promise<WebRuntimeSource["source"]> {
let raw: unknown;
try {
raw = await this.session.command("Debugger.getScriptSource", {
scriptId,
});
} catch (cause: unknown) {
if (
this.session.options.signal?.aborted ||
!(cause instanceof AnalysisError)
)
throw cause;
return {
state: "unavailable",
reason: cause.userMessage ?? cause.message,
};
}
const source = z.object({ scriptSource: z.string() }).safeParse(raw);
if (!source.success)
throw new AnalysisOutputError(
this.session.operation,
"Debugger.getScriptSource returned malformed source text.",
);
const text = source.data.scriptSource;
const bytes = Buffer.byteLength(text);
this.#sourceBytes += bytes;
if (this.#sourceBytes > WEB_RUNTIME_LIMITS.sourceBytes)
throw new AnalysisOutputError(
this.session.operation,
"Complete runtime source evidence exceeds its 32 MiB budget; no partial evidence is returned.",
);
return {
state: "captured",
text,
sha256: createHash("sha256").update(text).digest("hex"),
utf8_bytes: bytes,
utf16_units: text.length,
};
}
}
@@ -0,0 +1,97 @@
import { z } from "zod";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import type { WebRuntimePort } from "../../application/WebRuntimePort.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import type { BrowserObservationOperation } from "../../domain/browserObservationErrors.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
webExecutionSchema,
type ObserveWebExecutionInput,
type WebExecution,
} from "../../domain/webExecution.js";
import {
webEventListenersSchema,
type InspectWebEventListenersInput,
type WebEventListeners,
} from "../../domain/webEventListeners.js";
import { CDP_BROWSER_PROVIDER_IDENTITY } from "../providerIdentities.js";
import { CdpRuntimeSession } from "./CdpRuntimeSession.js";
import { CdpRuntimeSources } from "./CdpRuntimeSources.js";
import { captureWebExecution } from "./CdpExecutionCapture.js";
import {
captureWebEventListeners,
eventListenerObjectGroup,
} from "./CdpEventListeners.js";
/** Native CDP integration with distinct inspection/instrumentation authority and confirmed cleanup. */
export class CdpWebRuntimeProvider implements WebRuntimePort {
/** Identify this adapter independently of the captured browser version. */
identity() {
return CDP_BROWSER_PROVIDER_IDENTITY;
}
/** Observe one instrumented window while preserving the externally owned page. */
observeExecution(
input: ObserveWebExecutionInput,
options: ExecutionOptions = {},
): Promise<Result<WebExecution, AnalysisError>> {
return this.run(
input,
"observe_web_execution",
options,
webExecutionSchema,
(sources) => captureWebExecution(input, sources),
);
}
/** Inspect one selected node's registered callback locations. */
inspectEventListeners(
input: InspectWebEventListenersInput,
options: ExecutionOptions = {},
): Promise<Result<WebEventListeners, AnalysisError>> {
const group = eventListenerObjectGroup();
return this.run(
input,
"inspect_web_event_listeners",
options,
webEventListenersSchema,
(sources) => captureWebEventListeners(input, sources, group),
group,
);
}
private async run<T>(
input: ObserveWebExecutionInput | InspectWebEventListenersInput,
operation: BrowserObservationOperation,
options: ExecutionOptions,
schema: z.ZodType<T>,
capture: (sources: CdpRuntimeSources) => Promise<T>,
group?: string,
): Promise<Result<T, AnalysisError>> {
let session: CdpRuntimeSession | undefined;
let result: Result<T, AnalysisError>;
try {
session = await CdpRuntimeSession.open(input, operation, options);
result = ok(schema.parse(await capture(new CdpRuntimeSources(session))));
} catch (cause: unknown) {
result = err(
cause instanceof AnalysisError
? cause
: cause instanceof z.ZodError
? new AnalysisOutputError(operation, cause.message)
: new ProviderAdapterError(this.identity().id, operation, {
cause,
}),
);
}
if (session !== undefined) {
const failure = await session.close(
result.ok ? undefined : result.error,
group,
);
if (failure !== undefined) return err(failure);
}
return result;
}
}
+2
View File
@@ -15,6 +15,7 @@ import { registerBrowserCommands } from "./cli/browserCommands.js";
import { registerWebScriptCommands } from "./cli/webScriptCommands.js";
import { registerWebModuleCommands } from "./cli/webModuleCommands.js";
import { registerWebSourceLocationCommands } from "./cli/webSourceLocationCommands.js";
import { registerWebRuntimeCommands } from "./cli/webRuntimeCommands.js";
import { registerJavaScriptRecoveryCommands } from "./cli/javascriptRecoveryCommands.js";
import { registerAdvancedBrowserCommands } from "./cli/browserAdvancedCommands.js";
import { registerBrowserScenarioCommands } from "./cliBrowserScenarioCommands.js";
@@ -61,6 +62,7 @@ export const createCli = (
registerWebScriptCommands(cli, logger);
registerWebModuleCommands(cli, logger, environment);
registerWebSourceLocationCommands(cli, logger, environment);
registerWebRuntimeCommands(cli, logger);
registerJavaScriptRecoveryCommands(cli, logger, environment);
registerAdvancedBrowserCommands(cli, logger);
registerBrowserScenarioCommands(cli, logger);
+84
View File
@@ -0,0 +1,84 @@
import { Cli, z } from "incur";
import { createWebRuntimeService } from "../composition/webRuntime.js";
import { browserCliError } from "../cliBrowserContext.js";
import {
browserScopeOptions,
observationDuration,
} from "../cliObservationOptions.js";
import { logCliCommand } from "../cliLogging.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import type { Logger } from "../logger.js";
import type { ProgressReporter } from "../application/ProgressReporter.js";
import { withCommandCancellation } from "./commandCancellation.js";
/** CLI progress exposes the actual armed point on stderr without corrupting JSON results. */
const runtimeProgress: ProgressReporter = {
report: async (update) => {
process.stderr.write(`${JSON.stringify({ rea_progress: update })}\n`);
},
};
/** Register public equivalents of the two modular website runtime tools. */
export const registerWebRuntimeCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.observeWebExecution, {
description:
"Observe precise page execution; resets counters and temporarily disables optimization",
args: z.object({
endpoint: z.string().describe("Existing loopback browser CDP endpoint"),
targetId: z
.string()
.describe("Selected page target ID from list-browser-targets"),
}),
options: z.object({
...browserScopeOptions,
observationMs: observationDuration(10_000, 1),
}),
run: ({ args, options }) =>
logCliCommand(logger, "observe-web-execution", async () => {
const result = await withCommandCancellation((signal) =>
createWebRuntimeService().observe(
{
cdp_endpoint: args.endpoint,
target_id: args.targetId,
allowed_origins: options.allowedOrigins,
observation_ms: options.observationMs,
},
{ progress: runtimeProgress, signal },
),
);
return result.ok ? result.value : browserCliError(result.error);
}),
});
cli.command(CLI_COMMANDS.inspectWebEventListeners, {
description:
"Inspect native listener source locations on the first main-document CSS match",
args: z.object({
endpoint: z.string().describe("Existing loopback browser CDP endpoint"),
targetId: z
.string()
.describe("Selected page target ID from list-browser-targets"),
selector: z
.string()
.describe("Native CSS selector; inspect the first main-document match"),
}),
options: z.object({ ...browserScopeOptions }),
run: ({ args, options }) =>
logCliCommand(logger, "inspect-web-event-listeners", async () => {
const result = await withCommandCancellation((signal) =>
createWebRuntimeService().inspect(
{
cdp_endpoint: args.endpoint,
target_id: args.targetId,
selector: args.selector,
allowed_origins: options.allowedOrigins,
},
{ signal },
),
);
return result.ok ? result.value : browserCliError(result.error);
}),
});
};
+2
View File
@@ -1,5 +1,7 @@
/** Canonical names used by every one-shot CLI command registration. */
export const CLI_COMMANDS = Object.freeze({
observeWebExecution: "observe-web-execution",
inspectWebEventListeners: "inspect-web-event-listeners",
traceWebSourceLocation: "trace-web-source-location",
traceWebModuleImports: "trace-web-module-imports",
analyze: "analyze",
+6
View File
@@ -0,0 +1,6 @@
import { WebRuntimeService } from "../application/WebRuntimeService.js";
import { CdpWebRuntimeProvider } from "../browser/execution/CdpWebRuntimeProvider.js";
/** Construct the live attribution workflow without opening a browser connection. */
export const createWebRuntimeService = (): WebRuntimeService =>
new WebRuntimeService(new CdpWebRuntimeProvider());
+2
View File
@@ -15,6 +15,7 @@ import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "./browserScenarioToolContracts.
import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascript/javascriptRuntimeObservationToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
import { WEB_RUNTIME_TOOL_CONTRACTS } from "./webRuntimeToolContracts.js";
import { WEB_SCRIPT_TOOL_CONTRACTS } from "./webScriptToolContracts.js";
import { JAVASCRIPT_RECOVERY_TOOL_CONTRACTS } from "./javascript/javascriptRecoveryToolContracts.js";
import { TOOL_EFFECTS } from "./toolEffects.js";
@@ -78,6 +79,7 @@ describe("tool contract surface", () => {
...JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
...WEB_SCRIPT_TOOL_CONTRACTS,
...WEB_RUNTIME_TOOL_CONTRACTS,
...JAVASCRIPT_RECOVERY_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
].map(({ name }) => name);
+4
View File
@@ -16,6 +16,7 @@ import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascript/java
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
import { JAVASCRIPT_RECOVERY_TOOL_CONTRACTS } from "./javascript/javascriptRecoveryToolContracts.js";
import { WEB_SCRIPT_TOOL_CONTRACTS } from "./webScriptToolContracts.js";
import { WEB_RUNTIME_TOOL_CONTRACTS } from "./webRuntimeToolContracts.js";
const GROUPS = {
official: OFFICIAL_TOOL_CONTRACTS,
@@ -32,6 +33,7 @@ const GROUPS = {
application: APPLICATION_TOOL_CONTRACTS,
javascript_recovery: JAVASCRIPT_RECOVERY_TOOL_CONTRACTS,
web_script_export: WEB_SCRIPT_TOOL_CONTRACTS,
web_runtime: WEB_RUNTIME_TOOL_CONTRACTS,
session: SESSION_TOOL_CONTRACTS,
} as const;
@@ -85,6 +87,8 @@ const PUBLISHED_TOOL_NAME_FLOOR = [
"export_web_scripts",
"trace_web_module_imports",
"trace_web_source_location",
"observe_web_execution",
"inspect_web_event_listeners",
"find_changed_behavior",
"find_xrefs_to_name",
"get_call_graph",
+2
View File
@@ -9,6 +9,7 @@ import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascript/javascriptRuntimeObservationToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
import { WEB_SCRIPT_TOOL_CONTRACTS } from "./webScriptToolContracts.js";
import { WEB_RUNTIME_TOOL_CONTRACTS } from "./webRuntimeToolContracts.js";
import { JAVASCRIPT_RECOVERY_TOOL_CONTRACTS } from "./javascript/javascriptRecoveryToolContracts.js";
import { OFFICIAL_TOOL_CONTRACTS } from "./officialToolContracts.js";
import { ENHANCED_TOOL_CONTRACTS } from "./enhancedToolContracts.js";
@@ -31,6 +32,7 @@ export const TOOL_CONTRACTS = [
...JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
...WEB_SCRIPT_TOOL_CONTRACTS,
...WEB_RUNTIME_TOOL_CONTRACTS,
...JAVASCRIPT_RECOVERY_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
] as const;
+8
View File
@@ -41,6 +41,14 @@ const sessionEvidence = effects({ mutatesSession: true });
/** Explicit effect audit for every public tool. */
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
observe_web_execution: effects({
mutatesTarget: true,
mutatesSession: true,
accessesNetwork: true,
mayDiscardData: true,
idempotent: false,
}),
inspect_web_event_listeners: browserEvidence,
trace_web_source_location: effects({
mutatesSession: true,
writesFilesystem: true,
+53
View File
@@ -0,0 +1,53 @@
import type { ToolContract } from "./toolContracts.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemas.js";
import {
observeWebExecutionInputSchema,
webExecutionSchema,
} from "../domain/webExecution.js";
import {
inspectWebEventListenersInputSchema,
webEventListenersSchema,
} from "../domain/webEventListeners.js";
/** Native website runtime primitives distinguish instrumentation from listener inspection. */
export const WEB_RUNTIME_TOOL_CONTRACTS = [
{
name: "observe_web_execution",
...toolContractMetadata("observe_web_execution"),
description:
"Instrument one selected CDP page for a finite, externally driven precise coverage window. Resets execution counters and prevents optimized execution until stopped. Returns complete nested UTF-16 ranges/counts, independently hashed script text and request initiator associations by session script ID. Does not navigate, click, evaluate selected code or close the externally owned page. Navigation ends document-scoped collection; workers and UI causality remain outside this claim. Emits an actual armed progress notification before external actions.",
kind: "browser-provider",
inputSchema: observeWebExecutionInputSchema,
outputSchema: evidenceResultOf(webExecutionSchema),
examples: [
{
title: "Attribute externally triggered page execution",
input: {
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "TARGET_ID_FROM_LIST_BROWSER_TARGETS",
observation_ms: 10_000,
},
},
],
},
{
name: "inspect_web_event_listeners",
...toolContractMetadata("inspect_web_event_listeners"),
description:
"Inspect listeners registered directly on the first main-document CSS match in one selected CDP page. Returns event flags, native callback locations, source ownership and exact script text/digests inline. Does not dispatch events, evaluate JavaScript or invoke handlers. Delegated ancestor/framework listeners and execution history remain unknown. Releases REA's object group and transport, preserving the external page.",
kind: "browser-provider",
inputSchema: inspectWebEventListenersInputSchema,
outputSchema: evidenceResultOf(webEventListenersSchema),
examples: [
{
title: "Find a selected button's callback source",
input: {
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "TARGET_ID_FROM_LIST_BROWSER_TARGETS",
selector: "#submit",
},
},
],
},
] as const satisfies readonly ToolContract[];
+3 -1
View File
@@ -11,13 +11,15 @@ export class BrowserObservationError extends AnalysisError {
override readonly cleanupIncomplete: boolean;
override readonly cleanupResources: readonly string[];
override readonly userCategory: "cancelled" | undefined;
override readonly userMessage: string | undefined;
constructor(
readonly operation: BrowserObservationOperation,
readonly reason: BrowserObservationFailureReason,
options?: ErrorOptions,
options?: ErrorOptions & { readonly detail?: string },
) {
super(`Browser observation ${operation} failed: ${reason}`, options);
this.userMessage = options?.detail;
this.cleanupIncomplete = reason === "cleanup_failed";
this.cleanupResources =
reason === "cleanup_failed" ? ["browser_transport"] : [];
+2
View File
@@ -5,6 +5,8 @@ export type BrowserObservationOperation =
| "analyze_web_bundle"
| "trace_web_module_imports"
| "observe_web_session"
| "observe_web_execution"
| "inspect_web_event_listeners"
| "discover_webmcp_tools"
| "compare_web_captures"
| "capture_web_screenshot"
+44
View File
@@ -0,0 +1,44 @@
import { z } from "zod";
import {
webRuntimeBrowserSchema,
webRuntimeLocationSchema,
webRuntimeScopeSchema,
webRuntimeSourceSchema,
webRuntimeTargetSchema,
} from "./webRuntime.js";
/** Inspect listeners registered directly on the first main-document CSS match. */
export const inspectWebEventListenersInputSchema = webRuntimeScopeSchema.extend(
{
selector: z.string().min(1),
},
);
export type InspectWebEventListenersInput = z.infer<
typeof inspectWebEventListenersInputSchema
>;
/** A listener declaration and its source location do not establish that it ran. */
export const webEventListenersSchema = z.object({
browser: webRuntimeBrowserSchema,
target: webRuntimeTargetSchema,
inspected_at: z.iso.datetime(),
selected_node: z.object({
selector: z.string(),
match: z.enum(["found", "not_found"]),
backend_node_id: z.number().int().min(1).nullable(),
}),
listeners: z.array(
z.object({
type: z.string(),
use_capture: z.boolean(),
passive: z.boolean(),
once: z.boolean(),
location: webRuntimeLocationSchema,
execution: z.literal("unknown"),
}),
),
sources: z.array(webRuntimeSourceSchema),
cleanup: z.literal("confirmed"),
limitations: z.array(z.string()),
});
export type WebEventListeners = z.infer<typeof webEventListenersSchema>;
+93
View File
@@ -0,0 +1,93 @@
import { z } from "zod";
import { jsonObjectSchema } from "./jsonValue.js";
import {
webRuntimeBrowserSchema,
webRuntimeLocationSchema,
webRuntimeScopeSchema,
webRuntimeSourceSchema,
webRuntimeTargetSchema,
} from "./webRuntime.js";
/** Explicit instrumentation request for one finite, externally driven execution window. */
export const observeWebExecutionInputSchema = webRuntimeScopeSchema.extend({
observation_ms: z.number().int().min(1).max(2_147_483_647).default(10_000),
});
export type ObserveWebExecutionInput = z.infer<
typeof observeWebExecutionInputSchema
>;
const rangeSchema = z.object({
start_offset: z.number().int().min(0),
end_offset: z.number().int().min(0),
count: z.number().int().min(0),
source_bounds: z.enum(["verified", "unknown"]),
});
const functionSchema = z.object({
name: z.string(),
is_block_coverage: z.boolean(),
ranges: z.array(rangeSchema),
});
/** Precise V8 ranges retain their nested structure and counts without summing them. */
export const webExecutionSchema = z.object({
browser: webRuntimeBrowserSchema,
target: webRuntimeTargetSchema,
window: z.object({
armed_at: z.iso.datetime(),
ended_at: z.iso.datetime(),
requested_ms: z.number().int().min(1),
end_reason: z.enum([
"window_elapsed",
"document_changed",
"target_terminated",
]),
producer_started_seconds: z.number().min(0),
producer_sampled_seconds: z.number().min(0).nullable(),
}),
coverage: z.object({
state: z.enum(["captured", "unavailable"]),
reason: z.string().nullable(),
offset_units: z.literal("utf16-code-units"),
end_offset: z.literal("exclusive"),
scripts: z.array(
z.object({
script_id: z.string().min(1),
reported_url: z.string(),
functions: z.array(functionSchema),
}),
),
excluded_scripts: z.number().int().min(0),
}),
requests: z.array(
z.object({
request_id: z.string().min(1),
url: z.string(),
method: z.string(),
timestamp_seconds: z.number().min(0),
initiator_type: z.string(),
reported_initiator: jsonObjectSchema,
callsites: z.array(webRuntimeLocationSchema),
async_parent_ids: z.array(
z.object({ id: z.string(), debugger_id: z.string().nullable() }),
),
causal_attribution: z.literal("unknown"),
}),
),
excluded_requests: z.number().int().min(0),
script_inventory: z.object({
main_document_scripts: z.number().int().min(0),
not_reported_script_ids: z.array(z.string().min(1)),
coverage_absence: z.literal("unknown"),
}),
sources: z.array(webRuntimeSourceSchema),
instrumentation: z.object({
resets_execution_counters: z.literal(true),
disables_optimized_execution: z.literal(true),
takes_one_resetting_sample: z.boolean(),
executes_selected_code: z.literal(false),
cleanup: z.literal("confirmed"),
page_ownership: z.literal("external"),
}),
limitations: z.array(z.string()),
});
export type WebExecution = z.infer<typeof webExecutionSchema>;
+79
View File
@@ -0,0 +1,79 @@
import { z } from "zod";
import {
browserAllowedOriginsSchema,
browserEndpointSchema,
} from "./browserObservation.js";
import { browserVersionSchema } from "./browserObservationSchemas.js";
import { jsonObjectSchema } from "./jsonValue.js";
/** Scope for one externally owned page; omitted origins select its current origin. */
export const webRuntimeScopeSchema = z.strictObject({
cdp_endpoint: browserEndpointSchema,
allowed_origins: browserAllowedOriginsSchema,
target_id: z.string().min(1),
});
/** Source evidence is bound by the selected CDP session's script ID, never URL equality. */
export const webRuntimeSourceSchema = z.object({
script_id: z.string().min(1),
url: z.string(),
execution_context_id: z.number().int().nullable(),
reported_execution_context: jsonObjectSchema.nullable(),
reported_script_context_aux_data: jsonObjectSchema.nullable(),
frame_id: z.string().nullable(),
producer_hash: z.string().nullable(),
source_map_url: z.string().nullable(),
has_source_url: z.boolean().nullable(),
language: z.string().nullable(),
resource_start: z
.object({
line_number: z.number().int().min(0),
column_number: z.number().int().min(0),
})
.nullable(),
source: z.discriminatedUnion("state", [
z.object({
state: z.literal("captured"),
text: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
utf8_bytes: z.number().int().min(0),
utf16_units: z.number().int().min(0),
}),
z.object({
state: z.enum(["unavailable", "excluded"]),
reason: z.string().min(1),
}),
]),
});
export type WebRuntimeSource = z.infer<typeof webRuntimeSourceSchema>;
/** Producer callsite coordinates are zero-based resource lines and UTF-16 columns. */
export const webRuntimeLocationSchema = z.object({
script_id: z.string(),
url: z.string().nullable(),
line_number: z.number().int().min(0),
column_number: z.number().int().min(0).nullable(),
function_name: z.string().nullable(),
source_association: z.enum(["script_id", "unknown"]),
});
/** Common identity for a selected live page document. */
export const webRuntimeTargetSchema = z.object({
target_id: z.string().min(1),
origin: z.string().min(1),
initial_url: z.string(),
frame_id: z.string().min(1),
loader_id: z.string().nullable(),
});
/** Producer product identity is observed separately from the unknown host platform. */
export const webRuntimeBrowserSchema = browserVersionSchema;
/** Complete runtime evidence has explicit byte budgets rather than silent item truncation. */
export const WEB_RUNTIME_LIMITS = {
protocolBytes: 64 * 1024 * 1024,
retainedEventBytes: 8 * 1024 * 1024,
sourceBytes: 32 * 1024 * 1024,
commandTimeoutMs: 20_000,
cleanupTimeoutMs: 5_000,
} as const;
File diff suppressed because one or more lines are too long
+10
View File
@@ -22,6 +22,9 @@ import { createWebModuleTraceService } from "../composition/webModules.js";
import { createWebSourceLocationService } from "../composition/webSourceLocations.js";
import { registerWebSourceLocationTool } from "./registerWebSourceLocationTool.js";
import type { WebSourceLocationService } from "../application/WebSourceLocationService.js";
import type { WebRuntimeService } from "../application/WebRuntimeService.js";
import { createWebRuntimeService } from "../composition/webRuntime.js";
import { registerWebRuntimeTools } from "./registerWebRuntimeTools.js";
import { registerJavaScriptRecoveryTool } from "./registerJavaScriptRecoveryTool.js";
import { JavaScriptRecoveryService } from "../application/javascript/JavaScriptRecoveryService.js";
import type { JavaScriptRecoveryPort } from "../application/javascript/JavaScriptRecoveryPort.js";
@@ -58,6 +61,7 @@ export interface CreateServerOptions {
readonly javascriptRecovery?: JavaScriptRecoveryPort;
readonly webModuleTrace?: WebModuleTraceService;
readonly webSourceLocation?: WebSourceLocationService;
readonly webRuntime?: WebRuntimeService;
readonly androidAnalysis?: AndroidAnalysisPort;
readonly browserObservation?: BrowserObservationPort;
readonly browserScenarioCapture?: BrowserScenarioCapturePort;
@@ -203,6 +207,12 @@ export const createServer = (
toolLogger,
recordEvidence,
);
registerWebRuntimeTools(
server,
options.webRuntime ?? createWebRuntimeService(),
toolLogger,
recordEvidence,
);
registerJavaScriptRecoveryTool(
server,
new JavaScriptRecoveryService(
+51
View File
@@ -0,0 +1,51 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { WebRuntimeService } from "../application/WebRuntimeService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "../logger.js";
import { mcpProgressReporter } from "./mcpProgress.js";
import { logToolExecution } from "./toolLogging.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { toCallToolResult } from "./toolResult.js";
/** Bind distinct runtime operations to named contracts and the session's Evidence owner. */
export const registerWebRuntimeTools = (
server: McpServer,
service: WebRuntimeService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
): void => {
const execution = toolContract("observe_web_execution");
const listeners = toolContract("inspect_web_event_listeners");
server.registerTool(
execution.name,
toolRegistrationOptions(execution),
async (input, context) => {
const result = await logToolExecution(logger, execution.name, () =>
service.observe(input, {
signal: context.mcpReq.signal,
progress: mcpProgressReporter(context),
}),
);
if (!result.ok) return toCallToolResult(result, execution);
const recorded = recordEvidence?.(result.value);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, execution)
: toCallToolResult(result, execution);
},
);
server.registerTool(
listeners.name,
toolRegistrationOptions(listeners),
async (input, context) => {
const result = await logToolExecution(logger, listeners.name, () =>
service.inspect(input, { signal: context.mcpReq.signal }),
);
if (!result.ok) return toCallToolResult(result, listeners);
const recorded = recordEvidence?.(result.value);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, listeners)
: toCallToolResult(result, listeners);
},
);
};