effect-browser 0.2.0-beta.8 → 0.2.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"PublicSession-Bs61Eal8.mjs","names":["capture","failure","failure","lifecycle","Trace.span","registryView","Trace.span","Trace.start","Trace.annotate","capture","Trace.span","Trace.start","Trace.span"],"sources":["../src/internal/Trace.ts","../src/internal/browser/NativeCalls.ts","../src/internal/browser/NativePacing.ts","../src/internal/browser/Performance.ts","../src/internal/browser/Association.ts","../src/internal/timeline/Producers.ts","../src/internal/timeline/Retirement.ts","../src/internal/timeline/SessionJournal.ts","../src/internal/timeline/Store.ts","../src/internal/browser/ConnectionCleanup.ts","../src/internal/browser/OperationPolicy.ts","../src/internal/browser/Admission.ts","../src/internal/browser/Owner.ts","../src/internal/browser/PlanExecution.ts","../src/internal/browser/StepPreparation.ts","../src/internal/browser/PlanSteps.ts","../src/internal/browser/Random.ts","../src/internal/browser/Session.ts","../src/internal/browser/PublicSession.ts"],"sourcesContent":["import {\n Cause,\n Clock,\n Context,\n Effect,\n Exit,\n Option,\n References,\n Schema,\n Stream,\n Tracer,\n} from \"effect\";\n\nimport { BrowserError } from \"../Errors.ts\";\n\n/** Causality crosses ownership boundaries as ids and sampling, never a live caller context. */\nexport const capture = Effect.gen(function* () {\n const current = yield* Effect.serviceOption(Tracer.ParentSpan);\n const enabled = yield* References.TracerEnabled;\n const level = yield* Tracer.CurrentTraceLevel;\n const minimum = yield* Tracer.MinimumTraceLevel;\n\n return yield* Effect.sync(() => {\n try {\n let parent = Option.getOrUndefined(current);\n\n while (parent !== undefined && Context.get(parent.annotations, Tracer.DisablePropagation))\n parent = parent._tag === \"Span\" ? Option.getOrUndefined(parent.parent) : undefined;\n\n return {\n enabled,\n level,\n minimum,\n parent:\n parent === undefined\n ? undefined\n : Object.freeze(\n Tracer.externalSpan({\n traceId: parent.traceId,\n spanId: parent.spanId,\n sampled: parent.sampled,\n }),\n ),\n };\n } catch {\n // A broken tracer identity cannot turn causal capture into an operation defect.\n return { enabled: false, level, minimum, parent: undefined };\n }\n });\n});\n\nexport type Identity = Effect.Success<typeof capture>;\n\n/** A native page callback has no observable Tool caller. It starts a linked, sampling-aware root. */\nexport const autonomous = (identity: Identity): Tracer.SpanOptionsNoTrace => ({\n root: true,\n links: identity.parent === undefined ? [] : [{ span: identity.parent, attributes: {} }],\n ...(identity.parent?.sampled === false ? { sampled: false } : {}),\n});\n\nexport interface Started {\n readonly span: Tracer.Span;\n readonly end: (exit: Exit.Exit<unknown, unknown>, attributes?: Record<string, unknown>) => void;\n}\n\n/** Only finite, library-owned facts are passed here; exporter pressure loses telemetry only. */\nexport const annotate = (attributes: Record<string, unknown>) =>\n Effect.gen(function* () {\n if (!(yield* References.TracerEnabled)) return;\n const current = yield* Effect.serviceOption(Tracer.ParentSpan);\n\n if (Option.isNone(current) || current.value._tag !== \"Span\") return;\n const span = current.value;\n\n yield* Effect.sync(() => {\n try {\n for (const [key, value] of Object.entries(attributes)) span.attribute(key, value);\n } catch {\n // Result construction and cleanup must not depend on exporter health.\n }\n });\n });\n\n/**\n * Library spans export neither successful values nor original causes/stacks. Tracer failures\n * cannot suppress dispatch or alter its result. Sampling metadata is available in annotations\n * at creation: rc.117 applies SpanOptions.attributes only after Tracer.span has returned.\n */\nexport const start = Effect.fnUntraced(function* (\n name: string,\n options: Tracer.SpanOptionsNoTrace = {},\n): Effect.fn.Return<Started | undefined> {\n const identity = yield* capture;\n\n if (!identity.enabled) return undefined;\n const clock = yield* Clock.Clock;\n const timing = yield* References.TracerTimingEnabled;\n const attributes = options.attributes ?? {};\n\n const parent = options.parent ?? (options.root === true ? undefined : identity.parent);\n\n const created = yield* Effect.makeSpan(name, {\n ...options,\n attributes: undefined,\n parent,\n root: options.root ?? parent === undefined,\n annotations: Context.make(References.TracerSpanAnnotations, attributes),\n }).pipe(\n Effect.provideService(References.TracerSpanAnnotations, {}),\n Effect.provideService(References.TracerSpanLinks, []),\n Effect.exit,\n );\n\n if (Exit.isFailure(created)) return undefined;\n\n return yield* Effect.sync((): Started => {\n const span = created.value;\n let ended = false;\n\n try {\n for (const [key, value] of Object.entries(attributes)) span.attribute(key, value);\n } catch {\n // Retain the allocated span for one termination even if its attributes were refused.\n }\n\n return {\n span,\n end: (exit, extra = {}) => {\n if (ended) return;\n ended = true;\n const interrupted = Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause);\n\n try {\n const failure = Exit.isFailure(exit)\n ? Option.getOrUndefined(Cause.findErrorOption(exit.cause))\n : undefined;\n\n const known = Schema.is(BrowserError)(failure) ? failure : undefined;\n\n for (const [key, value] of Object.entries(extra)) span.attribute(key, value);\n span.attribute(\n \"browser.status\",\n Exit.isSuccess(exit) ? \"success\" : interrupted ? \"interrupted\" : \"failure\",\n );\n if (known !== undefined) {\n span.attribute(\"browser.reason\", known.reason._tag);\n span.attribute(\"browser.outcome\", known.outcome);\n }\n } catch {\n // Exporter pressure and shutdown are telemetry loss, never an operation failure.\n }\n try {\n span.end(\n timing ? clock.currentTimeNanosUnsafe() : 0n,\n Exit.isSuccess(exit)\n ? Exit.void\n : Exit.fail(interrupted ? \"Operation interrupted\" : \"Operation failed\"),\n );\n } catch {\n // An exporter is allowed to fail after accepting a span; never retry its termination.\n }\n },\n };\n });\n});\n\nexport const span =\n (name: string, options: Tracer.SpanOptionsNoTrace = {}) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Effect.uninterruptibleMask((restore) =>\n start(name, options).pipe(\n Effect.flatMap((started) =>\n started === undefined\n ? restore(effect)\n : restore(effect).pipe(\n Effect.provideService(Tracer.ParentSpan, started.span),\n Effect.onExit((exit) => Effect.sync(() => started.end(exit))),\n ),\n ),\n ),\n );\n\n/** One span per consumption; end after setup, pulls and the original channel scope's finalizers. */\nexport const stream =\n (name: string, options: Tracer.SpanOptionsNoTrace = {}) =>\n <A, E, R>(source: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> =>\n Stream.suspend(() => {\n let terminal: Exit.Exit<unknown, unknown> | undefined;\n\n return Stream.unwrap(\n Effect.uninterruptible(\n start(name, options).pipe(\n Effect.flatMap((value) => {\n return value === undefined\n ? Effect.succeed(source)\n : Effect.addFinalizer((exit) =>\n Effect.sync(() => value.end(terminal ?? exit)),\n ).pipe(\n Effect.as(source.pipe(Stream.provideService(Tracer.ParentSpan, value.span))),\n );\n }),\n ),\n ),\n ).pipe(\n Stream.onExit((exit) =>\n Effect.sync(() => {\n terminal = exit;\n }),\n ),\n );\n });\n","import { Exit, type Fiber, Schema } from \"effect\";\n\nimport {\n BrowserError,\n BrowserOutcome,\n Reasons,\n type BrowserOperation,\n type BrowserReason,\n} from \"../../Errors.ts\";\nimport type { ReadTicket } from \"./Owner.ts\";\n\n/** A fiber's Exit as a Promise, for native callers that cannot await an Effect. */\nexport const exitPromise = <A, E>(fiber: Fiber.Fiber<A, E>): Promise<Exit.Exit<A, E>> =>\n new Promise((resolve) => {\n fiber.addObserver(resolve);\n });\n\n/** Carries a captured Clock defect/interruption across the native Promise boundary unchanged. */\nexport class NativeEffectFailure extends Schema.TaggedError<NativeEffectFailure>()(\n \"NativeEffectFailure\",\n { cause: Schema.Cause(Schema.Never, Schema.Unknown) },\n) {}\n\n/**\n * A native step failed. It names no operation: the owner stamps the one the caller asked for\n * when it admits the work, so a step's own vocabulary can never become public API.\n */\nexport class NativeFailure extends Schema.TaggedError<NativeFailure>()(\"NativeFailure\", {\n reason: BrowserError.fields.reason,\n // Some native helpers run both before and after dispatch. Only their owner has that evidence.\n outcome: Schema.optionalKey(BrowserOutcome),\n}) {}\n\n/**\n * The only way a native failure becomes public. A fenced ticket already speaks publicly and\n * passes through with the operation the owner gave it; a native failure keeps its reason and\n * takes the caller's operation; anything else is the caller's fallback.\n */\nexport const publicError = (\n error: unknown,\n operation: BrowserOperation,\n fallback: Pick<BrowserError, \"reason\" | \"outcome\">,\n): BrowserError => {\n if (Schema.is(BrowserError)(error)) return error;\n const known = Schema.is(NativeFailure)(error) ? error : fallback;\n\n return BrowserError.make({\n operation,\n reason: known.reason,\n outcome: known.outcome ?? fallback.outcome,\n });\n};\n\n/** Shared by the Playwright driver's seams, so every native call fails in the same vocabulary. */\nexport const failure = (reason: BrowserReason, outcome?: BrowserOutcome) =>\n NativeFailure.make({ reason, ...(outcome === undefined ? {} : { outcome }) });\n\nexport const safeDecode = <A>(codec: Schema.Codec<A, unknown, never, never>, raw: unknown): A => {\n const decoded = Schema.decodeUnknownExit(codec)(raw);\n\n // A schema issue and a throw while reading the reply are both a malformed reply.\n if (Exit.isFailure(decoded)) throw failure(Reasons.Malformed.make({}));\n\n return decoded.value;\n};\n\n// oxlint-disable-next-line no-control-regex -- matches the terminal escape codes Playwright colours its call log with\nconst escapes = /\\u001b\\[[0-9;]*m/g;\n\nconst addresses = /\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s\"'<>]*/gi;\n\n/**\n * An address keeps only its origin: a path, query or user name can carry a credential, such as\n * a DevTools endpoint's browser id or a provider's signed connection URL.\n */\nconst originOf = (address: string): string => {\n try {\n const parsed = new URL(address);\n\n return parsed.host === \"\" ? `${parsed.protocol}…` : `${parsed.protocol}//${parsed.host}/…`;\n } catch {\n return \"…\";\n }\n};\n\n/**\n * The first line of what the engine said, which names the call and its reason. Playwright's\n * call log below it repeats addresses, selectors and endpoints, so it never leaves.\n */\nexport const nativeDetail = (error: unknown): string | undefined => {\n const message =\n error instanceof Error ? error.message : typeof error === \"string\" ? error : undefined;\n\n const line = message?.replace(escapes, \"\").split(\"\\n\", 1)[0]?.trim();\n\n if (line === undefined || line === \"\") return undefined;\n\n return line.replace(addresses, originOf).slice(0, 512);\n};\n\n/** A raw failure the engine raised, with what it said about it. */\nexport const providerReason = (error: unknown) => {\n const detail = nativeDetail(error);\n\n return Reasons.Provider.make(detail === undefined ? {} : { detail });\n};\n\n/**\n * No raw exception from Playwright crosses this private boundary: only its sanitized first line\n * does, as the provider reason's detail. A ticket's own fence is already a public error and\n * passes through with the operation the owner gave it.\n */\nexport const sanitize = <A>(action: () => Promise<A>): Promise<A> =>\n Promise.resolve()\n .then(action)\n .catch((error: unknown) => {\n throw Schema.is(NativeEffectFailure)(error) ||\n Schema.is(BrowserError)(error) ||\n Schema.is(NativeFailure)(error)\n ? error\n : failure(providerReason(error));\n });\n\nexport const closeWithin = async (\n action: () => Promise<unknown>,\n milliseconds = 2000,\n): Promise<void> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n await Promise.race([\n Promise.resolve().then(action),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(failure(Reasons.Timeout.make({}))), milliseconds);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n};\n\n// The native timeout is finite as well as Effect's authoritative deadline. It cannot undo dispatch.\nexport const timeout = (ticket: ReadTicket) => {\n ticket.check();\n\n return ticket.remainingMillis();\n};\n","import { type Clock, Duration, Effect, Exit } from \"effect\";\n\nimport { type BrowserError, Reasons } from \"../../Errors.ts\";\nimport { failure, NativeEffectFailure } from \"./NativeCalls.ts\";\nimport type { Performance, Ticket } from \"./Owner.ts\";\n\n/**\n * The one bridge from performed pacing back into Effect. A performed input paces between the\n * native commands of a single admitted operation, inside the Promise driver that the Playwright\n * and scripted engines share, so its pauses must be awaitable there. The sleep runs on the\n * owner's captured Clock, the clock that stamps the operation's evidence and that tests control,\n * and the admission's signal interrupts it; a failed Exit returns to the driver unchanged.\n * Scheduling the pauses in Effect instead would need the driver to expose each native command on\n * its own: a driver redesign, not a change to how pacing waits.\n */\nconst sleepOnOwnerClock = async (clock: Clock.Clock, nanos: bigint, signal: AbortSignal) => {\n // oxlint-disable-next-line no-restricted-properties -- the native Promise callback awaits only its captured Clock and carries the original Exit back to Effect\n const exit = await Effect.runPromiseExit(clock.sleep(Duration.nanos(nanos)), { signal });\n\n if (Exit.isFailure(exit)) throw NativeEffectFailure.make({ cause: exit.cause });\n};\n\n/**\n * The pacing an admitted performed operation grants its driver: the original owner's clock, the\n * time left before the operation's deadline, and pauses on that clock which the admission's\n * signal interrupts. A pause that would end at or past the deadline is refused before it starts.\n */\nexport const grantedPacing = (owner: {\n readonly clock: Clock.Clock;\n readonly deadlineNanos: () => bigint;\n readonly signal: AbortSignal;\n readonly check: () => void;\n readonly overBudget: () => BrowserError;\n}): Pick<Performance, \"now\" | \"remainingTimeNanos\" | \"pauseUntil\"> => ({\n now: () => owner.clock.monotonicTimeNanosUnsafe(),\n remainingTimeNanos: () => owner.deadlineNanos() - owner.clock.monotonicTimeNanosUnsafe(),\n pauseUntil: async (atNanos) => {\n owner.check();\n if (atNanos >= owner.deadlineNanos()) throw owner.overBudget();\n const remaining = atNanos - owner.clock.monotonicTimeNanosUnsafe();\n\n if (remaining > 0n) await sleepOnOwnerClock(owner.clock, remaining, owner.signal);\n owner.check();\n },\n});\n\n/** A performed admission's ticket: the owner's pacing is always present on it. */\nexport type PerformedTicket = Ticket & { readonly performance: Performance };\n\n/** Whether this admission is performed, which narrows the ticket to carry the owner's pacing. */\nexport const isPerformed = (ticket: Ticket): ticket is PerformedTicket =>\n ticket.performance !== undefined;\n\n/** The original owner's pacing for a performed admission, checked before any input is planned. */\nexport const ownerPacing = (ticket: PerformedTicket) => {\n const { now, pauseUntil, remainingTimeNanos } = ticket.performance;\n\n return {\n now,\n pauseUntil,\n requireDuration: (durationMillis: number) => {\n ticket.check();\n if (!Number.isFinite(durationMillis) || durationMillis < 0)\n throw failure(Reasons.Malformed.make({}), ticket.outcome ?? \"undispatched\");\n if (BigInt(Math.round(durationMillis * 1_000_000)) >= remainingTimeNanos())\n throw failure(Reasons.TimingBudgetExceeded.make({}), ticket.outcome ?? \"undispatched\");\n },\n /** Refuses, before more input, work the original deadline would not see finish by `atNanos`. */\n requireBy: (atNanos: bigint) => {\n ticket.check();\n if (atNanos >= now() + remainingTimeNanos())\n throw failure(Reasons.TimingBudgetExceeded.make({}), ticket.outcome ?? \"undispatched\");\n },\n };\n};\n","import { Effect, Random, Result } from \"effect\";\n\nimport { BrowserError, Reasons } from \"../../Errors.ts\";\nimport type { MotionProfile, Performed } from \"../../PlanData.ts\";\n\n/**\n * These caps are independent of logical action admission and pending native replies. Every\n * schedule is bounded by construction: a path or scroll has at most `samples` points, and a code\n * point expands to at most three strokes (a slip, its Backspace and the key), so typed text has at\n * most 768.\n */\nexport const Limits = {\n samples: 128,\n codePoints: 256,\n} as const;\n\ninterface KeyRandom {\n readonly interval: number;\n readonly hold: number;\n readonly slip: number;\n readonly wrong: number;\n}\n\n/** Finite, geometry-independent policy data; this value owns no clock, permit or native work. */\nexport interface PerformancePlan {\n readonly seed: number;\n readonly profile: MotionProfile;\n readonly pointer: { readonly aimX: number; readonly aimY: number; readonly curvature: number };\n readonly keys: ReadonlyArray<KeyRandom>;\n readonly scroll: number;\n readonly slipsProbability: number;\n}\n\nexport interface Point {\n readonly x: number;\n readonly y: number;\n}\n\nexport interface PointerGeometry {\n readonly from: Point | null;\n readonly box: Point & { readonly width: number; readonly height: number };\n readonly viewport: { readonly width: number; readonly height: number };\n}\n\nexport interface MoveGeometry {\n readonly from: Point | null;\n readonly to: Point;\n readonly viewport: { readonly width: number; readonly height: number };\n}\n\nexport interface PointerSchedule {\n /** Intended viewport point, never evidence of the native engine's actual pointer position. */\n readonly aim: Point;\n readonly durationMillis: number;\n readonly samples: ReadonlyArray<{ readonly offsetMillis: number; readonly position: Point }>;\n}\n\nexport interface Stroke {\n readonly key: string;\n readonly index: number;\n /** Quiet interval from the preceding keyup to this keydown; the first stroke has no delay. */\n readonly intervalMillis: number;\n readonly holdMillis: number;\n readonly offsetMillis: number;\n readonly completedOffsetMillis: number;\n readonly kind: \"type\" | \"slip\" | \"backspace\";\n}\n\nexport interface KeySchedule {\n readonly fieldIndex: number;\n readonly codePoints: number;\n readonly durationMillis: number;\n readonly strokes: ReadonlyArray<Stroke>;\n}\n\nexport interface ScrollSchedule {\n readonly durationMillis: number;\n readonly samples: ReadonlyArray<{\n readonly offsetMillis: number;\n readonly deltaX: number;\n readonly deltaY: number;\n }>;\n}\n\nconst failure = (reason: BrowserError[\"reason\"]) =>\n BrowserError.make({ operation: \"run\", reason, outcome: \"undispatched\" });\n\nconst lerp = (minimum: number, maximum: number, unit: number) =>\n minimum + (maximum - minimum) * unit;\n\nconst clamp = (value: number, minimum: number, maximum: number) =>\n Math.min(maximum, Math.max(minimum, value));\n\n/** Fifth-order progress for zero endpoint velocity/acceleration; curved paths remain policy. */\nexport const progress = (unit: number): number => {\n const u = clamp(unit, 0, 1);\n\n return u * u * u * (10 + u * (-15 + 6 * u));\n};\n\n/** Allocate a fresh pinned generator on execution, never a shared run/callback Random service. */\nexport const prepare = (style: Performed, seed: number, stepId: string) =>\n Effect.suspend(() =>\n Effect.gen(function* () {\n const aimX = yield* Random.next;\n const aimY = yield* Random.next;\n const curvature = yield* Random.next;\n const scroll = yield* Random.next;\n\n const keys = yield* Effect.forEach(Array.from({ length: Limits.codePoints }), () =>\n Effect.gen(function* () {\n return Object.freeze({\n interval: yield* Random.next,\n hold: yield* Random.next,\n slip: yield* Random.next,\n wrong: yield* Random.next,\n });\n }),\n );\n\n return Object.freeze({\n seed,\n profile: style.motion,\n pointer: Object.freeze({ aimX, aimY, curvature }),\n keys: Object.freeze(keys),\n scroll,\n slipsProbability: style.slips.probability,\n });\n }).pipe(Random.withSeed(`effect-browser/performed/1:${seed}:${stepId.length}:${stepId}`)),\n );\n\nconst path = (\n plan: PerformancePlan,\n from: Point | null,\n aim: Point,\n viewport: MoveGeometry[\"viewport\"],\n durationMillis: number,\n): Result.Result<PointerSchedule, BrowserError> => {\n if (from === null)\n return Result.succeed(Object.freeze({ aim, durationMillis: 0, samples: Object.freeze([]) }));\n\n const deltaX = aim.x - from.x;\n const deltaY = aim.y - from.y;\n const distance = Math.hypot(deltaX, deltaY);\n\n if (!Number.isFinite(distance)) return Result.fail(failure(Reasons.Malformed.make({})));\n if (distance === 0)\n return Result.succeed(Object.freeze({ aim, durationMillis: 0, samples: Object.freeze([]) }));\n const count = Math.min(Limits.samples, Math.max(2, Math.ceil(durationMillis / (1000 / 60)) + 1));\n const curvature = (plan.pointer.curvature * 2 - 1) * plan.profile.pointer.curvature * distance;\n const normalX = -deltaY / distance;\n const normalY = deltaX / distance;\n\n const samples = Array.from({ length: count }, (_value, index) => {\n const unit = index / (count - 1);\n const eased = progress(unit);\n const bend = 4 * eased * (1 - eased) * curvature;\n\n return Object.freeze({\n offsetMillis: unit * durationMillis,\n position: Object.freeze({\n x: clamp(from.x + deltaX * eased + normalX * bend, 0, viewport.width),\n y: clamp(from.y + deltaY * eased + normalY * bend, 0, viewport.height),\n }),\n });\n });\n\n return Result.succeed(Object.freeze({ aim, durationMillis, samples: Object.freeze(samples) }));\n};\n\n/** The existing native hit checker must validate the returned aim on the exact leased node. */\nexport const pointer = (\n plan: PerformancePlan,\n geometry: PointerGeometry,\n): Result.Result<PointerSchedule, BrowserError> => {\n const { from, box, viewport } = geometry;\n\n const values = [\n box.x,\n box.y,\n box.width,\n box.height,\n viewport.width,\n viewport.height,\n ...(from === null ? [] : [from.x, from.y]),\n ];\n\n if (values.some((value) => !Number.isFinite(value)))\n return Result.fail(failure(Reasons.Malformed.make({})));\n const left = Math.max(0, box.x);\n const top = Math.max(0, box.y);\n const right = Math.min(viewport.width, box.x + box.width);\n const bottom = Math.min(viewport.height, box.y + box.height);\n const width = right - left;\n const height = bottom - top;\n\n if (width <= 0 || height <= 0 || box.width <= 0 || box.height <= 0)\n return Result.fail(failure(Reasons.NotVisible.make({})));\n const inset = plan.profile.pointer.aimInset;\n\n const aim = Object.freeze({\n x: lerp(left + width * inset, right - width * inset, plan.pointer.aimX),\n y: lerp(top + height * inset, bottom - height * inset, plan.pointer.aimY),\n });\n\n const distance = from === null ? 0 : Math.hypot(aim.x - from.x, aim.y - from.y);\n const range = plan.profile.pointer.duration;\n\n // Shannon duration form with chosen policy coefficients, not measured human calibration.\n const durationMillis = clamp(\n 100 + 150 * Math.log2(distance / Math.min(width, height) + 1),\n range.minMillis,\n range.maxMillis,\n );\n\n return path(plan, from, aim, viewport, durationMillis);\n};\n\n/** Authored coordinates stay exact; the bounded timing policy needs no synthetic target box. */\nexport const move = (\n plan: PerformancePlan,\n geometry: MoveGeometry,\n): Result.Result<PointerSchedule, BrowserError> => {\n const { from, to, viewport } = geometry;\n\n if (\n [to.x, to.y, viewport.width, viewport.height, ...(from === null ? [] : [from.x, from.y])].some(\n (value) => !Number.isFinite(value),\n )\n )\n return Result.fail(failure(Reasons.Malformed.make({})));\n if (\n viewport.width <= 0 ||\n viewport.height <= 0 ||\n to.x < 0 ||\n to.y < 0 ||\n to.x > viewport.width ||\n to.y > viewport.height\n )\n return Result.fail(failure(Reasons.NotVisible.make({})));\n const aim = Object.freeze({ x: to.x, y: to.y });\n const distance = from === null ? 0 : Math.hypot(to.x - from.x, to.y - from.y);\n const range = plan.profile.pointer.duration;\n\n // Chosen linear-distance pacing, with no claim of measured human calibration.\n const durationMillis = clamp(100 + distance * 0.35, range.minMillis, range.maxMillis);\n\n return path(plan, from, aim, viewport, durationMillis);\n};\n\nconst slipKeys = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** Input text is transient host data; receipts/timeline retain counts and intervals only. */\nexport const keys = (\n plan: PerformancePlan,\n text: string,\n fieldIndex = 0,\n): Result.Result<KeySchedule, BrowserError> => {\n if (!Number.isSafeInteger(fieldIndex) || fieldIndex < 0 || fieldIndex > 31)\n return Result.fail(failure(Reasons.Malformed.make({})));\n // Input values are already bounded to 65,536 UTF-8 bytes, so the count is measured in full.\n const characters = [...text];\n\n if (characters.length > Limits.codePoints)\n return Result.fail(\n failure(\n Reasons.Limit.make({\n dimension: \"code-points\",\n maximum: Limits.codePoints,\n observed: characters.length,\n }),\n ),\n );\n const strokes: Array<Stroke> = [];\n let durationMillis = 0;\n\n const append = (key: string, index: number, random: KeyRandom, kind: Stroke[\"kind\"]) => {\n const intervalMillis =\n strokes.length === 0\n ? 0\n : lerp(\n plan.profile.keys.interval.minMillis,\n plan.profile.keys.interval.maxMillis,\n random.interval,\n );\n\n const holdMillis = lerp(\n plan.profile.keys.hold.minMillis,\n plan.profile.keys.hold.maxMillis,\n random.hold,\n );\n\n const offsetMillis = durationMillis + intervalMillis;\n\n durationMillis = offsetMillis + holdMillis;\n strokes.push(\n Object.freeze({\n key,\n index,\n intervalMillis,\n holdMillis,\n offsetMillis,\n completedOffsetMillis: durationMillis,\n kind,\n }),\n );\n };\n\n for (const [index, key] of characters.entries()) {\n const random = plan.keys[(index + fieldIndex * 17) % Limits.codePoints];\n\n if (random === undefined) return Result.fail(failure(Reasons.Malformed.make({})));\n if (plan.slipsProbability > 0 && random.slip < plan.slipsProbability && /^[a-z]$/u.test(key)) {\n const wrongIndex = Math.floor(random.wrong * (slipKeys.length - 1));\n const originalIndex = slipKeys.indexOf(key);\n const wrong = slipKeys[wrongIndex >= originalIndex ? wrongIndex + 1 : wrongIndex];\n\n if (wrong === undefined) return Result.fail(failure(Reasons.Malformed.make({})));\n append(wrong, index, random, \"slip\");\n append(\"Backspace\", index, random, \"backspace\");\n }\n append(key, index, random, \"type\");\n }\n\n return Result.succeed(\n Object.freeze({\n fieldIndex,\n codePoints: characters.length,\n durationMillis,\n strokes: Object.freeze(strokes),\n }),\n );\n};\n\n/** Explicit deltas apply to the existing checked scroll capability, not a synthetic wheel target. */\nexport const scroll = (\n plan: PerformancePlan,\n deltaX: number,\n deltaY: number,\n): Result.Result<ScrollSchedule, BrowserError> => {\n if (!Number.isFinite(deltaX) || !Number.isFinite(deltaY))\n return Result.fail(failure(Reasons.Malformed.make({})));\n if (deltaX === 0 && deltaY === 0)\n return Result.succeed(Object.freeze({ durationMillis: 0, samples: Object.freeze([]) }));\n const range = plan.profile.scroll.duration;\n const durationMillis = lerp(range.minMillis, range.maxMillis, plan.scroll);\n\n const count = Math.min(\n Limits.samples,\n Math.max(1, Math.ceil(durationMillis / plan.profile.scroll.intervalMillis)),\n );\n\n let sentX = 0;\n let sentY = 0;\n\n const samples = Array.from({ length: count }, (_value, index) => {\n const unit = (index + 1) / count;\n const x = index + 1 === count ? deltaX : deltaX * progress(unit);\n const y = index + 1 === count ? deltaY : deltaY * progress(unit);\n\n const sample = Object.freeze({\n offsetMillis: unit * durationMillis,\n deltaX: x - sentX,\n deltaY: y - sentY,\n });\n\n sentX = x;\n sentY = y;\n\n return sample;\n });\n\n return Result.succeed(Object.freeze({ durationMillis, samples: Object.freeze(samples) }));\n};\n","import { Effect } from \"effect\";\n\nimport type { PageStatus } from \"../../Browser.ts\";\nimport type { PageInfo, Target } from \"../../BrowserData.ts\";\nimport type { CaptureQualification } from \"../../CaptureData.ts\";\nimport { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type { CaptureReason } from \"../../TimelineData.ts\";\nimport type { CaptureSource } from \"./Driver.ts\";\nimport type { Owner, Ticket } from \"./Owner.ts\";\n\nexport interface CaptureLease {\n readonly pageId: string;\n readonly stop: Effect.Effect<void>;\n readonly invalidate: (reason: string) => void;\n readonly reservedBytes: number;\n}\n\nexport interface CaptureResolution {\n /** Stable native page identity used to quarantine an unconfirmed screencast across reconnects. */\n readonly key: string;\n readonly target: Target;\n readonly source: CaptureSource;\n /** Retains one bounded authority record after it leaves the owner's live inventory. */\n readonly status?: () => Pick<PageStatus, \"phase\" | \"containment\">;\n /** Captured when this exact interval is resolved, never redirected by reconnect. */\n readonly metadata?: (event: CaptureMetadata) => void;\n}\n\n/** Original interval evidence only; no frame bytes or new capture ownership. */\nexport type CaptureMetadata =\n | {\n readonly _tag: \"FirstFrame\";\n readonly captureId: string;\n readonly target: Target;\n readonly captureBoundary: number;\n readonly captureDocument: number;\n readonly frameSequence: number;\n readonly sourceTimeMillis: number;\n readonly sourceClock: \"presentation-unix-millis\";\n readonly receivedMonotonicNanos: bigint;\n readonly width: number;\n readonly height: number;\n readonly viewportWidth: number;\n readonly viewportHeight: number;\n }\n | {\n readonly _tag: \"CaptureBoundary\";\n readonly captureId: string;\n readonly target: Target;\n readonly captureBoundary: number;\n readonly captureDocument: number;\n readonly sameDocument: boolean;\n readonly url: string | null;\n readonly urlQualification: \"NativeCached\" | \"Omitted\";\n readonly afterSequence: number | null;\n readonly observedMonotonicNanos: bigint;\n }\n | {\n readonly _tag: \"Capture\";\n readonly captureId: string;\n readonly target: Target;\n readonly phase: \"Reserved\" | \"Watching\" | \"Started\" | \"Ended\" | \"Stopped\";\n readonly latePhase: boolean;\n readonly observedMonotonicNanos: bigint;\n readonly captureBoundary: number;\n readonly captureDocument: number;\n readonly qualification: CaptureQualification;\n readonly initialUrl: string | null;\n readonly initialUrlQualification: \"NativeCached\" | \"Unread\" | \"Omitted\";\n readonly reason: CaptureReason | null;\n readonly nativeStop: \"confirmed\" | \"unconfirmed\" | null;\n readonly received: number;\n readonly delivered: number;\n readonly discarded: number;\n readonly overflow: number;\n readonly late: number;\n readonly duplicates: number;\n readonly rejected: number;\n readonly upstreamDrops: \"unknown\";\n };\n\n/** Capture ownership and accounting, shared by a session and every Page it issues. */\nexport interface CaptureParent {\n readonly owner: Owner;\n /** Prebound to the original owner's Crypto; starting capture adds no caller service. */\n readonly newCaptureId: Effect.Effect<string>;\n readonly resolve: (\n ticket: Ticket,\n page: PageInfo,\n ) => Effect.Effect<CaptureResolution, BrowserError>;\n readonly captureLeases: Map<string, CaptureLease>;\n captureReservedBytes: number;\n}\n\n/** The capture parent of one issued Page: the only kind that can start a capture. */\nexport interface PageCaptureParent extends CaptureParent {\n /** The page's own authority check, reported under the caller's operation. */\n readonly validate: (operation: BrowserOperation) => Effect.Effect<void, BrowserError>;\n /** The exact page this parent captures. */\n readonly page: PageInfo;\n}\n\n/** A page delegates to the same owner and accounting; its destination cannot be replaced. */\nexport const forPage = (\n parent: CaptureParent,\n info: PageInfo,\n identity: Target,\n validate: (operation: BrowserOperation) => Effect.Effect<void, BrowserError>,\n): PageCaptureParent => ({\n validate,\n page: info,\n owner: parent.owner,\n newCaptureId: parent.newCaptureId,\n captureLeases: parent.captureLeases,\n get captureReservedBytes() {\n return parent.captureReservedBytes;\n },\n set captureReservedBytes(value) {\n parent.captureReservedBytes = value;\n },\n resolve: (ticket, requested) =>\n validate(\"capture\").pipe(\n Effect.andThen(\n Effect.suspend(() => {\n if (ticket.generation !== identity.generation)\n return Effect.fail(\n BrowserError.make({\n operation: \"capture\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n }),\n );\n if (requested.pageId !== info.pageId || requested.targetId !== info.targetId)\n return Effect.fail(\n BrowserError.make({\n operation: \"capture\",\n reason: Reasons.Configuration.make({ path: \"target\" }),\n outcome: \"undispatched\",\n }),\n );\n\n return parent\n .resolve(ticket, info)\n .pipe(Effect.tap(() => Effect.sync(() => ticket.check())));\n }),\n ),\n ),\n});\n","import { Predicate, Schema } from \"effect\";\n\nimport {\n type Correlation,\n type EvidenceTarget,\n type Payload,\n PayloadTag,\n type Stamp,\n} from \"../../TimelineData.ts\";\nimport type { CaptureMetadata } from \"../browser/Association.ts\";\nimport type { NativeCachedPage } from \"../browser/Driver.ts\";\nimport type { OperationListener } from \"../browser/Owner.ts\";\nimport type { AppendInput, makeStore } from \"./Store.ts\";\n\nexport type Store = ReturnType<typeof makeStore>;\n\n/** Native receipts may contain checked Schema classes; journal metadata is plain data. */\nconst geometry = (value: { readonly x: number; readonly y: number }) => ({\n x: value.x,\n y: value.y,\n});\n\nconst isPayloadTag = Schema.is(PayloadTag);\n\n/** Reads a refused payload's own tag without running any accessor it might carry. */\nconst omittedTag = (event: unknown): PayloadTag | null => {\n try {\n const tag: unknown = Predicate.isObject(event)\n ? Object.getOwnPropertyDescriptor(event, \"_tag\")?.value\n : undefined;\n\n return isPayloadTag(tag) ? tag : null;\n } catch {\n return null;\n }\n};\n\n/**\n * Refusing an external fact must never change the native operation's original outcome. The\n * omission keeps the refused event's target, correlation and tag, so a Page view sees its own\n * gap; only when that attribution is itself refused does the omission stand unattributed.\n */\nexport const publish = (store: Store, input: AppendInput) => {\n const result = store.append(input);\n\n if (result._tag !== \"Refused\" || result.reason === \"Closed\") return result;\n const reason = result.reason;\n\n const attributed = store.append({\n target: input.target,\n correlation: input.correlation,\n event: { _tag: \"MetadataOmitted\", reason, originalTag: omittedTag(input.event) },\n });\n\n return attributed._tag === \"Appended\"\n ? attributed\n : store.append({\n target: null,\n correlation: null,\n event: { _tag: \"MetadataOmitted\", reason, originalTag: null },\n });\n};\n\nexport const stamp = (store: Store, originNanos: bigint, nanos: bigint): Stamp => ({\n clockId: store.now().clockId,\n offsetNanos: nanos - originNanos,\n});\n\nexport const cachedTarget = (page: NativeCachedPage, generation: number): EvidenceTarget => ({\n generation,\n pageId: page.pageId,\n frameId: page.frameId,\n document: page.documentEpoch,\n});\n\n/**\n * The timeline's subscription to every operation the owner guards. It records each fact as the\n * owner reported it, lateness included, and an operation's end as its Finished facts.\n */\nexport const operationEvents =\n (configuration: {\n readonly store: () => Store;\n readonly originNanos: bigint;\n readonly retain: (pageId: string | undefined) => () => void;\n }): OperationListener =>\n (facts) => {\n // One closure per original admitted ticket, with no registry of historical stores.\n const store = configuration.store();\n const scope = facts.scope;\n\n const pageId =\n scope === undefined || scope === \"all\" || scope === \"none\" ? undefined : scope.pageId;\n\n const release = configuration.retain(pageId);\n\n const target: EvidenceTarget | null =\n pageId === undefined\n ? null\n : {\n generation: facts.generation,\n pageId,\n frameId: null,\n document: null,\n };\n\n const correlation = facts.correlation;\n\n const append = (event: Payload, actualTarget: EvidenceTarget | null = target) =>\n publish(store, { target: actualTarget, correlation, event });\n\n let ordinal = 0;\n let picture: { readonly at: Stamp; readonly target: EvidenceTarget } | undefined;\n const at = (nanos: bigint) => stamp(store, configuration.originNanos, nanos);\n\n const interval = (start: bigint, end: bigint) => ({\n start: at(start),\n end: at(end),\n qualification: \"native-call-interval\" as const,\n });\n\n const actualTarget = (value: {\n readonly generation?: number;\n readonly pageId: string;\n readonly frameId: string;\n }): EvidenceTarget => ({\n generation: value.generation ?? facts.generation,\n pageId: value.pageId,\n frameId: value.frameId,\n // A receipt's target grants frame attribution, not a document sampling guarantee.\n document: null,\n });\n\n return (event) => {\n switch (event._tag) {\n case \"Phase\": {\n if (event.phase === \"Dispatched\") ordinal++;\n\n const common = {\n operation: facts.operation,\n operationId: facts.operationId,\n nativeOrdinal: ordinal,\n mutation: event.mutation,\n late: event.late,\n };\n\n // Consumers tell a preparatory or burst reply from completed logical input by its fact.\n append(\n event.phase === \"Acknowledged\" && event.acknowledgement !== undefined\n ? {\n _tag: event.phase,\n ...common,\n acknowledgement: {\n subphase: event.acknowledgement.subphase,\n logicalComplete: event.acknowledgement.logicalComplete,\n },\n }\n : { _tag: event.phase, ...common },\n );\n\n return;\n }\n // The timeline records an operation's end through its Finished facts.\n case \"Terminal\":\n return;\n case \"Picture\": {\n const boundary = event.boundary;\n\n const captured: EvidenceTarget = {\n generation: facts.generation,\n ...boundary.target,\n document: boundary.documentEpoch,\n };\n\n const now = store.now();\n\n if (boundary.phase === \"Requested\") picture = { at: now, target: captured };\n else if (picture !== undefined) {\n const requested = picture;\n\n picture = undefined;\n append(\n {\n _tag: \"Picture\",\n operationId: facts.operationId,\n mediaType: \"image/png\",\n nativeRequest: requested.at,\n nativeReturn: now,\n qualification: \"native-call-interval\",\n requestDocument: requested.target.document,\n returnDocument: boundary.documentEpoch,\n },\n {\n ...requested.target,\n document:\n requested.target.document === boundary.documentEpoch\n ? boundary.documentEpoch\n : null,\n },\n );\n }\n\n return;\n }\n case \"Input\": {\n const { receipt, keys } = event;\n const timing = interval(receipt.startedMonotonicNanos, receipt.completedMonotonicNanos);\n const correlated = { operationId: facts.operationId, interval: timing };\n let payload: Payload | undefined;\n\n switch (receipt.kind) {\n case \"pointer-move\":\n case \"hover\":\n payload = {\n _tag: \"Pointer\",\n kind: receipt.kind,\n position: receipt.position === null ? null : geometry(receipt.position),\n ...correlated,\n };\n break;\n case \"click\":\n payload = {\n _tag: \"Press\",\n position: receipt.position === null ? null : geometry(receipt.position),\n ...(receipt.intended === undefined\n ? {}\n : {\n intended: {\n position: geometry(receipt.intended.position),\n relativePosition: geometry(receipt.intended.relativePosition),\n qualification: receipt.intended.qualification,\n },\n }),\n ...correlated,\n };\n break;\n case \"wheel\":\n payload = {\n _tag: \"Scroll\",\n kind: \"wheel\",\n delta:\n receipt.delta === undefined || receipt.delta === null\n ? null\n : geometry(receipt.delta),\n ...correlated,\n };\n break;\n case \"press\":\n case \"type\":\n if (keys === undefined) return;\n payload = { _tag: \"Keys\", kind: receipt.kind, ...keys, ...correlated };\n break;\n }\n append(\n payload ?? { _tag: \"MetadataOmitted\", reason: \"Malformed\", originalTag: null },\n actualTarget(receipt.target),\n );\n\n return;\n }\n case \"Scroll\": {\n const value = event.facts;\n\n append(\n {\n _tag: \"Scroll\",\n operationId: facts.operationId,\n kind: \"scroll\",\n // A scroll-into-view moves by whatever the browser chose; it has no requested delta.\n delta:\n value.x === undefined || value.y === undefined ? null : { x: value.x, y: value.y },\n ...(value.qualification === undefined ? {} : { qualification: value.qualification }),\n interval: interval(value.startedMonotonicNanos, value.completedMonotonicNanos),\n },\n actualTarget(value.target),\n );\n\n return;\n }\n case \"Settled\":\n append(\n {\n _tag: \"Settled\",\n operationId: facts.operationId,\n quietMillis: event.evidence.quietMillis,\n withinMillis: event.evidence.withinMillis,\n signals: event.evidence.signals,\n },\n actualTarget(event.target),\n );\n\n return;\n case \"Glide\": {\n const value = event.facts;\n\n if (value.samples.length < 2) return;\n append(\n {\n _tag: \"Glide\",\n operationId: facts.operationId,\n qualification: \"intended-schedule\",\n schedule: value.samples.map((sample) => ({\n at: at(\n value.startedMonotonicNanos + BigInt(Math.round(sample.offsetMillis * 1_000_000)),\n ),\n position: geometry(sample.position),\n })),\n },\n actualTarget(value.target),\n );\n\n return;\n }\n case \"Finished\":\n if (event.containment._tag !== \"NotRequired\")\n append({ _tag: \"Contained\", containment: event.containment });\n if (event.kind === \"Cancelled\")\n append({ _tag: \"Cancelled\", operationId: facts.operationId, outcome: event.outcome });\n else if (event.kind === \"Failed\")\n append({\n _tag: \"Failed\",\n operationId: facts.operationId,\n operation: facts.operation,\n reason: event.error?.reason._tag ?? \"Failed\",\n outcome: event.outcome,\n });\n release();\n }\n };\n };\n\nexport const captureMetadata =\n (store: Store, originNanos: bigint) =>\n (value: CaptureMetadata): void => {\n // Capture document/boundary numbers name receipt attribution, never native document epochs.\n const target: EvidenceTarget = { ...value.target, document: null };\n\n const common = {\n captureId: value.captureId,\n captureBoundary: value.captureBoundary,\n captureDocument: value.captureDocument,\n };\n\n const at = (nanos: bigint) => stamp(store, originNanos, nanos);\n let event: Payload;\n\n switch (value._tag) {\n case \"FirstFrame\":\n event = {\n _tag: \"FirstFrame\",\n ...common,\n frameSequence: value.frameSequence,\n sourceTimeMillis: value.sourceTimeMillis,\n sourceClock: value.sourceClock,\n received: at(value.receivedMonotonicNanos),\n width: value.width,\n height: value.height,\n viewportWidth: value.viewportWidth,\n viewportHeight: value.viewportHeight,\n qualification: \"received-boundary-attribution\",\n };\n break;\n case \"CaptureBoundary\":\n event = {\n _tag: \"CaptureBoundary\",\n ...common,\n sameDocument: value.sameDocument,\n afterSequence: value.afterSequence,\n observed: at(value.observedMonotonicNanos),\n qualification: \"received-boundary-attribution\",\n url: value.url,\n urlQualification: value.urlQualification,\n };\n break;\n case \"Capture\":\n event = {\n _tag: \"Capture\",\n ...common,\n phase: value.phase,\n observed: at(value.observedMonotonicNanos),\n qualification: value.qualification,\n reason: value.reason,\n nativeStop: value.nativeStop,\n received: value.received,\n delivered: value.delivered,\n discarded: value.discarded,\n overflow: value.overflow,\n late: value.late,\n duplicates: value.duplicates,\n rejected: value.rejected,\n upstreamDrops: value.upstreamDrops,\n latePhase: value.latePhase,\n };\n break;\n }\n publish(store, { target, correlation: null, event });\n };\n\nexport const planPublisher =\n (store: Store, target: EvidenceTarget | null) =>\n (correlation: Correlation, event: Payload): void => {\n publish(store, { target, correlation, event });\n };\n","import { Deferred, Effect } from \"effect\";\n\nimport type { TerminalReason } from \"../../TimelineData.ts\";\n\n/** Original bounded logical owners finish their evidence before the domain's one terminal. */\nexport const makeRetirement = (complete: (reason: TerminalReason) => void) => {\n let count = 0;\n let requested: TerminalReason | null = null;\n let finished = false;\n const signal = Deferred.makeUnsafe<void>();\n\n const finish = () => {\n if (finished || requested === null || count !== 0) return;\n finished = true;\n complete(requested);\n };\n\n return {\n retain: (): (() => void) => {\n if (finished) return () => {};\n count++;\n let released = false;\n\n return () => {\n if (released) return;\n released = true;\n count--;\n finish();\n };\n },\n request: (reason: TerminalReason): void => {\n requested ??= reason;\n // Waiters resume on their own fibers, never inside the native callback that retires.\n Deferred.doneUnsafe(signal, Effect.yieldNow);\n finish();\n },\n /** Completes once retirement is requested, before retained owners have finished. */\n requested: Deferred.await(signal),\n };\n};\n","import { Effect, Result, Schema, Stream } from \"effect\";\n\nimport type { PageStatus } from \"../../Browser.ts\";\nimport type { Timeline } from \"../../Timeline.ts\";\nimport {\n PagesInventory,\n TimelineLimit,\n TimelineMalformed,\n type CachedPage,\n type Event,\n type PageEvent,\n type Terminal,\n type TimelineError,\n} from \"../../TimelineData.ts\";\nimport type { NativeCachedPage } from \"../browser/Driver.ts\";\nimport type { makeStore, Subscription, View } from \"./Store.ts\";\n\ntype Store = ReturnType<typeof makeStore>;\n\ninterface Attachment {\n readonly inventory: PagesInventory;\n readonly subscription: Subscription;\n}\n\nconst decodeInventory = Schema.decodeResult(PagesInventory);\n\nconst lifecycle = (value: Event): boolean => {\n switch (value.event._tag) {\n case \"Lifecycle\":\n case \"PageOpened\":\n case \"PageClosed\":\n case \"DisplayChanged\":\n case \"MetadataChanged\":\n case \"Navigated\":\n case \"Terminal\":\n case \"MetadataOmitted\":\n return true;\n case \"Planned\":\n case \"Prepared\":\n case \"Dispatched\":\n case \"Acknowledged\":\n case \"FollowUp\":\n case \"Pointer\":\n case \"Press\":\n case \"Keys\":\n case \"Scroll\":\n case \"Glide\":\n case \"FirstFrame\":\n case \"Capture\":\n case \"CaptureBoundary\":\n case \"Picture\":\n case \"Settled\":\n case \"Contained\":\n case \"Failed\":\n case \"Cancelled\":\n return false;\n }\n};\n\nconst viewTimeline = (store: Store, view?: View): Timeline => ({\n snapshot: (options) => store.snapshot(options, view),\n events: (from) =>\n Stream.unwrap(\n store\n .subscribe({\n ...(from === undefined ? {} : { from }),\n ...(view === undefined ? {} : { view }),\n })\n .pipe(Effect.map((subscription) => Stream.fromPull(Effect.succeed(subscription.pull)))),\n ),\n now: Effect.sync(store.now),\n});\n\n/** The original registry and one journal attach atomically; no metadata refresh issues authority. */\nexport const makeJournal = (configuration: {\n readonly store: () => Store;\n readonly cachedPages: () => ReadonlyArray<NativeCachedPage>;\n readonly pageStatus: (pageId: string) => Pick<PageStatus, \"phase\" | \"containment\"> | undefined;\n readonly generation: () => number;\n}) => {\n const timeline: Timeline = {\n snapshot: (options) => Effect.suspend(() => configuration.store().snapshot(options)),\n events: (from) => Stream.suspend(() => viewTimeline(configuration.store()).events(from)),\n now: Effect.sync(() => configuration.store().now()),\n };\n\n const forPage = (\n store: Store,\n pageId: string,\n generation: number,\n terminal: () => Terminal | null,\n ): Timeline => viewTimeline(store, { pageId, generation, terminal });\n\n const attachInventory = (): Result.Result<Attachment, TimelineError> => {\n const store = configuration.store();\n const native = configuration.cachedPages();\n\n if (native.length > 32)\n return Result.fail(new TimelineLimit({ maximum: 32, observed: native.length }));\n const generation = configuration.generation();\n\n const pages: CachedPage[] = native.map((page) => {\n const status = configuration.pageStatus(page.pageId);\n const urlOmitted = page.url !== null && page.url.length > 8192;\n const titleOmitted = page.title !== null && page.title.length > 512;\n\n return {\n identity: {\n generation,\n pageId: page.pageId,\n frameId: page.frameId,\n document: page.documentEpoch,\n },\n targetId: page.targetId,\n url: urlOmitted ? null : page.url,\n urlQualification: urlOmitted\n ? \"Omitted\"\n : page.url === null && page.urlQualification !== \"Omitted\"\n ? \"Unread\"\n : page.urlQualification,\n title: titleOmitted ? null : page.title,\n titleQualification: titleOmitted\n ? \"Omitted\"\n : page.title === null && page.titleQualification === \"ObservedCached\"\n ? \"Unread\"\n : page.titleQualification,\n selected: page.selected,\n displayState: page.displayState === \"suspended\" ? \"held\" : page.displayState,\n phase: status?.phase ?? (page.displayState === \"suspended\" ? \"paused\" : \"open\"),\n containment: status?.containment ?? { _tag: \"NotRequired\" },\n };\n });\n\n const decoded = decodeInventory(\n { _tag: \"Inventory\", pages, resumeAfter: store.cursor() },\n { onExcessProperty: \"error\" },\n );\n\n if (Result.isFailure(decoded)) return Result.fail(new TimelineMalformed({ path: \"Inventory\" }));\n const inventory = decoded.success;\n\n for (const page of inventory.pages) {\n Object.freeze(page.identity);\n Object.freeze(page.containment);\n Object.freeze(page);\n }\n Object.freeze(inventory.pages);\n Object.freeze(inventory.resumeAfter);\n Object.freeze(inventory);\n const attached = store.attach({ from: inventory.resumeAfter });\n\n return Result.isFailure(attached)\n ? Result.fail(attached.failure)\n : Result.succeed({ inventory, subscription: attached.success });\n };\n\n const acquire = Effect.sync(attachInventory).pipe(Effect.flatMap(Effect.fromResult));\n\n const pageEvents: Stream.Stream<PageEvent, TimelineError> = Stream.unwrap(\n Effect.acquireRelease(acquire, (value) => Effect.sync(value.subscription.release)).pipe(\n Effect.map(({ inventory, subscription }) =>\n Stream.concat(\n Stream.succeed(inventory),\n Stream.fromPull(Effect.succeed(subscription.pull)).pipe(Stream.filter(lifecycle)),\n ),\n ),\n ),\n );\n\n return { timeline, forPage, pageEvents };\n};\n","import {\n type Array as Arr,\n Cause,\n type Clock,\n Deferred,\n Effect,\n Predicate,\n type Pull,\n Result,\n Schema,\n type Scope,\n} from \"effect\";\n\nimport {\n type Cursor,\n Event,\n EventJson,\n Selector,\n SnapshotOptions,\n TimelineCursorError,\n TimelineGap,\n TimelineLimit,\n TimelineMalformed,\n type Retention,\n type Snapshot,\n type Stamp,\n type StoreIdentity,\n type Terminal,\n type TerminalReason,\n type TimelineError,\n} from \"../../TimelineData.ts\";\n\nexport interface View {\n readonly pageId: string;\n readonly generation: number;\n readonly terminal: () => Terminal | null;\n}\n\nexport interface SubscriptionOptions {\n readonly from?: Selector;\n readonly view?: View;\n}\n\nexport interface Subscription {\n readonly cursor: Cursor;\n readonly pull: Pull.Pull<Arr.NonEmptyReadonlyArray<Event>, TimelineError>;\n readonly release: () => void;\n}\n\nexport type AppendInput = Pick<Event, \"target\" | \"correlation\" | \"event\">;\n\nexport type AppendResult =\n | { readonly _tag: \"Appended\"; readonly event: Event }\n | {\n readonly _tag: \"Refused\";\n readonly reason: \"Closed\" | \"Malformed\" | \"Oversized\";\n readonly bytes?: number;\n };\n\ninterface Entry {\n readonly event: Event;\n readonly bytes: number;\n}\n\ninterface Reader {\n sequence: bigint;\n readonly minimumAt: bigint | undefined;\n readonly view: View | undefined;\n wake: Deferred.Deferred<void> | undefined;\n released: boolean;\n}\n\nconst maximumInteger = (1n << 128n) - 1n;\nconst utf8 = new TextEncoder();\nconst decodeEvent = Schema.decodeUnknownResult(Event);\nconst encodeEvent = Schema.encodeResult(EventJson);\nconst decodeSelector = Schema.decodeUnknownResult(Selector);\nconst decodeSnapshotOptions = Schema.decodeUnknownResult(SnapshotOptions);\nconst closed = { onExcessProperty: \"error\" } as const;\n\n/** Producer cost admission rejects accessors and oversized trees before semantic decoding. */\nconst metadataAdmission = (\n value: unknown,\n maximumBytes: number,\n): \"Malformed\" | \"Oversized\" | undefined => {\n let bytes = 0;\n let nodes = 0;\n let refusal: \"Malformed\" | \"Oversized\" | undefined;\n const ancestors = new Set<object>();\n\n const add = (count: number) => {\n bytes += count;\n if (bytes > maximumBytes) refusal = \"Oversized\";\n };\n\n const text = (value: string) => {\n if (value.length > maximumBytes) refusal = \"Oversized\";\n else add(utf8.encode(JSON.stringify(value)).byteLength);\n };\n\n const visit = (input: unknown, depth: number): void => {\n if (refusal !== undefined) return;\n if (++nodes > 4096 || depth > 12) {\n refusal = \"Oversized\";\n\n return;\n }\n if (input === null) return add(4);\n switch (typeof input) {\n case \"string\":\n return text(input);\n case \"boolean\":\n return add(input ? 4 : 5);\n case \"number\":\n if (Number.isFinite(input)) return add(JSON.stringify(input).length);\n refusal = \"Malformed\";\n\n return;\n case \"bigint\":\n if (input < 0n || input > maximumInteger) refusal = \"Malformed\";\n else text(input.toString());\n\n return;\n case \"object\":\n break;\n case \"undefined\":\n case \"symbol\":\n case \"function\":\n refusal = \"Malformed\";\n\n return;\n }\n if (!Predicate.isObjectKeyword(input) || ancestors.has(input)) {\n refusal = \"Malformed\";\n\n return;\n }\n ancestors.add(input);\n const keys = Reflect.ownKeys(input);\n\n if (Array.isArray(input)) {\n if (input.length > 128 || keys.length !== input.length + 1) {\n refusal = \"Oversized\";\n\n return;\n }\n add(2 + Math.max(0, input.length - 1));\n for (let index = 0; index < input.length; index++) {\n const property = Object.getOwnPropertyDescriptor(input, String(index));\n\n if (property === undefined || !(\"value\" in property)) {\n refusal = \"Malformed\";\n\n return;\n }\n visit(property.value, depth + 1);\n if (refusal !== undefined) return;\n }\n } else {\n const prototype: unknown = Object.getPrototypeOf(input);\n\n if (prototype !== null && prototype !== Object.prototype) {\n refusal = \"Malformed\";\n\n return;\n }\n if (keys.length > 64) {\n refusal = \"Oversized\";\n\n return;\n }\n add(2 + Math.max(0, keys.length - 1));\n for (const key of keys) {\n if (typeof key !== \"string\") {\n refusal = \"Malformed\";\n\n return;\n }\n const property = Object.getOwnPropertyDescriptor(input, key);\n\n if (property === undefined || !property.enumerable || !(\"value\" in property)) {\n refusal = \"Malformed\";\n\n return;\n }\n text(key);\n add(1);\n visit(property.value, depth + 1);\n if (refusal !== undefined) return;\n }\n }\n ancestors.delete(input);\n };\n\n try {\n visit(value, 0);\n\n return refusal;\n } catch {\n return \"Malformed\";\n }\n};\n\nconst immutable = <A>(value: A): A => {\n const freeze = (input: unknown): void => {\n if (!Predicate.isObjectKeyword(input) || Object.isFrozen(input)) return;\n for (const child of Object.values(input)) freeze(child);\n Object.freeze(input);\n };\n\n freeze(value);\n\n return value;\n};\n\n/** One connection's bounded journal. Its captured Clock is the owner's original clock. */\nexport const makeStore = (configuration: {\n readonly clock: Clock.Clock;\n readonly originNanos: bigint;\n readonly identity: StoreIdentity;\n readonly limits: Retention;\n /**\n * The clock-domain offset this journal's coverage starts at. A reconnect's journal shares the\n * session clock but holds nothing from before it began; earlier times are another journal's.\n */\n readonly coversFromNanos?: bigint;\n}) => {\n const { clock, originNanos } = configuration;\n const coversFrom = configuration.coversFromNanos ?? 0n;\n const identity = Object.freeze({ ...configuration.identity });\n const limits = Object.freeze({ ...configuration.limits });\n\n const entries: Array<Entry | undefined> = Array.from(\n { length: limits.maxEvents },\n () => undefined,\n );\n\n const readers = new Set<Reader>();\n const maximumAge = BigInt(Math.floor(limits.maxDurationMillis * 1_000_000));\n let head = 0;\n let size = 0;\n let retainedBytes = 0;\n let watermark = 0n;\n let evictedThrough = 0n;\n let evictedAt: bigint | undefined;\n let evicted = 0;\n let terminal: Terminal | null = null;\n\n const cursor = (sequence = watermark): Cursor => Object.freeze({ ...identity, sequence });\n\n const now = (): Stamp =>\n Object.freeze({\n clockId: identity.clockId,\n offsetNanos: clock.monotonicTimeNanosUnsafe() - originNanos,\n });\n\n const entry = (index: number) => entries[(head + index) % limits.maxEvents];\n\n const evict = () => {\n const oldest = entry(0);\n\n if (oldest === undefined) return;\n entries[head] = undefined;\n head = (head + 1) % limits.maxEvents;\n size--;\n retainedBytes -= oldest.bytes;\n evictedThrough = oldest.event.sequence;\n evictedAt = oldest.event.at.offsetNanos;\n evicted++;\n };\n\n const expire = () => {\n const current = now().offsetNanos;\n\n while (size > 0) {\n const oldest = entry(0);\n\n if (oldest === undefined || current - oldest.event.at.offsetNanos <= maximumAge) return;\n evict();\n }\n };\n\n const bounds = () => ({\n oldest: size === 0 ? null : cursor(entry(0)?.event.sequence),\n newest: size === 0 ? null : cursor(entry(size - 1)?.event.sequence),\n resumeAfter: cursor(),\n evictedThrough: cursor(evictedThrough),\n });\n\n const gap = (requested: Selector) => new TimelineGap({ requested, ...bounds() });\n\n const validate = (requested: Selector): TimelineError | undefined => {\n if (\"sequence\" in requested) {\n if (requested.storeId !== identity.storeId)\n return new TimelineCursorError({ reason: \"Store\", requested, current: cursor() });\n if (requested.clockId !== identity.clockId)\n return new TimelineCursorError({ reason: \"Clock\", requested, current: cursor() });\n if (requested.sequence > watermark)\n return new TimelineCursorError({ reason: \"Future\", requested, current: cursor() });\n if (requested.sequence < evictedThrough) return gap(requested);\n } else {\n if (requested.at.clockId !== identity.clockId)\n return new TimelineCursorError({ reason: \"Clock\", requested, current: cursor() });\n if (\n requested.at.offsetNanos < coversFrom ||\n (evictedAt !== undefined && requested.at.offsetNanos <= evictedAt)\n )\n return gap(requested);\n }\n\n return undefined;\n };\n\n const normalize = (requested: unknown): Result.Result<Selector, TimelineError> => {\n if (metadataAdmission(requested, 2048) !== undefined)\n return Result.fail(new TimelineMalformed({}));\n const parsed = decodeSelector(requested, closed);\n\n if (Result.isFailure(parsed)) return Result.fail(new TimelineMalformed({}));\n const selected = immutable(parsed.success);\n const refusal = validate(selected);\n\n return refusal === undefined ? Result.succeed(selected) : Result.fail(refusal);\n };\n\n const viewTerminal = (view: View | undefined) => view?.terminal() ?? terminal;\n\n // An omission that could not keep its attribution may have been any Page's evidence.\n const matches = (event: Event, view: View | undefined) =>\n view === undefined ||\n (event.target === null\n ? event.event._tag === \"MetadataOmitted\"\n : event.target.pageId === view.pageId && event.target.generation === view.generation);\n\n const wake = () => {\n for (const reader of readers) {\n const pending = reader.wake;\n\n reader.wake = undefined;\n // Completing with void would synchronously run consumer work inside native publication.\n if (pending !== undefined) Deferred.doneUnsafe(pending, Effect.yieldNow);\n }\n };\n\n const append = (input: AppendInput): AppendResult => {\n if (terminal !== null) return { _tag: \"Refused\", reason: \"Closed\" };\n const refusal = metadataAdmission(input, limits.maxEventBytes);\n\n if (refusal !== undefined) return { _tag: \"Refused\", reason: refusal };\n const candidate = { ...input, version: 1, ...identity, sequence: watermark + 1n, at: now() };\n const decoded = decodeEvent(candidate, closed);\n\n if (Result.isFailure(decoded)) return { _tag: \"Refused\", reason: \"Malformed\" };\n const encoded = encodeEvent(decoded.success, closed);\n\n if (Result.isFailure(encoded)) return { _tag: \"Refused\", reason: \"Malformed\" };\n const bytes = utf8.encode(JSON.stringify(encoded.success)).byteLength;\n\n if (bytes > limits.maxEventBytes) return { _tag: \"Refused\", reason: \"Oversized\", bytes };\n const event = immutable(decoded.success);\n\n expire();\n while (size >= limits.maxEvents) evict();\n entries[(head + size) % limits.maxEvents] = { event, bytes };\n size++;\n retainedBytes += bytes;\n watermark = event.sequence;\n if (event.event._tag === \"Terminal\" && event.event.scope === \"session\")\n terminal = immutable({\n cursor: cursor(),\n at: event.at,\n scope: event.event.scope,\n reason: event.event.reason,\n });\n while (retainedBytes > limits.maxBytes) evict();\n wake();\n\n return { _tag: \"Appended\", event };\n };\n\n /** Closure is an owner fact even when retention cannot admit its terminal envelope. */\n const finish = (reason: TerminalReason): AppendResult => {\n const result = append({\n target: null,\n correlation: null,\n event: { _tag: \"Terminal\", scope: \"session\", reason },\n });\n\n if (terminal === null) {\n terminal = immutable({ cursor: cursor(), at: now(), scope: \"session\", reason });\n wake();\n }\n\n return result;\n };\n\n const snapshot = Effect.fnUntraced(function* (\n options?: SnapshotOptions,\n view?: View,\n ): Effect.fn.Return<Snapshot, TimelineError> {\n expire();\n let from: Selector | undefined;\n\n if (options !== undefined) {\n if (metadataAdmission(options, 2048) !== undefined) return yield* new TimelineMalformed({});\n const parsed = decodeSnapshotOptions(options, closed);\n\n if (Result.isFailure(parsed)) return yield* new TimelineMalformed({});\n from = parsed.success.from;\n if (from !== undefined) {\n const checked = normalize(from);\n\n if (Result.isFailure(checked)) return yield* checked.failure;\n from = checked.success;\n }\n }\n const events: Event[] = [];\n const ending = viewTerminal(view);\n\n for (let index = 0; index < size; index++) {\n const current = entry(index)?.event;\n\n if (current !== undefined && ending !== null && current.sequence > ending.cursor.sequence)\n break;\n if (current === undefined || !matches(current, view)) continue;\n if (\n from !== undefined &&\n (\"sequence\" in from\n ? current.sequence <= from.sequence\n : current.at.offsetNanos < from.at.offsetNanos)\n )\n continue;\n events.push(current);\n }\n\n return immutable({ events, ...bounds(), evicted, retainedBytes, terminal: ending });\n });\n\n const attach = (\n options: SubscriptionOptions = {},\n ): Result.Result<Subscription, TimelineError> => {\n expire();\n let sequence = watermark;\n let minimumAt: bigint | undefined;\n\n if (options.from !== undefined) {\n const selected = normalize(options.from);\n\n if (Result.isFailure(selected)) return Result.fail(selected.failure);\n if (\"sequence\" in selected.success) sequence = selected.success.sequence;\n else {\n minimumAt = selected.success.at.offsetNanos;\n sequence = evictedThrough;\n }\n }\n if (readers.size >= limits.maxSubscribers)\n return Result.fail(\n new TimelineLimit({ maximum: limits.maxSubscribers, observed: readers.size + 1 }),\n );\n\n const reader: Reader = {\n sequence,\n minimumAt,\n view: options.view,\n wake: undefined,\n released: false,\n };\n\n readers.add(reader);\n\n const release = () => {\n if (reader.released) return;\n reader.released = true;\n readers.delete(reader);\n const pending = reader.wake;\n\n reader.wake = undefined;\n if (pending !== undefined) Deferred.doneUnsafe(pending, Effect.yieldNow);\n };\n\n const pull: Subscription[\"pull\"] = Effect.suspend(() => {\n expire();\n if (reader.sequence < evictedThrough) return Effect.fail(gap(cursor(reader.sequence)));\n if (reader.released) return Cause.done();\n const output: Event[] = [];\n const ending = viewTerminal(reader.view);\n const first = entry(0)?.event.sequence;\n\n // Retained sequences are contiguous from the oldest, so a reader resumes at its own index\n // instead of rescanning the whole ring on every wake.\n for (\n let index =\n first === undefined || reader.sequence < first ? 0 : Number(reader.sequence - first) + 1;\n index < size;\n index++\n ) {\n const current = entry(index)?.event;\n\n if (current === undefined || current.sequence <= reader.sequence) continue;\n if (ending !== null && current.sequence > ending.cursor.sequence) break;\n reader.sequence = current.sequence;\n if (\n (reader.minimumAt === undefined || current.at.offsetNanos >= reader.minimumAt) &&\n matches(current, reader.view)\n )\n output.push(current);\n if (output.length >= 32) break;\n }\n if (output.length > 0) {\n const first = output[0];\n\n if (first !== undefined) return Effect.succeed([first, ...output.slice(1)]);\n }\n if (ending !== null && reader.sequence >= ending.cursor.sequence) return Cause.done();\n reader.wake ??= Deferred.makeUnsafe<void>();\n\n return Deferred.await(reader.wake).pipe(Effect.andThen(pull));\n });\n\n return Result.succeed({\n get cursor() {\n return cursor(reader.sequence);\n },\n pull,\n release,\n });\n };\n\n const subscribe = (\n options?: SubscriptionOptions,\n ): Effect.Effect<Subscription, TimelineError, Scope.Scope> =>\n Effect.acquireRelease(\n Effect.suspend(() => Effect.fromResult(attach(options))),\n (subscription) => Effect.sync(subscription.release),\n );\n\n return { append, finish, snapshot, attach, subscribe, cursor, now };\n};\n","import { Cause, Effect, Exit, Option } from \"effect\";\n\nimport type { BrowserError, InitializationError } from \"../../Errors.ts\";\nimport * as Trace from \"../Trace.ts\";\n\n/** Evidence about this connection, independent of the lifetime of its browser process. */\nexport type ConnectionState = \"closed\" | \"failed\" | \"not-connected\" | \"pending\";\n\n/** Captured teardown operations supplied to the lifetime which owns this connection. */\nexport interface ConnectionCleanup {\n readonly fence: Effect.Effect<void>;\n readonly capture: Effect.Effect<void, BrowserError>;\n readonly initialization: Effect.Effect<void, BrowserError | InitializationError>;\n readonly disconnect: Effect.Effect<ConnectionState, BrowserError>;\n}\n\nexport const noConnection: ConnectionCleanup = {\n fence: Effect.void,\n capture: Effect.void,\n initialization: Effect.void,\n disconnect: Effect.succeed(\"not-connected\"),\n};\n\nexport type CleanupStep<A> =\n | { readonly _tag: \"Success\"; readonly value: A }\n | { readonly _tag: \"Failure\"; readonly reason: \"timeout\" | \"interrupted\" | \"failed\" };\n\nconst timedOut = Symbol(\"BrowserCleanupTimeout\");\n\n/** Every step settles independently, so one failure never suppresses subsequent teardown. */\nexport const cleanupStep = <A, E, R>(\n action: Effect.Effect<A, E, R>,\n timeoutMillis: number,\n): Effect.Effect<CleanupStep<A>, never, R> =>\n action.pipe(\n Effect.interruptible,\n Effect.timeoutOrElse({ duration: timeoutMillis, orElse: () => Effect.fail(timedOut) }),\n Trace.span(\"Browser.cleanup.step\"),\n Effect.exit,\n Effect.map((exit): CleanupStep<A> => {\n if (Exit.isSuccess(exit)) return { _tag: \"Success\", value: exit.value };\n const error = Cause.findErrorOption(exit.cause);\n\n return {\n _tag: \"Failure\",\n reason:\n Option.isSome(error) && error.value === timedOut\n ? \"timeout\"\n : Cause.hasInterrupts(exit.cause)\n ? \"interrupted\"\n : \"failed\",\n };\n }),\n );\n\n/** Bounded host notification; reporting cannot change the cleanup evidence it describes. */\nexport const reported = <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<void> =>\n cleanupStep(effect, 2000).pipe(Effect.asVoid);\n","import type { BrowserOperation } from \"../../Errors.ts\";\n\n/**\n * What the owner spends on an operation: a browser action, a host read, or nothing (inventory,\n * lifecycle, recovery and inspection that sends no input).\n */\nexport type Charge = \"action\" | \"host-read\" | \"none\";\n\n/**\n * The static facts of one operation confined to one exact page: it takes that page's permit, and\n * an unknown outcome is contained by closing that page.\n */\nexport interface PagePolicy {\n readonly work: \"page\";\n /** Dispatching it can change the document, so it retires the page's observations. */\n readonly mutation: boolean;\n readonly charge: Charge;\n /** A page held by `PageControl.suspend` is refused before any native work, never woken. */\n readonly refuseHeld: boolean;\n /** It depends on an initialized document, so it waits for the current one's readiness. */\n readonly ready: boolean;\n /**\n * Recovery work stops or closes what is already in flight: it has its own bounded admission,\n * so a pending navigation's reservation does not refuse it.\n */\n readonly recovery: boolean;\n /** A pending native wait on the page refuses it, as it refuses every mutation. */\n readonly refuseWhileWaiting: boolean;\n}\n\n/**\n * Work on the page inventory: it takes the registry permit, and an unknown outcome fences the\n * owner, since no single page could absorb it.\n */\nexport interface RegistryPolicy {\n readonly work: \"registry\";\n readonly mutation: boolean;\n readonly charge: Charge;\n}\n\n/**\n * `lifecycle`, `capture` and `boundary` operations are admitted elsewhere (the owner's phase\n * changes, the capture module, or a refusal at the public boundary) and never take the page or\n * registry execution path.\n */\nexport type OperationPolicy =\n | PagePolicy\n | RegistryPolicy\n | { readonly work: \"lifecycle\" | \"capture\" | \"boundary\" };\n\nconst onPage = (facts: {\n readonly mutation: boolean;\n readonly charge: Charge;\n readonly refuseHeld: boolean;\n readonly ready: boolean;\n readonly recovery?: true;\n readonly refuseWhileWaiting?: true;\n}): PagePolicy => ({\n work: \"page\",\n recovery: false,\n refuseWhileWaiting: false,\n ...facts,\n});\n\nconst registry = (facts: {\n readonly mutation: boolean;\n readonly charge: Charge;\n}): RegistryPolicy => ({ work: \"registry\", ...facts });\n\nconst lifecycle = { work: \"lifecycle\" } as const;\nconst capture = { work: \"capture\" } as const;\nconst boundary = { work: \"boundary\" } as const;\n\n/** Every operation's policy. A new operation does not compile until its row decides it. */\nexport const OperationPolicies = {\n // configuration and lifetime: the owner's own phase changes\n configure: boundary,\n launch: lifecycle,\n connect: lifecycle,\n reconnect: lifecycle,\n detach: lifecycle,\n disconnect: lifecycle,\n close: lifecycle,\n handoff: lifecycle,\n resume: lifecycle,\n \"live-view\": lifecycle,\n // targets\n target: registry({ mutation: false, charge: \"none\" }),\n handle: boundary,\n \"list-pages\": registry({ mutation: false, charge: \"none\" }),\n \"describe-page\": onPage({ mutation: false, charge: \"none\", refuseHeld: false, ready: false }),\n \"list-frames\": onPage({ mutation: false, charge: \"none\", refuseHeld: false, ready: false }),\n \"select-page\": registry({ mutation: false, charge: \"none\" }),\n // Opening a tab changes the inventory, not any page's document.\n \"new-page\": registry({ mutation: true, charge: \"none\" }),\n \"close-page\": onPage({\n mutation: true,\n charge: \"none\",\n refuseHeld: false,\n ready: false,\n recovery: true,\n }),\n resize: onPage({ mutation: true, charge: \"none\", refuseHeld: true, ready: false }),\n // reading\n ready: onPage({ mutation: false, charge: \"none\", refuseHeld: false, ready: false }),\n observe: onPage({\n mutation: false,\n charge: \"action\",\n refuseHeld: true,\n ready: true,\n refuseWhileWaiting: true,\n }),\n checkpoint: onPage({ mutation: false, charge: \"host-read\", refuseHeld: true, ready: true }),\n \"control-facts\": onPage({ mutation: false, charge: \"host-read\", refuseHeld: true, ready: true }),\n revalidate: onPage({ mutation: false, charge: \"none\", refuseHeld: true, ready: true }),\n \"read-text\": onPage({ mutation: false, charge: \"action\", refuseHeld: true, ready: true }),\n screenshot: onPage({ mutation: false, charge: \"action\", refuseHeld: true, ready: true }),\n wait: onPage({ mutation: false, charge: \"action\", refuseHeld: true, ready: true }),\n resolve: onPage({ mutation: false, charge: \"host-read\", refuseHeld: true, ready: false }),\n // A plan's own reads (preconditions and postconditions) are host reads of its page.\n run: onPage({ mutation: false, charge: \"host-read\", refuseHeld: true, ready: false }),\n settled: onPage({ mutation: false, charge: \"action\", refuseHeld: true, ready: false }),\n // input\n navigate: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: false }),\n \"navigate-stop\": onPage({\n mutation: true,\n charge: \"none\",\n refuseHeld: false,\n ready: false,\n recovery: true,\n }),\n click: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n fill: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"fill-form\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"select-option\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: false }),\n scroll: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"click-and-wait\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"download-action\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"select-files\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"file-chooser\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"action-result\": boundary,\n // native pointer input\n \"pointer-move\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n hover: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n wheel: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n // native key input\n press: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n type: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n // page control acts on a held page, so it never refuses one\n \"page-control\": boundary,\n \"page-state\": onPage({ mutation: false, charge: \"none\", refuseHeld: false, ready: false }),\n \"page-suspend\": onPage({\n mutation: false,\n charge: \"none\",\n refuseHeld: false,\n ready: false,\n refuseWhileWaiting: true,\n }),\n \"page-resume\": onPage({\n mutation: false,\n charge: \"none\",\n refuseHeld: false,\n ready: false,\n refuseWhileWaiting: true,\n }),\n // capture\n capture,\n \"capture-start\": capture,\n \"capture-stop\": capture,\n \"capture-consume\": capture,\n} as const satisfies Record<BrowserOperation, OperationPolicy>;\n\ntype Policies = typeof OperationPolicies;\n\n/** Operations confined to one exact page. */\nexport type PageOperation = {\n readonly [K in BrowserOperation]: Policies[K] extends PagePolicy ? K : never;\n}[BrowserOperation];\n\n/** Operations on the page inventory. */\nexport type RegistryOperation = {\n readonly [K in BrowserOperation]: Policies[K] extends RegistryPolicy ? K : never;\n}[BrowserOperation];\n\n/** Operations the session executes through its one page and registry path. */\nexport type ExecutedOperation = PageOperation | RegistryOperation;\n\nexport const policyOf = (operation: ExecutedOperation): PagePolicy | RegistryPolicy =>\n OperationPolicies[operation];\n","import { Deferred, Effect } from \"effect\";\n\nimport type { AdmissionStatus } from \"../../Browser.ts\";\nimport type { AdmissionLimits } from \"../../BrowserData.ts\";\nimport { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type { DriverTarget } from \"./Driver.ts\";\n\nexport interface NativeWait {\n readonly connection: object;\n readonly target: DriverTarget;\n readonly cancel: (reason?: BrowserError[\"reason\"]) => void;\n readonly retire: () => void;\n pending: boolean;\n}\n\nexport interface PendingAdmission {\n readonly token: object;\n readonly operation: BrowserOperation;\n readonly deadline: number;\n readonly requestedAt: number;\n readonly queueDeadline: number;\n readonly result: Deferred.Deferred<void, BrowserError>;\n readonly reserved: boolean;\n}\n\n/** Native ownership survives generation changes and caller cancellation. */\nexport interface NativePageCapacity {\n readonly work: ReadonlySet<object>;\n readonly wait?: NativeWait;\n readonly stopSetupPending?: Deferred.Deferred<void>;\n /** The connection whose positive retirement may release `stopSetupPending`. */\n readonly stopSetupConnection?: object;\n}\n\n/**\n * One page's caller ownership and retained native capacity share this record. Callers read it;\n * only admission's own operations change it.\n */\nexport interface AdmissionLane {\n readonly pageId?: string;\n readonly generation: number;\n readonly pending: ReadonlyArray<PendingAdmission>;\n readonly native: NativePageCapacity;\n readonly revision: number;\n readonly holder?: object;\n readonly active?: {\n readonly controller: AbortController;\n readonly operation: BrowserOperation;\n };\n readonly reservation?: AbortController;\n readonly recovery?: AdmissionLane;\n readonly closure?: AdmissionLane;\n readonly revoked: boolean;\n readonly retired: boolean;\n}\n\ninterface CapacityState {\n readonly work: Set<object>;\n wait?: NativeWait;\n stopSetupPending?: Deferred.Deferred<void>;\n stopSetupConnection?: object;\n}\n\ninterface LaneState {\n readonly pageId?: string;\n readonly generation: number;\n readonly pending: Array<PendingAdmission>;\n readonly native: CapacityState;\n revision: number;\n holder?: object;\n active?: { readonly controller: AbortController; readonly operation: BrowserOperation };\n reservation?: AbortController;\n recovery?: LaneState;\n closure?: LaneState;\n revoked: boolean;\n retired: boolean;\n}\n\nexport const makeAdmission = (\n now: () => number,\n expired: () => boolean,\n limits: AdmissionLimits = {},\n /** Called after work leaves admission, once its bookkeeping is complete. */\n settled: () => void = () => {},\n) => {\n const pages = new Map<string, LaneState>();\n const retained = new Set<LaneState>();\n // Every lane this admission made, by identity: callers hold the read-only view of each one.\n const owned = new WeakMap<AdmissionLane, LaneState>();\n\n const own = (lane: LaneState): LaneState => {\n owned.set(lane, lane);\n\n return lane;\n };\n\n const state = (lane: AdmissionLane): LaneState => {\n const found = owned.get(lane);\n\n if (found === undefined) throw new TypeError(\"Admission lane belongs to another admission\");\n\n return found;\n };\n\n const registry = own({\n generation: 0,\n pending: [],\n native: { work: new Set() },\n revision: 0,\n revoked: false,\n retired: false,\n });\n\n const maximumPage = limits.pendingPerPage ?? 32;\n const maximumSession = limits.pendingPerSession ?? 128;\n const maximumNative = 128;\n let pendingCount = 0;\n\n const native = new Map<\n object,\n {\n readonly lane: LaneState;\n readonly connection?: object;\n /** Whether this unsettled native call can still change its page. */\n readonly occupies: () => boolean;\n }\n >();\n\n const error = (operation: BrowserOperation, reason: BrowserError[\"reason\"]) =>\n BrowserError.make({ operation, reason, outcome: \"undispatched\" });\n\n /**\n * Native work outlives its caller. Work that dispatched input keeps its page until it settles;\n * a read, or a mutation whose caller left before dispatch, can no longer change the page.\n */\n const occupied = (capacity: CapacityState) =>\n [...capacity.work].some((token) => native.get(token)?.occupies() !== false);\n\n const available = (lane: LaneState) => lane.holder === undefined && !occupied(lane.native);\n\n const forgetState = (lane: LaneState) => {\n if (\n !lane.retired ||\n lane.native.work.size > 0 ||\n lane.holder !== undefined ||\n lane.native.stopSetupPending !== undefined ||\n lane.native.wait !== undefined ||\n lane.reservation !== undefined\n )\n return;\n retained.delete(lane);\n if (lane.pageId !== undefined && pages.get(lane.pageId) === lane) pages.delete(lane.pageId);\n };\n\n const next = (lane: LaneState) => {\n if (!available(lane) || lane.revoked) return;\n while (lane.pending.length > 0) {\n const head = lane.pending.shift();\n\n if (head === undefined) return;\n if (!head.reserved) pendingCount--;\n const time = now();\n\n const refusal = expired()\n ? Reasons.Expired.make({})\n : time >= head.deadline\n ? Reasons.Timeout.make({})\n : time >= head.queueDeadline\n ? Reasons.QueueExpired.make({})\n : undefined;\n\n if (refusal !== undefined) {\n Deferred.doneUnsafe(head.result, Effect.fail(error(head.operation, refusal)));\n continue;\n }\n // The next caller owns admission before it wakes. A fresh arrival cannot barge.\n lane.holder = head.token;\n Deferred.doneUnsafe(head.result, Effect.void);\n\n return;\n }\n };\n\n const releaseState = (lane: LaneState, token: object) => {\n if (lane.holder !== token) return;\n lane.holder = undefined;\n next(lane);\n forgetState(lane);\n settled();\n };\n\n const cancelState = (lane: LaneState, pending: PendingAdmission) => {\n const index = lane.pending.indexOf(pending);\n\n if (index >= 0) {\n lane.pending.splice(index, 1);\n if (!pending.reserved) pendingCount--;\n next(lane);\n } else releaseState(lane, pending.token);\n };\n\n const revokeState = (lane: LaneState, reason: BrowserError[\"reason\"]) => {\n lane.revoked = true;\n lane.active?.controller.abort();\n const pending = lane.pending.splice(0);\n\n pendingCount -= pending.filter((waiter) => !waiter.reserved).length;\n for (const waiter of pending)\n Deferred.doneUnsafe(waiter.result, Effect.fail(error(waiter.operation, reason)));\n };\n\n const snapshot = (lane: AdmissionLane): AdmissionStatus =>\n Object.freeze({\n active: lane.active?.operation ?? null,\n waiting: lane.pending.length,\n maximum: maximumPage,\n oldestWaitMillis:\n lane.pending[0] === undefined ? null : Math.max(0, now() - lane.pending[0].requestedAt),\n nativePending: lane.native.work.size,\n nativeWaitPending: lane.native.wait !== undefined,\n stopSetupPending: lane.native.stopSetupPending !== undefined,\n });\n\n /** Ends a navigation stop's setup on its capacity, if it is still the current one. */\n const clearStopSetup = (capacity: CapacityState) => {\n const setup = capacity.stopSetupPending;\n\n capacity.stopSetupPending = undefined;\n capacity.stopSetupConnection = undefined;\n if (setup !== undefined) Deferred.doneUnsafe(setup, Effect.void);\n };\n\n const wake = (capacity: CapacityState) => {\n for (const waiting of [registry, ...retained]) if (waiting.native === capacity) next(waiting);\n };\n\n const registryView: AdmissionLane = registry;\n\n return {\n registry: registryView,\n snapshot,\n status: () =>\n Object.freeze({\n waiting: pendingCount,\n maximum: maximumSession,\n nativePending: native.size,\n nativeMaximum: maximumNative,\n nativeWaits: new Set(\n [registry, ...retained]\n .map((lane) => lane.native)\n .filter((capacity) => capacity.wait !== undefined),\n ).size,\n stopSetups: new Set(\n [registry, ...retained]\n .map((lane) => lane.native)\n .filter((capacity) => capacity.stopSetupPending !== undefined),\n ).size,\n registry: snapshot(registry),\n }),\n /** The page's current lane, if it has one. */\n lane: (pageId: string): AdmissionLane | undefined => pages.get(pageId),\n lanes: (): ReadonlyArray<AdmissionLane> => [registry, ...retained],\n page: (pageId: string, generation: number): AdmissionLane => {\n const previous = pages.get(pageId);\n\n if (previous?.generation === generation) return previous;\n if (previous !== undefined) previous.retired = true;\n\n const lane = own({\n pageId,\n generation,\n pending: [],\n native: previous?.native ?? { work: new Set() },\n revision: previous?.revision ?? 0,\n revoked: false,\n retired: false,\n });\n\n pages.set(pageId, lane);\n retained.add(lane);\n if (previous !== undefined) forgetState(previous);\n\n return lane;\n },\n recovery: (lane: AdmissionLane, operation: BrowserOperation): AdmissionLane => {\n const page = state(lane);\n const key = operation === \"close-page\" ? \"closure\" : \"recovery\";\n const previous = page[key];\n\n if (previous !== undefined) {\n if (key === \"closure\" && !previous.retired && !page.retired) previous.revoked = false;\n\n return previous;\n }\n\n const recovery = own({\n ...(page.pageId === undefined ? {} : { pageId: page.pageId }),\n generation: page.generation,\n pending: [],\n native: { work: new Set() },\n revision: page.revision,\n revoked: false,\n retired: false,\n });\n\n page[key] = recovery;\n retained.add(recovery);\n\n return recovery;\n },\n acquire: (lane: AdmissionLane, pending: PendingAdmission, queueMillis: number) => {\n const owner = state(lane);\n\n if (owner.revoked) return Effect.fail(error(pending.operation, Reasons.Stale.make({})));\n if (available(owner) && owner.pending.length === 0) {\n owner.holder = pending.token;\n\n return Effect.void;\n }\n if (queueMillis <= 0) return Effect.fail(error(pending.operation, Reasons.Busy.make({})));\n\n if (pending.reserved && owner.pending.length >= 1)\n return Effect.fail(error(pending.operation, Reasons.Busy.make({})));\n\n const scope =\n pendingCount >= maximumSession\n ? \"session\"\n : owner.pageId === undefined\n ? \"registry\"\n : \"page\";\n\n if (\n !pending.reserved &&\n (pendingCount >= maximumSession || owner.pending.length >= maximumPage)\n )\n return Effect.fail(\n error(\n pending.operation,\n Reasons.QueueFull.make({\n scope,\n maximum: scope === \"session\" ? maximumSession : maximumPage,\n observed: (scope === \"session\" ? pendingCount : owner.pending.length) + 1,\n }),\n ),\n );\n owner.pending.push(pending);\n if (!pending.reserved) pendingCount++;\n\n return Deferred.await(pending.result);\n },\n cancel: (lane: AdmissionLane, pending: PendingAdmission) => cancelState(state(lane), pending),\n release: (lane: AdmissionLane, token: object) => releaseState(state(lane), token),\n forget: (lane: AdmissionLane) => forgetState(state(lane)),\n revoke: (lane: AdmissionLane, reason: BrowserError[\"reason\"]) =>\n revokeState(state(lane), reason),\n /** A page whose quarantine an operator released admits work again. */\n restore: (pageId: string) => {\n const lane = pages.get(pageId);\n\n if (lane !== undefined) lane.revoked = false;\n },\n /** Observation evidence on these pages (all of them without a page) is out of date. */\n revise: (pageId?: string) => {\n for (const lane of pages.values())\n if (pageId === undefined || lane.pageId === pageId) lane.revision++;\n },\n /** The admitted operation now running in this lane, until `deactivate`. */\n activate: (lane: AdmissionLane, controller: AbortController, operation: BrowserOperation) => {\n state(lane).active = { controller, operation };\n },\n deactivate: (lane: AdmissionLane, controller: AbortController) => {\n const owner = state(lane);\n\n if (owner.active?.controller === controller) owner.active = undefined;\n },\n /** A dispatched navigation's claim on its page, held until it settles or a fence aborts it. */\n reserve: (lane: AdmissionLane, controller: AbortController) => {\n state(lane).reservation = controller;\n },\n /** Clears the lane's reservation if it is still `controller`; false when it was replaced. */\n settleReservation: (lane: AdmissionLane, controller: AbortController): boolean => {\n const owner = state(lane);\n\n if (owner.reservation !== controller) return false;\n owner.reservation = undefined;\n\n return true;\n },\n /** Removes and returns the lane's reservation, for the caller to abort or settle. */\n takeReservation: (lane: AdmissionLane): AbortController | undefined => {\n const owner = state(lane);\n const reservation = owner.reservation;\n\n owner.reservation = undefined;\n\n return reservation;\n },\n /** A pure wait owns its page's single wait slot until `endWait`. */\n beginWait: (lane: AdmissionLane, wait: NativeWait) => {\n state(lane).native.wait = wait;\n },\n endWait: (wait: NativeWait) => {\n for (const lane of [registry, ...retained]) {\n if (lane.native.wait !== wait) continue;\n lane.native.wait = undefined;\n forgetState(lane);\n }\n },\n /**\n * Installs a navigation stop's setup on the lane's native capacity for `connection`. Returns\n * undefined while another setup is pending; otherwise its settle, which clears the setup if\n * it is still current and releases anyone waiting for it.\n */\n beginStopSetup: (lane: AdmissionLane, connection: object | undefined) => {\n const capacity = state(lane).native;\n\n if (capacity.stopSetupPending !== undefined) return undefined;\n const setup = Deferred.makeUnsafe<void>();\n\n capacity.stopSetupPending = setup;\n capacity.stopSetupConnection = connection;\n\n return () => {\n if (capacity.stopSetupPending === setup) {\n capacity.stopSetupPending = undefined;\n capacity.stopSetupConnection = undefined;\n }\n Deferred.doneUnsafe(setup, Effect.void);\n };\n },\n blockPending: (reason: BrowserError[\"reason\"]) => {\n for (const lane of [registry, ...retained]) {\n const pending = lane.pending.filter((waiter) => !waiter.reserved);\n\n if (pending.length === 0) continue;\n for (const waiter of pending) lane.pending.splice(lane.pending.indexOf(waiter), 1);\n\n pendingCount -= pending.length;\n for (const waiter of pending)\n Deferred.doneUnsafe(waiter.result, Effect.fail(error(waiter.operation, reason)));\n }\n },\n fence: (reason: BrowserError[\"reason\"]) => {\n // Registry ownership belongs to the transition that performed the fence.\n for (const lane of retained) {\n lane.retired = true;\n revokeState(lane, reason);\n }\n registry.active?.controller.abort();\n const pending = registry.pending.splice(0);\n\n pendingCount -= pending.filter((waiter) => !waiter.reserved).length;\n for (const waiter of pending)\n Deferred.doneUnsafe(waiter.result, Effect.fail(error(waiter.operation, reason)));\n for (const lane of retained) forgetState(lane);\n },\n retainNative: (\n lane: AdmissionLane,\n operation: BrowserOperation,\n connection?: object,\n occupies: () => boolean = () => true,\n ) => {\n const owner = state(lane);\n\n if (native.size >= maximumNative)\n throw error(\n operation,\n Reasons.Limit.make({\n dimension: \"native-operations\",\n maximum: maximumNative,\n observed: native.size,\n }),\n );\n const token = {};\n\n owner.native.work.add(token);\n native.set(token, {\n lane: owner,\n occupies,\n ...(connection === undefined ? {} : { connection }),\n });\n\n return () => {\n if (!native.delete(token)) return;\n owner.native.work.delete(token);\n wake(owner.native);\n forgetState(owner);\n settled();\n };\n },\n retirePage: (pageId: string) => {\n for (const lane of retained) {\n if (lane.pageId !== pageId) continue;\n for (const token of lane.native.work) native.delete(token);\n lane.native.work.clear();\n clearStopSetup(lane.native);\n lane.revoked = true;\n lane.retired = true;\n forgetState(lane);\n next(lane);\n }\n pages.delete(pageId);\n settled();\n },\n retire: () => {\n native.clear();\n for (const lane of [registry, ...retained]) {\n lane.native.work.clear();\n clearStopSetup(lane.native);\n forgetState(lane);\n }\n settled();\n },\n retireConnection: (connection: object) => {\n for (const lane of [registry, ...retained]) {\n // Only the setup's own connection may release it, even when that retirement arrives\n // after a successor connection has used the same page.\n if (lane.native.stopSetupConnection !== connection) continue;\n clearStopSetup(lane.native);\n forgetState(lane);\n }\n for (const [token, lease] of native) {\n if (lease.connection !== connection) continue;\n native.delete(token);\n lease.lane.native.work.delete(token);\n wake(lease.lane.native);\n forgetState(lease.lane);\n }\n settled();\n },\n /**\n * Only native work that can still change a page must settle. A `held` lane belongs to an\n * operator's quarantine, whose own work, including a pending stop setup, cannot hold up the\n * handoff that releases it.\n */\n drained: (except?: AbortSignal, held: (lane: AdmissionLane) => boolean = () => false) =>\n [...native.values()].every((lease) => !lease.occupies() || held(lease.lane)) &&\n [registry, ...retained].every(\n (lane) =>\n (lane.native.stopSetupPending === undefined || held(lane)) &&\n (lane.holder === undefined ||\n (except !== undefined && lane.active?.controller.signal === except)),\n ),\n };\n};\n","import { Cause, Clock, Deferred, Duration, Effect, Exit, Option, Schema } from \"effect\";\n\nimport type { OperationOptions } from \"../../Browser.ts\";\nimport {\n BrowserDiagnostic,\n BrowserDiagnostics,\n type ObservedElement,\n type InputReceipt,\n type AdmissionLimits,\n SessionStatus,\n type SessionReason,\n type SessionPhase,\n} from \"../../BrowserData.ts\";\nimport {\n BrowserError,\n Reasons,\n type BrowserOperation,\n type BrowserOutcome,\n type BrowserReason,\n type Containment,\n} from \"../../Errors.ts\";\nimport type { AcknowledgementFact, SettledEvidence } from \"../../PlanData.ts\";\nimport type { Correlation } from \"../../TimelineData.ts\";\nimport * as Trace from \"../Trace.ts\";\nimport { makeAdmission } from \"./Admission.ts\";\nimport type { DriverFault, DriverTarget } from \"./Driver.ts\";\nimport { NativeEffectFailure, providerReason, publicError } from \"./NativeCalls.ts\";\nimport { grantedPacing } from \"./NativePacing.ts\";\nimport type { DescriptorSample, ResolvedElement } from \"./Observation.ts\";\nimport type { PerformancePlan } from \"./Performance.ts\";\n\nexport interface NativePictureBoundary {\n readonly phase: \"Requested\" | \"Returned\";\n readonly target: DriverTarget;\n readonly documentEpoch: number;\n readonly geometry: { readonly width: number; readonly height: number };\n readonly byteLength?: number;\n}\n\n/** One native scroll a driver performed for an admitted operation. */\nexport interface ScrollFacts {\n readonly target: DriverTarget;\n readonly x?: number;\n readonly y?: number;\n readonly qualification?: \"exact-node-scroll-into-view\";\n readonly startedMonotonicNanos: bigint;\n readonly completedMonotonicNanos: bigint;\n}\n\n/** The pointer path a driver intends for an admitted operation, before the pointer moves. */\nexport interface GlideFacts {\n readonly target: DriverTarget;\n readonly startedMonotonicNanos: bigint;\n readonly samples: ReadonlyArray<{\n readonly offsetMillis: number;\n readonly position: { readonly x: number; readonly y: number };\n }>;\n}\n\n/** How much logical keyboard input a press or type receipt carried. */\nexport interface KeyCount {\n readonly count: number;\n readonly countUnit: \"unicode-codepoints\" | \"logical-strokes\";\n}\n\n/**\n * One fact about one operation. Its ticket emits each fact once, to every listener, and decides\n * once whether the fact is late: whether it arrived after the operation ended (for any fact but\n * the end itself), after the operation was given up, or past its deadline. `Finished` is the\n * only fact of an operation that was refused before it was admitted.\n */\nexport type OperationEvent =\n | {\n readonly _tag: \"Phase\";\n readonly phase: Exclude<NonNullable<Ticket[\"phase\"]>, \"Terminal\">;\n /** Whether the phase sends a native command or acknowledges the one pending. */\n readonly mutation: boolean;\n readonly acknowledgement?: AcknowledgementFact;\n readonly late: boolean;\n readonly atMonotonicNanos: bigint;\n }\n | {\n readonly _tag: \"Terminal\";\n /** The owner's classification of everything this operation's native commands did. */\n readonly outcome: BrowserOutcome;\n readonly containment: Containment;\n readonly late: boolean;\n readonly atMonotonicNanos: bigint;\n }\n | { readonly _tag: \"Picture\"; readonly boundary: NativePictureBoundary }\n | { readonly _tag: \"Input\"; readonly receipt: InputReceipt; readonly keys?: KeyCount }\n | {\n readonly _tag: \"Scroll\";\n readonly facts: ScrollFacts;\n /** The connection generation the scrolling ticket was admitted under. */\n readonly generation: number;\n readonly late: boolean;\n }\n | { readonly _tag: \"Glide\"; readonly facts: GlideFacts }\n | { readonly _tag: \"Settled\"; readonly evidence: SettledEvidence; readonly target: DriverTarget }\n | {\n readonly _tag: \"Finished\";\n readonly kind: \"Completed\" | \"Failed\" | \"Cancelled\";\n readonly outcome: BrowserOutcome;\n readonly error?: BrowserError;\n readonly containment: Containment;\n };\n\n/** What a listener learns about one operation before its first event. */\nexport interface OperationFacts {\n readonly operation: BrowserOperation;\n readonly operationId: string;\n readonly generation: number;\n readonly scope: ObservationScope | undefined;\n readonly correlation: Correlation | null;\n}\n\n/**\n * Subscribes to operations: called once for each one the owner guards, it returns the receiver\n * of that operation's events. Listeners observe; they grant no authority.\n */\nexport type OperationListener = (operation: OperationFacts) => (event: OperationEvent) => void;\n\nconst outcomeRank: Record<BrowserOutcome, number> = {\n undispatched: 0,\n rejected: 1,\n performed: 2,\n unknown: 3,\n};\n\n/**\n * What is known about input never weakens: an unknown outcome stays unknown, acknowledged input\n * stays performed, and refused preparation stays rejected, whichever evidence says so.\n */\nexport const strongestOutcome = (left: BrowserOutcome, right: BrowserOutcome): BrowserOutcome =>\n outcomeRank[right] > outcomeRank[left] ? right : left;\n\n/** The browser domain's bounded step: one deadline, one declared BrowserError timeout. */\nexport const within = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n deadline: number,\n onTimeout: () => BrowserError,\n): Effect.Effect<A, E | BrowserError, R> =>\n Effect.gen(function* () {\n const now = Number(yield* Clock.monotonicTimeNanos) / 1_000_000;\n\n return yield* deadline <= now\n ? Effect.fail(onTimeout())\n : effect.pipe(\n Effect.timeoutOrElse({\n duration: Duration.millis(deadline - now),\n orElse: () => Effect.fail(onTimeout()),\n }),\n );\n });\n\nexport type Phase = SessionPhase;\n\nexport type Invalidation =\n | \"observation\"\n | \"target-changed\"\n | \"resized\"\n | \"paused\"\n | \"disconnected\"\n | \"uncertain\"\n | \"closed\";\n\n/**\n * Observation retirement is independent of the owner's revision and connection fences. A frame\n * narrows a page: an observation holds nodes of the one frame it read, so another frame of the\n * page navigating or detaching (an advertisement reloading, say) changes nothing it names.\n */\nexport type ObservationScope =\n | \"all\"\n | \"none\"\n | { readonly pageId: string; readonly frameId?: string };\n\n/** A bounded native reading has no mutation dispatch authority. */\nexport interface ReadTicket {\n readonly signal: AbortSignal;\n readonly deadline: number;\n readonly generation: number;\n readonly remainingMillis: () => number;\n check(): void;\n}\n\n/** What a performed operation asks of the owner: its seeded plan and, in a form, its field. */\nexport interface PerformanceRequest {\n readonly plan: PerformancePlan;\n readonly fieldIndex?: number;\n}\n\n/**\n * A performed admission: the request, plus the original owner's clock, deadline and sleep, which\n * the owner grants every performed ticket. A plain ticket has none of them.\n */\nexport interface Performance extends PerformanceRequest {\n /** The original owner's monotonic clock. */\n readonly now: () => bigint;\n /** Exact original-owner time left; native SDK timeouts retain their separate millisecond floor. */\n readonly remainingTimeNanos: () => bigint;\n /** Original-owner sleep, bounded by this admission and fenced before and after waiting. */\n readonly pauseUntil: (atNanos: bigint) => Promise<void>;\n}\n\n/** One admitted native operation; checks at dispatch also fence late Promise continuations. */\nexport interface Ticket extends ReadTicket {\n /** Present exactly when the operation is performed, with the owner's pacing. */\n readonly performance?: Performance;\n readonly operationId?: string;\n readonly picture?: (boundary: NativePictureBoundary) => void;\n readonly recordInput?: (receipt: InputReceipt, keys?: KeyCount) => void;\n readonly recordScroll?: (facts: ScrollFacts) => void;\n readonly recordGlide?: (facts: GlideFacts) => void;\n readonly recordSettled?: (evidence: SettledEvidence, target: DriverTarget) => void;\n /** Native work keeps capacity until settlement, independently of the request fiber. */\n readonly retainNative?: () => () => void;\n readonly dispatched: boolean;\n /** Original phase-aware native outcome; preparatory acknowledgement is not logical success. */\n readonly outcome?: BrowserOutcome;\n readonly phase?: \"Prepared\" | \"Dispatched\" | \"Acknowledged\" | \"FollowUp\" | \"Terminal\";\n /** Actual owner's containment, including pure interruption without a typed failure. */\n readonly containment?: Containment;\n dispatch(): void;\n /** Called only for positive completion of all native commands in the current mutation phase. */\n acknowledge?(fact?: AcknowledgementFact): void;\n followUp?(): void;\n /** Facts from the checked node immediately before dispatch; no separate recording read. */\n readonly captureTarget?: (\n target: string | ObservedElement | ResolvedElement,\n sample: DescriptorSample | undefined,\n ) => void;\n}\n\n/**\n * A composite operation's own evidence about the operations it admits: their correlation, its\n * subscription to their events, and the exact targets they checked. Never dispatch authority.\n */\nexport interface ExecutionEvidence {\n readonly correlation?: () => Correlation | null;\n readonly listener?: OperationListener;\n readonly target?: NonNullable<Ticket[\"captureTarget\"]>;\n}\n\n/** The driver retires native capacity only after its wait and required handle disposal settle. */\nexport interface WaitTicket extends ReadTicket {\n invalidate(): void;\n retire(): void;\n}\n\nexport interface OwnedWait {\n readonly ticket: WaitTicket;\n readonly completed: Effect.Effect<void, BrowserError>;\n readonly start: (body: () => Promise<void>) => void;\n readonly cancel: (reason?: BrowserError[\"reason\"]) => void;\n}\n\n/**\n * A dispatched mutation the browser is still performing after its permit was released: an\n * in-flight navigation. It keeps other mutations off that page while reads, holds and other\n * pages proceed. Like a permit it cannot be dropped silently: only a known outcome releases it.\n */\nexport interface Reservation {\n /** Aborted by any fence, so work that outlives its connection is never treated as current. */\n readonly signal: AbortSignal;\n /** `unknown` fences the owner, exactly as a mutation interrupted after dispatch does. */\n readonly settle: (outcome: \"known\" | \"unknown\") => void;\n}\n\nexport interface Limits {\n readonly admissionLimits?: AdmissionLimits;\n readonly maxActions: number;\n readonly maxHostReads: number;\n readonly maxElapsedMillis: number;\n readonly actionTimeoutMillis: number;\n}\n\n/** One span per public operation attempt, from validation to its terminal outcome. */\nexport const operationSpan = (operation: BrowserOperation) =>\n Trace.span(`Browser.${operation}`, { attributes: { \"browser.operation\": operation } });\n\nexport const makeOwner = Effect.fnUntraced(function* (limits: Limits) {\n const clock = yield* Clock.Clock;\n let listener: OperationListener | undefined;\n let observePhase: ((phase: Phase) => void) | undefined;\n let operationSequence = 0n;\n\n const lifetimeDeadline =\n Number(yield* Clock.monotonicTimeNanos) / 1_000_000 + limits.maxElapsedMillis;\n\n const hooks = new Set<\n (reason: Invalidation, scope: ObservationScope, origin?: AbortSignal) => void\n >();\n\n const state = {\n phase: \"acquiring\" as Phase,\n generation: 0,\n revision: 0,\n actions: 0,\n hostReads: 0,\n };\n\n let admissionBarrier: object | undefined;\n let nativeConnection: object | undefined;\n // Completed once whenever work settles, so a handoff's drain waits for a change, not a timer.\n let change = Deferred.makeUnsafe<void>();\n\n const changed = () => {\n const previous = change;\n\n change = Deferred.makeUnsafe<void>();\n Deferred.doneUnsafe(previous, Effect.void);\n };\n\n const admission = makeAdmission(\n () => Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000,\n () => terminalReason === \"expired\",\n limits.admissionLimits,\n () => changed(),\n );\n\n const waits = () =>\n new Set(\n admission\n .lanes()\n .flatMap((lane) => (lane.native.wait === undefined ? [] : [lane.native.wait])),\n );\n\n const waitOn = (pageId: string) => admission.lane(pageId)?.native.wait;\n // These facts outlive the tickets which produced them. Aborting admission is not retirement.\n const unresolved = new Map<object, string | undefined>();\n let nativeUncertainty = false;\n let terminalReason: SessionReason | null = null;\n let pauseReason: SessionReason | null = null;\n const policies = new Map<object, Extract<DriverFault, { readonly source: \"policy\" }>>();\n // Pages a popup/dialog policy paused: an operator, not containment, decides their work.\n const quarantined = new Set<string>();\n const records: Array<BrowserDiagnostics[\"records\"][number]> = [];\n let total = 0;\n let dropped = 0;\n\n const record = (\n reason: SessionReason,\n disposition: BrowserDiagnostics[\"records\"][number][\"disposition\"],\n generation = state.generation,\n ) => {\n total = Math.min(Number.MAX_SAFE_INTEGER, total + 1);\n if (records.length === 32) {\n records.shift();\n dropped = Math.min(Number.MAX_SAFE_INTEGER, dropped + 1);\n }\n records.push(\n Object.freeze(\n BrowserDiagnostic.make({\n reason,\n disposition,\n generation,\n monotonicNanos: clock.monotonicTimeNanosUnsafe(),\n }),\n ),\n );\n };\n\n /**\n * Why admission refuses work in the owner's present state, or undefined when it would admit it.\n * Both of the guard's admission checks and stale-capability reporting share this one answer,\n * so a pending policy cleanup reports busy only while the session can still recover.\n */\n const refusal = (\n options: {\n readonly phases?: ReadonlyArray<Phase>;\n readonly recovery?: boolean;\n readonly bypassBlocked?: boolean;\n } = {},\n ): BrowserReason | undefined => {\n const blocked = admissionBarrier !== undefined && options.bypassBlocked !== true;\n\n if (\n (options.phases ?? [\"open\"]).includes(state.phase) &&\n (policies.size === 0 || options.recovery === true) &&\n (!blocked || options.recovery === true)\n )\n return undefined;\n\n return terminalReason === \"expired\"\n ? Reasons.Expired.make({})\n : state.phase === \"paused\" || blocked || (terminalReason === null && policies.size > 0)\n ? Reasons.Busy.make({})\n : Reasons.Closed.make({});\n };\n\n const transition = (phase: Phase) => {\n if (\n (terminalReason !== null || state.phase === \"closed\" || state.phase === \"closing\") &&\n phase !== \"closing\" &&\n phase !== \"closed\"\n )\n return;\n const changed = state.phase !== phase;\n\n state.phase = phase;\n if (phase === \"open\") pauseReason = null;\n if (changed) observePhase?.(state.phase);\n };\n\n const invalidate = (\n reason: Invalidation,\n scope: ObservationScope = \"all\",\n origin?: AbortSignal,\n ) => {\n for (const waiting of waits())\n if (scope === \"all\" || (scope !== \"none\" && scope.pageId === waiting.target.pageId))\n waiting.cancel(Reasons.Stale.make({}));\n if (scope === \"all\") admission.revise();\n else if (scope !== \"none\") admission.revise(scope.pageId);\n state.revision++;\n for (const hook of hooks) hook(reason, scope, origin);\n };\n\n const fence = (phase: Phase, reason: Invalidation, trigger?: SessionReason) => {\n if (\n state.phase === \"closed\" ||\n (state.phase === \"closing\" && phase !== \"closed\" && phase !== \"closing\")\n )\n return;\n if (phase === \"uncertain\" || phase === \"faulted\" || phase === \"closing\" || phase === \"closed\")\n terminalReason ??= trigger ?? (phase === \"uncertain\" ? \"native-failure\" : \"closed\");\n else if (trigger !== undefined) pauseReason = trigger;\n // A known trigger is retained even when the abort below interrupts dispatched work.\n const previous = state.phase;\n\n if (!(state.phase === \"faulted\" && phase === \"uncertain\")) state.phase = phase;\n state.generation++;\n if (state.phase !== previous) observePhase?.(state.phase);\n const pending: Array<AbortController> = [];\n\n for (const lane of admission.lanes()) {\n const reservation = admission.takeReservation(lane);\n\n if (reservation !== undefined) pending.push(reservation);\n }\n\n const refusal =\n terminalReason === \"expired\" ? Reasons.Expired.make({}) : Reasons.Stale.make({});\n\n // A handoff keeps each quarantine for its operator; losing the connection ends them.\n if (reason === \"disconnected\" || reason === \"uncertain\" || reason === \"closed\")\n quarantined.clear();\n admission.fence(refusal);\n for (const waiting of waits()) waiting.cancel(refusal);\n for (const reservation of pending) reservation.abort();\n invalidate(reason);\n changed();\n };\n\n const terminate = (\n reason: SessionReason,\n disposition: \"known\" | \"not-dispatched\" | \"unknown\",\n generation = state.generation,\n ) => {\n if (disposition === \"unknown\") nativeUncertainty = true;\n record(reason, disposition === \"known\" ? \"confirmed\" : disposition, generation);\n fence(\n disposition === \"unknown\" ? \"uncertain\" : \"faulted\",\n disposition === \"unknown\" ? \"uncertain\" : \"closed\",\n reason,\n );\n };\n\n const expire = () => {\n if (terminalReason !== null || state.phase === \"closing\" || state.phase === \"closed\") return;\n terminate(\"expired\", \"known\");\n };\n\n /** Quarantine changes admission only; an originating click keeps its own valid ticket. */\n const policy = (\n event: Extract<DriverFault, { readonly source: \"policy\" }>,\n generation: number,\n ) => {\n if (event.disposition !== \"dispatched\") record(event.reason, event.disposition, generation);\n const previous = policies.get(event.token);\n\n switch (event.disposition) {\n case \"pending\":\n if (previous === undefined && terminalReason === null) policies.set(event.token, event);\n break;\n case \"dispatched\":\n unresolved.set(event.token, undefined);\n if (previous !== undefined) policies.set(event.token, event);\n break;\n case \"confirmed\":\n unresolved.delete(event.token);\n policies.delete(event.token);\n break;\n case \"unknown\":\n // Keep the token so a late acknowledgement may retire it, but never reopen admission.\n unresolved.set(event.token, undefined);\n fence(\"uncertain\", \"uncertain\", event.reason);\n break;\n case \"not-dispatched\":\n policies.delete(event.token);\n fence(\"faulted\", \"closed\", event.reason);\n break;\n }\n changed();\n };\n\n /** Taken under the permit that dispatched the work, so nothing can interleave before it. */\n const reserve = (key: string): Reservation => {\n // Outlives the fiber that dispatched it, and must be abortable by a fence from outside it.\n const controller = new AbortController();\n\n const lane = admission.lane(key);\n\n if (lane === undefined)\n throw BrowserError.make({\n operation: \"navigate\",\n reason: Reasons.Stale.make({}),\n outcome: \"unknown\",\n });\n admission.reserve(lane, controller);\n unresolved.set(controller, key);\n\n return {\n signal: controller.signal,\n settle: (outcome) => {\n // Navigation recovery is bounded by the lifetime, so it can give up at the same instant\n // as the independent lifetime timer. As for an action's timer, that instant is expiry.\n if (\n outcome === \"unknown\" &&\n lane.reservation === controller &&\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline\n )\n expire();\n // A fence already cleared it, and decided the outcome for everything it aborted.\n if (!admission.settleReservation(lane, controller)) return;\n if (outcome === \"known\") unresolved.delete(controller);\n else fence(\"uncertain\", \"uncertain\");\n admission.forget(lane);\n changed();\n },\n };\n };\n\n /**\n * Admission transfers a pure wait to an independent deadline and cancellation record. Its\n * logical barrier may end before uncancellable native work; neither is a mutation reservation.\n */\n const beginWait = (\n admitted: Ticket,\n target: DriverTarget,\n connection: object,\n operation: \"wait\" | \"settled\" = \"wait\",\n ): OwnedWait => {\n admitted.check();\n const lane = admission.lane(target.pageId);\n\n if (lane === undefined || lane.native.wait !== undefined)\n throw BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n });\n const controller = new AbortController();\n const result = Deferred.makeUnsafe<void, BrowserError>();\n const generation = admitted.generation;\n const deadline = admitted.deadline;\n let retired = false;\n let started = false;\n let canceled: BrowserError | undefined;\n\n const error = (reason: BrowserError[\"reason\"]) =>\n BrowserError.make({ operation, reason, outcome: \"undispatched\" });\n\n const release = () => {\n if (retired && !record.pending) admission.endWait(record);\n };\n\n const complete = (exit: Effect.Effect<void, BrowserError>) => {\n if (!record.pending) return;\n record.pending = false;\n release();\n Deferred.doneUnsafe(result, exit);\n };\n\n const cancel: OwnedWait[\"cancel\"] = (reason = Reasons.Interrupted.make({})) => {\n if (record.pending) {\n canceled = error(reason);\n complete(Effect.fail(canceled));\n }\n controller.abort();\n };\n\n const record = {\n connection,\n target: { ...target },\n pending: true,\n cancel,\n retire: () => {\n retired = true;\n release();\n },\n };\n\n admission.beginWait(lane, record);\n\n const check = () => {\n const now = Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000;\n\n if (now >= lifetimeDeadline) expire();\n if (canceled !== undefined) throw canceled;\n if (controller.signal.aborted || state.generation !== generation || state.phase !== \"open\")\n throw error(Reasons.Stale.make({}));\n if (now >= deadline) throw error(Reasons.Timeout.make({}));\n };\n\n const ticket: WaitTicket = {\n signal: controller.signal,\n deadline,\n generation,\n remainingMillis: () =>\n Math.max(1, deadline - Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000),\n check,\n invalidate: () => cancel(Reasons.Stale.make({})),\n retire: record.retire,\n };\n\n const fail = (cause: unknown) => {\n let failure = publicError(cause, operation, {\n reason: Reasons.Provider.make({}),\n outcome: \"undispatched\",\n });\n\n try {\n check();\n } catch (current) {\n failure = publicError(current, \"wait\", failure);\n }\n complete(Effect.fail(failure));\n };\n\n return {\n ticket,\n cancel,\n completed: within(Deferred.await(result), deadline, () => {\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline) expire();\n cancel(Reasons.Timeout.make({}));\n\n return canceled ?? error(Reasons.Timeout.make({}));\n }).pipe(\n Effect.provideService(Clock.Clock, clock),\n Effect.tap(() =>\n Effect.try({\n try: check,\n catch: (cause) =>\n publicError(cause, operation, {\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n }),\n }),\n ),\n ),\n start: (body) => {\n if (started) return;\n started = true;\n try {\n check();\n // Observe settlement after cancellation too; the native retire callback owns capacity.\n void body().then(() => {\n try {\n check();\n complete(Effect.void);\n } catch (cause) {\n fail(cause);\n }\n }, fail);\n } catch (cause) {\n record.retire();\n fail(cause);\n }\n },\n };\n };\n\n const contain = (\n page: { readonly pageId: string; readonly close: Effect.Effect<boolean> } | undefined,\n generation: number,\n ): Effect.Effect<Containment> =>\n Effect.uninterruptible(\n Effect.gen(function* () {\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline) expire();\n if (page === undefined || state.generation !== generation || state.phase !== \"open\") {\n fence(\"uncertain\", \"uncertain\");\n\n return { _tag: \"SessionFenced\", generation: state.generation };\n }\n const closed = yield* page.close;\n\n if (!closed || state.generation !== generation || state.phase !== \"open\") {\n fence(\"uncertain\", \"uncertain\");\n\n return { _tag: \"SessionFenced\", generation: state.generation };\n }\n const lane = admission.lane(page.pageId);\n const reservation = lane === undefined ? undefined : admission.takeReservation(lane);\n\n if (reservation !== undefined) {\n unresolved.delete(reservation);\n reservation.abort();\n }\n record(\"page-contained\", \"confirmed\", generation);\n changed();\n\n return { _tag: \"PageClosed\", pageId: page.pageId, generation };\n }),\n );\n\n const guard = <A, E, R>(\n operation: BrowserOperation,\n body: (ticket: Ticket) => Effect.Effect<A, E, R>,\n options: {\n readonly charge?: boolean | \"host-read\";\n readonly mutation?: boolean;\n readonly mutationScope?: () => ObservationScope;\n /** Exact work attribution can remain page-local while a form preserves its observations. */\n readonly targetScope?: () => ObservationScope;\n readonly phases?: ReadonlyArray<Phase>;\n readonly verifyAfter?: boolean;\n readonly preflight?: Effect.Effect<void, BrowserError>;\n /** A request can shorten this operation's policy deadline, never extend it. */\n readonly timeoutMillis?: number;\n readonly admission?: OperationOptions[\"admission\"];\n /** Composite operations retain the deadlines captured by their original caller. */\n readonly operationDeadline?: number;\n readonly queueDeadline?: number;\n readonly evidence?: ExecutionEvidence;\n readonly performance?: PerformanceRequest;\n /** Private recovery admission: one absolute deadline also bounds waiting for this permit. */\n readonly waitUntil?: number;\n /** Recovery and lifecycle cleanup own independent, bounded capacity. */\n readonly recovery?: boolean;\n readonly bypassBlocked?: boolean;\n /**\n * Where this operation's own page can absorb an unknown outcome: the page, and a request\n * that the browser close it, made once the outcome is unknown, which says whether it did.\n * Undefined, or a page that did not close, fences.\n */\n readonly contain?: () =>\n | { readonly pageId: string; readonly close: Effect.Effect<boolean> }\n | undefined;\n /** False when the caller already spans the operation, including its own validation. */\n readonly traced?: boolean;\n } = {},\n ): Effect.Effect<A, E | BrowserError, R> =>\n Effect.uninterruptibleMask((restoreGuard) =>\n Effect.gen(function* () {\n // Admission is its own span: it ends when the permit is held, or with the refusal.\n const admissionSpan = yield* Trace.start(\"Browser.admission\", {\n attributes: { \"browser.operation\": operation },\n });\n\n let admittedTicket: Ticket | undefined;\n\n return yield* restoreGuard(\n Effect.suspend(() => {\n const requested = Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000;\n const operationId = (++operationSequence).toString();\n let admitted = false;\n\n const deadline = Math.min(\n requested +\n Math.min(\n options.timeoutMillis ?? limits.actionTimeoutMillis,\n limits.actionTimeoutMillis,\n ),\n options.operationDeadline ?? Number.POSITIVE_INFINITY,\n options.waitUntil ?? Number.POSITIVE_INFINITY,\n lifetimeDeadline,\n );\n\n const queueMillis =\n options.waitUntil !== undefined\n ? Math.max(0, options.waitUntil - requested)\n : options.admission?.queue === undefined\n ? 0\n : Duration.toMillis(options.admission.queue);\n\n const queueDeadline = options.queueDeadline ?? requested + queueMillis;\n const scope = options.targetScope?.() ?? options.mutationScope?.();\n\n const facts: OperationFacts = {\n operation,\n operationId,\n generation: state.generation,\n scope,\n correlation: options.evidence?.correlation?.() ?? null,\n };\n\n // The operation's own subscriber first, then the session's: each fact is emitted once.\n const receivers = [options.evidence?.listener?.(facts), listener?.(facts)];\n\n const emit = (event: OperationEvent) => {\n for (const receive of receivers) receive?.(event);\n };\n\n const pageLane =\n scope !== undefined && scope !== \"all\" && scope !== \"none\"\n ? admission.lane(scope.pageId)\n : undefined;\n\n const lane =\n options.recovery === true && pageLane !== undefined\n ? admission.recovery(pageLane, operation)\n : (pageLane ?? admission.registry);\n\n // A mutation of one page needs that page's lane. The registry lane would admit it without\n // the page's serialization, and a navigation could not reserve its page after dispatch.\n const unregistered =\n pageLane === undefined &&\n scope !== undefined &&\n scope !== \"all\" &&\n scope !== \"none\" &&\n options.mutation === true &&\n options.recovery !== true;\n\n const pending = {\n token: {},\n operation,\n requestedAt: requested,\n deadline,\n queueDeadline,\n result: Deferred.makeUnsafe<void, BrowserError>(),\n reserved: options.recovery === true,\n };\n\n const work = Effect.gen(function* () {\n admissionSpan?.end(Exit.void);\n const refused = refusal(options);\n\n if (refused !== undefined)\n return yield* BrowserError.make({\n operation,\n reason: refused,\n outcome: \"undispatched\",\n });\n yield* options.preflight ?? Effect.void;\n const now = Number(yield* Clock.monotonicTimeNanos) / 1_000_000;\n\n if (lane.revoked || unregistered)\n return yield* BrowserError.make({\n operation,\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n });\n if (now >= lifetimeDeadline) {\n expire();\n\n return yield* BrowserError.make({\n operation,\n reason: Reasons.Expired.make({}),\n outcome: \"undispatched\",\n });\n }\n\n if (now >= deadline)\n return yield* BrowserError.make({\n operation,\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n });\n if (options.charge !== false) {\n const hostRead = options.charge === \"host-read\";\n const maximum = hostRead ? limits.maxHostReads : limits.maxActions;\n const observed = hostRead ? state.hostReads : state.actions;\n\n if (observed >= maximum)\n return yield* BrowserError.make({\n operation,\n reason: Reasons.Limit.make({\n dimension: hostRead ? \"host-reads\" : \"actions\",\n maximum,\n observed,\n }),\n outcome: \"undispatched\",\n });\n if (hostRead) state.hostReads++;\n else state.actions++;\n }\n // The lifecycle fence must actively abort admitted native work outside the current fiber.\n // @effect-diagnostics-next-line abortControllerInEffect:off\n const controller = new AbortController();\n\n admission.activate(lane, controller, operation);\n let dispatched = false;\n let pending = false;\n // Acknowledged input that landed, and acknowledged preparation that changed no input.\n let inputAcknowledged = false;\n let preparationAcknowledged = false;\n let phase: NonNullable<Ticket[\"phase\"]> = \"Prepared\";\n let unknownDecided = false;\n let containment: Containment = { _tag: \"NotRequired\" };\n const generation = state.generation;\n const allowed = options.phases ?? [\"open\"];\n\n // A driver's own outcome describes its last command; these flags, everything acknowledged.\n const currentOutcome = (driver: BrowserOutcome = \"undispatched\"): BrowserOutcome =>\n strongestOutcome(\n pending || unknownDecided\n ? \"unknown\"\n : inputAcknowledged\n ? \"performed\"\n : preparationAcknowledged\n ? \"rejected\"\n : \"undispatched\",\n driver,\n );\n\n const check = () => {\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline)\n expire();\n if (\n controller.signal.aborted ||\n state.generation !== generation ||\n !allowed.includes(state.phase)\n ) {\n throw BrowserError.make({\n operation,\n reason: Reasons.Stale.make({}),\n outcome: currentOutcome(),\n });\n }\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= deadline)\n throw BrowserError.make({\n operation,\n reason: Reasons.Timeout.make({}),\n outcome: currentOutcome(),\n });\n };\n\n /**\n * The one decision, for every listener, of whether a fact is late: it arrived after this\n * operation ended (unless it is the end itself), after it was given up, or past its\n * deadline.\n */\n const late = (end = false) =>\n (!end && phase === \"Terminal\") ||\n controller.signal.aborted ||\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= deadline;\n\n const reportPhase = (\n reached: Exclude<NonNullable<Ticket[\"phase\"]>, \"Terminal\">,\n mutation: boolean,\n acknowledgement?: AcknowledgementFact,\n ) =>\n emit({\n _tag: \"Phase\",\n phase: reached,\n mutation,\n ...(acknowledgement === undefined ? {} : { acknowledgement }),\n late: late(),\n atMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n });\n\n const ticket: Ticket = {\n ...(options.performance === undefined\n ? {}\n : {\n performance: {\n ...options.performance,\n ...grantedPacing({\n clock,\n deadlineNanos: () => BigInt(Math.floor(deadline * 1_000_000)),\n signal: controller.signal,\n check,\n overBudget: () =>\n BrowserError.make({\n operation,\n reason: Reasons.TimingBudgetExceeded.make({}),\n outcome: currentOutcome(),\n }),\n }),\n },\n }),\n operationId,\n picture: (boundary) => emit({ _tag: \"Picture\", boundary }),\n recordInput: (receipt, keys) =>\n emit({ _tag: \"Input\", receipt, ...(keys === undefined ? {} : { keys }) }),\n recordScroll: (scrolled) =>\n emit({ _tag: \"Scroll\", facts: scrolled, generation, late: late() }),\n recordGlide: (glide) => emit({ _tag: \"Glide\", facts: glide }),\n recordSettled: (evidence, target) => emit({ _tag: \"Settled\", evidence, target }),\n ...(options.evidence?.target === undefined\n ? {}\n : { captureTarget: options.evidence.target }),\n retainNative: () =>\n admission.retainNative(lane, operation, nativeConnection, () => dispatched),\n signal: controller.signal,\n deadline,\n generation,\n remainingMillis: () =>\n Math.max(1, deadline - Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000),\n get dispatched() {\n return dispatched;\n },\n get outcome() {\n return currentOutcome();\n },\n get phase() {\n return phase;\n },\n get containment() {\n return containment;\n },\n check,\n dispatch() {\n check();\n if (!dispatched && options.mutation)\n invalidate(\n \"observation\",\n options.mutationScope?.() ?? \"all\",\n controller.signal,\n );\n dispatched = true;\n pending = true;\n phase = \"Dispatched\";\n const scope = options.targetScope?.() ?? options.mutationScope?.();\n\n unresolved.set(\n controller,\n scope !== undefined && scope !== \"all\" && scope !== \"none\"\n ? scope.pageId\n : undefined,\n );\n reportPhase(\"Dispatched\", true);\n },\n acknowledge(fact) {\n const mutation = pending;\n\n pending = false;\n if (\n dispatched &&\n !unknownDecided &&\n !controller.signal.aborted &&\n phase !== \"Terminal\"\n ) {\n // A burst of keys or scroll samples is input that landed, even before the action\n // completes; only focus or scroll-into-view preparation leaves the input unchanged.\n if (\n fact === undefined ||\n fact.logicalComplete ||\n (fact.subphase !== \"focus\" && fact.subphase !== \"scroll-into-view\")\n )\n inputAcknowledged = true;\n else if (mutation) preparationAcknowledged = true;\n }\n if (phase !== \"Terminal\") phase = \"Acknowledged\";\n if (!unknownDecided) unresolved.delete(controller);\n reportPhase(\"Acknowledged\", mutation, fact);\n changed();\n },\n followUp() {\n if (phase === \"Acknowledged\") {\n phase = \"FollowUp\";\n reportPhase(\"FollowUp\", false);\n }\n },\n };\n\n admitted = true;\n admittedTicket = ticket;\n reportPhase(\"Prepared\", false);\n\n // A revocation freezes the pending attempt synchronously, before a late native\n // acknowledgement can run and before the interrupted Effect resumes its handler.\n const freezeUnknown = () => {\n if (phase !== \"Terminal\" && pending) unknownDecided = true;\n };\n\n controller.signal.addEventListener(\"abort\", freezeUnknown, { once: true });\n\n // Dispatched work this admission gave up on, whose outcome no fence has decided yet.\n let abandoned = false;\n\n const abandon = () => {\n // The action timer can win the same instant as the independent lifetime timer.\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline)\n expire();\n controller.abort();\n if (pending || unknownDecided) {\n unknownDecided = true;\n if (state.generation === generation && state.phase === \"open\") abandoned = true;\n else {\n if (state.phase === \"paused\" || state.phase === \"acquiring\")\n fence(\"uncertain\", \"uncertain\");\n containment = { _tag: \"SessionFenced\", generation: state.generation };\n }\n }\n };\n\n const current = () => state.generation === generation && state.phase === \"open\";\n\n /**\n * Work given up after dispatch fences the owner, since nothing knows what it did or\n * whether more of it will land. An operation confined to one page it may close instead\n * closes that page: once the browser confirms it closed, nothing still bound for it can\n * land anywhere, and every other page keeps working. It is still never replayed.\n */\n const settle = Effect.uninterruptible(\n Effect.suspend(() => {\n if (!abandoned) return Effect.void;\n abandoned = false;\n // A policy pause already holds this page for an operator: closing it would discard\n // the page the operator must inspect, and its quarantine refuses all automation.\n if (current() && lane.pageId !== undefined && quarantined.has(lane.pageId)) {\n containment = { _tag: \"PagePaused\", pageId: lane.pageId, generation };\n unresolved.delete(controller);\n changed();\n\n return Effect.void;\n }\n const page = current() ? options.contain?.() : undefined;\n\n return contain(page, generation).pipe(\n Effect.tap((result) =>\n Effect.sync(() => {\n containment = result;\n if (result._tag === \"PageClosed\") unresolved.delete(controller);\n }),\n ),\n );\n }),\n );\n\n return yield* within(body(ticket), ticket.deadline, () => {\n abandon();\n\n return BrowserError.make({\n operation,\n reason: Reasons.Timeout.make({}),\n outcome: currentOutcome(),\n });\n }).pipe(\n Effect.tap(() =>\n options.verifyAfter === false\n ? Effect.void\n : Effect.try({\n try: check,\n catch: (error) =>\n Schema.is(BrowserError)(error)\n ? error\n : BrowserError.make({\n operation,\n reason: Reasons.Stale.make({}),\n outcome: currentOutcome(),\n }),\n }),\n ),\n Effect.catch((error): Effect.Effect<never, E | BrowserError> => {\n const outcome = currentOutcome(\n Schema.is(BrowserError)(error) ? error.outcome : \"undispatched\",\n );\n\n if (pending || unknownDecided) abandon();\n\n // The permit adds dispatch evidence only to browser-operation errors. Typed\n // initialization/consumer failures retain their identity and original family.\n return settle.pipe(\n Effect.andThen(\n Effect.suspend((): Effect.Effect<never, E | BrowserError> =>\n Schema.is(BrowserError)(error)\n ? Effect.fail(\n BrowserError.make({\n operation,\n reason: error.reason,\n outcome,\n containment:\n containment._tag === \"NotRequired\"\n ? (error.containment ?? containment)\n : containment,\n }),\n )\n : Effect.fail(error),\n ),\n ),\n );\n }),\n Effect.onExit((exit) =>\n Exit.isFailure(exit) && containment._tag === \"NotRequired\"\n ? Effect.sync(abandon).pipe(Effect.andThen(settle))\n : Effect.void,\n ),\n Effect.tap(() =>\n Effect.sync(() => {\n unresolved.delete(controller);\n changed();\n }),\n ),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n const failure = Exit.isFailure(exit)\n ? Cause.findErrorOption(exit.cause)\n : Option.none();\n\n const error =\n Option.isSome(failure) && Schema.is(BrowserError)(failure.value)\n ? failure.value\n : undefined;\n\n emit({\n _tag: \"Finished\",\n kind: Exit.isSuccess(exit)\n ? \"Completed\"\n : Cause.hasInterrupts(exit.cause)\n ? \"Cancelled\"\n : \"Failed\",\n outcome: currentOutcome(error?.outcome),\n ...(error === undefined ? {} : { error }),\n containment:\n containment._tag === \"NotRequired\"\n ? (error?.containment ?? containment)\n : containment,\n });\n }),\n ),\n Effect.ensuring(\n Effect.sync(() => {\n phase = \"Terminal\";\n emit({\n _tag: \"Terminal\",\n outcome: currentOutcome(),\n containment,\n late: late(true),\n atMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n });\n controller.signal.removeEventListener(\"abort\", freezeUnknown);\n controller.abort();\n admission.deactivate(lane, controller);\n }),\n ),\n );\n });\n\n const checkAdmission = Effect.suspend(() => {\n const refused = refusal(options);\n\n return refused === undefined\n ? (options.preflight ?? Effect.void)\n : Effect.fail(\n BrowserError.make({ operation, reason: refused, outcome: \"undispatched\" }),\n );\n });\n\n return checkAdmission.pipe(\n Effect.andThen(\n Effect.uninterruptibleMask((restore) =>\n Effect.suspend(() =>\n restore(\n within(\n admission.acquire(\n lane,\n pending,\n options.recovery === true &&\n (operation !== \"navigate-stop\" || options.waitUntil === undefined)\n ? 0\n : queueMillis,\n ),\n lane.holder === pending.token || queueMillis <= 0\n ? deadline\n : Math.min(queueDeadline, deadline),\n () =>\n BrowserError.make({\n operation,\n reason:\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >=\n lifetimeDeadline\n ? Reasons.Expired.make({})\n : deadline <= queueDeadline\n ? Reasons.Timeout.make({})\n : Reasons.QueueExpired.make({}),\n outcome: \"undispatched\",\n }),\n ),\n ).pipe(\n Effect.onError(() => Effect.sync(() => admission.cancel(lane, pending))),\n Effect.andThen(restore(work)),\n Effect.ensuring(Effect.sync(() => admission.release(lane, pending.token))),\n ),\n ),\n ),\n ),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (admitted) return;\n\n const failure = Exit.isFailure(exit)\n ? Cause.findErrorOption(exit.cause)\n : Option.none();\n\n const error =\n Option.isSome(failure) && Schema.is(BrowserError)(failure.value)\n ? failure.value\n : undefined;\n\n emit({\n _tag: \"Finished\",\n kind: Exit.isSuccess(exit)\n ? \"Completed\"\n : Cause.hasInterrupts(exit.cause)\n ? \"Cancelled\"\n : \"Failed\",\n outcome: error?.outcome ?? \"undispatched\",\n ...(error === undefined ? {} : { error }),\n containment: error?.containment ?? { _tag: \"NotRequired\" },\n });\n }),\n ),\n );\n }),\n ).pipe(\n Effect.onExit((exit) =>\n Effect.sync(() => admissionSpan?.end(exit, { \"browser.outcome\": \"undispatched\" })),\n ),\n Effect.onInterrupt(() =>\n Trace.annotate({ \"browser.outcome\": admittedTicket?.outcome ?? \"undispatched\" }),\n ),\n );\n }),\n ).pipe(\n Effect.provideService(Clock.Clock, clock),\n options.traced === false ? (effect) => effect : operationSpan(operation),\n );\n\n /** Lifecycle transitions are performed while holding guard's permit; close alone preempts it. */\n return {\n clock,\n /** The session's subscription to every operation it guards, such as its timeline's. */\n observeOperations: (subscribe: OperationListener) => {\n listener = subscribe;\n },\n observePhase: (observer: (phase: Phase) => void) => {\n observePhase = observer;\n },\n state,\n lifetimeDeadline,\n guard,\n refusal,\n chargeHostRead: (ticket: Ticket, operation: BrowserOperation) => {\n ticket.check();\n if (state.hostReads >= limits.maxHostReads)\n throw BrowserError.make({\n operation,\n reason: Reasons.Limit.make({\n dimension: \"host-reads\",\n maximum: limits.maxHostReads,\n observed: state.hostReads,\n }),\n outcome: \"undispatched\",\n });\n state.hostReads++;\n },\n pageAdmission: admission.page,\n /** A navigation stop's setup on its page's native capacity; see `Admission.beginStopSetup`. */\n beginStopSetup: admission.beginStopSetup,\n admissionSnapshot: admission.snapshot,\n admissionStatus: Effect.sync(admission.status),\n setConnection: (connection: object) => {\n nativeConnection = connection;\n },\n hasActive: (except?: AbortSignal) =>\n admission\n .lanes()\n .some(\n (lane) =>\n lane.holder !== undefined &&\n (except === undefined || lane.active?.controller.signal !== except),\n ),\n restorePageAdmission: (pageId: string) => {\n quarantined.delete(pageId);\n admission.restore(pageId);\n },\n revision: (pageId: string) => admission.lane(pageId)?.revision ?? state.revision,\n reserve,\n contain,\n pauseAdmission: () => {\n if (admissionBarrier !== undefined) return undefined;\n const token = {};\n\n admissionBarrier = token;\n admission.blockPending(Reasons.Busy.make({}));\n\n return token;\n },\n resumeAdmission: (token: object) => {\n if (admissionBarrier !== token) return false;\n admissionBarrier = undefined;\n\n return true;\n },\n /**\n * No admitted work can still change a page. Pure waits only read; the fence that follows a\n * drain refuses them, so they never hold one up.\n */\n drained: (except?: AbortSignal) =>\n admission.drained(\n except,\n (lane) => lane.pageId !== undefined && quarantined.has(lane.pageId),\n ) &&\n !nativeUncertainty &&\n unresolved.size === 0 &&\n admission.lanes().every((lane) => lane.reservation === undefined) &&\n policies.size === 0,\n /**\n * No admitted operation, no native work that can still change a page, and no started\n * navigation that is still loading is running. Unlike `drained`, an earlier unresolved\n * outcome does not prevent it.\n */\n idle: (except?: AbortSignal) =>\n admission.drained(\n except,\n (lane) => lane.pageId !== undefined && quarantined.has(lane.pageId),\n ) && admission.lanes().every((lane) => lane.reservation === undefined),\n /** Completes after the next settlement of admitted work, a policy or a fence. */\n nextChange: Effect.suspend(() => Deferred.await(change)),\n reserved: (key: string): boolean => admission.lane(key)?.reservation !== undefined,\n /** Whether a popup/dialog policy holds this page for an operator. */\n paused: (pageId: string): boolean => quarantined.has(pageId),\n get pausedPages(): number {\n return quarantined.size;\n },\n /**\n * A popup/dialog policy pause: the page's admitted work is revoked as for closure, but an\n * outcome it leaves unknown is held by the quarantine for the operator rather than closed.\n */\n pausePage: (pageId: string) => {\n quarantined.add(pageId);\n for (const lane of admission.lanes()) {\n if (lane.pageId !== pageId) continue;\n admission.revoke(lane, Reasons.Stale.make({}));\n const reservation = admission.takeReservation(lane);\n\n if (reservation !== undefined) unresolved.delete(reservation);\n reservation?.abort();\n }\n waitOn(pageId)?.cancel(Reasons.Stale.make({}));\n changed();\n },\n revokePage: (pageId: string, except?: AbortSignal) => {\n for (const lane of admission.lanes()) {\n if (lane.pageId !== pageId) continue;\n if (except === undefined || lane.active?.controller.signal !== except)\n admission.revoke(lane, Reasons.Stale.make({}));\n admission.takeReservation(lane)?.abort();\n }\n waitOn(pageId)?.cancel(Reasons.Stale.make({}));\n },\n retirePage: (pageId: string) => {\n const waiting = waitOn(pageId);\n\n quarantined.delete(pageId);\n waiting?.cancel(Reasons.Stale.make({}));\n waiting?.retire();\n admission.retirePage(pageId);\n for (const [token, page] of unresolved) if (page === pageId) unresolved.delete(token);\n changed();\n },\n beginWait,\n waitAvailable: (pageId: string) => waitOn(pageId) === undefined,\n waitPending: (pageId?: string) =>\n pageId === undefined\n ? [...waits()].some((waiting) => waiting.pending)\n : waitOn(pageId)?.pending === true,\n /** Positive retirement is specific to a connection, including a late retired predecessor. */\n retireWait: (connection: object) => {\n admission.retireConnection(connection);\n for (const waiting of waits()) {\n if (waiting.connection !== connection) continue;\n waiting.cancel(Reasons.Stale.make({}));\n waiting.retire();\n }\n },\n invalidate,\n fence,\n get reason() {\n return terminalReason ?? pauseReason;\n },\n transition,\n expire,\n terminate,\n policy,\n record,\n /** Only positive lifetime-source evidence may retire control lost to a connection fence. */\n retireControl: () => {\n for (const waiting of waits()) {\n waiting.cancel(Reasons.Stale.make({}));\n waiting.retire();\n }\n admission.retire();\n unresolved.clear();\n nativeUncertainty = false;\n policies.clear();\n changed();\n },\n status: Effect.sync(() => {\n const status = SessionStatus.make({\n phase: state.phase,\n reason: terminalReason ?? pauseReason ?? policies.values().next().value?.reason ?? null,\n generation: state.generation,\n busy:\n admission\n .lanes()\n .some((lane) => lane.holder !== undefined || lane.native.work.size > 0) ||\n policies.size > 0 ||\n waits().size > 0,\n unresolvedDispatch: nativeUncertainty || unresolved.size > 0,\n actions: { used: state.actions, maximum: limits.maxActions },\n });\n\n // Schema construction owns the nested record; freeze the produced snapshot, not its input.\n Object.freeze(status.actions);\n\n return Object.freeze(status);\n }),\n diagnostics: Effect.sync(() => {\n const snapshot = BrowserDiagnostics.make({\n records: [...records],\n total,\n dropped,\n truncated: dropped > 0,\n });\n\n // Schema construction owns its array; freeze the produced snapshot, not merely its input.\n for (const record of snapshot.records) Object.freeze(record);\n Object.freeze(snapshot.records);\n\n return Object.freeze(snapshot);\n }),\n onInvalidate(\n hook: (reason: Invalidation, scope: ObservationScope, origin?: AbortSignal) => void,\n ): () => void {\n hooks.add(hook);\n\n return () => {\n hooks.delete(hook);\n };\n },\n };\n});\n\nexport type Owner = Effect.Success<ReturnType<typeof makeOwner>>;\n\n/** Without a native answer, whether the step was sent is all the owner knows about it. */\nconst unsettled = (ticket: Ticket, error: unknown): Pick<BrowserError, \"reason\" | \"outcome\"> => ({\n reason: providerReason(error),\n outcome: ticket.outcome ?? (ticket.dispatched ? \"unknown\" : \"undispatched\"),\n});\n\n/**\n * The one place a native step becomes a public error: whatever the driver raised, the caller\n * sees the operation it asked for.\n */\nexport const native = <A>(operation: BrowserOperation, ticket: Ticket, body: () => Promise<A>) =>\n Effect.callback<A, BrowserError>((resume) => {\n let done = false;\n let retire: (() => void) | undefined;\n\n const cleanup = () => {\n done = true;\n ticket.signal.removeEventListener(\"abort\", abort);\n };\n\n const abort = () => {\n if (done) return;\n cleanup();\n resume(\n Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Stale.make({}),\n outcome: ticket.outcome ?? (ticket.dispatched ? \"unknown\" : \"undispatched\"),\n }),\n ),\n );\n };\n\n ticket.signal.addEventListener(\"abort\", abort, { once: true });\n try {\n ticket.check();\n retire = ticket.retainNative?.();\n // Observe both branches even after the waiter exits. Cancellation does not undo native work.\n void body().then(\n (value) => {\n retire?.();\n if (!done) {\n cleanup();\n resume(Effect.succeed(value));\n }\n },\n (error: unknown) => {\n retire?.();\n if (!done) {\n cleanup();\n resume(\n Schema.is(NativeEffectFailure)(error)\n ? Effect.failCause(error.cause)\n : Effect.fail(publicError(error, operation, unsettled(ticket, error))),\n );\n }\n },\n );\n } catch (error) {\n retire?.();\n cleanup();\n resume(\n Schema.is(NativeEffectFailure)(error)\n ? Effect.failCause(error.cause)\n : Effect.fail(publicError(error, operation, unsettled(ticket, error))),\n );\n }\n\n return Effect.sync(cleanup);\n }).pipe(\n Effect.onInterrupt(() =>\n Trace.annotate({ \"browser.outcome\": ticket.dispatched ? \"unknown\" : \"undispatched\" }),\n ),\n Trace.span(`Browser.native.${operation}`, { attributes: { \"browser.operation\": operation } }),\n );\n","import {\n Cause,\n Clock,\n Deferred,\n Duration,\n Effect,\n Exit,\n Fiber,\n Option,\n Predicate,\n Schema,\n type Scope,\n} from \"effect\";\n\nimport type { ElementAdmission } from \"../../Browser.ts\";\nimport {\n type Checkpoint,\n type CheckpointOptions,\n InputReceipt,\n type ObservedElement,\n} from \"../../BrowserData.ts\";\nimport { BrowserError, Reasons, type BrowserOutcome, type Containment } from \"../../Errors.ts\";\nimport { type RunOperation, type RunOptions, StepFailed } from \"../../Plan.ts\";\nimport type {\n AttemptResult,\n AttemptSnapshot,\n DescriptorCapture,\n InputBindings,\n LivePlan,\n PhaseEvidence,\n Ran,\n RanStep,\n RunPhase,\n RunReceipt,\n RunTiming,\n Performed,\n PerformanceEvidence,\n Step,\n StepAttempt,\n} from \"../../PlanData.ts\";\nimport type { Correlation, Payload } from \"../../TimelineData.ts\";\nimport type { DescriptorSample, ResolvedElement } from \"./Descriptor.ts\";\nimport { type OperationEvent, type ScrollFacts, strongestOutcome } from \"./Owner.ts\";\nimport { prepare, type PerformancePlan } from \"./Performance.ts\";\nimport { capture, inputSlots, pathKey, type TargetSample, validateInputs } from \"./Recording.ts\";\nimport type { ExecutionOptions } from \"./Session.ts\";\n\nexport interface TargetBinding {\n readonly value: ObservedElement | ResolvedElement | string;\n readonly path: ReadonlyArray<string>;\n readonly sample?: DescriptorSample;\n}\n\nexport interface StepExecution {\n readonly options: ExecutionOptions;\n readonly policy?: ElementAdmission;\n readonly checkpoint?: CheckpointOptions;\n readonly phase: (phase: RunPhase, fieldIndex?: number) => void;\n readonly targets: (bindings: ReadonlyArray<TargetBinding>) => void;\n /** Partial form/input evidence survives a later failed verification, submit or postcondition. */\n readonly retainReceipt: (receipt: RunReceipt) => void;\n readonly performance?: PerformancePlan;\n}\n\nexport interface ValidatedRunOptions extends RunOptions {\n readonly style?: \"plain\" | Performed;\n readonly withinMillis?: number;\n readonly queueMillis?: number;\n}\n\nexport interface StepSuccess {\n readonly receipt: RunReceipt;\n readonly checkpoint?: Checkpoint;\n}\n\nexport interface PlanExecutionOptions {\n readonly clock: Clock.Clock;\n readonly validate: Effect.Effect<void, BrowserError>;\n readonly lifetimeDeadline: number;\n readonly actionTimeoutMillis: number;\n readonly newId: Effect.Effect<string>;\n readonly newSeed?: Effect.Effect<number>;\n /** Captured at run execution and retained with its original domain, never an evidence owner. */\n readonly publish?: () => {\n readonly append: (correlation: Correlation, event: Payload) => void;\n readonly release: () => void;\n };\n /** Completes once the issuing Page or its owner can no longer run; a scheduled start ends then. */\n readonly retired?: Effect.Effect<void>;\n /** This bounds registrations, never takes a Page mutation permit for the whole walk. */\n readonly reserve: Effect.Effect<() => void, BrowserError>;\n readonly executeStep: (\n step: Step,\n inputs: InputBindings,\n context: StepExecution,\n ) => Effect.Effect<StepSuccess, BrowserError>;\n}\n\nconst maximumPhases = 1024;\n\n/** Only bounded decoded data is frozen. Original Effect Causes are retained without traversal. */\nconst freezeData = <A>(value: A): A => {\n const seen = new WeakSet<object>();\n\n const freeze = (input: unknown): void => {\n if (!Predicate.isObjectKeyword(input) || seen.has(input) || Object.isFrozen(input)) return;\n seen.add(input);\n for (const child of Object.values(input)) freeze(child);\n Object.freeze(input);\n };\n\n freeze(value);\n\n return value;\n};\n\ninterface AttemptState {\n readonly id: string;\n readonly step: Step;\n readonly phases: Array<PhaseEvidence>;\n readonly samples: Map<string, TargetSample>;\n phase: RunPhase;\n fieldIndex?: number;\n overflow: boolean;\n completed: boolean;\n /** The strongest outcome the owner classified for any operation this attempt admitted. */\n reached: BrowserOutcome;\n capture?: DescriptorCapture;\n receipt?: RunReceipt;\n outcome?: BrowserOutcome;\n error?: BrowserError;\n cause?: Cause.Cause<BrowserError>;\n result?: AttemptResult;\n containment: Containment;\n performance?: PerformanceEvidence;\n}\n\nconst attemptSnapshot = (state: AttemptState): StepAttempt =>\n Object.freeze({\n id: state.id,\n stepId: state.step.id,\n sourceStep: state.step,\n action: state.step.action._tag,\n phase: state.phase,\n phases: Object.freeze([...state.phases]),\n ...(state.capture === undefined ? {} : { capture: state.capture }),\n ...(state.receipt === undefined ? {} : { receipt: state.receipt }),\n ...(state.outcome === undefined ? {} : { outcome: state.outcome }),\n ...(state.error === undefined ? {} : { error: state.error }),\n ...(state.cause === undefined ? {} : { cause: state.cause }),\n ...(state.result === undefined ? {} : { result: state.result }),\n containment: state.containment,\n completed: state.completed,\n ...(state.performance === undefined ? {} : { performance: state.performance }),\n });\n\n/** One classifier: the owner's, per admitted operation, never weakened by a later failure. */\nconst outcome = (state: AttemptState, error?: BrowserError): BrowserOutcome =>\n strongestOutcome(state.reached, error?.outcome ?? \"undispatched\");\n\nconst result = (value: BrowserOutcome, failed: boolean): AttemptResult => {\n switch (value) {\n case \"unknown\":\n return { _tag: \"Unknown\", outcome: value };\n case \"performed\":\n return {\n _tag: failed ? \"AcknowledgedWithPostconditionFailure\" : \"Acknowledged\",\n outcome: value,\n };\n case \"undispatched\":\n return { _tag: failed ? \"Refused\" : \"Acknowledged\", outcome: value };\n case \"rejected\":\n return { _tag: \"Refused\", outcome: value };\n }\n};\n\nconst preparationFailure = (error: BrowserError): StepFailed =>\n new StepFailed({ stage: \"PreparationFailed\", completed: [], error });\n\n/** The original scoped owner is supplied once; a RunOperation contains no reconnecting facade. */\nexport const makePlanExecution = (configuration: PlanExecutionOptions) => {\n const now = (): number => Number(configuration.clock.monotonicTimeNanosUnsafe()) / 1_000_000;\n\n const start = (\n plan: LivePlan,\n options: ValidatedRunOptions = {},\n ): Effect.Effect<RunOperation, StepFailed, Scope.Scope> =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const requestedMonotonicNanos = configuration.clock.monotonicTimeNanosUnsafe();\n const intendedMonotonicNanos = options.startAt ?? requestedMonotonicNanos;\n const began = Number(intendedMonotonicNanos) / 1_000_000;\n\n const runDeadline = Math.min(\n configuration.lifetimeDeadline,\n options.withinMillis === undefined\n ? Number.POSITIVE_INFINITY\n : began + options.withinMillis,\n );\n\n const last =\n options.through === undefined\n ? plan.steps.length - 1\n : plan.steps.findIndex((step) => step.id === options.through);\n\n if (last < 0)\n return yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Malformed.make({ path: \"through\" }),\n outcome: \"undispatched\",\n }),\n );\n const inputs = Object.freeze({ ...options.inputs });\n\n yield* restore(configuration.validate).pipe(Effect.mapError(preparationFailure));\n yield* restore(validateInputs(plan, inputs)).pipe(Effect.mapError(preparationFailure));\n if (!Number.isFinite(began) || !Number.isFinite(runDeadline))\n return yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Configuration.make({ path: \"startAt\" }),\n outcome: \"undispatched\",\n }),\n );\n if (began >= runDeadline || now() >= runDeadline)\n return yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.ScheduleMissed.make({}),\n outcome: \"undispatched\",\n }),\n );\n\n const style =\n options.style === undefined || options.style === \"plain\" ? undefined : options.style;\n\n const seed =\n style === undefined\n ? undefined\n : (style.seed ??\n (configuration.newSeed === undefined\n ? yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Configuration.make({ path: \"style.seed\" }),\n outcome: \"undispatched\",\n }),\n )\n : yield* restore(configuration.newSeed)));\n\n const runId = yield* restore(configuration.newId);\n const ids = yield* restore(Effect.forEach(plan.steps, () => configuration.newId));\n const release = yield* configuration.reserve.pipe(Effect.mapError(preparationFailure));\n // Evidence publication is taken when the walk starts, so a scheduled start retains no\n // journal while it waits and never holds back its domain's terminal.\n let publication: ReturnType<NonNullable<typeof configuration.publish>> | undefined;\n let publish: ((correlation: Correlation, event: Payload) => void) | undefined;\n let released = false;\n\n const releaseAll = () => {\n if (released) return;\n released = true;\n release();\n publication?.release();\n };\n\n const releaseOnce = Effect.sync(releaseAll);\n\n yield* Effect.addFinalizer(() => releaseOnce);\n freezeData(plan);\n const slots = inputSlots(plan);\n const completed: Array<RanStep> = [];\n const attempts: Array<AttemptState> = [];\n const completion = yield* Deferred.make<Ran, StepFailed>();\n let terminal = false;\n\n let timing: RunTiming = Object.freeze({\n requestedMonotonicNanos,\n intendedMonotonicNanos,\n startedMonotonicNanos: null,\n deadlineMonotonicNanos: BigInt(Math.floor(runDeadline * 1_000_000)),\n latenessNanos: null,\n ...(seed === undefined ? {} : { seed }),\n });\n\n const snapshot = (): AttemptSnapshot =>\n Object.freeze({\n runId,\n attempts: Object.freeze(attempts.map(attemptSnapshot)),\n completed: Object.freeze([...completed]),\n terminal,\n timing,\n });\n\n const worker = Effect.gen(function* () {\n let waited = false;\n\n // Timers have millisecond resolution and can wake before a fractional instant, so the\n // wait repeats until the owner's own monotonic clock has reached the intended start.\n while (configuration.clock.monotonicTimeNanosUnsafe() < intendedMonotonicNanos) {\n waited = true;\n\n const remainingNanos =\n intendedMonotonicNanos - configuration.clock.monotonicTimeNanosUnsafe();\n\n const retired = yield* (configuration.retired ?? Effect.never).pipe(\n Effect.timeoutOption(Duration.millis(Math.ceil(Number(remainingNanos) / 1_000_000))),\n );\n\n // The issuing Page or owner ended before the start: refuse with its current reason.\n if (Option.isSome(retired))\n return yield* configuration.validate.pipe(\n Effect.andThen(\n Effect.fail(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n }),\n ),\n ),\n Effect.mapError(preparationFailure),\n );\n }\n if (waited) yield* configuration.validate.pipe(Effect.mapError(preparationFailure));\n if (!released) {\n publication = configuration.publish?.();\n publish = publication?.append;\n }\n const startedMonotonicNanos = configuration.clock.monotonicTimeNanosUnsafe();\n\n timing = Object.freeze({\n ...timing,\n startedMonotonicNanos,\n latenessNanos:\n startedMonotonicNanos > intendedMonotonicNanos\n ? startedMonotonicNanos - intendedMonotonicNanos\n : 0n,\n });\n if (now() >= runDeadline)\n return yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.ScheduleMissed.make({}),\n outcome: \"undispatched\",\n }),\n );\n for (let index = 0; index <= last; index++) {\n const step = plan.steps[index];\n const attemptId = ids[index];\n\n // Both arrays are bounded, nonempty and correlated by ingress/preparation.\n if (step === undefined || attemptId === undefined)\n return yield* Effect.die(\n new Error(\"Validated plan/attempt inventory lost alignment\"),\n );\n const stepBegan = now();\n\n const stepDeadline = Math.min(\n runDeadline,\n stepBegan +\n Math.min(\n options.timeoutMillis ?? configuration.actionTimeoutMillis,\n configuration.actionTimeoutMillis,\n ),\n );\n\n const queueMillis =\n options.queueMillis ??\n (options.admission?.queue === undefined\n ? undefined\n : Duration.toMillis(Duration.fromInputUnsafe(options.admission.queue)));\n\n const queueDeadline =\n queueMillis === undefined\n ? undefined\n : Math.min(stepDeadline, stepBegan + queueMillis);\n\n const state: AttemptState = {\n id: attemptId,\n step,\n phase: \"Preparation\",\n phases: [],\n samples: new Map(),\n overflow: false,\n completed: false,\n reached: \"undispatched\",\n containment: { _tag: \"NotRequired\" },\n };\n\n attempts.push(state);\n\n const correlation = (): Correlation => ({\n runId,\n stepId: step.id,\n attemptId,\n ...(state.fieldIndex === undefined ? {} : { fieldIndex: state.fieldIndex }),\n });\n\n publish?.(correlation(), { _tag: \"Planned\", action: step.action._tag });\n\n const performance =\n style === undefined || seed === undefined\n ? undefined\n : yield* prepare(style, seed, step.id);\n\n if (performance !== undefined)\n state.performance = Object.freeze({\n seed: performance.seed,\n profile: performance.profile,\n });\n\n const targetBindings = new Map<\n ObservedElement | ResolvedElement | string,\n Array<ReadonlyArray<string>>\n >();\n\n const retainedInputs = new WeakSet<InputReceipt>();\n const checkedSamples = new Set<string>();\n // Bursts fold only within one admitted operation, named by its owner's operation id.\n let lastDispatchOperation: string | undefined;\n let lastBurstOperation: string | undefined;\n\n const append = (evidence: PhaseEvidence): void => {\n if (state.phases.length >= maximumPhases) {\n state.overflow = true;\n if (state.completed)\n state.capture = freezeData({\n _tag: \"Incomplete\",\n facts: { path: [] },\n reason: \"EvidenceLimit\",\n });\n\n return;\n }\n state.phases.push(Object.freeze(evidence));\n };\n\n const appendPhase = (evidence: PhaseEvidence, operationId: string): void => {\n if (evidence.phase === \"Dispatched\") lastDispatchOperation = operationId;\n const fact = evidence.acknowledgement;\n\n if (\n evidence.phase !== \"Acknowledged\" ||\n fact === undefined ||\n fact.logicalComplete ||\n (fact.subphase !== \"key-burst\" && fact.subphase !== \"scroll-burst\") ||\n lastDispatchOperation !== operationId\n ) {\n if (evidence.phase !== \"Dispatched\") lastBurstOperation = undefined;\n append(evidence);\n\n return;\n }\n let start = state.phases.length;\n\n while (start > 0) {\n const previous = state.phases[start - 1];\n\n if (\n previous?.phase !== \"Dispatched\" ||\n previous.operation !== evidence.operation ||\n previous.fieldIndex !== evidence.fieldIndex ||\n previous.late !== evidence.late\n )\n break;\n start--;\n }\n const dispatched = state.phases[start];\n\n if (dispatched === undefined) {\n lastBurstOperation = undefined;\n append(evidence);\n\n return;\n }\n const dispatches = state.phases.length - start;\n const previous = state.phases[start - 1];\n\n const combine =\n lastBurstOperation === operationId &&\n previous?.phase === \"Acknowledged\" &&\n previous.burst?.subphase === fact.subphase &&\n previous.operation === evidence.operation &&\n previous.fieldIndex === evidence.fieldIndex &&\n previous.late === evidence.late;\n\n state.phases.splice(start);\n\n const burst = Object.freeze({\n subphase: fact.subphase,\n dispatches: dispatches + (combine ? (previous.burst?.dispatches ?? 0) : 0),\n acknowledgements: 1 + (combine ? (previous.burst?.acknowledgements ?? 0) : 0),\n firstDispatchedMonotonicNanos: combine\n ? (previous.burst?.firstDispatchedMonotonicNanos ?? dispatched.atMonotonicNanos)\n : dispatched.atMonotonicNanos,\n lastAcknowledgedMonotonicNanos: evidence.atMonotonicNanos,\n });\n\n if (combine) {\n state.phases[start - 1] = Object.freeze({ ...previous, ...evidence, burst });\n } else append({ ...evidence, burst });\n lastBurstOperation = operationId;\n };\n\n const retainScroll = (facts: ScrollFacts, generation: number, late: boolean): void => {\n const scroll: NonNullable<PhaseEvidence[\"scroll\"]> = Object.freeze({\n target: Object.freeze({\n generation,\n pageId: facts.target.pageId,\n frameId: facts.target.frameId,\n }),\n startedMonotonicNanos: facts.startedMonotonicNanos,\n completedMonotonicNanos: facts.completedMonotonicNanos,\n qualification: facts.qualification ?? \"native-call-interval\",\n ...(facts.x === undefined || facts.y === undefined\n ? {}\n : { delta: Object.freeze({ x: facts.x, y: facts.y }) }),\n });\n\n const index = state.phases.length - 1;\n const previous = state.phases[index];\n\n if (\n !late &&\n previous?.phase === \"Acknowledged\" &&\n !previous.late &&\n previous.operation === state.phase &&\n previous.fieldIndex === state.fieldIndex\n ) {\n const original = previous.scroll;\n\n const delta =\n original?.delta !== undefined && scroll.delta !== undefined\n ? Object.freeze({\n x: original.delta.x + scroll.delta.x,\n y: original.delta.y + scroll.delta.y,\n })\n : scroll.delta;\n\n state.phases[index] = Object.freeze({\n ...previous,\n scroll:\n original === undefined\n ? scroll\n : Object.freeze({\n ...scroll,\n startedMonotonicNanos: original.startedMonotonicNanos,\n ...(delta === undefined ? {} : { delta }),\n }),\n });\n\n return;\n }\n lastBurstOperation = undefined;\n append({\n phase: \"SubphaseReceipt\",\n operation: state.phase,\n atMonotonicNanos: facts.completedMonotonicNanos,\n late,\n scroll,\n ...(state.fieldIndex === undefined ? {} : { fieldIndex: state.fieldIndex }),\n });\n };\n\n const retainInput = (\n input: InputReceipt,\n operation: RunPhase,\n fieldIndex?: number,\n ): void => {\n if (retainedInputs.has(input)) return;\n retainedInputs.add(input);\n const receipt = freezeData(input);\n\n for (let index = state.phases.length - 1; index >= 0; index--) {\n const evidence = state.phases[index];\n\n if (\n evidence?.phase === \"Acknowledged\" &&\n !evidence.late &&\n evidence.operation === operation &&\n evidence.fieldIndex === fieldIndex &&\n evidence.input === undefined &&\n evidence.atMonotonicNanos >= receipt.startedMonotonicNanos &&\n evidence.atMonotonicNanos <= receipt.completedMonotonicNanos\n ) {\n state.phases[index] = Object.freeze({ ...evidence, input: receipt });\n\n return;\n }\n }\n append({\n phase: \"InputReceipt\",\n operation,\n atMonotonicNanos: receipt.completedMonotonicNanos,\n late: state.completed,\n input: receipt,\n ...(fieldIndex === undefined ? {} : { fieldIndex }),\n });\n };\n\n const retainReceipt = (receipt: RunReceipt): void => {\n if (state.completed) return;\n state.receipt = freezeData(receipt);\n if (Schema.is(InputReceipt)(receipt)) retainInput(receipt, \"Input\");\n else if (receipt !== undefined) {\n if (\"input\" in receipt && receipt.input !== undefined)\n retainInput(receipt.input, \"Input\");\n if (\"fields\" in receipt)\n receipt.fields.forEach((field, index) => {\n if (field.input !== undefined) retainInput(field.input, \"Field\", index);\n });\n if (\"submitInput\" in receipt && receipt.submitInput !== undefined)\n retainInput(receipt.submitInput, \"Submit\");\n }\n };\n\n const context: StepExecution = {\n ...(performance === undefined ? {} : { performance }),\n ...(options.policy === undefined ? {} : { policy: options.policy }),\n ...(options.checkpoint === undefined\n ? {}\n : { checkpoint: freezeData({ ...options.checkpoint }) }),\n phase: (phase, fieldIndex) => {\n if (state.completed) return;\n state.phase = phase;\n state.fieldIndex = fieldIndex;\n },\n targets: (bindings) => {\n if (state.completed) return;\n for (const binding of bindings) {\n const paths = targetBindings.get(binding.value) ?? [];\n\n paths.push(binding.path);\n targetBindings.set(binding.value, paths);\n const key = pathKey(binding.path);\n\n if (binding.sample !== undefined && !state.samples.has(key))\n state.samples.set(key, { path: binding.path, sample: binding.sample });\n }\n },\n retainReceipt,\n options: {\n ...(options.timeoutMillis === undefined\n ? {}\n : { timeoutMillis: options.timeoutMillis }),\n ...(options.admission === undefined ? {} : { admission: options.admission }),\n operationDeadline: stepDeadline,\n ...(queueDeadline === undefined ? {} : { queueDeadline }),\n evidence: {\n correlation,\n // Each admitted operation's facts, with the owner's lateness; evidence that\n // arrives after this attempt completed is late for the attempt as well.\n listener:\n ({ operationId }) =>\n (event: OperationEvent) => {\n switch (event._tag) {\n case \"Phase\":\n case \"Terminal\":\n appendPhase(\n {\n phase: event._tag === \"Terminal\" ? \"Terminal\" : event.phase,\n operation: state.phase,\n atMonotonicNanos: event.atMonotonicNanos,\n late: state.completed || event.late,\n ...(state.fieldIndex === undefined\n ? {}\n : { fieldIndex: state.fieldIndex }),\n ...(event._tag === \"Terminal\" || event.acknowledgement === undefined\n ? {}\n : { acknowledgement: Object.freeze({ ...event.acknowledgement }) }),\n },\n operationId,\n );\n if (event._tag === \"Terminal\") {\n if (!state.completed)\n state.reached = strongestOutcome(state.reached, event.outcome);\n if (event.containment._tag !== \"NotRequired\")\n state.containment = Object.freeze({ ...event.containment });\n }\n\n return;\n case \"Scroll\":\n retainScroll(\n event.facts,\n event.generation,\n state.completed || event.late,\n );\n\n return;\n // Pictures, input receipts, glides, settling and the operation's\n // own summary reach the plan through its receipts, not as phases.\n case \"Picture\":\n case \"Input\":\n case \"Glide\":\n case \"Settled\":\n case \"Finished\":\n return;\n }\n },\n target: (target, sample) => {\n if (state.completed) return;\n for (const path of targetBindings.get(target) ?? []) {\n if (\n state.fieldIndex !== undefined &&\n path[0] === \"fields\" &&\n path[1] !== String(state.fieldIndex)\n )\n continue;\n const key = pathKey(path);\n\n if (!checkedSamples.has(key)) {\n state.samples.set(key, {\n path,\n ...(sample === undefined ? {} : { sample }),\n });\n checkedSamples.add(key);\n }\n }\n },\n },\n },\n };\n\n const effect =\n stepDeadline <= now()\n ? Effect.fail(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n }),\n )\n : configuration.executeStep(step, inputs, context).pipe(\n Effect.flatMap((success) => {\n if (\n success.receipt !== undefined &&\n \"stopped\" in success.receipt &&\n success.receipt.stopped !== undefined\n ) {\n retainReceipt(success.receipt);\n\n return Effect.fail(success.receipt.stopped.error);\n }\n\n return Effect.succeed(success);\n }),\n );\n\n const success = yield* effect.pipe(\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (Exit.isSuccess(exit)) retainReceipt(exit.value.receipt);\n else {\n state.cause = exit.cause;\n const error = Cause.findErrorOption(exit.cause);\n\n if (Option.isSome(error)) {\n state.error = error.value;\n state.containment = error.value.containment ?? state.containment;\n }\n }\n }).pipe(\n Effect.andThen(\n Effect.suspend(() => capture(step, state.samples, slots, state.overflow)),\n ),\n Effect.map((captured) => {\n state.capture = freezeData(captured);\n state.outcome = outcome(state, state.error);\n state.result = result(state.outcome, Exit.isFailure(exit));\n state.completed = true;\n if (Exit.isFailure(exit))\n publish?.(\n correlation(),\n Cause.hasInterrupts(exit.cause)\n ? { _tag: \"Cancelled\", outcome: state.outcome }\n : {\n _tag: \"Failed\",\n operation: \"run\",\n reason: state.error?.reason._tag ?? \"Failed\",\n outcome: state.outcome,\n },\n );\n }),\n ),\n ),\n Effect.mapError(\n (error) =>\n new StepFailed({\n stage: \"AttemptFailed\",\n stepId: step.id,\n completed: Object.freeze([...completed]),\n attempt: attemptSnapshot(state),\n error,\n }),\n ),\n );\n\n if (state.outcome === \"unknown\")\n return yield* new StepFailed({\n stage: \"AttemptFailed\",\n stepId: step.id,\n completed: Object.freeze([...completed]),\n attempt: attemptSnapshot(state),\n error: BrowserError.make({\n operation: \"run\",\n reason: Reasons.Interrupted.make({}),\n outcome: \"unknown\",\n containment: state.containment,\n }),\n });\n const captured = state.capture;\n\n if (captured === undefined)\n return yield* Effect.die(new Error(\"Terminal plan attempt lost capture evidence\"));\n completed.push(\n Object.freeze({\n id: step.id,\n sourceStep: step,\n receipt: success.receipt,\n attempt: attemptSnapshot(state),\n recorded: captured,\n ...(step.expect === undefined ? {} : { expect: step.expect }),\n resolution: step.resolution,\n ...(success.checkpoint === undefined\n ? {}\n : { checkpoint: freezeData(success.checkpoint) }),\n ...(step.action._tag === \"Wait\" &&\n step.action.mode._tag === \"Settled\" &&\n success.receipt !== undefined &&\n \"signals\" in success.receipt\n ? { settled: success.receipt }\n : {}),\n }),\n );\n }\n\n const next = plan.steps[last + 1];\n\n return freezeData({\n runId,\n version: 1 as const,\n timing,\n steps: Object.freeze([...completed]),\n completion:\n options.through === undefined\n ? { _tag: \"Complete\" as const }\n : {\n _tag: \"Through\" as const,\n through: options.through,\n next: next === undefined ? null : { index: last + 1, stepId: next.id },\n },\n });\n });\n\n const fiber = yield* worker.pipe(\n Effect.forkScoped({ startImmediately: false, uninterruptible: false }),\n );\n\n // Fiber observers cover interruption before the deferred worker evaluates any onExit.\n // Capacity and publication are released before a joined caller can resume.\n yield* Effect.sync(() => {\n fiber.addObserver((exit) => {\n releaseAll();\n terminal = true;\n Deferred.doneUnsafe(completion, exit);\n });\n });\n\n return Object.freeze({\n id: runId,\n attempts: Effect.sync(snapshot),\n completed: Deferred.await(completion),\n cancel: Fiber.interrupt(fiber),\n });\n }),\n ).pipe(Effect.provideService(Clock.Clock, configuration.clock));\n\n return {\n start,\n run: (plan: LivePlan, options?: ValidatedRunOptions): Effect.Effect<Ran, StepFailed> =>\n Effect.scoped(start(plan, options).pipe(Effect.flatMap((operation) => operation.completed))),\n };\n};\n","import { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type { RunPhase, Step } from \"../../PlanData.ts\";\nimport type { ResolvedElement, ResolvedGroup } from \"./Descriptor.ts\";\nimport type { Driver, DriverTarget } from \"./Driver.ts\";\nimport type { Ticket } from \"./Owner.ts\";\nimport type { StepExecution } from \"./PlanExecution.ts\";\nimport { actionTargets } from \"./Recording.ts\";\n\n/**\n * A plan step's native preparation. Inside the step's first admitted operation, before that\n * operation's own command, the Promise driver checks the step's preconditions and resolves its\n * targets once; every later admitted operation of the step only reactivates the resolved group.\n */\nexport const makeStepPreparation = (options: {\n readonly step: Step;\n readonly target: DriverTarget;\n readonly context: StepExecution;\n /** Charges preconditions and resolution to the admitted operation they run inside. */\n readonly chargeHostRead: (ticket: Ticket, operation: BrowserOperation) => void;\n /** The step's phase and field, reported again once preparation has run. */\n readonly current: () => readonly [RunPhase, number | undefined];\n}) => {\n const { step, target, context, chargeHostRead } = options;\n const requests = actionTargets(step.action);\n let group: ResolvedGroup | undefined;\n let prepared = false;\n\n /** The element resolved for the step's `index`th target. */\n const element = (index: number): ResolvedElement => {\n const value = group?.elements[index];\n\n if (value === undefined)\n throw BrowserError.make({\n operation: \"run\",\n reason: Reasons.Incomplete.make({}),\n outcome: \"undispatched\",\n });\n\n return value;\n };\n\n const beforeNative = async (driver: Driver, ticket: Ticket) => {\n if (!prepared) {\n if (step.expect?.before !== undefined) {\n context.phase(\"Precondition\");\n chargeHostRead(ticket, \"run\");\n await driver.expectations(step.expect.before, ticket, target);\n }\n if (requests.length > 0) {\n context.phase(\"Resolution\");\n chargeHostRead(ticket, \"resolve\");\n group = await driver.resolveGroup(requests, ticket, target, step.resolution);\n context.targets(\n requests.map((request, index) => ({\n value: element(index),\n path: request.path,\n ...(group?.samples?.[index] === undefined ? {} : { sample: group.samples[index] }),\n })),\n );\n }\n prepared = true;\n }\n group?.activate(ticket);\n ticket.check();\n context.phase(...options.current());\n };\n\n /** Releases the resolved group's retained nodes once the step is over. */\n const release = () => group?.release() ?? Promise.resolve();\n\n return { requests, element, beforeNative, release };\n};\n","import { Effect, Schema } from \"effect\";\n\nimport {\n ActionResult,\n Checkpoint,\n FillFormResult,\n InputReceipt,\n type KeyModifier,\n NavigationResult,\n type WaitForElementRequest,\n} from \"../../BrowserData.ts\";\nimport { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type {\n ActionTarget,\n InputBindings,\n Precondition,\n RunPhase,\n RunReceipt,\n SettledEvidence,\n SettledOptions,\n Step,\n ValueSource,\n} from \"../../PlanData.ts\";\nimport type { ResolvedElement } from \"./Descriptor.ts\";\nimport type { DriverTarget } from \"./Driver.ts\";\nimport type { AdmissionPolicy } from \"./Observation.ts\";\nimport type { Ticket } from \"./Owner.ts\";\nimport type { StepExecution, StepSuccess } from \"./PlanExecution.ts\";\nimport type { NativePoint } from \"./Pointer.ts\";\nimport type { ExecutionOptions, FormOutcome, FormSettings, FormSteps, Reading } from \"./Session.ts\";\nimport { makeStepPreparation } from \"./StepPreparation.ts\";\n\ntype Resolved = () => ResolvedElement;\n\n/**\n * What one plan step may do on its issued page: the page's own operations, each admitted under its\n * operation's policy, plus the few a step needs on targets it resolved itself. Step semantics live\n * here; admission, readiness and containment stay with the session that implements this port.\n */\nexport interface StepControls {\n readonly operations: {\n readonly navigate: (\n url: string,\n timeoutMillis: number | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly click: (\n target: Resolved,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly hover: (\n target: Resolved,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n readonly fill: (\n target: Resolved,\n value: string,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly type: (\n text: string,\n into: Resolved | undefined,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n readonly press: (\n key: string,\n modifiers: ReadonlyArray<KeyModifier>,\n into: Resolved | undefined,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n readonly scroll: (\n x: number,\n y: number,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly pointerMove: (\n to: NativePoint,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n readonly wheel: (\n deltaX: number,\n deltaY: number,\n at: NativePoint | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n };\n readonly selectOption: (\n target: Resolved,\n options: () => ReadonlyArray<ResolvedElement>,\n policy: AdmissionPolicy | undefined,\n operationOptions: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly settled: (\n settle: SettledOptions,\n options: ExecutionOptions,\n ) => Effect.Effect<SettledEvidence, BrowserError>;\n readonly fillForm: (\n form: FormSteps,\n policy: AdmissionPolicy | undefined,\n settings: FormSettings,\n options: ExecutionOptions,\n ) => Effect.Effect<FormOutcome, BrowserError>;\n readonly checkpoint: (\n reading: Omit<Reading, \"scope\"> & { readonly picture: boolean },\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n /** Scroll a resolved node into view. */\n readonly scrollTo: (\n target: Resolved,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n /** A plain pause on the page, admitted like any wait so the page cannot change under it. */\n readonly pause: (\n milliseconds: number,\n options: ExecutionOptions,\n ) => Effect.Effect<void, BrowserError>;\n /** Wait for a resolved node to reach a state. */\n readonly waitFor: (\n target: Resolved,\n state: WaitForElementRequest[\"state\"],\n timeoutMillis: number | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<void, BrowserError>;\n /** Check conditions on the page as one charged read. */\n readonly expectations: (\n conditions: ReadonlyArray<Precondition>,\n options: ExecutionOptions,\n ) => Effect.Effect<void, BrowserError>;\n}\n\nexport interface StepDependencies {\n /** The issued page or frame every step resolves and acts through. */\n readonly target: DriverTarget;\n readonly controls: StepControls;\n /** Charges a step's own native reads (preconditions, resolution) to its admitted operation. */\n readonly chargeHostRead: (ticket: Ticket, operation: BrowserOperation) => void;\n}\n\n/**\n * Runs plan steps on one issued page or frame: preconditions and target resolution inside the\n * step's first admitted operation, then the action, then its postconditions and checkpoint.\n */\nexport const makePlanSteps = ({ target, controls, chargeHostRead }: StepDependencies) => {\n const decodeReceipt = <S extends Schema.Constraint>(schema: S, value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() =>\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Malformed.make({}),\n outcome: \"performed\",\n }),\n ),\n );\n\n return (\n step: Step,\n inputs: InputBindings,\n context: StepExecution,\n ): Effect.Effect<StepSuccess, BrowserError> =>\n Effect.suspend(() => {\n let currentPhase: RunPhase =\n step.action._tag === \"FillForm\"\n ? \"Field\"\n : step.action._tag === \"Wait\" && step.action.mode._tag === \"Settled\"\n ? \"Settled\"\n : \"Input\";\n\n let currentField: number | undefined;\n\n const preparation = makeStepPreparation({\n step,\n target,\n context,\n chargeHostRead,\n current: () => [currentPhase, currentField],\n });\n\n const { requests, element: groupElement } = preparation;\n\n const planOptions: ExecutionOptions = {\n ...context.options,\n ...(context.performance === undefined\n ? {}\n : {\n performance: {\n plan: context.performance,\n get fieldIndex() {\n return currentField;\n },\n },\n }),\n phase: (phase, fieldIndex) => {\n currentPhase = phase;\n currentField = fieldIndex;\n context.phase(phase, fieldIndex);\n },\n beforeNative: preparation.beforeNative,\n };\n\n const indexed = (value: ActionTarget): (() => ResolvedElement) => {\n const index = requests.findIndex((request) => request.target === value);\n\n return () => groupElement(index);\n };\n\n const inputValue = (value: ValueSource): Effect.Effect<string, BrowserError> =>\n value._tag === \"Literal\"\n ? Effect.succeed(value.value)\n : inputs[value.name] === undefined\n ? Effect.fail(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Configuration.make({ path: `inputs.${value.name}` }),\n outcome: \"undispatched\",\n }),\n )\n : Effect.succeed(inputs[value.name] ?? \"\");\n\n const policy: AdmissionPolicy | undefined = context.policy?.admit;\n const action = step.action;\n\n const perform: Effect.Effect<RunReceipt, BrowserError> = Effect.suspend(() => {\n switch (action._tag) {\n case \"Navigate\":\n return controls.operations\n .navigate(action.url, action.timeoutMillis, planOptions)\n .pipe(Effect.flatMap((url) => decodeReceipt(NavigationResult, { url })));\n case \"Click\":\n return controls.operations\n .click(indexed(action.target), policy, planOptions)\n .pipe(Effect.flatMap((value) => decodeReceipt(ActionResult, value)));\n case \"Hover\":\n return controls.operations\n .hover(indexed(action.target), policy, planOptions)\n .pipe(\n Effect.flatMap((value) => decodeReceipt(InputReceipt, { ...value, kind: \"hover\" })),\n );\n case \"Fill\":\n return inputValue(action.value).pipe(\n Effect.flatMap((value) =>\n controls.operations.fill(indexed(action.target), value, policy, planOptions),\n ),\n Effect.flatMap((url) => decodeReceipt(ActionResult, { url })),\n );\n case \"Type\":\n return inputValue(action.text).pipe(\n Effect.flatMap((value) =>\n controls.operations.type(\n value,\n action.target === undefined ? undefined : indexed(action.target),\n policy,\n planOptions,\n ),\n ),\n Effect.flatMap((value) => decodeReceipt(InputReceipt, { ...value, kind: \"type\" })),\n );\n case \"Press\":\n return controls.operations\n .press(\n action.key,\n action.modifiers ?? [],\n action.target === undefined ? undefined : indexed(action.target),\n policy,\n planOptions,\n )\n .pipe(\n Effect.flatMap((value) => decodeReceipt(InputReceipt, { ...value, kind: \"press\" })),\n );\n case \"Select\":\n return controls\n .selectOption(\n indexed(action.target),\n () => action.options.map((option) => indexed(option)()),\n policy,\n planOptions,\n )\n .pipe(Effect.flatMap((url) => decodeReceipt(ActionResult, { url })));\n case \"Scroll\": {\n const mode = action.mode;\n\n return (\n mode._tag === \"By\"\n ? controls.operations.scroll(mode.deltaX, mode.deltaY, planOptions)\n : controls.scrollTo(indexed(mode.target), planOptions)\n ).pipe(Effect.flatMap((url) => decodeReceipt(ActionResult, { url })));\n }\n case \"PointerMove\":\n return controls.operations\n .pointerMove(action.to, planOptions)\n .pipe(\n Effect.flatMap((value) =>\n decodeReceipt(InputReceipt, { ...value, kind: \"pointer-move\" }),\n ),\n );\n case \"Wheel\":\n return controls.operations\n .wheel(action.deltaX, action.deltaY, action.at, planOptions)\n .pipe(\n Effect.flatMap((value) =>\n decodeReceipt(InputReceipt, {\n ...value,\n kind: \"wheel\",\n delta: { x: action.deltaX, y: action.deltaY },\n }),\n ),\n );\n case \"Wait\": {\n const mode = action.mode;\n\n if (mode._tag === \"Settled\") return controls.settled(mode, planOptions);\n if (mode._tag === \"Duration\") return controls.pause(mode.milliseconds, planOptions);\n\n return controls.waitFor(\n indexed(mode.target),\n mode.state,\n mode.timeoutMillis,\n planOptions,\n );\n }\n case \"FillForm\":\n return Effect.gen(function* () {\n // Each control reports the ID its plan target named; a descriptor its position.\n const reported = (target: ActionTarget, fallback: string) =>\n target._tag === \"Ref\" ? target.reference.elementId : fallback;\n\n const fields = yield* Effect.forEach(\n action.fields,\n (field, index): Effect.Effect<FormSteps[\"fields\"][number], BrowserError> => {\n const reportedId = reported(field.target, `field_${index}`);\n const reference = indexed(field.target);\n\n return field._tag === \"Value\"\n ? inputValue(field.value).pipe(\n Effect.map((value) => ({\n reportedId,\n reference,\n field: () => ({ elementId: reportedId, value }),\n })),\n )\n : Effect.succeed({\n reportedId,\n reference,\n field:\n field._tag === \"Checked\"\n ? () => ({ elementId: reportedId, checked: field.checked })\n : () => ({\n elementId: reportedId,\n options: field.options.map((option) => indexed(option)()),\n }),\n });\n },\n );\n\n const submit = action.submit;\n\n const result = yield* controls.fillForm(\n {\n fields,\n ...(submit === undefined\n ? {}\n : {\n submit: {\n reportedId: reported(submit, \"submit\"),\n reference: indexed(submit),\n },\n }),\n retainObservation: false,\n },\n policy,\n {\n verify: action.options?.verify ?? true,\n settleMillis: action.options?.settleMillis ?? 50,\n },\n planOptions,\n );\n\n const receipt = yield* decodeReceipt(FillFormResult, result);\n\n context.retainReceipt(receipt);\n if (result.stopped !== undefined) return yield* result.stopped.error;\n\n return receipt;\n });\n }\n });\n\n return perform.pipe(\n Effect.tap((receipt) => Effect.sync(() => context.retainReceipt(receipt))),\n Effect.flatMap((receipt) => {\n const checkpointOptions = context.checkpoint;\n\n const after =\n step.expect?.after === undefined\n ? Effect.void\n : Effect.suspend(() => {\n context.phase(\"Postcondition\");\n\n return controls.expectations(step.expect?.after ?? [], context.options);\n });\n\n return after.pipe(\n Effect.andThen(\n checkpointOptions === undefined\n ? Effect.succeed({ receipt })\n : Effect.suspend(() => {\n context.phase(\"Checkpoint\");\n\n return controls\n .checkpoint(\n { ...checkpointOptions, picture: checkpointOptions.picture ?? false },\n context.options,\n )\n .pipe(\n Effect.flatMap((value) => decodeReceipt(Checkpoint, value)),\n Effect.map((checkpoint) => ({ receipt, checkpoint })),\n );\n }),\n ),\n );\n }),\n Effect.ensuring(Effect.promise(preparation.release)),\n );\n });\n};\n","import { type Crypto, Effect } from \"effect\";\n\n/**\n * A fresh UUIDv4 from the consumer's `Crypto` service. Without secure random bytes no browser can\n * be owned safely, so a failure here is a defect rather than a typed browser error.\n */\nexport const randomUuid = (crypto: Crypto.Crypto): Effect.Effect<string> =>\n Effect.orDie(crypto.randomUUIDv4);\n","import {\n Cause,\n Clock,\n Crypto,\n Deferred,\n Duration,\n Effect,\n Exit,\n Option,\n Queue,\n Redacted,\n Schema,\n Scope,\n Tracer,\n} from \"effect\";\n\nimport type { OperationOptions, PageStatus } from \"../../Browser.ts\";\nimport {\n type FillFormRequest,\n type FrameInfo,\n type InputReceipt,\n Inventory,\n type KeyModifier,\n Observation,\n type ObservedElement,\n type PageInfo,\n type PageSuspension,\n Target,\n type Viewport,\n type WaitForElementRequest,\n} from \"../../BrowserData.ts\";\nimport type { Lifetime, Source } from \"../../BrowserRuntime.ts\";\nimport { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type {\n Descriptor,\n ResolveGuard,\n SettledOptions,\n SettledEvidence,\n RunPhase,\n} from \"../../PlanData.ts\";\nimport {\n TimelineDefaults,\n type Retention,\n type Terminal,\n type TerminalReason,\n} from \"../../TimelineData.ts\";\nimport {\n cachedTarget,\n captureMetadata,\n operationEvents,\n planPublisher,\n publish,\n} from \"../timeline/Producers.ts\";\nimport { makeRetirement } from \"../timeline/Retirement.ts\";\nimport { makeJournal } from \"../timeline/SessionJournal.ts\";\nimport { makeStore } from \"../timeline/Store.ts\";\nimport * as Trace from \"../Trace.ts\";\nimport { type CaptureMetadata, type CaptureParent } from \"./Association.ts\";\nimport type { BindingImplementation, ConnectionIdentity } from \"./Binding.ts\";\nimport type { ConnectionBindings } from \"./Bindings.ts\";\nimport { cleanupStep, type ConnectionCleanup, type ConnectionState } from \"./ConnectionCleanup.ts\";\nimport type {\n Driver,\n NativeCachedPage,\n DriverEvents,\n DriverFault,\n DriverOptions,\n DriverTarget,\n ElementTarget,\n NativeSelectOptions,\n NativeFormField,\n InputCapture,\n NativeFileSelection,\n NavigationControl,\n} from \"./Driver.ts\";\nimport { publicError } from \"./NativeCalls.ts\";\nimport type { AdmissionPolicy, ResolvedElement } from \"./Observation.ts\";\nimport { type ExecutedOperation, policyOf } from \"./OperationPolicy.ts\";\nimport {\n makeOwner,\n native,\n operationSpan,\n within,\n type Limits,\n type ObservationScope,\n type OwnedWait,\n type ExecutionEvidence,\n type PerformanceRequest,\n type Ticket,\n type WaitTicket,\n} from \"./Owner.ts\";\nimport { makePageRegistry, type PageRecord } from \"./PageRegistry.ts\";\nimport { makePlanExecution } from \"./PlanExecution.ts\";\nimport { makePlanSteps } from \"./PlanSteps.ts\";\nimport type { NativeInput, NativePoint } from \"./Pointer.ts\";\nimport { randomUuid } from \"./Random.ts\";\n\nexport type SessionLease = Lifetime;\nexport type RemoteSource<L extends SessionLease, E, R = never> = Source<L, E, R>;\n\n/** Bounds a reading of the selected document. Already validated at the public boundary. */\nexport interface Reading {\n readonly scope: \"document\" | \"viewport\";\n readonly match?: string;\n readonly maxTextBytes?: number;\n readonly maxControls?: number;\n}\n\n/** How a form proceeds. Already validated and defaulted at the public boundary. */\nexport interface FormSettings {\n readonly verify: boolean;\n readonly settleMillis: number;\n}\n\n/** Private composite bounds and evidence cannot enter through decoded public options. */\nexport interface ExecutionOptions extends OperationOptions {\n readonly performance?: PerformanceRequest;\n readonly operationDeadline?: number;\n readonly queueDeadline?: number;\n readonly evidence?: ExecutionEvidence;\n readonly beforeNative?: (driver: Driver, ticket: Ticket) => Promise<void>;\n readonly phase?: (phase: RunPhase, fieldIndex?: number) => void;\n}\n\ntype DeferredElementTarget = ElementTarget | (() => ElementTarget);\n\n/**\n * What one admission of page or registry work supplies beyond its operation's policy, which\n * decides admission, charge, observation retirement, containment and the native checks.\n */\ninterface Work extends ExecutionOptions {\n /** The exact issued target the work acts through; registry work has none. */\n readonly target?: DriverTarget;\n /** The target's connection generation: work for an earlier one is stale. */\n readonly generation?: number;\n /** The record the target was issued from, so containment closes exactly that page. */\n readonly authority?: PageRecord;\n /** The page the work is confined to, when it is not the target's own (page control). */\n readonly pageId?: string;\n /** The issued capability's own check, run before admission and again once admitted. */\n readonly validate?: (operation: BrowserOperation) => Effect.Effect<void, BrowserError>;\n /** Further checks once admitted, after validation and the page's reservation. */\n readonly preflight?: Effect.Effect<void, BrowserError>;\n /** A step of a composite operation that only reads: it sends no input and costs nothing. */\n readonly readOnly?: boolean;\n /** A composite operation's own steps keep the page's observation usable for each other. */\n readonly retainObservation?: boolean;\n /** Recovery admission's absolute bound, which also bounds waiting for the permit. */\n readonly waitUntil?: number;\n}\n\nconst codePointCount = (text: string): number => {\n let count = 0;\n\n for (const _point of text) count++;\n\n return count;\n};\n\nconst elementTarget = (value: DeferredElementTarget): ElementTarget =>\n typeof value === \"function\" ? value() : value;\n\nconst effectiveTarget = (value: ElementTarget | undefined, fallback: DriverTarget): DriverTarget =>\n typeof value === \"object\" && \"_tag\" in value && value._tag === \"ResolvedElement\"\n ? value.target\n : fallback;\n\n/**\n * A form as the form engine runs it. Each field and the submit carry the ID the outcome reports\n * for them and the exact node they act on, read when that step runs, so an outcome names only the\n * controls the caller named: there is no placeholder ID to translate back.\n */\nexport interface FormSteps {\n readonly fields: ReadonlyArray<{\n readonly reportedId: string;\n readonly reference: () => ObservedElement | ResolvedElement;\n readonly field: () => NativeFormField;\n }>;\n readonly submit?: {\n readonly reportedId: string;\n readonly reference: () => ObservedElement | ResolvedElement;\n };\n /** An observation's steps keep it usable for each other; resolved targets need no such care. */\n readonly retainObservation: boolean;\n}\n\n/** A form over one observation's controls, reporting the IDs the caller named. */\nexport const observedForm = (request: FillFormRequest): FormSteps => {\n const at = (elementId: string) => () => ({ observationId: request.observationId, elementId });\n const submit = request.submit;\n\n return {\n fields: request.fields.map((field) => ({\n reportedId: field.elementId,\n reference: at(field.elementId),\n field: () => field,\n })),\n ...(submit === undefined ? {} : { submit: { reportedId: submit, reference: at(submit) } }),\n retainObservation: true,\n };\n};\n\n/** What a form did; the public boundary decodes it. */\nexport interface FormOutcome {\n readonly fields: ReadonlyArray<{\n readonly elementId: string;\n readonly status: \"set\" | \"unchanged\";\n readonly input?: InputReceipt;\n }>;\n readonly submitted: boolean;\n readonly url: string;\n readonly submitInput?: InputReceipt;\n readonly stopped?: {\n readonly stage: \"field\" | \"verify\" | \"submit\";\n readonly elementId?: string;\n readonly error: BrowserError;\n };\n}\n\ninterface NavigationStopAttempt<E> {\n readonly result: Deferred.Deferred<void, E>;\n readonly retired: Deferred.Deferred<void>;\n running: boolean;\n committed: boolean;\n setupPending: boolean;\n}\n\n/**\n * Callers share the active attempt. Its owner may cancel it, but a committed Exit is permanent.\n * Before commitment, retry waits for actual native setup and port retirement, not the waiter.\n */\nconst makeNavigationStopCoordinator = <E, R>(\n done: () => boolean,\n attempt: (\n onDispatch: () => void,\n retainSetup: () => () => void,\n deadline?: number,\n ) => Effect.Effect<\"dispatched\" | \"settled\", E, R>,\n confirmed: () => void,\n) =>\n Effect.sync(() => {\n let current: NavigationStopAttempt<E | BrowserError> | undefined;\n\n const request = (deadline?: number): Effect.Effect<void, E | BrowserError, R> =>\n Effect.uninterruptibleMask((restore) =>\n Effect.suspend(() => {\n // Fencing may complete the navigation while a committed stop is still failing.\n if (current !== undefined && (current.running || current.committed)) {\n const joined = current;\n\n if (deadline === undefined || joined.committed)\n return restore(Deferred.await(joined.result));\n\n return restore(Effect.exit(Deferred.await(joined.result))).pipe(\n Effect.flatMap((exit) =>\n Exit.isSuccess(exit) || joined.committed\n ? exit\n : restore(Deferred.await(joined.retired)).pipe(Effect.andThen(request(deadline))),\n ),\n );\n }\n if (done()) return Effect.void;\n if (current !== undefined) {\n if (deadline !== undefined)\n return restore(Deferred.await(current.retired)).pipe(\n Effect.andThen(request(deadline)),\n );\n\n return Effect.fail(\n BrowserError.make({\n operation: \"navigate-stop\",\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n );\n }\n\n const active: NavigationStopAttempt<E | BrowserError> = {\n result: Deferred.makeUnsafe(),\n retired: Deferred.makeUnsafe(),\n running: true,\n committed: false,\n setupPending: false,\n };\n\n current = active;\n\n const retire = () => {\n active.setupPending = false;\n if (!active.running) {\n if (!active.committed && current === active) current = undefined;\n Deferred.doneUnsafe(active.retired, Effect.void);\n }\n };\n\n return restore(\n Effect.suspend(() =>\n attempt(\n () => {\n active.committed = true;\n },\n () => {\n active.setupPending = true;\n\n return retire;\n },\n deadline,\n ),\n ),\n ).pipe(\n Effect.tap((result) =>\n result === \"dispatched\" ? Effect.sync(confirmed) : Effect.void,\n ),\n Effect.asVoid,\n Effect.onExit((exit) =>\n Effect.sync(() => {\n active.running = false;\n if (!active.committed && !active.setupPending) current = undefined;\n if (!active.setupPending) Deferred.doneUnsafe(active.retired, Effect.void);\n Deferred.doneUnsafe(active.result, exit);\n }),\n ),\n );\n }),\n );\n\n return {\n stop: request(),\n recover: (deadline: number) =>\n within(request(deadline), deadline, () =>\n BrowserError.make({\n operation: \"navigate-stop\",\n reason: Reasons.Timeout.make({}),\n outcome: current?.committed === true ? \"unknown\" : \"undispatched\",\n }),\n ),\n };\n });\n\n/** Explicit callers retain the original cancellation and fail-fast admission contract. */\nexport const makeNavigationStop = <E, R>(\n done: () => boolean,\n attempt: (\n onDispatch: () => void,\n retainSetup: () => () => void,\n ) => Effect.Effect<\"dispatched\" | \"settled\", E, R>,\n confirmed: () => void,\n) =>\n makeNavigationStopCoordinator(done, attempt, confirmed).pipe(\n Effect.map((coordinator) => coordinator.stop),\n );\n\nexport interface SessionOptions<L extends SessionLease, E, R = never> {\n readonly implementation: string;\n readonly remote: RemoteSource<L, E, R>;\n /** The constructor resolves an issued binding before acquiring the lifetime. */\n readonly engine: BindingImplementation;\n /** Only a keep-alive session may detach and reattach inside this owner. */\n readonly keepAlive: boolean;\n readonly driver: DriverOptions;\n readonly maxReturnedBytes: number;\n /** Consumer E/R stays with the typed public supervisor; this installs its captured runtime. */\n readonly connectBindings?: (\n onFault: (event: DriverFault) => void,\n isActive: () => boolean,\n isCurrent: () => boolean,\n ) => Effect.Effect<ConnectionBindings, never, Scope.Scope>;\n}\n\n/**\n * One owner for page operations, bootstrap, capture and connection cleanup. The lifetime source\n * decides whether release also terminates a browser and how that termination is observed.\n */\nexport const acquireSession = Effect.fnUntraced(function* <L extends SessionLease, E, R>(\n limits: Limits & { readonly timelineLimits?: Retention },\n options: SessionOptions<L, E, R>,\n) {\n // The engine is resolved before anything is allocated, so an unissued binding costs nothing.\n const engine = options.engine;\n\n if (engine === undefined)\n return yield* BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Configuration.make({}),\n outcome: \"undispatched\",\n });\n const parentScope = yield* Scope.Scope;\n // Register the binding lifetime BEFORE the remote cleanup finalizer. On natural Scope\n // shutdown that finalizer must fence the owner before any callback finalizer can reenter it.\n const bindingLifetime = yield* Scope.fork(parentScope, \"sequential\");\n const ended = yield* Deferred.make<void>();\n const owner = yield* makeOwner(limits);\n const clock = owner.clock;\n let activeRuns = 0;\n const pageRuns = new Map<string, number>();\n const crypto = yield* Crypto.Crypto;\n const uuid = randomUuid(crypto);\n const clockId = yield* uuid;\n const originNanos = clock.monotonicTimeNanosUnsafe();\n\n const makeDomain = (storeId: string, coversFromNanos?: bigint) => {\n const store = makeStore({\n clock,\n originNanos,\n identity: { storeId, clockId },\n limits: limits.timelineLimits ?? TimelineDefaults,\n ...(coversFromNanos === undefined ? {} : { coversFromNanos }),\n });\n\n return {\n store,\n retirement: makeRetirement((reason) => {\n store.finish(reason);\n }),\n };\n };\n\n let domain = makeDomain(yield* uuid);\n let hasConnectedStore = false;\n\n let driver: Driver | undefined;\n let connectPending = false;\n // Native listeners can outlive disconnect. Authority belongs to this connection\n // lease, not merely to the current session phase or selected browser target.\n let activeConnection: object | undefined;\n let handoffToken: string | undefined;\n let reconnectTarget: string | undefined;\n let activeBindings: ConnectionBindings | undefined;\n\n const pages = makePageRegistry();\n\n const journal = makeJournal({\n store: () => domain.store,\n cachedPages: () => driver?.cachedPages() ?? [],\n pageStatus: (pageId) => {\n const record = pages.get(pageId);\n\n return record === undefined\n ? owner.state.phase === \"open\" || owner.state.phase === \"acquiring\"\n ? undefined\n : {\n phase:\n owner.state.phase === \"closing\"\n ? \"closing\"\n : owner.state.phase === \"closed\"\n ? \"closed\"\n : owner.state.phase === \"paused\"\n ? \"paused\"\n : \"stale\",\n containment:\n owner.state.phase === \"uncertain\"\n ? { _tag: \"SessionFenced\", generation: owner.state.generation }\n : { _tag: \"NotRequired\" },\n }\n : {\n phase: record.identity.generation === owner.state.generation ? record.phase : \"stale\",\n containment: record.containment,\n };\n },\n generation: () => owner.state.generation,\n });\n\n owner.observePhase((phase) => {\n publish(domain.store, { target: null, correlation: null, event: { _tag: \"Lifecycle\", phase } });\n });\n\n owner.observeOperations(\n operationEvents({\n store: () => domain.store,\n originNanos,\n retain: (pageId) => {\n const releaseDomain = domain.retirement.retain();\n\n const releasePage =\n pageId === undefined ? undefined : pages.get(pageId)?.retirement.retain();\n\n return () => {\n releasePage?.();\n releaseDomain();\n };\n },\n }),\n );\n\n const retirePageTimeline = (record: PageRecord, reason: TerminalReason) => {\n record.retirement.request(reason);\n };\n\n const endTimeline = (reason: TerminalReason) => {\n for (const record of pages.records()) retirePageTimeline(record, reason);\n domain.retirement.request(reason);\n };\n\n let initialTarget: DriverTarget | undefined;\n let initialInfo: PageInfo | undefined;\n let initialAuthority: ReturnType<typeof registerPage> | undefined;\n\n const pageClosed = (pageId: string, cached?: NativeCachedPage, store = domain.store) => {\n driver?.retireInitializationPage?.(pageId);\n activeBindings?.retirePage(pageId);\n const page = pages.get(pageId);\n\n // A native callback supplies the cached fact; its later owner confirmation is idempotent.\n if (page !== undefined || cached !== undefined)\n publish(store, {\n target:\n cached === undefined\n ? {\n generation: page?.identity.generation ?? owner.state.generation,\n pageId,\n frameId: null,\n document: null,\n }\n : cachedTarget(cached, owner.state.generation),\n correlation: null,\n event: { _tag: \"PageClosed\" },\n });\n if (page !== undefined) retirePageTimeline(page, \"closed\");\n\n if (page !== undefined && page.phase !== \"closing\") owner.revokePage(pageId);\n owner.retirePage(pageId);\n pages.closed(pageId);\n };\n\n const pendingPageFaults = new Map<\n string,\n { readonly generation: number; readonly authority: PageRecord | undefined }\n >();\n\n // Pages whose faults await containment, in arrival order. The pending map bounds it.\n const pageFaults = yield* Queue.unbounded<string>();\n\n const revokePage = (pageId: string, except?: AbortSignal) => {\n pages.closing(pageId);\n owner.revokePage(pageId, except);\n activeBindings?.fencePage(pageId);\n driver?.fenceInitializationPage?.(pageId);\n owner.invalidate(\"closed\", { pageId });\n };\n\n const restorePageAuthority = (pageId: string) => {\n owner.restorePageAdmission(pageId);\n driver?.restoreInitializationPage?.(pageId, owner.paused);\n activeBindings?.resumePage(pageId);\n };\n\n const fenceBindings = () => {\n activeBindings?.close();\n driver?.fenceInitialization?.();\n };\n\n const disposeBindings = Effect.gen(function* () {\n const connection = activeBindings;\n\n activeBindings = undefined;\n const callbacks = yield* Effect.exit(connection?.dispose ?? Effect.void);\n\n const registrations = yield* Effect.tryPromise({\n try: () => driver?.disposeInitialization?.() ?? Promise.resolve(),\n catch: () =>\n BrowserError.make({\n operation: \"close\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n }),\n }).pipe(Effect.exit);\n\n if (Exit.isFailure(callbacks)) return yield* Effect.failCause(callbacks.cause);\n if (Exit.isFailure(registrations)) return yield* Effect.failCause(registrations.cause);\n });\n\n const capture: CaptureParent = {\n owner,\n newCaptureId: uuid,\n resolve: (ticket, requested) => {\n const admittedDomain = domain;\n\n return native(\"capture-start\", ticket, async () => {\n if (driver === undefined)\n throw BrowserError.make({\n operation: \"capture\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n const binding = await driver.capture(requested);\n\n ticket.check();\n const generation = ticket.generation;\n\n const target = Target.make({\n generation,\n pageId: binding.pageId,\n frameId: binding.frameId,\n });\n\n const authority =\n pages.get(binding.pageId) ?? registerPage(requested, target, generation).record;\n\n const publishMetadata = captureMetadata(admittedDomain.store, originNanos);\n let releaseCapture: (() => void) | undefined;\n\n return {\n key: binding.targetId,\n target,\n metadata: (event: CaptureMetadata) => {\n if (\n releaseCapture === undefined &&\n event._tag === \"Capture\" &&\n event.phase === \"Reserved\"\n ) {\n const releaseDomain = admittedDomain.retirement.retain();\n const releasePage = authority.retirement.retain();\n\n releaseCapture = () => {\n releasePage();\n releaseDomain();\n };\n }\n publishMetadata(event);\n if (event._tag === \"Capture\" && event.phase === \"Stopped\") releaseCapture?.();\n },\n status: () => ({\n phase:\n authority.phase === \"closed\"\n ? \"closed\"\n : generation !== owner.state.generation\n ? \"stale\"\n : authority.phase,\n containment: authority.containment,\n }),\n source: binding.source,\n };\n });\n },\n captureLeases: new Map(),\n captureReservedBytes: 0,\n };\n\n owner.onInvalidate((reason, scope, origin) => {\n driver?.invalidateObservation(scope, reason === \"observation\" ? origin : undefined);\n if (scope !== \"all\" && scope !== \"none\" && (reason === \"paused\" || reason === \"closed\")) {\n const record = pages.get(scope.pageId);\n\n if (record !== undefined && record.phase !== \"open\")\n publish(record.store, {\n target: { ...record.identity, document: null },\n correlation: null,\n event: { _tag: \"Lifecycle\", phase: record.phase },\n });\n }\n if (reason === \"uncertain\" && scope === \"all\")\n for (const page of pages.records())\n pages.contain(page, { _tag: \"SessionFenced\", generation: owner.state.generation });\n if (scope === \"all\" && [\"paused\", \"disconnected\", \"uncertain\", \"closed\"].includes(reason)) {\n if (reason === \"paused\")\n for (const page of pages.records()) retirePageTimeline(page, \"stale\");\n else\n endTimeline(\n owner.reason === \"expired\"\n ? \"expired\"\n : owner.reason === \"detached\"\n ? \"detached\"\n : owner.state.phase === \"faulted\"\n ? \"faulted\"\n : reason === \"uncertain\"\n ? \"uncertain\"\n : reason === \"disconnected\"\n ? \"disconnected\"\n : \"closed\",\n );\n pages.clear();\n }\n if ([\"disconnected\", \"uncertain\", \"closed\"].includes(reason) && scope === \"all\")\n fenceBindings();\n if ([\"paused\", \"disconnected\", \"uncertain\", \"closed\"].includes(reason)) {\n if (reason !== \"paused\" && scope !== \"all\" && scope !== \"none\")\n activeBindings?.fencePage(scope.pageId);\n for (const lease of capture.captureLeases.values())\n if (scope === \"all\" || (scope !== \"none\" && lease.pageId === scope.pageId))\n lease.invalidate(reason);\n }\n });\n\n /**\n * The local half of cleanup. Each step is an independent fact for the canonical\n * coordinator, which owns the release request and the terminal status observation.\n */\n let releaseTimelineCleanup: (() => void) | undefined;\n\n const local: ConnectionCleanup = {\n fence: Effect.sync(() => {\n releaseTimelineCleanup ??= domain.retirement.retain();\n owner.fence(\"closing\", \"closed\");\n handoffToken = undefined;\n activeConnection = undefined;\n Deferred.doneUnsafe(ended, Effect.void);\n }),\n capture: Effect.suspend(() =>\n Effect.forEach([...capture.captureLeases.values()], (lease) => lease.stop, {\n discard: true,\n }),\n ),\n initialization: disposeBindings,\n disconnect: Effect.suspend(() => {\n const acquired = driver;\n\n driver = undefined;\n if (acquired === undefined)\n return Effect.succeed<ConnectionState>(connectPending ? \"pending\" : \"not-connected\");\n\n return Effect.tryPromise({\n try: () => acquired.disconnect(),\n catch: () =>\n BrowserError.make({\n operation: \"disconnect\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n }),\n }).pipe(Effect.as<ConnectionState>(\"closed\"));\n }).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n owner.transition(\"closed\");\n releaseTimelineCleanup?.();\n }),\n ),\n ),\n };\n\n // Registered before the source so natural scope closure observes its completed release first.\n let retireControl: Effect.Effect<void> = Effect.void;\n\n yield* Effect.addFinalizer(() => Effect.suspend(() => retireControl));\n\n const acquired = yield* options.remote(local, owner.lifetimeDeadline);\n\n retireControl = cleanupStep(\n Effect.suspend(() => acquired.controlRetired ?? Effect.succeed(false)),\n 2000,\n ).pipe(\n Effect.tap((result) =>\n result._tag === \"Success\" && result.value ? Effect.sync(owner.retireControl) : Effect.void,\n ),\n Effect.asVoid,\n Effect.ignoreCause,\n Effect.provideService(Clock.Clock, clock),\n );\n\n const ref: L[\"reference\"] = acquired.reference;\n // Effect.tap preserves the exact supplying lifetime's success; the generic constraint alone\n // would infer unknown here. No receipt value is decoded, constructed or coerced by this owner.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- restates L's own release type\n const release = acquired.release as Effect.Effect<Effect.Success<L[\"release\"]>>;\n const cleanupResult: L[\"cleanupResult\"] = acquired.cleanupResult;\n\n const closeScope = acquired.release.pipe(\n Effect.tap(() => retireControl),\n Effect.ensuring(Deferred.succeed(ended, undefined)),\n Effect.asVoid,\n Effect.provideService(Clock.Clock, clock),\n );\n\n const connectionEvents = (connectionLease: object, generation: number): DriverEvents => {\n const connectionDomain = domain;\n\n return {\n pageLifecycle: (event) => {\n if (activeConnection !== connectionLease) return;\n\n const target =\n event._tag === \"Navigated\"\n ? {\n generation: owner.state.generation,\n pageId: event.page.pageId,\n frameId: event.frameId,\n document: event.documentEpoch,\n }\n : cachedTarget(event.page, owner.state.generation);\n\n publish(connectionDomain.store, {\n target,\n correlation: null,\n event:\n event._tag === \"Opened\"\n ? { _tag: \"PageOpened\" }\n : event._tag === \"Navigated\"\n ? {\n _tag: \"Navigated\",\n sameDocument: event.sameDocument,\n url: event.url !== null && event.url.length <= 8192 ? event.url : null,\n urlQualification:\n event.url !== null && event.url.length > 8192\n ? \"Omitted\"\n : event.urlQualification,\n }\n : event._tag === \"Display\"\n ? {\n _tag: \"DisplayChanged\",\n selected: event.page.selected,\n displayState:\n event.page.displayState === \"suspended\" ? \"held\" : event.page.displayState,\n }\n : { _tag: \"MetadataChanged\" },\n });\n },\n pageFault: (pageId) => {\n if (activeConnection !== connectionLease) return;\n if (pendingPageFaults.has(pageId)) return;\n if (owner.state.phase !== \"open\" || pendingPageFaults.size >= options.driver.maxPages) {\n owner.terminate(\"native-failure\", \"unknown\", owner.state.generation);\n\n return;\n }\n pendingPageFaults.set(pageId, {\n generation: owner.state.generation,\n authority: pages.get(pageId),\n });\n revokePage(pageId);\n Queue.offerUnsafe(pageFaults, pageId);\n },\n frameClosed: (pageId, frameId) => {\n if (activeConnection !== connectionLease) return;\n pages.detachFrame(pageId, frameId);\n },\n pageClosed: (pageId, cached) => {\n if (activeConnection === connectionLease)\n pageClosed(pageId, cached, connectionDomain.store);\n },\n retired: () => owner.retireWait(connectionLease),\n invalidate: (reason, scope) => {\n if (activeConnection === connectionLease) owner.invalidate(reason, scope);\n },\n disconnected: () => {\n owner.retireWait(connectionLease);\n if (activeConnection !== connectionLease) return;\n if (\n owner.state.phase !== \"closing\" &&\n owner.state.phase !== \"closed\" &&\n owner.state.phase !== \"detached\"\n ) {\n owner.terminate(\"disconnected\", \"unknown\", generation);\n }\n },\n pause: (reason = \"dialog\", pageId) => {\n if (activeConnection !== connectionLease) return;\n const trigger = reason === \"popup\" ? \"popup-policy\" : \"dialog-policy\";\n\n owner.record(trigger, \"confirmed\", generation);\n if (pageId !== undefined && owner.state.phase === \"open\") {\n if (!owner.paused(pageId) && owner.pausedPages >= options.driver.maxPages) {\n owner.terminate(trigger, \"unknown\", generation);\n\n return;\n }\n pages.pause(pageId);\n activeBindings?.fencePage(pageId);\n driver?.fenceInitializationPage?.(pageId);\n owner.pausePage(pageId);\n owner.invalidate(\"paused\", { pageId });\n // This issued Page never runs again: the operator's release issues fresh Pages. Retire\n // it as an all-page pause retires every page, so work waiting on it ends now.\n const record = pages.get(pageId);\n\n if (record !== undefined) retirePageTimeline(record, \"stale\");\n\n return;\n }\n if (owner.state.phase === \"open\") owner.fence(\"paused\", \"paused\", trigger);\n // An unsolicited popup/dialog during setup cannot be silently admitted by\n // the later connect commit. No usable handle has been exposed: fail closed.\n else if (owner.state.phase === \"acquiring\") owner.terminate(trigger, \"known\", generation);\n },\n fault: (event) => {\n if (activeConnection !== connectionLease) return;\n if (event.source === \"policy\") {\n owner.policy(event, generation);\n\n return;\n }\n if (owner.state.phase === \"closing\" || owner.state.phase === \"closed\") return;\n owner.terminate(\n event.source === \"binding\"\n ? \"callback-failure\"\n : event.disposition === \"not-dispatched\"\n ? \"cleanup-capacity\"\n : event.reason === \"registration\"\n ? \"registration-failure\"\n : event.reason === \"connection\"\n ? \"disconnected\"\n : \"native-failure\",\n event.disposition,\n generation,\n );\n },\n };\n };\n\n const connectNative = (url: Redacted.Redacted<unknown>, nativeOptions: DriverOptions) =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n // Drawn before this attempt claims the connection, so a failed draw leaves nothing to undo.\n const identity: ConnectionIdentity = { namespace: yield* uuid, bindings: yield* uuid };\n\n if (hasConnectedStore) {\n endTimeline(\"detached\");\n domain = makeDomain(yield* uuid, clock.monotonicTimeNanosUnsafe() - originNanos);\n }\n hasConnectedStore = true;\n publish(domain.store, {\n target: null,\n correlation: null,\n event: { _tag: \"Lifecycle\", phase: \"acquiring\" },\n });\n const connectionLease = {};\n\n activeConnection = connectionLease;\n owner.setConnection(connectionLease);\n connectPending = true;\n const events = connectionEvents(connectionLease, owner.state.generation);\n\n const bindings =\n options.connectBindings === undefined\n ? undefined\n : yield* options\n .connectBindings(\n events.fault,\n () =>\n activeConnection === connectionLease &&\n (owner.state.phase === \"acquiring\" || owner.state.phase === \"open\"),\n () =>\n activeConnection === connectionLease &&\n [\"acquiring\", \"open\", \"paused\"].includes(owner.state.phase),\n )\n .pipe(Scope.provide(bindingLifetime));\n\n activeBindings = bindings;\n\n const retired = () =>\n activeConnection !== connectionLease ||\n [\"closing\", \"closed\", \"uncertain\", \"faulted\"].includes(owner.state.phase);\n\n if (retired()) {\n bindings?.close();\n yield* bindings?.dispose ?? Effect.void;\n\n return yield* BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n }\n\n const acquired = yield* restore(\n engine\n .connect({\n connection: Redacted.value(url),\n identity,\n options: {\n ...nativeOptions,\n ...(bindings === undefined\n ? {}\n : {\n bindings: bindings.bindings,\n onBindingFault: bindings.reportFailure,\n }),\n },\n events,\n onAbandoned: () => bindings?.close(),\n onSettled: () => {\n if (activeConnection === connectionLease) connectPending = false;\n },\n })\n .pipe(\n Trace.span(\"Browser.driver.connect\", {\n attributes: { \"browser.operation\": \"connect\" },\n }),\n ),\n );\n\n driver = acquired;\n if (\n activeConnection !== connectionLease ||\n owner.state.phase === \"closed\" ||\n owner.state.phase === \"closing\" ||\n owner.state.phase === \"uncertain\" ||\n owner.state.phase === \"faulted\"\n ) {\n yield* Effect.tryPromise({\n try: () => acquired.disconnect(),\n catch: () =>\n BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n }),\n }).pipe(Trace.span(\"Browser.driver.abandoned-disconnect\"), Effect.ignore);\n driver = undefined;\n\n return yield* BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Closed.make({}),\n outcome: \"unknown\",\n });\n }\n\n return acquired;\n }),\n );\n\n const getDriver = () => {\n if (driver === undefined)\n throw BrowserError.make({\n operation: \"target\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n\n return driver;\n };\n\n /**\n * Waits for the current document's readiness. Only work whose policy depends on an initialized\n * document asks: navigation, selection and page management deliberately do not, because\n * initialization must never deadlock the navigation that produces the document it waits for.\n */\n const requireReady = async (\n operation: BrowserOperation,\n ticket: Ticket,\n target: DriverTarget,\n ) => {\n const state = await getDriver().documentReadiness(ticket, target);\n\n if (state._tag === \"Ready\" || state._tag === \"NotApplicable\") return;\n throw BrowserError.make({\n operation,\n reason:\n state._tag === \"RequiresNavigation\" || state.reason === \"stale\"\n ? Reasons.Stale.make({})\n : state.reason === \"timeout\"\n ? Reasons.Timeout.make({})\n : Reasons.Failed.make({}),\n outcome: \"undispatched\",\n });\n };\n\n /** The policy's native checks on the exact target, before any of the work's own commands. */\n /**\n * The page checks an operation's policy requires before its native call. Work that reads no\n * document (`document: false`, a plan's duration pause) keeps the held-page refusal but never\n * waits for document readiness, so it can run before a navigation the bootstrap requires.\n */\n const prepare = async (\n operation: ExecutedOperation,\n ticket: Ticket,\n target: DriverTarget,\n reads: { readonly document?: boolean } = {},\n ) => {\n const policy = policyOf(operation);\n\n if (policy.work !== \"page\") return;\n // A held page is refused, never woken.\n if (policy.refuseHeld) await getDriver().pageControl?.checkTarget(target, ticket);\n if (policy.ready && reads.document !== false) await requireReady(operation, ticket, target);\n };\n\n /** Attribute preparation without changing the Promise's dispatch or cancellation boundary. */\n const readyNative = <A>(\n operation: ExecutedOperation,\n ticket: Ticket,\n preparation: () => Promise<void>,\n action: () => Promise<A>,\n ) =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const readiness = yield* Trace.start(\"Browser.readiness\", {\n attributes: { \"browser.operation\": operation },\n });\n\n return yield* restore(\n native(operation, ticket, async () => {\n try {\n await preparation();\n readiness?.end(Exit.void);\n } catch (error) {\n readiness?.end(Exit.fail(error));\n throw error;\n }\n\n return action();\n }),\n ).pipe(Effect.onExit((exit) => Effect.sync(() => readiness?.end(exit))));\n }),\n );\n\n const observeInside = (\n ticket: Ticket,\n maximumBytes: number,\n controls: number,\n scope: \"document\" | \"viewport\",\n match: string | undefined,\n target: DriverTarget,\n ) =>\n Effect.suspend(() => {\n const revision = owner.revision(target.pageId);\n\n return readyNative(\n \"observe\",\n ticket,\n () => prepare(\"observe\", ticket, target),\n () => getDriver().observe(scope, maximumBytes, controls, ticket, match, target),\n ).pipe(\n Effect.flatMap((raw) =>\n Effect.gen(function* () {\n if (owner.revision(target.pageId) !== revision)\n return yield* BrowserError.make({\n operation: \"observe\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n });\n\n const result = yield* Effect.try({\n try: () =>\n Observation.make({\n ...raw,\n target: Target.make({ generation: ticket.generation, ...target }),\n revision,\n }),\n catch: (error) =>\n publicError(error, \"observe\", {\n reason: Reasons.Malformed.make({}),\n outcome: \"undispatched\",\n }),\n });\n\n const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(Observation))(\n result,\n ).pipe(\n Effect.mapError(() =>\n BrowserError.make({\n operation: \"observe\",\n reason: Reasons.Malformed.make({}),\n outcome: \"undispatched\",\n }),\n ),\n );\n\n const bytes = new TextEncoder().encode(encoded).length;\n\n if (bytes > options.maxReturnedBytes) {\n return yield* BrowserError.make({\n operation: \"observe\",\n reason: Reasons.Limit.make({\n dimension: \"returned-bytes\",\n maximum: options.maxReturnedBytes,\n observed: bytes,\n }),\n outcome: \"undispatched\",\n });\n }\n\n return result;\n }).pipe(\n Trace.span(\"Browser.observe.result\", {\n attributes: { \"browser.operation\": \"observe\" },\n }),\n ),\n ),\n );\n });\n\n /** A requested text bound may narrow the policy's bound, never widen it. */\n const textBudget = (\n operation: BrowserOperation,\n requested: number | undefined,\n ): Effect.Effect<number, BrowserError> => {\n const bytes = requested ?? Math.min(options.maxReturnedBytes, 16384);\n\n return bytes > options.maxReturnedBytes\n ? Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Configuration.make({ path: \"maxTextBytes\" }),\n outcome: \"undispatched\",\n }),\n )\n : Effect.succeed(bytes);\n };\n\n /**\n * While a navigation is in flight on a page, nothing else may change that page.\n * Reads, checkpoints, holds and every other page proceed.\n */\n const unreserved = (operation: BrowserOperation, pageId: string) =>\n Effect.suspend(() =>\n owner.reserved(pageId) || owner.waitPending(pageId)\n ? Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n )\n : Effect.void,\n );\n\n /** Closing the exact affected page contains unknown input without retiring healthy peers. */\n const containment = (pageId: string, authority = pages.get(pageId)) => {\n const current = driver;\n\n if (current === undefined) return undefined;\n\n return {\n pageId,\n close: Effect.suspend(() => {\n const page = authority;\n const generation = page?.identity.generation ?? owner.state.generation;\n\n const confirmed = () => {\n if (page !== undefined && page.containment._tag === \"NotRequired\")\n pages.contain(page, { _tag: \"PageClosed\", pageId, generation });\n\n return true;\n };\n\n if (page?.phase === \"closed\") return Effect.sync(confirmed);\n if (page?.attempt !== undefined)\n return Deferred.await(page.attempt).pipe(\n Effect.timeoutOrElse({ duration: 3000, orElse: () => Effect.succeed(false) }),\n Effect.tap((closed) =>\n Effect.sync(() => {\n if (closed) confirmed();\n else pages.contain(page, { _tag: \"SessionFenced\", generation });\n }),\n ),\n );\n const attempt = Deferred.makeUnsafe<boolean>();\n\n if (page !== undefined) pages.attempting(page, attempt);\n revokePage(pageId);\n\n return Effect.promise(async () => {\n try {\n await current.containPage(pageId);\n confirmed();\n pageClosed(pageId);\n\n return true;\n } catch {\n return false;\n }\n }).pipe(\n Effect.timeoutOrElse({ duration: 3000, orElse: () => Effect.succeed(false) }),\n Effect.tap((closed) =>\n Effect.sync(() => {\n if (!closed && page !== undefined)\n pages.contain(page, { _tag: \"SessionFenced\", generation });\n }),\n ),\n Effect.tap((closed) => Deferred.succeed(attempt, closed)),\n );\n }),\n };\n };\n\n const waitFree = (operation: BrowserOperation, pageId?: string) =>\n Effect.suspend(() =>\n owner.waitPending(pageId)\n ? Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n )\n : Effect.void,\n );\n\n /**\n * Why a capability that can no longer act was refused, most specific first. A refused owner\n * outranks staleness: every phase change advances the generation, so a closed, expired,\n * disconnected or paused session must not look like a stale Page. A closed Page is closed. Only\n * work the owner would still admit is stale: a replaced generation, a closing page or a detached\n * frame, which a fresh Page or observation can replace.\n */\n const unavailable = (\n operation: BrowserOperation,\n page?: { readonly phase: \"open\" | \"paused\" | \"closing\" | \"closed\" },\n admission?: { readonly recovery?: boolean },\n ) =>\n BrowserError.make({\n operation,\n reason:\n owner.refusal(admission) ??\n (page?.phase === \"closed\" ? Reasons.Closed.make({}) : Reasons.Stale.make({})),\n outcome: \"undispatched\",\n });\n\n const checkTarget = (\n operation: BrowserOperation,\n target?: DriverTarget,\n generation?: number,\n admission?: { readonly recovery?: boolean },\n ) =>\n Effect.suspend(() =>\n (generation !== undefined && generation !== owner.state.generation) ||\n (target !== undefined && pages.get(target.pageId)?.phase === \"closing\")\n ? Effect.fail(unavailable(operation, undefined, admission))\n : Effect.void,\n );\n\n /**\n * Admits page or registry work under its operation's policy. The policy decides the permit, the\n * charge, which observations input retires and where an unknown outcome is contained; a call\n * supplies only what varies (its target, deadlines, evidence and further checks). The issued\n * capability is validated before admission and again once admitted.\n */\n const admit = <A, E, R>(\n operation: ExecutedOperation,\n body: (ticket: Ticket) => Effect.Effect<A, E, R>,\n work: Work = {},\n ): Effect.Effect<A, E | BrowserError, R> => {\n const policy = policyOf(operation);\n const page = policy.work === \"page\" ? policy : undefined;\n const pageId = page === undefined ? undefined : (work.pageId ?? work.target?.pageId);\n const mutation = policy.mutation && work.readOnly !== true;\n const charge = work.readOnly === true ? \"none\" : policy.charge;\n const scope = (): ObservationScope => (pageId === undefined ? \"none\" : { pageId });\n\n const validate = (operation: BrowserOperation) =>\n work.validate?.(operation) ?? checkTarget(operation, work.target, work.generation);\n\n // While a navigation is loading, or a native wait observes the page, nothing else may change\n // that page; recovery stops or closes exactly that work, so it is not refused by it.\n const settledPage =\n page === undefined || pageId === undefined\n ? Effect.void\n : mutation && !page.recovery\n ? unreserved(operation, pageId)\n : page.refuseWhileWaiting\n ? waitFree(operation, pageId)\n : Effect.void;\n\n return validate(operation).pipe(\n Effect.andThen(\n owner.guard(operation, body, {\n // This span opens before validation, so a refused attempt is recorded too.\n traced: false,\n ...(work.admission === undefined ? {} : { admission: work.admission }),\n ...(work.timeoutMillis === undefined ? {} : { timeoutMillis: work.timeoutMillis }),\n ...(work.operationDeadline === undefined\n ? {}\n : { operationDeadline: work.operationDeadline }),\n ...(work.queueDeadline === undefined ? {} : { queueDeadline: work.queueDeadline }),\n ...(work.evidence === undefined ? {} : { evidence: work.evidence }),\n ...(work.performance === undefined ? {} : { performance: work.performance }),\n ...(work.waitUntil === undefined ? {} : { waitUntil: work.waitUntil }),\n mutation,\n charge: charge === \"none\" ? false : charge === \"host-read\" ? \"host-read\" : true,\n recovery: page?.recovery === true,\n targetScope: scope,\n mutationScope: () => (work.retainObservation === true ? \"none\" : scope()),\n // Registry work has no page to close, so an unknown outcome fences the owner.\n contain: () =>\n pageId === undefined\n ? undefined\n : containment(pageId, pageId === work.target?.pageId ? work.authority : undefined),\n preflight: validate(operation).pipe(\n Effect.andThen(settledPage),\n Effect.andThen(work.preflight ?? Effect.void),\n ),\n }),\n ),\n operationSpan(operation),\n );\n };\n\n /**\n * One native action under its operation's policy: the policy's checks on the exact target\n * (a held page, the document's readiness), the work's own preparation, then the action.\n */\n const execute = <A>(\n operation: ExecutedOperation,\n action: (driver: Driver, ticket: Ticket) => Promise<A>,\n work: Work = {},\n ) =>\n admit(\n operation,\n (ticket) =>\n readyNative(\n operation,\n ticket,\n async () => {\n if (work.target !== undefined) await prepare(operation, ticket, work.target);\n },\n async () => {\n await work.beforeNative?.(getDriver(), ticket);\n ticket.check();\n\n return action(getDriver(), ticket);\n },\n ),\n work,\n );\n\n const wait = (\n start: (\n driver: Driver,\n ticket: WaitTicket,\n target: DriverTarget,\n operationTicket: Ticket,\n ) => Promise<void>,\n timeoutMillis: number | undefined,\n work: Work & { readonly target: DriverTarget },\n operation: \"wait\" | \"settled\" = \"wait\",\n ): Effect.Effect<void, BrowserError> =>\n Effect.suspend(() => {\n const target = work.target;\n let owned: OwnedWait | undefined;\n\n return admit(\n operation,\n (ticket) =>\n native(operation, ticket, async () => {\n const driver = getDriver();\n const connection = activeConnection;\n\n if (connection === undefined)\n throw BrowserError.make({\n operation,\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n const admitted = owner.beginWait(ticket, target, connection, operation);\n\n owned = admitted;\n let started = false;\n\n try {\n await prepare(operation, ticket, target);\n ticket.check();\n await work.beforeNative?.(driver, ticket);\n ticket.check();\n admitted.start(() => start(driver, admitted.ticket, target, ticket));\n started = true;\n\n return admitted;\n } finally {\n // Canceled readiness may still be native work: retire only when its raw task exits.\n if (!started) admitted.ticket.retire();\n }\n }),\n {\n ...work,\n ...(timeoutMillis === undefined\n ? {}\n : { timeoutMillis: Math.min(timeoutMillis, work.timeoutMillis ?? timeoutMillis) }),\n // A page has one native wait slot; a wait never starts during a loading navigation.\n preflight: Effect.suspend(() =>\n owner.waitAvailable(target.pageId)\n ? unreserved(operation, target.pageId)\n : Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n ),\n ),\n },\n ).pipe(\n Effect.flatMap((operation) => operation.completed),\n Effect.ensuring(Effect.sync(() => owned?.cancel())),\n );\n }).pipe(\n Trace.span(\"Browser.wait.completed\", { attributes: { \"browser.operation\": operation } }),\n );\n\n /** Input receipt boundaries retain the admitted exact target and original owner clock. */\n const captureClickAt =\n (target: Target, ticket: Ticket): InputCapture =>\n async (dispatch, dispatched) => {\n const startedMonotonicNanos = clock.monotonicTimeNanosUnsafe();\n\n await dispatch();\n\n const receipt = {\n ...dispatched,\n target,\n kind: \"click\" as const,\n startedMonotonicNanos,\n completedMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n };\n\n ticket.recordInput?.(receipt);\n\n return receipt;\n };\n\n const makeOperations = (\n issued: Work & {\n readonly target: DriverTarget;\n readonly generation: number;\n },\n ) => {\n const browserTarget = issued.target;\n\n const run = <A>(\n operation: ExecutedOperation,\n action: (driver: Driver, ticket: Ticket, target: DriverTarget) => Promise<A>,\n operationOptions?: ExecutionOptions,\n ) =>\n execute(operation, (driver, ticket) => action(driver, ticket, browserTarget), {\n ...issued,\n ...operationOptions,\n });\n\n const operationTarget = (target: DriverTarget) =>\n Target.make({ generation: issued.generation, ...target });\n\n /**\n * Native input, stamped on the host monotonic clock that stamps captured frames, around\n * the native command alone: admission and readiness are over before the clock is read.\n */\n const input = (\n operation: \"pointer-move\" | \"hover\" | \"wheel\" | \"press\" | \"type\",\n action: (driver: Driver, ticket: Ticket, target: DriverTarget) => Promise<NativeInput>,\n operationOptions?: ExecutionOptions,\n inputTarget?: (target: DriverTarget) => DriverTarget,\n keys?: {\n readonly count: number;\n readonly countUnit: \"unicode-codepoints\" | \"logical-strokes\";\n },\n ) =>\n run(\n operation,\n async (driver, ticket, browserTarget) => {\n // What the input is sent to, read first: input may replace the document it reaches.\n const target = operationTarget(inputTarget?.(browserTarget) ?? browserTarget);\n const startedMonotonicNanos = clock.monotonicTimeNanosUnsafe();\n const dispatched = await action(driver, ticket, browserTarget);\n\n const receipt = {\n ...dispatched,\n kind: operation,\n target,\n startedMonotonicNanos,\n completedMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n };\n\n ticket.recordInput?.(receipt, keys);\n\n return receipt;\n },\n operationOptions,\n );\n\n /**\n * Dispatches under a short permit and leaves the browser loading outside it. The reservation\n * is taken under that same permit, so no other mutation can reach the page in between, and\n * it is released only on a known outcome: an unsettled operation whose scope closes, or a\n * navigation that fails after dispatch, fences the owner exactly as an interrupted mutation\n * always has. Interrupting a waiter on `completed` stops nothing; `stop` is the one way to.\n */\n const startNavigation = (\n url: string,\n timeoutMillis: number = limits.actionTimeoutMillis,\n operationOptions?: ExecutionOptions,\n ) =>\n // Native dispatch remains interruptible; registering ownership of its outcome is atomic.\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const requestedTimeout = Math.min(\n timeoutMillis,\n operationOptions?.timeoutMillis ?? timeoutMillis,\n );\n\n const loadingDeadline = Math.min(\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 + requestedTimeout,\n owner.lifetimeDeadline,\n operationOptions?.operationDeadline ?? Number.POSITIVE_INFINITY,\n );\n\n let active = true;\n let dismissals = 0;\n let beforeUnload = false;\n let dismissalUnknown = false;\n let rejected: BrowserError | undefined;\n let reconsider = () => {};\n\n const control: NavigationControl = {\n identity: {},\n beforeUnload: () => {\n if (!active) return { dismissed: () => {} };\n beforeUnload = true;\n dismissals++;\n let settled = false;\n\n return {\n dismissed: (confirmed) => {\n if (settled || !active) return;\n settled = true;\n dismissals--;\n if (!confirmed) dismissalUnknown = true;\n reconsider();\n },\n };\n },\n };\n\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n active = false;\n }),\n );\n\n const begun = yield* restore(\n run(\n \"navigate\",\n async (driver, ticket, browserTarget) => {\n const target = operationTarget(browserTarget);\n\n const loadingStarted = Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000;\n const remainingLifetime = owner.lifetimeDeadline - loadingStarted;\n\n if (remainingLifetime <= 0)\n throw BrowserError.make({\n operation: \"navigate\",\n reason: Reasons.Expired.make({}),\n outcome: \"undispatched\",\n });\n\n const loadingTimeout = loadingDeadline - loadingStarted;\n\n if (loadingTimeout <= 0)\n throw BrowserError.make({\n operation: \"navigate\",\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n });\n\n const navigation = await driver.beginNavigation(\n url,\n loadingTimeout,\n ticket,\n browserTarget,\n control,\n );\n\n // A continuation that outlived its permit takes no reservation: whatever gave that\n // permit up has already decided this dispatch's outcome.\n ticket.check();\n\n const reservation = owner.reserve(navigation.pageId);\n\n ticket.acknowledge?.();\n\n return {\n target,\n navigation,\n reservation,\n authority: pages.get(navigation.pageId),\n recoveryDeadline: Math.min(\n loadingStarted + loadingTimeout + 3000,\n owner.lifetimeDeadline,\n ),\n };\n },\n { ...operationOptions, timeoutMillis: requestedTimeout },\n ),\n );\n\n const { navigation, reservation } = begun;\n\n const execution = yield* Trace.start(\"Browser.navigation\", {\n attributes: { \"browser.operation\": \"navigate\" },\n });\n\n const executionIdentity =\n execution === undefined\n ? undefined\n : yield* Trace.capture.pipe(Effect.provideService(Tracer.ParentSpan, execution.span));\n\n const admission =\n begun.authority?.admission ??\n owner.pageAdmission(navigation.pageId, begun.target.generation);\n\n const outcome = yield* Deferred.make<string, BrowserError>();\n const timeoutRecovery = yield* Deferred.make<boolean>();\n const unknown = yield* Deferred.make<void>();\n let pendingDecision: Exit.Exit<string, BrowserError> | undefined;\n let stopDispatched = false;\n let timedOut = false;\n let deciding = false;\n\n const failed = (reason: BrowserError[\"reason\"]) =>\n Exit.fail(BrowserError.make({ operation: \"navigate\", reason, outcome: \"unknown\" }));\n\n const settleUnknown = yield* Effect.cached(\n Effect.suspend(() => {\n const decision = pendingDecision;\n\n if (decision === undefined || Deferred.isDoneUnsafe(outcome)) return Effect.void;\n\n return owner\n .contain(containment(navigation.pageId, begun.authority), begun.target.generation)\n .pipe(\n Effect.tap((contained) =>\n Effect.sync(() => {\n reservation.settle(contained._tag === \"PageClosed\" ? \"known\" : \"unknown\");\n Deferred.doneUnsafe(\n outcome,\n decision.pipe(\n Effect.mapError((error) =>\n BrowserError.make({\n ...error,\n outcome: \"unknown\",\n containment: contained,\n }),\n ),\n ),\n );\n }),\n ),\n Effect.asVoid,\n );\n }),\n ).pipe(Effect.map(Effect.uninterruptible));\n\n /**\n * A navigation has exactly one outcome, and whoever decides it first settles the\n * reservation. It is released before anyone waiting is told, so the operation a waiter\n * runs next is admitted rather than finding its own page still reserved.\n */\n const decide = (result: Exit.Exit<string, BrowserError>, known: boolean) => {\n if (deciding || Deferred.isDoneUnsafe(outcome)) return;\n deciding = true;\n active = false;\n execution?.end(result, { \"browser.navigation.retired\": known });\n if (known) {\n reservation.settle(\"known\");\n Deferred.doneUnsafe(outcome, result);\n deciding = false;\n } else {\n pendingDecision = result;\n Deferred.doneUnsafe(unknown, Effect.void);\n }\n Deferred.doneUnsafe(timeoutRecovery, Effect.succeed(false));\n };\n\n reconsider = () => {\n if (!active || rejected === undefined || dismissals !== 0 || stopDispatched) return;\n if (beforeUnload) {\n // Both facts are required: this goto rejected and its exact dialog was dismissed.\n decide(\n dismissalUnknown ? Exit.fail(rejected) : failed(Reasons.Interrupted.make({})),\n !dismissalUnknown,\n );\n } else if (navigation.mainFrame === true && rejected.reason._tag === \"Timeout\") {\n timedOut = true;\n Deferred.doneUnsafe(timeoutRecovery, Effect.succeed(true));\n } else {\n decide(Exit.fail(rejected), false);\n }\n };\n\n navigation.settled.then(\n (url) => {\n if (!stopDispatched) decide(Exit.succeed(url), true);\n },\n (error: unknown) => {\n if (stopDispatched || Deferred.isDoneUnsafe(outcome)) return;\n\n rejected = publicError(error, \"navigate\", {\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n });\n reconsider();\n },\n );\n\n // A fence already cleared the reservation; this only releases anyone still waiting.\n const aborted = () =>\n decide(failed(timedOut ? Reasons.Timeout.make({}) : Reasons.Stale.make({})), true);\n\n reservation.signal.addEventListener(\"abort\", aborted, {\n once: true,\n });\n // Left unsettled, nothing knows what the browser did with it.\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n decide(failed(timedOut ? Reasons.Timeout.make({}) : Reasons.Stale.make({})), false);\n reservation.signal.removeEventListener(\"abort\", aborted);\n }).pipe(Effect.andThen(settleUnknown)),\n );\n yield* Deferred.await(unknown).pipe(Effect.andThen(settleUnknown), Effect.forkScoped);\n\n const stopTarget = { pageId: navigation.pageId, frameId: begun.target.frameId };\n\n const stop = yield* makeNavigationStopCoordinator(\n () => Deferred.isDoneUnsafe(outcome),\n (onDispatch, retainSetup, deadline) =>\n admit(\n \"navigate-stop\",\n (ticket) =>\n Effect.suspend(() =>\n deadline !== undefined && admission.native.stopSetupPending !== undefined\n ? Deferred.await(admission.native.stopSetupPending)\n : Effect.void,\n ).pipe(\n Effect.andThen(\n native(\"navigate-stop\", ticket, () =>\n navigation.stop(\n ticket,\n () => !Deferred.isDoneUnsafe(outcome),\n () => {\n onDispatch();\n stopDispatched = true;\n },\n () => {\n const settle = owner.beginStopSetup(admission, activeConnection);\n\n if (settle === undefined)\n throw BrowserError.make({\n operation: \"navigate-stop\",\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n });\n const retired = retainSetup();\n\n return () => {\n settle();\n retired();\n };\n },\n ),\n ),\n ),\n Effect.timeoutOrElse({\n duration: Math.min(3000, ticket.remainingMillis()),\n orElse: () =>\n Effect.fail(\n BrowserError.make({\n operation: \"navigate-stop\",\n reason: Reasons.Timeout.make({}),\n outcome: ticket.dispatched ? \"unknown\" : \"undispatched\",\n }),\n ),\n }),\n ),\n {\n target: stopTarget,\n generation: begun.target.generation,\n ...(begun.authority === undefined ? {} : { authority: begun.authority }),\n // Stopping is recovery: the lifecycle barrier and policy cleanup do not refuse it.\n validate: (operation) =>\n checkTarget(operation, stopTarget, begun.target.generation, { recovery: true }),\n ...(deadline === undefined ? {} : { waitUntil: deadline }),\n },\n ),\n () =>\n decide(\n failed(timedOut ? Reasons.Timeout.make({}) : Reasons.Interrupted.make({})),\n true,\n ),\n );\n\n // One operation-scoped supervisor, signalled only by the exact native timeout classifier.\n // Its absolute deadline bounds joined public stops, permit wait and late setup retirement too.\n yield* Deferred.await(timeoutRecovery).pipe(\n Effect.flatMap((recover) =>\n recover\n ? stop.recover(begun.recoveryDeadline).pipe(\n Trace.span(\"Browser.navigation.recovery\", {\n parent: executionIdentity?.parent,\n }),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (Exit.isFailure(exit)) decide(failed(Reasons.Timeout.make({})), false);\n }),\n ),\n )\n : Effect.void,\n ),\n Effect.ignoreCause,\n Effect.forkScoped,\n );\n\n return {\n target: begun.target,\n completed: Deferred.await(outcome).pipe(Trace.span(\"Browser.navigation.wait\")),\n /**\n * The browser's acknowledgement is the known outcome. Playwright's own promise is not\n * waited for: an aborted parse fires no DOMContentLoaded, so it only ever times out.\n */\n stop: stop.stop,\n };\n }),\n ).pipe(Effect.provideService(Clock.Clock, clock));\n\n return {\n startNavigation,\n // The same machinery, scoped to the call: leaving it unsettled fences, as it always has.\n navigate: (url: string, timeoutMillis?: number, operationOptions?: ExecutionOptions) =>\n Effect.scoped(\n startNavigation(url, timeoutMillis, operationOptions).pipe(\n Effect.flatMap((operation) => operation.completed),\n ),\n ),\n readText: (selector?: string, operationOptions?: ExecutionOptions) =>\n run(\n \"read-text\",\n (driver, ticket, browserTarget) =>\n driver.readText(selector, options.maxReturnedBytes, ticket, browserTarget),\n operationOptions,\n ),\n click: (\n target: DeferredElementTarget,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n run(\n \"click\",\n (driver, ticket, browserTarget) =>\n driver.click(\n elementTarget(target),\n ticket,\n captureClickAt(\n operationTarget(effectiveTarget(elementTarget(target), browserTarget)),\n ticket,\n ),\n policy,\n effectiveTarget(elementTarget(target), browserTarget),\n ),\n operationOptions,\n ),\n fill: (\n target: DeferredElementTarget,\n value: string,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n run(\n \"fill\",\n (driver, ticket, browserTarget) =>\n driver.fill(\n elementTarget(target),\n value,\n ticket,\n policy,\n effectiveTarget(elementTarget(target), browserTarget),\n ),\n operationOptions,\n ),\n scroll: (x: number, y: number, operationOptions?: ExecutionOptions) =>\n run(\n \"scroll\",\n async (driver, ticket, browserTarget) => {\n const startedMonotonicNanos = clock.monotonicTimeNanosUnsafe();\n const result = await driver.scroll(x, y, ticket, browserTarget);\n\n if (ticket.performance === undefined)\n ticket.recordScroll?.({\n target: browserTarget,\n x,\n y,\n startedMonotonicNanos,\n completedMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n });\n\n return result;\n },\n operationOptions,\n ),\n pointerMove: (to: NativePoint, operationOptions?: ExecutionOptions) =>\n input(\n \"pointer-move\",\n (driver, ticket, browserTarget) => driver.pointerMove(to, ticket, browserTarget),\n operationOptions,\n ),\n hover: (\n target: DeferredElementTarget,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n input(\n \"hover\",\n (driver, ticket, browserTarget) =>\n driver.hover(\n elementTarget(target),\n ticket,\n policy,\n effectiveTarget(elementTarget(target), browserTarget),\n ),\n operationOptions,\n (browserTarget) => effectiveTarget(elementTarget(target), browserTarget),\n ),\n wheel: (\n deltaX: number,\n deltaY: number,\n at?: NativePoint,\n operationOptions?: ExecutionOptions,\n ) =>\n input(\n \"wheel\",\n (driver, ticket, browserTarget) =>\n driver.wheel(deltaX, deltaY, at, ticket, browserTarget),\n operationOptions,\n ),\n press: (\n key: string,\n modifiers: ReadonlyArray<KeyModifier>,\n into?: DeferredElementTarget,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n input(\n \"press\",\n (driver, ticket, browserTarget) =>\n driver.press(\n key,\n modifiers,\n into === undefined ? undefined : elementTarget(into),\n ticket,\n policy,\n effectiveTarget(into === undefined ? undefined : elementTarget(into), browserTarget),\n ),\n operationOptions,\n (browserTarget) =>\n effectiveTarget(into === undefined ? undefined : elementTarget(into), browserTarget),\n { count: 1, countUnit: \"logical-strokes\" },\n ),\n type: (\n text: string,\n into?: DeferredElementTarget,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n input(\n \"type\",\n (driver, ticket, browserTarget) =>\n driver.type(\n text,\n into === undefined ? undefined : elementTarget(into),\n ticket,\n policy,\n effectiveTarget(into === undefined ? undefined : elementTarget(into), browserTarget),\n ),\n operationOptions,\n (browserTarget) =>\n effectiveTarget(into === undefined ? undefined : elementTarget(into), browserTarget),\n { count: codePointCount(text), countUnit: \"unicode-codepoints\" },\n ),\n screenshot: (full: boolean, operationOptions?: ExecutionOptions) =>\n run(\n \"screenshot\",\n (driver, ticket, browserTarget) =>\n driver.screenshot(full, options.maxReturnedBytes, ticket, browserTarget),\n operationOptions,\n ),\n };\n };\n\n /** The runtime supplies its remaining budget; endpoint sources apply their own wait limits. */\n const remainingMillis = () =>\n Math.max(\n 1,\n Math.ceil(owner.lifetimeDeadline - Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000),\n );\n\n const connectionUrl = (operation: BrowserOperation) =>\n Effect.suspend(() => acquired.connection(remainingMillis())).pipe(\n Effect.mapError((error) =>\n BrowserError.make({ operation, reason: error.reason, outcome: error.outcome }),\n ),\n );\n\n const connected = yield* Effect.cached(\n owner\n .guard(\n \"connect\",\n (ticket) =>\n connectionUrl(\"connect\").pipe(\n Effect.flatMap((url) => connectNative(url, options.driver)),\n Effect.andThen(\n native(\"connect\", ticket, async () => {\n initialTarget = getDriver().selected();\n const targetId = await getDriver().selectedTargetId();\n\n ticket.check();\n initialInfo = {\n pageId: initialTarget.pageId,\n targetId,\n url: \"\",\n title: \"\",\n selected: true,\n };\n initialAuthority = registerPage(initialInfo, initialTarget, ticket.generation);\n }),\n ),\n Effect.tap(() =>\n Effect.sync(() => {\n owner.transition(\"open\");\n }),\n ),\n ),\n { phases: [\"acquiring\"], charge: false, verifyAfter: false },\n )\n .pipe(\n Effect.onError(() => closeScope),\n Effect.onInterrupt(() => closeScope),\n ),\n );\n\n const execution = () => {\n const port = getDriver().pageControl;\n\n if (port === undefined)\n throw BrowserError.make({\n operation: \"page-control\",\n reason: Reasons.Unsupported.make({}),\n outcome: \"undispatched\",\n });\n\n return port;\n };\n\n const makePageControls = (authority: PageRecord, target: DriverTarget, generation: number) => {\n const frameAuthority = authority.frames.get(target.frameId);\n\n // Validation failures keep the operation the caller asked for.\n const validate = (operation: BrowserOperation) =>\n Effect.suspend(() =>\n authority.phase !== \"open\" || frameAuthority?.detached === true\n ? Effect.fail(unavailable(operation, authority))\n : checkTarget(operation, target, generation),\n );\n\n /** The issued capability every operation on it acts through. */\n const bound = { validate, target, generation, authority };\n\n const targetData = (actual: DriverTarget = target) => Target.make({ generation, ...actual });\n\n const controls = {\n resolve: (descriptor: Descriptor, guard: ResolveGuard, operationOptions?: ExecutionOptions) =>\n execute(\n \"resolve\",\n (driver, ticket) => driver.resolveDescriptor(descriptor, ticket, target, guard),\n { ...bound, ...operationOptions },\n ),\n settled: (\n settle: SettledOptions,\n operationOptions?: ExecutionOptions,\n ): Effect.Effect<SettledEvidence, BrowserError> =>\n Effect.suspend(() => {\n let evidence: SettledEvidence | undefined;\n\n return wait(\n async (driver, ticket, resolved, operationTicket) => {\n evidence = await driver.settled(settle, ticket, resolved);\n operationTicket.recordSettled?.(evidence, resolved);\n },\n settle.withinMillis,\n { ...bound, ...operationOptions },\n \"settled\",\n ).pipe(\n Effect.flatMap(() =>\n evidence === undefined\n ? Effect.fail(\n BrowserError.make({\n operation: \"settled\",\n reason: Reasons.Incomplete.make({}),\n outcome: \"undispatched\",\n }),\n )\n : Effect.succeed(evidence),\n ),\n );\n }),\n pageControl: {\n state: (page: PageInfo, operationOptions?: ExecutionOptions) =>\n execute(\"page-state\", (_driver, ticket) => execution().state(page, ticket), {\n ...bound,\n ...operationOptions,\n pageId: page.pageId,\n }),\n suspend: (page: PageInfo, operationOptions?: ExecutionOptions) =>\n execute(\"page-suspend\", (_driver, ticket) => execution().suspend(page, ticket), {\n ...bound,\n ...operationOptions,\n pageId: page.pageId,\n }),\n resume: (receipt: PageSuspension, operationOptions?: ExecutionOptions) =>\n execute(\"page-resume\", (_driver, ticket) => execution().resume(receipt, ticket), {\n ...bound,\n ...operationOptions,\n pageId: receipt.pageId,\n }),\n },\n operations: makeOperations(bound),\n observe: (reading: Reading = { scope: \"document\" }, operationOptions?: ExecutionOptions) =>\n textBudget(\"observe\", reading.maxTextBytes).pipe(\n Effect.flatMap((bytes) =>\n admit(\n \"observe\",\n (ticket) =>\n observeInside(\n ticket,\n bytes,\n reading.maxControls ?? 32,\n reading.scope,\n reading.match,\n target,\n ),\n { ...bound, ...operationOptions },\n ),\n ),\n ),\n /**\n * Passive: not a mutation, so the action observation and the selection are left exactly as\n * they were. A held page is refused rather than woken to be read.\n */\n checkpoint: (\n reading: Omit<Reading, \"scope\"> & { readonly picture: boolean },\n operationOptions?: ExecutionOptions,\n ) =>\n textBudget(\"checkpoint\", reading.maxTextBytes).pipe(\n Effect.flatMap((bytes) =>\n execute(\n \"checkpoint\",\n async (driver, ticket) => {\n const capturedTarget = targetData();\n const revision = owner.revision(capturedTarget.pageId);\n const startedMonotonicNanos = clock.monotonicTimeNanosUnsafe();\n\n const sampled = await driver.checkpoint(\n bytes,\n reading.maxControls ?? 32,\n reading.picture ? options.maxReturnedBytes : undefined,\n ticket,\n target,\n );\n\n return {\n ...sampled,\n target: capturedTarget,\n revision,\n startedMonotonicNanos,\n completedMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n };\n },\n { ...bound, ...operationOptions },\n ),\n ),\n ),\n controlFacts: (reference: ObservedElement, operationOptions?: ExecutionOptions) =>\n execute(\n \"control-facts\",\n (driver, ticket) => driver.controlFacts(reference, ticket, target),\n { ...bound, ...operationOptions },\n ),\n selectOption: (\n reference: ObservedElement | ResolvedElement | (() => ObservedElement | ResolvedElement),\n options: NativeSelectOptions | (() => NativeSelectOptions),\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n execute(\n \"select-option\",\n (driver, ticket) => {\n const ref = typeof reference === \"function\" ? reference() : reference;\n\n return driver.selectOption(\n ref,\n typeof options === \"function\" ? options() : options,\n ticket,\n policy,\n effectiveTarget(ref, target),\n );\n },\n { ...bound, ...operationOptions },\n ),\n /**\n * Each step is its own admitted, charged mutation that leaves the observation usable for the\n * next one; anything else that changes the page still retires it. The form ends at the first\n * refusal, and whatever it dispatched retires the observation when it ends, however it ends.\n */\n fillForm: (\n form: FormSteps,\n policy: AdmissionPolicy | undefined,\n settings: FormSettings,\n operationOptions?: ExecutionOptions,\n ) =>\n Effect.suspend(() => {\n // Each field, the verification read and the submit is its own admitted action, so each\n // captures its own action and queue deadlines when requested. A bound the caller already\n // captured, such as a plan step's, still caps every one of them.\n const formOptions: ExecutionOptions = { ...operationOptions };\n\n // The page whose observation the steps kept usable, known once one of them dispatched.\n let pageId: string | undefined;\n\n const body = Effect.gen(function* () {\n const fields: Array<{\n elementId: string;\n status: \"set\" | \"unchanged\";\n input?: InputReceipt;\n }> = [];\n\n const states: Array<string | undefined> = [];\n let url = \"\";\n\n const finish = (submitted: boolean): FormOutcome => ({ fields, submitted, url });\n\n const stop = (\n stage: \"field\" | \"verify\" | \"submit\",\n error: BrowserError,\n elementId?: string,\n ): FormOutcome => ({\n ...finish(false),\n stopped: { stage, error, ...(elementId === undefined ? {} : { elementId }) },\n });\n\n for (const [fieldIndex, step] of form.fields.entries()) {\n formOptions.phase?.(\"Field\", fieldIndex);\n\n const exit = yield* Effect.exit(\n execute(\n \"fill-form\",\n async (driver, ticket) => {\n try {\n const reference = step.reference();\n\n return await driver.formStep(\n reference,\n step.field(),\n ticket,\n policy,\n settings.settleMillis,\n captureClickAt(targetData(effectiveTarget(reference, target)), ticket),\n effectiveTarget(reference, target),\n );\n } finally {\n if (ticket.dispatched) pageId ??= target.pageId;\n }\n },\n {\n ...bound,\n ...formOptions,\n ...(form.retainObservation ? { retainObservation: true } : {}),\n },\n ),\n );\n\n if (Exit.isFailure(exit)) {\n const error = Cause.findErrorOption(exit.cause);\n\n // Interruption and defects keep their own meaning. A form that has completed no\n // step fails exactly as its first step did.\n if (Option.isNone(error) || fields.length === 0)\n return yield* Effect.failCause(exit.cause);\n\n return stop(\"field\", error.value, step.reportedId);\n }\n const done = exit.value;\n\n fields.push({\n elementId: step.reportedId,\n status: done.status,\n ...(done.input === undefined ? {} : { input: done.input }),\n });\n states.push(done.state);\n url = done.url;\n if (!done.reached)\n return stop(\n \"field\",\n BrowserError.make({\n operation: \"fill-form\",\n reason: Reasons.Failed.make({}),\n outcome: \"rejected\",\n }),\n step.reportedId,\n );\n }\n\n if (settings.verify) {\n formOptions.phase?.(\"Verification\");\n\n // Not charged, like revalidation: it sends no input and reads nodes already issued.\n const exit = yield* Effect.exit(\n execute(\n \"fill-form\",\n (driver, ticket) =>\n driver.formState(\n form.fields.map((step) => step.reference()),\n ticket,\n target,\n ),\n { ...bound, ...formOptions, readOnly: true },\n ),\n );\n\n if (Exit.isFailure(exit)) {\n const error = Cause.findErrorOption(exit.cause);\n\n if (Option.isNone(error)) return yield* Effect.failCause(exit.cause);\n\n return stop(\"verify\", error.value);\n }\n for (const [index, step] of form.fields.entries()) {\n const expected = states[index];\n\n if (expected === undefined || exit.value[index] !== expected)\n return stop(\n \"verify\",\n BrowserError.make({\n operation: \"fill-form\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n }),\n step.reportedId,\n );\n }\n }\n\n const submit = form.submit;\n\n if (submit === undefined) return finish(false);\n\n formOptions.phase?.(\"Submit\");\n\n const exit = yield* Effect.exit(\n execute(\n \"fill-form\",\n (driver, ticket) => {\n const reference = submit.reference();\n\n return driver.formSubmit(\n reference,\n ticket,\n captureClickAt(targetData(effectiveTarget(reference, target)), ticket),\n policy,\n effectiveTarget(reference, target),\n );\n },\n { ...bound, ...formOptions },\n ),\n );\n\n if (Exit.isFailure(exit)) {\n const error = Cause.findErrorOption(exit.cause);\n\n if (Option.isNone(error)) return yield* Effect.failCause(exit.cause);\n\n return stop(\"submit\", error.value, submit.reportedId);\n }\n url = exit.value.url;\n\n return { ...finish(true), submitInput: exit.value.input };\n });\n\n // The steps kept the observation usable for each other only. A submit that dispatched\n // has already retired it, as every other mutation does.\n return body.pipe(\n Effect.ensuring(\n Effect.sync(() => {\n if (pageId !== undefined) owner.invalidate(\"observation\", { pageId });\n }),\n ),\n );\n }),\n /** Not charged: it sends no input and reads one node the caller was already given. */\n revalidate: (reference: ObservedElement, operationOptions?: ExecutionOptions) =>\n execute(\"revalidate\", (driver, ticket) => driver.revalidate(reference, ticket, target), {\n ...bound,\n ...operationOptions,\n }),\n // Inspecting readiness is not an action: it charges nothing and mutates nothing.\n readiness: (operationOptions?: ExecutionOptions) =>\n execute(\"ready\", (driver, ticket) => driver.documentReadiness(ticket, target), {\n ...bound,\n ...operationOptions,\n }),\n describe: (operationOptions?: ExecutionOptions) =>\n execute(\"describe-page\", (driver, ticket) => driver.describePage(authority.info, ticket), {\n ...bound,\n ...operationOptions,\n }),\n listFrames: (operationOptions?: ExecutionOptions) =>\n execute(\"list-frames\", (driver, ticket) => driver.listFrames(ticket, authority.info), {\n ...bound,\n ...operationOptions,\n }),\n close: (operationOptions?: ExecutionOptions) =>\n Effect.suspend(() => {\n const page = authority.info;\n\n const deadline = Math.min(\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 +\n Math.min(\n operationOptions?.timeoutMillis ?? limits.actionTimeoutMillis,\n limits.actionTimeoutMillis,\n ),\n owner.lifetimeDeadline,\n );\n\n // Closure has reserved recovery admission, which neither a policy cleanup nor a\n // lifecycle barrier refuses.\n const stale = () => unavailable(\"close-page\", authority, { recovery: true });\n\n const checked = Effect.suspend(() =>\n generation !== owner.state.generation || pages.get(page.pageId) !== authority\n ? Effect.fail(stale())\n : Effect.void,\n );\n\n const joined = (attempt: Deferred.Deferred<boolean>) =>\n within(Deferred.await(attempt), deadline, () =>\n BrowserError.make({\n operation: \"close-page\",\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n }),\n ).pipe(\n Effect.flatMap((closed) =>\n closed\n ? Effect.void\n : owner.contain(containment(page.pageId, authority), generation).pipe(\n Effect.flatMap((containment) =>\n Effect.fail(\n BrowserError.make({\n operation: \"close-page\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n containment,\n }),\n ),\n ),\n ),\n ),\n );\n\n if (authority.attempt !== undefined)\n return checked.pipe(Effect.andThen(joined(authority.attempt)));\n\n return admit(\n \"close-page\",\n (ticket) =>\n Effect.gen(function* () {\n yield* native(\"close-page\", ticket, () => getDriver().resolvePage(page, ticket));\n\n if (authority.attempt !== undefined) return yield* joined(authority.attempt);\n const attempt = Deferred.makeUnsafe<boolean>();\n\n return yield* native(\"close-page\", ticket, async () => {\n try {\n await getDriver().closePage(page, ticket, () => {\n pages.attempting(authority, attempt);\n revokePage(page.pageId, ticket.signal);\n });\n pageClosed(page.pageId);\n } catch (error) {\n if (authority.attempt === attempt)\n Deferred.doneUnsafe(attempt, Effect.succeed(authority.phase === \"closed\"));\n throw error;\n }\n });\n }),\n {\n ...bound,\n ...operationOptions,\n // A paused page may still be closed; only its registration must be current.\n validate: () => checked,\n waitUntil: deadline,\n preflight: Effect.suspend(() =>\n authority.phase !== \"open\" && authority.phase !== \"paused\"\n ? Effect.fail(stale())\n : Effect.void,\n ),\n },\n );\n }).pipe(Effect.provideService(Clock.Clock, clock)),\n resize: (viewport: Viewport, operationOptions?: ExecutionOptions) =>\n execute(\"resize\", (driver, ticket) => driver.resize(viewport, ticket, target), {\n ...bound,\n ...operationOptions,\n }),\n waitFor: (\n selector: string,\n state: \"visible\" | \"hidden\" | \"attached\" | \"detached\",\n operationOptions?: ExecutionOptions,\n ) =>\n wait(\n (driver, ticket, resolved) => driver.waitFor(selector, state, ticket, resolved),\n undefined,\n { ...bound, ...operationOptions },\n ),\n waitForElement: (request: WaitForElementRequest, operationOptions?: ExecutionOptions) =>\n wait(\n (driver, ticket, target) =>\n driver.waitForElement(request.reference, request.state, ticket, target),\n request.timeoutMillis,\n { ...bound, ...operationOptions },\n ),\n clickAndWait: (element: string | ObservedElement, operationOptions?: ExecutionOptions) =>\n execute(\n \"click-and-wait\",\n (driver, ticket) =>\n driver.clickAndWait(element, ticket, captureClickAt(targetData(), ticket), target),\n { ...bound, ...operationOptions },\n ),\n clickForDownload: (element: string | ObservedElement, operationOptions?: ExecutionOptions) =>\n execute(\n \"download-action\",\n (driver, ticket) => driver.clickForDownload(element, ticket, target),\n { ...bound, ...operationOptions },\n ),\n selectFiles: (\n element: string | ObservedElement,\n files: ReadonlyArray<NativeFileSelection>,\n operationOptions?: ExecutionOptions,\n ) =>\n execute(\n \"select-files\",\n (driver, ticket) => driver.selectFiles(element, files, ticket, target),\n { ...bound, ...operationOptions },\n ),\n clickForFileSelection: (\n element: string | ObservedElement,\n files: ReadonlyArray<NativeFileSelection>,\n operationOptions?: ExecutionOptions,\n ) =>\n execute(\n \"file-chooser\",\n (driver, ticket) => driver.clickForFileSelection(element, files, ticket, target),\n { ...bound, ...operationOptions },\n ),\n validate,\n };\n\n // A plan step's own needs on this page, each admitted under its operation's policy.\n const executeStep = makePlanSteps({\n target,\n chargeHostRead: owner.chargeHostRead,\n controls: {\n operations: controls.operations,\n selectOption: controls.selectOption,\n settled: controls.settled,\n fillForm: controls.fillForm,\n checkpoint: controls.checkpoint,\n scrollTo: (element, operationOptions) =>\n execute(\n \"scroll\",\n (driver, ticket) => {\n const ref = element();\n\n return driver.scrollTo(ref, ticket, ref.target);\n },\n { ...bound, ...operationOptions },\n ),\n pause: (milliseconds, operationOptions) =>\n admit(\n \"wait\",\n (ticket) =>\n native(\"wait\", ticket, async () => {\n await prepare(\"wait\", ticket, target, { document: false });\n await operationOptions.beforeNative?.(getDriver(), ticket);\n }).pipe(\n Effect.andThen(Effect.sleep(milliseconds)),\n Effect.andThen(Effect.sync(() => ticket.check())),\n ),\n { ...bound, ...operationOptions },\n ),\n waitFor: (element, state, timeoutMillis, operationOptions) =>\n wait(\n (driver, ticket) => {\n const ref = element();\n\n return driver.waitForElement(ref, state, ticket, ref.target);\n },\n timeoutMillis,\n { ...bound, ...operationOptions },\n ),\n expectations: (conditions, operationOptions) =>\n execute(\n \"run\",\n async (driver, ticket) => {\n await driver.expectations(conditions, ticket, target);\n },\n { ...bound, ...operationOptions },\n ),\n },\n });\n\n const plans = makePlanExecution({\n clock,\n validate: validate(\"run\"),\n lifetimeDeadline: owner.lifetimeDeadline,\n actionTimeoutMillis: limits.actionTimeoutMillis,\n newId: uuid,\n newSeed: crypto.randomInt,\n publish: () => {\n const releaseDomain = domain.retirement.retain();\n const releasePage = authority.retirement.retain();\n\n return {\n append: planPublisher(domain.store, { generation, ...target, document: null }),\n release: () => {\n releasePage();\n releaseDomain();\n },\n };\n },\n retired: Effect.suspend(() =>\n Effect.raceFirst(domain.retirement.requested, authority.retirement.requested),\n ),\n reserve: Effect.suspend(() => {\n const pageId = target.pageId;\n const count = pageRuns.get(pageId) ?? 0;\n\n if (activeRuns >= 128 || count >= 32)\n return Effect.fail(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Limit.make({\n dimension: \"runs\",\n maximum: count >= 32 ? 32 : 128,\n observed: count >= 32 ? count : activeRuns,\n }),\n outcome: \"undispatched\",\n }),\n );\n activeRuns++;\n pageRuns.set(pageId, count + 1);\n let released = false;\n\n return Effect.succeed(() => {\n if (released) return;\n released = true;\n activeRuns--;\n const remaining = (pageRuns.get(pageId) ?? 1) - 1;\n\n if (remaining === 0) pageRuns.delete(pageId);\n else pageRuns.set(pageId, remaining);\n });\n }),\n executeStep,\n });\n\n return { ...controls, plans };\n };\n\n const registerPage = (info: PageInfo, target: DriverTarget, generation: number) => {\n let page = pages.get(info.pageId);\n\n if (page === undefined || page.identity.generation !== generation) {\n const identity = Target.make({ generation, ...target });\n const store = domain.store;\n let terminal: Terminal | null = null;\n\n const retirement = makeRetirement((reason) => {\n // Native closure can request retirement before the original containment receipt settles.\n // Logical owners retain this record until that confirmed outcome is available.\n const terminalReason = page?.containment._tag === \"PageClosed\" ? \"contained\" : reason;\n\n const result = publish(store, {\n target: { ...identity, document: null },\n correlation: null,\n event: { _tag: \"Terminal\", scope: \"page\", reason: terminalReason },\n });\n\n terminal = Object.freeze({\n cursor:\n result._tag === \"Appended\"\n ? Object.freeze({\n storeId: result.event.storeId,\n clockId: result.event.clockId,\n sequence: result.event.sequence,\n })\n : store.cursor(),\n at: result._tag === \"Appended\" ? result.event.at : store.now(),\n scope: \"page\",\n reason: terminalReason,\n });\n });\n\n page = pages.add({\n identity,\n admission: owner.pageAdmission(info.pageId, generation),\n info,\n paused: owner.paused(info.pageId),\n store,\n retirement,\n terminal: () => terminal,\n });\n }\n const record = page;\n\n return {\n record,\n timeline: journal.forPage(\n record.store,\n info.pageId,\n record.identity.generation,\n () => record.terminal,\n ),\n controls: makePageControls(record, target, generation),\n status: Effect.sync((): PageStatus =>\n Object.freeze({\n identity: Object.freeze({ ...record.identity }),\n phase:\n record.phase === \"closed\"\n ? \"closed\"\n : record.identity.generation !== owner.state.generation\n ? \"stale\"\n : record.phase,\n containment: Object.freeze({ ...record.containment }),\n admission: owner.admissionSnapshot(record.admission),\n }),\n ),\n };\n };\n\n /**\n * Issuing authenticates a page and registers it; it is not work on that page. It takes the\n * registry permit, so it never waits for, or is refused by, the page's own operations.\n */\n const page = (info: PageInfo, operationOptions?: ExecutionOptions) =>\n execute(\n \"target\",\n async (driver, ticket) => {\n const target = await driver.resolvePage(info, ticket);\n\n ticket.check();\n\n return registerPage(info, target, ticket.generation);\n },\n operationOptions,\n );\n\n // A generation change retires every issued capability. Rebuild from the same live connection\n // while the lifecycle permit is still held, before new operations can be admitted.\n const refreshPages = (ticket: Ticket, restore = false) =>\n native(\"list-pages\", ticket, async () => {\n const current = getDriver();\n const inventory = await current.listPages(ticket);\n const resolved = [];\n\n for (const info of inventory) {\n const target = await current.resolvePage(info, ticket);\n\n ticket.check();\n resolved.push({ info, target });\n }\n ticket.check();\n\n const fresh = Inventory.make({\n generation: ticket.generation,\n pages: Object.freeze(inventory.map((info) => Object.freeze({ ...info }))),\n });\n\n for (const { info, target } of resolved) {\n if (restore) {\n restorePageAuthority(info.pageId);\n }\n registerPage(info, target, ticket.generation);\n }\n\n return Object.freeze(fresh);\n });\n\n const listPages = (operationOptions?: ExecutionOptions) =>\n admit(\n \"list-pages\",\n (ticket) => refreshPages(ticket).pipe(Effect.map((inventory) => inventory.pages)),\n operationOptions,\n );\n\n const initialPage = () => {\n if (initialAuthority === undefined)\n throw BrowserError.make({\n operation: \"target\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n\n return initialAuthority;\n };\n\n /**\n * Waits until `drained` holds, or fails `Timeout/undispatched` at the bound. The owner signals\n * settled work; driver and binding cleanup is rechecked meanwhile.\n */\n const drainAdmitted = (operation: BrowserOperation, ticket: Ticket, drained: () => boolean) =>\n Effect.gen(function* () {\n while (!drained()) {\n yield* owner.nextChange.pipe(\n Effect.timeoutOrElse({ duration: Duration.millis(25), orElse: () => Effect.void }),\n );\n // A settlement can complete the signal synchronously; decide on a later turn.\n yield* Effect.yieldNow;\n }\n }).pipe((drain) =>\n within(\n drain,\n Math.min(ticket.deadline, Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 + 3000),\n () =>\n BrowserError.make({\n operation,\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n }),\n ),\n );\n\n const lifecycle = <A, E, R>(\n operation: BrowserOperation,\n supported: () => boolean,\n work: () => Effect.Effect<A, E, R>,\n ): Effect.Effect<A, E | BrowserError, R> =>\n // The barrier is installed and its release registered in one uninterruptible step, so an\n // interruption cannot leave every later operation refused as busy.\n Effect.acquireUseRelease(\n Effect.suspend(() => {\n if (!supported())\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Unsupported.make({}),\n outcome: \"undispatched\",\n }),\n );\n // An ordinary active caller owns its deadline. A lifecycle request refuses before\n // installing its barrier rather than converting that caller's latency into uncertainty.\n if (owner.hasActive())\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n );\n const barrier = owner.pauseAdmission();\n\n if (barrier === undefined)\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n );\n activeBindings?.pauseAdmission();\n\n return Effect.succeed(barrier);\n }),\n () => Effect.suspend(work),\n (barrier) =>\n Effect.sync(() => {\n if (owner.resumeAdmission(barrier) && owner.state.phase === \"open\")\n activeBindings?.resumeAdmission();\n }),\n );\n\n const controls = {\n listPages,\n selectPage: (page: PageInfo, operationOptions?: ExecutionOptions) =>\n execute(\n \"select-page\",\n async (driver, ticket) => {\n const target = await driver.resolvePage(page, ticket);\n\n ticket.check();\n registerPage(page, target, ticket.generation);\n await driver.selectPage(page, ticket);\n },\n operationOptions,\n ),\n /**\n * Creation and adoption use the registry lane, independently of Page work. The registration\n * it returns is what a Page is issued from, so creating and issuing are one admission.\n */\n createPage: (operationOptions?: ExecutionOptions) =>\n execute(\n \"new-page\",\n async (driver, ticket) => {\n const info = await driver.newPage(ticket);\n\n ticket.check();\n const target = await driver.resolvePage(info, ticket);\n\n return registerPage(info, target, ticket.generation);\n },\n operationOptions,\n ),\n\n monotonicTimeNanos: clock.monotonicTimeNanos,\n timeline: journal.timeline,\n pageEvents: journal.pageEvents,\n initialPage,\n page,\n frame: (\n info: PageInfo,\n frame: FrameInfo,\n generation: number,\n operationOptions?: ExecutionOptions,\n ) =>\n // Like a Page, a Frame is issued under the registry permit, not its page's own.\n execute(\n \"target\",\n async (driver, ticket) => {\n const target = await driver.resolveFrame(info, frame, ticket);\n\n ticket.check();\n const page = pages.get(info.pageId);\n\n if (page === undefined || page.phase !== \"open\")\n throw BrowserError.make({\n operation: \"target\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n });\n if (!page.frames.has(target.frameId) && page.frames.size >= 128)\n throw BrowserError.make({\n operation: \"target\",\n reason: Reasons.Limit.make({\n dimension: \"frames\",\n maximum: 128,\n observed: page.frames.size + 1,\n }),\n outcome: \"undispatched\",\n });\n const record = pages.frame(page, target.frameId);\n\n return {\n identity: Target.make({ generation, ...target }),\n record,\n controls: makePageControls(page, target, generation),\n };\n },\n { ...operationOptions, generation },\n ),\n implementation: options.implementation,\n status: owner.status,\n diagnostics: owner.diagnostics,\n admissionStatus: owner.admissionStatus,\n reference: ref,\n capture,\n cleanupResult,\n close: release.pipe(\n Effect.tap(() => retireControl),\n Effect.provideService(Clock.Clock, clock),\n ),\n closeChecked: acquired.closeChecked.pipe(\n Effect.onExit(() => retireControl),\n Effect.provideService(Clock.Clock, clock),\n ),\n liveView: <A>(issue: Effect.Effect<A, BrowserError>, operationOptions?: ExecutionOptions) =>\n owner.guard(\"live-view\", () => issue, {\n ...operationOptions,\n charge: false,\n phases: [\"open\", \"paused\"],\n }),\n beginHandoff: <A>(issue: Effect.Effect<A, BrowserError>, operationOptions?: ExecutionOptions) =>\n lifecycle(\n \"handoff\",\n () => !options.driver.pageControl,\n () =>\n owner.guard(\n \"handoff\",\n (ticket) =>\n Effect.gen(function* () {\n // Drawn before the fence, so the pause and the token that ends it commit together.\n const token = handoffToken ?? (yield* uuid);\n\n if (owner.state.phase === \"open\") {\n yield* Effect.forEach(\n [...capture.captureLeases.values()],\n (lease) => lease.stop,\n {\n discard: true,\n },\n );\n // Work that cannot settle in time fails only this request: the barrier lifts and\n // automation continues, as nothing was handed over or left undecided.\n yield* drainAdmitted(\n \"handoff\",\n ticket,\n () =>\n owner.drained(ticket.signal) &&\n activeBindings?.drained(owner.paused) !== false &&\n getDriver().handoffDrained?.(owner.paused) !== false &&\n pendingPageFaults.size === 0 &&\n capture.captureLeases.size === 0,\n );\n if (owner.state.phase !== \"open\")\n return yield* BrowserError.make({\n operation: \"handoff\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n containment: { _tag: \"SessionFenced\", generation: owner.state.generation },\n });\n owner.fence(\"paused\", \"paused\", \"handoff\");\n }\n handoffToken ??= token;\n // A refused authorization leaves automation paused until explicit operator release.\n const view = yield* issue;\n\n return { token: Redacted.make(handoffToken), view };\n }),\n {\n ...operationOptions,\n charge: false,\n phases: [\"open\", \"paused\"],\n verifyAfter: false,\n bypassBlocked: true,\n },\n ),\n ),\n resume: (\n token: Redacted.Redacted<string>,\n operatorReleasedControl: boolean,\n operationOptions?: ExecutionOptions,\n ) =>\n lifecycle(\n \"resume\",\n () => true,\n () =>\n owner.guard(\n \"resume\",\n (ticket) =>\n Effect.gen(function* () {\n if (\n !operatorReleasedControl ||\n handoffToken === undefined ||\n Redacted.value(token) !== handoffToken\n ) {\n return yield* BrowserError.make({\n operation: \"resume\",\n reason: Reasons.Authorization.make({}),\n outcome: \"undispatched\",\n });\n }\n yield* native(\"resume\", ticket, () => getDriver().dismissDialogs(ticket));\n const inventory = yield* refreshPages(ticket, true);\n\n // The fresh registry and phase commit share the lifecycle permit. Reading content\n // remains an explicit operation on a newly acquired Page.\n activeBindings?.resumeAdmission();\n owner.transition(\"open\");\n handoffToken = undefined;\n\n return inventory;\n }),\n {\n ...operationOptions,\n charge: false,\n phases: [\"paused\"],\n verifyAfter: false,\n bypassBlocked: true,\n },\n ),\n ),\n detach: lifecycle(\n \"detach\",\n () => options.keepAlive,\n () => {\n // Until the connection is given up, a failed detach leaves the session as it was.\n let disconnecting = false;\n\n return owner\n .guard(\n \"detach\",\n (ticket) =>\n Effect.gen(function* () {\n if (!options.keepAlive)\n return yield* BrowserError.make({\n operation: \"detach\",\n reason: Reasons.Unsupported.make({}),\n outcome: \"undispatched\",\n });\n\n const target = yield* native(\"detach\", ticket, () =>\n getDriver().selectedTargetId(),\n );\n\n const inventory = yield* refreshPages(ticket);\n\n if (!inventory.pages.some((info) => info.targetId === target))\n return yield* BrowserError.make({\n operation: \"detach\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n });\n // Bounded cleanup such as a page close is admitted behind the barrier; let it\n // finish rather than disconnect beneath it. Detach itself disposes bindings.\n yield* drainAdmitted(\"detach\", ticket, () => owner.idle(ticket.signal));\n const attached = getDriver();\n\n disconnecting = true;\n reconnectTarget = target;\n activeConnection = undefined;\n owner.fence(\"detached\", \"disconnected\", \"detached\");\n const initialization = yield* Effect.exit(disposeBindings);\n\n const disconnected = yield* Effect.tryPromise({\n try: () => attached.disconnect(),\n catch: () =>\n BrowserError.make({\n operation: \"detach\",\n reason: Reasons.Disconnected.make({}),\n outcome: \"unknown\",\n }),\n }).pipe(Effect.exit);\n\n driver = undefined;\n if (Exit.isFailure(initialization))\n return yield* Effect.failCause(initialization.cause);\n if (Exit.isFailure(disconnected))\n return yield* Effect.failCause(disconnected.cause);\n\n return { reference: ref, targetId: target, inventory };\n }),\n { charge: false, verifyAfter: false, bypassBlocked: true },\n )\n .pipe(\n Effect.onError(() =>\n Effect.sync(() => {\n if (disconnecting) owner.fence(\"uncertain\", \"uncertain\");\n }),\n ),\n );\n },\n ),\n reconnect: (operatorReleasedControl: boolean, operationOptions?: ExecutionOptions) =>\n lifecycle(\n \"reconnect\",\n () =>\n options.keepAlive &&\n reconnectTarget !== undefined &&\n operatorReleasedControl &&\n acquired.verifyReconnect !== undefined,\n () =>\n owner\n .guard(\n \"reconnect\",\n (ticket) =>\n Effect.gen(function* () {\n if (\n !options.keepAlive ||\n reconnectTarget === undefined ||\n !operatorReleasedControl ||\n acquired.verifyReconnect === undefined\n ) {\n return yield* BrowserError.make({\n operation: \"reconnect\",\n reason: Reasons.Unsupported.make({}),\n outcome: \"undispatched\",\n });\n }\n\n yield* acquired.verifyReconnect;\n owner.transition(\"acquiring\");\n const endpoint = yield* connectionUrl(\"reconnect\");\n\n yield* connectNative(endpoint, {\n ...options.driver,\n initialTargetId: reconnectTarget,\n newPage: false,\n preserveViewport: true,\n });\n const inventory = yield* refreshPages(ticket);\n\n owner.transition(\"open\");\n\n return inventory;\n }),\n {\n ...operationOptions,\n charge: false,\n phases: [\"detached\", \"acquiring\"],\n verifyAfter: false,\n bypassBlocked: true,\n },\n )\n .pipe(\n Effect.onError(() => closeScope),\n Effect.onInterrupt(() => closeScope),\n ),\n ),\n };\n\n yield* Queue.take(pageFaults).pipe(\n Effect.flatMap((pageId) => {\n const fault = pendingPageFaults.get(pageId);\n\n return fault === undefined\n ? Effect.void\n : owner\n .contain(containment(pageId, fault.authority), fault.generation)\n .pipe(Effect.ensuring(Effect.sync(() => pendingPageFaults.delete(pageId))));\n }),\n Effect.forever,\n Effect.forkScoped,\n );\n\n // One timer belongs to the enclosing execution, never to an individual Tool call.\n const remaining = Math.max(\n 0,\n owner.lifetimeDeadline - Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000,\n );\n\n // The execution lifetime distinguishes expiry from natural completion before\n // running the shared close path; this race has the required proven semantics.\n // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off\n yield* Effect.raceFirst(\n Effect.sleep(remaining).pipe(Effect.as(true)),\n Deferred.await(ended).pipe(Effect.as(false)),\n ).pipe(\n Effect.flatMap((expired) =>\n expired ? Effect.sync(owner.expire).pipe(Effect.andThen(closeScope)) : Effect.void,\n ),\n Effect.forkIn(parentScope),\n );\n\n return {\n reference: ref,\n /** The caller keeps its own lease type, including whether an allocation attempt exists. */\n lease: acquired,\n close: controls.close,\n connect: Effect.suspend(() =>\n owner.state.phase === \"closed\" || owner.state.phase === \"closing\"\n ? Effect.fail(\n BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n }),\n )\n : connected.pipe(Effect.as(controls)),\n ),\n };\n});\n\nexport type SessionControls<L extends SessionLease = SessionLease> =\n Effect.Success<ReturnType<typeof acquireSession<L, never, never>>> extends {\n connect: Effect.Effect<infer A, infer _E, infer _R>;\n }\n ? A\n : never;\n\nexport type TargetControls = PageControls[\"operations\"];\n\nexport type PageControls = ReturnType<SessionControls[\"initialPage\"]>[\"controls\"];\n","import { Duration, Effect, Schema } from \"effect\";\n\nimport type * as Bootstrap from \"../../Bootstrap.ts\";\nimport type {\n BrowserSession,\n Page,\n Frame,\n PageOperations,\n OperationOptions,\n} from \"../../Browser.ts\";\nimport {\n ActionResult,\n Checkpoint,\n CheckpointOptions,\n ClickRequest,\n FillFormOptions,\n FillFormRequest,\n FillFormResult,\n FillRequest,\n FrameInfo,\n HoverRequest,\n InputReceipt,\n KeyStroke,\n NavigateRequest,\n NavigationResult,\n ObservationOptions,\n ObservedElement,\n PageInfo,\n PointerMoveRequest,\n PressRequest,\n ReadTextRequest,\n ScreenshotRequest,\n ScreenshotResult,\n ScrollRequest,\n SelectOptions,\n StartNavigationRequest,\n TextResult,\n TypeRequest,\n Viewport,\n WaitForElementRequest,\n WheelRequest,\n} from \"../../BrowserData.ts\";\nimport {\n BrowserError,\n Reasons,\n type BrowserOperation,\n type BrowserOutcome,\n type Containment,\n InitializationError,\n} from \"../../Errors.ts\";\nimport { StepFailed, type RunOptions } from \"../../Plan.ts\";\nimport type { LivePlanEncoded, PlanEncoded } from \"../../PlanData.ts\";\nimport * as Trace from \"../Trace.ts\";\nimport { forPage } from \"./Association.ts\";\nimport type { Bindings } from \"./Bindings.ts\";\nimport { OperationOptionsSchema } from \"./OperationOptions.ts\";\nimport { issueFrame, issuedPageOf, issuePage, issueSession } from \"./PageRegistry.ts\";\nimport {\n checkedDescriptor,\n checkedLivePlan,\n checkedResolveOptions,\n checkedRunOptions,\n checkedSettled,\n} from \"./PlanOptions.ts\";\nimport { schemaPath } from \"./SchemaPath.ts\";\nimport {\n observedForm,\n type TargetControls,\n type SessionControls,\n type SessionLease,\n type PageControls,\n type FormOutcome,\n} from \"./Session.ts\";\n\nexport const checked = <A>(\n schema: Schema.Codec<A, unknown, never, never>,\n value: unknown,\n operation: BrowserOperation,\n) =>\n Schema.decodeUnknownEffect(schema)(value, { onExcessProperty: \"error\" }).pipe(\n Effect.mapError((error) =>\n BrowserError.make({\n operation,\n reason: Reasons.Configuration.make(schemaPath(error)),\n outcome: \"undispatched\",\n }),\n ),\n Trace.span(\"Browser.validate\", { attributes: { \"browser.operation\": operation } }),\n );\n\n/** Decode when the Effect executes and retain no caller-owned mutable admission data. */\nexport const checkedOperationOptions = (\n value: unknown,\n operation: BrowserOperation,\n): Effect.Effect<OperationOptions, BrowserError> =>\n checked(OperationOptionsSchema, value === undefined ? {} : value, operation).pipe(\n Effect.map((options) =>\n Object.freeze({\n ...(options.timeoutMillis === undefined ? {} : { timeoutMillis: options.timeoutMillis }),\n ...(options.admission === undefined\n ? {}\n : {\n admission: Object.freeze(\n options.admission.queue === undefined\n ? {}\n : {\n queue: Duration.toMillis(Duration.fromInputUnsafe(options.admission.queue)),\n },\n ),\n }),\n }),\n ),\n );\n\nconst withOperationOptions = <A, E, R>(\n options: OperationOptions | undefined,\n operation: BrowserOperation,\n use: (options: OperationOptions) => Effect.Effect<A, E, R>,\n): Effect.Effect<A, E | BrowserError, R> =>\n checkedOperationOptions(options, operation).pipe(Effect.flatMap(use));\n\nexport const decoded =\n <A>(\n schema: Schema.Codec<A, unknown, never, never>,\n operation: BrowserOperation,\n outcome: BrowserOutcome,\n containment?: Containment,\n ) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError((error) =>\n BrowserError.make({\n operation,\n reason: Reasons.Malformed.make(schemaPath(error)),\n outcome,\n ...(containment === undefined ? {} : { containment }),\n }),\n ),\n Trace.span(\"Browser.result\", { attributes: { \"browser.operation\": operation } }),\n );\n\nconst action = decoded(ActionResult, \"action-result\", \"performed\");\nconst pointerMoved = decoded(InputReceipt, \"pointer-move\", \"performed\");\nconst hovered = decoded(InputReceipt, \"hover\", \"performed\");\nconst wheeled = decoded(InputReceipt, \"wheel\", \"performed\");\nconst pressed = decoded(InputReceipt, \"press\", \"performed\");\nconst typed = decoded(InputReceipt, \"type\", \"performed\");\n\nconst formed = (value: FormOutcome) => {\n const stopped = value.stopped?.error;\n\n const outcome =\n stopped?.outcome === \"unknown\"\n ? \"unknown\"\n : value.submitted ||\n value.fields.some((field) => field.status === \"set\") ||\n stopped?.outcome === \"performed\"\n ? \"performed\"\n : \"undispatched\";\n\n return decoded(FillFormResult, \"fill-form\", outcome, stopped?.containment)(value);\n};\n\nconst makeTarget = (\n bound: TargetControls,\n): Pick<\n PageOperations,\n | \"navigate\"\n | \"startNavigation\"\n | \"readText\"\n | \"click\"\n | \"fill\"\n | \"scroll\"\n | \"pointerMove\"\n | \"hover\"\n | \"wheel\"\n | \"press\"\n | \"type\"\n | \"screenshot\"\n> => ({\n navigate: (request, options) =>\n checked(NavigateRequest, request, \"navigate\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"navigate\", (options) =>\n bound.navigate(value.url, value.timeoutMillis, options),\n ),\n ),\n Effect.flatMap((url) => decoded(NavigationResult, \"navigate\", \"performed\")({ url })),\n ),\n startNavigation: (request, options) =>\n checked(StartNavigationRequest, request, \"navigate\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"navigate\", (options) =>\n bound.startNavigation(value.url, value.timeoutMillis, options),\n ),\n ),\n Effect.map((operation) => ({\n target: operation.target,\n completed: operation.completed.pipe(\n Effect.flatMap((url) => decoded(NavigationResult, \"navigate\", \"performed\")({ url })),\n ),\n stop: operation.stop,\n })),\n ),\n readText: (request, options) =>\n checked(ReadTextRequest, request, \"read-text\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"read-text\", (options) =>\n bound.readText(value.selector, options),\n ),\n ),\n Effect.flatMap((text) => decoded(TextResult, \"read-text\", \"undispatched\")({ text })),\n ),\n click: (request, options) =>\n checked(ClickRequest, request, \"click\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"click\", (options) =>\n bound.click(value.selector, undefined, options),\n ),\n ),\n Effect.flatMap(({ url, input }) => action({ url, input })),\n ),\n fill: (request, options) =>\n checked(FillRequest, request, \"fill\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"fill\", (options) =>\n bound.fill(value.selector, value.value, undefined, options),\n ),\n ),\n Effect.flatMap((url) => action({ url })),\n ),\n scroll: (request, options) =>\n checked(ScrollRequest, request, \"scroll\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"scroll\", (options) =>\n bound.scroll(value.deltaX, value.deltaY, options),\n ),\n ),\n Effect.flatMap((url) => action({ url })),\n ),\n pointerMove: (request, options) =>\n checked(PointerMoveRequest, request, \"pointer-move\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"pointer-move\", (options) =>\n bound.pointerMove(value.to, options),\n ),\n ),\n Effect.flatMap((input) => pointerMoved({ ...input, kind: \"pointer-move\" })),\n ),\n hover: (request, options) =>\n checked(HoverRequest, request, \"hover\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"hover\", (options) =>\n bound.hover(value.selector, undefined, options),\n ),\n ),\n Effect.flatMap((input) => hovered({ ...input, kind: \"hover\" })),\n ),\n wheel: (request, options) =>\n checked(WheelRequest, request, \"wheel\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"wheel\", (options) =>\n bound\n .wheel(value.deltaX, value.deltaY, value.at, options)\n .pipe(\n Effect.flatMap((input) =>\n wheeled({ ...input, kind: \"wheel\", delta: { x: value.deltaX, y: value.deltaY } }),\n ),\n ),\n ),\n ),\n ),\n press: (request, options) =>\n checked(PressRequest, request, \"press\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"press\", (options) =>\n bound.press(value.key, value.modifiers ?? [], value.into, undefined, options),\n ),\n ),\n Effect.flatMap((input) => pressed({ ...input, kind: \"press\" })),\n ),\n type: (request, options) =>\n checked(TypeRequest, request, \"type\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"type\", (options) =>\n bound.type(value.text, value.into, undefined, options),\n ),\n ),\n Effect.flatMap((input) => typed({ ...input, kind: \"type\" })),\n ),\n screenshot: (request, options) =>\n checked(ScreenshotRequest, request, \"screenshot\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"screenshot\", (options) =>\n bound.screenshot(value.fullPage, options),\n ),\n ),\n Effect.flatMap((bytes) =>\n decoded(\n ScreenshotResult,\n \"screenshot\",\n \"undispatched\",\n )({ mediaType: \"image/png\", bytes: new Uint8Array(bytes) }),\n ),\n ),\n});\n\n/** A browser-operation failure keeps its meaning when it is reported as an initialization one. */\nconst initialization = (reason: BrowserError[\"reason\"]): InitializationError[\"reason\"] =>\n reason._tag === \"Busy\" || reason._tag === \"QueueFull\"\n ? \"busy\"\n : reason._tag === \"Closed\" || reason._tag === \"Disconnected\"\n ? \"closed\"\n : reason._tag === \"Timeout\" || reason._tag === \"QueueExpired\"\n ? \"timeout\"\n : reason._tag === \"Stale\"\n ? \"stale\"\n : reason._tag === \"Unsupported\"\n ? \"unsupported\"\n : reason._tag === \"Configuration\"\n ? \"configuration\"\n : \"native\";\n\nconst makePageOperations = (controls: PageControls): PageOperations => {\n const Wait = Schema.Struct({\n selector: ClickRequest.fields.selector,\n state: Schema.Literals([\"visible\", \"hidden\", \"attached\", \"detached\"]),\n });\n\n const navigate = (url: string) => action({ url });\n\n return {\n ...makeTarget(controls.operations),\n observe: (options = {}, operationOptions) =>\n checked(ObservationOptions, options, \"observe\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(operationOptions, \"observe\", (options) =>\n controls.observe({ ...value, scope: value.scope ?? \"document\" }, options),\n ),\n ),\n ),\n checkpoint: (options = {}, operationOptions) =>\n checked(CheckpointOptions, options, \"checkpoint\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(operationOptions, \"checkpoint\", (options) =>\n controls.checkpoint({ ...value, picture: value.picture ?? false }, options),\n ),\n ),\n Effect.flatMap(({ picture, ...sampled }) =>\n decoded(\n Checkpoint,\n \"checkpoint\",\n \"undispatched\",\n )({\n ...sampled,\n ...(picture === undefined\n ? {}\n : { picture: { mediaType: \"image/png\", bytes: new Uint8Array(picture) } }),\n }),\n ),\n ),\n controlFacts: (reference, options) =>\n checked(ObservedElement, reference, \"control-facts\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"control-facts\", (options) =>\n controls.controlFacts(value, options),\n ),\n ),\n ),\n revalidateElement: (reference, options) =>\n checked(ObservedElement, reference, \"revalidate\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"revalidate\", (options) =>\n controls.revalidate(value, options).pipe(Effect.as(value)),\n ),\n ),\n ),\n clickElement: (reference, admission, options) =>\n checked(ObservedElement, reference, \"click\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"click\", (options) =>\n controls.operations.click(value, admission?.admit, options),\n ),\n ),\n Effect.flatMap(({ url, input }) => action({ url, input })),\n ),\n fillElement: (reference, value, admission, options) =>\n checked(ObservedElement, reference, \"fill\").pipe(\n Effect.flatMap((element) =>\n checked(FillRequest.fields.value, value, \"fill\").pipe(\n Effect.flatMap((text) =>\n withOperationOptions(options, \"fill\", (options) =>\n controls.operations.fill(element, text, admission?.admit, options),\n ),\n ),\n ),\n ),\n Effect.flatMap(navigate),\n ),\n selectOption: (reference, options, admission, operationOptions) =>\n checked(ObservedElement, reference, \"select-option\").pipe(\n Effect.flatMap((element) =>\n checked(SelectOptions, options, \"select-option\").pipe(\n Effect.flatMap((ids) =>\n withOperationOptions(operationOptions, \"select-option\", (options) =>\n controls.selectOption(element, ids, admission?.admit, options),\n ),\n ),\n ),\n ),\n Effect.flatMap(navigate),\n ),\n fillForm: (request, admission, options = {}, operationOptions) =>\n checked(FillFormRequest, request, \"fill-form\").pipe(\n Effect.flatMap((form) =>\n checked(FillFormOptions, options, \"fill-form\").pipe(\n Effect.flatMap((settings) =>\n withOperationOptions(operationOptions, \"fill-form\", (options) =>\n controls.fillForm(\n observedForm(form),\n admission?.admit,\n {\n verify: settings.verify ?? true,\n settleMillis: settings.settleMillis ?? 50,\n },\n options,\n ),\n ),\n ),\n ),\n ),\n Effect.flatMap(formed),\n ),\n hoverElement: (reference, admission, options) =>\n checked(ObservedElement, reference, \"hover\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"hover\", (options) =>\n controls.operations.hover(value, admission?.admit, options),\n ),\n ),\n Effect.flatMap((input) => hovered({ ...input, kind: \"hover\" })),\n ),\n pressElement: (reference, stroke, admission, options) =>\n checked(ObservedElement, reference, \"press\").pipe(\n Effect.flatMap((element) =>\n checked(KeyStroke, stroke, \"press\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"press\", (options) =>\n controls.operations.press(\n value.key,\n value.modifiers ?? [],\n element,\n admission?.admit,\n options,\n ),\n ),\n ),\n ),\n ),\n Effect.flatMap((input) => pressed({ ...input, kind: \"press\" })),\n ),\n typeElement: (reference, text, admission, options) =>\n checked(ObservedElement, reference, \"type\").pipe(\n Effect.flatMap((element) =>\n checked(TypeRequest.fields.text, text, \"type\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"type\", (options) =>\n controls.operations.type(value, element, admission?.admit, options),\n ),\n ),\n ),\n ),\n Effect.flatMap((input) => typed({ ...input, kind: \"type\" })),\n ),\n waitFor: (request, options) =>\n checked(Wait, request, \"wait\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"wait\", (options) =>\n controls.waitFor(value.selector, value.state, options),\n ),\n ),\n ),\n waitForElement: (request, options) =>\n checked(WaitForElementRequest, request, \"wait\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"wait\", (options) =>\n controls.waitForElement(value, options),\n ),\n ),\n ),\n clickAndWait: (request, options) =>\n checked(ClickRequest, request, \"click-and-wait\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"click-and-wait\", (options) =>\n controls.clickAndWait(value.selector, options),\n ),\n ),\n Effect.flatMap(({ url, input }) => action({ url, input })),\n ),\n ready: (options = {}) =>\n checkedOperationOptions(options, \"ready\").pipe(\n Effect.flatMap((options) => controls.readiness(options)),\n Effect.mapError((error) =>\n InitializationError.make({\n operation: \"ready\",\n step: \"session\",\n reason: initialization(error.reason),\n }),\n ),\n Effect.flatMap((state) =>\n state._tag === \"NotReady\"\n ? Effect.fail(\n InitializationError.make({\n operation: \"ready\",\n step: state.step,\n reason: state.reason === \"failed\" ? \"output\" : state.reason,\n }),\n )\n : Effect.succeed<Bootstrap.ReadinessOutcome>({ _tag: state._tag }),\n ),\n ),\n };\n};\n\nconst makePlanOperations = (\n controls: PageControls,\n): Pick<Frame, \"start\" | \"run\" | \"resolve\" | \"settled\"> => {\n const prepare = (plan: LivePlanEncoded | PlanEncoded, options: RunOptions | undefined) =>\n checkedRunOptions(options).pipe(\n Effect.flatMap((options) =>\n checkedLivePlan(plan).pipe(Effect.map((plan) => ({ plan, options }))),\n ),\n Effect.mapError(\n (error) => new StepFailed({ stage: \"PreparationFailed\", completed: [], error }),\n ),\n );\n\n return {\n start: (plan, options) =>\n prepare(plan, options).pipe(\n Effect.flatMap(({ plan, options }) => controls.plans.start(plan, options)),\n ),\n run: (plan, options) =>\n prepare(plan, options).pipe(\n Effect.flatMap(({ plan, options }) => controls.plans.run(plan, options)),\n ),\n resolve: (descriptor, options) =>\n checkedResolveOptions(options).pipe(\n Effect.flatMap(({ operationOptions, guard }) =>\n checkedDescriptor(descriptor).pipe(\n Effect.flatMap((descriptor) => controls.resolve(descriptor, guard, operationOptions)),\n ),\n ),\n ),\n settled: (request, options) =>\n checkedSettled(request).pipe(\n Effect.flatMap((request) =>\n withOperationOptions(options, \"settled\", (options) => controls.settled(request, options)),\n ),\n ),\n };\n};\n\nexport const makeSession = <E>(\n controls: SessionControls<SessionLease>,\n bindings: Bindings<E>,\n): BrowserSession<E> => {\n const issuedPage = (value: ReturnType<SessionControls[\"initialPage\"]>): Page =>\n issuePage(\n value.record,\n (): Page => ({\n ...makePageOperations(value.controls),\n ...makePlanOperations(value.controls),\n timeline: value.timeline,\n identity: Object.freeze(value.record.identity),\n status: value.status,\n monotonicTimeNanos: controls.monotonicTimeNanos,\n describe: (options = {}) =>\n checkedOperationOptions(options, \"describe-page\").pipe(\n Effect.flatMap((options) => value.controls.describe(options)),\n ),\n listFrames: (options = {}) =>\n checkedOperationOptions(options, \"list-frames\").pipe(\n Effect.flatMap((options) => value.controls.listFrames(options)),\n ),\n frame: (info, options) =>\n checked(FrameInfo, info, \"target\").pipe(\n Effect.tap(() => value.controls.validate(\"target\")),\n Effect.flatMap((info) =>\n withOperationOptions(options, \"target\", (options) =>\n controls.frame(value.record.info, info, value.record.identity.generation, options),\n ),\n ),\n Effect.map((frame): Frame => {\n const issuedFrame: Frame = {\n ...makePageOperations(frame.controls),\n ...makePlanOperations(frame.controls),\n identity: Object.freeze(frame.identity),\n monotonicTimeNanos: controls.monotonicTimeNanos,\n status: value.status.pipe(\n Effect.map((status) =>\n Object.freeze({\n ...status,\n identity: frame.identity,\n phase:\n status.phase !== \"closed\" && frame.record.detached ? \"stale\" : status.phase,\n }),\n ),\n ),\n };\n\n issueFrame(issuedFrame, controls.capture.owner, frame.controls);\n\n return issuedFrame;\n }),\n ),\n resizeViewport: (viewport, options) =>\n checked(Viewport, viewport, \"resize\").pipe(\n Effect.flatMap((viewport) =>\n withOperationOptions(options, \"resize\", (options) =>\n value.controls.resize(viewport, options),\n ),\n ),\n ),\n close: (options = {}) =>\n checkedOperationOptions(options, \"close-page\").pipe(\n Effect.flatMap((options) => value.controls.close(options)),\n ),\n }),\n () => ({\n controls: value.controls,\n capture: forPage(\n controls.capture,\n value.record.info,\n value.record.identity,\n value.controls.validate,\n ),\n pageControl: { port: value.controls.pageControl, page: value.record.info },\n }),\n );\n\n const session: BrowserSession<E> = {\n monotonicTimeNanos: controls.monotonicTimeNanos,\n timeline: controls.timeline,\n pages: controls.pageEvents,\n initialPage: issuedPage(controls.initialPage()),\n page: (info, options) =>\n checked(PageInfo, info, \"target\").pipe(\n Effect.flatMap((info) =>\n withOperationOptions(options, \"target\", (options) => controls.page(info, options)),\n ),\n Effect.map(issuedPage),\n ),\n listPages: (options = {}) =>\n checkedOperationOptions(options, \"list-pages\").pipe(\n Effect.flatMap((options) => controls.listPages(options)),\n ),\n implementation: controls.implementation,\n status: controls.status,\n diagnostics: controls.diagnostics,\n admission: controls.admissionStatus,\n closeChecked: controls.closeChecked,\n failure: bindings.failure,\n bindingDiagnostics: bindings.diagnostics,\n selectPage: (page, options) =>\n Effect.suspend(() => {\n // Display selection names an issued Page by identity, never by copied metadata.\n const registration = issuedPageOf(page, controls.capture.owner);\n\n return registration === undefined\n ? Effect.fail(\n BrowserError.make({\n operation: \"select-page\",\n reason: Reasons.UnregisteredSession.make({}),\n outcome: \"undispatched\",\n }),\n )\n : registration.controls\n .validate(\"select-page\")\n .pipe(\n Effect.andThen(\n withOperationOptions(options, \"select-page\", (options) =>\n controls.selectPage(registration.record.info, options),\n ),\n ),\n );\n }),\n createPage: (options) =>\n withOperationOptions(options, \"new-page\", (options) => controls.createPage(options)).pipe(\n Effect.map(issuedPage),\n ),\n };\n\n issueSession(session, controls.capture);\n\n return session;\n};\n"],"mappings":";;;;;;;;;AAgBA,MAAaA,YAAU,OAAO,IAAI,aAAa;CAC7C,MAAM,UAAU,OAAO,OAAO,cAAc,OAAO,UAAU;CAC7D,MAAM,UAAU,OAAO,WAAW;CAClC,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,UAAU,OAAO,OAAO;CAE9B,OAAO,OAAO,OAAO,WAAW;EAC9B,IAAI;GACF,IAAI,SAAS,OAAO,eAAe,OAAO;GAE1C,OAAO,WAAW,KAAA,KAAa,QAAQ,IAAI,OAAO,aAAa,OAAO,kBAAkB,GACtF,SAAS,OAAO,SAAS,SAAS,OAAO,eAAe,OAAO,MAAM,IAAI,KAAA;GAE3E,OAAO;IACL;IACA;IACA;IACA,QACE,WAAW,KAAA,IACP,KAAA,IACA,OAAO,OACL,OAAO,aAAa;KAClB,SAAS,OAAO;KAChB,QAAQ,OAAO;KACf,SAAS,OAAO;IAClB,CAAC,CACH;GACR;EACF,QAAQ;GAEN,OAAO;IAAE,SAAS;IAAO;IAAO;IAAS,QAAQ,KAAA;GAAU;E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M,MAAM,SAAS;GAAa,MAAM,MAAM,OAAO;EAAK;CAC3E,EACF;CAEF,MAAM,UAA6B;EACjC,oBAAoB,SAAS;EAC7B,UAAU,SAAS;EACnB,OAAO,SAAS;EAChB,aAAa,WAAW,SAAS,YAAY,CAAC;EAC9C,OAAO,MAAM,YACX,QAAQ,UAAU,MAAM,QAAQ,CAAC,CAAC,KAChC,OAAO,SAAS,SACd,qBAAqB,SAAS,WAAW,YAAY,SAAS,KAAK,MAAM,OAAO,CAAC,CACnF,GACA,OAAO,IAAI,UAAU,CACvB;EACF,YAAY,UAAU,CAAC,MACrB,wBAAwB,SAAS,YAAY,CAAC,CAAC,KAC7C,OAAO,SAAS,YAAY,SAAS,UAAU,OAAO,CAAC,CACzD;EACF,gBAAgB,SAAS;EACzB,QAAQ,SAAS;EACjB,aAAa,SAAS;EACtB,WAAW,SAAS;EACpB,cAAc,SAAS;EACvB,SAAS,SAAS;EAClB,oBAAoB,SAAS;EAC7B,aAAa,MAAM,YACjB,OAAO,cAAc;GAEnB,MAAM,eAAe,aAAa,MAAM,SAAS,QAAQ,KAAK;GAE9D,OAAO,iBAAiB,KAAA,IACpB,OAAO,KACL,aAAa,KAAK;IAChB,WAAW;IACX,QAAQ,QAAQ,oBAAoB,KAAK,CAAC,CAAC;IAC3C,SAAS;GACX,CAAC,CACH,IACA,aAAa,SACV,SAAS,aAAa,CAAC,CACvB,KACC,OAAO,QACL,qBAAqB,SAAS,gBAAgB,YAC5C,SAAS,WAAW,aAAa,OAAO,MAAM,OAAO,CACvD,CACF,CACF;EACR,CAAC;EACH,aAAa,YACX,qBAAqB,SAAS,aAAa,YAAY,SAAS,WAAW,OAAO,CAAC,CAAC,CAAC,KACnF,OAAO,IAAI,UAAU,CACvB;CACJ;CAEA,aAAa,SAAS,SAAS,OAAO;CAEtC,OAAO;AACT"}
1
+ {"version":3,"file":"PublicSession-DCSMMqOj.mjs","names":["capture","failure","failure","lifecycle","Trace.span","registryView","Trace.span","Trace.start","Trace.annotate","capture","Trace.span","Trace.start","Trace.span"],"sources":["../src/internal/Trace.ts","../src/internal/browser/NativeCalls.ts","../src/internal/browser/NativePacing.ts","../src/internal/browser/Performance.ts","../src/internal/browser/Association.ts","../src/internal/timeline/Producers.ts","../src/internal/timeline/Retirement.ts","../src/internal/timeline/SessionJournal.ts","../src/internal/timeline/Store.ts","../src/internal/browser/ConnectionCleanup.ts","../src/internal/browser/OperationPolicy.ts","../src/internal/browser/Admission.ts","../src/internal/browser/Owner.ts","../src/internal/browser/PlanExecution.ts","../src/internal/browser/StepPreparation.ts","../src/internal/browser/PlanSteps.ts","../src/internal/browser/Random.ts","../src/internal/browser/Session.ts","../src/internal/browser/PublicSession.ts"],"sourcesContent":["import {\n Cause,\n Clock,\n Context,\n Effect,\n Exit,\n Option,\n References,\n Schema,\n Stream,\n Tracer,\n} from \"effect\";\n\nimport { BrowserError } from \"../Errors.ts\";\n\n/** Causality crosses ownership boundaries as ids and sampling, never a live caller context. */\nexport const capture = Effect.gen(function* () {\n const current = yield* Effect.serviceOption(Tracer.ParentSpan);\n const enabled = yield* References.TracerEnabled;\n const level = yield* Tracer.CurrentTraceLevel;\n const minimum = yield* Tracer.MinimumTraceLevel;\n\n return yield* Effect.sync(() => {\n try {\n let parent = Option.getOrUndefined(current);\n\n while (parent !== undefined && Context.get(parent.annotations, Tracer.DisablePropagation))\n parent = parent._tag === \"Span\" ? Option.getOrUndefined(parent.parent) : undefined;\n\n return {\n enabled,\n level,\n minimum,\n parent:\n parent === undefined\n ? undefined\n : Object.freeze(\n Tracer.externalSpan({\n traceId: parent.traceId,\n spanId: parent.spanId,\n sampled: parent.sampled,\n }),\n ),\n };\n } catch {\n // A broken tracer identity cannot turn causal capture into an operation defect.\n return { enabled: false, level, minimum, parent: undefined };\n }\n });\n});\n\nexport type Identity = Effect.Success<typeof capture>;\n\n/** A native page callback has no observable Tool caller. It starts a linked, sampling-aware root. */\nexport const autonomous = (identity: Identity): Tracer.SpanOptionsNoTrace => ({\n root: true,\n links: identity.parent === undefined ? [] : [{ span: identity.parent, attributes: {} }],\n ...(identity.parent?.sampled === false ? { sampled: false } : {}),\n});\n\nexport interface Started {\n readonly span: Tracer.Span;\n readonly end: (exit: Exit.Exit<unknown, unknown>, attributes?: Record<string, unknown>) => void;\n}\n\n/** Only finite, library-owned facts are passed here; exporter pressure loses telemetry only. */\nexport const annotate = (attributes: Record<string, unknown>) =>\n Effect.gen(function* () {\n if (!(yield* References.TracerEnabled)) return;\n const current = yield* Effect.serviceOption(Tracer.ParentSpan);\n\n if (Option.isNone(current) || current.value._tag !== \"Span\") return;\n const span = current.value;\n\n yield* Effect.sync(() => {\n try {\n for (const [key, value] of Object.entries(attributes)) span.attribute(key, value);\n } catch {\n // Result construction and cleanup must not depend on exporter health.\n }\n });\n });\n\n/**\n * Library spans export neither successful values nor original causes/stacks. Tracer failures\n * cannot suppress dispatch or alter its result. Sampling metadata is available in annotations\n * at creation: rc.117 applies SpanOptions.attributes only after Tracer.span has returned.\n */\nexport const start = Effect.fnUntraced(function* (\n name: string,\n options: Tracer.SpanOptionsNoTrace = {},\n): Effect.fn.Return<Started | undefined> {\n const identity = yield* capture;\n\n if (!identity.enabled) return undefined;\n const clock = yield* Clock.Clock;\n const timing = yield* References.TracerTimingEnabled;\n const attributes = options.attributes ?? {};\n\n const parent = options.parent ?? (options.root === true ? undefined : identity.parent);\n\n const created = yield* Effect.makeSpan(name, {\n ...options,\n attributes: undefined,\n parent,\n root: options.root ?? parent === undefined,\n annotations: Context.make(References.TracerSpanAnnotations, attributes),\n }).pipe(\n Effect.provideService(References.TracerSpanAnnotations, {}),\n Effect.provideService(References.TracerSpanLinks, []),\n Effect.exit,\n );\n\n if (Exit.isFailure(created)) return undefined;\n\n return yield* Effect.sync((): Started => {\n const span = created.value;\n let ended = false;\n\n try {\n for (const [key, value] of Object.entries(attributes)) span.attribute(key, value);\n } catch {\n // Retain the allocated span for one termination even if its attributes were refused.\n }\n\n return {\n span,\n end: (exit, extra = {}) => {\n if (ended) return;\n ended = true;\n const interrupted = Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause);\n\n try {\n const failure = Exit.isFailure(exit)\n ? Option.getOrUndefined(Cause.findErrorOption(exit.cause))\n : undefined;\n\n const known = Schema.is(BrowserError)(failure) ? failure : undefined;\n\n for (const [key, value] of Object.entries(extra)) span.attribute(key, value);\n span.attribute(\n \"browser.status\",\n Exit.isSuccess(exit) ? \"success\" : interrupted ? \"interrupted\" : \"failure\",\n );\n if (known !== undefined) {\n span.attribute(\"browser.reason\", known.reason._tag);\n span.attribute(\"browser.outcome\", known.outcome);\n }\n } catch {\n // Exporter pressure and shutdown are telemetry loss, never an operation failure.\n }\n try {\n span.end(\n timing ? clock.currentTimeNanosUnsafe() : 0n,\n Exit.isSuccess(exit)\n ? Exit.void\n : Exit.fail(interrupted ? \"Operation interrupted\" : \"Operation failed\"),\n );\n } catch {\n // An exporter is allowed to fail after accepting a span; never retry its termination.\n }\n },\n };\n });\n});\n\nexport const span =\n (name: string, options: Tracer.SpanOptionsNoTrace = {}) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Effect.uninterruptibleMask((restore) =>\n start(name, options).pipe(\n Effect.flatMap((started) =>\n started === undefined\n ? restore(effect)\n : restore(effect).pipe(\n Effect.provideService(Tracer.ParentSpan, started.span),\n Effect.onExit((exit) => Effect.sync(() => started.end(exit))),\n ),\n ),\n ),\n );\n\n/** One span per consumption; end after setup, pulls and the original channel scope's finalizers. */\nexport const stream =\n (name: string, options: Tracer.SpanOptionsNoTrace = {}) =>\n <A, E, R>(source: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> =>\n Stream.suspend(() => {\n let terminal: Exit.Exit<unknown, unknown> | undefined;\n\n return Stream.unwrap(\n Effect.uninterruptible(\n start(name, options).pipe(\n Effect.flatMap((value) => {\n return value === undefined\n ? Effect.succeed(source)\n : Effect.addFinalizer((exit) =>\n Effect.sync(() => value.end(terminal ?? exit)),\n ).pipe(\n Effect.as(source.pipe(Stream.provideService(Tracer.ParentSpan, value.span))),\n );\n }),\n ),\n ),\n ).pipe(\n Stream.onExit((exit) =>\n Effect.sync(() => {\n terminal = exit;\n }),\n ),\n );\n });\n","import { Exit, type Fiber, Schema } from \"effect\";\n\nimport {\n BrowserError,\n BrowserOutcome,\n Reasons,\n type BrowserOperation,\n type BrowserReason,\n} from \"../../Errors.ts\";\nimport type { ReadTicket } from \"./Owner.ts\";\n\n/** A fiber's Exit as a Promise, for native callers that cannot await an Effect. */\nexport const exitPromise = <A, E>(fiber: Fiber.Fiber<A, E>): Promise<Exit.Exit<A, E>> =>\n new Promise((resolve) => {\n fiber.addObserver(resolve);\n });\n\n/** Carries a captured Clock defect/interruption across the native Promise boundary unchanged. */\nexport class NativeEffectFailure extends Schema.TaggedError<NativeEffectFailure>()(\n \"NativeEffectFailure\",\n { cause: Schema.Cause(Schema.Never, Schema.Unknown) },\n) {}\n\n/**\n * A native step failed. It names no operation: the owner stamps the one the caller asked for\n * when it admits the work, so a step's own vocabulary can never become public API.\n */\nexport class NativeFailure extends Schema.TaggedError<NativeFailure>()(\"NativeFailure\", {\n reason: BrowserError.fields.reason,\n // Some native helpers run both before and after dispatch. Only their owner has that evidence.\n outcome: Schema.optionalKey(BrowserOutcome),\n}) {}\n\n/**\n * The only way a native failure becomes public. A fenced ticket already speaks publicly and\n * passes through with the operation the owner gave it; a native failure keeps its reason and\n * takes the caller's operation; anything else is the caller's fallback.\n */\nexport const publicError = (\n error: unknown,\n operation: BrowserOperation,\n fallback: Pick<BrowserError, \"reason\" | \"outcome\">,\n): BrowserError => {\n if (Schema.is(BrowserError)(error)) return error;\n const known = Schema.is(NativeFailure)(error) ? error : fallback;\n\n return BrowserError.make({\n operation,\n reason: known.reason,\n outcome: known.outcome ?? fallback.outcome,\n });\n};\n\n/** Shared by the Playwright driver's seams, so every native call fails in the same vocabulary. */\nexport const failure = (reason: BrowserReason, outcome?: BrowserOutcome) =>\n NativeFailure.make({ reason, ...(outcome === undefined ? {} : { outcome }) });\n\nexport const safeDecode = <A>(codec: Schema.Codec<A, unknown, never, never>, raw: unknown): A => {\n const decoded = Schema.decodeUnknownExit(codec)(raw);\n\n // A schema issue and a throw while reading the reply are both a malformed reply.\n if (Exit.isFailure(decoded)) throw failure(Reasons.Malformed.make({}));\n\n return decoded.value;\n};\n\n// oxlint-disable-next-line no-control-regex -- matches the terminal escape codes Playwright colours its call log with\nconst escapes = /\\u001b\\[[0-9;]*m/g;\n\nconst addresses = /\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s\"'<>]*/gi;\n\n/**\n * An address keeps only its origin: a path, query or user name can carry a credential, such as\n * a DevTools endpoint's browser id or a provider's signed connection URL.\n */\nconst originOf = (address: string): string => {\n try {\n const parsed = new URL(address);\n\n return parsed.host === \"\" ? `${parsed.protocol}…` : `${parsed.protocol}//${parsed.host}/…`;\n } catch {\n return \"…\";\n }\n};\n\n/**\n * The first line of what the engine said, which names the call and its reason. Playwright's\n * call log below it repeats addresses, selectors and endpoints, so it never leaves.\n */\nexport const nativeDetail = (error: unknown): string | undefined => {\n const message =\n error instanceof Error ? error.message : typeof error === \"string\" ? error : undefined;\n\n const line = message?.replace(escapes, \"\").split(\"\\n\", 1)[0]?.trim();\n\n if (line === undefined || line === \"\") return undefined;\n\n return line.replace(addresses, originOf).slice(0, 512);\n};\n\n/** A raw failure the engine raised, with what it said about it. */\nexport const providerReason = (error: unknown) => {\n const detail = nativeDetail(error);\n\n return Reasons.Provider.make(detail === undefined ? {} : { detail });\n};\n\n/**\n * No raw exception from Playwright crosses this private boundary: only its sanitized first line\n * does, as the provider reason's detail. A ticket's own fence is already a public error and\n * passes through with the operation the owner gave it.\n */\nexport const sanitize = <A>(action: () => Promise<A>): Promise<A> =>\n Promise.resolve()\n .then(action)\n .catch((error: unknown) => {\n throw Schema.is(NativeEffectFailure)(error) ||\n Schema.is(BrowserError)(error) ||\n Schema.is(NativeFailure)(error)\n ? error\n : failure(providerReason(error));\n });\n\nexport const closeWithin = async (\n action: () => Promise<unknown>,\n milliseconds = 2000,\n): Promise<void> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n await Promise.race([\n Promise.resolve().then(action),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(failure(Reasons.Timeout.make({}))), milliseconds);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n};\n\n// The native timeout is finite as well as Effect's authoritative deadline. It cannot undo dispatch.\nexport const timeout = (ticket: ReadTicket) => {\n ticket.check();\n\n return ticket.remainingMillis();\n};\n","import { type Clock, Duration, Effect, Exit } from \"effect\";\n\nimport { type BrowserError, Reasons } from \"../../Errors.ts\";\nimport { failure, NativeEffectFailure } from \"./NativeCalls.ts\";\nimport type { Performance, Ticket } from \"./Owner.ts\";\n\n/**\n * The one bridge from performed pacing back into Effect. A performed input paces between the\n * native commands of a single admitted operation, inside the Promise driver that the Playwright\n * and scripted engines share, so its pauses must be awaitable there. The sleep runs on the\n * owner's captured Clock, the clock that stamps the operation's evidence and that tests control,\n * and the admission's signal interrupts it; a failed Exit returns to the driver unchanged.\n * Scheduling the pauses in Effect instead would need the driver to expose each native command on\n * its own: a driver redesign, not a change to how pacing waits.\n */\nconst sleepOnOwnerClock = async (clock: Clock.Clock, nanos: bigint, signal: AbortSignal) => {\n // oxlint-disable-next-line no-restricted-properties -- the native Promise callback awaits only its captured Clock and carries the original Exit back to Effect\n const exit = await Effect.runPromiseExit(clock.sleep(Duration.nanos(nanos)), { signal });\n\n if (Exit.isFailure(exit)) throw NativeEffectFailure.make({ cause: exit.cause });\n};\n\n/**\n * The pacing an admitted performed operation grants its driver: the original owner's clock, the\n * time left before the operation's deadline, and pauses on that clock which the admission's\n * signal interrupts. A pause that would end at or past the deadline is refused before it starts.\n */\nexport const grantedPacing = (owner: {\n readonly clock: Clock.Clock;\n readonly deadlineNanos: () => bigint;\n readonly signal: AbortSignal;\n readonly check: () => void;\n readonly overBudget: () => BrowserError;\n}): Pick<Performance, \"now\" | \"remainingTimeNanos\" | \"pauseUntil\"> => ({\n now: () => owner.clock.monotonicTimeNanosUnsafe(),\n remainingTimeNanos: () => owner.deadlineNanos() - owner.clock.monotonicTimeNanosUnsafe(),\n pauseUntil: async (atNanos) => {\n owner.check();\n if (atNanos >= owner.deadlineNanos()) throw owner.overBudget();\n const remaining = atNanos - owner.clock.monotonicTimeNanosUnsafe();\n\n if (remaining > 0n) await sleepOnOwnerClock(owner.clock, remaining, owner.signal);\n owner.check();\n },\n});\n\n/** A performed admission's ticket: the owner's pacing is always present on it. */\nexport type PerformedTicket = Ticket & { readonly performance: Performance };\n\n/** Whether this admission is performed, which narrows the ticket to carry the owner's pacing. */\nexport const isPerformed = (ticket: Ticket): ticket is PerformedTicket =>\n ticket.performance !== undefined;\n\n/** The original owner's pacing for a performed admission, checked before any input is planned. */\nexport const ownerPacing = (ticket: PerformedTicket) => {\n const { now, pauseUntil, remainingTimeNanos } = ticket.performance;\n\n return {\n now,\n pauseUntil,\n requireDuration: (durationMillis: number) => {\n ticket.check();\n if (!Number.isFinite(durationMillis) || durationMillis < 0)\n throw failure(Reasons.Malformed.make({}), ticket.outcome ?? \"undispatched\");\n if (BigInt(Math.round(durationMillis * 1_000_000)) >= remainingTimeNanos())\n throw failure(Reasons.TimingBudgetExceeded.make({}), ticket.outcome ?? \"undispatched\");\n },\n /** Refuses, before more input, work the original deadline would not see finish by `atNanos`. */\n requireBy: (atNanos: bigint) => {\n ticket.check();\n if (atNanos >= now() + remainingTimeNanos())\n throw failure(Reasons.TimingBudgetExceeded.make({}), ticket.outcome ?? \"undispatched\");\n },\n };\n};\n","import { Effect, Random, Result } from \"effect\";\n\nimport { BrowserError, Reasons } from \"../../Errors.ts\";\nimport type { MotionProfile, Performed } from \"../../PlanData.ts\";\n\n/**\n * These caps are independent of logical action admission and pending native replies. Every\n * schedule is bounded by construction: a path or scroll has at most `samples` points, and a code\n * point expands to at most three strokes (a slip, its Backspace and the key), so typed text has at\n * most 768.\n */\nexport const Limits = {\n samples: 128,\n codePoints: 256,\n} as const;\n\ninterface KeyRandom {\n readonly interval: number;\n readonly hold: number;\n readonly slip: number;\n readonly wrong: number;\n}\n\n/** Finite, geometry-independent policy data; this value owns no clock, permit or native work. */\nexport interface PerformancePlan {\n readonly seed: number;\n readonly profile: MotionProfile;\n readonly pointer: { readonly aimX: number; readonly aimY: number; readonly curvature: number };\n readonly keys: ReadonlyArray<KeyRandom>;\n readonly scroll: number;\n readonly slipsProbability: number;\n}\n\nexport interface Point {\n readonly x: number;\n readonly y: number;\n}\n\nexport interface PointerGeometry {\n readonly from: Point | null;\n readonly box: Point & { readonly width: number; readonly height: number };\n readonly viewport: { readonly width: number; readonly height: number };\n}\n\nexport interface MoveGeometry {\n readonly from: Point | null;\n readonly to: Point;\n readonly viewport: { readonly width: number; readonly height: number };\n}\n\nexport interface PointerSchedule {\n /** Intended viewport point, never evidence of the native engine's actual pointer position. */\n readonly aim: Point;\n readonly durationMillis: number;\n readonly samples: ReadonlyArray<{ readonly offsetMillis: number; readonly position: Point }>;\n}\n\nexport interface Stroke {\n readonly key: string;\n readonly index: number;\n /** Quiet interval from the preceding keyup to this keydown; the first stroke has no delay. */\n readonly intervalMillis: number;\n readonly holdMillis: number;\n readonly offsetMillis: number;\n readonly completedOffsetMillis: number;\n readonly kind: \"type\" | \"slip\" | \"backspace\";\n}\n\nexport interface KeySchedule {\n readonly fieldIndex: number;\n readonly codePoints: number;\n readonly durationMillis: number;\n readonly strokes: ReadonlyArray<Stroke>;\n}\n\nexport interface ScrollSchedule {\n readonly durationMillis: number;\n readonly samples: ReadonlyArray<{\n readonly offsetMillis: number;\n readonly deltaX: number;\n readonly deltaY: number;\n }>;\n}\n\nconst failure = (reason: BrowserError[\"reason\"]) =>\n BrowserError.make({ operation: \"run\", reason, outcome: \"undispatched\" });\n\nconst lerp = (minimum: number, maximum: number, unit: number) =>\n minimum + (maximum - minimum) * unit;\n\nconst clamp = (value: number, minimum: number, maximum: number) =>\n Math.min(maximum, Math.max(minimum, value));\n\n/** Fifth-order progress for zero endpoint velocity/acceleration; curved paths remain policy. */\nexport const progress = (unit: number): number => {\n const u = clamp(unit, 0, 1);\n\n return u * u * u * (10 + u * (-15 + 6 * u));\n};\n\n/** Allocate a fresh pinned generator on execution, never a shared run/callback Random service. */\nexport const prepare = (style: Performed, seed: number, stepId: string) =>\n Effect.suspend(() =>\n Effect.gen(function* () {\n const aimX = yield* Random.next;\n const aimY = yield* Random.next;\n const curvature = yield* Random.next;\n const scroll = yield* Random.next;\n\n const keys = yield* Effect.forEach(Array.from({ length: Limits.codePoints }), () =>\n Effect.gen(function* () {\n return Object.freeze({\n interval: yield* Random.next,\n hold: yield* Random.next,\n slip: yield* Random.next,\n wrong: yield* Random.next,\n });\n }),\n );\n\n return Object.freeze({\n seed,\n profile: style.motion,\n pointer: Object.freeze({ aimX, aimY, curvature }),\n keys: Object.freeze(keys),\n scroll,\n slipsProbability: style.slips.probability,\n });\n }).pipe(Random.withSeed(`effect-browser/performed/1:${seed}:${stepId.length}:${stepId}`)),\n );\n\nconst path = (\n plan: PerformancePlan,\n from: Point | null,\n aim: Point,\n viewport: MoveGeometry[\"viewport\"],\n durationMillis: number,\n): Result.Result<PointerSchedule, BrowserError> => {\n if (from === null)\n return Result.succeed(Object.freeze({ aim, durationMillis: 0, samples: Object.freeze([]) }));\n\n const deltaX = aim.x - from.x;\n const deltaY = aim.y - from.y;\n const distance = Math.hypot(deltaX, deltaY);\n\n if (!Number.isFinite(distance)) return Result.fail(failure(Reasons.Malformed.make({})));\n if (distance === 0)\n return Result.succeed(Object.freeze({ aim, durationMillis: 0, samples: Object.freeze([]) }));\n const count = Math.min(Limits.samples, Math.max(2, Math.ceil(durationMillis / (1000 / 60)) + 1));\n const curvature = (plan.pointer.curvature * 2 - 1) * plan.profile.pointer.curvature * distance;\n const normalX = -deltaY / distance;\n const normalY = deltaX / distance;\n\n const samples = Array.from({ length: count }, (_value, index) => {\n const unit = index / (count - 1);\n const eased = progress(unit);\n const bend = 4 * eased * (1 - eased) * curvature;\n\n return Object.freeze({\n offsetMillis: unit * durationMillis,\n position: Object.freeze({\n x: clamp(from.x + deltaX * eased + normalX * bend, 0, viewport.width),\n y: clamp(from.y + deltaY * eased + normalY * bend, 0, viewport.height),\n }),\n });\n });\n\n return Result.succeed(Object.freeze({ aim, durationMillis, samples: Object.freeze(samples) }));\n};\n\n/** The existing native hit checker must validate the returned aim on the exact leased node. */\nexport const pointer = (\n plan: PerformancePlan,\n geometry: PointerGeometry,\n): Result.Result<PointerSchedule, BrowserError> => {\n const { from, box, viewport } = geometry;\n\n const values = [\n box.x,\n box.y,\n box.width,\n box.height,\n viewport.width,\n viewport.height,\n ...(from === null ? [] : [from.x, from.y]),\n ];\n\n if (values.some((value) => !Number.isFinite(value)))\n return Result.fail(failure(Reasons.Malformed.make({})));\n const left = Math.max(0, box.x);\n const top = Math.max(0, box.y);\n const right = Math.min(viewport.width, box.x + box.width);\n const bottom = Math.min(viewport.height, box.y + box.height);\n const width = right - left;\n const height = bottom - top;\n\n if (width <= 0 || height <= 0 || box.width <= 0 || box.height <= 0)\n return Result.fail(failure(Reasons.NotVisible.make({})));\n const inset = plan.profile.pointer.aimInset;\n\n const aim = Object.freeze({\n x: lerp(left + width * inset, right - width * inset, plan.pointer.aimX),\n y: lerp(top + height * inset, bottom - height * inset, plan.pointer.aimY),\n });\n\n const distance = from === null ? 0 : Math.hypot(aim.x - from.x, aim.y - from.y);\n const range = plan.profile.pointer.duration;\n\n // Shannon duration form with chosen policy coefficients, not measured human calibration.\n const durationMillis = clamp(\n 100 + 150 * Math.log2(distance / Math.min(width, height) + 1),\n range.minMillis,\n range.maxMillis,\n );\n\n return path(plan, from, aim, viewport, durationMillis);\n};\n\n/** Authored coordinates stay exact; the bounded timing policy needs no synthetic target box. */\nexport const move = (\n plan: PerformancePlan,\n geometry: MoveGeometry,\n): Result.Result<PointerSchedule, BrowserError> => {\n const { from, to, viewport } = geometry;\n\n if (\n [to.x, to.y, viewport.width, viewport.height, ...(from === null ? [] : [from.x, from.y])].some(\n (value) => !Number.isFinite(value),\n )\n )\n return Result.fail(failure(Reasons.Malformed.make({})));\n if (\n viewport.width <= 0 ||\n viewport.height <= 0 ||\n to.x < 0 ||\n to.y < 0 ||\n to.x > viewport.width ||\n to.y > viewport.height\n )\n return Result.fail(failure(Reasons.NotVisible.make({})));\n const aim = Object.freeze({ x: to.x, y: to.y });\n const distance = from === null ? 0 : Math.hypot(to.x - from.x, to.y - from.y);\n const range = plan.profile.pointer.duration;\n\n // Chosen linear-distance pacing, with no claim of measured human calibration.\n const durationMillis = clamp(100 + distance * 0.35, range.minMillis, range.maxMillis);\n\n return path(plan, from, aim, viewport, durationMillis);\n};\n\nconst slipKeys = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** Input text is transient host data; receipts/timeline retain counts and intervals only. */\nexport const keys = (\n plan: PerformancePlan,\n text: string,\n fieldIndex = 0,\n): Result.Result<KeySchedule, BrowserError> => {\n if (!Number.isSafeInteger(fieldIndex) || fieldIndex < 0 || fieldIndex > 31)\n return Result.fail(failure(Reasons.Malformed.make({})));\n // Input values are already bounded to 65,536 UTF-8 bytes, so the count is measured in full.\n const characters = [...text];\n\n if (characters.length > Limits.codePoints)\n return Result.fail(\n failure(\n Reasons.Limit.make({\n dimension: \"code-points\",\n maximum: Limits.codePoints,\n observed: characters.length,\n }),\n ),\n );\n const strokes: Array<Stroke> = [];\n let durationMillis = 0;\n\n const append = (key: string, index: number, random: KeyRandom, kind: Stroke[\"kind\"]) => {\n const intervalMillis =\n strokes.length === 0\n ? 0\n : lerp(\n plan.profile.keys.interval.minMillis,\n plan.profile.keys.interval.maxMillis,\n random.interval,\n );\n\n const holdMillis = lerp(\n plan.profile.keys.hold.minMillis,\n plan.profile.keys.hold.maxMillis,\n random.hold,\n );\n\n const offsetMillis = durationMillis + intervalMillis;\n\n durationMillis = offsetMillis + holdMillis;\n strokes.push(\n Object.freeze({\n key,\n index,\n intervalMillis,\n holdMillis,\n offsetMillis,\n completedOffsetMillis: durationMillis,\n kind,\n }),\n );\n };\n\n for (const [index, key] of characters.entries()) {\n const random = plan.keys[(index + fieldIndex * 17) % Limits.codePoints];\n\n if (random === undefined) return Result.fail(failure(Reasons.Malformed.make({})));\n if (plan.slipsProbability > 0 && random.slip < plan.slipsProbability && /^[a-z]$/u.test(key)) {\n const wrongIndex = Math.floor(random.wrong * (slipKeys.length - 1));\n const originalIndex = slipKeys.indexOf(key);\n const wrong = slipKeys[wrongIndex >= originalIndex ? wrongIndex + 1 : wrongIndex];\n\n if (wrong === undefined) return Result.fail(failure(Reasons.Malformed.make({})));\n append(wrong, index, random, \"slip\");\n append(\"Backspace\", index, random, \"backspace\");\n }\n append(key, index, random, \"type\");\n }\n\n return Result.succeed(\n Object.freeze({\n fieldIndex,\n codePoints: characters.length,\n durationMillis,\n strokes: Object.freeze(strokes),\n }),\n );\n};\n\n/** Explicit deltas apply to the existing checked scroll capability, not a synthetic wheel target. */\nexport const scroll = (\n plan: PerformancePlan,\n deltaX: number,\n deltaY: number,\n): Result.Result<ScrollSchedule, BrowserError> => {\n if (!Number.isFinite(deltaX) || !Number.isFinite(deltaY))\n return Result.fail(failure(Reasons.Malformed.make({})));\n if (deltaX === 0 && deltaY === 0)\n return Result.succeed(Object.freeze({ durationMillis: 0, samples: Object.freeze([]) }));\n const range = plan.profile.scroll.duration;\n const durationMillis = lerp(range.minMillis, range.maxMillis, plan.scroll);\n\n const count = Math.min(\n Limits.samples,\n Math.max(1, Math.ceil(durationMillis / plan.profile.scroll.intervalMillis)),\n );\n\n let sentX = 0;\n let sentY = 0;\n\n const samples = Array.from({ length: count }, (_value, index) => {\n const unit = (index + 1) / count;\n const x = index + 1 === count ? deltaX : deltaX * progress(unit);\n const y = index + 1 === count ? deltaY : deltaY * progress(unit);\n\n const sample = Object.freeze({\n offsetMillis: unit * durationMillis,\n deltaX: x - sentX,\n deltaY: y - sentY,\n });\n\n sentX = x;\n sentY = y;\n\n return sample;\n });\n\n return Result.succeed(Object.freeze({ durationMillis, samples: Object.freeze(samples) }));\n};\n","import { Effect } from \"effect\";\n\nimport type { PageStatus } from \"../../Browser.ts\";\nimport type { PageInfo, Target } from \"../../BrowserData.ts\";\nimport type { CaptureQualification } from \"../../CaptureData.ts\";\nimport { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type { CaptureReason } from \"../../TimelineData.ts\";\nimport type { CaptureSource } from \"./Driver.ts\";\nimport type { Owner, Ticket } from \"./Owner.ts\";\n\nexport interface CaptureLease {\n readonly pageId: string;\n readonly stop: Effect.Effect<void>;\n readonly invalidate: (reason: string) => void;\n readonly reservedBytes: number;\n}\n\nexport interface CaptureResolution {\n /** Stable native page identity used to quarantine an unconfirmed screencast across reconnects. */\n readonly key: string;\n readonly target: Target;\n readonly source: CaptureSource;\n /** Retains one bounded authority record after it leaves the owner's live inventory. */\n readonly status?: () => Pick<PageStatus, \"phase\" | \"containment\">;\n /** Captured when this exact interval is resolved, never redirected by reconnect. */\n readonly metadata?: (event: CaptureMetadata) => void;\n}\n\n/** Original interval evidence only; no frame bytes or new capture ownership. */\nexport type CaptureMetadata =\n | {\n readonly _tag: \"FirstFrame\";\n readonly captureId: string;\n readonly target: Target;\n readonly captureBoundary: number;\n readonly captureDocument: number;\n readonly frameSequence: number;\n readonly sourceTimeMillis: number;\n readonly sourceClock: \"presentation-unix-millis\";\n readonly receivedMonotonicNanos: bigint;\n readonly width: number;\n readonly height: number;\n readonly viewportWidth: number;\n readonly viewportHeight: number;\n }\n | {\n readonly _tag: \"CaptureBoundary\";\n readonly captureId: string;\n readonly target: Target;\n readonly captureBoundary: number;\n readonly captureDocument: number;\n readonly sameDocument: boolean;\n readonly url: string | null;\n readonly urlQualification: \"NativeCached\" | \"Omitted\";\n readonly afterSequence: number | null;\n readonly observedMonotonicNanos: bigint;\n }\n | {\n readonly _tag: \"Capture\";\n readonly captureId: string;\n readonly target: Target;\n readonly phase: \"Reserved\" | \"Watching\" | \"Started\" | \"Ended\" | \"Stopped\";\n readonly latePhase: boolean;\n readonly observedMonotonicNanos: bigint;\n readonly captureBoundary: number;\n readonly captureDocument: number;\n readonly qualification: CaptureQualification;\n readonly initialUrl: string | null;\n readonly initialUrlQualification: \"NativeCached\" | \"Unread\" | \"Omitted\";\n readonly reason: CaptureReason | null;\n readonly nativeStop: \"confirmed\" | \"unconfirmed\" | null;\n readonly received: number;\n readonly delivered: number;\n readonly discarded: number;\n readonly overflow: number;\n readonly late: number;\n readonly duplicates: number;\n readonly rejected: number;\n readonly upstreamDrops: \"unknown\";\n };\n\n/** Capture ownership and accounting, shared by a session and every Page it issues. */\nexport interface CaptureParent {\n readonly owner: Owner;\n /** Prebound to the original owner's Crypto; starting capture adds no caller service. */\n readonly newCaptureId: Effect.Effect<string>;\n readonly resolve: (\n ticket: Ticket,\n page: PageInfo,\n ) => Effect.Effect<CaptureResolution, BrowserError>;\n readonly captureLeases: Map<string, CaptureLease>;\n captureReservedBytes: number;\n}\n\n/** The capture parent of one issued Page: the only kind that can start a capture. */\nexport interface PageCaptureParent extends CaptureParent {\n /** The page's own authority check, reported under the caller's operation. */\n readonly validate: (operation: BrowserOperation) => Effect.Effect<void, BrowserError>;\n /** The exact page this parent captures. */\n readonly page: PageInfo;\n}\n\n/** A page delegates to the same owner and accounting; its destination cannot be replaced. */\nexport const forPage = (\n parent: CaptureParent,\n info: PageInfo,\n identity: Target,\n validate: (operation: BrowserOperation) => Effect.Effect<void, BrowserError>,\n): PageCaptureParent => ({\n validate,\n page: info,\n owner: parent.owner,\n newCaptureId: parent.newCaptureId,\n captureLeases: parent.captureLeases,\n get captureReservedBytes() {\n return parent.captureReservedBytes;\n },\n set captureReservedBytes(value) {\n parent.captureReservedBytes = value;\n },\n resolve: (ticket, requested) =>\n validate(\"capture\").pipe(\n Effect.andThen(\n Effect.suspend(() => {\n if (ticket.generation !== identity.generation)\n return Effect.fail(\n BrowserError.make({\n operation: \"capture\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n }),\n );\n if (requested.pageId !== info.pageId || requested.targetId !== info.targetId)\n return Effect.fail(\n BrowserError.make({\n operation: \"capture\",\n reason: Reasons.Configuration.make({ path: \"target\" }),\n outcome: \"undispatched\",\n }),\n );\n\n return parent\n .resolve(ticket, info)\n .pipe(Effect.tap(() => Effect.sync(() => ticket.check())));\n }),\n ),\n ),\n});\n","import { Predicate, Schema } from \"effect\";\n\nimport {\n type Correlation,\n type EvidenceTarget,\n type Payload,\n PayloadTag,\n type Stamp,\n} from \"../../TimelineData.ts\";\nimport type { CaptureMetadata } from \"../browser/Association.ts\";\nimport type { NativeCachedPage } from \"../browser/Driver.ts\";\nimport type { OperationListener } from \"../browser/Owner.ts\";\nimport type { AppendInput, makeStore } from \"./Store.ts\";\n\nexport type Store = ReturnType<typeof makeStore>;\n\n/** Native receipts may contain checked Schema classes; journal metadata is plain data. */\nconst geometry = (value: { readonly x: number; readonly y: number }) => ({\n x: value.x,\n y: value.y,\n});\n\nconst isPayloadTag = Schema.is(PayloadTag);\n\n/** Reads a refused payload's own tag without running any accessor it might carry. */\nconst omittedTag = (event: unknown): PayloadTag | null => {\n try {\n const tag: unknown = Predicate.isObject(event)\n ? Object.getOwnPropertyDescriptor(event, \"_tag\")?.value\n : undefined;\n\n return isPayloadTag(tag) ? tag : null;\n } catch {\n return null;\n }\n};\n\n/**\n * Refusing an external fact must never change the native operation's original outcome. The\n * omission keeps the refused event's target, correlation and tag, so a Page view sees its own\n * gap; only when that attribution is itself refused does the omission stand unattributed.\n */\nexport const publish = (store: Store, input: AppendInput) => {\n const result = store.append(input);\n\n if (result._tag !== \"Refused\" || result.reason === \"Closed\") return result;\n const reason = result.reason;\n\n const attributed = store.append({\n target: input.target,\n correlation: input.correlation,\n event: { _tag: \"MetadataOmitted\", reason, originalTag: omittedTag(input.event) },\n });\n\n return attributed._tag === \"Appended\"\n ? attributed\n : store.append({\n target: null,\n correlation: null,\n event: { _tag: \"MetadataOmitted\", reason, originalTag: null },\n });\n};\n\nexport const stamp = (store: Store, originNanos: bigint, nanos: bigint): Stamp => ({\n clockId: store.now().clockId,\n offsetNanos: nanos - originNanos,\n});\n\nexport const cachedTarget = (page: NativeCachedPage, generation: number): EvidenceTarget => ({\n generation,\n pageId: page.pageId,\n frameId: page.frameId,\n document: page.documentEpoch,\n});\n\n/**\n * The timeline's subscription to every operation the owner guards. It records each fact as the\n * owner reported it, lateness included, and an operation's end as its Finished facts.\n */\nexport const operationEvents =\n (configuration: {\n readonly store: () => Store;\n readonly originNanos: bigint;\n readonly retain: (pageId: string | undefined) => () => void;\n }): OperationListener =>\n (facts) => {\n // One closure per original admitted ticket, with no registry of historical stores.\n const store = configuration.store();\n const scope = facts.scope;\n\n const pageId =\n scope === undefined || scope === \"all\" || scope === \"none\" ? undefined : scope.pageId;\n\n const release = configuration.retain(pageId);\n\n const target: EvidenceTarget | null =\n pageId === undefined\n ? null\n : {\n generation: facts.generation,\n pageId,\n frameId: null,\n document: null,\n };\n\n const correlation = facts.correlation;\n\n const append = (event: Payload, actualTarget: EvidenceTarget | null = target) =>\n publish(store, { target: actualTarget, correlation, event });\n\n let ordinal = 0;\n let picture: { readonly at: Stamp; readonly target: EvidenceTarget } | undefined;\n const at = (nanos: bigint) => stamp(store, configuration.originNanos, nanos);\n\n const interval = (start: bigint, end: bigint) => ({\n start: at(start),\n end: at(end),\n qualification: \"native-call-interval\" as const,\n });\n\n const actualTarget = (value: {\n readonly generation?: number;\n readonly pageId: string;\n readonly frameId: string;\n }): EvidenceTarget => ({\n generation: value.generation ?? facts.generation,\n pageId: value.pageId,\n frameId: value.frameId,\n // A receipt's target grants frame attribution, not a document sampling guarantee.\n document: null,\n });\n\n return (event) => {\n switch (event._tag) {\n case \"Phase\": {\n if (event.phase === \"Dispatched\") ordinal++;\n\n const common = {\n operation: facts.operation,\n operationId: facts.operationId,\n nativeOrdinal: ordinal,\n mutation: event.mutation,\n late: event.late,\n };\n\n // Consumers tell a preparatory or burst reply from completed logical input by its fact.\n append(\n event.phase === \"Acknowledged\" && event.acknowledgement !== undefined\n ? {\n _tag: event.phase,\n ...common,\n acknowledgement: {\n subphase: event.acknowledgement.subphase,\n logicalComplete: event.acknowledgement.logicalComplete,\n },\n }\n : { _tag: event.phase, ...common },\n );\n\n return;\n }\n // The timeline records an operation's end through its Finished facts.\n case \"Terminal\":\n return;\n case \"Picture\": {\n const boundary = event.boundary;\n\n const captured: EvidenceTarget = {\n generation: facts.generation,\n ...boundary.target,\n document: boundary.documentEpoch,\n };\n\n const now = store.now();\n\n if (boundary.phase === \"Requested\") picture = { at: now, target: captured };\n else if (picture !== undefined) {\n const requested = picture;\n\n picture = undefined;\n append(\n {\n _tag: \"Picture\",\n operationId: facts.operationId,\n mediaType: \"image/png\",\n nativeRequest: requested.at,\n nativeReturn: now,\n qualification: \"native-call-interval\",\n requestDocument: requested.target.document,\n returnDocument: boundary.documentEpoch,\n },\n {\n ...requested.target,\n document:\n requested.target.document === boundary.documentEpoch\n ? boundary.documentEpoch\n : null,\n },\n );\n }\n\n return;\n }\n case \"Input\": {\n const { receipt, keys } = event;\n const timing = interval(receipt.startedMonotonicNanos, receipt.completedMonotonicNanos);\n const correlated = { operationId: facts.operationId, interval: timing };\n let payload: Payload | undefined;\n\n switch (receipt.kind) {\n case \"pointer-move\":\n case \"hover\":\n payload = {\n _tag: \"Pointer\",\n kind: receipt.kind,\n position: receipt.position === null ? null : geometry(receipt.position),\n ...correlated,\n };\n break;\n case \"click\":\n payload = {\n _tag: \"Press\",\n position: receipt.position === null ? null : geometry(receipt.position),\n ...(receipt.intended === undefined\n ? {}\n : {\n intended: {\n position: geometry(receipt.intended.position),\n relativePosition: geometry(receipt.intended.relativePosition),\n qualification: receipt.intended.qualification,\n },\n }),\n ...correlated,\n };\n break;\n case \"wheel\":\n payload = {\n _tag: \"Scroll\",\n kind: \"wheel\",\n delta:\n receipt.delta === undefined || receipt.delta === null\n ? null\n : geometry(receipt.delta),\n ...correlated,\n };\n break;\n case \"press\":\n case \"type\":\n if (keys === undefined) return;\n payload = { _tag: \"Keys\", kind: receipt.kind, ...keys, ...correlated };\n break;\n }\n append(\n payload ?? { _tag: \"MetadataOmitted\", reason: \"Malformed\", originalTag: null },\n actualTarget(receipt.target),\n );\n\n return;\n }\n case \"Scroll\": {\n const value = event.facts;\n\n append(\n {\n _tag: \"Scroll\",\n operationId: facts.operationId,\n kind: \"scroll\",\n // A scroll-into-view moves by whatever the browser chose; it has no requested delta.\n delta:\n value.x === undefined || value.y === undefined ? null : { x: value.x, y: value.y },\n ...(value.qualification === undefined ? {} : { qualification: value.qualification }),\n interval: interval(value.startedMonotonicNanos, value.completedMonotonicNanos),\n },\n actualTarget(value.target),\n );\n\n return;\n }\n case \"Settled\":\n append(\n {\n _tag: \"Settled\",\n operationId: facts.operationId,\n quietMillis: event.evidence.quietMillis,\n withinMillis: event.evidence.withinMillis,\n signals: event.evidence.signals,\n },\n actualTarget(event.target),\n );\n\n return;\n case \"Glide\": {\n const value = event.facts;\n\n if (value.samples.length < 2) return;\n append(\n {\n _tag: \"Glide\",\n operationId: facts.operationId,\n qualification: \"intended-schedule\",\n schedule: value.samples.map((sample) => ({\n at: at(\n value.startedMonotonicNanos + BigInt(Math.round(sample.offsetMillis * 1_000_000)),\n ),\n position: geometry(sample.position),\n })),\n },\n actualTarget(value.target),\n );\n\n return;\n }\n case \"Finished\":\n if (event.containment._tag !== \"NotRequired\")\n append({ _tag: \"Contained\", containment: event.containment });\n if (event.kind === \"Cancelled\")\n append({ _tag: \"Cancelled\", operationId: facts.operationId, outcome: event.outcome });\n else if (event.kind === \"Failed\")\n append({\n _tag: \"Failed\",\n operationId: facts.operationId,\n operation: facts.operation,\n reason: event.error?.reason._tag ?? \"Failed\",\n outcome: event.outcome,\n });\n release();\n }\n };\n };\n\nexport const captureMetadata =\n (store: Store, originNanos: bigint) =>\n (value: CaptureMetadata): void => {\n // Capture document/boundary numbers name receipt attribution, never native document epochs.\n const target: EvidenceTarget = { ...value.target, document: null };\n\n const common = {\n captureId: value.captureId,\n captureBoundary: value.captureBoundary,\n captureDocument: value.captureDocument,\n };\n\n const at = (nanos: bigint) => stamp(store, originNanos, nanos);\n let event: Payload;\n\n switch (value._tag) {\n case \"FirstFrame\":\n event = {\n _tag: \"FirstFrame\",\n ...common,\n frameSequence: value.frameSequence,\n sourceTimeMillis: value.sourceTimeMillis,\n sourceClock: value.sourceClock,\n received: at(value.receivedMonotonicNanos),\n width: value.width,\n height: value.height,\n viewportWidth: value.viewportWidth,\n viewportHeight: value.viewportHeight,\n qualification: \"received-boundary-attribution\",\n };\n break;\n case \"CaptureBoundary\":\n event = {\n _tag: \"CaptureBoundary\",\n ...common,\n sameDocument: value.sameDocument,\n afterSequence: value.afterSequence,\n observed: at(value.observedMonotonicNanos),\n qualification: \"received-boundary-attribution\",\n url: value.url,\n urlQualification: value.urlQualification,\n };\n break;\n case \"Capture\":\n event = {\n _tag: \"Capture\",\n ...common,\n phase: value.phase,\n observed: at(value.observedMonotonicNanos),\n qualification: value.qualification,\n reason: value.reason,\n nativeStop: value.nativeStop,\n received: value.received,\n delivered: value.delivered,\n discarded: value.discarded,\n overflow: value.overflow,\n late: value.late,\n duplicates: value.duplicates,\n rejected: value.rejected,\n upstreamDrops: value.upstreamDrops,\n latePhase: value.latePhase,\n };\n break;\n }\n publish(store, { target, correlation: null, event });\n };\n\nexport const planPublisher =\n (store: Store, target: EvidenceTarget | null) =>\n (correlation: Correlation, event: Payload): void => {\n publish(store, { target, correlation, event });\n };\n","import { Deferred, Effect } from \"effect\";\n\nimport type { TerminalReason } from \"../../TimelineData.ts\";\n\n/** Original bounded logical owners finish their evidence before the domain's one terminal. */\nexport const makeRetirement = (complete: (reason: TerminalReason) => void) => {\n let count = 0;\n let requested: TerminalReason | null = null;\n let finished = false;\n const signal = Deferred.makeUnsafe<void>();\n\n const finish = () => {\n if (finished || requested === null || count !== 0) return;\n finished = true;\n complete(requested);\n };\n\n return {\n retain: (): (() => void) => {\n if (finished) return () => {};\n count++;\n let released = false;\n\n return () => {\n if (released) return;\n released = true;\n count--;\n finish();\n };\n },\n request: (reason: TerminalReason): void => {\n requested ??= reason;\n // Waiters resume on their own fibers, never inside the native callback that retires.\n Deferred.doneUnsafe(signal, Effect.yieldNow);\n finish();\n },\n /** Completes once retirement is requested, before retained owners have finished. */\n requested: Deferred.await(signal),\n };\n};\n","import { Effect, Result, Schema, Stream } from \"effect\";\n\nimport type { PageStatus } from \"../../Browser.ts\";\nimport type { Timeline } from \"../../Timeline.ts\";\nimport {\n PagesInventory,\n TimelineLimit,\n TimelineMalformed,\n type CachedPage,\n type Event,\n type PageEvent,\n type Terminal,\n type TimelineError,\n} from \"../../TimelineData.ts\";\nimport type { NativeCachedPage } from \"../browser/Driver.ts\";\nimport type { makeStore, Subscription, View } from \"./Store.ts\";\n\ntype Store = ReturnType<typeof makeStore>;\n\ninterface Attachment {\n readonly inventory: PagesInventory;\n readonly subscription: Subscription;\n}\n\nconst decodeInventory = Schema.decodeResult(PagesInventory);\n\nconst lifecycle = (value: Event): boolean => {\n switch (value.event._tag) {\n case \"Lifecycle\":\n case \"PageOpened\":\n case \"PageClosed\":\n case \"DisplayChanged\":\n case \"MetadataChanged\":\n case \"Navigated\":\n case \"Terminal\":\n case \"MetadataOmitted\":\n return true;\n case \"Planned\":\n case \"Prepared\":\n case \"Dispatched\":\n case \"Acknowledged\":\n case \"FollowUp\":\n case \"Pointer\":\n case \"Press\":\n case \"Keys\":\n case \"Scroll\":\n case \"Glide\":\n case \"FirstFrame\":\n case \"Capture\":\n case \"CaptureBoundary\":\n case \"Picture\":\n case \"Settled\":\n case \"Contained\":\n case \"Failed\":\n case \"Cancelled\":\n return false;\n }\n};\n\nconst viewTimeline = (store: Store, view?: View): Timeline => ({\n snapshot: (options) => store.snapshot(options, view),\n events: (from) =>\n Stream.unwrap(\n store\n .subscribe({\n ...(from === undefined ? {} : { from }),\n ...(view === undefined ? {} : { view }),\n })\n .pipe(Effect.map((subscription) => Stream.fromPull(Effect.succeed(subscription.pull)))),\n ),\n now: Effect.sync(store.now),\n});\n\n/** The original registry and one journal attach atomically; no metadata refresh issues authority. */\nexport const makeJournal = (configuration: {\n readonly store: () => Store;\n readonly cachedPages: () => ReadonlyArray<NativeCachedPage>;\n readonly pageStatus: (pageId: string) => Pick<PageStatus, \"phase\" | \"containment\"> | undefined;\n readonly generation: () => number;\n}) => {\n const timeline: Timeline = {\n snapshot: (options) => Effect.suspend(() => configuration.store().snapshot(options)),\n events: (from) => Stream.suspend(() => viewTimeline(configuration.store()).events(from)),\n now: Effect.sync(() => configuration.store().now()),\n };\n\n const forPage = (\n store: Store,\n pageId: string,\n generation: number,\n terminal: () => Terminal | null,\n ): Timeline => viewTimeline(store, { pageId, generation, terminal });\n\n const attachInventory = (): Result.Result<Attachment, TimelineError> => {\n const store = configuration.store();\n const native = configuration.cachedPages();\n\n if (native.length > 32)\n return Result.fail(new TimelineLimit({ maximum: 32, observed: native.length }));\n const generation = configuration.generation();\n\n const pages: CachedPage[] = native.map((page) => {\n const status = configuration.pageStatus(page.pageId);\n const urlOmitted = page.url !== null && page.url.length > 8192;\n const titleOmitted = page.title !== null && page.title.length > 512;\n\n return {\n identity: {\n generation,\n pageId: page.pageId,\n frameId: page.frameId,\n document: page.documentEpoch,\n },\n targetId: page.targetId,\n url: urlOmitted ? null : page.url,\n urlQualification: urlOmitted\n ? \"Omitted\"\n : page.url === null && page.urlQualification !== \"Omitted\"\n ? \"Unread\"\n : page.urlQualification,\n title: titleOmitted ? null : page.title,\n titleQualification: titleOmitted\n ? \"Omitted\"\n : page.title === null && page.titleQualification === \"ObservedCached\"\n ? \"Unread\"\n : page.titleQualification,\n selected: page.selected,\n displayState: page.displayState === \"suspended\" ? \"held\" : page.displayState,\n phase: status?.phase ?? (page.displayState === \"suspended\" ? \"paused\" : \"open\"),\n containment: status?.containment ?? { _tag: \"NotRequired\" },\n };\n });\n\n const decoded = decodeInventory(\n { _tag: \"Inventory\", pages, resumeAfter: store.cursor() },\n { onExcessProperty: \"error\" },\n );\n\n if (Result.isFailure(decoded)) return Result.fail(new TimelineMalformed({ path: \"Inventory\" }));\n const inventory = decoded.success;\n\n for (const page of inventory.pages) {\n Object.freeze(page.identity);\n Object.freeze(page.containment);\n Object.freeze(page);\n }\n Object.freeze(inventory.pages);\n Object.freeze(inventory.resumeAfter);\n Object.freeze(inventory);\n const attached = store.attach({ from: inventory.resumeAfter });\n\n return Result.isFailure(attached)\n ? Result.fail(attached.failure)\n : Result.succeed({ inventory, subscription: attached.success });\n };\n\n const acquire = Effect.sync(attachInventory).pipe(Effect.flatMap(Effect.fromResult));\n\n const pageEvents: Stream.Stream<PageEvent, TimelineError> = Stream.unwrap(\n Effect.acquireRelease(acquire, (value) => Effect.sync(value.subscription.release)).pipe(\n Effect.map(({ inventory, subscription }) =>\n Stream.concat(\n Stream.succeed(inventory),\n Stream.fromPull(Effect.succeed(subscription.pull)).pipe(Stream.filter(lifecycle)),\n ),\n ),\n ),\n );\n\n return { timeline, forPage, pageEvents };\n};\n","import {\n type Array as Arr,\n Cause,\n type Clock,\n Deferred,\n Effect,\n Predicate,\n type Pull,\n Result,\n Schema,\n type Scope,\n} from \"effect\";\n\nimport {\n type Cursor,\n Event,\n EventJson,\n Selector,\n SnapshotOptions,\n TimelineCursorError,\n TimelineGap,\n TimelineLimit,\n TimelineMalformed,\n type Retention,\n type Snapshot,\n type Stamp,\n type StoreIdentity,\n type Terminal,\n type TerminalReason,\n type TimelineError,\n} from \"../../TimelineData.ts\";\n\nexport interface View {\n readonly pageId: string;\n readonly generation: number;\n readonly terminal: () => Terminal | null;\n}\n\nexport interface SubscriptionOptions {\n readonly from?: Selector;\n readonly view?: View;\n}\n\nexport interface Subscription {\n readonly cursor: Cursor;\n readonly pull: Pull.Pull<Arr.NonEmptyReadonlyArray<Event>, TimelineError>;\n readonly release: () => void;\n}\n\nexport type AppendInput = Pick<Event, \"target\" | \"correlation\" | \"event\">;\n\nexport type AppendResult =\n | { readonly _tag: \"Appended\"; readonly event: Event }\n | {\n readonly _tag: \"Refused\";\n readonly reason: \"Closed\" | \"Malformed\" | \"Oversized\";\n readonly bytes?: number;\n };\n\ninterface Entry {\n readonly event: Event;\n readonly bytes: number;\n}\n\ninterface Reader {\n sequence: bigint;\n readonly minimumAt: bigint | undefined;\n readonly view: View | undefined;\n wake: Deferred.Deferred<void> | undefined;\n released: boolean;\n}\n\nconst maximumInteger = (1n << 128n) - 1n;\nconst utf8 = new TextEncoder();\nconst decodeEvent = Schema.decodeUnknownResult(Event);\nconst encodeEvent = Schema.encodeResult(EventJson);\nconst decodeSelector = Schema.decodeUnknownResult(Selector);\nconst decodeSnapshotOptions = Schema.decodeUnknownResult(SnapshotOptions);\nconst closed = { onExcessProperty: \"error\" } as const;\n\n/** Producer cost admission rejects accessors and oversized trees before semantic decoding. */\nconst metadataAdmission = (\n value: unknown,\n maximumBytes: number,\n): \"Malformed\" | \"Oversized\" | undefined => {\n let bytes = 0;\n let nodes = 0;\n let refusal: \"Malformed\" | \"Oversized\" | undefined;\n const ancestors = new Set<object>();\n\n const add = (count: number) => {\n bytes += count;\n if (bytes > maximumBytes) refusal = \"Oversized\";\n };\n\n const text = (value: string) => {\n if (value.length > maximumBytes) refusal = \"Oversized\";\n else add(utf8.encode(JSON.stringify(value)).byteLength);\n };\n\n const visit = (input: unknown, depth: number): void => {\n if (refusal !== undefined) return;\n if (++nodes > 4096 || depth > 12) {\n refusal = \"Oversized\";\n\n return;\n }\n if (input === null) return add(4);\n switch (typeof input) {\n case \"string\":\n return text(input);\n case \"boolean\":\n return add(input ? 4 : 5);\n case \"number\":\n if (Number.isFinite(input)) return add(JSON.stringify(input).length);\n refusal = \"Malformed\";\n\n return;\n case \"bigint\":\n if (input < 0n || input > maximumInteger) refusal = \"Malformed\";\n else text(input.toString());\n\n return;\n case \"object\":\n break;\n case \"undefined\":\n case \"symbol\":\n case \"function\":\n refusal = \"Malformed\";\n\n return;\n }\n if (!Predicate.isObjectKeyword(input) || ancestors.has(input)) {\n refusal = \"Malformed\";\n\n return;\n }\n ancestors.add(input);\n const keys = Reflect.ownKeys(input);\n\n if (Array.isArray(input)) {\n if (input.length > 128 || keys.length !== input.length + 1) {\n refusal = \"Oversized\";\n\n return;\n }\n add(2 + Math.max(0, input.length - 1));\n for (let index = 0; index < input.length; index++) {\n const property = Object.getOwnPropertyDescriptor(input, String(index));\n\n if (property === undefined || !(\"value\" in property)) {\n refusal = \"Malformed\";\n\n return;\n }\n visit(property.value, depth + 1);\n if (refusal !== undefined) return;\n }\n } else {\n const prototype: unknown = Object.getPrototypeOf(input);\n\n if (prototype !== null && prototype !== Object.prototype) {\n refusal = \"Malformed\";\n\n return;\n }\n if (keys.length > 64) {\n refusal = \"Oversized\";\n\n return;\n }\n add(2 + Math.max(0, keys.length - 1));\n for (const key of keys) {\n if (typeof key !== \"string\") {\n refusal = \"Malformed\";\n\n return;\n }\n const property = Object.getOwnPropertyDescriptor(input, key);\n\n if (property === undefined || !property.enumerable || !(\"value\" in property)) {\n refusal = \"Malformed\";\n\n return;\n }\n text(key);\n add(1);\n visit(property.value, depth + 1);\n if (refusal !== undefined) return;\n }\n }\n ancestors.delete(input);\n };\n\n try {\n visit(value, 0);\n\n return refusal;\n } catch {\n return \"Malformed\";\n }\n};\n\nconst immutable = <A>(value: A): A => {\n const freeze = (input: unknown): void => {\n if (!Predicate.isObjectKeyword(input) || Object.isFrozen(input)) return;\n for (const child of Object.values(input)) freeze(child);\n Object.freeze(input);\n };\n\n freeze(value);\n\n return value;\n};\n\n/** One connection's bounded journal. Its captured Clock is the owner's original clock. */\nexport const makeStore = (configuration: {\n readonly clock: Clock.Clock;\n readonly originNanos: bigint;\n readonly identity: StoreIdentity;\n readonly limits: Retention;\n /**\n * The clock-domain offset this journal's coverage starts at. A reconnect's journal shares the\n * session clock but holds nothing from before it began; earlier times are another journal's.\n */\n readonly coversFromNanos?: bigint;\n}) => {\n const { clock, originNanos } = configuration;\n const coversFrom = configuration.coversFromNanos ?? 0n;\n const identity = Object.freeze({ ...configuration.identity });\n const limits = Object.freeze({ ...configuration.limits });\n\n const entries: Array<Entry | undefined> = Array.from(\n { length: limits.maxEvents },\n () => undefined,\n );\n\n const readers = new Set<Reader>();\n const maximumAge = BigInt(Math.floor(limits.maxDurationMillis * 1_000_000));\n let head = 0;\n let size = 0;\n let retainedBytes = 0;\n let watermark = 0n;\n let evictedThrough = 0n;\n let evictedAt: bigint | undefined;\n let evicted = 0;\n let terminal: Terminal | null = null;\n\n const cursor = (sequence = watermark): Cursor => Object.freeze({ ...identity, sequence });\n\n const now = (): Stamp =>\n Object.freeze({\n clockId: identity.clockId,\n offsetNanos: clock.monotonicTimeNanosUnsafe() - originNanos,\n });\n\n const entry = (index: number) => entries[(head + index) % limits.maxEvents];\n\n const evict = () => {\n const oldest = entry(0);\n\n if (oldest === undefined) return;\n entries[head] = undefined;\n head = (head + 1) % limits.maxEvents;\n size--;\n retainedBytes -= oldest.bytes;\n evictedThrough = oldest.event.sequence;\n evictedAt = oldest.event.at.offsetNanos;\n evicted++;\n };\n\n const expire = () => {\n const current = now().offsetNanos;\n\n while (size > 0) {\n const oldest = entry(0);\n\n if (oldest === undefined || current - oldest.event.at.offsetNanos <= maximumAge) return;\n evict();\n }\n };\n\n const bounds = () => ({\n oldest: size === 0 ? null : cursor(entry(0)?.event.sequence),\n newest: size === 0 ? null : cursor(entry(size - 1)?.event.sequence),\n resumeAfter: cursor(),\n evictedThrough: cursor(evictedThrough),\n });\n\n const gap = (requested: Selector) => new TimelineGap({ requested, ...bounds() });\n\n const validate = (requested: Selector): TimelineError | undefined => {\n if (\"sequence\" in requested) {\n if (requested.storeId !== identity.storeId)\n return new TimelineCursorError({ reason: \"Store\", requested, current: cursor() });\n if (requested.clockId !== identity.clockId)\n return new TimelineCursorError({ reason: \"Clock\", requested, current: cursor() });\n if (requested.sequence > watermark)\n return new TimelineCursorError({ reason: \"Future\", requested, current: cursor() });\n if (requested.sequence < evictedThrough) return gap(requested);\n } else {\n if (requested.at.clockId !== identity.clockId)\n return new TimelineCursorError({ reason: \"Clock\", requested, current: cursor() });\n if (\n requested.at.offsetNanos < coversFrom ||\n (evictedAt !== undefined && requested.at.offsetNanos <= evictedAt)\n )\n return gap(requested);\n }\n\n return undefined;\n };\n\n const normalize = (requested: unknown): Result.Result<Selector, TimelineError> => {\n if (metadataAdmission(requested, 2048) !== undefined)\n return Result.fail(new TimelineMalformed({}));\n const parsed = decodeSelector(requested, closed);\n\n if (Result.isFailure(parsed)) return Result.fail(new TimelineMalformed({}));\n const selected = immutable(parsed.success);\n const refusal = validate(selected);\n\n return refusal === undefined ? Result.succeed(selected) : Result.fail(refusal);\n };\n\n const viewTerminal = (view: View | undefined) => view?.terminal() ?? terminal;\n\n // An omission that could not keep its attribution may have been any Page's evidence.\n const matches = (event: Event, view: View | undefined) =>\n view === undefined ||\n (event.target === null\n ? event.event._tag === \"MetadataOmitted\"\n : event.target.pageId === view.pageId && event.target.generation === view.generation);\n\n const wake = () => {\n for (const reader of readers) {\n const pending = reader.wake;\n\n reader.wake = undefined;\n // Completing with void would synchronously run consumer work inside native publication.\n if (pending !== undefined) Deferred.doneUnsafe(pending, Effect.yieldNow);\n }\n };\n\n const append = (input: AppendInput): AppendResult => {\n if (terminal !== null) return { _tag: \"Refused\", reason: \"Closed\" };\n const refusal = metadataAdmission(input, limits.maxEventBytes);\n\n if (refusal !== undefined) return { _tag: \"Refused\", reason: refusal };\n const candidate = { ...input, version: 1, ...identity, sequence: watermark + 1n, at: now() };\n const decoded = decodeEvent(candidate, closed);\n\n if (Result.isFailure(decoded)) return { _tag: \"Refused\", reason: \"Malformed\" };\n const encoded = encodeEvent(decoded.success, closed);\n\n if (Result.isFailure(encoded)) return { _tag: \"Refused\", reason: \"Malformed\" };\n const bytes = utf8.encode(JSON.stringify(encoded.success)).byteLength;\n\n if (bytes > limits.maxEventBytes) return { _tag: \"Refused\", reason: \"Oversized\", bytes };\n const event = immutable(decoded.success);\n\n expire();\n while (size >= limits.maxEvents) evict();\n entries[(head + size) % limits.maxEvents] = { event, bytes };\n size++;\n retainedBytes += bytes;\n watermark = event.sequence;\n if (event.event._tag === \"Terminal\" && event.event.scope === \"session\")\n terminal = immutable({\n cursor: cursor(),\n at: event.at,\n scope: event.event.scope,\n reason: event.event.reason,\n });\n while (retainedBytes > limits.maxBytes) evict();\n wake();\n\n return { _tag: \"Appended\", event };\n };\n\n /** Closure is an owner fact even when retention cannot admit its terminal envelope. */\n const finish = (reason: TerminalReason): AppendResult => {\n const result = append({\n target: null,\n correlation: null,\n event: { _tag: \"Terminal\", scope: \"session\", reason },\n });\n\n if (terminal === null) {\n terminal = immutable({ cursor: cursor(), at: now(), scope: \"session\", reason });\n wake();\n }\n\n return result;\n };\n\n const snapshot = Effect.fnUntraced(function* (\n options?: SnapshotOptions,\n view?: View,\n ): Effect.fn.Return<Snapshot, TimelineError> {\n expire();\n let from: Selector | undefined;\n\n if (options !== undefined) {\n if (metadataAdmission(options, 2048) !== undefined) return yield* new TimelineMalformed({});\n const parsed = decodeSnapshotOptions(options, closed);\n\n if (Result.isFailure(parsed)) return yield* new TimelineMalformed({});\n from = parsed.success.from;\n if (from !== undefined) {\n const checked = normalize(from);\n\n if (Result.isFailure(checked)) return yield* checked.failure;\n from = checked.success;\n }\n }\n const events: Event[] = [];\n const ending = viewTerminal(view);\n\n for (let index = 0; index < size; index++) {\n const current = entry(index)?.event;\n\n if (current !== undefined && ending !== null && current.sequence > ending.cursor.sequence)\n break;\n if (current === undefined || !matches(current, view)) continue;\n if (\n from !== undefined &&\n (\"sequence\" in from\n ? current.sequence <= from.sequence\n : current.at.offsetNanos < from.at.offsetNanos)\n )\n continue;\n events.push(current);\n }\n\n return immutable({ events, ...bounds(), evicted, retainedBytes, terminal: ending });\n });\n\n const attach = (\n options: SubscriptionOptions = {},\n ): Result.Result<Subscription, TimelineError> => {\n expire();\n let sequence = watermark;\n let minimumAt: bigint | undefined;\n\n if (options.from !== undefined) {\n const selected = normalize(options.from);\n\n if (Result.isFailure(selected)) return Result.fail(selected.failure);\n if (\"sequence\" in selected.success) sequence = selected.success.sequence;\n else {\n minimumAt = selected.success.at.offsetNanos;\n sequence = evictedThrough;\n }\n }\n if (readers.size >= limits.maxSubscribers)\n return Result.fail(\n new TimelineLimit({ maximum: limits.maxSubscribers, observed: readers.size + 1 }),\n );\n\n const reader: Reader = {\n sequence,\n minimumAt,\n view: options.view,\n wake: undefined,\n released: false,\n };\n\n readers.add(reader);\n\n const release = () => {\n if (reader.released) return;\n reader.released = true;\n readers.delete(reader);\n const pending = reader.wake;\n\n reader.wake = undefined;\n if (pending !== undefined) Deferred.doneUnsafe(pending, Effect.yieldNow);\n };\n\n const pull: Subscription[\"pull\"] = Effect.suspend(() => {\n expire();\n if (reader.sequence < evictedThrough) return Effect.fail(gap(cursor(reader.sequence)));\n if (reader.released) return Cause.done();\n const output: Event[] = [];\n const ending = viewTerminal(reader.view);\n const first = entry(0)?.event.sequence;\n\n // Retained sequences are contiguous from the oldest, so a reader resumes at its own index\n // instead of rescanning the whole ring on every wake.\n for (\n let index =\n first === undefined || reader.sequence < first ? 0 : Number(reader.sequence - first) + 1;\n index < size;\n index++\n ) {\n const current = entry(index)?.event;\n\n if (current === undefined || current.sequence <= reader.sequence) continue;\n if (ending !== null && current.sequence > ending.cursor.sequence) break;\n reader.sequence = current.sequence;\n if (\n (reader.minimumAt === undefined || current.at.offsetNanos >= reader.minimumAt) &&\n matches(current, reader.view)\n )\n output.push(current);\n if (output.length >= 32) break;\n }\n if (output.length > 0) {\n const first = output[0];\n\n if (first !== undefined) return Effect.succeed([first, ...output.slice(1)]);\n }\n if (ending !== null && reader.sequence >= ending.cursor.sequence) return Cause.done();\n reader.wake ??= Deferred.makeUnsafe<void>();\n\n return Deferred.await(reader.wake).pipe(Effect.andThen(pull));\n });\n\n return Result.succeed({\n get cursor() {\n return cursor(reader.sequence);\n },\n pull,\n release,\n });\n };\n\n const subscribe = (\n options?: SubscriptionOptions,\n ): Effect.Effect<Subscription, TimelineError, Scope.Scope> =>\n Effect.acquireRelease(\n Effect.suspend(() => Effect.fromResult(attach(options))),\n (subscription) => Effect.sync(subscription.release),\n );\n\n return { append, finish, snapshot, attach, subscribe, cursor, now };\n};\n","import { Cause, Effect, Exit, Option } from \"effect\";\n\nimport type { BrowserError, InitializationError } from \"../../Errors.ts\";\nimport * as Trace from \"../Trace.ts\";\n\n/** Evidence about this connection, independent of the lifetime of its browser process. */\nexport type ConnectionState = \"closed\" | \"failed\" | \"not-connected\" | \"pending\";\n\n/** Captured teardown operations supplied to the lifetime which owns this connection. */\nexport interface ConnectionCleanup {\n readonly fence: Effect.Effect<void>;\n readonly capture: Effect.Effect<void, BrowserError>;\n readonly initialization: Effect.Effect<void, BrowserError | InitializationError>;\n readonly disconnect: Effect.Effect<ConnectionState, BrowserError>;\n}\n\nexport const noConnection: ConnectionCleanup = {\n fence: Effect.void,\n capture: Effect.void,\n initialization: Effect.void,\n disconnect: Effect.succeed(\"not-connected\"),\n};\n\nexport type CleanupStep<A> =\n | { readonly _tag: \"Success\"; readonly value: A }\n | { readonly _tag: \"Failure\"; readonly reason: \"timeout\" | \"interrupted\" | \"failed\" };\n\nconst timedOut = Symbol(\"BrowserCleanupTimeout\");\n\n/** Every step settles independently, so one failure never suppresses subsequent teardown. */\nexport const cleanupStep = <A, E, R>(\n action: Effect.Effect<A, E, R>,\n timeoutMillis: number,\n): Effect.Effect<CleanupStep<A>, never, R> =>\n action.pipe(\n Effect.interruptible,\n Effect.timeoutOrElse({ duration: timeoutMillis, orElse: () => Effect.fail(timedOut) }),\n Trace.span(\"Browser.cleanup.step\"),\n Effect.exit,\n Effect.map((exit): CleanupStep<A> => {\n if (Exit.isSuccess(exit)) return { _tag: \"Success\", value: exit.value };\n const error = Cause.findErrorOption(exit.cause);\n\n return {\n _tag: \"Failure\",\n reason:\n Option.isSome(error) && error.value === timedOut\n ? \"timeout\"\n : Cause.hasInterrupts(exit.cause)\n ? \"interrupted\"\n : \"failed\",\n };\n }),\n );\n\n/** Bounded host notification; reporting cannot change the cleanup evidence it describes. */\nexport const reported = <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<void> =>\n cleanupStep(effect, 2000).pipe(Effect.asVoid);\n","import type { BrowserOperation } from \"../../Errors.ts\";\n\n/**\n * What the owner spends on an operation: a browser action, a host read, or nothing (inventory,\n * lifecycle, recovery and inspection that sends no input).\n */\nexport type Charge = \"action\" | \"host-read\" | \"none\";\n\n/**\n * The static facts of one operation confined to one exact page: it takes that page's permit, and\n * an unknown outcome is contained by closing that page.\n */\nexport interface PagePolicy {\n readonly work: \"page\";\n /** Dispatching it can change the document, so it retires the page's observations. */\n readonly mutation: boolean;\n readonly charge: Charge;\n /** A page held by `PageControl.suspend` is refused before any native work, never woken. */\n readonly refuseHeld: boolean;\n /** It depends on an initialized document, so it waits for the current one's readiness. */\n readonly ready: boolean;\n /**\n * Recovery work stops or closes what is already in flight: it has its own bounded admission,\n * so a pending navigation's reservation does not refuse it.\n */\n readonly recovery: boolean;\n /** A pending native wait on the page refuses it, as it refuses every mutation. */\n readonly refuseWhileWaiting: boolean;\n}\n\n/**\n * Work on the page inventory: it takes the registry permit, and an unknown outcome fences the\n * owner, since no single page could absorb it.\n */\nexport interface RegistryPolicy {\n readonly work: \"registry\";\n readonly mutation: boolean;\n readonly charge: Charge;\n}\n\n/**\n * `lifecycle`, `capture` and `boundary` operations are admitted elsewhere (the owner's phase\n * changes, the capture module, or a refusal at the public boundary) and never take the page or\n * registry execution path.\n */\nexport type OperationPolicy =\n | PagePolicy\n | RegistryPolicy\n | { readonly work: \"lifecycle\" | \"capture\" | \"boundary\" };\n\nconst onPage = (facts: {\n readonly mutation: boolean;\n readonly charge: Charge;\n readonly refuseHeld: boolean;\n readonly ready: boolean;\n readonly recovery?: true;\n readonly refuseWhileWaiting?: true;\n}): PagePolicy => ({\n work: \"page\",\n recovery: false,\n refuseWhileWaiting: false,\n ...facts,\n});\n\nconst registry = (facts: {\n readonly mutation: boolean;\n readonly charge: Charge;\n}): RegistryPolicy => ({ work: \"registry\", ...facts });\n\nconst lifecycle = { work: \"lifecycle\" } as const;\nconst capture = { work: \"capture\" } as const;\nconst boundary = { work: \"boundary\" } as const;\n\n/** Every operation's policy. A new operation does not compile until its row decides it. */\nexport const OperationPolicies = {\n // configuration and lifetime: the owner's own phase changes\n configure: boundary,\n launch: lifecycle,\n connect: lifecycle,\n reconnect: lifecycle,\n detach: lifecycle,\n disconnect: lifecycle,\n close: lifecycle,\n handoff: lifecycle,\n resume: lifecycle,\n \"live-view\": lifecycle,\n // targets\n target: registry({ mutation: false, charge: \"none\" }),\n handle: boundary,\n \"list-pages\": registry({ mutation: false, charge: \"none\" }),\n \"describe-page\": onPage({ mutation: false, charge: \"none\", refuseHeld: false, ready: false }),\n \"list-frames\": onPage({ mutation: false, charge: \"none\", refuseHeld: false, ready: false }),\n \"select-page\": registry({ mutation: false, charge: \"none\" }),\n // Opening a tab changes the inventory, not any page's document.\n \"new-page\": registry({ mutation: true, charge: \"none\" }),\n \"close-page\": onPage({\n mutation: true,\n charge: \"none\",\n refuseHeld: false,\n ready: false,\n recovery: true,\n }),\n resize: onPage({ mutation: true, charge: \"none\", refuseHeld: true, ready: false }),\n // reading\n ready: onPage({ mutation: false, charge: \"none\", refuseHeld: false, ready: false }),\n observe: onPage({\n mutation: false,\n charge: \"action\",\n refuseHeld: true,\n ready: true,\n refuseWhileWaiting: true,\n }),\n checkpoint: onPage({ mutation: false, charge: \"host-read\", refuseHeld: true, ready: true }),\n \"control-facts\": onPage({ mutation: false, charge: \"host-read\", refuseHeld: true, ready: true }),\n revalidate: onPage({ mutation: false, charge: \"none\", refuseHeld: true, ready: true }),\n \"read-text\": onPage({ mutation: false, charge: \"action\", refuseHeld: true, ready: true }),\n screenshot: onPage({ mutation: false, charge: \"action\", refuseHeld: true, ready: true }),\n wait: onPage({ mutation: false, charge: \"action\", refuseHeld: true, ready: true }),\n resolve: onPage({ mutation: false, charge: \"host-read\", refuseHeld: true, ready: false }),\n // A plan's own reads (preconditions and postconditions) are host reads of its page.\n run: onPage({ mutation: false, charge: \"host-read\", refuseHeld: true, ready: false }),\n settled: onPage({ mutation: false, charge: \"action\", refuseHeld: true, ready: false }),\n // input\n navigate: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: false }),\n \"navigate-stop\": onPage({\n mutation: true,\n charge: \"none\",\n refuseHeld: false,\n ready: false,\n recovery: true,\n }),\n click: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n fill: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"fill-form\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"select-option\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: false }),\n scroll: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"click-and-wait\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"download-action\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"select-files\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"file-chooser\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n \"action-result\": boundary,\n // native pointer input\n \"pointer-move\": onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n hover: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n wheel: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n // native key input\n press: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n type: onPage({ mutation: true, charge: \"action\", refuseHeld: true, ready: true }),\n // page control acts on a held page, so it never refuses one\n \"page-control\": boundary,\n \"page-state\": onPage({ mutation: false, charge: \"none\", refuseHeld: false, ready: false }),\n \"page-suspend\": onPage({\n mutation: false,\n charge: \"none\",\n refuseHeld: false,\n ready: false,\n refuseWhileWaiting: true,\n }),\n \"page-resume\": onPage({\n mutation: false,\n charge: \"none\",\n refuseHeld: false,\n ready: false,\n refuseWhileWaiting: true,\n }),\n // capture\n capture,\n \"capture-start\": capture,\n \"capture-stop\": capture,\n \"capture-consume\": capture,\n} as const satisfies Record<BrowserOperation, OperationPolicy>;\n\ntype Policies = typeof OperationPolicies;\n\n/** Operations confined to one exact page. */\nexport type PageOperation = {\n readonly [K in BrowserOperation]: Policies[K] extends PagePolicy ? K : never;\n}[BrowserOperation];\n\n/** Operations on the page inventory. */\nexport type RegistryOperation = {\n readonly [K in BrowserOperation]: Policies[K] extends RegistryPolicy ? K : never;\n}[BrowserOperation];\n\n/** Operations the session executes through its one page and registry path. */\nexport type ExecutedOperation = PageOperation | RegistryOperation;\n\nexport const policyOf = (operation: ExecutedOperation): PagePolicy | RegistryPolicy =>\n OperationPolicies[operation];\n","import { Deferred, Effect } from \"effect\";\n\nimport type { AdmissionStatus } from \"../../Browser.ts\";\nimport type { AdmissionLimits } from \"../../BrowserData.ts\";\nimport { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type { DriverTarget } from \"./Driver.ts\";\n\nexport interface NativeWait {\n readonly connection: object;\n readonly target: DriverTarget;\n readonly cancel: (reason?: BrowserError[\"reason\"]) => void;\n readonly retire: () => void;\n pending: boolean;\n}\n\nexport interface PendingAdmission {\n readonly token: object;\n readonly operation: BrowserOperation;\n readonly deadline: number;\n readonly requestedAt: number;\n readonly queueDeadline: number;\n readonly result: Deferred.Deferred<void, BrowserError>;\n readonly reserved: boolean;\n}\n\n/** Native ownership survives generation changes and caller cancellation. */\nexport interface NativePageCapacity {\n readonly work: ReadonlySet<object>;\n readonly wait?: NativeWait;\n readonly stopSetupPending?: Deferred.Deferred<void>;\n /** The connection whose positive retirement may release `stopSetupPending`. */\n readonly stopSetupConnection?: object;\n}\n\n/**\n * One page's caller ownership and retained native capacity share this record. Callers read it;\n * only admission's own operations change it.\n */\nexport interface AdmissionLane {\n readonly pageId?: string;\n readonly generation: number;\n readonly pending: ReadonlyArray<PendingAdmission>;\n readonly native: NativePageCapacity;\n readonly revision: number;\n readonly holder?: object;\n readonly active?: {\n readonly controller: AbortController;\n readonly operation: BrowserOperation;\n };\n readonly reservation?: AbortController;\n readonly recovery?: AdmissionLane;\n readonly closure?: AdmissionLane;\n readonly revoked: boolean;\n readonly retired: boolean;\n}\n\ninterface CapacityState {\n readonly work: Set<object>;\n wait?: NativeWait;\n stopSetupPending?: Deferred.Deferred<void>;\n stopSetupConnection?: object;\n}\n\ninterface LaneState {\n readonly pageId?: string;\n readonly generation: number;\n readonly pending: Array<PendingAdmission>;\n readonly native: CapacityState;\n revision: number;\n holder?: object;\n active?: { readonly controller: AbortController; readonly operation: BrowserOperation };\n reservation?: AbortController;\n recovery?: LaneState;\n closure?: LaneState;\n revoked: boolean;\n retired: boolean;\n}\n\nexport const makeAdmission = (\n now: () => number,\n expired: () => boolean,\n limits: AdmissionLimits = {},\n /** Called after work leaves admission, once its bookkeeping is complete. */\n settled: () => void = () => {},\n) => {\n const pages = new Map<string, LaneState>();\n const retained = new Set<LaneState>();\n // Every lane this admission made, by identity: callers hold the read-only view of each one.\n const owned = new WeakMap<AdmissionLane, LaneState>();\n\n const own = (lane: LaneState): LaneState => {\n owned.set(lane, lane);\n\n return lane;\n };\n\n const state = (lane: AdmissionLane): LaneState => {\n const found = owned.get(lane);\n\n if (found === undefined) throw new TypeError(\"Admission lane belongs to another admission\");\n\n return found;\n };\n\n const registry = own({\n generation: 0,\n pending: [],\n native: { work: new Set() },\n revision: 0,\n revoked: false,\n retired: false,\n });\n\n const maximumPage = limits.pendingPerPage ?? 32;\n const maximumSession = limits.pendingPerSession ?? 128;\n const maximumNative = 128;\n let pendingCount = 0;\n\n const native = new Map<\n object,\n {\n readonly lane: LaneState;\n readonly connection?: object;\n /** Whether this unsettled native call can still change its page. */\n readonly occupies: () => boolean;\n }\n >();\n\n const error = (operation: BrowserOperation, reason: BrowserError[\"reason\"]) =>\n BrowserError.make({ operation, reason, outcome: \"undispatched\" });\n\n /**\n * Native work outlives its caller. Work that dispatched input keeps its page until it settles;\n * a read, or a mutation whose caller left before dispatch, can no longer change the page.\n */\n const occupied = (capacity: CapacityState) =>\n [...capacity.work].some((token) => native.get(token)?.occupies() !== false);\n\n const available = (lane: LaneState) => lane.holder === undefined && !occupied(lane.native);\n\n const forgetState = (lane: LaneState) => {\n if (\n !lane.retired ||\n lane.native.work.size > 0 ||\n lane.holder !== undefined ||\n lane.native.stopSetupPending !== undefined ||\n lane.native.wait !== undefined ||\n lane.reservation !== undefined\n )\n return;\n retained.delete(lane);\n if (lane.pageId !== undefined && pages.get(lane.pageId) === lane) pages.delete(lane.pageId);\n };\n\n const next = (lane: LaneState) => {\n if (!available(lane) || lane.revoked) return;\n while (lane.pending.length > 0) {\n const head = lane.pending.shift();\n\n if (head === undefined) return;\n if (!head.reserved) pendingCount--;\n const time = now();\n\n const refusal = expired()\n ? Reasons.Expired.make({})\n : time >= head.deadline\n ? Reasons.Timeout.make({})\n : time >= head.queueDeadline\n ? Reasons.QueueExpired.make({})\n : undefined;\n\n if (refusal !== undefined) {\n Deferred.doneUnsafe(head.result, Effect.fail(error(head.operation, refusal)));\n continue;\n }\n // The next caller owns admission before it wakes. A fresh arrival cannot barge.\n lane.holder = head.token;\n Deferred.doneUnsafe(head.result, Effect.void);\n\n return;\n }\n };\n\n const releaseState = (lane: LaneState, token: object) => {\n if (lane.holder !== token) return;\n lane.holder = undefined;\n next(lane);\n forgetState(lane);\n settled();\n };\n\n const cancelState = (lane: LaneState, pending: PendingAdmission) => {\n const index = lane.pending.indexOf(pending);\n\n if (index >= 0) {\n lane.pending.splice(index, 1);\n if (!pending.reserved) pendingCount--;\n next(lane);\n } else releaseState(lane, pending.token);\n };\n\n const revokeState = (lane: LaneState, reason: BrowserError[\"reason\"]) => {\n lane.revoked = true;\n lane.active?.controller.abort();\n const pending = lane.pending.splice(0);\n\n pendingCount -= pending.filter((waiter) => !waiter.reserved).length;\n for (const waiter of pending)\n Deferred.doneUnsafe(waiter.result, Effect.fail(error(waiter.operation, reason)));\n };\n\n const snapshot = (lane: AdmissionLane): AdmissionStatus =>\n Object.freeze({\n active: lane.active?.operation ?? null,\n waiting: lane.pending.length,\n maximum: maximumPage,\n oldestWaitMillis:\n lane.pending[0] === undefined ? null : Math.max(0, now() - lane.pending[0].requestedAt),\n nativePending: lane.native.work.size,\n nativeWaitPending: lane.native.wait !== undefined,\n stopSetupPending: lane.native.stopSetupPending !== undefined,\n });\n\n /** Ends a navigation stop's setup on its capacity, if it is still the current one. */\n const clearStopSetup = (capacity: CapacityState) => {\n const setup = capacity.stopSetupPending;\n\n capacity.stopSetupPending = undefined;\n capacity.stopSetupConnection = undefined;\n if (setup !== undefined) Deferred.doneUnsafe(setup, Effect.void);\n };\n\n const wake = (capacity: CapacityState) => {\n for (const waiting of [registry, ...retained]) if (waiting.native === capacity) next(waiting);\n };\n\n const registryView: AdmissionLane = registry;\n\n return {\n registry: registryView,\n snapshot,\n status: () =>\n Object.freeze({\n waiting: pendingCount,\n maximum: maximumSession,\n nativePending: native.size,\n nativeMaximum: maximumNative,\n nativeWaits: new Set(\n [registry, ...retained]\n .map((lane) => lane.native)\n .filter((capacity) => capacity.wait !== undefined),\n ).size,\n stopSetups: new Set(\n [registry, ...retained]\n .map((lane) => lane.native)\n .filter((capacity) => capacity.stopSetupPending !== undefined),\n ).size,\n registry: snapshot(registry),\n }),\n /** The page's current lane, if it has one. */\n lane: (pageId: string): AdmissionLane | undefined => pages.get(pageId),\n lanes: (): ReadonlyArray<AdmissionLane> => [registry, ...retained],\n page: (pageId: string, generation: number): AdmissionLane => {\n const previous = pages.get(pageId);\n\n if (previous?.generation === generation) return previous;\n if (previous !== undefined) previous.retired = true;\n\n const lane = own({\n pageId,\n generation,\n pending: [],\n native: previous?.native ?? { work: new Set() },\n revision: previous?.revision ?? 0,\n revoked: false,\n retired: false,\n });\n\n pages.set(pageId, lane);\n retained.add(lane);\n if (previous !== undefined) forgetState(previous);\n\n return lane;\n },\n recovery: (lane: AdmissionLane, operation: BrowserOperation): AdmissionLane => {\n const page = state(lane);\n const key = operation === \"close-page\" ? \"closure\" : \"recovery\";\n const previous = page[key];\n\n if (previous !== undefined) {\n if (key === \"closure\" && !previous.retired && !page.retired) previous.revoked = false;\n\n return previous;\n }\n\n const recovery = own({\n ...(page.pageId === undefined ? {} : { pageId: page.pageId }),\n generation: page.generation,\n pending: [],\n native: { work: new Set() },\n revision: page.revision,\n revoked: false,\n retired: false,\n });\n\n page[key] = recovery;\n retained.add(recovery);\n\n return recovery;\n },\n acquire: (lane: AdmissionLane, pending: PendingAdmission, queueMillis: number) => {\n const owner = state(lane);\n\n if (owner.revoked) return Effect.fail(error(pending.operation, Reasons.Stale.make({})));\n if (available(owner) && owner.pending.length === 0) {\n owner.holder = pending.token;\n\n return Effect.void;\n }\n if (queueMillis <= 0) return Effect.fail(error(pending.operation, Reasons.Busy.make({})));\n\n if (pending.reserved && owner.pending.length >= 1)\n return Effect.fail(error(pending.operation, Reasons.Busy.make({})));\n\n const scope =\n pendingCount >= maximumSession\n ? \"session\"\n : owner.pageId === undefined\n ? \"registry\"\n : \"page\";\n\n if (\n !pending.reserved &&\n (pendingCount >= maximumSession || owner.pending.length >= maximumPage)\n )\n return Effect.fail(\n error(\n pending.operation,\n Reasons.QueueFull.make({\n scope,\n maximum: scope === \"session\" ? maximumSession : maximumPage,\n observed: (scope === \"session\" ? pendingCount : owner.pending.length) + 1,\n }),\n ),\n );\n owner.pending.push(pending);\n if (!pending.reserved) pendingCount++;\n\n return Deferred.await(pending.result);\n },\n cancel: (lane: AdmissionLane, pending: PendingAdmission) => cancelState(state(lane), pending),\n release: (lane: AdmissionLane, token: object) => releaseState(state(lane), token),\n forget: (lane: AdmissionLane) => forgetState(state(lane)),\n revoke: (lane: AdmissionLane, reason: BrowserError[\"reason\"]) =>\n revokeState(state(lane), reason),\n /** A page whose quarantine an operator released admits work again. */\n restore: (pageId: string) => {\n const lane = pages.get(pageId);\n\n if (lane !== undefined) lane.revoked = false;\n },\n /** Observation evidence on these pages (all of them without a page) is out of date. */\n revise: (pageId?: string) => {\n for (const lane of pages.values())\n if (pageId === undefined || lane.pageId === pageId) lane.revision++;\n },\n /** The admitted operation now running in this lane, until `deactivate`. */\n activate: (lane: AdmissionLane, controller: AbortController, operation: BrowserOperation) => {\n state(lane).active = { controller, operation };\n },\n deactivate: (lane: AdmissionLane, controller: AbortController) => {\n const owner = state(lane);\n\n if (owner.active?.controller === controller) owner.active = undefined;\n },\n /** A dispatched navigation's claim on its page, held until it settles or a fence aborts it. */\n reserve: (lane: AdmissionLane, controller: AbortController) => {\n state(lane).reservation = controller;\n },\n /** Clears the lane's reservation if it is still `controller`; false when it was replaced. */\n settleReservation: (lane: AdmissionLane, controller: AbortController): boolean => {\n const owner = state(lane);\n\n if (owner.reservation !== controller) return false;\n owner.reservation = undefined;\n\n return true;\n },\n /** Removes and returns the lane's reservation, for the caller to abort or settle. */\n takeReservation: (lane: AdmissionLane): AbortController | undefined => {\n const owner = state(lane);\n const reservation = owner.reservation;\n\n owner.reservation = undefined;\n\n return reservation;\n },\n /** A pure wait owns its page's single wait slot until `endWait`. */\n beginWait: (lane: AdmissionLane, wait: NativeWait) => {\n state(lane).native.wait = wait;\n },\n endWait: (wait: NativeWait) => {\n for (const lane of [registry, ...retained]) {\n if (lane.native.wait !== wait) continue;\n lane.native.wait = undefined;\n forgetState(lane);\n }\n },\n /**\n * Installs a navigation stop's setup on the lane's native capacity for `connection`. Returns\n * undefined while another setup is pending; otherwise its settle, which clears the setup if\n * it is still current and releases anyone waiting for it.\n */\n beginStopSetup: (lane: AdmissionLane, connection: object | undefined) => {\n const capacity = state(lane).native;\n\n if (capacity.stopSetupPending !== undefined) return undefined;\n const setup = Deferred.makeUnsafe<void>();\n\n capacity.stopSetupPending = setup;\n capacity.stopSetupConnection = connection;\n\n return () => {\n if (capacity.stopSetupPending === setup) {\n capacity.stopSetupPending = undefined;\n capacity.stopSetupConnection = undefined;\n }\n Deferred.doneUnsafe(setup, Effect.void);\n };\n },\n blockPending: (reason: BrowserError[\"reason\"]) => {\n for (const lane of [registry, ...retained]) {\n const pending = lane.pending.filter((waiter) => !waiter.reserved);\n\n if (pending.length === 0) continue;\n for (const waiter of pending) lane.pending.splice(lane.pending.indexOf(waiter), 1);\n\n pendingCount -= pending.length;\n for (const waiter of pending)\n Deferred.doneUnsafe(waiter.result, Effect.fail(error(waiter.operation, reason)));\n }\n },\n fence: (reason: BrowserError[\"reason\"]) => {\n // Registry ownership belongs to the transition that performed the fence.\n for (const lane of retained) {\n lane.retired = true;\n revokeState(lane, reason);\n }\n registry.active?.controller.abort();\n const pending = registry.pending.splice(0);\n\n pendingCount -= pending.filter((waiter) => !waiter.reserved).length;\n for (const waiter of pending)\n Deferred.doneUnsafe(waiter.result, Effect.fail(error(waiter.operation, reason)));\n for (const lane of retained) forgetState(lane);\n },\n retainNative: (\n lane: AdmissionLane,\n operation: BrowserOperation,\n connection?: object,\n occupies: () => boolean = () => true,\n ) => {\n const owner = state(lane);\n\n if (native.size >= maximumNative)\n throw error(\n operation,\n Reasons.Limit.make({\n dimension: \"native-operations\",\n maximum: maximumNative,\n observed: native.size,\n }),\n );\n const token = {};\n\n owner.native.work.add(token);\n native.set(token, {\n lane: owner,\n occupies,\n ...(connection === undefined ? {} : { connection }),\n });\n\n return () => {\n if (!native.delete(token)) return;\n owner.native.work.delete(token);\n wake(owner.native);\n forgetState(owner);\n settled();\n };\n },\n retirePage: (pageId: string) => {\n for (const lane of retained) {\n if (lane.pageId !== pageId) continue;\n for (const token of lane.native.work) native.delete(token);\n lane.native.work.clear();\n clearStopSetup(lane.native);\n lane.revoked = true;\n lane.retired = true;\n forgetState(lane);\n next(lane);\n }\n pages.delete(pageId);\n settled();\n },\n retire: () => {\n native.clear();\n for (const lane of [registry, ...retained]) {\n lane.native.work.clear();\n clearStopSetup(lane.native);\n forgetState(lane);\n }\n settled();\n },\n retireConnection: (connection: object) => {\n for (const lane of [registry, ...retained]) {\n // Only the setup's own connection may release it, even when that retirement arrives\n // after a successor connection has used the same page.\n if (lane.native.stopSetupConnection !== connection) continue;\n clearStopSetup(lane.native);\n forgetState(lane);\n }\n for (const [token, lease] of native) {\n if (lease.connection !== connection) continue;\n native.delete(token);\n lease.lane.native.work.delete(token);\n wake(lease.lane.native);\n forgetState(lease.lane);\n }\n settled();\n },\n /**\n * Only native work that can still change a page must settle. A `held` lane belongs to an\n * operator's quarantine, whose own work, including a pending stop setup, cannot hold up the\n * handoff that releases it.\n */\n drained: (except?: AbortSignal, held: (lane: AdmissionLane) => boolean = () => false) =>\n [...native.values()].every((lease) => !lease.occupies() || held(lease.lane)) &&\n [registry, ...retained].every(\n (lane) =>\n (lane.native.stopSetupPending === undefined || held(lane)) &&\n (lane.holder === undefined ||\n (except !== undefined && lane.active?.controller.signal === except)),\n ),\n };\n};\n","import { Cause, Clock, Deferred, Duration, Effect, Exit, Option, Schema } from \"effect\";\n\nimport type { OperationOptions } from \"../../Browser.ts\";\nimport {\n BrowserDiagnostic,\n BrowserDiagnostics,\n type ObservedElement,\n type InputReceipt,\n type AdmissionLimits,\n SessionStatus,\n type SessionReason,\n type SessionPhase,\n} from \"../../BrowserData.ts\";\nimport {\n BrowserError,\n Reasons,\n type BrowserOperation,\n type BrowserOutcome,\n type BrowserReason,\n type Containment,\n} from \"../../Errors.ts\";\nimport type { AcknowledgementFact, SettledEvidence } from \"../../PlanData.ts\";\nimport type { Correlation } from \"../../TimelineData.ts\";\nimport * as Trace from \"../Trace.ts\";\nimport { makeAdmission } from \"./Admission.ts\";\nimport type { DriverFault, DriverTarget } from \"./Driver.ts\";\nimport { NativeEffectFailure, providerReason, publicError } from \"./NativeCalls.ts\";\nimport { grantedPacing } from \"./NativePacing.ts\";\nimport type { DescriptorSample, ResolvedElement } from \"./Observation.ts\";\nimport type { PerformancePlan } from \"./Performance.ts\";\n\nexport interface NativePictureBoundary {\n readonly phase: \"Requested\" | \"Returned\";\n readonly target: DriverTarget;\n readonly documentEpoch: number;\n readonly geometry: { readonly width: number; readonly height: number };\n readonly byteLength?: number;\n}\n\n/** One native scroll a driver performed for an admitted operation. */\nexport interface ScrollFacts {\n readonly target: DriverTarget;\n readonly x?: number;\n readonly y?: number;\n readonly qualification?: \"exact-node-scroll-into-view\";\n readonly startedMonotonicNanos: bigint;\n readonly completedMonotonicNanos: bigint;\n}\n\n/** The pointer path a driver intends for an admitted operation, before the pointer moves. */\nexport interface GlideFacts {\n readonly target: DriverTarget;\n readonly startedMonotonicNanos: bigint;\n readonly samples: ReadonlyArray<{\n readonly offsetMillis: number;\n readonly position: { readonly x: number; readonly y: number };\n }>;\n}\n\n/** How much logical keyboard input a press or type receipt carried. */\nexport interface KeyCount {\n readonly count: number;\n readonly countUnit: \"unicode-codepoints\" | \"logical-strokes\";\n}\n\n/**\n * One fact about one operation. Its ticket emits each fact once, to every listener, and decides\n * once whether the fact is late: whether it arrived after the operation ended (for any fact but\n * the end itself), after the operation was given up, or past its deadline. `Finished` is the\n * only fact of an operation that was refused before it was admitted.\n */\nexport type OperationEvent =\n | {\n readonly _tag: \"Phase\";\n readonly phase: Exclude<NonNullable<Ticket[\"phase\"]>, \"Terminal\">;\n /** Whether the phase sends a native command or acknowledges the one pending. */\n readonly mutation: boolean;\n readonly acknowledgement?: AcknowledgementFact;\n readonly late: boolean;\n readonly atMonotonicNanos: bigint;\n }\n | {\n readonly _tag: \"Terminal\";\n /** The owner's classification of everything this operation's native commands did. */\n readonly outcome: BrowserOutcome;\n readonly containment: Containment;\n readonly late: boolean;\n readonly atMonotonicNanos: bigint;\n }\n | { readonly _tag: \"Picture\"; readonly boundary: NativePictureBoundary }\n | { readonly _tag: \"Input\"; readonly receipt: InputReceipt; readonly keys?: KeyCount }\n | {\n readonly _tag: \"Scroll\";\n readonly facts: ScrollFacts;\n /** The connection generation the scrolling ticket was admitted under. */\n readonly generation: number;\n readonly late: boolean;\n }\n | { readonly _tag: \"Glide\"; readonly facts: GlideFacts }\n | { readonly _tag: \"Settled\"; readonly evidence: SettledEvidence; readonly target: DriverTarget }\n | {\n readonly _tag: \"Finished\";\n readonly kind: \"Completed\" | \"Failed\" | \"Cancelled\";\n readonly outcome: BrowserOutcome;\n readonly error?: BrowserError;\n readonly containment: Containment;\n };\n\n/** What a listener learns about one operation before its first event. */\nexport interface OperationFacts {\n readonly operation: BrowserOperation;\n readonly operationId: string;\n readonly generation: number;\n readonly scope: ObservationScope | undefined;\n readonly correlation: Correlation | null;\n}\n\n/**\n * Subscribes to operations: called once for each one the owner guards, it returns the receiver\n * of that operation's events. Listeners observe; they grant no authority.\n */\nexport type OperationListener = (operation: OperationFacts) => (event: OperationEvent) => void;\n\nconst outcomeRank: Record<BrowserOutcome, number> = {\n undispatched: 0,\n rejected: 1,\n performed: 2,\n unknown: 3,\n};\n\n/**\n * What is known about input never weakens: an unknown outcome stays unknown, acknowledged input\n * stays performed, and refused preparation stays rejected, whichever evidence says so.\n */\nexport const strongestOutcome = (left: BrowserOutcome, right: BrowserOutcome): BrowserOutcome =>\n outcomeRank[right] > outcomeRank[left] ? right : left;\n\n/** The browser domain's bounded step: one deadline, one declared BrowserError timeout. */\nexport const within = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n deadline: number,\n onTimeout: () => BrowserError,\n): Effect.Effect<A, E | BrowserError, R> =>\n Effect.gen(function* () {\n const now = Number(yield* Clock.monotonicTimeNanos) / 1_000_000;\n\n return yield* deadline <= now\n ? Effect.fail(onTimeout())\n : effect.pipe(\n Effect.timeoutOrElse({\n duration: Duration.millis(deadline - now),\n orElse: () => Effect.fail(onTimeout()),\n }),\n );\n });\n\nexport type Phase = SessionPhase;\n\nexport type Invalidation =\n | \"observation\"\n | \"target-changed\"\n | \"resized\"\n | \"paused\"\n | \"disconnected\"\n | \"uncertain\"\n | \"closed\";\n\n/**\n * Observation retirement is independent of the owner's revision and connection fences. A frame\n * narrows a page: an observation holds nodes of the one frame it read, so another frame of the\n * page navigating or detaching (an advertisement reloading, say) changes nothing it names.\n */\nexport type ObservationScope =\n | \"all\"\n | \"none\"\n | { readonly pageId: string; readonly frameId?: string };\n\n/** A bounded native reading has no mutation dispatch authority. */\nexport interface ReadTicket {\n readonly signal: AbortSignal;\n readonly deadline: number;\n readonly generation: number;\n readonly remainingMillis: () => number;\n check(): void;\n}\n\n/** What a performed operation asks of the owner: its seeded plan and, in a form, its field. */\nexport interface PerformanceRequest {\n readonly plan: PerformancePlan;\n readonly fieldIndex?: number;\n}\n\n/**\n * A performed admission: the request, plus the original owner's clock, deadline and sleep, which\n * the owner grants every performed ticket. A plain ticket has none of them.\n */\nexport interface Performance extends PerformanceRequest {\n /** The original owner's monotonic clock. */\n readonly now: () => bigint;\n /** Exact original-owner time left; native SDK timeouts retain their separate millisecond floor. */\n readonly remainingTimeNanos: () => bigint;\n /** Original-owner sleep, bounded by this admission and fenced before and after waiting. */\n readonly pauseUntil: (atNanos: bigint) => Promise<void>;\n}\n\n/** One admitted native operation; checks at dispatch also fence late Promise continuations. */\nexport interface Ticket extends ReadTicket {\n /** Present exactly when the operation is performed, with the owner's pacing. */\n readonly performance?: Performance;\n readonly operationId?: string;\n readonly picture?: (boundary: NativePictureBoundary) => void;\n readonly recordInput?: (receipt: InputReceipt, keys?: KeyCount) => void;\n readonly recordScroll?: (facts: ScrollFacts) => void;\n readonly recordGlide?: (facts: GlideFacts) => void;\n readonly recordSettled?: (evidence: SettledEvidence, target: DriverTarget) => void;\n /** Native work keeps capacity until settlement, independently of the request fiber. */\n readonly retainNative?: () => () => void;\n readonly dispatched: boolean;\n /** Original phase-aware native outcome; preparatory acknowledgement is not logical success. */\n readonly outcome?: BrowserOutcome;\n readonly phase?: \"Prepared\" | \"Dispatched\" | \"Acknowledged\" | \"FollowUp\" | \"Terminal\";\n /** Actual owner's containment, including pure interruption without a typed failure. */\n readonly containment?: Containment;\n dispatch(): void;\n /** Called only for positive completion of all native commands in the current mutation phase. */\n acknowledge?(fact?: AcknowledgementFact): void;\n followUp?(): void;\n /** Facts from the checked node immediately before dispatch; no separate recording read. */\n readonly captureTarget?: (\n target: string | ObservedElement | ResolvedElement,\n sample: DescriptorSample | undefined,\n ) => void;\n}\n\n/**\n * A composite operation's own evidence about the operations it admits: their correlation, its\n * subscription to their events, and the exact targets they checked. Never dispatch authority.\n */\nexport interface ExecutionEvidence {\n readonly correlation?: () => Correlation | null;\n readonly listener?: OperationListener;\n readonly target?: NonNullable<Ticket[\"captureTarget\"]>;\n}\n\n/** The driver retires native capacity only after its wait and required handle disposal settle. */\nexport interface WaitTicket extends ReadTicket {\n invalidate(): void;\n retire(): void;\n}\n\nexport interface OwnedWait {\n readonly ticket: WaitTicket;\n readonly completed: Effect.Effect<void, BrowserError>;\n readonly start: (body: () => Promise<void>) => void;\n readonly cancel: (reason?: BrowserError[\"reason\"]) => void;\n}\n\n/**\n * A dispatched mutation the browser is still performing after its permit was released: an\n * in-flight navigation. It keeps other mutations off that page while reads, holds and other\n * pages proceed. Like a permit it cannot be dropped silently: only a known outcome releases it.\n */\nexport interface Reservation {\n /** Aborted by any fence, so work that outlives its connection is never treated as current. */\n readonly signal: AbortSignal;\n /** `unknown` fences the owner, exactly as a mutation interrupted after dispatch does. */\n readonly settle: (outcome: \"known\" | \"unknown\") => void;\n}\n\nexport interface Limits {\n readonly admissionLimits?: AdmissionLimits;\n readonly maxActions: number;\n readonly maxHostReads: number;\n readonly maxElapsedMillis: number;\n readonly actionTimeoutMillis: number;\n}\n\n/** One span per public operation attempt, from validation to its terminal outcome. */\nexport const operationSpan = (operation: BrowserOperation) =>\n Trace.span(`Browser.${operation}`, { attributes: { \"browser.operation\": operation } });\n\nexport const makeOwner = Effect.fnUntraced(function* (limits: Limits) {\n const clock = yield* Clock.Clock;\n let listener: OperationListener | undefined;\n let observePhase: ((phase: Phase) => void) | undefined;\n let operationSequence = 0n;\n\n const lifetimeDeadline =\n Number(yield* Clock.monotonicTimeNanos) / 1_000_000 + limits.maxElapsedMillis;\n\n const hooks = new Set<\n (reason: Invalidation, scope: ObservationScope, origin?: AbortSignal) => void\n >();\n\n const state = {\n phase: \"acquiring\" as Phase,\n generation: 0,\n revision: 0,\n actions: 0,\n hostReads: 0,\n };\n\n let admissionBarrier: object | undefined;\n let nativeConnection: object | undefined;\n // Completed once whenever work settles, so a handoff's drain waits for a change, not a timer.\n let change = Deferred.makeUnsafe<void>();\n\n const changed = () => {\n const previous = change;\n\n change = Deferred.makeUnsafe<void>();\n Deferred.doneUnsafe(previous, Effect.void);\n };\n\n const admission = makeAdmission(\n () => Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000,\n () => terminalReason === \"expired\",\n limits.admissionLimits,\n () => changed(),\n );\n\n const waits = () =>\n new Set(\n admission\n .lanes()\n .flatMap((lane) => (lane.native.wait === undefined ? [] : [lane.native.wait])),\n );\n\n const waitOn = (pageId: string) => admission.lane(pageId)?.native.wait;\n // These facts outlive the tickets which produced them. Aborting admission is not retirement.\n const unresolved = new Map<object, string | undefined>();\n let nativeUncertainty = false;\n let terminalReason: SessionReason | null = null;\n let pauseReason: SessionReason | null = null;\n const policies = new Map<object, Extract<DriverFault, { readonly source: \"policy\" }>>();\n // Pages a popup/dialog policy paused: an operator, not containment, decides their work.\n const quarantined = new Set<string>();\n const records: Array<BrowserDiagnostics[\"records\"][number]> = [];\n let total = 0;\n let dropped = 0;\n\n const record = (\n reason: SessionReason,\n disposition: BrowserDiagnostics[\"records\"][number][\"disposition\"],\n generation = state.generation,\n ) => {\n total = Math.min(Number.MAX_SAFE_INTEGER, total + 1);\n if (records.length === 32) {\n records.shift();\n dropped = Math.min(Number.MAX_SAFE_INTEGER, dropped + 1);\n }\n records.push(\n Object.freeze(\n BrowserDiagnostic.make({\n reason,\n disposition,\n generation,\n monotonicNanos: clock.monotonicTimeNanosUnsafe(),\n }),\n ),\n );\n };\n\n /**\n * Why admission refuses work in the owner's present state, or undefined when it would admit it.\n * Both of the guard's admission checks and stale-capability reporting share this one answer,\n * so a pending policy cleanup reports busy only while the session can still recover.\n */\n const refusal = (\n options: {\n readonly phases?: ReadonlyArray<Phase>;\n readonly recovery?: boolean;\n readonly bypassBlocked?: boolean;\n } = {},\n ): BrowserReason | undefined => {\n const blocked = admissionBarrier !== undefined && options.bypassBlocked !== true;\n\n if (\n (options.phases ?? [\"open\"]).includes(state.phase) &&\n (policies.size === 0 || options.recovery === true) &&\n (!blocked || options.recovery === true)\n )\n return undefined;\n\n return terminalReason === \"expired\"\n ? Reasons.Expired.make({})\n : state.phase === \"paused\" || blocked || (terminalReason === null && policies.size > 0)\n ? Reasons.Busy.make({})\n : Reasons.Closed.make({});\n };\n\n const transition = (phase: Phase) => {\n if (\n (terminalReason !== null || state.phase === \"closed\" || state.phase === \"closing\") &&\n phase !== \"closing\" &&\n phase !== \"closed\"\n )\n return;\n const changed = state.phase !== phase;\n\n state.phase = phase;\n if (phase === \"open\") pauseReason = null;\n if (changed) observePhase?.(state.phase);\n };\n\n const invalidate = (\n reason: Invalidation,\n scope: ObservationScope = \"all\",\n origin?: AbortSignal,\n ) => {\n for (const waiting of waits())\n if (scope === \"all\" || (scope !== \"none\" && scope.pageId === waiting.target.pageId))\n waiting.cancel(Reasons.Stale.make({}));\n if (scope === \"all\") admission.revise();\n else if (scope !== \"none\") admission.revise(scope.pageId);\n state.revision++;\n for (const hook of hooks) hook(reason, scope, origin);\n };\n\n const fence = (phase: Phase, reason: Invalidation, trigger?: SessionReason) => {\n if (\n state.phase === \"closed\" ||\n (state.phase === \"closing\" && phase !== \"closed\" && phase !== \"closing\")\n )\n return;\n if (phase === \"uncertain\" || phase === \"faulted\" || phase === \"closing\" || phase === \"closed\")\n terminalReason ??= trigger ?? (phase === \"uncertain\" ? \"native-failure\" : \"closed\");\n else if (trigger !== undefined) pauseReason = trigger;\n // A known trigger is retained even when the abort below interrupts dispatched work.\n const previous = state.phase;\n\n if (!(state.phase === \"faulted\" && phase === \"uncertain\")) state.phase = phase;\n state.generation++;\n if (state.phase !== previous) observePhase?.(state.phase);\n const pending: Array<AbortController> = [];\n\n for (const lane of admission.lanes()) {\n const reservation = admission.takeReservation(lane);\n\n if (reservation !== undefined) pending.push(reservation);\n }\n\n const refusal =\n terminalReason === \"expired\" ? Reasons.Expired.make({}) : Reasons.Stale.make({});\n\n // A handoff keeps each quarantine for its operator; losing the connection ends them.\n if (reason === \"disconnected\" || reason === \"uncertain\" || reason === \"closed\")\n quarantined.clear();\n admission.fence(refusal);\n for (const waiting of waits()) waiting.cancel(refusal);\n for (const reservation of pending) reservation.abort();\n invalidate(reason);\n changed();\n };\n\n const terminate = (\n reason: SessionReason,\n disposition: \"known\" | \"not-dispatched\" | \"unknown\",\n generation = state.generation,\n ) => {\n if (disposition === \"unknown\") nativeUncertainty = true;\n record(reason, disposition === \"known\" ? \"confirmed\" : disposition, generation);\n fence(\n disposition === \"unknown\" ? \"uncertain\" : \"faulted\",\n disposition === \"unknown\" ? \"uncertain\" : \"closed\",\n reason,\n );\n };\n\n const expire = () => {\n if (terminalReason !== null || state.phase === \"closing\" || state.phase === \"closed\") return;\n terminate(\"expired\", \"known\");\n };\n\n /** Quarantine changes admission only; an originating click keeps its own valid ticket. */\n const policy = (\n event: Extract<DriverFault, { readonly source: \"policy\" }>,\n generation: number,\n ) => {\n if (event.disposition !== \"dispatched\") record(event.reason, event.disposition, generation);\n const previous = policies.get(event.token);\n\n switch (event.disposition) {\n case \"pending\":\n if (previous === undefined && terminalReason === null) policies.set(event.token, event);\n break;\n case \"dispatched\":\n unresolved.set(event.token, undefined);\n if (previous !== undefined) policies.set(event.token, event);\n break;\n case \"confirmed\":\n unresolved.delete(event.token);\n policies.delete(event.token);\n break;\n case \"unknown\":\n // Keep the token so a late acknowledgement may retire it, but never reopen admission.\n unresolved.set(event.token, undefined);\n fence(\"uncertain\", \"uncertain\", event.reason);\n break;\n case \"not-dispatched\":\n policies.delete(event.token);\n fence(\"faulted\", \"closed\", event.reason);\n break;\n }\n changed();\n };\n\n /** Taken under the permit that dispatched the work, so nothing can interleave before it. */\n const reserve = (key: string): Reservation => {\n // Outlives the fiber that dispatched it, and must be abortable by a fence from outside it.\n const controller = new AbortController();\n\n const lane = admission.lane(key);\n\n if (lane === undefined)\n throw BrowserError.make({\n operation: \"navigate\",\n reason: Reasons.Stale.make({}),\n outcome: \"unknown\",\n });\n admission.reserve(lane, controller);\n unresolved.set(controller, key);\n\n return {\n signal: controller.signal,\n settle: (outcome) => {\n // Navigation recovery is bounded by the lifetime, so it can give up at the same instant\n // as the independent lifetime timer. As for an action's timer, that instant is expiry.\n if (\n outcome === \"unknown\" &&\n lane.reservation === controller &&\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline\n )\n expire();\n // A fence already cleared it, and decided the outcome for everything it aborted.\n if (!admission.settleReservation(lane, controller)) return;\n if (outcome === \"known\") unresolved.delete(controller);\n else fence(\"uncertain\", \"uncertain\");\n admission.forget(lane);\n changed();\n },\n };\n };\n\n /**\n * Admission transfers a pure wait to an independent deadline and cancellation record. Its\n * logical barrier may end before uncancellable native work; neither is a mutation reservation.\n */\n const beginWait = (\n admitted: Ticket,\n target: DriverTarget,\n connection: object,\n operation: \"wait\" | \"settled\" = \"wait\",\n ): OwnedWait => {\n admitted.check();\n const lane = admission.lane(target.pageId);\n\n if (lane === undefined || lane.native.wait !== undefined)\n throw BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n });\n const controller = new AbortController();\n const result = Deferred.makeUnsafe<void, BrowserError>();\n const generation = admitted.generation;\n const deadline = admitted.deadline;\n let retired = false;\n let started = false;\n let canceled: BrowserError | undefined;\n\n const error = (reason: BrowserError[\"reason\"]) =>\n BrowserError.make({ operation, reason, outcome: \"undispatched\" });\n\n const release = () => {\n if (retired && !record.pending) admission.endWait(record);\n };\n\n const complete = (exit: Effect.Effect<void, BrowserError>) => {\n if (!record.pending) return;\n record.pending = false;\n release();\n Deferred.doneUnsafe(result, exit);\n };\n\n const cancel: OwnedWait[\"cancel\"] = (reason = Reasons.Interrupted.make({})) => {\n if (record.pending) {\n canceled = error(reason);\n complete(Effect.fail(canceled));\n }\n controller.abort();\n };\n\n const record = {\n connection,\n target: { ...target },\n pending: true,\n cancel,\n retire: () => {\n retired = true;\n release();\n },\n };\n\n admission.beginWait(lane, record);\n\n const check = () => {\n const now = Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000;\n\n if (now >= lifetimeDeadline) expire();\n if (canceled !== undefined) throw canceled;\n if (controller.signal.aborted || state.generation !== generation || state.phase !== \"open\")\n throw error(Reasons.Stale.make({}));\n if (now >= deadline) throw error(Reasons.Timeout.make({}));\n };\n\n const ticket: WaitTicket = {\n signal: controller.signal,\n deadline,\n generation,\n remainingMillis: () =>\n Math.max(1, deadline - Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000),\n check,\n invalidate: () => cancel(Reasons.Stale.make({})),\n retire: record.retire,\n };\n\n const fail = (cause: unknown) => {\n let failure = publicError(cause, operation, {\n reason: Reasons.Provider.make({}),\n outcome: \"undispatched\",\n });\n\n try {\n check();\n } catch (current) {\n failure = publicError(current, \"wait\", failure);\n }\n complete(Effect.fail(failure));\n };\n\n return {\n ticket,\n cancel,\n completed: within(Deferred.await(result), deadline, () => {\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline) expire();\n cancel(Reasons.Timeout.make({}));\n\n return canceled ?? error(Reasons.Timeout.make({}));\n }).pipe(\n Effect.provideService(Clock.Clock, clock),\n Effect.tap(() =>\n Effect.try({\n try: check,\n catch: (cause) =>\n publicError(cause, operation, {\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n }),\n }),\n ),\n ),\n start: (body) => {\n if (started) return;\n started = true;\n try {\n check();\n // Observe settlement after cancellation too; the native retire callback owns capacity.\n void body().then(() => {\n try {\n check();\n complete(Effect.void);\n } catch (cause) {\n fail(cause);\n }\n }, fail);\n } catch (cause) {\n record.retire();\n fail(cause);\n }\n },\n };\n };\n\n const contain = (\n page: { readonly pageId: string; readonly close: Effect.Effect<boolean> } | undefined,\n generation: number,\n ): Effect.Effect<Containment> =>\n Effect.uninterruptible(\n Effect.gen(function* () {\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline) expire();\n if (page === undefined || state.generation !== generation || state.phase !== \"open\") {\n fence(\"uncertain\", \"uncertain\");\n\n return { _tag: \"SessionFenced\", generation: state.generation };\n }\n const closed = yield* page.close;\n\n if (!closed || state.generation !== generation || state.phase !== \"open\") {\n fence(\"uncertain\", \"uncertain\");\n\n return { _tag: \"SessionFenced\", generation: state.generation };\n }\n const lane = admission.lane(page.pageId);\n const reservation = lane === undefined ? undefined : admission.takeReservation(lane);\n\n if (reservation !== undefined) {\n unresolved.delete(reservation);\n reservation.abort();\n }\n record(\"page-contained\", \"confirmed\", generation);\n changed();\n\n return { _tag: \"PageClosed\", pageId: page.pageId, generation };\n }),\n );\n\n const guard = <A, E, R>(\n operation: BrowserOperation,\n body: (ticket: Ticket) => Effect.Effect<A, E, R>,\n options: {\n readonly charge?: boolean | \"host-read\";\n readonly mutation?: boolean;\n readonly mutationScope?: () => ObservationScope;\n /** Exact work attribution can remain page-local while a form preserves its observations. */\n readonly targetScope?: () => ObservationScope;\n readonly phases?: ReadonlyArray<Phase>;\n readonly verifyAfter?: boolean;\n readonly preflight?: Effect.Effect<void, BrowserError>;\n /** A request can shorten this operation's policy deadline, never extend it. */\n readonly timeoutMillis?: number;\n readonly admission?: OperationOptions[\"admission\"];\n /** Composite operations retain the deadlines captured by their original caller. */\n readonly operationDeadline?: number;\n readonly queueDeadline?: number;\n readonly evidence?: ExecutionEvidence;\n readonly performance?: PerformanceRequest;\n /** Private recovery admission: one absolute deadline also bounds waiting for this permit. */\n readonly waitUntil?: number;\n /** Recovery and lifecycle cleanup own independent, bounded capacity. */\n readonly recovery?: boolean;\n readonly bypassBlocked?: boolean;\n /**\n * Where this operation's own page can absorb an unknown outcome: the page, and a request\n * that the browser close it, made once the outcome is unknown, which says whether it did.\n * Undefined, or a page that did not close, fences.\n */\n readonly contain?: () =>\n | { readonly pageId: string; readonly close: Effect.Effect<boolean> }\n | undefined;\n /** False when the caller already spans the operation, including its own validation. */\n readonly traced?: boolean;\n } = {},\n ): Effect.Effect<A, E | BrowserError, R> =>\n Effect.uninterruptibleMask((restoreGuard) =>\n Effect.gen(function* () {\n // Admission is its own span: it ends when the permit is held, or with the refusal.\n const admissionSpan = yield* Trace.start(\"Browser.admission\", {\n attributes: { \"browser.operation\": operation },\n });\n\n let admittedTicket: Ticket | undefined;\n\n return yield* restoreGuard(\n Effect.suspend(() => {\n const requested = Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000;\n const operationId = (++operationSequence).toString();\n let admitted = false;\n\n const deadline = Math.min(\n requested +\n Math.min(\n options.timeoutMillis ?? limits.actionTimeoutMillis,\n limits.actionTimeoutMillis,\n ),\n options.operationDeadline ?? Number.POSITIVE_INFINITY,\n options.waitUntil ?? Number.POSITIVE_INFINITY,\n lifetimeDeadline,\n );\n\n const queueMillis =\n options.waitUntil !== undefined\n ? Math.max(0, options.waitUntil - requested)\n : options.admission?.queue === undefined\n ? 0\n : Duration.toMillis(options.admission.queue);\n\n const queueDeadline = options.queueDeadline ?? requested + queueMillis;\n const scope = options.targetScope?.() ?? options.mutationScope?.();\n\n const facts: OperationFacts = {\n operation,\n operationId,\n generation: state.generation,\n scope,\n correlation: options.evidence?.correlation?.() ?? null,\n };\n\n // The operation's own subscriber first, then the session's: each fact is emitted once.\n const receivers = [options.evidence?.listener?.(facts), listener?.(facts)];\n\n const emit = (event: OperationEvent) => {\n for (const receive of receivers) receive?.(event);\n };\n\n const pageLane =\n scope !== undefined && scope !== \"all\" && scope !== \"none\"\n ? admission.lane(scope.pageId)\n : undefined;\n\n const lane =\n options.recovery === true && pageLane !== undefined\n ? admission.recovery(pageLane, operation)\n : (pageLane ?? admission.registry);\n\n // A mutation of one page needs that page's lane. The registry lane would admit it without\n // the page's serialization, and a navigation could not reserve its page after dispatch.\n const unregistered =\n pageLane === undefined &&\n scope !== undefined &&\n scope !== \"all\" &&\n scope !== \"none\" &&\n options.mutation === true &&\n options.recovery !== true;\n\n const pending = {\n token: {},\n operation,\n requestedAt: requested,\n deadline,\n queueDeadline,\n result: Deferred.makeUnsafe<void, BrowserError>(),\n reserved: options.recovery === true,\n };\n\n const work = Effect.gen(function* () {\n admissionSpan?.end(Exit.void);\n const refused = refusal(options);\n\n if (refused !== undefined)\n return yield* BrowserError.make({\n operation,\n reason: refused,\n outcome: \"undispatched\",\n });\n yield* options.preflight ?? Effect.void;\n const now = Number(yield* Clock.monotonicTimeNanos) / 1_000_000;\n\n if (lane.revoked || unregistered)\n return yield* BrowserError.make({\n operation,\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n });\n if (now >= lifetimeDeadline) {\n expire();\n\n return yield* BrowserError.make({\n operation,\n reason: Reasons.Expired.make({}),\n outcome: \"undispatched\",\n });\n }\n\n if (now >= deadline)\n return yield* BrowserError.make({\n operation,\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n });\n if (options.charge !== false) {\n const hostRead = options.charge === \"host-read\";\n const maximum = hostRead ? limits.maxHostReads : limits.maxActions;\n const observed = hostRead ? state.hostReads : state.actions;\n\n if (observed >= maximum)\n return yield* BrowserError.make({\n operation,\n reason: Reasons.Limit.make({\n dimension: hostRead ? \"host-reads\" : \"actions\",\n maximum,\n observed,\n }),\n outcome: \"undispatched\",\n });\n if (hostRead) state.hostReads++;\n else state.actions++;\n }\n // The lifecycle fence must actively abort admitted native work outside the current fiber.\n // @effect-diagnostics-next-line abortControllerInEffect:off\n const controller = new AbortController();\n\n admission.activate(lane, controller, operation);\n let dispatched = false;\n let pending = false;\n // Acknowledged input that landed, and acknowledged preparation that changed no input.\n let inputAcknowledged = false;\n let preparationAcknowledged = false;\n let phase: NonNullable<Ticket[\"phase\"]> = \"Prepared\";\n let unknownDecided = false;\n let containment: Containment = { _tag: \"NotRequired\" };\n const generation = state.generation;\n const allowed = options.phases ?? [\"open\"];\n\n // A driver's own outcome describes its last command; these flags, everything acknowledged.\n const currentOutcome = (driver: BrowserOutcome = \"undispatched\"): BrowserOutcome =>\n strongestOutcome(\n pending || unknownDecided\n ? \"unknown\"\n : inputAcknowledged\n ? \"performed\"\n : preparationAcknowledged\n ? \"rejected\"\n : \"undispatched\",\n driver,\n );\n\n const check = () => {\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline)\n expire();\n if (\n controller.signal.aborted ||\n state.generation !== generation ||\n !allowed.includes(state.phase)\n ) {\n throw BrowserError.make({\n operation,\n reason: Reasons.Stale.make({}),\n outcome: currentOutcome(),\n });\n }\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= deadline)\n throw BrowserError.make({\n operation,\n reason: Reasons.Timeout.make({}),\n outcome: currentOutcome(),\n });\n };\n\n /**\n * The one decision, for every listener, of whether a fact is late: it arrived after this\n * operation ended (unless it is the end itself), after it was given up, or past its\n * deadline.\n */\n const late = (end = false) =>\n (!end && phase === \"Terminal\") ||\n controller.signal.aborted ||\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= deadline;\n\n const reportPhase = (\n reached: Exclude<NonNullable<Ticket[\"phase\"]>, \"Terminal\">,\n mutation: boolean,\n acknowledgement?: AcknowledgementFact,\n ) =>\n emit({\n _tag: \"Phase\",\n phase: reached,\n mutation,\n ...(acknowledgement === undefined ? {} : { acknowledgement }),\n late: late(),\n atMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n });\n\n const ticket: Ticket = {\n ...(options.performance === undefined\n ? {}\n : {\n performance: {\n ...options.performance,\n ...grantedPacing({\n clock,\n deadlineNanos: () => BigInt(Math.floor(deadline * 1_000_000)),\n signal: controller.signal,\n check,\n overBudget: () =>\n BrowserError.make({\n operation,\n reason: Reasons.TimingBudgetExceeded.make({}),\n outcome: currentOutcome(),\n }),\n }),\n },\n }),\n operationId,\n picture: (boundary) => emit({ _tag: \"Picture\", boundary }),\n recordInput: (receipt, keys) =>\n emit({ _tag: \"Input\", receipt, ...(keys === undefined ? {} : { keys }) }),\n recordScroll: (scrolled) =>\n emit({ _tag: \"Scroll\", facts: scrolled, generation, late: late() }),\n recordGlide: (glide) => emit({ _tag: \"Glide\", facts: glide }),\n recordSettled: (evidence, target) => emit({ _tag: \"Settled\", evidence, target }),\n ...(options.evidence?.target === undefined\n ? {}\n : { captureTarget: options.evidence.target }),\n retainNative: () =>\n admission.retainNative(lane, operation, nativeConnection, () => dispatched),\n signal: controller.signal,\n deadline,\n generation,\n remainingMillis: () =>\n Math.max(1, deadline - Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000),\n get dispatched() {\n return dispatched;\n },\n get outcome() {\n return currentOutcome();\n },\n get phase() {\n return phase;\n },\n get containment() {\n return containment;\n },\n check,\n dispatch() {\n check();\n if (!dispatched && options.mutation)\n invalidate(\n \"observation\",\n options.mutationScope?.() ?? \"all\",\n controller.signal,\n );\n dispatched = true;\n pending = true;\n phase = \"Dispatched\";\n const scope = options.targetScope?.() ?? options.mutationScope?.();\n\n unresolved.set(\n controller,\n scope !== undefined && scope !== \"all\" && scope !== \"none\"\n ? scope.pageId\n : undefined,\n );\n reportPhase(\"Dispatched\", true);\n },\n acknowledge(fact) {\n const mutation = pending;\n\n pending = false;\n if (\n dispatched &&\n !unknownDecided &&\n !controller.signal.aborted &&\n phase !== \"Terminal\"\n ) {\n // A burst of keys or scroll samples is input that landed, even before the action\n // completes; only focus or scroll-into-view preparation leaves the input unchanged.\n if (\n fact === undefined ||\n fact.logicalComplete ||\n (fact.subphase !== \"focus\" && fact.subphase !== \"scroll-into-view\")\n )\n inputAcknowledged = true;\n else if (mutation) preparationAcknowledged = true;\n }\n if (phase !== \"Terminal\") phase = \"Acknowledged\";\n if (!unknownDecided) unresolved.delete(controller);\n reportPhase(\"Acknowledged\", mutation, fact);\n changed();\n },\n followUp() {\n if (phase === \"Acknowledged\") {\n phase = \"FollowUp\";\n reportPhase(\"FollowUp\", false);\n }\n },\n };\n\n admitted = true;\n admittedTicket = ticket;\n reportPhase(\"Prepared\", false);\n\n // A revocation freezes the pending attempt synchronously, before a late native\n // acknowledgement can run and before the interrupted Effect resumes its handler.\n const freezeUnknown = () => {\n if (phase !== \"Terminal\" && pending) unknownDecided = true;\n };\n\n controller.signal.addEventListener(\"abort\", freezeUnknown, { once: true });\n\n // Dispatched work this admission gave up on, whose outcome no fence has decided yet.\n let abandoned = false;\n\n const abandon = () => {\n // The action timer can win the same instant as the independent lifetime timer.\n if (Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >= lifetimeDeadline)\n expire();\n controller.abort();\n if (pending || unknownDecided) {\n unknownDecided = true;\n if (state.generation === generation && state.phase === \"open\") abandoned = true;\n else {\n if (state.phase === \"paused\" || state.phase === \"acquiring\")\n fence(\"uncertain\", \"uncertain\");\n containment = { _tag: \"SessionFenced\", generation: state.generation };\n }\n }\n };\n\n const current = () => state.generation === generation && state.phase === \"open\";\n\n /**\n * Work given up after dispatch fences the owner, since nothing knows what it did or\n * whether more of it will land. An operation confined to one page it may close instead\n * closes that page: once the browser confirms it closed, nothing still bound for it can\n * land anywhere, and every other page keeps working. It is still never replayed.\n */\n const settle = Effect.uninterruptible(\n Effect.suspend(() => {\n if (!abandoned) return Effect.void;\n abandoned = false;\n // A policy pause already holds this page for an operator: closing it would discard\n // the page the operator must inspect, and its quarantine refuses all automation.\n if (current() && lane.pageId !== undefined && quarantined.has(lane.pageId)) {\n containment = { _tag: \"PagePaused\", pageId: lane.pageId, generation };\n unresolved.delete(controller);\n changed();\n\n return Effect.void;\n }\n const page = current() ? options.contain?.() : undefined;\n\n return contain(page, generation).pipe(\n Effect.tap((result) =>\n Effect.sync(() => {\n containment = result;\n if (result._tag === \"PageClosed\") unresolved.delete(controller);\n }),\n ),\n );\n }),\n );\n\n return yield* within(body(ticket), ticket.deadline, () => {\n abandon();\n\n return BrowserError.make({\n operation,\n reason: Reasons.Timeout.make({}),\n outcome: currentOutcome(),\n });\n }).pipe(\n Effect.tap(() =>\n options.verifyAfter === false\n ? Effect.void\n : Effect.try({\n try: check,\n catch: (error) =>\n Schema.is(BrowserError)(error)\n ? error\n : BrowserError.make({\n operation,\n reason: Reasons.Stale.make({}),\n outcome: currentOutcome(),\n }),\n }),\n ),\n Effect.catch((error): Effect.Effect<never, E | BrowserError> => {\n const outcome = currentOutcome(\n Schema.is(BrowserError)(error) ? error.outcome : \"undispatched\",\n );\n\n if (pending || unknownDecided) abandon();\n\n // The permit adds dispatch evidence only to browser-operation errors. Typed\n // initialization/consumer failures retain their identity and original family.\n return settle.pipe(\n Effect.andThen(\n Effect.suspend((): Effect.Effect<never, E | BrowserError> =>\n Schema.is(BrowserError)(error)\n ? Effect.fail(\n BrowserError.make({\n operation,\n reason: error.reason,\n outcome,\n containment:\n containment._tag === \"NotRequired\"\n ? (error.containment ?? containment)\n : containment,\n }),\n )\n : Effect.fail(error),\n ),\n ),\n );\n }),\n Effect.onExit((exit) =>\n Exit.isFailure(exit) && containment._tag === \"NotRequired\"\n ? Effect.sync(abandon).pipe(Effect.andThen(settle))\n : Effect.void,\n ),\n Effect.tap(() =>\n Effect.sync(() => {\n unresolved.delete(controller);\n changed();\n }),\n ),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n const failure = Exit.isFailure(exit)\n ? Cause.findErrorOption(exit.cause)\n : Option.none();\n\n const error =\n Option.isSome(failure) && Schema.is(BrowserError)(failure.value)\n ? failure.value\n : undefined;\n\n emit({\n _tag: \"Finished\",\n kind: Exit.isSuccess(exit)\n ? \"Completed\"\n : Cause.hasInterrupts(exit.cause)\n ? \"Cancelled\"\n : \"Failed\",\n outcome: currentOutcome(error?.outcome),\n ...(error === undefined ? {} : { error }),\n containment:\n containment._tag === \"NotRequired\"\n ? (error?.containment ?? containment)\n : containment,\n });\n }),\n ),\n Effect.ensuring(\n Effect.sync(() => {\n phase = \"Terminal\";\n emit({\n _tag: \"Terminal\",\n outcome: currentOutcome(),\n containment,\n late: late(true),\n atMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n });\n controller.signal.removeEventListener(\"abort\", freezeUnknown);\n controller.abort();\n admission.deactivate(lane, controller);\n }),\n ),\n );\n });\n\n const checkAdmission = Effect.suspend(() => {\n const refused = refusal(options);\n\n return refused === undefined\n ? (options.preflight ?? Effect.void)\n : Effect.fail(\n BrowserError.make({ operation, reason: refused, outcome: \"undispatched\" }),\n );\n });\n\n return checkAdmission.pipe(\n Effect.andThen(\n Effect.uninterruptibleMask((restore) =>\n Effect.suspend(() =>\n restore(\n within(\n admission.acquire(\n lane,\n pending,\n options.recovery === true &&\n (operation !== \"navigate-stop\" || options.waitUntil === undefined)\n ? 0\n : queueMillis,\n ),\n lane.holder === pending.token || queueMillis <= 0\n ? deadline\n : Math.min(queueDeadline, deadline),\n () =>\n BrowserError.make({\n operation,\n reason:\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 >=\n lifetimeDeadline\n ? Reasons.Expired.make({})\n : deadline <= queueDeadline\n ? Reasons.Timeout.make({})\n : Reasons.QueueExpired.make({}),\n outcome: \"undispatched\",\n }),\n ),\n ).pipe(\n Effect.onError(() => Effect.sync(() => admission.cancel(lane, pending))),\n Effect.andThen(restore(work)),\n Effect.ensuring(Effect.sync(() => admission.release(lane, pending.token))),\n ),\n ),\n ),\n ),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (admitted) return;\n\n const failure = Exit.isFailure(exit)\n ? Cause.findErrorOption(exit.cause)\n : Option.none();\n\n const error =\n Option.isSome(failure) && Schema.is(BrowserError)(failure.value)\n ? failure.value\n : undefined;\n\n emit({\n _tag: \"Finished\",\n kind: Exit.isSuccess(exit)\n ? \"Completed\"\n : Cause.hasInterrupts(exit.cause)\n ? \"Cancelled\"\n : \"Failed\",\n outcome: error?.outcome ?? \"undispatched\",\n ...(error === undefined ? {} : { error }),\n containment: error?.containment ?? { _tag: \"NotRequired\" },\n });\n }),\n ),\n );\n }),\n ).pipe(\n Effect.onExit((exit) =>\n Effect.sync(() => admissionSpan?.end(exit, { \"browser.outcome\": \"undispatched\" })),\n ),\n Effect.onInterrupt(() =>\n Trace.annotate({ \"browser.outcome\": admittedTicket?.outcome ?? \"undispatched\" }),\n ),\n );\n }),\n ).pipe(\n Effect.provideService(Clock.Clock, clock),\n options.traced === false ? (effect) => effect : operationSpan(operation),\n );\n\n /** Lifecycle transitions are performed while holding guard's permit; close alone preempts it. */\n return {\n clock,\n /** The session's subscription to every operation it guards, such as its timeline's. */\n observeOperations: (subscribe: OperationListener) => {\n listener = subscribe;\n },\n observePhase: (observer: (phase: Phase) => void) => {\n observePhase = observer;\n },\n state,\n lifetimeDeadline,\n guard,\n refusal,\n chargeHostRead: (ticket: Ticket, operation: BrowserOperation) => {\n ticket.check();\n if (state.hostReads >= limits.maxHostReads)\n throw BrowserError.make({\n operation,\n reason: Reasons.Limit.make({\n dimension: \"host-reads\",\n maximum: limits.maxHostReads,\n observed: state.hostReads,\n }),\n outcome: \"undispatched\",\n });\n state.hostReads++;\n },\n pageAdmission: admission.page,\n /** A navigation stop's setup on its page's native capacity; see `Admission.beginStopSetup`. */\n beginStopSetup: admission.beginStopSetup,\n admissionSnapshot: admission.snapshot,\n admissionStatus: Effect.sync(admission.status),\n setConnection: (connection: object) => {\n nativeConnection = connection;\n },\n hasActive: (except?: AbortSignal) =>\n admission\n .lanes()\n .some(\n (lane) =>\n lane.holder !== undefined &&\n (except === undefined || lane.active?.controller.signal !== except),\n ),\n restorePageAdmission: (pageId: string) => {\n quarantined.delete(pageId);\n admission.restore(pageId);\n },\n revision: (pageId: string) => admission.lane(pageId)?.revision ?? state.revision,\n reserve,\n contain,\n pauseAdmission: () => {\n if (admissionBarrier !== undefined) return undefined;\n const token = {};\n\n admissionBarrier = token;\n admission.blockPending(Reasons.Busy.make({}));\n\n return token;\n },\n resumeAdmission: (token: object) => {\n if (admissionBarrier !== token) return false;\n admissionBarrier = undefined;\n\n return true;\n },\n /**\n * No admitted work can still change a page. Pure waits only read; the fence that follows a\n * drain refuses them, so they never hold one up.\n */\n drained: (except?: AbortSignal) =>\n admission.drained(\n except,\n (lane) => lane.pageId !== undefined && quarantined.has(lane.pageId),\n ) &&\n !nativeUncertainty &&\n unresolved.size === 0 &&\n admission.lanes().every((lane) => lane.reservation === undefined) &&\n policies.size === 0,\n /**\n * No admitted operation, no native work that can still change a page, and no started\n * navigation that is still loading is running. Unlike `drained`, an earlier unresolved\n * outcome does not prevent it.\n */\n idle: (except?: AbortSignal) =>\n admission.drained(\n except,\n (lane) => lane.pageId !== undefined && quarantined.has(lane.pageId),\n ) && admission.lanes().every((lane) => lane.reservation === undefined),\n /** Completes after the next settlement of admitted work, a policy or a fence. */\n nextChange: Effect.suspend(() => Deferred.await(change)),\n reserved: (key: string): boolean => admission.lane(key)?.reservation !== undefined,\n /** Whether a popup/dialog policy holds this page for an operator. */\n paused: (pageId: string): boolean => quarantined.has(pageId),\n get pausedPages(): number {\n return quarantined.size;\n },\n /**\n * A popup/dialog policy pause: the page's admitted work is revoked as for closure, but an\n * outcome it leaves unknown is held by the quarantine for the operator rather than closed.\n */\n pausePage: (pageId: string) => {\n quarantined.add(pageId);\n for (const lane of admission.lanes()) {\n if (lane.pageId !== pageId) continue;\n admission.revoke(lane, Reasons.Stale.make({}));\n const reservation = admission.takeReservation(lane);\n\n if (reservation !== undefined) unresolved.delete(reservation);\n reservation?.abort();\n }\n waitOn(pageId)?.cancel(Reasons.Stale.make({}));\n changed();\n },\n revokePage: (pageId: string, except?: AbortSignal) => {\n for (const lane of admission.lanes()) {\n if (lane.pageId !== pageId) continue;\n if (except === undefined || lane.active?.controller.signal !== except)\n admission.revoke(lane, Reasons.Stale.make({}));\n admission.takeReservation(lane)?.abort();\n }\n waitOn(pageId)?.cancel(Reasons.Stale.make({}));\n },\n retirePage: (pageId: string) => {\n const waiting = waitOn(pageId);\n\n quarantined.delete(pageId);\n waiting?.cancel(Reasons.Stale.make({}));\n waiting?.retire();\n admission.retirePage(pageId);\n for (const [token, page] of unresolved) if (page === pageId) unresolved.delete(token);\n changed();\n },\n beginWait,\n waitAvailable: (pageId: string) => waitOn(pageId) === undefined,\n waitPending: (pageId?: string) =>\n pageId === undefined\n ? [...waits()].some((waiting) => waiting.pending)\n : waitOn(pageId)?.pending === true,\n /** Positive retirement is specific to a connection, including a late retired predecessor. */\n retireWait: (connection: object) => {\n admission.retireConnection(connection);\n for (const waiting of waits()) {\n if (waiting.connection !== connection) continue;\n waiting.cancel(Reasons.Stale.make({}));\n waiting.retire();\n }\n },\n invalidate,\n fence,\n get reason() {\n return terminalReason ?? pauseReason;\n },\n transition,\n expire,\n terminate,\n policy,\n record,\n /** Only positive lifetime-source evidence may retire control lost to a connection fence. */\n retireControl: () => {\n for (const waiting of waits()) {\n waiting.cancel(Reasons.Stale.make({}));\n waiting.retire();\n }\n admission.retire();\n unresolved.clear();\n nativeUncertainty = false;\n policies.clear();\n changed();\n },\n status: Effect.sync(() => {\n const status = SessionStatus.make({\n phase: state.phase,\n reason: terminalReason ?? pauseReason ?? policies.values().next().value?.reason ?? null,\n generation: state.generation,\n busy:\n admission\n .lanes()\n .some((lane) => lane.holder !== undefined || lane.native.work.size > 0) ||\n policies.size > 0 ||\n waits().size > 0,\n unresolvedDispatch: nativeUncertainty || unresolved.size > 0,\n actions: { used: state.actions, maximum: limits.maxActions },\n });\n\n // Schema construction owns the nested record; freeze the produced snapshot, not its input.\n Object.freeze(status.actions);\n\n return Object.freeze(status);\n }),\n diagnostics: Effect.sync(() => {\n const snapshot = BrowserDiagnostics.make({\n records: [...records],\n total,\n dropped,\n truncated: dropped > 0,\n });\n\n // Schema construction owns its array; freeze the produced snapshot, not merely its input.\n for (const record of snapshot.records) Object.freeze(record);\n Object.freeze(snapshot.records);\n\n return Object.freeze(snapshot);\n }),\n onInvalidate(\n hook: (reason: Invalidation, scope: ObservationScope, origin?: AbortSignal) => void,\n ): () => void {\n hooks.add(hook);\n\n return () => {\n hooks.delete(hook);\n };\n },\n };\n});\n\nexport type Owner = Effect.Success<ReturnType<typeof makeOwner>>;\n\n/** Without a native answer, whether the step was sent is all the owner knows about it. */\nconst unsettled = (ticket: Ticket, error: unknown): Pick<BrowserError, \"reason\" | \"outcome\"> => ({\n reason: providerReason(error),\n outcome: ticket.outcome ?? (ticket.dispatched ? \"unknown\" : \"undispatched\"),\n});\n\n/**\n * The one place a native step becomes a public error: whatever the driver raised, the caller\n * sees the operation it asked for.\n */\nexport const native = <A>(operation: BrowserOperation, ticket: Ticket, body: () => Promise<A>) =>\n Effect.callback<A, BrowserError>((resume) => {\n let done = false;\n let retire: (() => void) | undefined;\n\n const cleanup = () => {\n done = true;\n ticket.signal.removeEventListener(\"abort\", abort);\n };\n\n const abort = () => {\n if (done) return;\n cleanup();\n resume(\n Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Stale.make({}),\n outcome: ticket.outcome ?? (ticket.dispatched ? \"unknown\" : \"undispatched\"),\n }),\n ),\n );\n };\n\n ticket.signal.addEventListener(\"abort\", abort, { once: true });\n try {\n ticket.check();\n retire = ticket.retainNative?.();\n // Observe both branches even after the waiter exits. Cancellation does not undo native work.\n void body().then(\n (value) => {\n retire?.();\n if (!done) {\n cleanup();\n resume(Effect.succeed(value));\n }\n },\n (error: unknown) => {\n retire?.();\n if (!done) {\n cleanup();\n resume(\n Schema.is(NativeEffectFailure)(error)\n ? Effect.failCause(error.cause)\n : Effect.fail(publicError(error, operation, unsettled(ticket, error))),\n );\n }\n },\n );\n } catch (error) {\n retire?.();\n cleanup();\n resume(\n Schema.is(NativeEffectFailure)(error)\n ? Effect.failCause(error.cause)\n : Effect.fail(publicError(error, operation, unsettled(ticket, error))),\n );\n }\n\n return Effect.sync(cleanup);\n }).pipe(\n Effect.onInterrupt(() =>\n Trace.annotate({ \"browser.outcome\": ticket.dispatched ? \"unknown\" : \"undispatched\" }),\n ),\n Trace.span(`Browser.native.${operation}`, { attributes: { \"browser.operation\": operation } }),\n );\n","import {\n Cause,\n Clock,\n Deferred,\n Duration,\n Effect,\n Exit,\n Fiber,\n Option,\n Predicate,\n Schema,\n type Scope,\n} from \"effect\";\n\nimport type { ElementAdmission } from \"../../Browser.ts\";\nimport {\n type Checkpoint,\n type CheckpointOptions,\n InputReceipt,\n type ObservedElement,\n} from \"../../BrowserData.ts\";\nimport { BrowserError, Reasons, type BrowserOutcome, type Containment } from \"../../Errors.ts\";\nimport { type RunOperation, type RunOptions, StepFailed } from \"../../Plan.ts\";\nimport type {\n AttemptResult,\n AttemptSnapshot,\n DescriptorCapture,\n InputBindings,\n LivePlan,\n PhaseEvidence,\n Ran,\n RanStep,\n RunPhase,\n RunReceipt,\n RunTiming,\n Performed,\n PerformanceEvidence,\n Step,\n StepAttempt,\n} from \"../../PlanData.ts\";\nimport type { Correlation, Payload } from \"../../TimelineData.ts\";\nimport type { DescriptorSample, ResolvedElement } from \"./Descriptor.ts\";\nimport { type OperationEvent, type ScrollFacts, strongestOutcome } from \"./Owner.ts\";\nimport { prepare, type PerformancePlan } from \"./Performance.ts\";\nimport { capture, inputSlots, pathKey, type TargetSample, validateInputs } from \"./Recording.ts\";\nimport type { ExecutionOptions } from \"./Session.ts\";\n\nexport interface TargetBinding {\n readonly value: ObservedElement | ResolvedElement | string;\n readonly path: ReadonlyArray<string>;\n readonly sample?: DescriptorSample;\n}\n\nexport interface StepExecution {\n readonly options: ExecutionOptions;\n readonly policy?: ElementAdmission;\n readonly checkpoint?: CheckpointOptions;\n readonly phase: (phase: RunPhase, fieldIndex?: number) => void;\n readonly targets: (bindings: ReadonlyArray<TargetBinding>) => void;\n /** Partial form/input evidence survives a later failed verification, submit or postcondition. */\n readonly retainReceipt: (receipt: RunReceipt) => void;\n readonly performance?: PerformancePlan;\n}\n\nexport interface ValidatedRunOptions extends RunOptions {\n readonly style?: \"plain\" | Performed;\n readonly withinMillis?: number;\n readonly queueMillis?: number;\n}\n\nexport interface StepSuccess {\n readonly receipt: RunReceipt;\n readonly checkpoint?: Checkpoint;\n}\n\nexport interface PlanExecutionOptions {\n readonly clock: Clock.Clock;\n readonly validate: Effect.Effect<void, BrowserError>;\n readonly lifetimeDeadline: number;\n readonly actionTimeoutMillis: number;\n readonly newId: Effect.Effect<string>;\n readonly newSeed?: Effect.Effect<number>;\n /** Captured at run execution and retained with its original domain, never an evidence owner. */\n readonly publish?: () => {\n readonly append: (correlation: Correlation, event: Payload) => void;\n readonly release: () => void;\n };\n /** Completes once the issuing Page or its owner can no longer run; a scheduled start ends then. */\n readonly retired?: Effect.Effect<void>;\n /** This bounds registrations, never takes a Page mutation permit for the whole walk. */\n readonly reserve: Effect.Effect<() => void, BrowserError>;\n readonly executeStep: (\n step: Step,\n inputs: InputBindings,\n context: StepExecution,\n ) => Effect.Effect<StepSuccess, BrowserError>;\n}\n\nconst maximumPhases = 1024;\n\n/** Only bounded decoded data is frozen. Original Effect Causes are retained without traversal. */\nconst freezeData = <A>(value: A): A => {\n const seen = new WeakSet<object>();\n\n const freeze = (input: unknown): void => {\n if (!Predicate.isObjectKeyword(input) || seen.has(input) || Object.isFrozen(input)) return;\n seen.add(input);\n for (const child of Object.values(input)) freeze(child);\n Object.freeze(input);\n };\n\n freeze(value);\n\n return value;\n};\n\ninterface AttemptState {\n readonly id: string;\n readonly step: Step;\n readonly phases: Array<PhaseEvidence>;\n readonly samples: Map<string, TargetSample>;\n phase: RunPhase;\n fieldIndex?: number;\n overflow: boolean;\n completed: boolean;\n /** The strongest outcome the owner classified for any operation this attempt admitted. */\n reached: BrowserOutcome;\n capture?: DescriptorCapture;\n receipt?: RunReceipt;\n outcome?: BrowserOutcome;\n error?: BrowserError;\n cause?: Cause.Cause<BrowserError>;\n result?: AttemptResult;\n containment: Containment;\n performance?: PerformanceEvidence;\n}\n\nconst attemptSnapshot = (state: AttemptState): StepAttempt =>\n Object.freeze({\n id: state.id,\n stepId: state.step.id,\n sourceStep: state.step,\n action: state.step.action._tag,\n phase: state.phase,\n phases: Object.freeze([...state.phases]),\n ...(state.capture === undefined ? {} : { capture: state.capture }),\n ...(state.receipt === undefined ? {} : { receipt: state.receipt }),\n ...(state.outcome === undefined ? {} : { outcome: state.outcome }),\n ...(state.error === undefined ? {} : { error: state.error }),\n ...(state.cause === undefined ? {} : { cause: state.cause }),\n ...(state.result === undefined ? {} : { result: state.result }),\n containment: state.containment,\n completed: state.completed,\n ...(state.performance === undefined ? {} : { performance: state.performance }),\n });\n\n/** One classifier: the owner's, per admitted operation, never weakened by a later failure. */\nconst outcome = (state: AttemptState, error?: BrowserError): BrowserOutcome =>\n strongestOutcome(state.reached, error?.outcome ?? \"undispatched\");\n\nconst result = (value: BrowserOutcome, failed: boolean): AttemptResult => {\n switch (value) {\n case \"unknown\":\n return { _tag: \"Unknown\", outcome: value };\n case \"performed\":\n return {\n _tag: failed ? \"AcknowledgedWithPostconditionFailure\" : \"Acknowledged\",\n outcome: value,\n };\n case \"undispatched\":\n return { _tag: failed ? \"Refused\" : \"Acknowledged\", outcome: value };\n case \"rejected\":\n return { _tag: \"Refused\", outcome: value };\n }\n};\n\nconst preparationFailure = (error: BrowserError): StepFailed =>\n new StepFailed({ stage: \"PreparationFailed\", completed: [], error });\n\n/** The original scoped owner is supplied once; a RunOperation contains no reconnecting facade. */\nexport const makePlanExecution = (configuration: PlanExecutionOptions) => {\n const now = (): number => Number(configuration.clock.monotonicTimeNanosUnsafe()) / 1_000_000;\n\n const start = (\n plan: LivePlan,\n options: ValidatedRunOptions = {},\n ): Effect.Effect<RunOperation, StepFailed, Scope.Scope> =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const requestedMonotonicNanos = configuration.clock.monotonicTimeNanosUnsafe();\n const intendedMonotonicNanos = options.startAt ?? requestedMonotonicNanos;\n const began = Number(intendedMonotonicNanos) / 1_000_000;\n\n const runDeadline = Math.min(\n configuration.lifetimeDeadline,\n options.withinMillis === undefined\n ? Number.POSITIVE_INFINITY\n : began + options.withinMillis,\n );\n\n const last =\n options.through === undefined\n ? plan.steps.length - 1\n : plan.steps.findIndex((step) => step.id === options.through);\n\n if (last < 0)\n return yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Malformed.make({ path: \"through\" }),\n outcome: \"undispatched\",\n }),\n );\n const inputs = Object.freeze({ ...options.inputs });\n\n yield* restore(configuration.validate).pipe(Effect.mapError(preparationFailure));\n yield* restore(validateInputs(plan, inputs)).pipe(Effect.mapError(preparationFailure));\n if (!Number.isFinite(began) || !Number.isFinite(runDeadline))\n return yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Configuration.make({ path: \"startAt\" }),\n outcome: \"undispatched\",\n }),\n );\n if (began >= runDeadline || now() >= runDeadline)\n return yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.ScheduleMissed.make({}),\n outcome: \"undispatched\",\n }),\n );\n\n const style =\n options.style === undefined || options.style === \"plain\" ? undefined : options.style;\n\n const seed =\n style === undefined\n ? undefined\n : (style.seed ??\n (configuration.newSeed === undefined\n ? yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Configuration.make({ path: \"style.seed\" }),\n outcome: \"undispatched\",\n }),\n )\n : yield* restore(configuration.newSeed)));\n\n const runId = yield* restore(configuration.newId);\n const ids = yield* restore(Effect.forEach(plan.steps, () => configuration.newId));\n const release = yield* configuration.reserve.pipe(Effect.mapError(preparationFailure));\n // Evidence publication is taken when the walk starts, so a scheduled start retains no\n // journal while it waits and never holds back its domain's terminal.\n let publication: ReturnType<NonNullable<typeof configuration.publish>> | undefined;\n let publish: ((correlation: Correlation, event: Payload) => void) | undefined;\n let released = false;\n\n const releaseAll = () => {\n if (released) return;\n released = true;\n release();\n publication?.release();\n };\n\n const releaseOnce = Effect.sync(releaseAll);\n\n yield* Effect.addFinalizer(() => releaseOnce);\n freezeData(plan);\n const slots = inputSlots(plan);\n const completed: Array<RanStep> = [];\n const attempts: Array<AttemptState> = [];\n const completion = yield* Deferred.make<Ran, StepFailed>();\n let terminal = false;\n\n let timing: RunTiming = Object.freeze({\n requestedMonotonicNanos,\n intendedMonotonicNanos,\n startedMonotonicNanos: null,\n deadlineMonotonicNanos: BigInt(Math.floor(runDeadline * 1_000_000)),\n latenessNanos: null,\n ...(seed === undefined ? {} : { seed }),\n });\n\n const snapshot = (): AttemptSnapshot =>\n Object.freeze({\n runId,\n attempts: Object.freeze(attempts.map(attemptSnapshot)),\n completed: Object.freeze([...completed]),\n terminal,\n timing,\n });\n\n const worker = Effect.gen(function* () {\n let waited = false;\n\n // Timers have millisecond resolution and can wake before a fractional instant, so the\n // wait repeats until the owner's own monotonic clock has reached the intended start.\n while (configuration.clock.monotonicTimeNanosUnsafe() < intendedMonotonicNanos) {\n waited = true;\n\n const remainingNanos =\n intendedMonotonicNanos - configuration.clock.monotonicTimeNanosUnsafe();\n\n const retired = yield* (configuration.retired ?? Effect.never).pipe(\n Effect.timeoutOption(Duration.millis(Math.ceil(Number(remainingNanos) / 1_000_000))),\n );\n\n // The issuing Page or owner ended before the start: refuse with its current reason.\n if (Option.isSome(retired))\n return yield* configuration.validate.pipe(\n Effect.andThen(\n Effect.fail(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n }),\n ),\n ),\n Effect.mapError(preparationFailure),\n );\n }\n if (waited) yield* configuration.validate.pipe(Effect.mapError(preparationFailure));\n if (!released) {\n publication = configuration.publish?.();\n publish = publication?.append;\n }\n const startedMonotonicNanos = configuration.clock.monotonicTimeNanosUnsafe();\n\n timing = Object.freeze({\n ...timing,\n startedMonotonicNanos,\n latenessNanos:\n startedMonotonicNanos > intendedMonotonicNanos\n ? startedMonotonicNanos - intendedMonotonicNanos\n : 0n,\n });\n if (now() >= runDeadline)\n return yield* preparationFailure(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.ScheduleMissed.make({}),\n outcome: \"undispatched\",\n }),\n );\n for (let index = 0; index <= last; index++) {\n const step = plan.steps[index];\n const attemptId = ids[index];\n\n // Both arrays are bounded, nonempty and correlated by ingress/preparation.\n if (step === undefined || attemptId === undefined)\n return yield* Effect.die(\n new Error(\"Validated plan/attempt inventory lost alignment\"),\n );\n const stepBegan = now();\n\n const stepDeadline = Math.min(\n runDeadline,\n stepBegan +\n Math.min(\n options.timeoutMillis ?? configuration.actionTimeoutMillis,\n configuration.actionTimeoutMillis,\n ),\n );\n\n const queueMillis =\n options.queueMillis ??\n (options.admission?.queue === undefined\n ? undefined\n : Duration.toMillis(Duration.fromInputUnsafe(options.admission.queue)));\n\n const queueDeadline =\n queueMillis === undefined\n ? undefined\n : Math.min(stepDeadline, stepBegan + queueMillis);\n\n const state: AttemptState = {\n id: attemptId,\n step,\n phase: \"Preparation\",\n phases: [],\n samples: new Map(),\n overflow: false,\n completed: false,\n reached: \"undispatched\",\n containment: { _tag: \"NotRequired\" },\n };\n\n attempts.push(state);\n\n const correlation = (): Correlation => ({\n runId,\n stepId: step.id,\n attemptId,\n ...(state.fieldIndex === undefined ? {} : { fieldIndex: state.fieldIndex }),\n });\n\n publish?.(correlation(), { _tag: \"Planned\", action: step.action._tag });\n\n const performance =\n style === undefined || seed === undefined\n ? undefined\n : yield* prepare(style, seed, step.id);\n\n if (performance !== undefined)\n state.performance = Object.freeze({\n seed: performance.seed,\n profile: performance.profile,\n });\n\n const targetBindings = new Map<\n ObservedElement | ResolvedElement | string,\n Array<ReadonlyArray<string>>\n >();\n\n const retainedInputs = new WeakSet<InputReceipt>();\n const checkedSamples = new Set<string>();\n // Bursts fold only within one admitted operation, named by its owner's operation id.\n let lastDispatchOperation: string | undefined;\n let lastBurstOperation: string | undefined;\n\n const append = (evidence: PhaseEvidence): void => {\n if (state.phases.length >= maximumPhases) {\n state.overflow = true;\n if (state.completed)\n state.capture = freezeData({\n _tag: \"Incomplete\",\n facts: { path: [] },\n reason: \"EvidenceLimit\",\n });\n\n return;\n }\n state.phases.push(Object.freeze(evidence));\n };\n\n const appendPhase = (evidence: PhaseEvidence, operationId: string): void => {\n if (evidence.phase === \"Dispatched\") lastDispatchOperation = operationId;\n const fact = evidence.acknowledgement;\n\n if (\n evidence.phase !== \"Acknowledged\" ||\n fact === undefined ||\n fact.logicalComplete ||\n (fact.subphase !== \"key-burst\" && fact.subphase !== \"scroll-burst\") ||\n lastDispatchOperation !== operationId\n ) {\n if (evidence.phase !== \"Dispatched\") lastBurstOperation = undefined;\n append(evidence);\n\n return;\n }\n let start = state.phases.length;\n\n while (start > 0) {\n const previous = state.phases[start - 1];\n\n if (\n previous?.phase !== \"Dispatched\" ||\n previous.operation !== evidence.operation ||\n previous.fieldIndex !== evidence.fieldIndex ||\n previous.late !== evidence.late\n )\n break;\n start--;\n }\n const dispatched = state.phases[start];\n\n if (dispatched === undefined) {\n lastBurstOperation = undefined;\n append(evidence);\n\n return;\n }\n const dispatches = state.phases.length - start;\n const previous = state.phases[start - 1];\n\n const combine =\n lastBurstOperation === operationId &&\n previous?.phase === \"Acknowledged\" &&\n previous.burst?.subphase === fact.subphase &&\n previous.operation === evidence.operation &&\n previous.fieldIndex === evidence.fieldIndex &&\n previous.late === evidence.late;\n\n state.phases.splice(start);\n\n const burst = Object.freeze({\n subphase: fact.subphase,\n dispatches: dispatches + (combine ? (previous.burst?.dispatches ?? 0) : 0),\n acknowledgements: 1 + (combine ? (previous.burst?.acknowledgements ?? 0) : 0),\n firstDispatchedMonotonicNanos: combine\n ? (previous.burst?.firstDispatchedMonotonicNanos ?? dispatched.atMonotonicNanos)\n : dispatched.atMonotonicNanos,\n lastAcknowledgedMonotonicNanos: evidence.atMonotonicNanos,\n });\n\n if (combine) {\n state.phases[start - 1] = Object.freeze({ ...previous, ...evidence, burst });\n } else append({ ...evidence, burst });\n lastBurstOperation = operationId;\n };\n\n const retainScroll = (facts: ScrollFacts, generation: number, late: boolean): void => {\n const scroll: NonNullable<PhaseEvidence[\"scroll\"]> = Object.freeze({\n target: Object.freeze({\n generation,\n pageId: facts.target.pageId,\n frameId: facts.target.frameId,\n }),\n startedMonotonicNanos: facts.startedMonotonicNanos,\n completedMonotonicNanos: facts.completedMonotonicNanos,\n qualification: facts.qualification ?? \"native-call-interval\",\n ...(facts.x === undefined || facts.y === undefined\n ? {}\n : { delta: Object.freeze({ x: facts.x, y: facts.y }) }),\n });\n\n const index = state.phases.length - 1;\n const previous = state.phases[index];\n\n if (\n !late &&\n previous?.phase === \"Acknowledged\" &&\n !previous.late &&\n previous.operation === state.phase &&\n previous.fieldIndex === state.fieldIndex\n ) {\n const original = previous.scroll;\n\n const delta =\n original?.delta !== undefined && scroll.delta !== undefined\n ? Object.freeze({\n x: original.delta.x + scroll.delta.x,\n y: original.delta.y + scroll.delta.y,\n })\n : scroll.delta;\n\n state.phases[index] = Object.freeze({\n ...previous,\n scroll:\n original === undefined\n ? scroll\n : Object.freeze({\n ...scroll,\n startedMonotonicNanos: original.startedMonotonicNanos,\n ...(delta === undefined ? {} : { delta }),\n }),\n });\n\n return;\n }\n lastBurstOperation = undefined;\n append({\n phase: \"SubphaseReceipt\",\n operation: state.phase,\n atMonotonicNanos: facts.completedMonotonicNanos,\n late,\n scroll,\n ...(state.fieldIndex === undefined ? {} : { fieldIndex: state.fieldIndex }),\n });\n };\n\n const retainInput = (\n input: InputReceipt,\n operation: RunPhase,\n fieldIndex?: number,\n ): void => {\n if (retainedInputs.has(input)) return;\n retainedInputs.add(input);\n const receipt = freezeData(input);\n\n for (let index = state.phases.length - 1; index >= 0; index--) {\n const evidence = state.phases[index];\n\n if (\n evidence?.phase === \"Acknowledged\" &&\n !evidence.late &&\n evidence.operation === operation &&\n evidence.fieldIndex === fieldIndex &&\n evidence.input === undefined &&\n evidence.atMonotonicNanos >= receipt.startedMonotonicNanos &&\n evidence.atMonotonicNanos <= receipt.completedMonotonicNanos\n ) {\n state.phases[index] = Object.freeze({ ...evidence, input: receipt });\n\n return;\n }\n }\n append({\n phase: \"InputReceipt\",\n operation,\n atMonotonicNanos: receipt.completedMonotonicNanos,\n late: state.completed,\n input: receipt,\n ...(fieldIndex === undefined ? {} : { fieldIndex }),\n });\n };\n\n const retainReceipt = (receipt: RunReceipt): void => {\n if (state.completed) return;\n state.receipt = freezeData(receipt);\n if (Schema.is(InputReceipt)(receipt)) retainInput(receipt, \"Input\");\n else if (receipt !== undefined) {\n if (\"input\" in receipt && receipt.input !== undefined)\n retainInput(receipt.input, \"Input\");\n if (\"fields\" in receipt)\n receipt.fields.forEach((field, index) => {\n if (field.input !== undefined) retainInput(field.input, \"Field\", index);\n });\n if (\"submitInput\" in receipt && receipt.submitInput !== undefined)\n retainInput(receipt.submitInput, \"Submit\");\n }\n };\n\n const context: StepExecution = {\n ...(performance === undefined ? {} : { performance }),\n ...(options.policy === undefined ? {} : { policy: options.policy }),\n ...(options.checkpoint === undefined\n ? {}\n : { checkpoint: freezeData({ ...options.checkpoint }) }),\n phase: (phase, fieldIndex) => {\n if (state.completed) return;\n state.phase = phase;\n state.fieldIndex = fieldIndex;\n },\n targets: (bindings) => {\n if (state.completed) return;\n for (const binding of bindings) {\n const paths = targetBindings.get(binding.value) ?? [];\n\n paths.push(binding.path);\n targetBindings.set(binding.value, paths);\n const key = pathKey(binding.path);\n\n if (binding.sample !== undefined && !state.samples.has(key))\n state.samples.set(key, { path: binding.path, sample: binding.sample });\n }\n },\n retainReceipt,\n options: {\n ...(options.timeoutMillis === undefined\n ? {}\n : { timeoutMillis: options.timeoutMillis }),\n ...(options.admission === undefined ? {} : { admission: options.admission }),\n operationDeadline: stepDeadline,\n ...(queueDeadline === undefined ? {} : { queueDeadline }),\n evidence: {\n correlation,\n // Each admitted operation's facts, with the owner's lateness; evidence that\n // arrives after this attempt completed is late for the attempt as well.\n listener:\n ({ operationId }) =>\n (event: OperationEvent) => {\n switch (event._tag) {\n case \"Phase\":\n case \"Terminal\":\n appendPhase(\n {\n phase: event._tag === \"Terminal\" ? \"Terminal\" : event.phase,\n operation: state.phase,\n atMonotonicNanos: event.atMonotonicNanos,\n late: state.completed || event.late,\n ...(state.fieldIndex === undefined\n ? {}\n : { fieldIndex: state.fieldIndex }),\n ...(event._tag === \"Terminal\" || event.acknowledgement === undefined\n ? {}\n : { acknowledgement: Object.freeze({ ...event.acknowledgement }) }),\n },\n operationId,\n );\n if (event._tag === \"Terminal\") {\n if (!state.completed)\n state.reached = strongestOutcome(state.reached, event.outcome);\n if (event.containment._tag !== \"NotRequired\")\n state.containment = Object.freeze({ ...event.containment });\n }\n\n return;\n case \"Scroll\":\n retainScroll(\n event.facts,\n event.generation,\n state.completed || event.late,\n );\n\n return;\n // Pictures, input receipts, glides, settling and the operation's\n // own summary reach the plan through its receipts, not as phases.\n case \"Picture\":\n case \"Input\":\n case \"Glide\":\n case \"Settled\":\n case \"Finished\":\n return;\n }\n },\n target: (target, sample) => {\n if (state.completed) return;\n for (const path of targetBindings.get(target) ?? []) {\n if (\n state.fieldIndex !== undefined &&\n path[0] === \"fields\" &&\n path[1] !== String(state.fieldIndex)\n )\n continue;\n const key = pathKey(path);\n\n if (!checkedSamples.has(key)) {\n state.samples.set(key, {\n path,\n ...(sample === undefined ? {} : { sample }),\n });\n checkedSamples.add(key);\n }\n }\n },\n },\n },\n };\n\n const effect =\n stepDeadline <= now()\n ? Effect.fail(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n }),\n )\n : configuration.executeStep(step, inputs, context).pipe(\n Effect.flatMap((success) => {\n if (\n success.receipt !== undefined &&\n \"stopped\" in success.receipt &&\n success.receipt.stopped !== undefined\n ) {\n retainReceipt(success.receipt);\n\n return Effect.fail(success.receipt.stopped.error);\n }\n\n return Effect.succeed(success);\n }),\n );\n\n const success = yield* effect.pipe(\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (Exit.isSuccess(exit)) retainReceipt(exit.value.receipt);\n else {\n state.cause = exit.cause;\n const error = Cause.findErrorOption(exit.cause);\n\n if (Option.isSome(error)) {\n state.error = error.value;\n state.containment = error.value.containment ?? state.containment;\n }\n }\n }).pipe(\n Effect.andThen(\n Effect.suspend(() => capture(step, state.samples, slots, state.overflow)),\n ),\n Effect.map((captured) => {\n state.capture = freezeData(captured);\n state.outcome = outcome(state, state.error);\n state.result = result(state.outcome, Exit.isFailure(exit));\n state.completed = true;\n if (Exit.isFailure(exit))\n publish?.(\n correlation(),\n Cause.hasInterrupts(exit.cause)\n ? { _tag: \"Cancelled\", outcome: state.outcome }\n : {\n _tag: \"Failed\",\n operation: \"run\",\n reason: state.error?.reason._tag ?? \"Failed\",\n outcome: state.outcome,\n },\n );\n }),\n ),\n ),\n Effect.mapError(\n (error) =>\n new StepFailed({\n stage: \"AttemptFailed\",\n stepId: step.id,\n completed: Object.freeze([...completed]),\n attempt: attemptSnapshot(state),\n error,\n }),\n ),\n );\n\n if (state.outcome === \"unknown\")\n return yield* new StepFailed({\n stage: \"AttemptFailed\",\n stepId: step.id,\n completed: Object.freeze([...completed]),\n attempt: attemptSnapshot(state),\n error: BrowserError.make({\n operation: \"run\",\n reason: Reasons.Interrupted.make({}),\n outcome: \"unknown\",\n containment: state.containment,\n }),\n });\n const captured = state.capture;\n\n if (captured === undefined)\n return yield* Effect.die(new Error(\"Terminal plan attempt lost capture evidence\"));\n completed.push(\n Object.freeze({\n id: step.id,\n sourceStep: step,\n receipt: success.receipt,\n attempt: attemptSnapshot(state),\n recorded: captured,\n ...(step.expect === undefined ? {} : { expect: step.expect }),\n resolution: step.resolution,\n ...(success.checkpoint === undefined\n ? {}\n : { checkpoint: freezeData(success.checkpoint) }),\n ...(step.action._tag === \"Wait\" &&\n step.action.mode._tag === \"Settled\" &&\n success.receipt !== undefined &&\n \"signals\" in success.receipt\n ? { settled: success.receipt }\n : {}),\n }),\n );\n }\n\n const next = plan.steps[last + 1];\n\n return freezeData({\n runId,\n version: 1 as const,\n timing,\n steps: Object.freeze([...completed]),\n completion:\n options.through === undefined\n ? { _tag: \"Complete\" as const }\n : {\n _tag: \"Through\" as const,\n through: options.through,\n next: next === undefined ? null : { index: last + 1, stepId: next.id },\n },\n });\n });\n\n const fiber = yield* worker.pipe(\n Effect.forkScoped({ startImmediately: false, uninterruptible: false }),\n );\n\n // Fiber observers cover interruption before the deferred worker evaluates any onExit.\n // Capacity and publication are released before a joined caller can resume.\n yield* Effect.sync(() => {\n fiber.addObserver((exit) => {\n releaseAll();\n terminal = true;\n Deferred.doneUnsafe(completion, exit);\n });\n });\n\n return Object.freeze({\n id: runId,\n attempts: Effect.sync(snapshot),\n completed: Deferred.await(completion),\n cancel: Fiber.interrupt(fiber),\n });\n }),\n ).pipe(Effect.provideService(Clock.Clock, configuration.clock));\n\n return {\n start,\n run: (plan: LivePlan, options?: ValidatedRunOptions): Effect.Effect<Ran, StepFailed> =>\n Effect.scoped(start(plan, options).pipe(Effect.flatMap((operation) => operation.completed))),\n };\n};\n","import { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type { RunPhase, Step } from \"../../PlanData.ts\";\nimport type { ResolvedElement, ResolvedGroup } from \"./Descriptor.ts\";\nimport type { Driver, DriverTarget } from \"./Driver.ts\";\nimport type { Ticket } from \"./Owner.ts\";\nimport type { StepExecution } from \"./PlanExecution.ts\";\nimport { actionTargets } from \"./Recording.ts\";\n\n/**\n * A plan step's native preparation. Inside the step's first admitted operation, before that\n * operation's own command, the Promise driver checks the step's preconditions and resolves its\n * targets once; every later admitted operation of the step only reactivates the resolved group.\n */\nexport const makeStepPreparation = (options: {\n readonly step: Step;\n readonly target: DriverTarget;\n readonly context: StepExecution;\n /** Charges preconditions and resolution to the admitted operation they run inside. */\n readonly chargeHostRead: (ticket: Ticket, operation: BrowserOperation) => void;\n /** The step's phase and field, reported again once preparation has run. */\n readonly current: () => readonly [RunPhase, number | undefined];\n}) => {\n const { step, target, context, chargeHostRead } = options;\n const requests = actionTargets(step.action);\n let group: ResolvedGroup | undefined;\n let prepared = false;\n\n /** The element resolved for the step's `index`th target. */\n const element = (index: number): ResolvedElement => {\n const value = group?.elements[index];\n\n if (value === undefined)\n throw BrowserError.make({\n operation: \"run\",\n reason: Reasons.Incomplete.make({}),\n outcome: \"undispatched\",\n });\n\n return value;\n };\n\n const beforeNative = async (driver: Driver, ticket: Ticket) => {\n if (!prepared) {\n if (step.expect?.before !== undefined) {\n context.phase(\"Precondition\");\n chargeHostRead(ticket, \"run\");\n await driver.expectations(step.expect.before, ticket, target);\n }\n if (requests.length > 0) {\n context.phase(\"Resolution\");\n chargeHostRead(ticket, \"resolve\");\n group = await driver.resolveGroup(requests, ticket, target, step.resolution);\n context.targets(\n requests.map((request, index) => ({\n value: element(index),\n path: request.path,\n ...(group?.samples?.[index] === undefined ? {} : { sample: group.samples[index] }),\n })),\n );\n }\n prepared = true;\n }\n group?.activate(ticket);\n ticket.check();\n context.phase(...options.current());\n };\n\n /** Releases the resolved group's retained nodes once the step is over. */\n const release = () => group?.release() ?? Promise.resolve();\n\n return { requests, element, beforeNative, release };\n};\n","import { Effect, Schema } from \"effect\";\n\nimport {\n ActionResult,\n Checkpoint,\n FillFormResult,\n InputReceipt,\n type KeyModifier,\n NavigationResult,\n type WaitForElementRequest,\n} from \"../../BrowserData.ts\";\nimport { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type {\n ActionTarget,\n InputBindings,\n Precondition,\n RunPhase,\n RunReceipt,\n SettledEvidence,\n SettledOptions,\n Step,\n ValueSource,\n} from \"../../PlanData.ts\";\nimport type { ResolvedElement } from \"./Descriptor.ts\";\nimport type { DriverTarget } from \"./Driver.ts\";\nimport type { AdmissionPolicy } from \"./Observation.ts\";\nimport type { Ticket } from \"./Owner.ts\";\nimport type { StepExecution, StepSuccess } from \"./PlanExecution.ts\";\nimport type { NativePoint } from \"./Pointer.ts\";\nimport type { ExecutionOptions, FormOutcome, FormSettings, FormSteps, Reading } from \"./Session.ts\";\nimport { makeStepPreparation } from \"./StepPreparation.ts\";\n\ntype Resolved = () => ResolvedElement;\n\n/**\n * What one plan step may do on its issued page: the page's own operations, each admitted under its\n * operation's policy, plus the few a step needs on targets it resolved itself. Step semantics live\n * here; admission, readiness and containment stay with the session that implements this port.\n */\nexport interface StepControls {\n readonly operations: {\n readonly navigate: (\n url: string,\n timeoutMillis: number | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly click: (\n target: Resolved,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly hover: (\n target: Resolved,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n readonly fill: (\n target: Resolved,\n value: string,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly type: (\n text: string,\n into: Resolved | undefined,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n readonly press: (\n key: string,\n modifiers: ReadonlyArray<KeyModifier>,\n into: Resolved | undefined,\n policy: AdmissionPolicy | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n readonly scroll: (\n x: number,\n y: number,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly pointerMove: (\n to: NativePoint,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n readonly wheel: (\n deltaX: number,\n deltaY: number,\n at: NativePoint | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<object, BrowserError>;\n };\n readonly selectOption: (\n target: Resolved,\n options: () => ReadonlyArray<ResolvedElement>,\n policy: AdmissionPolicy | undefined,\n operationOptions: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n readonly settled: (\n settle: SettledOptions,\n options: ExecutionOptions,\n ) => Effect.Effect<SettledEvidence, BrowserError>;\n readonly fillForm: (\n form: FormSteps,\n policy: AdmissionPolicy | undefined,\n settings: FormSettings,\n options: ExecutionOptions,\n ) => Effect.Effect<FormOutcome, BrowserError>;\n readonly checkpoint: (\n reading: Omit<Reading, \"scope\"> & { readonly picture: boolean },\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n /** Scroll a resolved node into view. */\n readonly scrollTo: (\n target: Resolved,\n options: ExecutionOptions,\n ) => Effect.Effect<unknown, BrowserError>;\n /** A plain pause on the page, admitted like any wait so the page cannot change under it. */\n readonly pause: (\n milliseconds: number,\n options: ExecutionOptions,\n ) => Effect.Effect<void, BrowserError>;\n /** Wait for a resolved node to reach a state. */\n readonly waitFor: (\n target: Resolved,\n state: WaitForElementRequest[\"state\"],\n timeoutMillis: number | undefined,\n options: ExecutionOptions,\n ) => Effect.Effect<void, BrowserError>;\n /** Check conditions on the page as one charged read. */\n readonly expectations: (\n conditions: ReadonlyArray<Precondition>,\n options: ExecutionOptions,\n ) => Effect.Effect<void, BrowserError>;\n}\n\nexport interface StepDependencies {\n /** The issued page or frame every step resolves and acts through. */\n readonly target: DriverTarget;\n readonly controls: StepControls;\n /** Charges a step's own native reads (preconditions, resolution) to its admitted operation. */\n readonly chargeHostRead: (ticket: Ticket, operation: BrowserOperation) => void;\n}\n\n/**\n * Runs plan steps on one issued page or frame: preconditions and target resolution inside the\n * step's first admitted operation, then the action, then its postconditions and checkpoint.\n */\nexport const makePlanSteps = ({ target, controls, chargeHostRead }: StepDependencies) => {\n const decodeReceipt = <S extends Schema.Constraint>(schema: S, value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() =>\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Malformed.make({}),\n outcome: \"performed\",\n }),\n ),\n );\n\n return (\n step: Step,\n inputs: InputBindings,\n context: StepExecution,\n ): Effect.Effect<StepSuccess, BrowserError> =>\n Effect.suspend(() => {\n let currentPhase: RunPhase =\n step.action._tag === \"FillForm\"\n ? \"Field\"\n : step.action._tag === \"Wait\" && step.action.mode._tag === \"Settled\"\n ? \"Settled\"\n : \"Input\";\n\n let currentField: number | undefined;\n\n const preparation = makeStepPreparation({\n step,\n target,\n context,\n chargeHostRead,\n current: () => [currentPhase, currentField],\n });\n\n const { requests, element: groupElement } = preparation;\n\n const planOptions: ExecutionOptions = {\n ...context.options,\n ...(context.performance === undefined\n ? {}\n : {\n performance: {\n plan: context.performance,\n get fieldIndex() {\n return currentField;\n },\n },\n }),\n phase: (phase, fieldIndex) => {\n currentPhase = phase;\n currentField = fieldIndex;\n context.phase(phase, fieldIndex);\n },\n beforeNative: preparation.beforeNative,\n };\n\n const indexed = (value: ActionTarget): (() => ResolvedElement) => {\n const index = requests.findIndex((request) => request.target === value);\n\n return () => groupElement(index);\n };\n\n const inputValue = (value: ValueSource): Effect.Effect<string, BrowserError> =>\n value._tag === \"Literal\"\n ? Effect.succeed(value.value)\n : inputs[value.name] === undefined\n ? Effect.fail(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Configuration.make({ path: `inputs.${value.name}` }),\n outcome: \"undispatched\",\n }),\n )\n : Effect.succeed(inputs[value.name] ?? \"\");\n\n const policy: AdmissionPolicy | undefined = context.policy?.admit;\n const action = step.action;\n\n const perform: Effect.Effect<RunReceipt, BrowserError> = Effect.suspend(() => {\n switch (action._tag) {\n case \"Navigate\":\n return controls.operations\n .navigate(action.url, action.timeoutMillis, planOptions)\n .pipe(Effect.flatMap((url) => decodeReceipt(NavigationResult, { url })));\n case \"Click\":\n return controls.operations\n .click(indexed(action.target), policy, planOptions)\n .pipe(Effect.flatMap((value) => decodeReceipt(ActionResult, value)));\n case \"Hover\":\n return controls.operations\n .hover(indexed(action.target), policy, planOptions)\n .pipe(\n Effect.flatMap((value) => decodeReceipt(InputReceipt, { ...value, kind: \"hover\" })),\n );\n case \"Fill\":\n return inputValue(action.value).pipe(\n Effect.flatMap((value) =>\n controls.operations.fill(indexed(action.target), value, policy, planOptions),\n ),\n Effect.flatMap((url) => decodeReceipt(ActionResult, { url })),\n );\n case \"Type\":\n return inputValue(action.text).pipe(\n Effect.flatMap((value) =>\n controls.operations.type(\n value,\n action.target === undefined ? undefined : indexed(action.target),\n policy,\n planOptions,\n ),\n ),\n Effect.flatMap((value) => decodeReceipt(InputReceipt, { ...value, kind: \"type\" })),\n );\n case \"Press\":\n return controls.operations\n .press(\n action.key,\n action.modifiers ?? [],\n action.target === undefined ? undefined : indexed(action.target),\n policy,\n planOptions,\n )\n .pipe(\n Effect.flatMap((value) => decodeReceipt(InputReceipt, { ...value, kind: \"press\" })),\n );\n case \"Select\":\n return controls\n .selectOption(\n indexed(action.target),\n () => action.options.map((option) => indexed(option)()),\n policy,\n planOptions,\n )\n .pipe(Effect.flatMap((url) => decodeReceipt(ActionResult, { url })));\n case \"Scroll\": {\n const mode = action.mode;\n\n return (\n mode._tag === \"By\"\n ? controls.operations.scroll(mode.deltaX, mode.deltaY, planOptions)\n : controls.scrollTo(indexed(mode.target), planOptions)\n ).pipe(Effect.flatMap((url) => decodeReceipt(ActionResult, { url })));\n }\n case \"PointerMove\":\n return controls.operations\n .pointerMove(action.to, planOptions)\n .pipe(\n Effect.flatMap((value) =>\n decodeReceipt(InputReceipt, { ...value, kind: \"pointer-move\" }),\n ),\n );\n case \"Wheel\":\n return controls.operations\n .wheel(action.deltaX, action.deltaY, action.at, planOptions)\n .pipe(\n Effect.flatMap((value) =>\n decodeReceipt(InputReceipt, {\n ...value,\n kind: \"wheel\",\n delta: { x: action.deltaX, y: action.deltaY },\n }),\n ),\n );\n case \"Wait\": {\n const mode = action.mode;\n\n if (mode._tag === \"Settled\") return controls.settled(mode, planOptions);\n if (mode._tag === \"Duration\") return controls.pause(mode.milliseconds, planOptions);\n\n return controls.waitFor(\n indexed(mode.target),\n mode.state,\n mode.timeoutMillis,\n planOptions,\n );\n }\n case \"FillForm\":\n return Effect.gen(function* () {\n // Each control reports the ID its plan target named; a descriptor its position.\n const reported = (target: ActionTarget, fallback: string) =>\n target._tag === \"Ref\" ? target.reference.elementId : fallback;\n\n const fields = yield* Effect.forEach(\n action.fields,\n (field, index): Effect.Effect<FormSteps[\"fields\"][number], BrowserError> => {\n const reportedId = reported(field.target, `field_${index}`);\n const reference = indexed(field.target);\n\n return field._tag === \"Value\"\n ? inputValue(field.value).pipe(\n Effect.map((value) => ({\n reportedId,\n reference,\n field: () => ({ elementId: reportedId, value }),\n })),\n )\n : Effect.succeed({\n reportedId,\n reference,\n field:\n field._tag === \"Checked\"\n ? () => ({ elementId: reportedId, checked: field.checked })\n : () => ({\n elementId: reportedId,\n options: field.options.map((option) => indexed(option)()),\n }),\n });\n },\n );\n\n const submit = action.submit;\n\n const result = yield* controls.fillForm(\n {\n fields,\n ...(submit === undefined\n ? {}\n : {\n submit: {\n reportedId: reported(submit, \"submit\"),\n reference: indexed(submit),\n },\n }),\n retainObservation: false,\n },\n policy,\n {\n verify: action.options?.verify ?? true,\n settleMillis: action.options?.settleMillis ?? 50,\n },\n planOptions,\n );\n\n const receipt = yield* decodeReceipt(FillFormResult, result);\n\n context.retainReceipt(receipt);\n if (result.stopped !== undefined) return yield* result.stopped.error;\n\n return receipt;\n });\n }\n });\n\n return perform.pipe(\n Effect.tap((receipt) => Effect.sync(() => context.retainReceipt(receipt))),\n Effect.flatMap((receipt) => {\n const checkpointOptions = context.checkpoint;\n\n const after =\n step.expect?.after === undefined\n ? Effect.void\n : Effect.suspend(() => {\n context.phase(\"Postcondition\");\n\n return controls.expectations(step.expect?.after ?? [], context.options);\n });\n\n return after.pipe(\n Effect.andThen(\n checkpointOptions === undefined\n ? Effect.succeed({ receipt })\n : Effect.suspend(() => {\n context.phase(\"Checkpoint\");\n\n return controls\n .checkpoint(\n { ...checkpointOptions, picture: checkpointOptions.picture ?? false },\n context.options,\n )\n .pipe(\n Effect.flatMap((value) => decodeReceipt(Checkpoint, value)),\n Effect.map((checkpoint) => ({ receipt, checkpoint })),\n );\n }),\n ),\n );\n }),\n Effect.ensuring(Effect.promise(preparation.release)),\n );\n });\n};\n","import { type Crypto, Effect } from \"effect\";\n\n/**\n * A fresh UUIDv4 from the consumer's `Crypto` service. Without secure random bytes no browser can\n * be owned safely, so a failure here is a defect rather than a typed browser error.\n */\nexport const randomUuid = (crypto: Crypto.Crypto): Effect.Effect<string> =>\n Effect.orDie(crypto.randomUUIDv4);\n","import {\n Cause,\n Clock,\n Crypto,\n Deferred,\n Duration,\n Effect,\n Exit,\n Option,\n Queue,\n Redacted,\n Schema,\n Scope,\n Tracer,\n} from \"effect\";\n\nimport type { OperationOptions, PageStatus } from \"../../Browser.ts\";\nimport {\n type FillFormRequest,\n type FrameInfo,\n type InputReceipt,\n Inventory,\n type KeyModifier,\n Observation,\n type ObservedElement,\n type PageInfo,\n type PageSuspension,\n Target,\n type Viewport,\n type WaitForElementRequest,\n} from \"../../BrowserData.ts\";\nimport type { Lifetime, Source } from \"../../BrowserRuntime.ts\";\nimport { BrowserError, Reasons, type BrowserOperation } from \"../../Errors.ts\";\nimport type {\n Descriptor,\n ResolveGuard,\n SettledOptions,\n SettledEvidence,\n RunPhase,\n} from \"../../PlanData.ts\";\nimport {\n TimelineDefaults,\n type Retention,\n type Terminal,\n type TerminalReason,\n} from \"../../TimelineData.ts\";\nimport {\n cachedTarget,\n captureMetadata,\n operationEvents,\n planPublisher,\n publish,\n} from \"../timeline/Producers.ts\";\nimport { makeRetirement } from \"../timeline/Retirement.ts\";\nimport { makeJournal } from \"../timeline/SessionJournal.ts\";\nimport { makeStore } from \"../timeline/Store.ts\";\nimport * as Trace from \"../Trace.ts\";\nimport { type CaptureMetadata, type CaptureParent } from \"./Association.ts\";\nimport type { BindingImplementation, ConnectionIdentity } from \"./Binding.ts\";\nimport type { ConnectionBindings } from \"./Bindings.ts\";\nimport { cleanupStep, type ConnectionCleanup, type ConnectionState } from \"./ConnectionCleanup.ts\";\nimport type {\n Driver,\n NativeCachedPage,\n DriverEvents,\n DriverFault,\n DriverOptions,\n DriverTarget,\n ElementTarget,\n NativeSelectOptions,\n NativeFormField,\n InputCapture,\n NativeFileSelection,\n NavigationControl,\n} from \"./Driver.ts\";\nimport { publicError } from \"./NativeCalls.ts\";\nimport type { AdmissionPolicy, ResolvedElement } from \"./Observation.ts\";\nimport { type ExecutedOperation, policyOf } from \"./OperationPolicy.ts\";\nimport {\n makeOwner,\n native,\n operationSpan,\n within,\n type Limits,\n type ObservationScope,\n type OwnedWait,\n type ExecutionEvidence,\n type PerformanceRequest,\n type Ticket,\n type WaitTicket,\n} from \"./Owner.ts\";\nimport { makePageRegistry, type PageRecord } from \"./PageRegistry.ts\";\nimport { makePlanExecution } from \"./PlanExecution.ts\";\nimport { makePlanSteps } from \"./PlanSteps.ts\";\nimport type { NativeInput, NativePoint } from \"./Pointer.ts\";\nimport { randomUuid } from \"./Random.ts\";\n\nexport type SessionLease = Lifetime;\nexport type RemoteSource<L extends SessionLease, E, R = never> = Source<L, E, R>;\n\n/** Bounds a reading of the selected document. Already validated at the public boundary. */\nexport interface Reading {\n readonly scope: \"document\" | \"viewport\";\n readonly match?: string;\n readonly maxTextBytes?: number;\n readonly maxControls?: number;\n}\n\n/** How a form proceeds. Already validated and defaulted at the public boundary. */\nexport interface FormSettings {\n readonly verify: boolean;\n readonly settleMillis: number;\n}\n\n/** Private composite bounds and evidence cannot enter through decoded public options. */\nexport interface ExecutionOptions extends OperationOptions {\n readonly performance?: PerformanceRequest;\n readonly operationDeadline?: number;\n readonly queueDeadline?: number;\n readonly evidence?: ExecutionEvidence;\n readonly beforeNative?: (driver: Driver, ticket: Ticket) => Promise<void>;\n readonly phase?: (phase: RunPhase, fieldIndex?: number) => void;\n}\n\ntype DeferredElementTarget = ElementTarget | (() => ElementTarget);\n\n/**\n * What one admission of page or registry work supplies beyond its operation's policy, which\n * decides admission, charge, observation retirement, containment and the native checks.\n */\ninterface Work extends ExecutionOptions {\n /** The exact issued target the work acts through; registry work has none. */\n readonly target?: DriverTarget;\n /** The target's connection generation: work for an earlier one is stale. */\n readonly generation?: number;\n /** The record the target was issued from, so containment closes exactly that page. */\n readonly authority?: PageRecord;\n /** The page the work is confined to, when it is not the target's own (page control). */\n readonly pageId?: string;\n /** The issued capability's own check, run before admission and again once admitted. */\n readonly validate?: (operation: BrowserOperation) => Effect.Effect<void, BrowserError>;\n /** Further checks once admitted, after validation and the page's reservation. */\n readonly preflight?: Effect.Effect<void, BrowserError>;\n /** A step of a composite operation that only reads: it sends no input and costs nothing. */\n readonly readOnly?: boolean;\n /** A composite operation's own steps keep the page's observation usable for each other. */\n readonly retainObservation?: boolean;\n /** Recovery admission's absolute bound, which also bounds waiting for the permit. */\n readonly waitUntil?: number;\n}\n\nconst codePointCount = (text: string): number => {\n let count = 0;\n\n for (const _point of text) count++;\n\n return count;\n};\n\nconst elementTarget = (value: DeferredElementTarget): ElementTarget =>\n typeof value === \"function\" ? value() : value;\n\nconst effectiveTarget = (value: ElementTarget | undefined, fallback: DriverTarget): DriverTarget =>\n typeof value === \"object\" && \"_tag\" in value && value._tag === \"ResolvedElement\"\n ? value.target\n : fallback;\n\n/**\n * A form as the form engine runs it. Each field and the submit carry the ID the outcome reports\n * for them and the exact node they act on, read when that step runs, so an outcome names only the\n * controls the caller named: there is no placeholder ID to translate back.\n */\nexport interface FormSteps {\n readonly fields: ReadonlyArray<{\n readonly reportedId: string;\n readonly reference: () => ObservedElement | ResolvedElement;\n readonly field: () => NativeFormField;\n }>;\n readonly submit?: {\n readonly reportedId: string;\n readonly reference: () => ObservedElement | ResolvedElement;\n };\n /** An observation's steps keep it usable for each other; resolved targets need no such care. */\n readonly retainObservation: boolean;\n}\n\n/** A form over one observation's controls, reporting the IDs the caller named. */\nexport const observedForm = (request: FillFormRequest): FormSteps => {\n const at = (elementId: string) => () => ({ observationId: request.observationId, elementId });\n const submit = request.submit;\n\n return {\n fields: request.fields.map((field) => ({\n reportedId: field.elementId,\n reference: at(field.elementId),\n field: () => field,\n })),\n ...(submit === undefined ? {} : { submit: { reportedId: submit, reference: at(submit) } }),\n retainObservation: true,\n };\n};\n\n/** What a form did; the public boundary decodes it. */\nexport interface FormOutcome {\n readonly fields: ReadonlyArray<{\n readonly elementId: string;\n readonly status: \"set\" | \"unchanged\";\n readonly input?: InputReceipt;\n }>;\n readonly submitted: boolean;\n readonly url: string;\n readonly submitInput?: InputReceipt;\n readonly stopped?: {\n readonly stage: \"field\" | \"verify\" | \"submit\";\n readonly elementId?: string;\n readonly error: BrowserError;\n };\n}\n\ninterface NavigationStopAttempt<E> {\n readonly result: Deferred.Deferred<void, E>;\n readonly retired: Deferred.Deferred<void>;\n running: boolean;\n committed: boolean;\n setupPending: boolean;\n}\n\n/**\n * Callers share the active attempt. Its owner may cancel it, but a committed Exit is permanent.\n * Before commitment, retry waits for actual native setup and port retirement, not the waiter.\n */\nconst makeNavigationStopCoordinator = <E, R>(\n done: () => boolean,\n attempt: (\n onDispatch: () => void,\n retainSetup: () => () => void,\n deadline?: number,\n ) => Effect.Effect<\"dispatched\" | \"settled\", E, R>,\n confirmed: () => void,\n) =>\n Effect.sync(() => {\n let current: NavigationStopAttempt<E | BrowserError> | undefined;\n\n const request = (deadline?: number): Effect.Effect<void, E | BrowserError, R> =>\n Effect.uninterruptibleMask((restore) =>\n Effect.suspend(() => {\n // Fencing may complete the navigation while a committed stop is still failing.\n if (current !== undefined && (current.running || current.committed)) {\n const joined = current;\n\n if (deadline === undefined || joined.committed)\n return restore(Deferred.await(joined.result));\n\n return restore(Effect.exit(Deferred.await(joined.result))).pipe(\n Effect.flatMap((exit) =>\n Exit.isSuccess(exit) || joined.committed\n ? exit\n : restore(Deferred.await(joined.retired)).pipe(Effect.andThen(request(deadline))),\n ),\n );\n }\n if (done()) return Effect.void;\n if (current !== undefined) {\n if (deadline !== undefined)\n return restore(Deferred.await(current.retired)).pipe(\n Effect.andThen(request(deadline)),\n );\n\n return Effect.fail(\n BrowserError.make({\n operation: \"navigate-stop\",\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n );\n }\n\n const active: NavigationStopAttempt<E | BrowserError> = {\n result: Deferred.makeUnsafe(),\n retired: Deferred.makeUnsafe(),\n running: true,\n committed: false,\n setupPending: false,\n };\n\n current = active;\n\n const retire = () => {\n active.setupPending = false;\n if (!active.running) {\n if (!active.committed && current === active) current = undefined;\n Deferred.doneUnsafe(active.retired, Effect.void);\n }\n };\n\n return restore(\n Effect.suspend(() =>\n attempt(\n () => {\n active.committed = true;\n },\n () => {\n active.setupPending = true;\n\n return retire;\n },\n deadline,\n ),\n ),\n ).pipe(\n Effect.tap((result) =>\n result === \"dispatched\" ? Effect.sync(confirmed) : Effect.void,\n ),\n Effect.asVoid,\n Effect.onExit((exit) =>\n Effect.sync(() => {\n active.running = false;\n if (!active.committed && !active.setupPending) current = undefined;\n if (!active.setupPending) Deferred.doneUnsafe(active.retired, Effect.void);\n Deferred.doneUnsafe(active.result, exit);\n }),\n ),\n );\n }),\n );\n\n return {\n stop: request(),\n recover: (deadline: number) =>\n within(request(deadline), deadline, () =>\n BrowserError.make({\n operation: \"navigate-stop\",\n reason: Reasons.Timeout.make({}),\n outcome: current?.committed === true ? \"unknown\" : \"undispatched\",\n }),\n ),\n };\n });\n\n/** Explicit callers retain the original cancellation and fail-fast admission contract. */\nexport const makeNavigationStop = <E, R>(\n done: () => boolean,\n attempt: (\n onDispatch: () => void,\n retainSetup: () => () => void,\n ) => Effect.Effect<\"dispatched\" | \"settled\", E, R>,\n confirmed: () => void,\n) =>\n makeNavigationStopCoordinator(done, attempt, confirmed).pipe(\n Effect.map((coordinator) => coordinator.stop),\n );\n\nexport interface SessionOptions<L extends SessionLease, E, R = never> {\n readonly implementation: string;\n readonly remote: RemoteSource<L, E, R>;\n /** The constructor resolves an issued binding before acquiring the lifetime. */\n readonly engine: BindingImplementation;\n /** Only a keep-alive session may detach and reattach inside this owner. */\n readonly keepAlive: boolean;\n readonly driver: DriverOptions;\n readonly maxReturnedBytes: number;\n /** Consumer E/R stays with the typed public supervisor; this installs its captured runtime. */\n readonly connectBindings?: (\n onFault: (event: DriverFault) => void,\n isActive: () => boolean,\n isCurrent: () => boolean,\n ) => Effect.Effect<ConnectionBindings, never, Scope.Scope>;\n}\n\n/**\n * One owner for page operations, bootstrap, capture and connection cleanup. The lifetime source\n * decides whether release also terminates a browser and how that termination is observed.\n */\nexport const acquireSession = Effect.fnUntraced(function* <L extends SessionLease, E, R>(\n limits: Limits & { readonly timelineLimits?: Retention },\n options: SessionOptions<L, E, R>,\n) {\n // The engine is resolved before anything is allocated, so an unissued binding costs nothing.\n const engine = options.engine;\n\n if (engine === undefined)\n return yield* BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Configuration.make({}),\n outcome: \"undispatched\",\n });\n const parentScope = yield* Scope.Scope;\n // Register the binding lifetime BEFORE the remote cleanup finalizer. On natural Scope\n // shutdown that finalizer must fence the owner before any callback finalizer can reenter it.\n const bindingLifetime = yield* Scope.fork(parentScope, \"sequential\");\n const ended = yield* Deferred.make<void>();\n const owner = yield* makeOwner(limits);\n const clock = owner.clock;\n let activeRuns = 0;\n const pageRuns = new Map<string, number>();\n const crypto = yield* Crypto.Crypto;\n const uuid = randomUuid(crypto);\n const clockId = yield* uuid;\n const originNanos = clock.monotonicTimeNanosUnsafe();\n\n const makeDomain = (storeId: string, coversFromNanos?: bigint) => {\n const store = makeStore({\n clock,\n originNanos,\n identity: { storeId, clockId },\n limits: limits.timelineLimits ?? TimelineDefaults,\n ...(coversFromNanos === undefined ? {} : { coversFromNanos }),\n });\n\n return {\n store,\n retirement: makeRetirement((reason) => {\n store.finish(reason);\n }),\n };\n };\n\n let domain = makeDomain(yield* uuid);\n let hasConnectedStore = false;\n\n let driver: Driver | undefined;\n let connectPending = false;\n // Native listeners can outlive disconnect. Authority belongs to this connection\n // lease, not merely to the current session phase or selected browser target.\n let activeConnection: object | undefined;\n let handoffToken: string | undefined;\n let reconnectTarget: string | undefined;\n let activeBindings: ConnectionBindings | undefined;\n\n const pages = makePageRegistry();\n\n const journal = makeJournal({\n store: () => domain.store,\n cachedPages: () => driver?.cachedPages() ?? [],\n pageStatus: (pageId) => {\n const record = pages.get(pageId);\n\n return record === undefined\n ? owner.state.phase === \"open\" || owner.state.phase === \"acquiring\"\n ? undefined\n : {\n phase:\n owner.state.phase === \"closing\"\n ? \"closing\"\n : owner.state.phase === \"closed\"\n ? \"closed\"\n : owner.state.phase === \"paused\"\n ? \"paused\"\n : \"stale\",\n containment:\n owner.state.phase === \"uncertain\"\n ? { _tag: \"SessionFenced\", generation: owner.state.generation }\n : { _tag: \"NotRequired\" },\n }\n : {\n phase: record.identity.generation === owner.state.generation ? record.phase : \"stale\",\n containment: record.containment,\n };\n },\n generation: () => owner.state.generation,\n });\n\n owner.observePhase((phase) => {\n publish(domain.store, { target: null, correlation: null, event: { _tag: \"Lifecycle\", phase } });\n });\n\n owner.observeOperations(\n operationEvents({\n store: () => domain.store,\n originNanos,\n retain: (pageId) => {\n const releaseDomain = domain.retirement.retain();\n\n const releasePage =\n pageId === undefined ? undefined : pages.get(pageId)?.retirement.retain();\n\n return () => {\n releasePage?.();\n releaseDomain();\n };\n },\n }),\n );\n\n const retirePageTimeline = (record: PageRecord, reason: TerminalReason) => {\n record.retirement.request(reason);\n };\n\n const endTimeline = (reason: TerminalReason) => {\n for (const record of pages.records()) retirePageTimeline(record, reason);\n domain.retirement.request(reason);\n };\n\n let initialTarget: DriverTarget | undefined;\n let initialInfo: PageInfo | undefined;\n let initialAuthority: ReturnType<typeof registerPage> | undefined;\n\n const pageClosed = (pageId: string, cached?: NativeCachedPage, store = domain.store) => {\n driver?.retireInitializationPage?.(pageId);\n activeBindings?.retirePage(pageId);\n const page = pages.get(pageId);\n\n // A native callback supplies the cached fact; its later owner confirmation is idempotent.\n if (page !== undefined || cached !== undefined)\n publish(store, {\n target:\n cached === undefined\n ? {\n generation: page?.identity.generation ?? owner.state.generation,\n pageId,\n frameId: null,\n document: null,\n }\n : cachedTarget(cached, owner.state.generation),\n correlation: null,\n event: { _tag: \"PageClosed\" },\n });\n if (page !== undefined) retirePageTimeline(page, \"closed\");\n\n if (page !== undefined && page.phase !== \"closing\") owner.revokePage(pageId);\n owner.retirePage(pageId);\n pages.closed(pageId);\n };\n\n const pendingPageFaults = new Map<\n string,\n { readonly generation: number; readonly authority: PageRecord | undefined }\n >();\n\n // Pages whose faults await containment, in arrival order. The pending map bounds it.\n const pageFaults = yield* Queue.unbounded<string>();\n\n const revokePage = (pageId: string, except?: AbortSignal) => {\n pages.closing(pageId);\n owner.revokePage(pageId, except);\n activeBindings?.fencePage(pageId);\n driver?.fenceInitializationPage?.(pageId);\n owner.invalidate(\"closed\", { pageId });\n };\n\n const restorePageAuthority = (pageId: string) => {\n owner.restorePageAdmission(pageId);\n driver?.restoreInitializationPage?.(pageId, owner.paused);\n activeBindings?.resumePage(pageId);\n };\n\n const fenceBindings = () => {\n activeBindings?.close();\n driver?.fenceInitialization?.();\n };\n\n const disposeBindings = Effect.gen(function* () {\n const connection = activeBindings;\n\n activeBindings = undefined;\n const callbacks = yield* Effect.exit(connection?.dispose ?? Effect.void);\n\n const registrations = yield* Effect.tryPromise({\n try: () => driver?.disposeInitialization?.() ?? Promise.resolve(),\n catch: () =>\n BrowserError.make({\n operation: \"close\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n }),\n }).pipe(Effect.exit);\n\n if (Exit.isFailure(callbacks)) return yield* Effect.failCause(callbacks.cause);\n if (Exit.isFailure(registrations)) return yield* Effect.failCause(registrations.cause);\n });\n\n const capture: CaptureParent = {\n owner,\n newCaptureId: uuid,\n resolve: (ticket, requested) => {\n const admittedDomain = domain;\n\n return native(\"capture-start\", ticket, async () => {\n if (driver === undefined)\n throw BrowserError.make({\n operation: \"capture\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n const binding = await driver.capture(requested);\n\n ticket.check();\n const generation = ticket.generation;\n\n const target = Target.make({\n generation,\n pageId: binding.pageId,\n frameId: binding.frameId,\n });\n\n const authority =\n pages.get(binding.pageId) ?? registerPage(requested, target, generation).record;\n\n const publishMetadata = captureMetadata(admittedDomain.store, originNanos);\n let releaseCapture: (() => void) | undefined;\n\n return {\n key: binding.targetId,\n target,\n metadata: (event: CaptureMetadata) => {\n if (\n releaseCapture === undefined &&\n event._tag === \"Capture\" &&\n event.phase === \"Reserved\"\n ) {\n const releaseDomain = admittedDomain.retirement.retain();\n const releasePage = authority.retirement.retain();\n\n releaseCapture = () => {\n releasePage();\n releaseDomain();\n };\n }\n publishMetadata(event);\n if (event._tag === \"Capture\" && event.phase === \"Stopped\") releaseCapture?.();\n },\n status: () => ({\n phase:\n authority.phase === \"closed\"\n ? \"closed\"\n : generation !== owner.state.generation\n ? \"stale\"\n : authority.phase,\n containment: authority.containment,\n }),\n source: binding.source,\n };\n });\n },\n captureLeases: new Map(),\n captureReservedBytes: 0,\n };\n\n owner.onInvalidate((reason, scope, origin) => {\n driver?.invalidateObservation(scope, reason === \"observation\" ? origin : undefined);\n if (scope !== \"all\" && scope !== \"none\" && (reason === \"paused\" || reason === \"closed\")) {\n const record = pages.get(scope.pageId);\n\n if (record !== undefined && record.phase !== \"open\")\n publish(record.store, {\n target: { ...record.identity, document: null },\n correlation: null,\n event: { _tag: \"Lifecycle\", phase: record.phase },\n });\n }\n if (reason === \"uncertain\" && scope === \"all\")\n for (const page of pages.records())\n pages.contain(page, { _tag: \"SessionFenced\", generation: owner.state.generation });\n if (scope === \"all\" && [\"paused\", \"disconnected\", \"uncertain\", \"closed\"].includes(reason)) {\n if (reason === \"paused\")\n for (const page of pages.records()) retirePageTimeline(page, \"stale\");\n else\n endTimeline(\n owner.reason === \"expired\"\n ? \"expired\"\n : owner.reason === \"detached\"\n ? \"detached\"\n : owner.state.phase === \"faulted\"\n ? \"faulted\"\n : reason === \"uncertain\"\n ? \"uncertain\"\n : reason === \"disconnected\"\n ? \"disconnected\"\n : \"closed\",\n );\n pages.clear();\n }\n if ([\"disconnected\", \"uncertain\", \"closed\"].includes(reason) && scope === \"all\")\n fenceBindings();\n if ([\"paused\", \"disconnected\", \"uncertain\", \"closed\"].includes(reason)) {\n if (reason !== \"paused\" && scope !== \"all\" && scope !== \"none\")\n activeBindings?.fencePage(scope.pageId);\n for (const lease of capture.captureLeases.values())\n if (scope === \"all\" || (scope !== \"none\" && lease.pageId === scope.pageId))\n lease.invalidate(reason);\n }\n });\n\n /**\n * The local half of cleanup. Each step is an independent fact for the canonical\n * coordinator, which owns the release request and the terminal status observation.\n */\n let releaseTimelineCleanup: (() => void) | undefined;\n\n const local: ConnectionCleanup = {\n fence: Effect.sync(() => {\n releaseTimelineCleanup ??= domain.retirement.retain();\n owner.fence(\"closing\", \"closed\");\n handoffToken = undefined;\n activeConnection = undefined;\n Deferred.doneUnsafe(ended, Effect.void);\n }),\n capture: Effect.suspend(() =>\n Effect.forEach([...capture.captureLeases.values()], (lease) => lease.stop, {\n discard: true,\n }),\n ),\n initialization: disposeBindings,\n disconnect: Effect.suspend(() => {\n const acquired = driver;\n\n driver = undefined;\n if (acquired === undefined)\n return Effect.succeed<ConnectionState>(connectPending ? \"pending\" : \"not-connected\");\n\n return Effect.tryPromise({\n try: () => acquired.disconnect(),\n catch: () =>\n BrowserError.make({\n operation: \"disconnect\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n }),\n }).pipe(Effect.as<ConnectionState>(\"closed\"));\n }).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n owner.transition(\"closed\");\n releaseTimelineCleanup?.();\n }),\n ),\n ),\n };\n\n // Registered before the source so natural scope closure observes its completed release first.\n let retireControl: Effect.Effect<void> = Effect.void;\n\n yield* Effect.addFinalizer(() => Effect.suspend(() => retireControl));\n\n const acquired = yield* options.remote(local, owner.lifetimeDeadline);\n\n retireControl = cleanupStep(\n Effect.suspend(() => acquired.controlRetired ?? Effect.succeed(false)),\n 2000,\n ).pipe(\n Effect.tap((result) =>\n result._tag === \"Success\" && result.value ? Effect.sync(owner.retireControl) : Effect.void,\n ),\n Effect.asVoid,\n Effect.ignoreCause,\n Effect.provideService(Clock.Clock, clock),\n );\n\n const ref: L[\"reference\"] = acquired.reference;\n // Effect.tap preserves the exact supplying lifetime's success; the generic constraint alone\n // would infer unknown here. No receipt value is decoded, constructed or coerced by this owner.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- restates L's own release type\n const release = acquired.release as Effect.Effect<Effect.Success<L[\"release\"]>>;\n const cleanupResult: L[\"cleanupResult\"] = acquired.cleanupResult;\n\n const closeScope = acquired.release.pipe(\n Effect.tap(() => retireControl),\n Effect.ensuring(Deferred.succeed(ended, undefined)),\n Effect.asVoid,\n Effect.provideService(Clock.Clock, clock),\n );\n\n const connectionEvents = (connectionLease: object, generation: number): DriverEvents => {\n const connectionDomain = domain;\n\n return {\n pageLifecycle: (event) => {\n if (activeConnection !== connectionLease) return;\n\n const target =\n event._tag === \"Navigated\"\n ? {\n generation: owner.state.generation,\n pageId: event.page.pageId,\n frameId: event.frameId,\n document: event.documentEpoch,\n }\n : cachedTarget(event.page, owner.state.generation);\n\n publish(connectionDomain.store, {\n target,\n correlation: null,\n event:\n event._tag === \"Opened\"\n ? { _tag: \"PageOpened\" }\n : event._tag === \"Navigated\"\n ? {\n _tag: \"Navigated\",\n sameDocument: event.sameDocument,\n url: event.url !== null && event.url.length <= 8192 ? event.url : null,\n urlQualification:\n event.url !== null && event.url.length > 8192\n ? \"Omitted\"\n : event.urlQualification,\n }\n : event._tag === \"Display\"\n ? {\n _tag: \"DisplayChanged\",\n selected: event.page.selected,\n displayState:\n event.page.displayState === \"suspended\" ? \"held\" : event.page.displayState,\n }\n : { _tag: \"MetadataChanged\" },\n });\n },\n pageFault: (pageId) => {\n if (activeConnection !== connectionLease) return;\n if (pendingPageFaults.has(pageId)) return;\n if (owner.state.phase !== \"open\" || pendingPageFaults.size >= options.driver.maxPages) {\n owner.terminate(\"native-failure\", \"unknown\", owner.state.generation);\n\n return;\n }\n pendingPageFaults.set(pageId, {\n generation: owner.state.generation,\n authority: pages.get(pageId),\n });\n revokePage(pageId);\n Queue.offerUnsafe(pageFaults, pageId);\n },\n frameClosed: (pageId, frameId) => {\n if (activeConnection !== connectionLease) return;\n pages.detachFrame(pageId, frameId);\n },\n pageClosed: (pageId, cached) => {\n if (activeConnection === connectionLease)\n pageClosed(pageId, cached, connectionDomain.store);\n },\n retired: () => owner.retireWait(connectionLease),\n invalidate: (reason, scope) => {\n if (activeConnection === connectionLease) owner.invalidate(reason, scope);\n },\n disconnected: () => {\n owner.retireWait(connectionLease);\n if (activeConnection !== connectionLease) return;\n if (\n owner.state.phase !== \"closing\" &&\n owner.state.phase !== \"closed\" &&\n owner.state.phase !== \"detached\"\n ) {\n owner.terminate(\"disconnected\", \"unknown\", generation);\n }\n },\n pause: (reason = \"dialog\", pageId) => {\n if (activeConnection !== connectionLease) return;\n const trigger = reason === \"popup\" ? \"popup-policy\" : \"dialog-policy\";\n\n owner.record(trigger, \"confirmed\", generation);\n if (pageId !== undefined && owner.state.phase === \"open\") {\n if (!owner.paused(pageId) && owner.pausedPages >= options.driver.maxPages) {\n owner.terminate(trigger, \"unknown\", generation);\n\n return;\n }\n pages.pause(pageId);\n activeBindings?.fencePage(pageId);\n driver?.fenceInitializationPage?.(pageId);\n owner.pausePage(pageId);\n owner.invalidate(\"paused\", { pageId });\n // This issued Page never runs again: the operator's release issues fresh Pages. Retire\n // it as an all-page pause retires every page, so work waiting on it ends now.\n const record = pages.get(pageId);\n\n if (record !== undefined) retirePageTimeline(record, \"stale\");\n\n return;\n }\n if (owner.state.phase === \"open\") owner.fence(\"paused\", \"paused\", trigger);\n // An unsolicited popup/dialog during setup cannot be silently admitted by\n // the later connect commit. No usable handle has been exposed: fail closed.\n else if (owner.state.phase === \"acquiring\") owner.terminate(trigger, \"known\", generation);\n },\n fault: (event) => {\n if (activeConnection !== connectionLease) return;\n if (event.source === \"policy\") {\n owner.policy(event, generation);\n\n return;\n }\n if (owner.state.phase === \"closing\" || owner.state.phase === \"closed\") return;\n owner.terminate(\n event.source === \"binding\"\n ? \"callback-failure\"\n : event.disposition === \"not-dispatched\"\n ? \"cleanup-capacity\"\n : event.reason === \"registration\"\n ? \"registration-failure\"\n : event.reason === \"connection\"\n ? \"disconnected\"\n : \"native-failure\",\n event.disposition,\n generation,\n );\n },\n };\n };\n\n const connectNative = (url: Redacted.Redacted<unknown>, nativeOptions: DriverOptions) =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n // Drawn before this attempt claims the connection, so a failed draw leaves nothing to undo.\n const identity: ConnectionIdentity = { namespace: yield* uuid, bindings: yield* uuid };\n\n if (hasConnectedStore) {\n endTimeline(\"detached\");\n domain = makeDomain(yield* uuid, clock.monotonicTimeNanosUnsafe() - originNanos);\n }\n hasConnectedStore = true;\n publish(domain.store, {\n target: null,\n correlation: null,\n event: { _tag: \"Lifecycle\", phase: \"acquiring\" },\n });\n const connectionLease = {};\n\n activeConnection = connectionLease;\n owner.setConnection(connectionLease);\n connectPending = true;\n const events = connectionEvents(connectionLease, owner.state.generation);\n\n const bindings =\n options.connectBindings === undefined\n ? undefined\n : yield* options\n .connectBindings(\n events.fault,\n () =>\n activeConnection === connectionLease &&\n (owner.state.phase === \"acquiring\" || owner.state.phase === \"open\"),\n () =>\n activeConnection === connectionLease &&\n [\"acquiring\", \"open\", \"paused\"].includes(owner.state.phase),\n )\n .pipe(Scope.provide(bindingLifetime));\n\n activeBindings = bindings;\n\n const retired = () =>\n activeConnection !== connectionLease ||\n [\"closing\", \"closed\", \"uncertain\", \"faulted\"].includes(owner.state.phase);\n\n if (retired()) {\n bindings?.close();\n yield* bindings?.dispose ?? Effect.void;\n\n return yield* BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n }\n\n const acquired = yield* restore(\n engine\n .connect({\n connection: Redacted.value(url),\n identity,\n options: {\n ...nativeOptions,\n ...(bindings === undefined\n ? {}\n : {\n bindings: bindings.bindings,\n onBindingFault: bindings.reportFailure,\n }),\n },\n events,\n onAbandoned: () => bindings?.close(),\n onSettled: () => {\n if (activeConnection === connectionLease) connectPending = false;\n },\n })\n .pipe(\n Trace.span(\"Browser.driver.connect\", {\n attributes: { \"browser.operation\": \"connect\" },\n }),\n ),\n );\n\n driver = acquired;\n if (\n activeConnection !== connectionLease ||\n owner.state.phase === \"closed\" ||\n owner.state.phase === \"closing\" ||\n owner.state.phase === \"uncertain\" ||\n owner.state.phase === \"faulted\"\n ) {\n yield* Effect.tryPromise({\n try: () => acquired.disconnect(),\n catch: () =>\n BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n }),\n }).pipe(Trace.span(\"Browser.driver.abandoned-disconnect\"), Effect.ignore);\n driver = undefined;\n\n return yield* BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Closed.make({}),\n outcome: \"unknown\",\n });\n }\n\n return acquired;\n }),\n );\n\n const getDriver = () => {\n if (driver === undefined)\n throw BrowserError.make({\n operation: \"target\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n\n return driver;\n };\n\n /**\n * Waits for the current document's readiness. Only work whose policy depends on an initialized\n * document asks: navigation, selection and page management deliberately do not, because\n * initialization must never deadlock the navigation that produces the document it waits for.\n */\n const requireReady = async (\n operation: BrowserOperation,\n ticket: Ticket,\n target: DriverTarget,\n ) => {\n const state = await getDriver().documentReadiness(ticket, target);\n\n if (state._tag === \"Ready\" || state._tag === \"NotApplicable\") return;\n throw BrowserError.make({\n operation,\n reason:\n state._tag === \"RequiresNavigation\" || state.reason === \"stale\"\n ? Reasons.Stale.make({})\n : state.reason === \"timeout\"\n ? Reasons.Timeout.make({})\n : Reasons.Failed.make({}),\n outcome: \"undispatched\",\n });\n };\n\n /** The policy's native checks on the exact target, before any of the work's own commands. */\n /**\n * The page checks an operation's policy requires before its native call. Work that reads no\n * document (`document: false`, a plan's duration pause) keeps the held-page refusal but never\n * waits for document readiness, so it can run before a navigation the bootstrap requires.\n */\n const prepare = async (\n operation: ExecutedOperation,\n ticket: Ticket,\n target: DriverTarget,\n reads: { readonly document?: boolean } = {},\n ) => {\n const policy = policyOf(operation);\n\n if (policy.work !== \"page\") return;\n // A held page is refused, never woken.\n if (policy.refuseHeld) await getDriver().pageControl?.checkTarget(target, ticket);\n if (policy.ready && reads.document !== false) await requireReady(operation, ticket, target);\n };\n\n /** Attribute preparation without changing the Promise's dispatch or cancellation boundary. */\n const readyNative = <A>(\n operation: ExecutedOperation,\n ticket: Ticket,\n preparation: () => Promise<void>,\n action: () => Promise<A>,\n ) =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const readiness = yield* Trace.start(\"Browser.readiness\", {\n attributes: { \"browser.operation\": operation },\n });\n\n return yield* restore(\n native(operation, ticket, async () => {\n try {\n await preparation();\n readiness?.end(Exit.void);\n } catch (error) {\n readiness?.end(Exit.fail(error));\n throw error;\n }\n\n return action();\n }),\n ).pipe(Effect.onExit((exit) => Effect.sync(() => readiness?.end(exit))));\n }),\n );\n\n const observeInside = (\n ticket: Ticket,\n maximumBytes: number,\n controls: number,\n scope: \"document\" | \"viewport\",\n match: string | undefined,\n target: DriverTarget,\n ) =>\n Effect.suspend(() => {\n const revision = owner.revision(target.pageId);\n\n return readyNative(\n \"observe\",\n ticket,\n () => prepare(\"observe\", ticket, target),\n () => getDriver().observe(scope, maximumBytes, controls, ticket, match, target),\n ).pipe(\n Effect.flatMap((raw) =>\n Effect.gen(function* () {\n if (owner.revision(target.pageId) !== revision)\n return yield* BrowserError.make({\n operation: \"observe\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n });\n\n const result = yield* Effect.try({\n try: () =>\n Observation.make({\n ...raw,\n target: Target.make({ generation: ticket.generation, ...target }),\n revision,\n }),\n catch: (error) =>\n publicError(error, \"observe\", {\n reason: Reasons.Malformed.make({}),\n outcome: \"undispatched\",\n }),\n });\n\n const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(Observation))(\n result,\n ).pipe(\n Effect.mapError(() =>\n BrowserError.make({\n operation: \"observe\",\n reason: Reasons.Malformed.make({}),\n outcome: \"undispatched\",\n }),\n ),\n );\n\n const bytes = new TextEncoder().encode(encoded).length;\n\n if (bytes > options.maxReturnedBytes) {\n return yield* BrowserError.make({\n operation: \"observe\",\n reason: Reasons.Limit.make({\n dimension: \"returned-bytes\",\n maximum: options.maxReturnedBytes,\n observed: bytes,\n }),\n outcome: \"undispatched\",\n });\n }\n\n return result;\n }).pipe(\n Trace.span(\"Browser.observe.result\", {\n attributes: { \"browser.operation\": \"observe\" },\n }),\n ),\n ),\n );\n });\n\n /** A requested text bound may narrow the policy's bound, never widen it. */\n const textBudget = (\n operation: BrowserOperation,\n requested: number | undefined,\n ): Effect.Effect<number, BrowserError> => {\n const bytes = requested ?? Math.min(options.maxReturnedBytes, 16384);\n\n return bytes > options.maxReturnedBytes\n ? Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Configuration.make({ path: \"maxTextBytes\" }),\n outcome: \"undispatched\",\n }),\n )\n : Effect.succeed(bytes);\n };\n\n /**\n * While a navigation is in flight on a page, nothing else may change that page.\n * Reads, checkpoints, holds and every other page proceed.\n */\n const unreserved = (operation: BrowserOperation, pageId: string) =>\n Effect.suspend(() =>\n owner.reserved(pageId) || owner.waitPending(pageId)\n ? Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n )\n : Effect.void,\n );\n\n /** Closing the exact affected page contains unknown input without retiring healthy peers. */\n const containment = (pageId: string, authority = pages.get(pageId)) => {\n const current = driver;\n\n if (current === undefined) return undefined;\n\n return {\n pageId,\n close: Effect.suspend(() => {\n const page = authority;\n const generation = page?.identity.generation ?? owner.state.generation;\n\n const confirmed = () => {\n if (page !== undefined && page.containment._tag === \"NotRequired\")\n pages.contain(page, { _tag: \"PageClosed\", pageId, generation });\n\n return true;\n };\n\n if (page?.phase === \"closed\") return Effect.sync(confirmed);\n if (page?.attempt !== undefined)\n return Deferred.await(page.attempt).pipe(\n Effect.timeoutOrElse({ duration: 3000, orElse: () => Effect.succeed(false) }),\n Effect.tap((closed) =>\n Effect.sync(() => {\n if (closed) confirmed();\n else pages.contain(page, { _tag: \"SessionFenced\", generation });\n }),\n ),\n );\n const attempt = Deferred.makeUnsafe<boolean>();\n\n if (page !== undefined) pages.attempting(page, attempt);\n revokePage(pageId);\n\n return Effect.promise(async () => {\n try {\n await current.containPage(pageId);\n confirmed();\n pageClosed(pageId);\n\n return true;\n } catch {\n return false;\n }\n }).pipe(\n Effect.timeoutOrElse({ duration: 3000, orElse: () => Effect.succeed(false) }),\n Effect.tap((closed) =>\n Effect.sync(() => {\n if (!closed && page !== undefined)\n pages.contain(page, { _tag: \"SessionFenced\", generation });\n }),\n ),\n Effect.tap((closed) => Deferred.succeed(attempt, closed)),\n );\n }),\n };\n };\n\n const waitFree = (operation: BrowserOperation, pageId?: string) =>\n Effect.suspend(() =>\n owner.waitPending(pageId)\n ? Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n )\n : Effect.void,\n );\n\n /**\n * Why a capability that can no longer act was refused, most specific first. A refused owner\n * outranks staleness: every phase change advances the generation, so a closed, expired,\n * disconnected or paused session must not look like a stale Page. A closed Page is closed. Only\n * work the owner would still admit is stale: a replaced generation, a closing page or a detached\n * frame, which a fresh Page or observation can replace.\n */\n const unavailable = (\n operation: BrowserOperation,\n page?: { readonly phase: \"open\" | \"paused\" | \"closing\" | \"closed\" },\n admission?: { readonly recovery?: boolean },\n ) =>\n BrowserError.make({\n operation,\n reason:\n owner.refusal(admission) ??\n (page?.phase === \"closed\" ? Reasons.Closed.make({}) : Reasons.Stale.make({})),\n outcome: \"undispatched\",\n });\n\n const checkTarget = (\n operation: BrowserOperation,\n target?: DriverTarget,\n generation?: number,\n admission?: { readonly recovery?: boolean },\n ) =>\n Effect.suspend(() =>\n (generation !== undefined && generation !== owner.state.generation) ||\n (target !== undefined && pages.get(target.pageId)?.phase === \"closing\")\n ? Effect.fail(unavailable(operation, undefined, admission))\n : Effect.void,\n );\n\n /**\n * Admits page or registry work under its operation's policy. The policy decides the permit, the\n * charge, which observations input retires and where an unknown outcome is contained; a call\n * supplies only what varies (its target, deadlines, evidence and further checks). The issued\n * capability is validated before admission and again once admitted.\n */\n const admit = <A, E, R>(\n operation: ExecutedOperation,\n body: (ticket: Ticket) => Effect.Effect<A, E, R>,\n work: Work = {},\n ): Effect.Effect<A, E | BrowserError, R> => {\n const policy = policyOf(operation);\n const page = policy.work === \"page\" ? policy : undefined;\n const pageId = page === undefined ? undefined : (work.pageId ?? work.target?.pageId);\n const mutation = policy.mutation && work.readOnly !== true;\n const charge = work.readOnly === true ? \"none\" : policy.charge;\n const scope = (): ObservationScope => (pageId === undefined ? \"none\" : { pageId });\n\n const validate = (operation: BrowserOperation) =>\n work.validate?.(operation) ?? checkTarget(operation, work.target, work.generation);\n\n // While a navigation is loading, or a native wait observes the page, nothing else may change\n // that page; recovery stops or closes exactly that work, so it is not refused by it.\n const settledPage =\n page === undefined || pageId === undefined\n ? Effect.void\n : mutation && !page.recovery\n ? unreserved(operation, pageId)\n : page.refuseWhileWaiting\n ? waitFree(operation, pageId)\n : Effect.void;\n\n return validate(operation).pipe(\n Effect.andThen(\n owner.guard(operation, body, {\n // This span opens before validation, so a refused attempt is recorded too.\n traced: false,\n ...(work.admission === undefined ? {} : { admission: work.admission }),\n ...(work.timeoutMillis === undefined ? {} : { timeoutMillis: work.timeoutMillis }),\n ...(work.operationDeadline === undefined\n ? {}\n : { operationDeadline: work.operationDeadline }),\n ...(work.queueDeadline === undefined ? {} : { queueDeadline: work.queueDeadline }),\n ...(work.evidence === undefined ? {} : { evidence: work.evidence }),\n ...(work.performance === undefined ? {} : { performance: work.performance }),\n ...(work.waitUntil === undefined ? {} : { waitUntil: work.waitUntil }),\n mutation,\n charge: charge === \"none\" ? false : charge === \"host-read\" ? \"host-read\" : true,\n recovery: page?.recovery === true,\n targetScope: scope,\n mutationScope: () => (work.retainObservation === true ? \"none\" : scope()),\n // Registry work has no page to close, so an unknown outcome fences the owner.\n contain: () =>\n pageId === undefined\n ? undefined\n : containment(pageId, pageId === work.target?.pageId ? work.authority : undefined),\n preflight: validate(operation).pipe(\n Effect.andThen(settledPage),\n Effect.andThen(work.preflight ?? Effect.void),\n ),\n }),\n ),\n operationSpan(operation),\n );\n };\n\n /**\n * One native action under its operation's policy: the policy's checks on the exact target\n * (a held page, the document's readiness), the work's own preparation, then the action.\n */\n const execute = <A>(\n operation: ExecutedOperation,\n action: (driver: Driver, ticket: Ticket) => Promise<A>,\n work: Work = {},\n ) =>\n admit(\n operation,\n (ticket) =>\n readyNative(\n operation,\n ticket,\n async () => {\n if (work.target !== undefined) await prepare(operation, ticket, work.target);\n },\n async () => {\n await work.beforeNative?.(getDriver(), ticket);\n ticket.check();\n\n return action(getDriver(), ticket);\n },\n ),\n work,\n );\n\n const wait = (\n start: (\n driver: Driver,\n ticket: WaitTicket,\n target: DriverTarget,\n operationTicket: Ticket,\n ) => Promise<void>,\n timeoutMillis: number | undefined,\n work: Work & { readonly target: DriverTarget },\n operation: \"wait\" | \"settled\" = \"wait\",\n ): Effect.Effect<void, BrowserError> =>\n Effect.suspend(() => {\n const target = work.target;\n let owned: OwnedWait | undefined;\n\n return admit(\n operation,\n (ticket) =>\n native(operation, ticket, async () => {\n const driver = getDriver();\n const connection = activeConnection;\n\n if (connection === undefined)\n throw BrowserError.make({\n operation,\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n const admitted = owner.beginWait(ticket, target, connection, operation);\n\n owned = admitted;\n let started = false;\n\n try {\n await prepare(operation, ticket, target);\n ticket.check();\n await work.beforeNative?.(driver, ticket);\n ticket.check();\n admitted.start(() => start(driver, admitted.ticket, target, ticket));\n started = true;\n\n return admitted;\n } finally {\n // Canceled readiness may still be native work: retire only when its raw task exits.\n if (!started) admitted.ticket.retire();\n }\n }),\n {\n ...work,\n ...(timeoutMillis === undefined\n ? {}\n : { timeoutMillis: Math.min(timeoutMillis, work.timeoutMillis ?? timeoutMillis) }),\n // A page has one native wait slot; a wait never starts during a loading navigation.\n preflight: Effect.suspend(() =>\n owner.waitAvailable(target.pageId)\n ? unreserved(operation, target.pageId)\n : Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n ),\n ),\n },\n ).pipe(\n Effect.flatMap((operation) => operation.completed),\n Effect.ensuring(Effect.sync(() => owned?.cancel())),\n );\n }).pipe(\n Trace.span(\"Browser.wait.completed\", { attributes: { \"browser.operation\": operation } }),\n );\n\n /** Input receipt boundaries retain the admitted exact target and original owner clock. */\n const captureClickAt =\n (target: Target, ticket: Ticket): InputCapture =>\n async (dispatch, dispatched) => {\n const startedMonotonicNanos = clock.monotonicTimeNanosUnsafe();\n\n await dispatch();\n\n const receipt = {\n ...dispatched,\n target,\n kind: \"click\" as const,\n startedMonotonicNanos,\n completedMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n };\n\n ticket.recordInput?.(receipt);\n\n return receipt;\n };\n\n const makeOperations = (\n issued: Work & {\n readonly target: DriverTarget;\n readonly generation: number;\n },\n ) => {\n const browserTarget = issued.target;\n\n const run = <A>(\n operation: ExecutedOperation,\n action: (driver: Driver, ticket: Ticket, target: DriverTarget) => Promise<A>,\n operationOptions?: ExecutionOptions,\n ) =>\n execute(operation, (driver, ticket) => action(driver, ticket, browserTarget), {\n ...issued,\n ...operationOptions,\n });\n\n const operationTarget = (target: DriverTarget) =>\n Target.make({ generation: issued.generation, ...target });\n\n /**\n * Native input, stamped on the host monotonic clock that stamps captured frames, around\n * the native command alone: admission and readiness are over before the clock is read.\n */\n const input = (\n operation: \"pointer-move\" | \"hover\" | \"wheel\" | \"press\" | \"type\",\n action: (driver: Driver, ticket: Ticket, target: DriverTarget) => Promise<NativeInput>,\n operationOptions?: ExecutionOptions,\n inputTarget?: (target: DriverTarget) => DriverTarget,\n keys?: {\n readonly count: number;\n readonly countUnit: \"unicode-codepoints\" | \"logical-strokes\";\n },\n ) =>\n run(\n operation,\n async (driver, ticket, browserTarget) => {\n // What the input is sent to, read first: input may replace the document it reaches.\n const target = operationTarget(inputTarget?.(browserTarget) ?? browserTarget);\n const startedMonotonicNanos = clock.monotonicTimeNanosUnsafe();\n const dispatched = await action(driver, ticket, browserTarget);\n\n const receipt = {\n ...dispatched,\n kind: operation,\n target,\n startedMonotonicNanos,\n completedMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n };\n\n ticket.recordInput?.(receipt, keys);\n\n return receipt;\n },\n operationOptions,\n );\n\n /**\n * Dispatches under a short permit and leaves the browser loading outside it. The reservation\n * is taken under that same permit, so no other mutation can reach the page in between, and\n * it is released only on a known outcome: an unsettled operation whose scope closes, or a\n * navigation that fails after dispatch, fences the owner exactly as an interrupted mutation\n * always has. Interrupting a waiter on `completed` stops nothing; `stop` is the one way to.\n */\n const startNavigation = (\n url: string,\n timeoutMillis: number = limits.actionTimeoutMillis,\n operationOptions?: ExecutionOptions,\n ) =>\n // Native dispatch remains interruptible; registering ownership of its outcome is atomic.\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const requestedTimeout = Math.min(\n timeoutMillis,\n operationOptions?.timeoutMillis ?? timeoutMillis,\n );\n\n const loadingDeadline = Math.min(\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 + requestedTimeout,\n owner.lifetimeDeadline,\n operationOptions?.operationDeadline ?? Number.POSITIVE_INFINITY,\n );\n\n let active = true;\n let dismissals = 0;\n let beforeUnload = false;\n let dismissalUnknown = false;\n let rejected: BrowserError | undefined;\n let reconsider = () => {};\n\n const control: NavigationControl = {\n identity: {},\n beforeUnload: () => {\n if (!active) return { dismissed: () => {} };\n beforeUnload = true;\n dismissals++;\n let settled = false;\n\n return {\n dismissed: (confirmed) => {\n if (settled || !active) return;\n settled = true;\n dismissals--;\n if (!confirmed) dismissalUnknown = true;\n reconsider();\n },\n };\n },\n };\n\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n active = false;\n }),\n );\n\n const begun = yield* restore(\n run(\n \"navigate\",\n async (driver, ticket, browserTarget) => {\n const target = operationTarget(browserTarget);\n\n const loadingStarted = Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000;\n const remainingLifetime = owner.lifetimeDeadline - loadingStarted;\n\n if (remainingLifetime <= 0)\n throw BrowserError.make({\n operation: \"navigate\",\n reason: Reasons.Expired.make({}),\n outcome: \"undispatched\",\n });\n\n const loadingTimeout = loadingDeadline - loadingStarted;\n\n if (loadingTimeout <= 0)\n throw BrowserError.make({\n operation: \"navigate\",\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n });\n\n const navigation = await driver.beginNavigation(\n url,\n loadingTimeout,\n ticket,\n browserTarget,\n control,\n );\n\n // A continuation that outlived its permit takes no reservation: whatever gave that\n // permit up has already decided this dispatch's outcome.\n ticket.check();\n\n const reservation = owner.reserve(navigation.pageId);\n\n ticket.acknowledge?.();\n\n return {\n target,\n navigation,\n reservation,\n authority: pages.get(navigation.pageId),\n recoveryDeadline: Math.min(\n loadingStarted + loadingTimeout + 3000,\n owner.lifetimeDeadline,\n ),\n };\n },\n { ...operationOptions, timeoutMillis: requestedTimeout },\n ),\n );\n\n const { navigation, reservation } = begun;\n\n const execution = yield* Trace.start(\"Browser.navigation\", {\n attributes: { \"browser.operation\": \"navigate\" },\n });\n\n const executionIdentity =\n execution === undefined\n ? undefined\n : yield* Trace.capture.pipe(Effect.provideService(Tracer.ParentSpan, execution.span));\n\n const admission =\n begun.authority?.admission ??\n owner.pageAdmission(navigation.pageId, begun.target.generation);\n\n const outcome = yield* Deferred.make<string, BrowserError>();\n const timeoutRecovery = yield* Deferred.make<boolean>();\n const unknown = yield* Deferred.make<void>();\n let pendingDecision: Exit.Exit<string, BrowserError> | undefined;\n let stopDispatched = false;\n let timedOut = false;\n let deciding = false;\n\n const failed = (reason: BrowserError[\"reason\"]) =>\n Exit.fail(BrowserError.make({ operation: \"navigate\", reason, outcome: \"unknown\" }));\n\n const settleUnknown = yield* Effect.cached(\n Effect.suspend(() => {\n const decision = pendingDecision;\n\n if (decision === undefined || Deferred.isDoneUnsafe(outcome)) return Effect.void;\n\n return owner\n .contain(containment(navigation.pageId, begun.authority), begun.target.generation)\n .pipe(\n Effect.tap((contained) =>\n Effect.sync(() => {\n reservation.settle(contained._tag === \"PageClosed\" ? \"known\" : \"unknown\");\n Deferred.doneUnsafe(\n outcome,\n decision.pipe(\n Effect.mapError((error) =>\n BrowserError.make({\n ...error,\n outcome: \"unknown\",\n containment: contained,\n }),\n ),\n ),\n );\n }),\n ),\n Effect.asVoid,\n );\n }),\n ).pipe(Effect.map(Effect.uninterruptible));\n\n /**\n * A navigation has exactly one outcome, and whoever decides it first settles the\n * reservation. It is released before anyone waiting is told, so the operation a waiter\n * runs next is admitted rather than finding its own page still reserved.\n */\n const decide = (result: Exit.Exit<string, BrowserError>, known: boolean) => {\n if (deciding || Deferred.isDoneUnsafe(outcome)) return;\n deciding = true;\n active = false;\n execution?.end(result, { \"browser.navigation.retired\": known });\n if (known) {\n reservation.settle(\"known\");\n Deferred.doneUnsafe(outcome, result);\n deciding = false;\n } else {\n pendingDecision = result;\n Deferred.doneUnsafe(unknown, Effect.void);\n }\n Deferred.doneUnsafe(timeoutRecovery, Effect.succeed(false));\n };\n\n reconsider = () => {\n if (!active || rejected === undefined || dismissals !== 0 || stopDispatched) return;\n if (beforeUnload) {\n // Both facts are required: this goto rejected and its exact dialog was dismissed.\n decide(\n dismissalUnknown ? Exit.fail(rejected) : failed(Reasons.Interrupted.make({})),\n !dismissalUnknown,\n );\n } else if (navigation.mainFrame === true && rejected.reason._tag === \"Timeout\") {\n timedOut = true;\n Deferred.doneUnsafe(timeoutRecovery, Effect.succeed(true));\n } else {\n decide(Exit.fail(rejected), false);\n }\n };\n\n navigation.settled.then(\n (url) => {\n if (!stopDispatched) decide(Exit.succeed(url), true);\n },\n (error: unknown) => {\n if (stopDispatched || Deferred.isDoneUnsafe(outcome)) return;\n\n rejected = publicError(error, \"navigate\", {\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n });\n reconsider();\n },\n );\n\n // A fence already cleared the reservation; this only releases anyone still waiting.\n const aborted = () =>\n decide(failed(timedOut ? Reasons.Timeout.make({}) : Reasons.Stale.make({})), true);\n\n reservation.signal.addEventListener(\"abort\", aborted, {\n once: true,\n });\n // Left unsettled, nothing knows what the browser did with it.\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n decide(failed(timedOut ? Reasons.Timeout.make({}) : Reasons.Stale.make({})), false);\n reservation.signal.removeEventListener(\"abort\", aborted);\n }).pipe(Effect.andThen(settleUnknown)),\n );\n yield* Deferred.await(unknown).pipe(Effect.andThen(settleUnknown), Effect.forkScoped);\n\n const stopTarget = { pageId: navigation.pageId, frameId: begun.target.frameId };\n\n const stop = yield* makeNavigationStopCoordinator(\n () => Deferred.isDoneUnsafe(outcome),\n (onDispatch, retainSetup, deadline) =>\n admit(\n \"navigate-stop\",\n (ticket) =>\n Effect.suspend(() =>\n deadline !== undefined && admission.native.stopSetupPending !== undefined\n ? Deferred.await(admission.native.stopSetupPending)\n : Effect.void,\n ).pipe(\n Effect.andThen(\n native(\"navigate-stop\", ticket, () =>\n navigation.stop(\n ticket,\n () => !Deferred.isDoneUnsafe(outcome),\n () => {\n onDispatch();\n stopDispatched = true;\n },\n () => {\n const settle = owner.beginStopSetup(admission, activeConnection);\n\n if (settle === undefined)\n throw BrowserError.make({\n operation: \"navigate-stop\",\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n });\n const retired = retainSetup();\n\n return () => {\n settle();\n retired();\n };\n },\n ),\n ),\n ),\n Effect.timeoutOrElse({\n duration: Math.min(3000, ticket.remainingMillis()),\n orElse: () =>\n Effect.fail(\n BrowserError.make({\n operation: \"navigate-stop\",\n reason: Reasons.Timeout.make({}),\n outcome: ticket.dispatched ? \"unknown\" : \"undispatched\",\n }),\n ),\n }),\n ),\n {\n target: stopTarget,\n generation: begun.target.generation,\n ...(begun.authority === undefined ? {} : { authority: begun.authority }),\n // Stopping is recovery: the lifecycle barrier and policy cleanup do not refuse it.\n validate: (operation) =>\n checkTarget(operation, stopTarget, begun.target.generation, { recovery: true }),\n ...(deadline === undefined ? {} : { waitUntil: deadline }),\n },\n ),\n () =>\n decide(\n failed(timedOut ? Reasons.Timeout.make({}) : Reasons.Interrupted.make({})),\n true,\n ),\n );\n\n // One operation-scoped supervisor, signalled only by the exact native timeout classifier.\n // Its absolute deadline bounds joined public stops, permit wait and late setup retirement too.\n yield* Deferred.await(timeoutRecovery).pipe(\n Effect.flatMap((recover) =>\n recover\n ? stop.recover(begun.recoveryDeadline).pipe(\n Trace.span(\"Browser.navigation.recovery\", {\n parent: executionIdentity?.parent,\n }),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (Exit.isFailure(exit)) decide(failed(Reasons.Timeout.make({})), false);\n }),\n ),\n )\n : Effect.void,\n ),\n Effect.ignoreCause,\n Effect.forkScoped,\n );\n\n return {\n target: begun.target,\n completed: Deferred.await(outcome).pipe(Trace.span(\"Browser.navigation.wait\")),\n /**\n * The browser's acknowledgement is the known outcome. Playwright's own promise is not\n * waited for: an aborted parse fires no DOMContentLoaded, so it only ever times out.\n */\n stop: stop.stop,\n };\n }),\n ).pipe(Effect.provideService(Clock.Clock, clock));\n\n return {\n startNavigation,\n // The same machinery, scoped to the call: leaving it unsettled fences, as it always has.\n navigate: (url: string, timeoutMillis?: number, operationOptions?: ExecutionOptions) =>\n Effect.scoped(\n startNavigation(url, timeoutMillis, operationOptions).pipe(\n Effect.flatMap((operation) => operation.completed),\n ),\n ),\n readText: (selector?: string, operationOptions?: ExecutionOptions) =>\n run(\n \"read-text\",\n (driver, ticket, browserTarget) =>\n driver.readText(selector, options.maxReturnedBytes, ticket, browserTarget),\n operationOptions,\n ),\n click: (\n target: DeferredElementTarget,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n run(\n \"click\",\n (driver, ticket, browserTarget) =>\n driver.click(\n elementTarget(target),\n ticket,\n captureClickAt(\n operationTarget(effectiveTarget(elementTarget(target), browserTarget)),\n ticket,\n ),\n policy,\n effectiveTarget(elementTarget(target), browserTarget),\n ),\n operationOptions,\n ),\n fill: (\n target: DeferredElementTarget,\n value: string,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n run(\n \"fill\",\n (driver, ticket, browserTarget) =>\n driver.fill(\n elementTarget(target),\n value,\n ticket,\n policy,\n effectiveTarget(elementTarget(target), browserTarget),\n ),\n operationOptions,\n ),\n scroll: (x: number, y: number, operationOptions?: ExecutionOptions) =>\n run(\n \"scroll\",\n async (driver, ticket, browserTarget) => {\n const startedMonotonicNanos = clock.monotonicTimeNanosUnsafe();\n const result = await driver.scroll(x, y, ticket, browserTarget);\n\n if (ticket.performance === undefined)\n ticket.recordScroll?.({\n target: browserTarget,\n x,\n y,\n startedMonotonicNanos,\n completedMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n });\n\n return result;\n },\n operationOptions,\n ),\n pointerMove: (to: NativePoint, operationOptions?: ExecutionOptions) =>\n input(\n \"pointer-move\",\n (driver, ticket, browserTarget) => driver.pointerMove(to, ticket, browserTarget),\n operationOptions,\n ),\n hover: (\n target: DeferredElementTarget,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n input(\n \"hover\",\n (driver, ticket, browserTarget) =>\n driver.hover(\n elementTarget(target),\n ticket,\n policy,\n effectiveTarget(elementTarget(target), browserTarget),\n ),\n operationOptions,\n (browserTarget) => effectiveTarget(elementTarget(target), browserTarget),\n ),\n wheel: (\n deltaX: number,\n deltaY: number,\n at?: NativePoint,\n operationOptions?: ExecutionOptions,\n ) =>\n input(\n \"wheel\",\n (driver, ticket, browserTarget) =>\n driver.wheel(deltaX, deltaY, at, ticket, browserTarget),\n operationOptions,\n ),\n press: (\n key: string,\n modifiers: ReadonlyArray<KeyModifier>,\n into?: DeferredElementTarget,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n input(\n \"press\",\n (driver, ticket, browserTarget) =>\n driver.press(\n key,\n modifiers,\n into === undefined ? undefined : elementTarget(into),\n ticket,\n policy,\n effectiveTarget(into === undefined ? undefined : elementTarget(into), browserTarget),\n ),\n operationOptions,\n (browserTarget) =>\n effectiveTarget(into === undefined ? undefined : elementTarget(into), browserTarget),\n { count: 1, countUnit: \"logical-strokes\" },\n ),\n type: (\n text: string,\n into?: DeferredElementTarget,\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n input(\n \"type\",\n (driver, ticket, browserTarget) =>\n driver.type(\n text,\n into === undefined ? undefined : elementTarget(into),\n ticket,\n policy,\n effectiveTarget(into === undefined ? undefined : elementTarget(into), browserTarget),\n ),\n operationOptions,\n (browserTarget) =>\n effectiveTarget(into === undefined ? undefined : elementTarget(into), browserTarget),\n { count: codePointCount(text), countUnit: \"unicode-codepoints\" },\n ),\n screenshot: (full: boolean, operationOptions?: ExecutionOptions) =>\n run(\n \"screenshot\",\n (driver, ticket, browserTarget) =>\n driver.screenshot(full, options.maxReturnedBytes, ticket, browserTarget),\n operationOptions,\n ),\n };\n };\n\n /** The runtime supplies its remaining budget; endpoint sources apply their own wait limits. */\n const remainingMillis = () =>\n Math.max(\n 1,\n Math.ceil(owner.lifetimeDeadline - Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000),\n );\n\n const connectionUrl = (operation: BrowserOperation) =>\n Effect.suspend(() => acquired.connection(remainingMillis())).pipe(\n Effect.mapError((error) =>\n BrowserError.make({ operation, reason: error.reason, outcome: error.outcome }),\n ),\n );\n\n const connected = yield* Effect.cached(\n owner\n .guard(\n \"connect\",\n (ticket) =>\n connectionUrl(\"connect\").pipe(\n Effect.flatMap((url) => connectNative(url, options.driver)),\n Effect.andThen(\n native(\"connect\", ticket, async () => {\n initialTarget = getDriver().selected();\n const targetId = await getDriver().selectedTargetId();\n\n ticket.check();\n initialInfo = {\n pageId: initialTarget.pageId,\n targetId,\n url: \"\",\n title: \"\",\n selected: true,\n };\n initialAuthority = registerPage(initialInfo, initialTarget, ticket.generation);\n }),\n ),\n Effect.tap(() =>\n Effect.sync(() => {\n owner.transition(\"open\");\n }),\n ),\n ),\n { phases: [\"acquiring\"], charge: false, verifyAfter: false },\n )\n .pipe(\n Effect.onError(() => closeScope),\n Effect.onInterrupt(() => closeScope),\n ),\n );\n\n const execution = () => {\n const port = getDriver().pageControl;\n\n if (port === undefined)\n throw BrowserError.make({\n operation: \"page-control\",\n reason: Reasons.Unsupported.make({}),\n outcome: \"undispatched\",\n });\n\n return port;\n };\n\n const makePageControls = (authority: PageRecord, target: DriverTarget, generation: number) => {\n const frameAuthority = authority.frames.get(target.frameId);\n\n // Validation failures keep the operation the caller asked for.\n const validate = (operation: BrowserOperation) =>\n Effect.suspend(() =>\n authority.phase !== \"open\" || frameAuthority?.detached === true\n ? Effect.fail(unavailable(operation, authority))\n : checkTarget(operation, target, generation),\n );\n\n /** The issued capability every operation on it acts through. */\n const bound = { validate, target, generation, authority };\n\n const targetData = (actual: DriverTarget = target) => Target.make({ generation, ...actual });\n\n const controls = {\n resolve: (descriptor: Descriptor, guard: ResolveGuard, operationOptions?: ExecutionOptions) =>\n execute(\n \"resolve\",\n (driver, ticket) => driver.resolveDescriptor(descriptor, ticket, target, guard),\n { ...bound, ...operationOptions },\n ),\n settled: (\n settle: SettledOptions,\n operationOptions?: ExecutionOptions,\n ): Effect.Effect<SettledEvidence, BrowserError> =>\n Effect.suspend(() => {\n let evidence: SettledEvidence | undefined;\n\n return wait(\n async (driver, ticket, resolved, operationTicket) => {\n evidence = await driver.settled(settle, ticket, resolved);\n operationTicket.recordSettled?.(evidence, resolved);\n },\n settle.withinMillis,\n { ...bound, ...operationOptions },\n \"settled\",\n ).pipe(\n Effect.flatMap(() =>\n evidence === undefined\n ? Effect.fail(\n BrowserError.make({\n operation: \"settled\",\n reason: Reasons.Incomplete.make({}),\n outcome: \"undispatched\",\n }),\n )\n : Effect.succeed(evidence),\n ),\n );\n }),\n pageControl: {\n state: (page: PageInfo, operationOptions?: ExecutionOptions) =>\n execute(\"page-state\", (_driver, ticket) => execution().state(page, ticket), {\n ...bound,\n ...operationOptions,\n pageId: page.pageId,\n }),\n suspend: (page: PageInfo, operationOptions?: ExecutionOptions) =>\n execute(\"page-suspend\", (_driver, ticket) => execution().suspend(page, ticket), {\n ...bound,\n ...operationOptions,\n pageId: page.pageId,\n }),\n resume: (receipt: PageSuspension, operationOptions?: ExecutionOptions) =>\n execute(\"page-resume\", (_driver, ticket) => execution().resume(receipt, ticket), {\n ...bound,\n ...operationOptions,\n pageId: receipt.pageId,\n }),\n },\n operations: makeOperations(bound),\n observe: (reading: Reading = { scope: \"document\" }, operationOptions?: ExecutionOptions) =>\n textBudget(\"observe\", reading.maxTextBytes).pipe(\n Effect.flatMap((bytes) =>\n admit(\n \"observe\",\n (ticket) =>\n observeInside(\n ticket,\n bytes,\n reading.maxControls ?? 32,\n reading.scope,\n reading.match,\n target,\n ),\n { ...bound, ...operationOptions },\n ),\n ),\n ),\n /**\n * Passive: not a mutation, so the action observation and the selection are left exactly as\n * they were. A held page is refused rather than woken to be read.\n */\n checkpoint: (\n reading: Omit<Reading, \"scope\"> & { readonly picture: boolean },\n operationOptions?: ExecutionOptions,\n ) =>\n textBudget(\"checkpoint\", reading.maxTextBytes).pipe(\n Effect.flatMap((bytes) =>\n execute(\n \"checkpoint\",\n async (driver, ticket) => {\n const capturedTarget = targetData();\n const revision = owner.revision(capturedTarget.pageId);\n const startedMonotonicNanos = clock.monotonicTimeNanosUnsafe();\n\n const sampled = await driver.checkpoint(\n bytes,\n reading.maxControls ?? 32,\n reading.picture ? options.maxReturnedBytes : undefined,\n ticket,\n target,\n );\n\n return {\n ...sampled,\n target: capturedTarget,\n revision,\n startedMonotonicNanos,\n completedMonotonicNanos: clock.monotonicTimeNanosUnsafe(),\n };\n },\n { ...bound, ...operationOptions },\n ),\n ),\n ),\n controlFacts: (reference: ObservedElement, operationOptions?: ExecutionOptions) =>\n execute(\n \"control-facts\",\n (driver, ticket) => driver.controlFacts(reference, ticket, target),\n { ...bound, ...operationOptions },\n ),\n selectOption: (\n reference: ObservedElement | ResolvedElement | (() => ObservedElement | ResolvedElement),\n options: NativeSelectOptions | (() => NativeSelectOptions),\n policy?: AdmissionPolicy,\n operationOptions?: ExecutionOptions,\n ) =>\n execute(\n \"select-option\",\n (driver, ticket) => {\n const ref = typeof reference === \"function\" ? reference() : reference;\n\n return driver.selectOption(\n ref,\n typeof options === \"function\" ? options() : options,\n ticket,\n policy,\n effectiveTarget(ref, target),\n );\n },\n { ...bound, ...operationOptions },\n ),\n /**\n * Each step is its own admitted, charged mutation that leaves the observation usable for the\n * next one; anything else that changes the page still retires it. The form ends at the first\n * refusal, and whatever it dispatched retires the observation when it ends, however it ends.\n */\n fillForm: (\n form: FormSteps,\n policy: AdmissionPolicy | undefined,\n settings: FormSettings,\n operationOptions?: ExecutionOptions,\n ) =>\n Effect.suspend(() => {\n // Each field, the verification read and the submit is its own admitted action, so each\n // captures its own action and queue deadlines when requested. A bound the caller already\n // captured, such as a plan step's, still caps every one of them.\n const formOptions: ExecutionOptions = { ...operationOptions };\n\n // The page whose observation the steps kept usable, known once one of them dispatched.\n let pageId: string | undefined;\n\n const body = Effect.gen(function* () {\n const fields: Array<{\n elementId: string;\n status: \"set\" | \"unchanged\";\n input?: InputReceipt;\n }> = [];\n\n const states: Array<string | undefined> = [];\n let url = \"\";\n\n const finish = (submitted: boolean): FormOutcome => ({ fields, submitted, url });\n\n const stop = (\n stage: \"field\" | \"verify\" | \"submit\",\n error: BrowserError,\n elementId?: string,\n ): FormOutcome => ({\n ...finish(false),\n stopped: { stage, error, ...(elementId === undefined ? {} : { elementId }) },\n });\n\n for (const [fieldIndex, step] of form.fields.entries()) {\n formOptions.phase?.(\"Field\", fieldIndex);\n\n const exit = yield* Effect.exit(\n execute(\n \"fill-form\",\n async (driver, ticket) => {\n try {\n const reference = step.reference();\n\n return await driver.formStep(\n reference,\n step.field(),\n ticket,\n policy,\n settings.settleMillis,\n captureClickAt(targetData(effectiveTarget(reference, target)), ticket),\n effectiveTarget(reference, target),\n );\n } finally {\n if (ticket.dispatched) pageId ??= target.pageId;\n }\n },\n {\n ...bound,\n ...formOptions,\n ...(form.retainObservation ? { retainObservation: true } : {}),\n },\n ),\n );\n\n if (Exit.isFailure(exit)) {\n const error = Cause.findErrorOption(exit.cause);\n\n // Interruption and defects keep their own meaning. A form that has completed no\n // step fails exactly as its first step did.\n if (Option.isNone(error) || fields.length === 0)\n return yield* Effect.failCause(exit.cause);\n\n return stop(\"field\", error.value, step.reportedId);\n }\n const done = exit.value;\n\n fields.push({\n elementId: step.reportedId,\n status: done.status,\n ...(done.input === undefined ? {} : { input: done.input }),\n });\n states.push(done.state);\n url = done.url;\n if (!done.reached)\n return stop(\n \"field\",\n BrowserError.make({\n operation: \"fill-form\",\n reason: Reasons.Failed.make({}),\n outcome: \"rejected\",\n }),\n step.reportedId,\n );\n }\n\n if (settings.verify) {\n formOptions.phase?.(\"Verification\");\n\n // Not charged, like revalidation: it sends no input and reads nodes already issued.\n const exit = yield* Effect.exit(\n execute(\n \"fill-form\",\n (driver, ticket) =>\n driver.formState(\n form.fields.map((step) => step.reference()),\n ticket,\n target,\n ),\n { ...bound, ...formOptions, readOnly: true },\n ),\n );\n\n if (Exit.isFailure(exit)) {\n const error = Cause.findErrorOption(exit.cause);\n\n if (Option.isNone(error)) return yield* Effect.failCause(exit.cause);\n\n return stop(\"verify\", error.value);\n }\n for (const [index, step] of form.fields.entries()) {\n const expected = states[index];\n\n if (expected === undefined || exit.value[index] !== expected)\n return stop(\n \"verify\",\n BrowserError.make({\n operation: \"fill-form\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n }),\n step.reportedId,\n );\n }\n }\n\n const submit = form.submit;\n\n if (submit === undefined) return finish(false);\n\n formOptions.phase?.(\"Submit\");\n\n const exit = yield* Effect.exit(\n execute(\n \"fill-form\",\n (driver, ticket) => {\n const reference = submit.reference();\n\n return driver.formSubmit(\n reference,\n ticket,\n captureClickAt(targetData(effectiveTarget(reference, target)), ticket),\n policy,\n effectiveTarget(reference, target),\n );\n },\n { ...bound, ...formOptions },\n ),\n );\n\n if (Exit.isFailure(exit)) {\n const error = Cause.findErrorOption(exit.cause);\n\n if (Option.isNone(error)) return yield* Effect.failCause(exit.cause);\n\n return stop(\"submit\", error.value, submit.reportedId);\n }\n url = exit.value.url;\n\n return { ...finish(true), submitInput: exit.value.input };\n });\n\n // The steps kept the observation usable for each other only. A submit that dispatched\n // has already retired it, as every other mutation does.\n return body.pipe(\n Effect.ensuring(\n Effect.sync(() => {\n if (pageId !== undefined) owner.invalidate(\"observation\", { pageId });\n }),\n ),\n );\n }),\n /** Not charged: it sends no input and reads one node the caller was already given. */\n revalidate: (reference: ObservedElement, operationOptions?: ExecutionOptions) =>\n execute(\"revalidate\", (driver, ticket) => driver.revalidate(reference, ticket, target), {\n ...bound,\n ...operationOptions,\n }),\n // Inspecting readiness is not an action: it charges nothing and mutates nothing.\n readiness: (operationOptions?: ExecutionOptions) =>\n execute(\"ready\", (driver, ticket) => driver.documentReadiness(ticket, target), {\n ...bound,\n ...operationOptions,\n }),\n describe: (operationOptions?: ExecutionOptions) =>\n execute(\"describe-page\", (driver, ticket) => driver.describePage(authority.info, ticket), {\n ...bound,\n ...operationOptions,\n }),\n listFrames: (operationOptions?: ExecutionOptions) =>\n execute(\"list-frames\", (driver, ticket) => driver.listFrames(ticket, authority.info), {\n ...bound,\n ...operationOptions,\n }),\n close: (operationOptions?: ExecutionOptions) =>\n Effect.suspend(() => {\n const page = authority.info;\n\n const deadline = Math.min(\n Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 +\n Math.min(\n operationOptions?.timeoutMillis ?? limits.actionTimeoutMillis,\n limits.actionTimeoutMillis,\n ),\n owner.lifetimeDeadline,\n );\n\n // Closure has reserved recovery admission, which neither a policy cleanup nor a\n // lifecycle barrier refuses.\n const stale = () => unavailable(\"close-page\", authority, { recovery: true });\n\n const checked = Effect.suspend(() =>\n generation !== owner.state.generation || pages.get(page.pageId) !== authority\n ? Effect.fail(stale())\n : Effect.void,\n );\n\n const joined = (attempt: Deferred.Deferred<boolean>) =>\n within(Deferred.await(attempt), deadline, () =>\n BrowserError.make({\n operation: \"close-page\",\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n }),\n ).pipe(\n Effect.flatMap((closed) =>\n closed\n ? Effect.void\n : owner.contain(containment(page.pageId, authority), generation).pipe(\n Effect.flatMap((containment) =>\n Effect.fail(\n BrowserError.make({\n operation: \"close-page\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n containment,\n }),\n ),\n ),\n ),\n ),\n );\n\n if (authority.attempt !== undefined)\n return checked.pipe(Effect.andThen(joined(authority.attempt)));\n\n return admit(\n \"close-page\",\n (ticket) =>\n Effect.gen(function* () {\n yield* native(\"close-page\", ticket, () => getDriver().resolvePage(page, ticket));\n\n if (authority.attempt !== undefined) return yield* joined(authority.attempt);\n const attempt = Deferred.makeUnsafe<boolean>();\n\n return yield* native(\"close-page\", ticket, async () => {\n try {\n await getDriver().closePage(page, ticket, () => {\n pages.attempting(authority, attempt);\n revokePage(page.pageId, ticket.signal);\n });\n pageClosed(page.pageId);\n } catch (error) {\n if (authority.attempt === attempt)\n Deferred.doneUnsafe(attempt, Effect.succeed(authority.phase === \"closed\"));\n throw error;\n }\n });\n }),\n {\n ...bound,\n ...operationOptions,\n // A paused page may still be closed; only its registration must be current.\n validate: () => checked,\n waitUntil: deadline,\n preflight: Effect.suspend(() =>\n authority.phase !== \"open\" && authority.phase !== \"paused\"\n ? Effect.fail(stale())\n : Effect.void,\n ),\n },\n );\n }).pipe(Effect.provideService(Clock.Clock, clock)),\n resize: (viewport: Viewport, operationOptions?: ExecutionOptions) =>\n execute(\"resize\", (driver, ticket) => driver.resize(viewport, ticket, target), {\n ...bound,\n ...operationOptions,\n }),\n waitFor: (\n selector: string,\n state: \"visible\" | \"hidden\" | \"attached\" | \"detached\",\n operationOptions?: ExecutionOptions,\n ) =>\n wait(\n (driver, ticket, resolved) => driver.waitFor(selector, state, ticket, resolved),\n undefined,\n { ...bound, ...operationOptions },\n ),\n waitForElement: (request: WaitForElementRequest, operationOptions?: ExecutionOptions) =>\n wait(\n (driver, ticket, target) =>\n driver.waitForElement(request.reference, request.state, ticket, target),\n request.timeoutMillis,\n { ...bound, ...operationOptions },\n ),\n clickAndWait: (element: string | ObservedElement, operationOptions?: ExecutionOptions) =>\n execute(\n \"click-and-wait\",\n (driver, ticket) =>\n driver.clickAndWait(element, ticket, captureClickAt(targetData(), ticket), target),\n { ...bound, ...operationOptions },\n ),\n clickForDownload: (element: string | ObservedElement, operationOptions?: ExecutionOptions) =>\n execute(\n \"download-action\",\n (driver, ticket) => driver.clickForDownload(element, ticket, target),\n { ...bound, ...operationOptions },\n ),\n selectFiles: (\n element: string | ObservedElement,\n files: ReadonlyArray<NativeFileSelection>,\n operationOptions?: ExecutionOptions,\n ) =>\n execute(\n \"select-files\",\n (driver, ticket) => driver.selectFiles(element, files, ticket, target),\n { ...bound, ...operationOptions },\n ),\n clickForFileSelection: (\n element: string | ObservedElement,\n files: ReadonlyArray<NativeFileSelection>,\n operationOptions?: ExecutionOptions,\n ) =>\n execute(\n \"file-chooser\",\n (driver, ticket) => driver.clickForFileSelection(element, files, ticket, target),\n { ...bound, ...operationOptions },\n ),\n validate,\n };\n\n // A plan step's own needs on this page, each admitted under its operation's policy.\n const executeStep = makePlanSteps({\n target,\n chargeHostRead: owner.chargeHostRead,\n controls: {\n operations: controls.operations,\n selectOption: controls.selectOption,\n settled: controls.settled,\n fillForm: controls.fillForm,\n checkpoint: controls.checkpoint,\n scrollTo: (element, operationOptions) =>\n execute(\n \"scroll\",\n (driver, ticket) => {\n const ref = element();\n\n return driver.scrollTo(ref, ticket, ref.target);\n },\n { ...bound, ...operationOptions },\n ),\n pause: (milliseconds, operationOptions) =>\n admit(\n \"wait\",\n (ticket) =>\n native(\"wait\", ticket, async () => {\n await prepare(\"wait\", ticket, target, { document: false });\n await operationOptions.beforeNative?.(getDriver(), ticket);\n }).pipe(\n Effect.andThen(Effect.sleep(milliseconds)),\n Effect.andThen(Effect.sync(() => ticket.check())),\n ),\n { ...bound, ...operationOptions },\n ),\n waitFor: (element, state, timeoutMillis, operationOptions) =>\n wait(\n (driver, ticket) => {\n const ref = element();\n\n return driver.waitForElement(ref, state, ticket, ref.target);\n },\n timeoutMillis,\n { ...bound, ...operationOptions },\n ),\n expectations: (conditions, operationOptions) =>\n execute(\n \"run\",\n async (driver, ticket) => {\n await driver.expectations(conditions, ticket, target);\n },\n { ...bound, ...operationOptions },\n ),\n },\n });\n\n const plans = makePlanExecution({\n clock,\n validate: validate(\"run\"),\n lifetimeDeadline: owner.lifetimeDeadline,\n actionTimeoutMillis: limits.actionTimeoutMillis,\n newId: uuid,\n newSeed: crypto.randomInt,\n publish: () => {\n const releaseDomain = domain.retirement.retain();\n const releasePage = authority.retirement.retain();\n\n return {\n append: planPublisher(domain.store, { generation, ...target, document: null }),\n release: () => {\n releasePage();\n releaseDomain();\n },\n };\n },\n retired: Effect.suspend(() =>\n Effect.raceFirst(domain.retirement.requested, authority.retirement.requested),\n ),\n reserve: Effect.suspend(() => {\n const pageId = target.pageId;\n const count = pageRuns.get(pageId) ?? 0;\n\n if (activeRuns >= 128 || count >= 32)\n return Effect.fail(\n BrowserError.make({\n operation: \"run\",\n reason: Reasons.Limit.make({\n dimension: \"runs\",\n maximum: count >= 32 ? 32 : 128,\n observed: count >= 32 ? count : activeRuns,\n }),\n outcome: \"undispatched\",\n }),\n );\n activeRuns++;\n pageRuns.set(pageId, count + 1);\n let released = false;\n\n return Effect.succeed(() => {\n if (released) return;\n released = true;\n activeRuns--;\n const remaining = (pageRuns.get(pageId) ?? 1) - 1;\n\n if (remaining === 0) pageRuns.delete(pageId);\n else pageRuns.set(pageId, remaining);\n });\n }),\n executeStep,\n });\n\n return { ...controls, plans };\n };\n\n const registerPage = (info: PageInfo, target: DriverTarget, generation: number) => {\n let page = pages.get(info.pageId);\n\n if (page === undefined || page.identity.generation !== generation) {\n const identity = Target.make({ generation, ...target });\n const store = domain.store;\n let terminal: Terminal | null = null;\n\n const retirement = makeRetirement((reason) => {\n // Native closure can request retirement before the original containment receipt settles.\n // Logical owners retain this record until that confirmed outcome is available.\n const terminalReason = page?.containment._tag === \"PageClosed\" ? \"contained\" : reason;\n\n const result = publish(store, {\n target: { ...identity, document: null },\n correlation: null,\n event: { _tag: \"Terminal\", scope: \"page\", reason: terminalReason },\n });\n\n terminal = Object.freeze({\n cursor:\n result._tag === \"Appended\"\n ? Object.freeze({\n storeId: result.event.storeId,\n clockId: result.event.clockId,\n sequence: result.event.sequence,\n })\n : store.cursor(),\n at: result._tag === \"Appended\" ? result.event.at : store.now(),\n scope: \"page\",\n reason: terminalReason,\n });\n });\n\n page = pages.add({\n identity,\n admission: owner.pageAdmission(info.pageId, generation),\n info,\n paused: owner.paused(info.pageId),\n store,\n retirement,\n terminal: () => terminal,\n });\n }\n const record = page;\n\n return {\n record,\n timeline: journal.forPage(\n record.store,\n info.pageId,\n record.identity.generation,\n () => record.terminal,\n ),\n controls: makePageControls(record, target, generation),\n status: Effect.sync((): PageStatus =>\n Object.freeze({\n identity: Object.freeze({ ...record.identity }),\n phase:\n record.phase === \"closed\"\n ? \"closed\"\n : record.identity.generation !== owner.state.generation\n ? \"stale\"\n : record.phase,\n containment: Object.freeze({ ...record.containment }),\n admission: owner.admissionSnapshot(record.admission),\n }),\n ),\n };\n };\n\n /**\n * Issuing authenticates a page and registers it; it is not work on that page. It takes the\n * registry permit, so it never waits for, or is refused by, the page's own operations.\n */\n const page = (info: PageInfo, operationOptions?: ExecutionOptions) =>\n execute(\n \"target\",\n async (driver, ticket) => {\n const target = await driver.resolvePage(info, ticket);\n\n ticket.check();\n\n return registerPage(info, target, ticket.generation);\n },\n operationOptions,\n );\n\n // A generation change retires every issued capability. Rebuild from the same live connection\n // while the lifecycle permit is still held, before new operations can be admitted.\n const refreshPages = (ticket: Ticket, restore = false) =>\n native(\"list-pages\", ticket, async () => {\n const current = getDriver();\n const inventory = await current.listPages(ticket);\n const resolved = [];\n\n for (const info of inventory) {\n const target = await current.resolvePage(info, ticket);\n\n ticket.check();\n resolved.push({ info, target });\n }\n ticket.check();\n\n const fresh = Inventory.make({\n generation: ticket.generation,\n pages: Object.freeze(inventory.map((info) => Object.freeze({ ...info }))),\n });\n\n for (const { info, target } of resolved) {\n if (restore) {\n restorePageAuthority(info.pageId);\n }\n registerPage(info, target, ticket.generation);\n }\n\n return Object.freeze(fresh);\n });\n\n const listPages = (operationOptions?: ExecutionOptions) =>\n admit(\n \"list-pages\",\n (ticket) => refreshPages(ticket).pipe(Effect.map((inventory) => inventory.pages)),\n operationOptions,\n );\n\n const initialPage = () => {\n if (initialAuthority === undefined)\n throw BrowserError.make({\n operation: \"target\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n });\n\n return initialAuthority;\n };\n\n /**\n * Waits until `drained` holds, or fails `Timeout/undispatched` at the bound. The owner signals\n * settled work; driver and binding cleanup is rechecked meanwhile.\n */\n const drainAdmitted = (operation: BrowserOperation, ticket: Ticket, drained: () => boolean) =>\n Effect.gen(function* () {\n while (!drained()) {\n yield* owner.nextChange.pipe(\n Effect.timeoutOrElse({ duration: Duration.millis(25), orElse: () => Effect.void }),\n );\n // A settlement can complete the signal synchronously; decide on a later turn.\n yield* Effect.yieldNow;\n }\n }).pipe((drain) =>\n within(\n drain,\n Math.min(ticket.deadline, Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 + 3000),\n () =>\n BrowserError.make({\n operation,\n reason: Reasons.Timeout.make({}),\n outcome: \"undispatched\",\n }),\n ),\n );\n\n const lifecycle = <A, E, R>(\n operation: BrowserOperation,\n supported: () => boolean,\n work: () => Effect.Effect<A, E, R>,\n ): Effect.Effect<A, E | BrowserError, R> =>\n // The barrier is installed and its release registered in one uninterruptible step, so an\n // interruption cannot leave every later operation refused as busy.\n Effect.acquireUseRelease(\n Effect.suspend(() => {\n if (!supported())\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Unsupported.make({}),\n outcome: \"undispatched\",\n }),\n );\n // An ordinary active caller owns its deadline. A lifecycle request refuses before\n // installing its barrier rather than converting that caller's latency into uncertainty.\n if (owner.hasActive())\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n );\n const barrier = owner.pauseAdmission();\n\n if (barrier === undefined)\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Busy.make({}),\n outcome: \"undispatched\",\n }),\n );\n activeBindings?.pauseAdmission();\n\n return Effect.succeed(barrier);\n }),\n () => Effect.suspend(work),\n (barrier) =>\n Effect.sync(() => {\n if (owner.resumeAdmission(barrier) && owner.state.phase === \"open\")\n activeBindings?.resumeAdmission();\n }),\n );\n\n const controls = {\n listPages,\n selectPage: (page: PageInfo, operationOptions?: ExecutionOptions) =>\n execute(\n \"select-page\",\n async (driver, ticket) => {\n const target = await driver.resolvePage(page, ticket);\n\n ticket.check();\n registerPage(page, target, ticket.generation);\n await driver.selectPage(page, ticket);\n },\n operationOptions,\n ),\n /**\n * Creation and adoption use the registry lane, independently of Page work. The registration\n * it returns is what a Page is issued from, so creating and issuing are one admission.\n */\n createPage: (operationOptions?: ExecutionOptions) =>\n execute(\n \"new-page\",\n async (driver, ticket) => {\n const info = await driver.newPage(ticket);\n\n ticket.check();\n const target = await driver.resolvePage(info, ticket);\n\n return registerPage(info, target, ticket.generation);\n },\n operationOptions,\n ),\n\n monotonicTimeNanos: clock.monotonicTimeNanos,\n timeline: journal.timeline,\n pageEvents: journal.pageEvents,\n initialPage,\n page,\n frame: (\n info: PageInfo,\n frame: FrameInfo,\n generation: number,\n operationOptions?: ExecutionOptions,\n ) =>\n // Like a Page, a Frame is issued under the registry permit, not its page's own.\n execute(\n \"target\",\n async (driver, ticket) => {\n const target = await driver.resolveFrame(info, frame, ticket);\n\n ticket.check();\n const page = pages.get(info.pageId);\n\n if (page === undefined || page.phase !== \"open\")\n throw BrowserError.make({\n operation: \"target\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n });\n if (!page.frames.has(target.frameId) && page.frames.size >= 128)\n throw BrowserError.make({\n operation: \"target\",\n reason: Reasons.Limit.make({\n dimension: \"frames\",\n maximum: 128,\n observed: page.frames.size + 1,\n }),\n outcome: \"undispatched\",\n });\n const record = pages.frame(page, target.frameId);\n\n return {\n identity: Target.make({ generation, ...target }),\n record,\n controls: makePageControls(page, target, generation),\n };\n },\n { ...operationOptions, generation },\n ),\n implementation: options.implementation,\n status: owner.status,\n diagnostics: owner.diagnostics,\n admissionStatus: owner.admissionStatus,\n reference: ref,\n capture,\n cleanupResult,\n close: release.pipe(\n Effect.tap(() => retireControl),\n Effect.provideService(Clock.Clock, clock),\n ),\n closeChecked: acquired.closeChecked.pipe(\n Effect.onExit(() => retireControl),\n Effect.provideService(Clock.Clock, clock),\n ),\n liveView: <A>(issue: Effect.Effect<A, BrowserError>, operationOptions?: ExecutionOptions) =>\n owner.guard(\"live-view\", () => issue, {\n ...operationOptions,\n charge: false,\n phases: [\"open\", \"paused\"],\n }),\n beginHandoff: <A>(issue: Effect.Effect<A, BrowserError>, operationOptions?: ExecutionOptions) =>\n lifecycle(\n \"handoff\",\n () => !options.driver.pageControl,\n () =>\n owner.guard(\n \"handoff\",\n (ticket) =>\n Effect.gen(function* () {\n // Drawn before the fence, so the pause and the token that ends it commit together.\n const token = handoffToken ?? (yield* uuid);\n\n if (owner.state.phase === \"open\") {\n yield* Effect.forEach(\n [...capture.captureLeases.values()],\n (lease) => lease.stop,\n {\n discard: true,\n },\n );\n // Work that cannot settle in time fails only this request: the barrier lifts and\n // automation continues, as nothing was handed over or left undecided.\n yield* drainAdmitted(\n \"handoff\",\n ticket,\n () =>\n owner.drained(ticket.signal) &&\n activeBindings?.drained(owner.paused) !== false &&\n getDriver().handoffDrained?.(owner.paused) !== false &&\n pendingPageFaults.size === 0 &&\n capture.captureLeases.size === 0,\n );\n if (owner.state.phase !== \"open\")\n return yield* BrowserError.make({\n operation: \"handoff\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n containment: { _tag: \"SessionFenced\", generation: owner.state.generation },\n });\n owner.fence(\"paused\", \"paused\", \"handoff\");\n }\n handoffToken ??= token;\n // A refused authorization leaves automation paused until explicit operator release.\n const view = yield* issue;\n\n return { token: Redacted.make(handoffToken), view };\n }),\n {\n ...operationOptions,\n charge: false,\n phases: [\"open\", \"paused\"],\n verifyAfter: false,\n bypassBlocked: true,\n },\n ),\n ),\n resume: (\n token: Redacted.Redacted<string>,\n operatorReleasedControl: boolean,\n operationOptions?: ExecutionOptions,\n ) =>\n lifecycle(\n \"resume\",\n () => true,\n () =>\n owner.guard(\n \"resume\",\n (ticket) =>\n Effect.gen(function* () {\n if (\n !operatorReleasedControl ||\n handoffToken === undefined ||\n Redacted.value(token) !== handoffToken\n ) {\n return yield* BrowserError.make({\n operation: \"resume\",\n reason: Reasons.Authorization.make({}),\n outcome: \"undispatched\",\n });\n }\n yield* native(\"resume\", ticket, () => getDriver().dismissDialogs(ticket));\n const inventory = yield* refreshPages(ticket, true);\n\n // The fresh registry and phase commit share the lifecycle permit. Reading content\n // remains an explicit operation on a newly acquired Page.\n activeBindings?.resumeAdmission();\n owner.transition(\"open\");\n handoffToken = undefined;\n\n return inventory;\n }),\n {\n ...operationOptions,\n charge: false,\n phases: [\"paused\"],\n verifyAfter: false,\n bypassBlocked: true,\n },\n ),\n ),\n detach: lifecycle(\n \"detach\",\n () => options.keepAlive,\n () => {\n // Until the connection is given up, a failed detach leaves the session as it was.\n let disconnecting = false;\n\n return owner\n .guard(\n \"detach\",\n (ticket) =>\n Effect.gen(function* () {\n if (!options.keepAlive)\n return yield* BrowserError.make({\n operation: \"detach\",\n reason: Reasons.Unsupported.make({}),\n outcome: \"undispatched\",\n });\n\n const target = yield* native(\"detach\", ticket, () =>\n getDriver().selectedTargetId(),\n );\n\n const inventory = yield* refreshPages(ticket);\n\n if (!inventory.pages.some((info) => info.targetId === target))\n return yield* BrowserError.make({\n operation: \"detach\",\n reason: Reasons.Stale.make({}),\n outcome: \"undispatched\",\n });\n // Bounded cleanup such as a page close is admitted behind the barrier; let it\n // finish rather than disconnect beneath it. Detach itself disposes bindings.\n yield* drainAdmitted(\"detach\", ticket, () => owner.idle(ticket.signal));\n const attached = getDriver();\n\n disconnecting = true;\n reconnectTarget = target;\n activeConnection = undefined;\n owner.fence(\"detached\", \"disconnected\", \"detached\");\n const initialization = yield* Effect.exit(disposeBindings);\n\n const disconnected = yield* Effect.tryPromise({\n try: () => attached.disconnect(),\n catch: () =>\n BrowserError.make({\n operation: \"detach\",\n reason: Reasons.Disconnected.make({}),\n outcome: \"unknown\",\n }),\n }).pipe(Effect.exit);\n\n driver = undefined;\n if (Exit.isFailure(initialization))\n return yield* Effect.failCause(initialization.cause);\n if (Exit.isFailure(disconnected))\n return yield* Effect.failCause(disconnected.cause);\n\n return { reference: ref, targetId: target, inventory };\n }),\n { charge: false, verifyAfter: false, bypassBlocked: true },\n )\n .pipe(\n Effect.onError(() =>\n Effect.sync(() => {\n if (disconnecting) owner.fence(\"uncertain\", \"uncertain\");\n }),\n ),\n );\n },\n ),\n reconnect: (operatorReleasedControl: boolean, operationOptions?: ExecutionOptions) =>\n lifecycle(\n \"reconnect\",\n () =>\n options.keepAlive &&\n reconnectTarget !== undefined &&\n operatorReleasedControl &&\n acquired.verifyReconnect !== undefined,\n () =>\n owner\n .guard(\n \"reconnect\",\n (ticket) =>\n Effect.gen(function* () {\n if (\n !options.keepAlive ||\n reconnectTarget === undefined ||\n !operatorReleasedControl ||\n acquired.verifyReconnect === undefined\n ) {\n return yield* BrowserError.make({\n operation: \"reconnect\",\n reason: Reasons.Unsupported.make({}),\n outcome: \"undispatched\",\n });\n }\n\n yield* acquired.verifyReconnect;\n owner.transition(\"acquiring\");\n const endpoint = yield* connectionUrl(\"reconnect\");\n\n yield* connectNative(endpoint, {\n ...options.driver,\n initialTargetId: reconnectTarget,\n newPage: false,\n preserveViewport: true,\n });\n const inventory = yield* refreshPages(ticket);\n\n owner.transition(\"open\");\n\n return inventory;\n }),\n {\n ...operationOptions,\n charge: false,\n phases: [\"detached\", \"acquiring\"],\n verifyAfter: false,\n bypassBlocked: true,\n },\n )\n .pipe(\n Effect.onError(() => closeScope),\n Effect.onInterrupt(() => closeScope),\n ),\n ),\n };\n\n yield* Queue.take(pageFaults).pipe(\n Effect.flatMap((pageId) => {\n const fault = pendingPageFaults.get(pageId);\n\n return fault === undefined\n ? Effect.void\n : owner\n .contain(containment(pageId, fault.authority), fault.generation)\n .pipe(Effect.ensuring(Effect.sync(() => pendingPageFaults.delete(pageId))));\n }),\n Effect.forever,\n Effect.forkScoped,\n );\n\n // One timer belongs to the enclosing execution, never to an individual Tool call.\n const remaining = Math.max(\n 0,\n owner.lifetimeDeadline - Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000,\n );\n\n // The execution lifetime distinguishes expiry from natural completion before\n // running the shared close path; this race has the required proven semantics.\n // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off\n yield* Effect.raceFirst(\n Effect.sleep(remaining).pipe(Effect.as(true)),\n Deferred.await(ended).pipe(Effect.as(false)),\n ).pipe(\n Effect.flatMap((expired) =>\n expired ? Effect.sync(owner.expire).pipe(Effect.andThen(closeScope)) : Effect.void,\n ),\n Effect.forkIn(parentScope),\n );\n\n return {\n reference: ref,\n /** The caller keeps its own lease type, including whether an allocation attempt exists. */\n lease: acquired,\n close: controls.close,\n connect: Effect.suspend(() =>\n owner.state.phase === \"closed\" || owner.state.phase === \"closing\"\n ? Effect.fail(\n BrowserError.make({\n operation: \"connect\",\n reason: Reasons.Closed.make({}),\n outcome: \"undispatched\",\n }),\n )\n : connected.pipe(Effect.as(controls)),\n ),\n };\n});\n\nexport type SessionControls<L extends SessionLease = SessionLease> =\n Effect.Success<ReturnType<typeof acquireSession<L, never, never>>> extends {\n connect: Effect.Effect<infer A, infer _E, infer _R>;\n }\n ? A\n : never;\n\nexport type TargetControls = PageControls[\"operations\"];\n\nexport type PageControls = ReturnType<SessionControls[\"initialPage\"]>[\"controls\"];\n","import { Duration, Effect, Schema } from \"effect\";\n\nimport type * as Bootstrap from \"../../Bootstrap.ts\";\nimport type {\n BrowserSession,\n Page,\n Frame,\n PageOperations,\n OperationOptions,\n} from \"../../Browser.ts\";\nimport {\n ActionResult,\n Checkpoint,\n CheckpointOptions,\n ClickRequest,\n FillFormOptions,\n FillFormRequest,\n FillFormResult,\n FillRequest,\n FrameInfo,\n HoverRequest,\n InputReceipt,\n KeyStroke,\n NavigateRequest,\n NavigationResult,\n ObservationOptions,\n ObservedElement,\n PageInfo,\n PointerMoveRequest,\n PressRequest,\n ReadTextRequest,\n ScreenshotRequest,\n ScreenshotResult,\n ScrollRequest,\n SelectOptions,\n StartNavigationRequest,\n TextResult,\n TypeRequest,\n Viewport,\n WaitForElementRequest,\n WheelRequest,\n} from \"../../BrowserData.ts\";\nimport {\n BrowserError,\n Reasons,\n type BrowserOperation,\n type BrowserOutcome,\n type Containment,\n InitializationError,\n} from \"../../Errors.ts\";\nimport { StepFailed, type RunOptions } from \"../../Plan.ts\";\nimport type { LivePlanEncoded, PlanEncoded } from \"../../PlanData.ts\";\nimport * as Trace from \"../Trace.ts\";\nimport { forPage } from \"./Association.ts\";\nimport type { Bindings } from \"./Bindings.ts\";\nimport { OperationOptionsSchema } from \"./OperationOptions.ts\";\nimport { issueFrame, issuedPageOf, issuePage, issueSession } from \"./PageRegistry.ts\";\nimport {\n checkedDescriptor,\n checkedLivePlan,\n checkedResolveOptions,\n checkedRunOptions,\n checkedSettled,\n} from \"./PlanOptions.ts\";\nimport { schemaPath } from \"./SchemaPath.ts\";\nimport {\n observedForm,\n type TargetControls,\n type SessionControls,\n type SessionLease,\n type PageControls,\n type FormOutcome,\n} from \"./Session.ts\";\n\nexport const checked = <A>(\n schema: Schema.Codec<A, unknown, never, never>,\n value: unknown,\n operation: BrowserOperation,\n) =>\n Schema.decodeUnknownEffect(schema)(value, { onExcessProperty: \"error\" }).pipe(\n Effect.mapError((error) =>\n BrowserError.make({\n operation,\n reason: Reasons.Configuration.make(schemaPath(error)),\n outcome: \"undispatched\",\n }),\n ),\n Trace.span(\"Browser.validate\", { attributes: { \"browser.operation\": operation } }),\n );\n\n/** Decode when the Effect executes and retain no caller-owned mutable admission data. */\nexport const checkedOperationOptions = (\n value: unknown,\n operation: BrowserOperation,\n): Effect.Effect<OperationOptions, BrowserError> =>\n checked(OperationOptionsSchema, value === undefined ? {} : value, operation).pipe(\n Effect.map((options) =>\n Object.freeze({\n ...(options.timeoutMillis === undefined ? {} : { timeoutMillis: options.timeoutMillis }),\n ...(options.admission === undefined\n ? {}\n : {\n admission: Object.freeze(\n options.admission.queue === undefined\n ? {}\n : {\n queue: Duration.toMillis(Duration.fromInputUnsafe(options.admission.queue)),\n },\n ),\n }),\n }),\n ),\n );\n\nconst withOperationOptions = <A, E, R>(\n options: OperationOptions | undefined,\n operation: BrowserOperation,\n use: (options: OperationOptions) => Effect.Effect<A, E, R>,\n): Effect.Effect<A, E | BrowserError, R> =>\n checkedOperationOptions(options, operation).pipe(Effect.flatMap(use));\n\nexport const decoded =\n <A>(\n schema: Schema.Codec<A, unknown, never, never>,\n operation: BrowserOperation,\n outcome: BrowserOutcome,\n containment?: Containment,\n ) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError((error) =>\n BrowserError.make({\n operation,\n reason: Reasons.Malformed.make(schemaPath(error)),\n outcome,\n ...(containment === undefined ? {} : { containment }),\n }),\n ),\n Trace.span(\"Browser.result\", { attributes: { \"browser.operation\": operation } }),\n );\n\nconst action = decoded(ActionResult, \"action-result\", \"performed\");\nconst pointerMoved = decoded(InputReceipt, \"pointer-move\", \"performed\");\nconst hovered = decoded(InputReceipt, \"hover\", \"performed\");\nconst wheeled = decoded(InputReceipt, \"wheel\", \"performed\");\nconst pressed = decoded(InputReceipt, \"press\", \"performed\");\nconst typed = decoded(InputReceipt, \"type\", \"performed\");\n\nconst formed = (value: FormOutcome) => {\n const stopped = value.stopped?.error;\n\n const outcome =\n stopped?.outcome === \"unknown\"\n ? \"unknown\"\n : value.submitted ||\n value.fields.some((field) => field.status === \"set\") ||\n stopped?.outcome === \"performed\"\n ? \"performed\"\n : \"undispatched\";\n\n return decoded(FillFormResult, \"fill-form\", outcome, stopped?.containment)(value);\n};\n\nconst makeTarget = (\n bound: TargetControls,\n): Pick<\n PageOperations,\n | \"navigate\"\n | \"startNavigation\"\n | \"readText\"\n | \"click\"\n | \"fill\"\n | \"scroll\"\n | \"pointerMove\"\n | \"hover\"\n | \"wheel\"\n | \"press\"\n | \"type\"\n | \"screenshot\"\n> => ({\n navigate: (request, options) =>\n checked(NavigateRequest, request, \"navigate\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"navigate\", (options) =>\n bound.navigate(value.url, value.timeoutMillis, options),\n ),\n ),\n Effect.flatMap((url) => decoded(NavigationResult, \"navigate\", \"performed\")({ url })),\n ),\n startNavigation: (request, options) =>\n checked(StartNavigationRequest, request, \"navigate\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"navigate\", (options) =>\n bound.startNavigation(value.url, value.timeoutMillis, options),\n ).pipe(\n Effect.map((operation) => ({\n target: operation.target,\n request: value,\n completed: operation.completed.pipe(\n Effect.flatMap((url) => decoded(NavigationResult, \"navigate\", \"performed\")({ url })),\n ),\n stop: operation.stop,\n })),\n ),\n ),\n ),\n readText: (request, options) =>\n checked(ReadTextRequest, request, \"read-text\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"read-text\", (options) =>\n bound.readText(value.selector, options),\n ),\n ),\n Effect.flatMap((text) => decoded(TextResult, \"read-text\", \"undispatched\")({ text })),\n ),\n click: (request, options) =>\n checked(ClickRequest, request, \"click\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"click\", (options) =>\n bound.click(value.selector, undefined, options),\n ),\n ),\n Effect.flatMap(({ url, input }) => action({ url, input })),\n ),\n fill: (request, options) =>\n checked(FillRequest, request, \"fill\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"fill\", (options) =>\n bound.fill(value.selector, value.value, undefined, options),\n ),\n ),\n Effect.flatMap((url) => action({ url })),\n ),\n scroll: (request, options) =>\n checked(ScrollRequest, request, \"scroll\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"scroll\", (options) =>\n bound.scroll(value.deltaX, value.deltaY, options),\n ),\n ),\n Effect.flatMap((url) => action({ url })),\n ),\n pointerMove: (request, options) =>\n checked(PointerMoveRequest, request, \"pointer-move\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"pointer-move\", (options) =>\n bound.pointerMove(value.to, options),\n ),\n ),\n Effect.flatMap((input) => pointerMoved({ ...input, kind: \"pointer-move\" })),\n ),\n hover: (request, options) =>\n checked(HoverRequest, request, \"hover\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"hover\", (options) =>\n bound.hover(value.selector, undefined, options),\n ),\n ),\n Effect.flatMap((input) => hovered({ ...input, kind: \"hover\" })),\n ),\n wheel: (request, options) =>\n checked(WheelRequest, request, \"wheel\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"wheel\", (options) =>\n bound\n .wheel(value.deltaX, value.deltaY, value.at, options)\n .pipe(\n Effect.flatMap((input) =>\n wheeled({ ...input, kind: \"wheel\", delta: { x: value.deltaX, y: value.deltaY } }),\n ),\n ),\n ),\n ),\n ),\n press: (request, options) =>\n checked(PressRequest, request, \"press\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"press\", (options) =>\n bound.press(value.key, value.modifiers ?? [], value.into, undefined, options),\n ),\n ),\n Effect.flatMap((input) => pressed({ ...input, kind: \"press\" })),\n ),\n type: (request, options) =>\n checked(TypeRequest, request, \"type\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"type\", (options) =>\n bound.type(value.text, value.into, undefined, options),\n ),\n ),\n Effect.flatMap((input) => typed({ ...input, kind: \"type\" })),\n ),\n screenshot: (request, options) =>\n checked(ScreenshotRequest, request, \"screenshot\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"screenshot\", (options) =>\n bound.screenshot(value.fullPage, options),\n ),\n ),\n Effect.flatMap((bytes) =>\n decoded(\n ScreenshotResult,\n \"screenshot\",\n \"undispatched\",\n )({ mediaType: \"image/png\", bytes: new Uint8Array(bytes) }),\n ),\n ),\n});\n\n/** A browser-operation failure keeps its meaning when it is reported as an initialization one. */\nconst initialization = (reason: BrowserError[\"reason\"]): InitializationError[\"reason\"] =>\n reason._tag === \"Busy\" || reason._tag === \"QueueFull\"\n ? \"busy\"\n : reason._tag === \"Closed\" || reason._tag === \"Disconnected\"\n ? \"closed\"\n : reason._tag === \"Timeout\" || reason._tag === \"QueueExpired\"\n ? \"timeout\"\n : reason._tag === \"Stale\"\n ? \"stale\"\n : reason._tag === \"Unsupported\"\n ? \"unsupported\"\n : reason._tag === \"Configuration\"\n ? \"configuration\"\n : \"native\";\n\nconst makePageOperations = (controls: PageControls): PageOperations => {\n const Wait = Schema.Struct({\n selector: ClickRequest.fields.selector,\n state: Schema.Literals([\"visible\", \"hidden\", \"attached\", \"detached\"]),\n });\n\n const navigate = (url: string) => action({ url });\n\n return {\n ...makeTarget(controls.operations),\n observe: (options = {}, operationOptions) =>\n checked(ObservationOptions, options, \"observe\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(operationOptions, \"observe\", (options) =>\n controls.observe({ ...value, scope: value.scope ?? \"document\" }, options),\n ),\n ),\n ),\n checkpoint: (options = {}, operationOptions) =>\n checked(CheckpointOptions, options, \"checkpoint\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(operationOptions, \"checkpoint\", (options) =>\n controls.checkpoint({ ...value, picture: value.picture ?? false }, options),\n ),\n ),\n Effect.flatMap(({ picture, ...sampled }) =>\n decoded(\n Checkpoint,\n \"checkpoint\",\n \"undispatched\",\n )({\n ...sampled,\n ...(picture === undefined\n ? {}\n : { picture: { mediaType: \"image/png\", bytes: new Uint8Array(picture) } }),\n }),\n ),\n ),\n controlFacts: (reference, options) =>\n checked(ObservedElement, reference, \"control-facts\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"control-facts\", (options) =>\n controls.controlFacts(value, options),\n ),\n ),\n ),\n revalidateElement: (reference, options) =>\n checked(ObservedElement, reference, \"revalidate\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"revalidate\", (options) =>\n controls.revalidate(value, options).pipe(Effect.as(value)),\n ),\n ),\n ),\n clickElement: (reference, admission, options) =>\n checked(ObservedElement, reference, \"click\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"click\", (options) =>\n controls.operations.click(value, admission?.admit, options),\n ),\n ),\n Effect.flatMap(({ url, input }) => action({ url, input })),\n ),\n fillElement: (reference, value, admission, options) =>\n checked(ObservedElement, reference, \"fill\").pipe(\n Effect.flatMap((element) =>\n checked(FillRequest.fields.value, value, \"fill\").pipe(\n Effect.flatMap((text) =>\n withOperationOptions(options, \"fill\", (options) =>\n controls.operations.fill(element, text, admission?.admit, options),\n ),\n ),\n ),\n ),\n Effect.flatMap(navigate),\n ),\n selectOption: (reference, options, admission, operationOptions) =>\n checked(ObservedElement, reference, \"select-option\").pipe(\n Effect.flatMap((element) =>\n checked(SelectOptions, options, \"select-option\").pipe(\n Effect.flatMap((ids) =>\n withOperationOptions(operationOptions, \"select-option\", (options) =>\n controls.selectOption(element, ids, admission?.admit, options),\n ),\n ),\n ),\n ),\n Effect.flatMap(navigate),\n ),\n fillForm: (request, admission, options = {}, operationOptions) =>\n checked(FillFormRequest, request, \"fill-form\").pipe(\n Effect.flatMap((form) =>\n checked(FillFormOptions, options, \"fill-form\").pipe(\n Effect.flatMap((settings) =>\n withOperationOptions(operationOptions, \"fill-form\", (options) =>\n controls.fillForm(\n observedForm(form),\n admission?.admit,\n {\n verify: settings.verify ?? true,\n settleMillis: settings.settleMillis ?? 50,\n },\n options,\n ),\n ),\n ),\n ),\n ),\n Effect.flatMap(formed),\n ),\n hoverElement: (reference, admission, options) =>\n checked(ObservedElement, reference, \"hover\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"hover\", (options) =>\n controls.operations.hover(value, admission?.admit, options),\n ),\n ),\n Effect.flatMap((input) => hovered({ ...input, kind: \"hover\" })),\n ),\n pressElement: (reference, stroke, admission, options) =>\n checked(ObservedElement, reference, \"press\").pipe(\n Effect.flatMap((element) =>\n checked(KeyStroke, stroke, \"press\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"press\", (options) =>\n controls.operations.press(\n value.key,\n value.modifiers ?? [],\n element,\n admission?.admit,\n options,\n ),\n ),\n ),\n ),\n ),\n Effect.flatMap((input) => pressed({ ...input, kind: \"press\" })),\n ),\n typeElement: (reference, text, admission, options) =>\n checked(ObservedElement, reference, \"type\").pipe(\n Effect.flatMap((element) =>\n checked(TypeRequest.fields.text, text, \"type\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"type\", (options) =>\n controls.operations.type(value, element, admission?.admit, options),\n ),\n ),\n ),\n ),\n Effect.flatMap((input) => typed({ ...input, kind: \"type\" })),\n ),\n waitFor: (request, options) =>\n checked(Wait, request, \"wait\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"wait\", (options) =>\n controls.waitFor(value.selector, value.state, options),\n ),\n ),\n ),\n waitForElement: (request, options) =>\n checked(WaitForElementRequest, request, \"wait\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"wait\", (options) =>\n controls.waitForElement(value, options),\n ),\n ),\n ),\n clickAndWait: (request, options) =>\n checked(ClickRequest, request, \"click-and-wait\").pipe(\n Effect.flatMap((value) =>\n withOperationOptions(options, \"click-and-wait\", (options) =>\n controls.clickAndWait(value.selector, options),\n ),\n ),\n Effect.flatMap(({ url, input }) => action({ url, input })),\n ),\n ready: (options = {}) =>\n checkedOperationOptions(options, \"ready\").pipe(\n Effect.flatMap((options) => controls.readiness(options)),\n Effect.mapError((error) =>\n InitializationError.make({\n operation: \"ready\",\n step: \"session\",\n reason: initialization(error.reason),\n }),\n ),\n Effect.flatMap((state) =>\n state._tag === \"NotReady\"\n ? Effect.fail(\n InitializationError.make({\n operation: \"ready\",\n step: state.step,\n reason: state.reason === \"failed\" ? \"output\" : state.reason,\n }),\n )\n : Effect.succeed<Bootstrap.ReadinessOutcome>({ _tag: state._tag }),\n ),\n ),\n };\n};\n\nconst makePlanOperations = (\n controls: PageControls,\n): Pick<Frame, \"start\" | \"run\" | \"resolve\" | \"settled\"> => {\n const prepare = (plan: LivePlanEncoded | PlanEncoded, options: RunOptions | undefined) =>\n checkedRunOptions(options).pipe(\n Effect.flatMap((options) =>\n checkedLivePlan(plan).pipe(Effect.map((plan) => ({ plan, options }))),\n ),\n Effect.mapError(\n (error) => new StepFailed({ stage: \"PreparationFailed\", completed: [], error }),\n ),\n );\n\n return {\n start: (plan, options) =>\n prepare(plan, options).pipe(\n Effect.flatMap(({ plan, options }) => controls.plans.start(plan, options)),\n ),\n run: (plan, options) =>\n prepare(plan, options).pipe(\n Effect.flatMap(({ plan, options }) => controls.plans.run(plan, options)),\n ),\n resolve: (descriptor, options) =>\n checkedResolveOptions(options).pipe(\n Effect.flatMap(({ operationOptions, guard }) =>\n checkedDescriptor(descriptor).pipe(\n Effect.flatMap((descriptor) => controls.resolve(descriptor, guard, operationOptions)),\n ),\n ),\n ),\n settled: (request, options) =>\n checkedSettled(request).pipe(\n Effect.flatMap((request) =>\n withOperationOptions(options, \"settled\", (options) => controls.settled(request, options)),\n ),\n ),\n };\n};\n\nexport const makeSession = <E>(\n controls: SessionControls<SessionLease>,\n bindings: Bindings<E>,\n): BrowserSession<E> => {\n const issuedPage = (value: ReturnType<SessionControls[\"initialPage\"]>): Page =>\n issuePage(\n value.record,\n (): Page => ({\n ...makePageOperations(value.controls),\n ...makePlanOperations(value.controls),\n timeline: value.timeline,\n identity: Object.freeze(value.record.identity),\n status: value.status,\n monotonicTimeNanos: controls.monotonicTimeNanos,\n describe: (options = {}) =>\n checkedOperationOptions(options, \"describe-page\").pipe(\n Effect.flatMap((options) => value.controls.describe(options)),\n ),\n listFrames: (options = {}) =>\n checkedOperationOptions(options, \"list-frames\").pipe(\n Effect.flatMap((options) => value.controls.listFrames(options)),\n ),\n frame: (info, options) =>\n checked(FrameInfo, info, \"target\").pipe(\n Effect.tap(() => value.controls.validate(\"target\")),\n Effect.flatMap((info) =>\n withOperationOptions(options, \"target\", (options) =>\n controls.frame(value.record.info, info, value.record.identity.generation, options),\n ),\n ),\n Effect.map((frame): Frame => {\n const issuedFrame: Frame = {\n ...makePageOperations(frame.controls),\n ...makePlanOperations(frame.controls),\n identity: Object.freeze(frame.identity),\n monotonicTimeNanos: controls.monotonicTimeNanos,\n status: value.status.pipe(\n Effect.map((status) =>\n Object.freeze({\n ...status,\n identity: frame.identity,\n phase:\n status.phase !== \"closed\" && frame.record.detached ? \"stale\" : status.phase,\n }),\n ),\n ),\n };\n\n issueFrame(issuedFrame, controls.capture.owner, frame.controls);\n\n return issuedFrame;\n }),\n ),\n resizeViewport: (viewport, options) =>\n checked(Viewport, viewport, \"resize\").pipe(\n Effect.flatMap((viewport) =>\n withOperationOptions(options, \"resize\", (options) =>\n value.controls.resize(viewport, options),\n ),\n ),\n ),\n close: (options = {}) =>\n checkedOperationOptions(options, \"close-page\").pipe(\n Effect.flatMap((options) => value.controls.close(options)),\n ),\n }),\n () => ({\n controls: value.controls,\n capture: forPage(\n controls.capture,\n value.record.info,\n value.record.identity,\n value.controls.validate,\n ),\n pageControl: { port: value.controls.pageControl, page: value.record.info },\n }),\n );\n\n const session: BrowserSession<E> = {\n monotonicTimeNanos: controls.monotonicTimeNanos,\n timeline: controls.timeline,\n pages: controls.pageEvents,\n initialPage: issuedPage(controls.initialPage()),\n page: (info, options) =>\n checked(PageInfo, info, \"target\").pipe(\n Effect.flatMap((info) =>\n withOperationOptions(options, \"target\", (options) => controls.page(info, options)),\n ),\n Effect.map(issuedPage),\n ),\n listPages: (options = {}) =>\n checkedOperationOptions(options, \"list-pages\").pipe(\n Effect.flatMap((options) => controls.listPages(options)),\n ),\n implementation: controls.implementation,\n status: controls.status,\n diagnostics: controls.diagnostics,\n admission: controls.admissionStatus,\n closeChecked: controls.closeChecked,\n failure: bindings.failure,\n bindingDiagnostics: bindings.diagnostics,\n selectPage: (page, options) =>\n Effect.suspend(() => {\n // Display selection names an issued Page by identity, never by copied metadata.\n const registration = issuedPageOf(page, controls.capture.owner);\n\n return registration === undefined\n ? Effect.fail(\n BrowserError.make({\n operation: \"select-page\",\n reason: Reasons.UnregisteredSession.make({}),\n outcome: \"undispatched\",\n }),\n )\n : registration.controls\n .validate(\"select-page\")\n .pipe(\n Effect.andThen(\n withOperationOptions(options, \"select-page\", (options) =>\n controls.selectPage(registration.record.info, options),\n ),\n ),\n );\n }),\n createPage: (options) =>\n withOperationOptions(options, \"new-page\", (options) => controls.createPage(options)).pipe(\n Effect.map(issuedPage),\n ),\n };\n\n issueSession(session, controls.capture);\n\n return session;\n};\n"],"mappings":";;;;;;;;;AAgBA,MAAaA,YAAU,OAAO,IAAI,aAAa;CAC7C,MAAM,UAAU,OAAO,OAAO,cAAc,OAAO,UAAU;CAC7D,MAAM,UAAU,OAAO,WAAW;CAClC,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,UAAU,OAAO,OAAO;CAE9B,OAAO,OAAO,OAAO,WAAW;EAC9B,IAAI;GACF,IAAI,SAAS,OAAO,eAAe,OAAO;GAE1C,OAAO,WAAW,KAAA,KAAa,QAAQ,IAAI,OAAO,aAAa,OAAO,kBAAkB,GACtF,SAAS,OAAO,SAAS,SAAS,OAAO,eAAe,OAAO,MAAM,IAAI,KAAA;GAE3E,OAAO;IACL;IACA;IACA;IACA,QACE,WAAW,KAAA,IACP,KAAA,IACA,OAAO,OACL,OAAO,aAAa;KAClB,SAAS,OAAO;KAChB,QAAQ,OAAO;KACf,SAAS,OAAO;IAClB,CAAC,CACH;GACR;EACF,QAAQ;GAEN,OAAO;IAAE,SAAS;IAAO;IAAO;IAAS,QAAQ,KAAA;GAAU;EAC7D;CACF,CAAC;AACH,CAAC;;AAKD,MAAa,cAAc,cAAmD;CAC5E,MAAM;CACN,OAAO,SAAS,WAAW,KAAA,IAAY,CAAC,IAAI,CAAC;EAAE,MAAM,SAAS;EAAQ,YAAY,CAAC;CAAE,CAAC;CACtF,GAAI,SAAS,QAAQ,YAAY,QAAQ,E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