Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
refactor(browser): return complete scenario observations
morlutoe80fe414b132
diff --git a/docs/browser-scenario-contract.md b/docs/browser-scenario-contract.mdindex e9eb961cd..e07c891e7 100644--- a/docs/browser-scenario-contract.md+++ b/docs/browser-scenario-contract.md@@ -2,19 +2,20 @@`capture_browser_scenario` accepts the provider-neutral`browserScenarioSchema` through both MCP and the-`capture-browser-scenario INPUT_JSON` CLI command. The request is declarative-and bounded: it admits a fixed action vocabulary, exact HTTP(S) origins,-deterministic browser settings, explicit storage and request replay, and finite-capture limits. `INPUT_JSON` may be inline JSON or a JSON file path.+`capture-browser-scenario INPUT_JSON` CLI command. The request is declarative:+it admits a fixed action vocabulary, exact HTTP(S) origins, deterministic+browser settings, explicit storage and request replay, and provider-owned+liveness deadlines. `INPUT_JSON` may be inline JSON or a JSON file path.The minimal request contains only browser launch/connect authority, `start_url`,`allowed_origins`, and at least one `actions` entry. Environment settings,empty storage, disabled request replay, the required redaction policy, and afinal sanitized URL capture are supplied by default. Add secret declarations,storage seeds, replay routes, query redaction names, and additional artifact or-event capture only when the investigation needs them. Provider-owned duration,-action, navigation, event, and artifact budgets are fixed internal limits; the-request does not accept a caller-controlled `limits` object.+event capture only when the investigation needs them. Action, secret, storage,+and replay-route counts are not capped. Duration, action, and navigation+timeouts remain fixed provider-owned liveness limits; the request does not+accept a caller-controlled `limits` object.The browser boundary is part of the contract. Launch mode requires acaller-selected absolute executable, a provider-owned temporary profile,@@ -44,9 +45,13 @@ declared action. Each step reports action status, elapsed time, sanitized URLs,event bounds, and independently typed capture states for screenshot, DOM,accessibility, URL, history, and storage. Console, page-error, network,WebSocket, frame, worker, popup, and cancelled-download events are attributed to-steps and bounded by the scenario limits. Missing and truncated sections remain-explicit and make the capture ineligible for equality claims. Attach-mode-captures also declare the unavoidable pre-attach event gap.+steps and all observed events and requested artifacts are returned inline.+There are no event, frame, worker, popup, WebSocket, DOM-node,+accessibility-node, storage-entry, screenshot-count, or cumulative+metadata-byte caps. Requested artifacts and observed events are returned+inline without application-defined size ceilings. Other missing sections+remain explicit and make the capture ineligible for equality claims.+Attach-mode captures also declare the unavoidable pre-attach event gap.Browser automation is disabled by default. The administrator ceiling isconfigured with:@@ -84,6 +89,6 @@ capture fields and are preserved in the result.Each aligned step reports changed, unchanged, or unknown. Changed and unknownaction, screenshot, DOM, accessibility, URL, history, storage, and eventartifacts carry their normalized before/after digests and capture states.-`max_changes` bounds retained artifact records while total and omitted counts-remain visible. Missing, truncated, or mismatched capture coverage remains-unknown instead of being treated as equality.+Every changed or unknown artifact record is returned inline for each aligned+step. Missing, truncated, or mismatched capture coverage remains unknown+instead of being treated as equality.diff --git a/src/browser/BrowserScenarioSessionPort.ts b/src/browser/BrowserScenarioSessionPort.tsindex bec40bb43..69307b82c 100644--- a/src/browser/BrowserScenarioSessionPort.ts+++ b/src/browser/BrowserScenarioSessionPort.ts@@ -6,7 +6,6 @@ import type {BrowserScenarioEvent,BrowserStepArtifacts,} from "../domain/browserScenarioCapture.js";-import type { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];@@ -25,13 +24,6 @@ export interface BrowserScenarioSessionPort {readonly dropped: number;readonly items: readonly BrowserScenarioEvent[];};- eventTruncationSections(): readonly (- | "events"- | "frames"- | "workers"- | "popups"- | "websockets"- )[];perform(action: BrowserScenarioAction,maximumTimeoutMs: number,@@ -39,7 +31,6 @@ export interface BrowserScenarioSessionPort {): Promise<void>;capture(requested: ReadonlySet<SnapshotKind>,- budget: BrowserScenarioCaptureBudget,maximumTimeoutMs: number,signal?: AbortSignal,): Promise<BrowserStepArtifacts>;@@ -52,7 +43,6 @@ export interface BrowserScenarioSessionFactory {scenario: BrowserScenario,options?: {readonly signal?: AbortSignal;- readonly budget?: BrowserScenarioCaptureBudget;readonly deadlineAt?: number;},): Promise<BrowserScenarioSessionPort>;diff --git a/src/browser/PlaywrightBrowserScenarioProvider.test.ts b/src/browser/PlaywrightBrowserScenarioProvider.test.tsindex 1cfd26ec9..bc2a93f36 100644--- a/src/browser/PlaywrightBrowserScenarioProvider.test.ts+++ b/src/browser/PlaywrightBrowserScenarioProvider.test.ts@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";import type { BrowserScenarioSessionPort } from "./BrowserScenarioSessionPort.js";import { PlaywrightBrowserScenarioProvider } from "./PlaywrightBrowserScenarioProvider.js";-import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";import { sanitizeBrowserUrl } from "../domain/browserObservation.js";import {browserScenarioSchema,@@ -108,13 +107,6 @@ class FakeSession implements BrowserScenarioSessionPort {closeCalls = 0;performCalls = 0;captureCalls = 0;- eventTruncations: (- | "events"- | "frames"- | "workers"- | "popups"- | "websockets"- )[] = [];onPerform: (() => void) | undefined;private step = 0;@@ -151,10 +143,6 @@ class FakeSession implements BrowserScenarioSessionPort {return { retained: 0, dropped: 0, items: [] };}- eventTruncationSections() {- return this.eventTruncations;- }-async perform(_action: BrowserScenarioAction,_timeout: number,@@ -168,7 +156,8 @@ class FakeSession implements BrowserScenarioSessionPort {capture(requested: ReadonlySet<SnapshotKind>,- _budget: BrowserScenarioCaptureBudget,+ _maximumTimeoutMs: number,+ _signal?: AbortSignal,): Promise<BrowserStepArtifacts> {this.captureCalls += 1;if (this.failCapture) return Promise.reject(new Error("capture failed"));@@ -227,39 +216,34 @@ describe("PlaywrightBrowserScenarioProvider", () => {expect(session.closeCalls).toBe(1);});- it("makes missing and truncated captures ineligible for equality", async () => {- const session = new FakeSession("launch", true);+ it("returns an initial state and every step beyond the former action ceiling", async () => {+ const session = new FakeSession("launch");const provider = new PlaywrightBrowserScenarioProvider({open: () => Promise.resolve(session),});- const result = await provider.captureScenario(- scenario({ captures: ["screenshot", "dom"] }),- );+ const result = await provider.captureScenario(scenario({ actions: 129 }));expect(result.ok).toBe(true);if (!result.ok) return;- expect(result.value.completeness).toMatchObject({- status: "truncated",- equality_eligible: false,- missing_sections: ["dom"],- truncated_sections: ["screenshot"],- });+ expect(result.value.scenario.action_count).toBe(129);+ expect(result.value.steps).toHaveLength(130);+ expect(result.value.steps.at(-1)?.step_id).toBe("wait_128");});- it("makes event limit truncation ineligible for equality", async () => {- const session = new FakeSession("launch");- session.eventTruncations = ["events", "websockets"];+ it("makes missing and truncated captures ineligible for equality", async () => {+ const session = new FakeSession("launch", true);const provider = new PlaywrightBrowserScenarioProvider({open: () => Promise.resolve(session),});const result = await provider.captureScenario(- scenario({ events: ["websockets"] }),+ scenario({ captures: ["screenshot", "dom"] }),);expect(result.ok).toBe(true);if (!result.ok) return;expect(result.value.completeness).toMatchObject({status: "truncated",equality_eligible: false,- truncated_sections: ["events", "websockets"],+ missing_sections: ["dom"],+ truncated_sections: ["screenshot"],});});@@ -349,14 +333,3 @@ describe("PlaywrightBrowserScenarioProvider", () => {expect(session.closeCalls).toBe(1);});});--describe("BrowserScenarioCaptureBudget", () => {- it("enforces cumulative screenshot and metadata limits", () => {- const budget = new BrowserScenarioCaptureBudget(1, 10);- expect(budget.claimScreenshot()).toBe(true);- expect(budget.claimScreenshot()).toBe(false);- expect(budget.claimMetadata(6)).toBe(true);- expect(budget.claimMetadata(5)).toBe(false);- expect(budget.claimMetadata(4)).toBe(true);- });-});diff --git a/src/browser/PlaywrightBrowserScenarioProvider.ts b/src/browser/PlaywrightBrowserScenarioProvider.tsindex 05a952831..ba0cd8d93 100644--- a/src/browser/PlaywrightBrowserScenarioProvider.ts+++ b/src/browser/PlaywrightBrowserScenarioProvider.ts@@ -30,7 +30,6 @@ import type {BrowserScenarioSessionFactory,BrowserScenarioSessionPort,} from "./BrowserScenarioSessionPort.js";-import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";const OPERATION = "capture_browser_scenario" as const;let defaultFactory: Promise<BrowserScenarioSessionFactory> | undefined;@@ -134,16 +133,13 @@ const createStep = (const initialStep = async (input: {readonly session: BrowserScenarioSessionPort;readonly scenario: BrowserScenario;- readonly budget: BrowserScenarioCaptureBudget;readonly elapsedMs: number;readonly maximumTimeoutMs: number;readonly signal: AbortSignal | undefined;}): Promise<BrowserScenarioStep> => {- const { session, scenario, budget, elapsedMs, maximumTimeoutMs, signal } =- input;+ const { session, scenario, elapsedMs, maximumTimeoutMs, signal } = input;const artifacts = await session.capture(requestedForStep(scenario, 0),- budget,maximumTimeoutMs,signal,);@@ -165,7 +161,6 @@ const initialStep = async (input: {const executeStep = async (input: {readonly session: BrowserScenarioSessionPort;readonly scenario: BrowserScenario;- readonly budget: BrowserScenarioCaptureBudget;readonly action: BrowserScenarioAction;readonly stepIndex: number;readonly startedAt: number;@@ -175,7 +170,6 @@ const executeStep = async (input: {const {session,scenario,- budget,action,stepIndex,startedAt,@@ -234,7 +228,7 @@ const executeStep = async (input: {? "scenario request cancelled": "scenario duration limit reached",)- : await session.capture(requested, budget, remaining, signal);+ : await session.capture(requested, remaining, signal);return createStep({stepIndex,stepId: action.step_id,@@ -260,7 +254,6 @@ const globalCompleteness = (const truncated = steps.flatMap(({ completeness }) => completeness.truncated_sections,);- truncated.push(...session.eventTruncationSections());if (session.mode === "connect") missing.push("events");return classifyBrowserScenarioCompleteness(missing, truncated);};@@ -273,13 +266,8 @@ const runScenario = async (if (options.signal?.aborted === true)throw new BrowserObservationError(OPERATION, "cancelled");const startedAt = Date.now();- const budget = new BrowserScenarioCaptureBudget(- scenario.limits.max_screenshots,- scenario.limits.max_total_metadata_bytes,- );const session = await factory.open(scenario, {...(options.signal === undefined ? {} : { signal: options.signal }),- budget,deadlineAt: startedAt + scenario.limits.max_duration_ms,});const steps: BrowserScenarioStep[] = [];@@ -289,7 +277,6 @@ const runScenario = async (await initialStep({session,scenario,- budget,elapsedMs: Date.now() - startedAt,maximumTimeoutMs:scenario.limits.max_duration_ms - (Date.now() - startedAt),@@ -301,7 +288,6 @@ const runScenario = async (const step = await executeStep({session,scenario,- budget,action,stepIndex: offset + 1,startedAt,diff --git a/src/browser/PlaywrightScenarioArtifacts.test.ts b/src/browser/PlaywrightScenarioArtifacts.test.tsnew file mode 100644index 000000000..4c5ae4e30--- /dev/null+++ b/src/browser/PlaywrightScenarioArtifacts.test.ts@@ -0,0 +1,41 @@+import { expect, it } from "vitest";+import type { BrowserContext, Page } from "playwright-core";++import { browserScenarioSchema } from "../domain/browserScenario.js";+import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";+import { capturePlaywrightStepArtifacts } from "./PlaywrightScenarioArtifacts.js";++const scenario = browserScenarioSchema.parse({+ browser: {+ mode: "launch",+ executable_path: "/opt/chromium",+ headless: true,+ user_data: "temporary-owned",+ cleanup: "close-and-delete-profile",+ },+ start_url: { url: "https://app.example.test/" },+ allowed_origins: ["https://app.example.test"],+ actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],+});+const secrets = BrowserScenarioSecrets.resolve(scenario, {});+if (secrets === undefined)+ throw new Error("Expected resolved scenario secrets");++it("returns a complete requested text artifact beyond the former inline ceiling", async () => {+ const page = {+ url: () => "https://app.example.test/",+ content: () => Promise.resolve("x".repeat(16 * 1_024 * 1_024 + 1)),+ } as unknown as Page;++ const result = await capturePlaywrightStepArtifacts({+ context: {} as BrowserContext,+ page,+ scenario,+ secrets,+ requested: new Set(["dom"]),+ });+ expect(result.dom).toMatchObject({+ state: "captured",+ value: { bytes: 16 * 1_024 * 1_024 + 1 },+ });+});diff --git a/src/browser/PlaywrightScenarioArtifacts.ts b/src/browser/PlaywrightScenarioArtifacts.tsindex f75145b87..ac28f2ae5 100644--- a/src/browser/PlaywrightScenarioArtifacts.ts+++ b/src/browser/PlaywrightScenarioArtifacts.ts@@ -11,77 +11,28 @@ import {} from "../domain/browserScenarioCapture.js";import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";-const TEXT_ARTIFACT_MAX_BYTES = 1_048_576;-const historyValueSchema = z.strictObject({length: z.number().int().min(0),- navigation_entries: z- .array(- z.strictObject({- type: z.string(),- name: z.string(),- }),- )- .max(10_000),+ navigation_entries: z.array(+ z.strictObject({+ type: z.string(),+ name: z.string(),+ }),+ ),});const storageValueSchema = z.strictObject({- local_storage: z.array(z.tuple([z.string(), z.string()])).max(10_000),- session_storage: z.array(z.tuple([z.string(), z.string()])).max(10_000),+ local_storage: z.array(z.tuple([z.string(), z.string()])),+ session_storage: z.array(z.tuple([z.string(), z.string()])),});type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];-/** Shared retained-count budget for one scenario's screenshot artifacts. */-export class BrowserScenarioCaptureBudget {- private screenshotCount = 0;- private metadataBytes = 0;-- constructor(- private readonly maximumScreenshots: number,- private readonly maximumMetadataBytes: number,- ) {}-- claimScreenshot(): boolean {- if (this.screenshotCount >= this.maximumScreenshots) return false;- this.screenshotCount += 1;- return true;- }-- claimMetadata(bytes: number): boolean {- if (this.metadataBytes + bytes > this.maximumMetadataBytes) return false;- this.metadataBytes += bytes;- return true;- }-}-const notRequested = () => ({ state: "not_requested" as const });const missing = (reason: string) => ({ state: "missing" as const, reason });-const truncated = (observed: number, retained: number, reason: string) => ({- state: "truncated" as const,- observed,- retained,- reason,-});-const textArtifact = (- text: string,- maximumBytes: number,- budget: BrowserScenarioCaptureBudget,-) => {+const textArtifact = (text: string) => {const bytes = Buffer.from(text);- if (bytes.byteLength > maximumBytes)- return truncated(- bytes.byteLength,- 0,- `artifact exceeds ${maximumBytes} bytes`,- );- if (!budget.claimMetadata(bytes.byteLength))- return truncated(- bytes.byteLength,- 0,- "scenario metadata byte limit reached",- );return {state: "captured" as const,value: {@@ -92,23 +43,7 @@ const textArtifact = (};};-const metadataArtifact = <Value>(- value: Value,- budget: BrowserScenarioCaptureBudget,-) => {- const bytes = Buffer.byteLength(JSON.stringify(value));- return budget.claimMetadata(bytes)- ? { state: "captured" as const, value }- : truncated(bytes, 0, "scenario metadata byte limit reached");-};--const captureScreenshot = async (- page: Page,- scenario: BrowserScenario,- budget: BrowserScenarioCaptureBudget,-) => {- if (!budget.claimScreenshot())- return truncated(1, 0, "scenario screenshot count limit reached");+const captureScreenshot = async (page: Page) => {try {const bytes = await page.screenshot({type: "png",@@ -116,8 +51,6 @@ const captureScreenshot = async (animations: "disabled",caret: "hide",});- if (bytes.byteLength > scenario.limits.max_screenshot_bytes)- return truncated(bytes.byteLength, 0, "screenshot byte limit reached");const sha256 = createHash("sha256").update(bytes).digest("hex");return {state: "captured" as const,@@ -136,20 +69,10 @@ const captureScreenshot = async (const captureDom = async (input: {readonly page: Page;readonly secrets: BrowserScenarioSecrets;- readonly maximumBytes: number;- readonly maximumNodes: number;- readonly budget: BrowserScenarioCaptureBudget;}) => {- const { page, secrets, maximumBytes, maximumNodes, budget } = input;+ const { page, secrets } = input;try {- const nodes = await page.locator("*").count();- if (nodes > maximumNodes)- return truncated(nodes, 0, "DOM node limit reached");- return textArtifact(- secrets.redact(await page.content()),- Math.min(maximumBytes, TEXT_ARTIFACT_MAX_BYTES),- budget,- );+ return textArtifact(secrets.redact(await page.content()));} catch {return missing("DOM capture failed");}@@ -158,21 +81,11 @@ const captureDom = async (input: {const captureAccessibility = async (input: {readonly page: Page;readonly secrets: BrowserScenarioSecrets;- readonly maximumBytes: number;- readonly maximumNodes: number;- readonly budget: BrowserScenarioCaptureBudget;}) => {- const { page, secrets, maximumBytes, maximumNodes, budget } = input;+ const { page, secrets } = input;try {const text = await page.locator("html").ariaSnapshot();- const nodes = text.split("\n").filter((line) => line.trim() !== "").length;- if (nodes > maximumNodes)- return truncated(nodes, 0, "accessibility node limit reached");- return textArtifact(- secrets.redact(text),- Math.min(maximumBytes, TEXT_ARTIFACT_MAX_BYTES),- budget,- );+ return textArtifact(secrets.redact(text));} catch {return missing("accessibility capture failed");}@@ -192,10 +105,7 @@ const navigationType = (}};-const captureHistory = async (- page: Page,- budget: BrowserScenarioCaptureBudget,-) => {+const captureHistory = async (page: Page) => {try {const raw = historyValueSchema.parse(await page.evaluate(`(() => ({@@ -208,12 +118,6 @@ const captureHistory = async ()}))()`),);- if (raw.navigation_entries.length > 256)- return truncated(- raw.navigation_entries.length,- 0,- "navigation history entry limit reached",- );const value = {length: raw.length,current_url: sanitizeBrowserUrl(page.url()),@@ -222,7 +126,7 @@ const captureHistory = async (name: sanitizeBrowserUrl(name),})),};- return metadataArtifact(value, budget);+ return value;} catch {return missing("history capture failed");}@@ -233,9 +137,8 @@ const captureStorage = async (input: {readonly page: Page;readonly scenario: BrowserScenario;readonly secrets: BrowserScenarioSecrets;- readonly budget: BrowserScenarioCaptureBudget;}) => {- const { context, page, scenario, secrets, budget } = input;+ const { context, page, scenario, secrets } = input;try {const cookies = await context.cookies(scenario.allowed_origins);const pageStorage = storageValueSchema.parse(@@ -244,12 +147,6 @@ const captureStorage = async (input: {session_storage: Object.entries(window.sessionStorage)}))()`),);- const observed =- cookies.length +- pageStorage.local_storage.length +- pageStorage.session_storage.length;- if (observed > scenario.limits.max_storage_entries)- return truncated(observed, 0, "storage entry limit reached");const value = {cookies: cookies.map((cookie) => ({name: cookie.name,@@ -269,7 +166,7 @@ const captureStorage = async (input: {...secrets.fingerprint(value),})),};- return metadataArtifact(value, budget);+ return value;} catch {return missing("storage capture failed");}@@ -293,9 +190,8 @@ export const capturePlaywrightStepArtifacts = async (input: {readonly scenario: BrowserScenario;readonly secrets: BrowserScenarioSecrets;readonly requested: ReadonlySet<SnapshotKind>;- readonly budget: BrowserScenarioCaptureBudget;}): Promise<BrowserStepArtifacts> => {- const { context, page, scenario, secrets, requested, budget } = input;+ const { context, page, scenario, secrets, requested } = input;const allowed = isAllowedPage(page, new Set(scenario.allowed_origins));const denied = () => missing("current page is outside approved origins");const state = <Value>(@@ -310,33 +206,17 @@ export const capturePlaywrightStepArtifacts = async (input: {? capture(): Promise.resolve(denied());return browserStepArtifactsSchema.parse({- screenshot: await state("screenshot", () =>- captureScreenshot(page, scenario, budget),- ),- dom: await state("dom", () =>- captureDom({- page,- secrets,- maximumBytes: scenario.limits.max_total_metadata_bytes,- maximumNodes: scenario.limits.max_dom_nodes,- budget,- }),- ),+ screenshot: await state("screenshot", () => captureScreenshot(page)),+ dom: await state("dom", () => captureDom({ page, secrets })),accessibility: await state("accessibility", () =>- captureAccessibility({- page,- secrets,- maximumBytes: scenario.limits.max_total_metadata_bytes,- maximumNodes: scenario.limits.max_accessibility_nodes,- budget,- }),+ captureAccessibility({ page, secrets }),),url: await state("url", async () =>- metadataArtifact(sanitizeBrowserUrl(page.url()), budget),+ Promise.resolve(sanitizeBrowserUrl(page.url())),),- history: await state("history", () => captureHistory(page, budget)),+ history: await state("history", () => captureHistory(page)),storage: await state("storage", () =>- captureStorage({ context, page, scenario, secrets, budget }),+ captureStorage({ context, page, scenario, secrets }),),});};diff --git a/src/browser/PlaywrightScenarioEvents.test.ts b/src/browser/PlaywrightScenarioEvents.test.tsindex ee7e3d120..56addcd0a 100644--- a/src/browser/PlaywrightScenarioEvents.test.ts+++ b/src/browser/PlaywrightScenarioEvents.test.ts@@ -3,7 +3,6 @@ import type { Page } from "playwright-core";import { browserScenarioSchema } from "../domain/browserScenario.js";import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";-import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";describe("PlaywrightScenarioEvents", () => {@@ -58,9 +57,7 @@ describe("PlaywrightScenarioEvents", () => {const events = new PlaywrightScenarioEvents({page,enabled: new Set(["page-errors"]),- limits: scenario.limits,secrets,- budget: new BrowserScenarioCaptureBudget(1, 1_000_000),allowedOrigins: scenario.allowed_origins,});const error = new Error("m".repeat(70_000));@@ -69,8 +66,52 @@ describe("PlaywrightScenarioEvents", () => {expect(() => listeners.get("pageerror")?.(error)).not.toThrow();expect(events.result().items[0]).toMatchObject({kind: "page-error",- message: "m".repeat(65_536),- stack: "s".repeat(262_144),+ message: "m".repeat(70_000),+ stack: "s".repeat(300_000),+ });+ });++ it("retains every observed event without a collection count ceiling", () => {+ const listeners = new Map<string, ((value: Error) => void)[]>();+ const page = {+ url: () => "https://app.example.test/",+ on: (name: string, listener: (value: Error) => void) => {+ const registered = listeners.get(name) ?? [];+ registered.push(listener);+ listeners.set(name, registered);+ },+ } as unknown as Page;+ const scenario = browserScenarioSchema.parse({+ browser: {+ mode: "launch",+ executable_path: "/opt/chromium",+ headless: true,+ user_data: "temporary-owned",+ cleanup: "close-and-delete-profile",+ },+ start_url: { url: "https://app.example.test/" },+ allowed_origins: ["https://app.example.test"],+ actions: [+ { step_id: "wait", action: "wait_for_timeout", duration_ms: 1 },+ ],+ capture: { events: ["page-errors"] },+ });+ const secrets = BrowserScenarioSecrets.resolve(scenario, {});+ if (secrets === undefined) throw new Error("Expected resolved secrets");+ const events = new PlaywrightScenarioEvents({+ page,+ enabled: new Set(["page-errors"]),+ secrets,+ allowedOrigins: scenario.allowed_origins,+ });+ for (let index = 0; index < 2_001; index += 1)+ listeners+ .get("pageerror")+ ?.forEach((listener) => listener(new Error(`failure-${index}`)));+ expect(events.result()).toMatchObject({ retained: 2_001, dropped: 0 });+ expect(events.result().items.at(-1)).toMatchObject({+ kind: "page-error",+ message: "failure-2000",});});});diff --git a/src/browser/PlaywrightScenarioEvents.ts b/src/browser/PlaywrightScenarioEvents.tsindex bffecbb77..796535e81 100644--- a/src/browser/PlaywrightScenarioEvents.ts+++ b/src/browser/PlaywrightScenarioEvents.ts@@ -15,8 +15,6 @@ import {type BrowserScenarioEvent,} from "../domain/browserScenarioCapture.js";import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";-import type { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";-import type { BrowserScenario } from "../domain/browserScenario.js";type EventName =| "console"@@ -34,61 +32,25 @@ type UnindexedEvent = BrowserScenarioEvent extends infer Event: never: never;-type LimitedSection = "frames" | "workers" | "popups" | "websockets";-type TruncatedSection = "events" | LimitedSection;-interface EventCaptureOptions {readonly page: Page;readonly enabled: ReadonlySet<EventName>;- readonly limits: Pick<- BrowserScenario["limits"],- | "max_events"- | "max_frames"- | "max_workers"- | "max_popups"- | "max_websockets"- >;readonly secrets: BrowserScenarioSecrets;- readonly budget: BrowserScenarioCaptureBudget;readonly allowedOrigins: readonly string[];}-/** Bounded, arrival-ordered Playwright event capture with current-step attribution. */+/** Arrival-ordered Playwright event capture with current-step attribution. */export class PlaywrightScenarioEvents {private readonly items: BrowserScenarioEvent[] = [];- private readonly truncated = new Set<TruncatedSection>();- private readonly admitted = {- frames: new WeakSet<object>(),- workers: new WeakSet<object>(),- popups: new WeakSet<object>(),- websockets: new WeakSet<object>(),- };- private readonly rejected = {- frames: new WeakSet<object>(),- workers: new WeakSet<object>(),- popups: new WeakSet<object>(),- websockets: new WeakSet<object>(),- };- private readonly counts: Record<LimitedSection, number> = {- frames: 0,- workers: 0,- popups: 0,- websockets: 0,- };- private dropped = 0;private stepIndex = 0;private sequence = 0;private readonly enabled: ReadonlySet<EventName>;- private readonly limits: EventCaptureOptions["limits"];private readonly secrets: BrowserScenarioSecrets;- private readonly budget: BrowserScenarioCaptureBudget;private readonly allowedOrigins: ReadonlySet<string>;constructor(options: EventCaptureOptions) {this.enabled = options.enabled;- this.limits = options.limits;this.secrets = options.secrets;- this.budget = options.budget;this.allowedOrigins = new Set(options.allowedOrigins);this.observePage(options.page);}@@ -112,55 +74,21 @@ export class PlaywrightScenarioEvents {} {return {retained: this.items.length,- dropped: this.dropped,+ dropped: 0,items: this.items,};}- truncationSections(): readonly TruncatedSection[] {- return [...this.truncated].sort();- }-private push(event: UnindexedEvent): void {this.sequence += 1;- if (this.items.length >= this.limits.max_events) {- this.dropped += 1;- this.truncated.add("events");- return;- }const parsed = browserScenarioEventSchema.parse({...event,sequence: this.sequence,step_index: this.stepIndex,});- if (!this.budget.claimMetadata(Buffer.byteLength(JSON.stringify(parsed)))) {- this.dropped += 1;- this.truncated.add("events");- return;- }this.items.push(parsed);}- private admit(- section: LimitedSection,- value: object,- maximum: number,- ): boolean {- if (this.admitted[section].has(value)) return true;- if (this.rejected[section].has(value)) return false;- if (this.counts[section] >= maximum) {- this.rejected[section].add(value);- this.sequence += 1;- this.dropped += 1;- this.truncated.add("events");- this.truncated.add(section);- return false;- }- this.admitted[section].add(value);- this.counts[section] += 1;- return true;- }-private observePage(page: Page): void {if (this.enabled.has("console"))page.on("console", (message) => {@@ -171,11 +99,11 @@ export class PlaywrightScenarioEvents {if (this.pageInScope(page))this.push({kind: "page-error",- message: this.secrets.redact(error.message).slice(0, 65_536),+ message: this.secrets.redact(error.message),stack:error.stack === undefined? null- : this.secrets.redact(error.stack).slice(0, 262_144),+ : this.secrets.redact(error.stack),});});if (this.enabled.has("network")) {@@ -234,30 +162,27 @@ export class PlaywrightScenarioEvents {const location = message.location();this.push({kind: "console",- level: this.secrets.redact(message.type()).slice(0, 64),- text: this.secrets.redact(message.text()).slice(0, 65_536),+ level: this.secrets.redact(message.type()),+ text: this.secrets.redact(message.text()),url: location.url === "" ? null : this.safeUrl(location.url),});}private request(kind: "request" | "request-failed", request: Request): void {const observation = {- method: this.secrets.redact(request.method()).slice(0, 32),+ method: this.secrets.redact(request.method()),url: this.safeUrl(request.url()),- resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),+ resource_type: this.secrets.redact(request.resourceType()),header_names: Object.keys(request.headers())- .map((name) => this.secrets.redact(name).slice(0, 256))- .sort()- .slice(0, 256),+ .map((name) => this.secrets.redact(name))+ .sort(),};if (kind === "request-failed") {this.push({...observation,kind,status: null,- failure: this.secrets- .redact(request.failure()?.errorText ?? "unknown")- .slice(0, 1_024),+ failure: this.secrets.redact(request.failure()?.errorText ?? "unknown"),});return;}@@ -273,20 +198,18 @@ export class PlaywrightScenarioEvents {const request = response.request();this.push({kind: "response",- method: this.secrets.redact(request.method()).slice(0, 32),+ method: this.secrets.redact(request.method()),url: this.safeUrl(response.url()),- resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),+ resource_type: this.secrets.redact(request.resourceType()),status: response.status(),header_names: Object.keys(response.headers())- .map((name) => this.secrets.redact(name).slice(0, 256))- .sort()- .slice(0, 256),+ .map((name) => this.secrets.redact(name))+ .sort(),failure: null,});}private webSocket(page: Page, socket: WebSocket): void {- if (!this.admit("websockets", socket, this.limits.max_websockets)) return;const url = this.safeUrl(socket.url());this.push({ kind: "websocket-opened", url });socket.on("framesent", ({ payload }) => {@@ -320,14 +243,14 @@ export class PlaywrightScenarioEvents {});return;}- const text = this.secrets.redact(payload).slice(0, 65_536);+ const text = this.secrets.redact(payload);this.push({kind,url,payload_type: "text",payload_bytes: bytes,payload_text: text,- truncated: text.length < payload.length,+ truncated: false,});}@@ -335,19 +258,14 @@ export class PlaywrightScenarioEvents {kind: "frame-attached" | "frame-detached" | "frame-navigated",frame: Frame,): void {- if (!this.admit("frames", frame, this.limits.max_frames)) return;this.push({kind,url: frame.url() === "" ? null : this.safeUrl(frame.url()),- name:- frame.name() === ""- ? null- : this.secrets.redact(frame.name()).slice(0, 1_024),+ name: frame.name() === "" ? null : this.secrets.redact(frame.name()),});}private worker(page: Page, worker: Worker): void {- if (!this.admit("workers", worker, this.limits.max_workers)) return;const details = {url: this.safeUrl(worker.url()),name: null,@@ -364,7 +282,6 @@ export class PlaywrightScenarioEvents {void page.close().catch(() => undefined);return;}- if (!this.admit("popups", page, this.limits.max_popups)) return;const opened = {url: page.url() === "" ? null : this.safeUrl(page.url()),name: null,@@ -385,9 +302,7 @@ export class PlaywrightScenarioEvents {private download(download: Download): void {this.push({kind: "download-cancelled",- suggested_filename: this.secrets- .redact(download.suggestedFilename())- .slice(0, 1_024),+ suggested_filename: this.secrets.redact(download.suggestedFilename()),url: this.safeUrl(download.url()),});void download.cancel().catch(() => undefined);diff --git a/src/browser/PlaywrightScenarioSession.ts b/src/browser/PlaywrightScenarioSession.tsindex ca4e50eb5..c95f17022 100644--- a/src/browser/PlaywrightScenarioSession.ts+++ b/src/browser/PlaywrightScenarioSession.ts@@ -21,10 +21,7 @@ import {type OpenedScenarioBrowser,} from "./PlaywrightScenarioBrowser.js";import { performPlaywrightScenarioAction } from "./PlaywrightScenarioActions.js";-import {- BrowserScenarioCaptureBudget,- capturePlaywrightStepArtifacts,-} from "./PlaywrightScenarioArtifacts.js";+import { capturePlaywrightStepArtifacts } from "./PlaywrightScenarioArtifacts.js";import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";@@ -275,7 +272,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {environment: Readonly<Record<string, string | undefined>>,options: {readonly signal?: AbortSignal;- readonly budget: BrowserScenarioCaptureBudget;readonly deadlineAt: number;},): Promise<PlaywrightScenarioSession> {@@ -312,9 +308,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {const events = new PlaywrightScenarioEvents({page: opened.page,enabled: new Set(scenario.capture.events),- limits: scenario.limits,secrets,- budget: options.budget,allowedOrigins: scenario.allowed_origins,});const session = new PlaywrightScenarioSession(@@ -362,10 +356,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {return this.eventCapture.result();}- eventTruncationSections() {- return this.eventCapture.truncationSections();- }-async perform(action: BrowserScenarioAction,maximumTimeoutMs: number,@@ -389,7 +379,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {requested: ReadonlySet<BrowserScenario["capture"]["after_each_step"][number]>,- budget: BrowserScenarioCaptureBudget,maximumTimeoutMs: number,signal?: AbortSignal,) {@@ -401,7 +390,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {scenario: this.scenario,secrets: this.secrets,requested,- budget,}),maximumTimeoutMs,signal,@@ -421,9 +409,9 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {}redactError(error: unknown): string {- return this.secrets- .redact(error instanceof Error ? error.message : "browser action failed")- .slice(0, 4_096);+ return this.secrets.redact(+ error instanceof Error ? error.message : "browser action failed",+ );}}@@ -441,18 +429,11 @@ export class PlaywrightScenarioSessionFactoryscenario: BrowserScenario,options: {readonly signal?: AbortSignal;- readonly budget?: BrowserScenarioCaptureBudget;readonly deadlineAt?: number;} = {},): Promise<BrowserScenarioSessionPort> {return PlaywrightScenarioSession.open(scenario, this.environment, {...(options.signal === undefined ? {} : { signal: options.signal }),- budget:- options.budget ??- new BrowserScenarioCaptureBudget(- scenario.limits.max_screenshots,- scenario.limits.max_total_metadata_bytes,- ),deadlineAt:options.deadlineAt ?? Date.now() + scenario.limits.max_duration_ms,});diff --git a/src/contracts/browserScenarioToolContracts.ts b/src/contracts/browserScenarioToolContracts.tsindex 82e103bc9..ca8cbdb28 100644--- a/src/contracts/browserScenarioToolContracts.ts+++ b/src/contracts/browserScenarioToolContracts.ts@@ -30,7 +30,7 @@ export const BROWSER_SCENARIO_TOOL_CONTRACTS = [name: "capture_browser_scenario",...toolContractMetadata("capture_browser_scenario"),description:- "Run a controlled browser scenario when passive observation cannot exercise the application. Choose launch mode with an approved executable or connect mode with an approved loopback CDP target, declare the exact start origin scope, and provide explicit actions. Environment, empty storage, disabled request replay, redaction, and a URL-only final capture have safe defaults; declare secrets, initial storage, exact request replay, or additional retained artifacts only when needed. Provider-owned duration and collection budgets are fixed. Returns step-indexed Evidence with explicit missing/truncated sections and equality eligibility.",+ "Run a controlled browser scenario when passive observation cannot exercise the application. Choose launch mode with an approved executable or connect mode with an approved loopback CDP target, declare the exact start origin scope, and provide explicit actions. Environment, empty storage, disabled request replay, redaction, and a URL-only final capture have safe defaults; declare secrets, initial storage, exact request replay, or additional retained artifacts only when needed. Provider-owned duration, action, and navigation timeouts remain fixed. There are no action, secret, storage, route, event, frame, DOM, network, or cumulative metadata count caps; every observation is returned inline. Oversized text or screenshot artifacts fail with a payload-limit error instead of being silently omitted.",kind: "browser-provider",inputSchema: browserScenarioInputSchema,outputSchema: evidenceResultOf(browserScenarioCaptureSchema),diff --git a/src/domain/browserScenario.test.ts b/src/domain/browserScenario.test.tsnew file mode 100644index 000000000..472ff7e22--- /dev/null+++ b/src/domain/browserScenario.test.ts@@ -0,0 +1,73 @@+import { expect, it } from "vitest";++import { browserScenarioSchema } from "./browserScenario.js";++it("accepts scenarios beyond former action, secret, storage, and replay-route counts", () => {+ const actions = Array.from({ length: 129 }, (_, index) => ({+ step_id: `fill_${index}`,+ action: "fill",+ locator: { kind: "css", selector: "#field" },+ value: { source: "secret", secret_id: `secret_${index}` },+ }));+ const secrets = Array.from({ length: actions.length }, (_, index) => ({+ secret_id: `secret_${index}`,+ environment_variable: `SECRET_${index}`,+ purpose: "input",+ redaction: "replace-with-secret-reference",+ }));+ const cookies = Array.from({ length: 129 }, (_, index) => ({+ name: `cookie_${index}`,+ value: { source: "literal", value: "value", classification: "public" },+ destination: { url: "https://app.example.test/" },+ http_only: false,+ secure: true,+ same_site: "Lax",+ }));+ const storageEntries = Array.from({ length: 129 }, (_, index) => ({+ name: `entry_${index}`,+ value: { source: "literal", value: "value", classification: "public" },+ }));+ const routes = Array.from({ length: 257 }, (_, index) => ({+ route_id: `route_${index}`,+ method: "GET",+ request: { url: `https://app.example.test/${index}` },+ response: { kind: "response", status: 200 },+ }));++ const result = browserScenarioSchema.parse({+ browser: {+ mode: "launch",+ executable_path: "/opt/chromium",+ headless: true,+ user_data: "temporary-owned",+ cleanup: "close-and-delete-profile",+ },+ start_url: { url: "https://app.example.test/" },+ allowed_origins: ["https://app.example.test"],+ actions,+ secrets,+ storage: {+ cookies,+ local_storage: [+ { origin: "https://app.example.test", entries: storageEntries },+ ],+ session_storage: [+ { origin: "https://app.example.test", entries: storageEntries },+ ],+ },+ request_replay: {+ mode: "exact",+ unmatched: "abort",+ routes,+ },+ });++ expect(result.actions).toHaveLength(129);+ expect(result.secrets).toHaveLength(129);+ expect(result.storage.cookies).toHaveLength(129);+ expect(result.storage.local_storage[0]?.entries).toHaveLength(129);+ expect(result.storage.session_storage[0]?.entries).toHaveLength(129);+ expect(+ result.request_replay.mode === "exact" && result.request_replay.routes,+ ).toHaveLength(257);+});diff --git a/src/domain/browserScenario.ts b/src/domain/browserScenario.tsindex 7d8a0fd52..d057559b9 100644--- a/src/domain/browserScenario.ts+++ b/src/domain/browserScenario.ts@@ -1,7 +1,6 @@import { z } from "zod";import {- BROWSER_SCENARIO_LIMITS,BROWSER_SCENARIO_CAPTURE_LIMITS,browserScenarioActionSchema,browserScenarioAllowedOriginsSchema,@@ -42,13 +41,11 @@ export const browserScenarioInputSchema = z.strictObject({actions: z.array(browserScenarioActionSchema).min(1)- .max(BROWSER_SCENARIO_LIMITS.actions)- .describe("Required bounded sequence of explicit browser actions."),+ .describe("Required sequence of explicit browser actions."),storage: browserScenarioStorageSchema,request_replay: browserScenarioRequestReplaySchema,secrets: z.array(browserScenarioSecretSchema)- .max(BROWSER_SCENARIO_LIMITS.secrets).default([]).describe("Optional references to approved environment variables. Secret values are never supplied inline; declarations are required only when an action, URL, storage value, or replay route references a secret.",diff --git a/src/domain/browserScenarioCapture.test.ts b/src/domain/browserScenarioCapture.test.tsindex 614bbe07c..034343919 100644--- a/src/domain/browserScenarioCapture.test.ts+++ b/src/domain/browserScenarioCapture.test.ts@@ -1,3 +1,5 @@+import { createHash } from "node:crypto";+import { expect, it } from "vitest";import { sanitizeBrowserUrl } from "./browserObservation.js";@@ -86,6 +88,58 @@ it("does not attach a content digest to redacted storage secrets", () => {).toBe(false);});+it("accepts complete storage, history, and text artifacts beyond former caps", () => {+ const text = "x".repeat(1_048_577);+ const fingerprint = {+ name: "entry",+ value_state: "hashed",+ value_sha256: "a".repeat(64),+ } as const;+ const parsed = browserStepArtifactsSchema.safeParse({+ screenshot: { state: "not_requested" },+ dom: {+ state: "captured",+ value: {+ sha256: createHash("sha256").update(text).digest("hex"),+ bytes: Buffer.byteLength(text),+ text,+ },+ },+ accessibility: { state: "not_requested" },+ url: { state: "not_requested" },+ history: {+ state: "captured",+ value: {+ length: 257,+ current_url: sanitizeBrowserUrl("https://example.test/"),+ navigation_entries: Array.from({ length: 257 }, () => ({+ type: "navigate",+ name: sanitizeBrowserUrl("https://example.test/"),+ })),+ },+ },+ storage: {+ state: "captured",+ value: {+ cookies: Array.from({ length: 513 }, () => ({+ name: fingerprint.name,+ domain: "example.test",+ path: "/",+ secure: true,+ http_only: false,+ same_site: "Lax",+ value_state: fingerprint.value_state,+ value_sha256: fingerprint.value_sha256,+ })),+ local_storage: Array.from({ length: 513 }, () => fingerprint),+ session_storage: Array.from({ length: 513 }, () => fingerprint),+ },+ },+ });++ expect(parsed.success).toBe(true);+});+it("derives equality eligibility from exact completeness state", () => {expect(browserScenarioCompletenessSchema.safeParse({diff --git a/src/domain/browserScenarioCapture.ts b/src/domain/browserScenarioCapture.tsindex 9bf361bca..3ae14dad0 100644--- a/src/domain/browserScenarioCapture.ts+++ b/src/domain/browserScenarioCapture.ts@@ -34,15 +34,15 @@ export const browserScenarioCaptureSchema = zscenario: z.strictObject({start_origin: z.string().min(1).max(2_048),allowed_origins: z.array(z.string().min(1).max(2_048)).min(1).max(32),- action_count: z.number().int().min(1).max(128),- secret_references: z.array(z.string().min(1).max(64)).max(64),+ action_count: z.number().int().min(1),+ secret_references: z.array(z.string().min(1).max(64)),}),duration_ms: z.number().int().min(0),- steps: z.array(browserScenarioStepSchema).min(1).max(129),+ steps: z.array(browserScenarioStepSchema).min(1),events: z.strictObject({retained: z.number().int().min(0),dropped: z.number().int().min(0),- items: z.array(browserScenarioEventSchema).max(100_000),+ items: z.array(browserScenarioEventSchema),}),completeness: browserScenarioCompletenessSchema,limitations: z.array(z.string().min(1).max(2_048)).max(64),diff --git a/src/domain/browserScenarioCaptureValues.ts b/src/domain/browserScenarioCaptureValues.tsindex 74e4227d9..5b12b5400 100644--- a/src/domain/browserScenarioCaptureValues.ts+++ b/src/domain/browserScenarioCaptureValues.ts@@ -6,17 +6,11 @@ import { sanitizedBrowserUrlSchema } from "./browserObservation.js";import { webScreenshotArtifactSchema } from "./webScreenshot.js";const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);-const boundedTextSchema = z.string().max(1_048_576);-const textArtifactSchema = z.strictObject({sha256: digestSchema,- bytes: z- .number()- .int()- .min(0)- .max(16 * 1_024 * 1_024),- text: boundedTextSchema,+ bytes: z.number().int().min(0),+ text: z.string(),}).superRefine((artifact, context) => {const bytes = Buffer.from(artifact.text);@@ -49,20 +43,18 @@ export const captureStateSchema = <Schema extends z.ZodType>(value: Schema) =>const historySchema = z.strictObject({length: z.number().int().min(0),current_url: sanitizedBrowserUrlSchema,- navigation_entries: z- .array(- z.strictObject({- type: z.enum([- "navigate",- "reload",- "back_forward",- "prerender",- "unknown",- ]),- name: sanitizedBrowserUrlSchema,- }),- )- .max(256),+ navigation_entries: z.array(+ z.strictObject({+ type: z.enum([+ "navigate",+ "reload",+ "back_forward",+ "prerender",+ "unknown",+ ]),+ name: sanitizedBrowserUrlSchema,+ }),+ ),});const hashedStorageValueShape = {@@ -83,35 +75,33 @@ export type BrowserStorageValueFingerprint = z.infer<const storageValueSchema = z.discriminatedUnion("value_state", [z.strictObject({- name: z.string().max(1_024),+ name: z.string(),...hashedStorageValueShape,}),z.strictObject({- name: z.string().max(1_024),+ name: z.string(),...redactedStorageValueShape,}),]);const cookieShape = {- name: z.string().max(1_024),- domain: z.string().max(2_048),- path: z.string().max(4_096),+ name: z.string(),+ domain: z.string(),+ path: z.string(),secure: z.boolean(),http_only: z.boolean(),same_site: z.enum(["Strict", "Lax", "None"]),};const storageSnapshotSchema = z.strictObject({- cookies: z- .array(- z.discriminatedUnion("value_state", [- z.strictObject({ ...cookieShape, ...hashedStorageValueShape }),- z.strictObject({ ...cookieShape, ...redactedStorageValueShape }),- ]),- )- .max(512),- local_storage: z.array(storageValueSchema).max(512),- session_storage: z.array(storageValueSchema).max(512),+ cookies: z.array(+ z.discriminatedUnion("value_state", [+ z.strictObject({ ...cookieShape, ...hashedStorageValueShape }),+ z.strictObject({ ...cookieShape, ...redactedStorageValueShape }),+ ]),+ ),+ local_storage: z.array(storageValueSchema),+ session_storage: z.array(storageValueSchema),});export const browserStepArtifactsSchema = z.strictObject({@@ -132,10 +122,10 @@ const eventBase = {const eventUrl = sanitizedBrowserUrlSchema.nullable();const networkEventShape = {...eventBase,- method: z.string().min(1).max(32),+ method: z.string().min(1),url: sanitizedBrowserUrlSchema,- resource_type: z.string().min(1).max(64),- header_names: z.array(z.string().max(256)).max(256),+ resource_type: z.string().min(1),+ header_names: z.array(z.string()),};const webSocketFrameShape = {...eventBase,@@ -149,15 +139,15 @@ export const browserScenarioEventSchema = z.union([z.strictObject({...eventBase,kind: z.literal("console"),- level: z.string().min(1).max(64),- text: z.string().max(65_536),+ level: z.string().min(1),+ text: z.string(),url: eventUrl,}),z.strictObject({...eventBase,kind: z.literal("page-error"),- message: z.string().max(65_536),- stack: z.string().max(262_144).nullable(),+ message: z.string(),+ stack: z.string().nullable(),}),z.strictObject({...networkEventShape,@@ -175,7 +165,7 @@ export const browserScenarioEventSchema = z.union([...networkEventShape,kind: z.literal("request-failed"),status: z.null(),- failure: z.string().min(1).max(1_024),+ failure: z.string().min(1),}),z.strictObject({...eventBase,@@ -185,7 +175,7 @@ export const browserScenarioEventSchema = z.union([z.strictObject({...webSocketFrameShape,payload_type: z.literal("text"),- payload_text: z.string().max(65_536),+ payload_text: z.string(),}),z.strictObject({...webSocketFrameShape,@@ -204,12 +194,12 @@ export const browserScenarioEventSchema = z.union(["popup-closed",]),url: eventUrl,- name: z.string().max(1_024).nullable(),+ name: z.string().nullable(),}),z.strictObject({...eventBase,kind: z.literal("download-cancelled"),- suggested_filename: z.string().max(1_024),+ suggested_filename: z.string(),url: sanitizedBrowserUrlSchema,}),]);@@ -310,7 +300,7 @@ export const browserScenarioStepSchema = z.union([z.strictObject({...browserScenarioStepShape,status: z.enum(["failed", "cancelled"]),- error: z.string().max(4_096),+ error: z.string(),}),]);export type BrowserScenarioStep = z.infer<typeof browserScenarioStepSchema>;diff --git a/src/domain/browserScenarioValues.ts b/src/domain/browserScenarioValues.tsindex c7e527628..89e503aad 100644--- a/src/domain/browserScenarioValues.ts+++ b/src/domain/browserScenarioValues.ts@@ -7,30 +7,14 @@ import {} from "./browserObservation.js";export const BROWSER_SCENARIO_LIMITS = {- actions: 128,- secrets: 64,- storageEntries: 512,- replayRoutes: 256,- durationMs: 300_000,actionTimeoutMs: 60_000,} as const;-/** Fixed internal budgets for provider-owned scenario capture. */+/** Fixed internal deadlines for provider-owned scenario capture. */export interface BrowserScenarioCaptureLimits {readonly max_duration_ms: number;readonly action_timeout_ms: number;readonly navigation_timeout_ms: number;- readonly max_events: number;- readonly max_frames: number;- readonly max_workers: number;- readonly max_popups: number;- readonly max_websockets: number;- readonly max_dom_nodes: number;- readonly max_accessibility_nodes: number;- readonly max_screenshots: number;- readonly max_screenshot_bytes: number;- readonly max_storage_entries: number;- readonly max_total_metadata_bytes: number;}export const BROWSER_SCENARIO_CAPTURE_LIMITS: BrowserScenarioCaptureLimits =@@ -38,17 +22,6 @@ export const BROWSER_SCENARIO_CAPTURE_LIMITS: BrowserScenarioCaptureLimits =max_duration_ms: 60_000,action_timeout_ms: 5_000,navigation_timeout_ms: 10_000,- max_events: 2_000,- max_frames: 100,- max_workers: 20,- max_popups: 10,- max_websockets: 100,- max_dom_nodes: 10_000,- max_accessibility_nodes: 10_000,- max_screenshots: 16,- max_screenshot_bytes: 4 * 1_024 * 1_024,- max_storage_entries: 256,- max_total_metadata_bytes: 4 * 1_024 * 1_024,});export const scenarioIdentifierSchema = z@@ -117,7 +90,7 @@ const queryEntrySchema = z.strictObject({/** URL whose values remain explicit public literals or declared secret references. */export const browserScenarioUrlSchema = z.strictObject({url: browserScenarioBaseUrlSchema,- query: z.array(queryEntrySchema).max(64).default([]),+ query: z.array(queryEntrySchema).default([]),});export type BrowserScenarioUrl = z.infer<typeof browserScenarioUrlSchema>;@@ -290,25 +263,22 @@ export const browserScenarioStorageSchema = zsame_site: z.enum(["Strict", "Lax", "None"]),}),)- .max(128).default([]),local_storage: z.array(z.strictObject({origin: browserOriginSchema,- entries: z.array(storageEntrySchema).max(128),+ entries: z.array(storageEntrySchema),}),)- .max(32).default([]),session_storage: z.array(z.strictObject({origin: browserOriginSchema,- entries: z.array(storageEntrySchema).max(128),+ entries: z.array(storageEntrySchema),}),)- .max(32).default([]),}).default({ cookies: [], local_storage: [], session_storage: [] })@@ -332,7 +302,7 @@ const replayResponseSchema = z.discriminatedUnion("kind", [z.strictObject({kind: z.literal("response"),status: z.number().int().min(100).max(599),- headers: z.array(replayHeaderSchema).max(64).default([]),+ headers: z.array(replayHeaderSchema).default([]),body: browserScenarioValueSchema.optional(),}),z.strictObject({@@ -361,10 +331,7 @@ export const browserScenarioRequestReplaySchema = zz.strictObject({mode: z.literal("exact"),unmatched: z.enum(["abort", "passthrough-approved-origins"]),- routes: z- .array(replayRouteSchema)- .min(1)- .max(BROWSER_SCENARIO_LIMITS.replayRoutes),+ routes: z.array(replayRouteSchema).min(1),}),]).default({ mode: "disabled" })@@ -386,7 +353,7 @@ const REQUIRED_REDACTED_HEADERS = ["set-cookie",] as const;-const normalizedNames = (maximum: number) =>+const normalizedNames = () =>z.array(z@@ -396,7 +363,6 @@ const normalizedNames = (maximum: number) =>.max(256).transform((value) => value.toLowerCase()),)- .max(maximum).transform((values) => [...new Set(values)].sort());export const browserScenarioRedactionSchema = z@@ -404,8 +370,8 @@ export const browserScenarioRedactionSchema = zsecret_values: z.literal("replace-with-secret-reference").default("replace-with-secret-reference"),- query_parameter_names: normalizedNames(128).default([]),- header_names: normalizedNames(128).default([...REQUIRED_REDACTED_HEADERS]),+ query_parameter_names: normalizedNames().default([]),+ header_names: normalizedNames().default([...REQUIRED_REDACTED_HEADERS]),}).superRefine(({ header_names: names }, context) => {for (const required of REQUIRED_REDACTED_HEADERS)