@wenathlan/extension 1.1.34 → 1.1.36

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,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../memory.ts", "../../policy.ts", "../../progress.ts", "../../version.ts", "../../types.ts", "../../protocol.ts", "../browsertabs.ts", "../pagedialogs.ts", "../pageinteract.ts", "../pagecontrols.ts", "../background.ts"],
4
- "sourcesContent": ["import type { a11ycapture, agentplan, agentsession, auditevent, bannerreport, capabilityreport, clickablemap, derivedselector, diagnosticreport, dialogdecision, dialogpolicy, endpointconfig, focusevent, keyholdstate, mutationevent, observationrecord, pagesignals, planprogress, readercapture, resolutionsummary, retryoutcome, runsettings, snapshotdiff, stepoutcome, templateprofile, watchregistration } from \"./types.js\";\n\n/** Provides a small storage seam that works in browser, tests and future adapters. */\nexport interface memoryadapter {\n get<T>(key: string): Promise<T | undefined>;\n set<T>(key: string, value: T): Promise<void>;\n}\n\n/**\n * Local memory for sessions, plans, audit evidence and interaction state.\n * Correlated rules for every stored record live in this one seam; each accessor is a one line storage delegation so future backends replace the adapter only.\n */\nexport class sessionmemory {\n constructor(private readonly adapter: memoryadapter) {}\n\n async getconfig(): Promise<endpointconfig | undefined> { return this.adapter.get<endpointconfig>(\"config\"); }\n async setconfig(value: endpointconfig): Promise<void> { return this.adapter.set(\"config\", value); }\n async getsession(): Promise<agentsession | undefined> { return this.adapter.get<agentsession>(\"session\"); }\n async setsession(value: agentsession): Promise<void> { return this.adapter.set(\"session\", value); }\n async getplan(): Promise<agentplan | undefined> { return this.adapter.get<agentplan>(\"plan\"); }\n async setplan(value: agentplan): Promise<void> { return this.adapter.set(\"plan\", value); }\n async getdiagnostic(): Promise<diagnosticreport | undefined> { return this.adapter.get<diagnosticreport>(\"diagnostic\"); }\n async setdiagnostic(value: diagnosticreport): Promise<void> { return this.adapter.set(\"diagnostic\", value); }\n async getprogress(): Promise<planprogress | undefined> { return this.adapter.get<planprogress>(\"progress\"); }\n async setprogress(value: planprogress): Promise<void> { return this.adapter.set(\"progress\", value); }\n async getcapabilities(): Promise<capabilityreport | undefined> { return this.adapter.get<capabilityreport>(\"capabilities\"); }\n async setcapabilities(value: capabilityreport): Promise<void> { return this.adapter.set(\"capabilities\", value); }\n async getsettings(): Promise<runsettings | undefined> { return this.adapter.get<runsettings>(\"settings\"); }\n async setsettings(value: runsettings): Promise<void> { return this.adapter.set(\"settings\", value); }\n async getaudit(): Promise<auditevent[]> { return (await this.adapter.get<auditevent[]>(\"audit\")) ?? []; }\n async getoutcomes(): Promise<stepoutcome[]> { return (await this.adapter.get<stepoutcome[]>(\"outcomes\")) ?? []; }\n\n /** Records one audit event; retention is a user setting and an absent setting keeps every event. */\n async addaudi(event: auditevent): Promise<void> {\n const records = await this.getaudit();\n const combined = [event, ...records];\n const retention = (await this.getsettings())?.auditretention;\n await this.adapter.set(\"audit\", retention === undefined ? combined : combined.slice(0, retention));\n }\n\n /** Records one step outcome; retention is a user setting and an absent setting keeps every outcome. */\n async addoutcome(outcome: stepoutcome): Promise<void> {\n const records = await this.getoutcomes();\n const combined = [outcome, ...records];\n const retention = (await this.getsettings())?.outcomeretention;\n await this.adapter.set(\"outcomes\", retention === undefined ? combined : combined.slice(0, retention));\n }\n\n /** Stores one clickable map under its observation version so every captured map stays available. */\n async setmap(map: clickablemap): Promise<void> { return this.adapter.set(`map${map.version}`, map); }\n\n /** Returns one stored clickable map by its observation version. */\n async getmap(version: number): Promise<clickablemap | undefined> { return this.adapter.get<clickablemap>(`map${version}`); }\n\n /** Advances and persists the observation version counter used to stamp clickable maps. */\n async nextobservationversion(): Promise<number> {\n const current = (await this.adapter.get<number>(\"observationversion\")) ?? 0;\n const next = current + 1;\n await this.adapter.set(\"observationversion\", next);\n return next;\n }\n\n /** Returns the latest observation version used to stamp a clickable map. */\n async getobservationversion(): Promise<number | undefined> { return this.adapter.get<number>(\"observationversion\"); }\n\n /** Returns the key hold registry, persisted so holds survive service worker restarts. */\n async getholds(): Promise<keyholdstate[]> { return (await this.adapter.get<keyholdstate[]>(\"holds\")) ?? []; }\n\n /** Replaces the key hold registry after one press or release transition. */\n async setholds(holds: keyholdstate[]): Promise<void> { return this.adapter.set(\"holds\", holds); }\n\n /** Returns every dialog decision recorded for the audit trail. */\n async getdialogs(): Promise<dialogdecision[]> { return (await this.adapter.get<dialogdecision[]>(\"dialogs\")) ?? []; }\n\n /** Records one dialog decision with the reviewed answer and the observed dialog text. */\n async adddialog(decision: dialogdecision): Promise<void> {\n const records = await this.getdialogs();\n await this.adapter.set(\"dialogs\", [decision, ...records]);\n }\n\n /** Returns every retry outcome recorded with attempts and movement deltas. */\n async getretries(): Promise<retryoutcome[]> { return (await this.adapter.get<retryoutcome[]>(\"retries\")) ?? []; }\n\n /** Records one retry outcome with the attempts made and the movement delta observed. */\n async addretry(outcome: retryoutcome): Promise<void> {\n const records = await this.getretries();\n await this.adapter.set(\"retries\", [outcome, ...records]);\n }\n\n /** Returns every resolution summary stored per target mode. */\n async getresolutions(): Promise<resolutionsummary[]> { return (await this.adapter.get<resolutionsummary[]>(\"resolutions\")) ?? []; }\n\n /** Records one resolution summary for later selector derivation. */\n async addresolution(summary: resolutionsummary): Promise<void> {\n const records = await this.getresolutions();\n await this.adapter.set(\"resolutions\", [summary, ...records]);\n }\n\n /** Returns the reviewed default dialog policy kept for the session auto handler. */\n async getdialogpolicy(): Promise<dialogpolicy | undefined> { return this.adapter.get<dialogpolicy>(\"dialogpolicy\"); }\n\n /** Stores the reviewed default dialog policy of the latest approved plan. */\n async setdialogpolicy(policy: dialogpolicy): Promise<void> { return this.adapter.set(\"dialogpolicy\", policy); }\n\n /** Stores one observation capture under its version so every observation version stays available. */\n async setobservation(record: observationrecord): Promise<void> { return this.adapter.set(`observation${record.version}`, record); }\n\n /** Returns one stored observation version. */\n async getobservation(version: number): Promise<observationrecord | undefined> { return this.adapter.get<observationrecord>(`observation${version}`); }\n\n /** Returns the observation retention window; an absent setting keeps every capture. */\n private async observationretention(): Promise<number | undefined> { return (await this.getsettings())?.observationretention; }\n\n /** Stores one accessibility tree capture; retention is a user setting and an absent setting keeps every tree. */\n async adda11ytree(capture: a11ycapture): Promise<void> {\n const records = await this.geta11ytrees();\n const combined = [capture, ...records];\n const retention = await this.observationretention();\n await this.adapter.set(\"a11ytrees\", retention === undefined ? combined : combined.slice(0, retention));\n }\n\n /** Returns every stored accessibility tree capture, newest first. */\n async geta11ytrees(): Promise<a11ycapture[]> { return (await this.adapter.get<a11ycapture[]>(\"a11ytrees\")) ?? []; }\n\n /** Stores one reader article capture; retention is a user setting and an absent setting keeps every article. */\n async addreaderarticle(capture: readercapture): Promise<void> {\n const records = await this.getreaderarticles();\n const combined = [capture, ...records];\n const retention = await this.observationretention();\n await this.adapter.set(\"readerarticles\", retention === undefined ? combined : combined.slice(0, retention));\n }\n\n /** Returns every stored reader article capture, newest first. */\n async getreaderarticles(): Promise<readercapture[]> { return (await this.adapter.get<readercapture[]>(\"readerarticles\")) ?? []; }\n\n /** Records one dom mutation observed inside a reviewed watch. */\n async addmutationevent(event: mutationevent): Promise<void> {\n const records = await this.getmutationevents();\n await this.adapter.set(\"mutationevents\", [event, ...records]);\n }\n\n /** Returns the mutation event stream of every reviewed watch. */\n async getmutationevents(): Promise<mutationevent[]> { return (await this.adapter.get<mutationevent[]>(\"mutationevents\")) ?? []; }\n\n /** Records one focus change observed inside a reviewed watch. */\n async addfocusevent(event: focusevent): Promise<void> {\n const records = await this.getfocusevents();\n await this.adapter.set(\"focusevents\", [event, ...records]);\n }\n\n /** Returns the focus event stream of every reviewed watch. */\n async getfocusevents(): Promise<focusevent[]> { return (await this.adapter.get<focusevent[]>(\"focusevents\")) ?? []; }\n\n /** Records one consent banner observed by a reviewed banner watch. */\n async addbanner(event: bannerreport): Promise<void> {\n const records = await this.getbanners();\n await this.adapter.set(\"banners\", [event, ...records]);\n }\n\n /** Returns every consent banner report observed so far. */\n async getbanners(): Promise<bannerreport[]> { return (await this.adapter.get<bannerreport[]>(\"banners\")) ?? []; }\n\n /** Records one snapshot diff between two observation versions. */\n async adddiff(diff: snapshotdiff): Promise<void> {\n const records = await this.getdiffs();\n await this.adapter.set(\"diffs\", [diff, ...records]);\n }\n\n /** Returns every stored snapshot diff, newest first. */\n async getdiffs(): Promise<snapshotdiff[]> { return (await this.adapter.get<snapshotdiff[]>(\"diffs\")) ?? []; }\n\n /** Records one derived selector with its stability score for reuse. */\n async addselector(selector: derivedselector): Promise<void> {\n const records = await this.getselectors();\n await this.adapter.set(\"selectors\", [selector, ...records]);\n }\n\n /** Returns every stored derived selector with its stability score, newest first. */\n async getselectors(): Promise<derivedselector[]> { return (await this.adapter.get<derivedselector[]>(\"selectors\")) ?? []; }\n\n /** Records one detected template class or section fingerprint for its origin. */\n async addtemplate(profile: templateprofile): Promise<void> {\n const records = await this.gettemplates();\n await this.adapter.set(\"templates\", [profile, ...records]);\n }\n\n /** Returns every stored template class and section fingerprint, newest first. */\n async gettemplates(): Promise<templateprofile[]> { return (await this.adapter.get<templateprofile[]>(\"templates\")) ?? []; }\n\n /** Records one watch registration so it survives service worker restarts. */\n async addwatch(watch: watchregistration): Promise<void> {\n const records = await this.getwatches();\n await this.adapter.set(\"watches\", [watch, ...records]);\n }\n\n /** Returns every watch registration, newest first, including closed windows. */\n async getwatches(): Promise<watchregistration[]> { return (await this.adapter.get<watchregistration[]>(\"watches\")) ?? []; }\n\n /** Closes one watch registration by watch id once its reviewed lifetime window ends. */\n async closewatch(watchid: string, closedat: number): Promise<void> {\n const records = await this.getwatches();\n await this.adapter.set(\"watches\", records.map(watch => watch.watchid === watchid && watch.closedat === undefined ? { ...watch, closedat } : watch));\n }\n\n /** Returns the live page signals of language, template, scroll lock and banner state. */\n async getsignals(): Promise<pagesignals | undefined> { return this.adapter.get<pagesignals>(\"signals\"); }\n\n /** Replaces the live page signals after an observation step refreshes them. */\n async setsignals(signals: pagesignals): Promise<void> { return this.adapter.set(\"signals\", signals); }\n}\n\n/** Creates identifiers locally without a network dependency. */\nexport function randomid(): string {\n return crypto.randomUUID();\n}\n", "import type { actionkind, agentplan, agentsession, endpointconfig, observationmode, policyevaluation, toolstep } from \"./types.js\";\n\nconst sensitiveactions = new Set<actionkind>([\"click\", \"type\", \"navigate\", \"select\", \"presskey\", \"drag\", \"drop\", \"upload\", \"clear\", \"check\", \"uncheck\", \"toggle\", \"submit\", \"reload\", \"back\", \"forward\", \"writestorage\", \"setattribute\", \"removeattribute\", \"evaluate\", \"tabcreate\", \"tabactivate\", \"tabclose\", \"tabreload\", \"windowcreate\", \"windowclose\", \"windowresize\", \"downloadfile\", \"clickpoint\", \"shiftclick\", \"dismissdialog\", \"enterframe\", \"typetime\", \"appendtext\", \"setvalue\", \"typeedit\", \"keyhold\", \"keyrelease\", \"submitsearch\", \"selectmulti\", \"chooseradio\", \"setslider\", \"setdate\", \"setcolor\"]);\nconst interactionactions = new Set<actionkind>([\"focus\", \"scroll\", \"hover\", \"clickdeep\", \"rightclick\", \"doubleclick\", \"scrollpage\", \"scrollby\", \"scrollend\", \"scrolltop\", \"fullscreen\", \"zoomset\", \"movepointer\", \"clicktext\", \"clickaria\", \"clickname\", \"expanddetails\", \"pierceshadow\", \"retryaction\"]);\nconst readactions = new Set<actionkind>([\"observe\", \"inspect\", \"extract\", \"wait\", \"waitfor\", \"waittext\", \"readattribute\", \"readstyle\", \"readgeometry\", \"readvalue\", \"readtext\", \"readhtml\", \"countelements\", \"readtable\", \"readlinks\", \"readimages\", \"readmeta\", \"readforms\", \"readstorage\", \"highlight\", \"tablist\", \"windowlist\", \"tabsnapshot\", \"mapclicks\", \"verifyvisible\", \"verifyenabled\", \"resolvexpath\", \"a11ytree\", \"readvisible\", \"readertree\", \"detectlists\", \"detecttables\", \"readjson\", \"watchmutate\", \"waitquiet\", \"watchbanner\", \"detectinfinitescroll\", \"detectvirtual\", \"detectlazy\", \"readscrollpos\", \"readlang\", \"readoutline\", \"countpages\", \"listshadow\", \"listframes\", \"classifypage\", \"fingerprintsection\", \"diffsnapshots\", \"readselection\", \"watchfocus\", \"detectsticky\", \"detectscrolllock\", \"readopengraph\", \"detectlanguage\", \"deriveselector\"]);\nconst allowedactions = new Set<actionkind>([...sensitiveactions, ...interactionactions, ...readactions]);\nconst watchactions = new Set<actionkind>([\"watchmutate\", \"watchbanner\", \"watchfocus\"]);\nconst targetactions = new Set<actionkind>([\"inspect\", \"focus\", \"click\", \"type\", \"scroll\", \"select\", \"hover\", \"clickdeep\", \"rightclick\", \"doubleclick\", \"drag\", \"drop\", \"upload\", \"clear\", \"check\", \"uncheck\", \"toggle\", \"submit\", \"readattribute\", \"readstyle\", \"readgeometry\", \"readvalue\", \"readtext\", \"readhtml\", \"countelements\", \"readtable\", \"highlight\", \"setattribute\", \"removeattribute\", \"waitfor\", \"shiftclick\", \"typetime\", \"appendtext\", \"setvalue\", \"typeedit\", \"submitsearch\", \"selectmulti\", \"chooseradio\", \"setslider\", \"setdate\", \"setcolor\", \"expanddetails\", \"verifyvisible\", \"verifyenabled\", \"pierceshadow\", \"deriveselector\", \"fingerprintsection\"]);\nconst valueactions = new Set<actionkind>([\"presskey\", \"drag\", \"drop\", \"upload\", \"readattribute\", \"removeattribute\", \"waittext\", \"evaluate\", \"zoomset\", \"tabactivate\", \"tabclose\", \"tabreload\", \"windowclose\", \"windowresize\", \"tabcreate\", \"windowcreate\", \"downloadfile\", \"typetime\", \"appendtext\", \"setvalue\", \"typeedit\", \"keyhold\", \"keyrelease\", \"chooseradio\", \"setslider\", \"setdate\", \"setcolor\"]);\n\n/** Normalizes a user supplied HTTPS endpoint without preserving a provider lock-in. */\nexport function normalizeendpoint(value: string): endpointconfig {\n const endpoint = new URL(value.trim());\n if (endpoint.protocol !== \"https:\") throw new Error(\"Devthink accepts HTTPS endpoints only.\");\n if (endpoint.username || endpoint.password) throw new Error(\"Endpoint credentials are not allowed in the URL.\");\n return { endpoint: endpoint.toString(), origin: endpoint.origin, configuredat: Date.now() };\n}\n\n/** Creates the exact optional host pattern requested from Chromium. */\nexport function hostpattern(origin: string): string {\n const parsed = new URL(origin);\n if (parsed.protocol !== \"https:\") throw new Error(\"Only HTTPS origins can be granted.\");\n return `${parsed.origin}/*`;\n}\n\n/** True when the action kind observes the page over a reviewed lifetime window. */\nexport function iswatchkind(kind: actionkind): boolean {\n return watchactions.has(kind);\n}\n\n/** Grades the observation mode of a kind: passive capture, watched lifetimes or diffing passes. */\nexport function observationmodeof(kind: actionkind): observationmode {\n if (watchactions.has(kind) || kind === \"waitquiet\") return \"watching\";\n if (kind === \"diffsnapshots\") return \"diffing\";\n return \"passive\";\n}\n\n/** Defines action risk from the fixed local allowlist. */\nexport function actionrisk(kind: actionkind): \"read\" | \"interaction\" | \"sensitive\" {\n if (!allowedactions.has(kind)) throw new Error(\"Unsupported browser action.\");\n if (sensitiveactions.has(kind)) return \"sensitive\";\n return interactionactions.has(kind) ? \"interaction\" : \"read\";\n}\n\n/** True when the action kind accepts a css selector target or a reviewed targetref. */\nexport function needstarget(kind: actionkind): boolean {\n return targetactions.has(kind);\n}\n\n/** Parses the reviewed JSON options of a step; malformed payloads are rejected early. */\nexport function parseoptions(step: toolstep): Record<string, unknown> {\n if (step.options === undefined) return {};\n let parsed: unknown;\n try { parsed = JSON.parse(step.options); } catch { throw new Error(\"Step options must be a JSON object.\"); }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new Error(\"Step options must be a JSON object.\");\n return parsed as Record<string, unknown>;\n}\n\n/** Maps an action kind to the optional browser permission it requires, if any. */\nexport function requiredcapability(kind: actionkind): string | undefined {\n if (kind === \"tablist\") return \"tabs\";\n if (kind === \"downloadfile\") return \"downloads\";\n return undefined;\n}\n\n/** Parses the reviewed wait duration of a wait step with no upper bound. */\nexport function waitduration(step: toolstep): number {\n const requested = step.value ? Number.parseInt(step.value, 10) : 250;\n if (!Number.isFinite(requested) || requested < 0) throw new Error(\"Wait duration must be zero or a positive number of milliseconds.\");\n return requested;\n}\n\nfunction isnumericid(value: unknown): value is string {\n return typeof value === \"string\" && /^\\d+$/.test(value);\n}\n\nfunction numericoption(options: Record<string, unknown>, key: string): boolean {\n return options[key] === undefined || (typeof options[key] === \"number\" && Number.isFinite(options[key] as number));\n}\n\n/** True when an optional numeric option is absent or a finite number of zero or more. */\nfunction nonnegativeoption(options: Record<string, unknown>, key: string): boolean {\n return numericoption(options, key) && !(typeof options[key] === \"number\" && (options[key] as number) < 0);\n}\n\nfunction isnonempty(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction ispoint(value: unknown): boolean {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const point = value as Record<string, unknown>;\n return typeof point.x === \"number\" && Number.isFinite(point.x) && typeof point.y === \"number\" && Number.isFinite(point.y);\n}\n\n/** Grades a resolution match count: zero is absent, one is resolved and more than one is refused as ambiguous. */\nexport function resolutionverdict(count: number): \"absent\" | \"resolved\" | \"ambiguous\" {\n if (!Number.isFinite(count) || count <= 0) return \"absent\";\n return count === 1 ? \"resolved\" : \"ambiguous\";\n}\n\n/** Validates the reviewed targetref grammar of every resolution mode and rejects empty references. */\nexport function validatetargetref(reference: unknown): policyevaluation {\n if (!reference || typeof reference !== \"object\" || Array.isArray(reference)) return { allowed: false, reason: \"The reviewed target reference must be an object.\" };\n const ref = reference as Record<string, unknown>;\n if (ref.mode === \"selector\") return isnonempty(ref.selector) ? { allowed: true } : { allowed: false, reason: \"The selector target reference needs a non-empty selector.\" };\n if (ref.mode === \"text\") return isnonempty(ref.text) ? { allowed: true } : { allowed: false, reason: \"The text target reference needs non-empty text.\" };\n if (ref.mode === \"aria\") {\n if (!isnonempty(ref.role)) return { allowed: false, reason: \"The aria target reference needs a non-empty role.\" };\n return isnonempty(ref.name) ? { allowed: true } : { allowed: false, reason: \"The aria target reference needs a non-empty name.\" };\n }\n if (ref.mode === \"name\") return isnonempty(ref.name) ? { allowed: true } : { allowed: false, reason: \"The name target reference needs a non-empty name.\" };\n if (ref.mode === \"xpath\") return isnonempty(ref.xpath) ? { allowed: true } : { allowed: false, reason: \"The xpath target reference needs a non-empty expression.\" };\n if (ref.mode === \"index\") {\n const index = ref.index;\n return typeof index === \"number\" && Number.isInteger(index) && index >= 1 ? { allowed: true } : { allowed: false, reason: \"The index target reference needs a positive integer map number.\" };\n }\n if (ref.mode === \"point\") {\n const pointok = typeof ref.x === \"number\" && Number.isFinite(ref.x) && typeof ref.y === \"number\" && Number.isFinite(ref.y);\n return pointok ? { allowed: true } : { allowed: false, reason: \"The point target reference needs numeric x and y coordinates.\" };\n }\n return { allowed: false, reason: \"The target reference mode must be selector, text, aria, name, xpath, index or point.\" };\n}\n\n/** True when the session origin grants cover the given origin; a session without grants only allows its own origin. */\nexport function origingranted(session: agentsession | undefined, origin: string): boolean {\n if (!session) return false;\n const grants = session.grants ?? [session.origin];\n return grants.includes(origin);\n}\n\n/** Validates the reviewed inner step of a retry or frame wrapper against the same rules as a top-level step. */\nfunction validateinnerstep(options: Record<string, unknown>, origin: string): policyevaluation {\n const stepid = options.stepid;\n const kind = options.kind;\n if (isnonempty(stepid)) {\n if (kind !== undefined) return { allowed: false, reason: \"The reviewed wrapper must reference a step id or an inline step, not both.\" };\n return { allowed: true };\n }\n if (typeof kind !== \"string\" || !kind.trim()) return { allowed: false, reason: \"A reviewed step id or inline step kind is required in options.\" };\n if (kind === \"retryaction\" || kind === \"enterframe\") return { allowed: false, reason: \"The reviewed inner step cannot be another wrapper kind.\" };\n if (!allowedactions.has(kind as actionkind)) return { allowed: false, reason: \"The reviewed inner step kind is unsupported.\" };\n const inneroptions = options.options;\n if (inneroptions !== undefined && (!inneroptions || typeof inneroptions !== \"object\" || Array.isArray(inneroptions))) return { allowed: false, reason: \"The reviewed inner step options must be an object.\" };\n const inner: toolstep = {\n id: \"inner\",\n kind: kind as actionkind,\n summary: \"Reviewed inner step.\",\n risk: actionrisk(kind as actionkind),\n ...(isnonempty(options.target) ? { target: options.target } : {}),\n ...(isnonempty(options.value) ? { value: options.value } : {}),\n ...(inneroptions !== undefined ? { options: JSON.stringify(inneroptions) } : {}),\n };\n return validatestep(inner, origin);\n}\n\n/** Validates a single proposal against the active tab origin and local policy. */\nexport function validatestep(step: toolstep, origin: string): policyevaluation {\n if (!allowedactions.has(step.kind)) return { allowed: false, reason: \"Unsupported action kind.\" };\n if (!step.summary.trim()) return { allowed: false, reason: \"A human-readable action summary is required.\" };\n let options: Record<string, unknown>;\n try { options = parseoptions(step); } catch { return { allowed: false, reason: \"Step options must be a JSON object.\" }; }\n const hastargetref = options.targetref !== undefined;\n if (targetactions.has(step.kind) && !step.target?.trim() && !hastargetref) return { allowed: false, reason: \"A page target is required.\" };\n if (valueactions.has(step.kind) && !step.value?.trim()) return { allowed: false, reason: \"A reviewed value is required.\" };\n if (step.kind === \"select\" && !step.value?.trim()) return { allowed: false, reason: \"A reviewed option value is required.\" };\n if (step.kind === \"navigate\" && !step.value) return { allowed: false, reason: \"A navigation URL is required.\" };\n if (hastargetref) {\n const reference = validatetargetref(options.targetref);\n if (!reference.allowed) return reference;\n }\n if (step.kind === \"wait\") {\n try { waitduration(step); } catch { return { allowed: false, reason: \"Wait duration must be zero or a positive number of milliseconds.\" }; }\n }\n if (step.kind === \"navigate\") {\n try {\n if (new URL(step.value ?? \"\").origin !== origin) return { allowed: false, reason: \"Navigation must remain within the approved origin.\" };\n } catch {\n return { allowed: false, reason: \"Navigation URL is invalid.\" };\n }\n }\n if (step.kind === \"tabcreate\" || step.kind === \"windowcreate\" || step.kind === \"downloadfile\") {\n try {\n const url = new URL(step.value ?? \"\");\n if (url.protocol !== \"https:\") return { allowed: false, reason: \"The reviewed URL must use HTTPS.\" };\n } catch {\n return { allowed: false, reason: \"The reviewed URL is invalid.\" };\n }\n }\n if (step.kind === \"tabactivate\" || step.kind === \"tabclose\" || step.kind === \"tabreload\" || step.kind === \"windowclose\" || step.kind === \"windowresize\") {\n if (!isnumericid(step.value)) return { allowed: false, reason: \"A numeric browser id is required.\" };\n }\n if (step.kind === \"zoomset\") {\n const zoom = Number(step.value);\n if (!Number.isFinite(zoom) || zoom <= 0) return { allowed: false, reason: \"The reviewed zoom must be a positive number.\" };\n }\n if (step.kind === \"setattribute\" || step.kind === \"writestorage\") {\n const keyname = step.kind === \"setattribute\" ? \"name\" : \"key\";\n if (typeof options[keyname] !== \"string\" || !(options[keyname] as string).trim()) return { allowed: false, reason: `A reviewed ${keyname} is required in options.` };\n if (typeof options.value !== \"string\") return { allowed: false, reason: \"A reviewed value is required in options.\" };\n }\n if (step.kind === \"windowresize\") {\n if (typeof options.width !== \"number\" || typeof options.height !== \"number\" || !Number.isFinite(options.width) || !Number.isFinite(options.height)) return { allowed: false, reason: \"Reviewed width and height numbers are required in options.\" };\n }\n if ((step.kind === \"scrollpage\" || step.kind === \"scrollby\") && (!numericoption(options, \"x\") || !numericoption(options, \"y\"))) return { allowed: false, reason: \"Scroll amounts must be numbers in options.\" };\n if (step.kind === \"waitfor\" && options.timeout !== undefined && (typeof options.timeout !== \"number\" || options.timeout < 0)) return { allowed: false, reason: \"The waitfor timeout must be zero or a positive number of milliseconds.\" };\n if (step.kind === \"movepointer\") {\n const path = options.pointpath;\n if (!path || typeof path !== \"object\" || Array.isArray(path)) return { allowed: false, reason: \"A reviewed pointpath with start and end points is required in options.\" };\n const points = path as Record<string, unknown>;\n if (!ispoint(points.start) || !ispoint(points.end)) return { allowed: false, reason: \"The reviewed pointpath needs numeric start and end points.\" };\n if (points.waypoints !== undefined && (!Array.isArray(points.waypoints) || !points.waypoints.every(waypoint => ispoint(waypoint)))) return { allowed: false, reason: \"The reviewed pointpath waypoints must be numeric points.\" };\n if (!nonnegativeoption(points, \"duration\")) return { allowed: false, reason: \"The reviewed pointpath duration must be zero or a positive number of milliseconds.\" };\n const speed = options.speedprofile;\n if (speed !== undefined) {\n if (!speed || typeof speed !== \"object\" || Array.isArray(speed)) return { allowed: false, reason: \"The reviewed speed profile must be an object.\" };\n const profile = speed as Record<string, unknown>;\n if (profile.easing !== undefined && profile.easing !== \"linear\" && profile.easing !== \"easeinout\") return { allowed: false, reason: \"The reviewed easing must be linear or easeinout.\" };\n if (!nonnegativeoption(profile, \"peak\")) return { allowed: false, reason: \"The reviewed peak velocity must be zero or a positive number.\" };\n if (!nonnegativeoption(profile, \"jitter\")) return { allowed: false, reason: \"The reviewed jitter window must be zero or a positive number of milliseconds.\" };\n }\n }\n if (step.kind === \"clickpoint\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"point\")) return { allowed: false, reason: \"A reviewed point target reference is required in options.\" };\n if (step.kind === \"clicktext\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"text\")) return { allowed: false, reason: \"A reviewed text target reference is required in options.\" };\n if (step.kind === \"clickaria\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"aria\")) return { allowed: false, reason: \"A reviewed aria target reference is required in options.\" };\n if (step.kind === \"clickname\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"name\")) return { allowed: false, reason: \"A reviewed name target reference is required in options.\" };\n if (step.kind === \"resolvexpath\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"xpath\")) return { allowed: false, reason: \"A reviewed xpath target reference is required in options.\" };\n if (step.kind === \"typetime\" && options.delay !== undefined && (typeof options.delay !== \"number\" || !Number.isFinite(options.delay) || options.delay < 0)) return { allowed: false, reason: \"The reviewed per keystroke delay must be zero or a positive number of milliseconds.\" };\n if (step.kind === \"submitsearch\") {\n if (!isnonempty(options.results)) return { allowed: false, reason: \"A reviewed results region selector is required in options.\" };\n if (options.timeout !== undefined && (typeof options.timeout !== \"number\" || !Number.isFinite(options.timeout) || options.timeout < 0)) return { allowed: false, reason: \"The submitsearch timeout must be zero or a positive number of milliseconds.\" };\n }\n if (step.kind === \"selectmulti\") {\n const values = options.values;\n if (!Array.isArray(values) || values.length === 0 || !values.every(value => isnonempty(value))) return { allowed: false, reason: \"A reviewed list of option values is required in options.\" };\n }\n if (step.kind === \"setslider\") {\n const slider = Number(step.value);\n if (!Number.isFinite(slider)) return { allowed: false, reason: \"The reviewed slider value must be a number.\" };\n }\n if (step.kind === \"setdate\" && !/^\\d{4}-\\d{2}-\\d{2}$/.test(step.value ?? \"\")) return { allowed: false, reason: \"The reviewed date must use the yyyy-mm-dd form.\" };\n if (step.kind === \"setcolor\" && !/^#[0-9a-fA-F]{6}$/.test(step.value ?? \"\")) return { allowed: false, reason: \"The reviewed color must use the #rrggbb form.\" };\n if (step.kind === \"keyhold\" && options.holdid !== undefined && !isnonempty(options.holdid)) return { allowed: false, reason: \"The reviewed hold id must be a non-empty string.\" };\n if (step.kind === \"dismissdialog\") {\n const accept = options.accept;\n const answer = options.answer;\n if (accept === undefined && !isnonempty(answer)) return { allowed: false, reason: \"A reviewed accept flag or prompt answer is required in options.\" };\n if (accept !== undefined && typeof accept !== \"boolean\") return { allowed: false, reason: \"The reviewed dialog accept flag must be a boolean.\" };\n if (answer !== undefined && !isnonempty(answer)) return { allowed: false, reason: \"The reviewed prompt answer must be a non-empty string.\" };\n }\n if (step.kind === \"pierceshadow\" && options.shadow !== undefined) {\n if (!Array.isArray(options.shadow) || !options.shadow.every(item => isnonempty(item))) return { allowed: false, reason: \"The reviewed shadow path must be a list of non-empty selectors.\" };\n }\n if (step.kind === \"enterframe\") {\n const path = options.framepath;\n if (!Array.isArray(path) || path.length === 0 || !path.every(item => typeof item === \"number\" && Number.isInteger(item) && item >= 0)) return { allowed: false, reason: \"A reviewed frame path of frame indexes is required in options.\" };\n return validateinnerstep(options, origin);\n }\n if (step.kind === \"retryaction\") {\n const inner = validateinnerstep(options, origin);\n if (!inner.allowed) return inner;\n const rule = options.retryrule;\n if (!rule || typeof rule !== \"object\" || Array.isArray(rule)) return { allowed: false, reason: \"A reviewed retry rule with attempts is required in options.\" };\n const retry = rule as Record<string, unknown>;\n if (typeof retry.attempts !== \"number\" || !Number.isInteger(retry.attempts) || retry.attempts < 1) return { allowed: false, reason: \"The reviewed retry attempts must be a positive integer with no code ceiling.\" };\n if (!nonnegativeoption(retry, \"settle\")) return { allowed: false, reason: \"The reviewed retry settle window must be zero or a positive number of milliseconds.\" };\n if (!nonnegativeoption(retry, \"tolerance\")) return { allowed: false, reason: \"The reviewed retry movement tolerance must be zero or a positive number of pixels.\" };\n }\n if (watchactions.has(step.kind)) {\n if (typeof options.lifetime !== \"number\" || !Number.isFinite(options.lifetime) || options.lifetime <= 0) return { allowed: false, reason: \"A reviewed watch lifetime window in milliseconds is required in options.\" };\n if (options.scopes !== undefined && (!Array.isArray(options.scopes) || !options.scopes.every(scope => isnonempty(scope)))) return { allowed: false, reason: \"The reviewed watch scopes must be a list of non-empty selectors.\" };\n if (options.events !== undefined && (!Array.isArray(options.events) || !options.events.every(event => isnonempty(event)))) return { allowed: false, reason: \"The reviewed watch event kinds must be a list of non-empty strings.\" };\n if (!nonnegativeoption(options, \"poll\")) return { allowed: false, reason: \"The reviewed watch poll interval must be zero or a positive number of milliseconds.\" };\n }\n if (step.kind === \"waitquiet\") {\n const rule = options.quietrule;\n if (!rule || typeof rule !== \"object\" || Array.isArray(rule)) return { allowed: false, reason: \"A reviewed quietrule with an idle threshold is required in options.\" };\n const quiet = rule as Record<string, unknown>;\n if (typeof quiet.idle !== \"number\" || !Number.isFinite(quiet.idle) || quiet.idle <= 0) return { allowed: false, reason: \"The reviewed quiet idle threshold must be a positive number of milliseconds with no code ceiling.\" };\n if (!nonnegativeoption(quiet, \"poll\")) return { allowed: false, reason: \"The reviewed quiet poll interval must be zero or a positive number of milliseconds.\" };\n if (!nonnegativeoption(quiet, \"timeout\")) return { allowed: false, reason: \"The reviewed quiet timeout must be zero or a positive number of milliseconds.\" };\n }\n if (step.kind === \"diffsnapshots\") {\n const versions = options.versions;\n if (!Array.isArray(versions) || versions.length !== 2 || !versions.every(version => typeof version === \"number\" && Number.isInteger(version) && version >= 1)) return { allowed: false, reason: \"Two reviewed observation version numbers are required in options.\" };\n }\n return { allowed: true };\n}\n\n/** Shared session gate: a live, unpaused session that still matches the active tab. */\nfunction sessiongate(input: { session: agentsession | undefined; tabid: number; origin: string; now: number; action: string }): policyevaluation {\n if (!input.session || input.session.stoppedat) return { allowed: false, reason: \"No active browser session exists.\" };\n if (input.session.expiresat <= input.now) return { allowed: false, reason: \"The browser session has expired.\" };\n if (input.session.pausedat) return { allowed: false, reason: `The browser session is paused and cannot ${input.action}.` };\n if (input.session.tabid !== input.tabid || input.session.origin !== input.origin) return { allowed: false, reason: `The ${input.action} is outside the approved tab or origin.` };\n return { allowed: true };\n}\n\n/** Applies the consent gate immediately before an action reaches the page bridge. */\nexport function canexecute(input: { session: agentsession | undefined; plan: agentplan | undefined; step: toolstep; tabid: number; origin: string; now?: number }): policyevaluation {\n const now = input.now ?? Date.now();\n const gate = sessiongate({ session: input.session, tabid: input.tabid, origin: input.origin, now, action: \"execute an action\" });\n if (!gate.allowed) return gate;\n if (!input.plan || input.plan.state !== \"approved\") return { allowed: false, reason: \"The plan has not received explicit approval.\" };\n if (input.plan.expiresat <= now) return { allowed: false, reason: \"The approved plan has expired.\" };\n if ((input.step.kind === \"pierceshadow\" || input.step.kind === \"enterframe\") && !origingranted(input.session, input.origin)) return { allowed: false, reason: \"The shadow or frame step is outside the session origin grants.\" };\n if (input.step.kind === \"readjson\" && !origingranted(input.session, input.origin)) return { allowed: false, reason: \"The json state read is outside the session origin grants.\" };\n return validatestep(input.step, input.origin);\n}\n\n/** Allows a non-mutating, temporary target preview during plan review. */\nexport function canpreview(input: { session: agentsession | undefined; plan: agentplan | undefined; step: toolstep; tabid: number; origin: string; now?: number }): policyevaluation {\n const now = input.now ?? Date.now();\n const gate = sessiongate({ session: input.session, tabid: input.tabid, origin: input.origin, now, action: \"preview a target\" });\n if (!gate.allowed) return gate;\n if (!input.plan || ![\"pending\", \"approved\"].includes(input.plan.state)) return { allowed: false, reason: \"Only a reviewed pending or approved plan can be previewed.\" };\n if (input.plan.expiresat <= now) return { allowed: false, reason: \"The reviewed plan has expired.\" };\n let options: Record<string, unknown> = {};\n try { options = parseoptions(input.step); } catch { options = {}; }\n if (!targetactions.has(input.step.kind) && options.targetref === undefined) return { allowed: false, reason: \"Only a target-based action can be previewed.\" };\n return validatestep(input.step, input.origin);\n}\n", "import type { agentplan, planprogress, stepoutcome } from \"./types.js\";\n\n/**\n * Execution-progress logics for reviewed plans.\n * Every correlated rule for step completion, outcome history, deduplication and plan closure lives in this file.\n */\n\n/** Returns a fresh progress record for a plan that has not executed any step yet. */\nexport function emptyprogress(planid: string, now: number): planprogress {\n return { planid, completedsteps: [], updatedat: now };\n}\n\n/** Records one successfully executed step; repeated executions of the same step stay deduplicated. */\nexport function recordstep(progress: planprogress | undefined, planid: string, stepid: string, now: number): planprogress {\n const base = progress && progress.planid === planid ? progress : emptyprogress(planid, now);\n if (base.completedsteps.includes(stepid)) return { ...base, updatedat: now };\n return { planid, completedsteps: [...base.completedsteps, stepid], updatedat: now };\n}\n\n/** Records one structured step outcome beside the completion log; outcomes are never truncated. */\nexport function recordoutcome(progress: planprogress | undefined, planid: string, outcome: stepoutcome, now: number): planprogress {\n const base = progress && progress.planid === planid ? progress : emptyprogress(planid, now);\n return { ...base, outcomes: [...(base.outcomes ?? []), outcome], updatedat: now };\n}\n\n/** True only when every step of the plan has a recorded, successful execution. */\nexport function iscomplete(progress: planprogress | undefined, plan: agentplan): boolean {\n if (!progress || progress.planid !== plan.id) return false;\n const required = plan.steps.map(step => step.id);\n return required.length > 0 && required.every(id => progress.completedsteps.includes(id));\n}\n\n/** Clears progress whenever a different plan replaces the tracked one while preserving prior history snapshots. */\nexport function resetforplan(progress: planprogress | undefined, plan: agentplan, now: number): planprogress {\n if (progress && progress.planid === plan.id) return progress;\n if (!progress) return emptyprogress(plan.id, now);\n const snapshot: planprogress = { planid: progress.planid, completedsteps: progress.completedsteps, ...(progress.outcomes ? { outcomes: progress.outcomes } : {}), updatedat: progress.updatedat };\n return { planid: plan.id, completedsteps: [], outcomes: [], prior: [...(progress.prior ?? []), snapshot], updatedat: now };\n}\n\n/** True when a reviewed watch lifetime window has closed at the given time. */\nexport function watchclosed(startedat: number, lifetime: number, now: number): boolean {\n return now >= startedat + lifetime;\n}\n\n/** Records one watch step as completed only once its reviewed lifetime window has closed. */\nexport function recordwatchcompletion(progress: planprogress | undefined, planid: string, stepid: string, startedat: number, lifetime: number, now: number): planprogress {\n const base = progress && progress.planid === planid ? progress : emptyprogress(planid, now);\n if (!watchclosed(startedat, lifetime, now)) return base;\n return recordstep(base, planid, stepid, now);\n}\n", "/** Canonical package version synchronized from package.json. */\nexport const packageversion = \"1.1.34\" as const;\n", "/** Shared contracts for every Devthink target. */\nimport { packageversion } from \"./version.js\";\n\nexport const protocolversion = packageversion;\n\n/** Every reviewed action kind. Read kinds observe, interaction kinds move focus, sensitive kinds change page or browser state. */\nexport type actionkind =\n | \"observe\" | \"inspect\" | \"extract\" | \"wait\" | \"waitfor\" | \"waittext\"\n | \"readattribute\" | \"readstyle\" | \"readgeometry\" | \"readvalue\" | \"readtext\" | \"readhtml\"\n | \"countelements\" | \"readtable\" | \"readlinks\" | \"readimages\" | \"readmeta\" | \"readforms\"\n | \"readstorage\" | \"highlight\" | \"tablist\" | \"windowlist\" | \"tabsnapshot\"\n | \"focus\" | \"scroll\" | \"hover\" | \"clickdeep\" | \"rightclick\" | \"doubleclick\"\n | \"scrollpage\" | \"scrollby\" | \"scrollend\" | \"scrolltop\" | \"fullscreen\" | \"zoomset\"\n | \"click\" | \"type\" | \"navigate\" | \"select\" | \"presskey\" | \"drag\" | \"drop\" | \"upload\"\n | \"clear\" | \"check\" | \"uncheck\" | \"toggle\" | \"submit\" | \"reload\" | \"back\" | \"forward\"\n | \"writestorage\" | \"setattribute\" | \"removeattribute\" | \"evaluate\"\n | \"tabcreate\" | \"tabactivate\" | \"tabclose\" | \"tabreload\"\n | \"windowcreate\" | \"windowclose\" | \"windowresize\" | \"downloadfile\"\n | \"movepointer\" | \"clickpoint\" | \"shiftclick\" | \"clicktext\" | \"clickaria\" | \"clickname\"\n | \"resolvexpath\" | \"typetime\" | \"appendtext\" | \"setvalue\" | \"typeedit\"\n | \"keyhold\" | \"keyrelease\" | \"submitsearch\" | \"selectmulti\" | \"chooseradio\"\n | \"setslider\" | \"setdate\" | \"setcolor\" | \"expanddetails\" | \"dismissdialog\"\n | \"pierceshadow\" | \"enterframe\" | \"retryaction\"\n | \"mapclicks\" | \"verifyvisible\" | \"verifyenabled\"\n | \"a11ytree\" | \"readvisible\" | \"readertree\" | \"detectlists\" | \"detecttables\"\n | \"readjson\" | \"watchmutate\" | \"waitquiet\" | \"watchbanner\" | \"detectinfinitescroll\"\n | \"detectvirtual\" | \"detectlazy\" | \"readscrollpos\" | \"readlang\" | \"readoutline\"\n | \"countpages\" | \"listshadow\" | \"listframes\" | \"classifypage\" | \"fingerprintsection\"\n | \"diffsnapshots\" | \"readselection\" | \"watchfocus\" | \"detectsticky\" | \"detectscrolllock\"\n | \"readopengraph\" | \"detectlanguage\" | \"deriveselector\";\n\nexport type actionrisk = \"read\" | \"interaction\" | \"sensitive\";\nexport type planstate = \"draft\" | \"pending\" | \"approved\" | \"rejected\" | \"expired\" | \"completed\" | \"cancelled\";\nexport type auditkind = \"configure\" | \"session\" | \"observe\" | \"proposal\" | \"approval\" | \"action\" | \"error\" | \"stop\" | \"pause\" | \"resume\" | \"complete\" | \"capability\" | \"tab\" | \"window\" | \"download\" | \"pointer\" | \"dialog\" | \"hold\" | \"retry\" | \"observation\" | \"watch\" | \"diff\";\n\n/** Observation mode classes: passive capture, watched lifetimes and diffing passes. */\nexport type observationmode = \"passive\" | \"watching\" | \"diffing\";\n\nexport interface toolstep {\n id: string;\n kind: actionkind;\n target?: string;\n value?: string;\n /** Reviewed JSON parameters such as modifiers, amounts or coordinates. */\n options?: string;\n summary: string;\n risk: actionrisk;\n}\n\nexport interface agentplan {\n id: string;\n objective: string;\n origin: string;\n steps: toolstep[];\n createdat: number;\n expiresat: number;\n state: planstate;\n approvedat?: number;\n completedat?: number;\n}\n\nexport interface agentsession {\n id: string;\n tabid: number;\n origin: string;\n startedat: number;\n expiresat: number;\n stoppedat?: number;\n pausedat?: number;\n /** Origins granted to this session; prepared for multi origin work. */\n grants?: string[];\n}\n\nexport interface endpointconfig {\n endpoint: string;\n origin: string;\n configuredat: number;\n}\n\nexport interface observation {\n /** Observation schema version for forward compatibility. */\n schemaversion: number;\n url: string;\n title: string;\n textpreview: string;\n textlength: number;\n forms: Array<{ label: string; type: string; name: string; options?: string[] }>;\n interactive: Array<{ selector: string; role: string; label: string }>;\n capturedat: number;\n /** Observation mode of this capture: passive, watching or diffing. */\n mode?: observationmode;\n /** Accessibility tree section captured by the page walker. */\n a11y?: a11ynode;\n /** Reader view article section extracted by the text density heuristic. */\n reader?: readerarticle;\n /** Repeated list patterns detected on the page. */\n listpattern?: listpattern[];\n /** Data table shapes detected on the page. */\n tableshape?: tableshape[];\n /** Snapshot diff section attached when two observation versions are compared. */\n diff?: snapshotdiff;\n}\n\nexport interface auditevent {\n id: string;\n kind: auditkind;\n at: number;\n summary: string;\n sessionid?: string;\n planid?: string;\n stepid?: string;\n}\n\nexport interface diagnosticreport {\n id: string;\n sessionid: string;\n origin: string;\n capturedat: number;\n tabid: number;\n title: string;\n textlength: number;\n interactivecount: number;\n formcount: number;\n bridgeavailable: boolean;\n}\n\n/** Live report of the optional browser capabilities the user has granted. */\nexport interface capabilityreport {\n tabs: boolean;\n downloads: boolean;\n clipboardread: boolean;\n clipboardwrite: boolean;\n reportedat: number;\n}\n\n/** Structured result of one executed step, kept with configurable retention. */\nexport interface stepoutcome {\n stepid: string;\n ok: boolean;\n summary: string;\n details?: Record<string, unknown>;\n at: number;\n}\n\n/** User chosen retention windows; an absent value keeps everything forever. */\nexport interface runsettings {\n auditretention?: number;\n outcomeretention?: number;\n /** Retention window for stored observation captures such as a11y trees and reader articles. */\n observationretention?: number;\n}\n\nexport interface proposalrequest {\n objective: string;\n session: agentsession;\n observation: observation;\n capabilities: capabilityreport;\n}\n\nexport interface planproposal {\n version: typeof protocolversion;\n plan: agentplan;\n}\n\nexport interface policyevaluation {\n allowed: boolean;\n reason?: string;\n}\n\n/** Tracks which reviewed steps of one plan have already executed locally. */\nexport interface planprogress {\n planid: string;\n completedsteps: string[];\n outcomes?: stepoutcome[];\n /** Prior progress snapshots preserved when a new plan replaces the tracked one. */\n prior?: planprogress[];\n updatedat: number;\n}\n\n/** Modes that address one element during target resolution. */\nexport type targetmode = \"selector\" | \"text\" | \"aria\" | \"name\" | \"xpath\" | \"index\" | \"point\";\n\n/** Reviewed element reference resolved by the page bridge at preview and execution time. */\nexport interface targetref {\n mode: targetmode;\n selector?: string;\n text?: string;\n role?: string;\n name?: string;\n xpath?: string;\n index?: number;\n x?: number;\n y?: number;\n}\n\n/** One point on a reviewed pointer path. */\nexport interface pointref {\n x: number;\n y: number;\n}\n\n/** Reviewed pointer path between two points through optional waypoints. */\nexport interface pointpath {\n start: pointref;\n end: pointref;\n waypoints?: pointref[];\n duration?: number;\n}\n\n/** Reviewed pointer speed shape with an easing curve, peak velocity and a jitter window. */\nexport interface speedprofile {\n easing?: \"linear\" | \"easeinout\";\n peak?: number;\n jitter?: number;\n}\n\n/** One key held down across steps under a hold id, with tab and step provenance. */\nexport interface keyholdstate {\n holdid: string;\n key: string;\n modifiers?: string[];\n tabid?: number;\n stepid?: string;\n pressedat: number;\n releasedat?: number;\n}\n\n/** Reviewed answers for confirm, alert and prompt dialogs; prompts need a reviewed answer. */\nexport interface dialogpolicy {\n accept: boolean;\n answer?: string;\n}\n\n/** Ordered frame indexes that address targets inside same origin iframes. */\nexport type framepath = number[];\n\n/** Ordered host selectors that address targets across open shadow roots. */\nexport type shadowpath = string[];\n\n/** Reviewed retry bounds with an attempt count that carries no hardcoded ceiling. */\nexport interface retryrule {\n attempts: number;\n settle?: number;\n tolerance?: number;\n}\n\n/** One numbered clickable element of a clickablemap. */\nexport interface mapentry {\n number: number;\n selector: string;\n role: string;\n label: string;\n mode: targetmode;\n}\n\n/** Numbered map of every clickable element captured inside one observation version. */\nexport interface clickablemap {\n version: number;\n entries: mapentry[];\n builtat: number;\n}\n\n/** Matched element summary attached to step results and review envelopes. */\nexport interface resolvedtarget {\n mode: targetmode;\n selector: string;\n tag: string;\n label: string;\n geometry: { x: number; y: number; width: number; height: number };\n candidates?: string[];\n}\n\n/** One dialog answered by the reviewed dialog policy, kept for the audit trail. */\nexport interface dialogdecision {\n id: string;\n dialog: string;\n text: string;\n accept: boolean;\n answer?: string;\n sessionid?: string;\n at: number;\n}\n\n/** One retry execution record with the attempts made and the movement delta observed between them. */\nexport interface retryoutcome {\n stepid: string;\n attempts: number;\n movement: number;\n ok: boolean;\n at: number;\n}\n\n/** Resolution summary stored per target mode for later selector derivation. */\nexport interface resolutionsummary {\n stepid: string;\n mode: targetmode;\n selector: string;\n label: string;\n at: number;\n}\n\n/** One accessibility tree node with role, accessible name, states, value and child refs. */\nexport interface a11ynode {\n role: string;\n name: string;\n states: string[];\n value?: string;\n childcount: number;\n children: a11ynode[];\n}\n\n/** One reader view article with title, byline, blocks and text statistics. */\nexport interface readerarticle {\n title: string;\n byline: string;\n blocks: Array<{ kind: string; text: string; words: number }>;\n words: number;\n characters: number;\n}\n\n/** One detected repeated list with its shared item selector, repeat count and samples. */\nexport interface listpattern {\n container: string;\n itemselector: string;\n repeat: number;\n samples: string[];\n}\n\n/** One detected data table shape with header row, column specs and caption. */\nexport interface tableshape {\n selector: string;\n headers: string[];\n columns: Array<{ label: string; cells: number }>;\n rows: number;\n caption: string;\n}\n\n/** One embedded json state payload extracted from an inline script. */\nexport interface jsonstate {\n scripturl: string;\n rootpath: string;\n payload: unknown;\n}\n\n/** Reviewed watch registration with selector scopes, event kinds and a lifetime window. */\nexport interface mutationwatch {\n watchid?: string;\n scopes?: string[];\n events?: string[];\n lifetime: number;\n}\n\n/** Reviewed network quiet rule with an idle threshold, poll interval and timeout. */\nexport interface quietrule {\n idle: number;\n poll?: number;\n timeout?: number;\n}\n\n/** One dom mutation observed inside a reviewed watch, with a timestamp and target path. */\nexport interface mutationevent {\n watchid: string;\n event: string;\n targetpath: string;\n sessionid?: string;\n at: number;\n}\n\n/** One focus change observed inside a reviewed focus watch, with a timestamp and target path. */\nexport interface focusevent {\n watchid: string;\n kind: \"focus\" | \"blur\";\n targetpath: string;\n sessionid?: string;\n at: number;\n}\n\n/** One consent banner observed by a reviewed banner watch, with its controls. */\nexport interface bannerreport {\n kind: string;\n selector: string;\n text: string;\n controls: string[];\n sessionid?: string;\n at: number;\n}\n\n/** One node change inside a snapshot diff. */\nexport interface diffentry {\n kind: \"added\" | \"removed\" | \"changed\";\n selector: string;\n summary: string;\n}\n\n/** One snapshot diff between two stored observation versions. */\nexport interface snapshotdiff {\n baseversion: number;\n targetversion: number;\n added: diffentry[];\n removed: diffentry[];\n changed: diffentry[];\n at: number;\n}\n\n/** One derived selector candidate with its strategy and stability score. */\nexport interface selectorcandidate {\n selector: string;\n strategy: string;\n score: number;\n}\n\n/** One derived selector stored with its stability score for reuse. */\nexport interface derivedselector {\n stepid: string;\n selector: string;\n strategy: string;\n score: number;\n at: number;\n}\n\n/** One watch registration persisted so watches survive service worker restarts. */\nexport interface watchregistration {\n watchid: string;\n kind: actionkind;\n stepid: string;\n sessionid: string;\n origin: string;\n scopes: string[];\n events: string[];\n startedat: number;\n lifetime: number;\n closedat?: number;\n}\n\n/** One stored observation capture under its version. */\nexport interface observationrecord {\n version: number;\n observation: observation;\n}\n\n/** One stored accessibility tree capture. */\nexport interface a11ycapture {\n version: number;\n tree: a11ynode;\n capturedat: number;\n}\n\n/** One stored reader article capture. */\nexport interface readercapture {\n version: number;\n article: readerarticle;\n capturedat: number;\n}\n\n/** Live page signals refreshed after observation steps: language, template, scroll lock and banner state. */\nexport interface pagesignals {\n language?: string;\n template?: string;\n scrolllocked?: boolean;\n banner?: string;\n refreshedat: number;\n}\n\n/** One detected template class or section fingerprint stored per origin. */\nexport interface templateprofile {\n origin: string;\n template: string;\n fingerprint: string;\n section?: string;\n at: number;\n}\n", "import { actionrisk, parseoptions, validatestep } from \"./policy.js\";\nimport { protocolversion, type agentplan, type bannerreport, type clickablemap, type focusevent, type keyholdstate, type mutationevent, type observation, type pagesignals, type planproposal, type proposalrequest, type resolvedtarget, type selectorcandidate, type snapshotdiff, type stepoutcome, type toolstep } from \"./types.js\";\n\nfunction record(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Protocol message must be an object.\");\n return value as Record<string, unknown>;\n}\n\nfunction text(value: unknown, field: string): string {\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`${field} must be a non-empty string.`);\n return value.trim();\n}\n\n/**\n * Reviewed options grammar shared by every step kind.\n *\n * A step may carry a JSON `options` object with the following reviewed fields:\n * - `targetref`: element addressing without a css selector, with `mode` one of `selector`, `text`, `aria`, `name`, `xpath`, `index` or `point`; the text mode carries `text`, the aria mode carries `role` plus `name`, the name mode carries `name`, the xpath mode carries `xpath`, the index mode carries a one based clickable map `index`, and the point mode carries viewport `x` and `y` coordinates.\n * - `pointpath`: pointer travel between two points, with `start` and `end` points, optional `waypoints` and a `duration` in milliseconds.\n * - `speedprofile`: pointer speed shape with `easing` (`linear` or `easeinout`), a `peak` velocity in pixels per second and a `jitter` window in milliseconds.\n * - `framepath`: ordered frame indexes routing a step inside same origin iframes.\n * - `shadow`: ordered host selectors addressing a target across open shadow roots.\n * - `retryrule`: retry bounds with `attempts`, a `settle` window in milliseconds and a movement `tolerance` in pixels; attempts carry no code ceiling.\n * - `dialogpolicy`: dialog answers with an `accept` flag and a reviewed prompt `answer` string.\n * - wrapper steps (`retryaction`, `enterframe`) reference an inner step by `stepid` or inline with `kind`, `target`, `value` and an `options` object.\n * - control kinds add reviewed `delay`, `values`, `results`, `timeout`, `holdid` and `modifiers` fields.\n * - watch kinds (`watchmutate`, `watchbanner`, `watchfocus`) carry a reviewed `lifetime` window in milliseconds, optional selector `scopes`, optional event kind filters `events` and an optional `poll` interval; the lifetime window carries no code ceiling.\n * - `waitquiet` carries a reviewed `quietrule` with a positive `idle` threshold in milliseconds, an optional `poll` interval and an optional `timeout`; every value carries no code ceiling.\n * - `diffsnapshots` carries exactly two reviewed observation `versions` to compare.\n * - observation kinds attach structured evidence to step details: a11y trees, reader articles, list patterns, table shapes, pagination estimates, watch event records, quiet probe samples, snapshot diffs and derived selector candidates with stability scores.\n *\n * Ambiguous text, aria or name resolutions are refused at execution time with the candidate list so the user can choose.\n */\n\n/** Validates agent output before it becomes a locally reviewable plan. Plans may carry any number of steps. */\nexport function parseproposal(value: unknown, origin: string): planproposal {\n const root = record(value);\n if (root.version !== protocolversion) throw new Error(\"Unsupported protocol version.\");\n const planinput = record(root.plan);\n const stepsinput = planinput.steps;\n if (!Array.isArray(stepsinput) || stepsinput.length === 0) throw new Error(\"A plan needs at least one step.\");\n const steps: toolstep[] = stepsinput.map((input, index) => {\n const candidate = record(input);\n const kind = text(candidate.kind, `step ${index + 1} kind`) as toolstep[\"kind\"];\n const step: toolstep = {\n id: typeof candidate.id === \"string\" ? candidate.id : crypto.randomUUID(),\n kind,\n summary: text(candidate.summary, `step ${index + 1} summary`),\n risk: actionrisk(kind),\n ...(typeof candidate.target === \"string\" ? { target: candidate.target } : {}),\n ...(typeof candidate.value === \"string\" ? { value: candidate.value } : {}),\n ...(typeof candidate.options === \"string\" ? { options: candidate.options } : {}),\n };\n const evaluation = validatestep(step, origin);\n if (!evaluation.allowed) throw new Error(evaluation.reason);\n return step;\n });\n for (const step of steps) {\n if (step.kind !== \"retryaction\" && step.kind !== \"enterframe\") continue;\n const options = parseoptions(step);\n if (typeof options.stepid === \"string\" && !steps.some(candidate => candidate.id === options.stepid)) throw new Error(\"A retry or frame wrapper references an unknown step id.\");\n }\n const createdat = Date.now();\n const expiresat = typeof planinput.expiresat === \"number\" ? planinput.expiresat : createdat + 10 * 60 * 1000;\n const plan: agentplan = {\n id: typeof planinput.id === \"string\" ? planinput.id : crypto.randomUUID(),\n objective: text(planinput.objective, \"objective\"),\n origin,\n steps,\n createdat,\n expiresat,\n state: \"pending\",\n };\n if (plan.expiresat <= createdat) throw new Error(\"Plan expiry must be in the future.\");\n return { version: protocolversion, plan };\n}\n\n/** Shapes the only data that may be sent to a user-configured agent endpoint. */\nexport function requestbody(input: proposalrequest): string {\n return JSON.stringify({ version: protocolversion, objective: input.objective, session: input.session, observation: input.observation, capabilities: input.capabilities });\n}\n\n/** Wraps one executed step outcome in the versioned response envelope for callers, attaching the matched element summary for review. */\nexport function outcomeresponse(input: { outcome: stepoutcome; plan: agentplan; resolvedtarget?: resolvedtarget }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, outcome: input.outcome, ...(input.resolvedtarget ? { resolvedtarget: input.resolvedtarget } : {}) });\n}\n\n/** Wraps a clickable map payload with numbered entries in the versioned response envelope. */\nexport function mapresponse(input: { map: clickablemap; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, map: input.map });\n}\n\n/** Reports the keys currently held on one tab for the live context envelope, refreshed per step. */\nexport function heldkeysreport(input: { tabid: number; holds: keyholdstate[] }): { version: typeof protocolversion; tabid: number; heldkeys: keyholdstate[] } {\n return { version: protocolversion, tabid: input.tabid, heldkeys: input.holds };\n}\n\n/** Wraps one observation capture with its a11y, reader, listpattern, tableshape and diff sections in the versioned response envelope. */\nexport function observationresponse(input: { observation: observation; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, observation: input.observation });\n}\n\n/** Wraps mutation, focus and banner event records with their timestamps and target paths in the versioned response envelope. */\nexport function eventresponse(input: { events: Array<mutationevent | focusevent | bannerreport>; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, events: input.events });\n}\n\n/** Wraps one snapshot diff with its added, removed and changed nodes and its two observation versions in the versioned response envelope. */\nexport function diffresponse(input: { diff: snapshotdiff; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, diff: input.diff });\n}\n\n/** Reports the detected page language, template class, scroll lock and banner state in the live context envelope. */\nexport function signalsreport(input: { signals?: pagesignals }): { version: typeof protocolversion; language?: string; template?: string; scrolllocked?: boolean; banner?: string } {\n const signals = input.signals;\n return {\n version: protocolversion,\n ...(signals && signals.language !== undefined ? { language: signals.language } : {}),\n ...(signals && signals.template !== undefined ? { template: signals.template } : {}),\n ...(signals && signals.scrolllocked !== undefined ? { scrolllocked: signals.scrolllocked } : {}),\n ...(signals && signals.banner !== undefined ? { banner: signals.banner } : {}),\n };\n}\n\n/** Wraps derived selector candidates with their stability scores in the versioned response envelope. */\nexport function selectorresponse(input: { candidates: selectorcandidate[]; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, candidates: input.candidates });\n}\n", "import type { capabilityreport, toolstep } from \"../types.js\";\n\n/**\n * Browser-level command surface for reviewed steps.\n * Every correlated rule for tab, window, zoom, snapshot and download actions plus capability negotiation lives in this file.\n */\n\nexport type browserresult = { ok: boolean; summary: string; details?: Record<string, unknown> };\n\nconst browserkinds: ReadonlySet<string> = new Set([\"tablist\", \"tabcreate\", \"tabactivate\", \"tabclose\", \"tabreload\", \"tabsnapshot\", \"windowlist\", \"windowcreate\", \"windowclose\", \"zoomset\", \"windowresize\", \"downloadfile\"]);\n\n/** True when the kind executes against browser-level surfaces instead of the page. */\nexport function isbrowserkind(kind: string): boolean {\n return browserkinds.has(kind);\n}\n\n/** Builds the live capability report from the optional permissions the user granted. */\nexport async function readcapabilities(): Promise<capabilityreport> {\n const [tabs, downloads, clipboardread, clipboardwrite] = await Promise.all([\n chrome.permissions.contains({ permissions: [\"tabs\"] }),\n chrome.permissions.contains({ permissions: [\"downloads\"] }),\n chrome.permissions.contains({ permissions: [\"clipboardRead\"] }),\n chrome.permissions.contains({ permissions: [\"clipboardWrite\"] }),\n ]);\n return { tabs, downloads, clipboardread, clipboardwrite, reportedat: Date.now() };\n}\n\nfunction stepoptions(step: toolstep): Record<string, unknown> {\n if (!step.options) return {};\n try {\n const parsed = JSON.parse(step.options);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};\n } catch { return {}; }\n}\n\nfunction tabid(step: toolstep): number {\n return Number.parseInt(step.value ?? \"\", 10);\n}\n\n/** Executes one reviewed browser-level action kind against the live browser. */\nexport async function runbrowseraction(step: toolstep, sessiontabid: number, windowid: number): Promise<browserresult> {\n const options = stepoptions(step);\n switch (step.kind) {\n case \"tablist\": {\n const tabs = await chrome.tabs.query({});\n return { ok: true, summary: `Listed ${tabs.length} open tab${tabs.length === 1 ? \"\" : \"s\"}.`, details: { tabs: tabs.map(tab => ({ id: tab.id ?? 0, index: tab.index, title: tab.title ?? \"\", url: tab.url ?? \"\", active: tab.active, pinned: tab.pinned, audible: tab.audible ?? false })) } };\n }\n case \"tabcreate\": {\n const created = await chrome.tabs.create({ url: step.value, active: options.active !== false, pinned: options.pinned === true });\n return { ok: true, summary: `Opened a new tab for ${step.value}.`, details: { tabid: created?.id ?? 0 } };\n }\n case \"tabactivate\": {\n await chrome.tabs.update(tabid(step), { active: true });\n return { ok: true, summary: `Activated tab ${tabid(step)}.` };\n }\n case \"tabclose\": {\n await chrome.tabs.remove(tabid(step));\n return { ok: true, summary: `Closed tab ${tabid(step)}.` };\n }\n case \"tabreload\": {\n await chrome.tabs.reload(tabid(step), { bypassCache: options.bypasscache === true });\n return { ok: true, summary: `Reloaded tab ${tabid(step)}.` };\n }\n case \"tabsnapshot\": {\n const shot = await chrome.tabs.captureVisibleTab(windowid, { format: \"png\" });\n return { ok: true, summary: \"Captured the visible area of the active tab.\", details: { shot } };\n }\n case \"windowlist\": {\n const windows = await chrome.windows.getAll();\n return { ok: true, summary: `Listed ${windows.length} open window${windows.length === 1 ? \"\" : \"s\"}.`, details: { windows: windows.map(item => ({ id: item.id ?? 0, type: item.type, state: item.state ?? \"\", focused: item.focused })) } };\n }\n case \"windowcreate\": {\n const created = await chrome.windows.create({ url: step.value ?? \"about:blank\", ...(typeof options.width === \"number\" ? { width: options.width } : {}), ...(typeof options.height === \"number\" ? { height: options.height } : {}) });\n return { ok: true, summary: `Opened a new window for ${step.value}.`, details: { windowid: created?.id ?? 0 } };\n }\n case \"windowclose\": {\n await chrome.windows.remove(tabid(step));\n return { ok: true, summary: `Closed window ${tabid(step)}.` };\n }\n case \"zoomset\": {\n const zoom = Number(step.value);\n await chrome.tabs.setZoom(sessiontabid, zoom);\n return { ok: true, summary: `Set the tab zoom to ${zoom}.` };\n }\n case \"windowresize\": {\n await chrome.windows.update(tabid(step), { width: options.width as number, height: options.height as number });\n return { ok: true, summary: `Resized window ${tabid(step)}.` };\n }\n case \"downloadfile\": {\n const downloadid = await chrome.downloads.download({ url: step.value ?? \"\" });\n return { ok: true, summary: `Started the download of ${step.value}.`, details: { downloadid } };\n }\n default: return { ok: false, summary: \"Unsupported browser action.\" };\n }\n}\n", "import type { dialogpolicy, toolstep } from \"../types.js\";\nimport { parseoptions } from \"../policy.js\";\n\n/**\n * Dialog policy logics for reviewed steps.\n * Every correlated rule for policy parsing, dialog answers, main world handler installation and observed dialog harvesting lives in this file.\n * The isolated world cannot override window.confirm, window.alert or window.prompt, so the background installs these wrappers through the scripting api in the main world.\n */\n\n/** One dialog observed by the main world handler, recorded on the shared document. */\nexport interface observeddialog {\n dialog: string;\n text: string;\n result: string | boolean | null;\n at: number;\n}\n\n/** Parses the reviewed dialog policy from step options; prompts need a reviewed answer. */\nexport function parsedialogpolicy(step: toolstep): dialogpolicy | null {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { return null; }\n const accept = options.accept;\n const answer = options.answer;\n if (typeof accept !== \"boolean\" && typeof answer !== \"string\") return null;\n return { accept: accept === true, ...(typeof answer === \"string\" && answer.trim() ? { answer } : {}) };\n}\n\n/** Decides how the reviewed policy answers one dialog kind; a prompt without a reviewed answer is dismissed. */\nexport function dialoganswer(policy: dialogpolicy, dialog: \"confirm\" | \"alert\" | \"prompt\"): { accept: boolean; answer?: string } {\n if (dialog === \"prompt\") {\n if (policy.answer === undefined || policy.answer === \"\") return { accept: false };\n return { accept: policy.accept !== false, ...(policy.answer !== undefined ? { answer: policy.answer } : {}) };\n }\n return { accept: policy.accept };\n}\n\n/** Reads and clears the dialog log the main world handler recorded on the shared document. */\nexport function harvestdialoglog(root: Document): observeddialog[] {\n const raw = root.documentElement.dataset.devthinkdialoglog;\n if (!raw) return [];\n delete root.documentElement.dataset.devthinkdialoglog;\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((item): item is observeddialog => Boolean(item) && typeof item === \"object\" && typeof (item as Record<string, unknown>).dialog === \"string\");\n } catch { return []; }\n}\n\n/** Installs confirm, alert and prompt wrappers in the page main world answering per the reviewed policy; runs through chrome.scripting with world main. */\nexport function installdialoghandler(accept: boolean, answer: string, persistent: boolean): void {\n const world = globalThis as typeof globalThis & { devthinkoriginaldialogs?: { confirm: (text?: string) => boolean; alert: (text?: string) => void; prompt: (text?: string, defaultvalue?: string) => string | null } };\n const originals = world.devthinkoriginaldialogs ?? { confirm: window.confirm.bind(window), alert: window.alert.bind(window), prompt: window.prompt.bind(window) };\n world.devthinkoriginaldialogs = originals;\n const decide = (dialog: string): { accept: boolean; answer: string | null } => {\n if (dialog === \"prompt\") return answer ? { accept: true, answer } : { accept: false, answer: null };\n return { accept, answer: null };\n };\n const record = (dialog: string, text: string, result: string | boolean | null): void => {\n try {\n const root = document.documentElement;\n const log = JSON.parse(root.dataset.devthinkdialoglog ?? \"[]\") as unknown[];\n log.push({ dialog, text, result, at: Date.now() });\n root.dataset.devthinkdialoglog = JSON.stringify(log);\n } catch { /* a locked down page refuses dataset writes; the handler still answers */ }\n };\n window.confirm = (text?: string): boolean => {\n const decision = decide(\"confirm\");\n record(\"confirm\", text ?? \"\", decision.accept);\n if (!persistent) window.confirm = originals.confirm;\n return decision.accept;\n };\n window.alert = (text?: string): void => {\n record(\"alert\", text ?? \"\", true);\n if (!persistent) window.alert = originals.alert;\n };\n window.prompt = (text?: string, defaultvalue?: string): string | null => {\n const decision = decide(\"prompt\");\n const outcome = decision.accept ? (decision.answer ?? defaultvalue ?? \"\") : null;\n record(\"prompt\", text ?? \"\", outcome);\n if (!persistent) window.prompt = originals.prompt;\n return outcome;\n };\n}\n", "import type { retryrule, toolstep } from \"../types.js\";\nimport { parseoptions } from \"../policy.js\";\nimport type { stepresult } from \"./pageactions.js\";\nimport { describeframes, queryscoped, queryshadowchain, resolvestep, targetsummary, walkframepath } from \"./pageresolve.js\";\nimport { dispatchclick, ensurevisible } from \"./pagepointer.js\";\n\n/**\n * Resolution driven interactions for reviewed steps.\n * Every correlated rule for text, aria and name clicks, shadow piercing, frame routing, wrapper step extraction and the retry loop lives in this file.\n */\n\n/** Reads the reviewed options of a step without throwing on malformed payloads. */\nfunction optionsof(step: toolstep): Record<string, unknown> {\n try { return parseoptions(step); } catch { return {}; }\n}\n\n/** Extracts the reviewed inner step of a retry or frame wrapper from its inline options. */\nexport function innerstep(step: toolstep): toolstep | null {\n const options = optionsof(step);\n const kind = options.kind;\n if (typeof kind !== \"string\" || !kind.trim()) return null;\n const inneroptions = options.options;\n return {\n id: `${step.id}inner`,\n kind: kind as toolstep[\"kind\"],\n summary: step.summary,\n risk: step.risk,\n ...(typeof options.target === \"string\" ? { target: options.target } : {}),\n ...(typeof options.value === \"string\" ? { value: options.value } : {}),\n ...(inneroptions && typeof inneroptions === \"object\" && !Array.isArray(inneroptions) ? { options: JSON.stringify(inneroptions) } : {}),\n };\n}\n\nfunction pointdistance(a: { x: number; y: number }, b: { x: number; y: number }): number {\n return Math.hypot(b.x - a.x, b.y - a.y);\n}\n\nfunction settle(delay: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, delay));\n}\n\nexport interface retryoutcomeplan {\n ok: boolean;\n attempts: number;\n movement: number;\n summary: string;\n}\n\n/** Runs the reviewed retry loop: each failed attempt waits the settle window, revalidates the target geometry and reruns only when the element moved beyond the tolerance. */\nexport async function runretries(rule: retryrule, probe: () => Promise<{ x: number; y: number } | null>, execute: (attempt: number) => Promise<{ ok: boolean; summary: string }>): Promise<retryoutcomeplan> {\n const attempts = Math.max(1, Number.isFinite(rule.attempts) ? Math.floor(rule.attempts) : 1);\n const tolerance = typeof rule.tolerance === \"number\" && Number.isFinite(rule.tolerance) ? rule.tolerance : 0;\n const settles = typeof rule.settle === \"number\" && Number.isFinite(rule.settle) ? rule.settle : 0;\n let previous = await probe();\n let movement = 0;\n let made = 0;\n let last = \"\";\n for (let attempt = 1; attempt <= attempts; attempt += 1) {\n made = attempt;\n const result = await execute(attempt);\n last = result.summary;\n if (result.ok) return { ok: true, attempts: made, movement, summary: `Retry interaction succeeded on attempt ${made} after ${movement.toFixed(1)} pixels of observed movement.` };\n if (attempt >= attempts) break;\n if (settles > 0) await settle(settles);\n const current = await probe();\n if (!current) { previous = null; continue; }\n if (previous) {\n const delta = pointdistance(previous, current);\n movement = Math.max(movement, delta);\n if (delta <= tolerance) return { ok: false, attempts: made, movement, summary: `The target stayed within the reviewed tolerance of ${tolerance} pixels; retry stopped after attempt ${made}. ${last}` };\n }\n previous = current;\n }\n return { ok: false, attempts: made, movement, summary: `Retry interaction failed after ${made} attempt${made === 1 ? \"\" : \"s\"} with ${movement.toFixed(1)} pixels of observed movement. ${last}` };\n}\n\n/** Dispatches one reviewed click on a resolved element and reports the target mode used. */\nfunction clickresolved(stepkind: string, resolution: ReturnType<typeof resolvestep>): stepresult {\n if (resolution.status === \"ambiguous\") return { ok: false, summary: `The reviewed ${resolution.mode} reference matched ${resolution.candidates.length} elements: ${resolution.candidates.join(\"; \")}.`, details: { mode: resolution.mode, candidates: resolution.candidates } };\n if (resolution.status !== \"resolved\") return { ok: false, summary: \"The reviewed target is no longer available.\" };\n ensurevisible(resolution.element);\n dispatchclick(resolution.element);\n return { ok: true, summary: `Clicked ${resolution.target.label || resolution.target.tag} resolved by ${stepkind} ${resolution.target.mode} mode.`, details: { mode: resolution.target.mode, resolvedtarget: resolution.target } };\n}\n\n/** Runs one resolution driven interaction: text, aria and name clicks, shadow piercing and frame routing. */\nexport function runinteractstep(step: toolstep, expectedorigin: string, dispatch: (inner: toolstep, origin: string, root?: Document) => stepresult | Promise<stepresult>): stepresult | Promise<stepresult> {\n if (step.kind === \"clicktext\" || step.kind === \"clickaria\" || step.kind === \"clickname\") {\n return clickresolved(step.kind, resolvestep(step, document));\n }\n if (step.kind === \"pierceshadow\") {\n const options = optionsof(step);\n const shadow = Array.isArray(options.shadow) ? options.shadow.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const element = shadow.length > 0 ? queryshadowchain(document, shadow) : queryscoped(document, step.target ?? \"\");\n if (!(element instanceof HTMLElement)) return { ok: false, summary: \"The reviewed shadow target is not available.\" };\n ensurevisible(element);\n dispatchclick(element);\n const summary = targetsummary(\"selector\", element);\n return { ok: true, summary: `Clicked ${summary.label || summary.tag} resolved through ${shadow.length > 0 ? \"the reviewed shadow path\" : \"open shadow roots\"}.`, details: { mode: \"selector\", resolvedtarget: summary } };\n }\n if (step.kind === \"enterframe\") {\n const options = optionsof(step);\n const path = Array.isArray(options.framepath) ? options.framepath.filter((item): item is number => typeof item === \"number\" && Number.isInteger(item) && item >= 0) : [];\n const walk = walkframepath(describeframes(document), path);\n if (!walk.ok) return { ok: false, summary: walk.reason };\n const framedocument = walk.document.live;\n if (!framedocument) return { ok: false, summary: \"The reviewed frame document is not available.\" };\n const inner = innerstep(step);\n if (!inner) return { ok: false, summary: \"The reviewed inner step is absent.\" };\n return dispatch(inner, expectedorigin, framedocument);\n }\n return { ok: false, summary: \"Unsupported interaction action.\" };\n}\n", "import type { keyholdstate, toolstep } from \"../types.js\";\nimport { parseoptions } from \"../policy.js\";\nimport type { stepresult } from \"./pageactions.js\";\nimport { clean } from \"./pageresolve.js\";\n\n/**\n * Field and control interactions for reviewed steps.\n * Every correlated rule for timed typing, value setting, key holds, search submission, multi selects, radio choices, sliders, dates, colors, details sections and the hold registry lives in this file.\n */\n\n/** Builds the per keystroke schedule of one reviewed typetime step. */\nexport function typetimeschedule(text: string, delay: number): Array<{ key: string; delay: number }> {\n return [...text].map((character, position) => ({ key: character, delay: position === 0 ? 0 : delay }));\n}\n\n/** Appends reviewed text to the current field value. */\nexport function appendvalue(current: string, addition: string): string {\n return current + addition;\n}\n\n/** Event order delivered after one reviewed value change. */\nexport function valueevents(): string[] {\n return [\"input\", \"change\"];\n}\n\n/** Splits reviewed multi select values into present and missing entries against the declared options. */\nexport function multichoices(values: string[], options: Array<{ value: string; label: string }>): { present: string[]; missing: string[] } {\n const present: string[] = [];\n const missing: string[] = [];\n for (const value of values) {\n const option = options.find(candidate => candidate.value === value || candidate.label === value);\n if (option) present.push(option.value);\n else missing.push(value);\n }\n return { present, missing };\n}\n\n/** Picks the reviewed radio input by value or label from one radio group; the index of the match or minus one. */\nexport function radiochoice(inputs: Array<{ value: string; label: string }>, choice: string): number {\n return inputs.findIndex(candidate => candidate.value === choice || candidate.label === choice);\n}\n\n/** Clamps one reviewed slider value to the declared range and step grid. */\nexport function slidervalue(requested: number, min: number, max: number, step: number): number {\n const lower = Math.min(min, max);\n const upper = Math.max(min, max);\n const clamped = Math.min(upper, Math.max(lower, requested));\n if (!Number.isFinite(step) || step <= 0) return clamped;\n return Math.round((clamped - lower) / step) * step + lower;\n}\n\n/** Validates and normalizes one reviewed yyyy-mm-dd date. */\nexport function datevalue(requested: string): string | null {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(requested)) return null;\n const parts = requested.split(\"-\").map(part => Number.parseInt(part, 10));\n const year = parts[0];\n const month = parts[1];\n const day = parts[2];\n if (!year || !month || !day || month < 1 || month > 12 || day < 1 || day > 31) return null;\n return requested;\n}\n\n/** Validates and normalizes one reviewed #rrggbb color. */\nexport function colorvalue(requested: string): string | null {\n if (!/^#[0-9a-fA-F]{6}$/.test(requested)) return null;\n return requested.toLowerCase();\n}\n\n/** Decides whether one reviewed details section still needs opening. */\nexport function expandstate(open: boolean): { open: boolean; changed: boolean } {\n return open ? { open: true, changed: false } : { open: true, changed: true };\n}\n\n/** Records one held key under its hold id; a repeated active hold id is refused. */\nexport function presshold(holds: keyholdstate[], hold: keyholdstate): { holds: keyholdstate[]; ok: boolean } {\n if (holds.some(existing => existing.holdid === hold.holdid && existing.releasedat === undefined)) return { holds, ok: false };\n return { holds: [...holds, hold], ok: true };\n}\n\n/** Releases one held key by hold id, keeping the release timestamp. */\nexport function releasehold(holds: keyholdstate[], holdid: string, releasedat: number): { holds: keyholdstate[]; released?: keyholdstate } {\n let released: keyholdstate | undefined;\n const next = holds.map(hold => {\n if (hold.holdid !== holdid || hold.releasedat !== undefined) return hold;\n released = { ...hold, releasedat };\n return released;\n });\n return { holds: next, ...(released ? { released } : {}) };\n}\n\n/** Returns the keys currently held, optionally filtered to one tab. */\nexport function heldkeys(holds: keyholdstate[], tabid?: number): keyholdstate[] {\n return holds.filter(hold => hold.releasedat === undefined && (tabid === undefined || hold.tabid === undefined || hold.tabid === tabid));\n}\n\nfunction events(target: Element): void {\n target.dispatchEvent(new Event(\"input\", { bubbles: true }));\n target.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n\nfunction modifiers(options: Record<string, unknown>): string[] {\n return Array.isArray(options.modifiers) ? options.modifiers.filter((item): item is string => typeof item === \"string\") : [];\n}\n\nfunction keyevent(type: \"keydown\" | \"keyup\", key: string, mods: string[]): KeyboardEvent {\n const code = key.length === 1 ? `Key${key.toUpperCase()}` : key;\n return new KeyboardEvent(type, { key, code, bubbles: true, cancelable: true, composed: true, ctrlKey: mods.includes(\"ctrl\"), shiftKey: mods.includes(\"shift\"), altKey: mods.includes(\"alt\"), metaKey: mods.includes(\"meta\") });\n}\n\nfunction fieldlike(target: Element | null): HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null {\n return target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement ? target : null;\n}\n\nfunction receiver(target: Element | null): HTMLElement {\n return target instanceof HTMLElement ? target : document.activeElement instanceof HTMLElement ? document.activeElement : document.body;\n}\n\nfunction wait(delay: number): Promise<void> {\n return new Promise(resolve => window.setTimeout(resolve, delay));\n}\n\n/** Focuses the reviewed target before typing; an explicit reviewed focus option forces or suppresses the focus. */\nfunction focuswhenneeded(target: Element, options: Record<string, unknown>): void {\n if (!(target instanceof HTMLElement)) return;\n if (options.focus === false) return;\n if (options.focus === true || document.activeElement !== target) target.focus();\n}\n\nfunction pollfor(predicate: () => boolean, description: string, timeout: number): Promise<stepresult> {\n return new Promise(resolve => {\n const started = Date.now();\n const check = (): void => {\n if (predicate()) { resolve({ ok: true, summary: `${description} is now present on the page.` }); return; }\n if (timeout > 0 && Date.now() - started >= timeout) { resolve({ ok: false, summary: `${description} did not appear within ${timeout} milliseconds.` }); return; }\n window.setTimeout(check, 100);\n };\n check();\n });\n}\n\n/** Runs one reviewed control interaction after the background policy gate and a fresh target check; frame routed steps receive their frame document as the root. */\nexport function runpagecontrol(step: toolstep, target: Element | null, root: Document = document): stepresult | Promise<stepresult> {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n switch (step.kind) {\n case \"typetime\": {\n const field = fieldlike(target);\n if (!field) return { ok: false, summary: \"Target cannot receive timed text.\" };\n const text = step.value ?? \"\";\n const delay = typeof options.delay === \"number\" && options.delay > 0 ? options.delay : 0;\n focuswhenneeded(field, options);\n const schedule = typetimeschedule(text, delay);\n return (async (): Promise<stepresult> => {\n for (const entry of schedule) {\n await wait(entry.delay);\n field.dispatchEvent(keyevent(\"keydown\", entry.key, []));\n field.dispatchEvent(new KeyboardEvent(\"keypress\", { key: entry.key, bubbles: true, cancelable: true }));\n field.value = `${field.value}${entry.key}`;\n field.dispatchEvent(new Event(\"input\", { bubbles: true }));\n }\n field.dispatchEvent(new Event(\"change\", { bubbles: true }));\n return { ok: true, summary: `Typed ${text.length} character${text.length === 1 ? \"\" : \"s\"} with a per keystroke delay of ${delay} milliseconds.` };\n })();\n }\n case \"appendtext\": {\n const field = fieldlike(target);\n if (!field) return { ok: false, summary: \"Target cannot hold a value.\" };\n focuswhenneeded(field, options);\n field.value = appendvalue(field.value, step.value ?? \"\");\n events(field);\n return { ok: true, summary: \"Reviewed text appended to the current field value.\" };\n }\n case \"setvalue\": {\n const field = fieldlike(target);\n if (!field) return { ok: false, summary: \"Target cannot hold a value.\" };\n focuswhenneeded(field, options);\n field.value = step.value ?? \"\";\n events(field);\n return { ok: true, summary: `Field value set through the dom property with ${valueevents().join(\" and \")} events.` };\n }\n case \"typeedit\": {\n if (!(target instanceof HTMLElement) || !target.isContentEditable) return { ok: false, summary: \"Target is not a content editable region.\" };\n focuswhenneeded(target, options);\n const text = step.value ?? \"\";\n return (async (): Promise<stepresult> => {\n for (const character of [...text]) {\n target.dispatchEvent(new InputEvent(\"beforeinput\", { bubbles: true, cancelable: true, data: character, inputType: \"insertText\" }));\n target.append(document.createTextNode(character));\n target.dispatchEvent(new InputEvent(\"input\", { bubbles: true, data: character, inputType: \"insertText\" }));\n }\n return { ok: true, summary: `Typed ${text.length} character${text.length === 1 ? \"\" : \"s\"} into the content editable region.` };\n })();\n }\n case \"keyhold\": {\n const key = step.value ?? \"\";\n const mods = modifiers(options);\n receiver(target).dispatchEvent(keyevent(\"keydown\", key, mods));\n const holdid = typeof options.holdid === \"string\" && options.holdid ? options.holdid : \"\";\n return { ok: true, summary: `Key ${key} pressed and held${holdid ? ` under hold id ${holdid}` : \"\"}.`, details: { ...(holdid ? { holdid } : {}), modifiers: mods } };\n }\n case \"keyrelease\": {\n const key = step.value ?? \"\";\n const mods = modifiers(options);\n receiver(target).dispatchEvent(keyevent(\"keyup\", key, mods));\n return { ok: true, summary: `Key ${key} released.`, details: { modifiers: mods } };\n }\n case \"submitsearch\": {\n const field = fieldlike(target);\n if (!field) return { ok: false, summary: \"Target is not a search field.\" };\n const results = typeof options.results === \"string\" ? options.results : \"\";\n const timeout = typeof options.timeout === \"number\" ? options.timeout : 0;\n focuswhenneeded(field, options);\n field.dispatchEvent(keyevent(\"keydown\", \"Enter\", []));\n field.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \"Enter\", bubbles: true, cancelable: true }));\n field.dispatchEvent(keyevent(\"keyup\", \"Enter\", []));\n return pollfor(() => Boolean(document.querySelector(results)), `Results region ${results}`, timeout);\n }\n case \"selectmulti\": {\n if (!(target instanceof HTMLSelectElement) || !target.multiple) return { ok: false, summary: \"Target is not a multi select control.\" };\n const choices = [...target.options].map(option => ({ value: option.value, label: clean(option.textContent || option.value) }));\n const requested = Array.isArray(options.values) ? options.values.filter((item): item is string => typeof item === \"string\") : [];\n const outcome = multichoices(requested, choices);\n if (outcome.missing.length > 0) return { ok: false, summary: `Reviewed option${outcome.missing.length === 1 ? \"\" : \"s\"} ${outcome.missing.join(\", \")} ${outcome.missing.length === 1 ? \"is\" : \"are\"} not part of the select control.` };\n for (const option of target.options) option.selected = outcome.present.includes(option.value);\n events(target);\n return { ok: true, summary: `Selected ${outcome.present.length} reviewed option${outcome.present.length === 1 ? \"\" : \"s\"} in the multi select control.`, details: { selected: outcome.present } };\n }\n case \"chooseradio\": {\n const radios = target instanceof HTMLInputElement && target.type === \"radio\"\n ? [...root.querySelectorAll<HTMLInputElement>(`input[type=radio][name=\"${CSS.escape(target.name)}\"]`)]\n : target ? [...(target as ParentNode).querySelectorAll<HTMLInputElement>(\"input[type=radio]\")] : [];\n if (radios.length === 0) return { ok: false, summary: \"No radio group owns the reviewed target.\" };\n const inputs = radios.map(radio => ({ value: radio.value, label: radio.labels && radio.labels.length > 0 ? clean(radio.labels[0]?.textContent || \"\") || radio.value : radio.value }));\n const index = radiochoice(inputs, step.value ?? \"\");\n const chosen = radios[index];\n if (!chosen) return { ok: false, summary: \"The reviewed radio option is not part of the group.\" };\n chosen.checked = true;\n events(chosen);\n return { ok: true, summary: `Picked reviewed radio option ${step.value}.`, details: { value: chosen.value } };\n }\n case \"setslider\": {\n if (!(target instanceof HTMLInputElement) || target.type !== \"range\") return { ok: false, summary: \"Target is not a range slider.\" };\n const requested = Number(step.value);\n if (!Number.isFinite(requested)) return { ok: false, summary: \"The reviewed slider value is not a number.\" };\n focuswhenneeded(target, options);\n const value = slidervalue(requested, Number(target.min), Number(target.max), Number(target.step));\n target.value = String(value);\n events(target);\n return { ok: true, summary: `Slider dragged to the reviewed value ${value}.`, details: { value } };\n }\n case \"setdate\": {\n if (!(target instanceof HTMLInputElement) || target.type !== \"date\") return { ok: false, summary: \"Target is not a date input.\" };\n const value = datevalue(step.value ?? \"\");\n if (value === null) return { ok: false, summary: \"The reviewed date is invalid.\" };\n focuswhenneeded(target, options);\n target.value = value;\n events(target);\n return { ok: true, summary: `Date input set to ${value}.`, details: { value } };\n }\n case \"setcolor\": {\n if (!(target instanceof HTMLInputElement) || target.type !== \"color\") return { ok: false, summary: \"Target is not a color input.\" };\n const value = colorvalue(step.value ?? \"\");\n if (value === null) return { ok: false, summary: \"The reviewed color is invalid.\" };\n focuswhenneeded(target, options);\n target.value = value;\n events(target);\n return { ok: true, summary: `Color input set to ${value}.`, details: { value } };\n }\n case \"expanddetails\": {\n const details = target instanceof HTMLElement ? target.closest(\"details\") : null;\n if (!details) return { ok: false, summary: \"Target is not inside a details section.\" };\n const outcome = expandstate(details.open);\n details.open = outcome.open;\n return { ok: true, summary: outcome.changed ? \"Collapsed details section opened.\" : \"Details section was already open.\", details: { changed: outcome.changed } };\n }\n default: return { ok: false, summary: \"Unsupported control action.\" };\n }\n}\n", "import { randomid, sessionmemory } from \"../memory.js\";\nimport { canexecute, canpreview, hostpattern, normalizeendpoint, parseoptions, requiredcapability, validatestep } from \"../policy.js\";\nimport { iscomplete, recordoutcome, recordstep, recordwatchcompletion, resetforplan, watchclosed } from \"../progress.js\";\nimport { heldkeysreport, mapresponse, observationresponse, outcomeresponse, parseproposal, requestbody, signalsreport } from \"../protocol.js\";\nimport type { a11ynode, agentplan, agentsession, auditevent, bannerreport, capabilityreport, clickablemap, derivedselector, diagnosticreport, diffentry, dialogdecision, dialogpolicy, focusevent, keyholdstate, mapentry, mutationevent, observation, pagesignals, readerarticle, resolvedtarget, retryoutcome, retryrule, selectorcandidate, snapshotdiff, stepoutcome, templateprofile, toolstep, watchregistration } from \"../types.js\";\nimport { isbrowserkind, readcapabilities, runbrowseraction } from \"./browsertabs.js\";\nimport { dialoganswer, installdialoghandler, parsedialogpolicy, type observeddialog } from \"./pagedialogs.js\";\nimport { innerstep, runretries } from \"./pageinteract.js\";\nimport { heldkeys, presshold, releasehold } from \"./pagecontrols.js\";\nimport type { nodesummary } from \"./pagewatch.js\";\n\nconst sessionduration = 15 * 60 * 1000;\nconst freshcheckkinds: ReadonlySet<string> = new Set([\"focus\", \"inspect\", \"click\", \"type\", \"scroll\", \"select\", \"hover\"]);\nconst pointerkinds: ReadonlySet<string> = new Set([\"movepointer\", \"clickpoint\", \"shiftclick\", \"clicktext\", \"clickaria\", \"clickname\", \"pierceshadow\"]);\nconst watchstepkinds: ReadonlySet<string> = new Set([\"watchmutate\", \"watchbanner\", \"watchfocus\"]);\nconst observationstepkinds: ReadonlySet<string> = new Set([\"a11ytree\", \"readvisible\", \"readertree\", \"detectlists\", \"detecttables\", \"readjson\", \"detectinfinitescroll\", \"detectvirtual\", \"detectlazy\", \"readscrollpos\", \"readlang\", \"readoutline\", \"countpages\", \"listshadow\", \"listframes\", \"classifypage\", \"fingerprintsection\", \"readselection\", \"detectsticky\", \"detectscrolllock\", \"readopengraph\", \"detectlanguage\", \"deriveselector\"]);\n\nconst chromestorage = {\n async get<T>(key: string): Promise<T | undefined> { return (await chrome.storage.local.get(key))[key] as T | undefined; },\n async set<T>(key: string, value: T): Promise<void> { await chrome.storage.local.set({ [key]: value }); },\n};\nconst memory = new sessionmemory(chromestorage);\n\ntype stepoutput = { ok: boolean; summary: string; details?: Record<string, unknown> };\n\nfunction extensionpage(sender: chrome.runtime.MessageSender): boolean {\n return sender.id === chrome.runtime.id && Boolean(sender.url?.startsWith(chrome.runtime.getURL(\"\")));\n}\n\nasync function audit(kind: auditevent[\"kind\"], summary: string, extra: Partial<auditevent> = {}): Promise<void> {\n await memory.addaudi({ id: randomid(), kind, at: Date.now(), summary, ...extra });\n}\n\n/** Reads the reviewed options of a step without throwing on malformed payloads. */\nfunction stepoptions(step: toolstep): Record<string, unknown> {\n try { return parseoptions(step); } catch { return {}; }\n}\n\n/** Refreshes and persists the capability report negotiated through the permissions api. */\nasync function refreshcapabilities(): Promise<capabilityreport> {\n const report = await readcapabilities();\n await memory.setcapabilities(report);\n return report;\n}\n\nasync function activecontext(): Promise<{ tab: chrome.tabs.Tab; origin: string }> {\n const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });\n if (!tab?.id || !tab.url) throw new Error(\"No active web tab is available.\");\n const origin = new URL(tab.url).origin;\n if (!origin.startsWith(\"https://\")) throw new Error(\"Devthink can work with HTTPS pages only.\");\n return { tab, origin };\n}\n\nasync function snapshot(tabid: number): Promise<observation> {\n await chrome.scripting.executeScript({ target: { tabId: tabid }, files: [\"pagebridge.js\"] });\n const result = await chrome.scripting.executeScript({ target: { tabId: tabid }, func: () => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { capturesnapshot: () => observation } }).devthinkbridge;\n if (!bridge) throw new Error(\"Devthink page bridge is unavailable.\");\n return bridge.capturesnapshot();\n } });\n const value = result[0]?.result;\n if (!value) throw new Error(\"The page did not return an observation.\");\n const observationcapture = value as observation;\n const version = await memory.nextobservationversion();\n await memory.setobservation({ version, observation: observationcapture });\n return observationcapture;\n}\n\n/** Finds the reviewed dialog policy of a plan, if the user reviewed a dismissdialog step. */\nfunction plandialogpolicy(plan: agentplan | undefined): dialogpolicy | null {\n const step = plan?.steps.find(candidate => candidate.kind === \"dismissdialog\");\n return step ? parsedialogpolicy(step) : null;\n}\n\n/** Installs the reviewed dialog handler in the main world of one tab; the isolated world cannot override window dialogs. */\nasync function installdialogpolicy(tabid: number, policy: dialogpolicy, persistent: boolean): Promise<void> {\n await chrome.scripting.executeScript({\n target: { tabId: tabid },\n world: \"MAIN\",\n func: installdialoghandler,\n args: [policy.accept, policy.answer ?? \"\", persistent],\n });\n}\n\n/** Applies the reviewed dialog policy before any step dispatch so unexpected dialogs cannot block the page. */\nasync function ensuredialoghandler(plan: agentplan | undefined, tabid: number): Promise<void> {\n const policy = plandialogpolicy(plan) ?? await memory.getdialogpolicy();\n if (!policy) return;\n try { await installdialogpolicy(tabid, policy, true); } catch { /* the page may refuse scripting; the step still dispatches */ }\n}\n\n/** Reads observed dialogs from the page and records each as an audited dialog decision with the reviewed answer. */\nasync function harvestdialogs(session: agentsession | undefined, plan: agentplan | undefined, stepid: string, tabid: number): Promise<void> {\n const policy = plandialogpolicy(plan) ?? await memory.getdialogpolicy();\n let observed: observeddialog[] = [];\n try {\n const result = await chrome.scripting.executeScript({ target: { tabId: tabid }, func: () => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { readdialogs?: () => unknown[] } }).devthinkbridge;\n return bridge?.readdialogs ? bridge.readdialogs() : [];\n } });\n const value = result[0]?.result;\n if (Array.isArray(value)) observed = value as observeddialog[];\n } catch { /* the page may refuse scripting; no dialogs can be harvested */ }\n for (const entry of observed) {\n const reviewed = policy ? dialoganswer(policy, ([\"confirm\", \"alert\", \"prompt\"] as const).includes(entry.dialog as \"confirm\" | \"alert\" | \"prompt\") ? entry.dialog as \"confirm\" | \"alert\" | \"prompt\" : \"confirm\") : undefined;\n const decision: dialogdecision = {\n id: randomid(),\n dialog: entry.dialog,\n text: entry.text,\n accept: reviewed ? reviewed.accept : entry.result !== null && entry.result !== false,\n ...(reviewed?.answer !== undefined ? { answer: reviewed.answer } : {}),\n ...(session ? { sessionid: session.id } : {}),\n at: Number.isFinite(entry.at) ? entry.at : Date.now(),\n };\n await memory.adddialog(decision);\n await audit(\"dialog\", `Dialog ${decision.dialog} answered ${decision.accept ? \"accept\" : \"dismiss\"}${decision.answer ? ` with the reviewed answer \"${decision.answer}\"` : \"\"} for dialog text \"${decision.text.slice(0, 120)}\".`, { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid });\n }\n}\n\n/** Dispatches one reviewed page step through the page bridge after arming the reviewed dialog handler. */\nasync function dispatchpagestep(step: toolstep, tabid: number, origin: string, plan?: agentplan): Promise<stepoutput | undefined> {\n const session = await memory.getsession();\n const activeplan = plan ?? await memory.getplan();\n await ensuredialoghandler(activeplan, tabid);\n const result = await chrome.scripting.executeScript({ target: { tabId: tabid }, func: (action: toolstep, expectedorigin: string) => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { performstep: (input: toolstep, origin: string) => Promise<{ ok: boolean; summary: string; details?: Record<string, unknown> }> } }).devthinkbridge;\n if (!bridge) throw new Error(\"Devthink page bridge is unavailable.\");\n return bridge.performstep(action, expectedorigin);\n }, args: [step, origin] });\n await harvestdialogs(session, activeplan, step.id, tabid);\n return result[0]?.result as stepoutput | undefined;\n}\n\nasync function startsession(): Promise<agentsession> {\n const { tab, origin } = await activecontext();\n const session: agentsession = { id: randomid(), tabid: tab.id as number, origin, startedat: Date.now(), expiresat: Date.now() + sessionduration, grants: [origin] };\n await memory.setsession(session);\n await audit(\"session\", `Session started for ${origin}.`, { sessionid: session.id });\n const policy = await memory.getdialogpolicy();\n if (policy) {\n try { await installdialogpolicy(session.tabid, policy, true); } catch { /* the auto handler is best effort until the page accepts scripting */ }\n }\n return session;\n}\n\nasync function diagnostic(): Promise<diagnosticreport> {\n const session = await memory.getsession();\n const { tab, origin } = await activecontext();\n if (!session || session.stoppedat || session.expiresat <= Date.now() || session.tabid !== tab.id || session.origin !== origin) throw new Error(\"Start a current session for this active tab before diagnostics.\");\n const observation = await snapshot(session.tabid);\n const report: diagnosticreport = { id: randomid(), sessionid: session.id, origin, capturedat: Date.now(), tabid: session.tabid, title: observation.title, textlength: observation.textlength, interactivecount: observation.interactive.length, formcount: observation.forms.length, bridgeavailable: true };\n await memory.setdiagnostic(report);\n await audit(\"observe\", \"Structured diagnostics captured for the approved active tab.\", { sessionid: session.id });\n return report;\n}\n\nfunction localplan(objective: string, session: agentsession): agentplan {\n const now = Date.now();\n return { id: randomid(), objective, origin: session.origin, steps: [{ id: randomid(), kind: \"observe\", summary: \"Capture a complete semantic snapshot of the approved active tab.\", risk: \"read\" }], createdat: now, expiresat: now + sessionduration, state: \"pending\" };\n}\n\nasync function propose(objective: string, remote: boolean): Promise<agentplan> {\n if (!objective.trim()) throw new Error(\"An objective is required.\");\n const session = await memory.getsession();\n if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error(\"Start a current browser session before requesting a plan.\");\n const { tab, origin } = await activecontext();\n if (session.tabid !== tab.id || session.origin !== origin) throw new Error(\"The selected tab or origin no longer matches the approved session.\");\n const observation = await snapshot(session.tabid);\n const capabilities = await refreshcapabilities();\n const config = await memory.getconfig();\n let plan = localplan(objective.trim(), session);\n if (remote) {\n if (!config) throw new Error(\"Configure an approved HTTPS endpoint before requesting a remote proposal.\");\n const response = await fetch(config.endpoint, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, credentials: \"omit\", body: requestbody({ objective: objective.trim(), session, observation, capabilities }) });\n if (!response.ok) throw new Error(`Proposal endpoint returned ${response.status}.`);\n plan = parseproposal(await response.json(), session.origin).plan;\n }\n await memory.setplan(plan);\n await memory.setprogress(resetforplan(await memory.getprogress(), plan, Date.now()));\n await audit(\"proposal\", `Plan proposed with ${plan.steps.length} reviewed step${plan.steps.length === 1 ? \"\" : \"s\"}.`, { sessionid: session.id, planid: plan.id });\n return plan;\n}\n\nfunction browserauditkind(step: toolstep): auditevent[\"kind\"] {\n if (step.kind === \"downloadfile\") return \"download\";\n if (step.kind.startsWith(\"window\")) return \"window\";\n return \"tab\";\n}\n\n/** Maps one page step to its audit kind, covering the pointer, dialog, hold, retry, observation, watch and diff event families. */\nfunction stepauditkind(step: toolstep, ok: boolean): auditevent[\"kind\"] {\n if (isbrowserkind(step.kind)) return browserauditkind(step);\n if (step.kind === \"dismissdialog\") return \"dialog\";\n if (step.kind === \"keyhold\" || step.kind === \"keyrelease\") return \"hold\";\n if (step.kind === \"retryaction\") return \"retry\";\n if (pointerkinds.has(step.kind)) return \"pointer\";\n if (watchstepkinds.has(step.kind)) return \"watch\";\n if (step.kind === \"diffsnapshots\") return \"diff\";\n if (observationstepkinds.has(step.kind)) return \"observation\";\n return ok ? \"action\" : \"error\";\n}\n\n/** Resolves the reviewed inner step of a retry or frame wrapper from a step id or inline options. */\nfunction resolvedinnerstep(step: toolstep, plan: agentplan): toolstep | null {\n const options = stepoptions(step);\n if (typeof options.stepid === \"string\" && options.stepid.trim()) {\n return plan.steps.find(candidate => candidate.id === options.stepid) ?? null;\n }\n return innerstep(step);\n}\n\n/** Executes one reviewed key hold: the page dispatches the keydown and the registry keeps the hold across steps. */\nasync function executekeyhold(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const output = await dispatchpagestep(step, tabid, origin, plan);\n if (!output?.ok) return output ?? { ok: false, summary: \"The key hold was not delivered.\" };\n const options = stepoptions(step);\n const holdid = typeof options.holdid === \"string\" && options.holdid.trim() ? options.holdid : randomid();\n const modifiers = Array.isArray(options.modifiers) ? options.modifiers.filter((item): item is string => typeof item === \"string\") : [];\n const hold: keyholdstate = { holdid, key: step.value ?? \"\", ...(modifiers.length > 0 ? { modifiers } : {}), tabid, stepid: step.id, pressedat: Date.now() };\n const next = presshold(await memory.getholds(), hold);\n if (!next.ok) return { ok: false, summary: `Hold id ${holdid} is already held.` };\n await memory.setholds(next.holds);\n await audit(\"hold\", `Key ${hold.key} held under hold id ${holdid} pressed at ${new Date(hold.pressedat).toISOString()}.`, { ...(session ? { sessionid: session.id } : {}), planid: plan.id, stepid: step.id });\n return { ok: true, summary: `Key ${hold.key} held under hold id ${holdid}.`, details: { holdid } };\n}\n\n/** Executes one reviewed key release: the held key receives its keyup and the registry records the release. */\nasync function executekeyrelease(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const holdid = step.value ?? \"\";\n const holds = await memory.getholds();\n const held = holds.find(candidate => candidate.holdid === holdid && candidate.releasedat === undefined);\n if (!held) throw new Error(`No held key matches hold id ${holdid}.`);\n const modifiers = held.modifiers ?? [];\n const dispatchstep: toolstep = { ...step, value: held.key, options: JSON.stringify({ ...(modifiers.length > 0 ? { modifiers } : {}) }) };\n const output = await dispatchpagestep(dispatchstep, tabid, origin, plan);\n const releasedat = Date.now();\n const transition = releasehold(holds, holdid, releasedat);\n await memory.setholds(transition.holds);\n await audit(\"hold\", `Key ${held.key} released from hold id ${holdid} at ${new Date(releasedat).toISOString()} after ${Math.max(0, releasedat - held.pressedat)} milliseconds.`, { ...(session ? { sessionid: session.id } : {}), planid: plan.id, stepid: step.id });\n return { ok: output?.ok ?? false, summary: output?.summary ?? \"Key release delivered.\", details: { holdid } };\n}\n\n/** Executes one reviewed dismissdialog step: one-shot main world wrappers answer the next dialog per the reviewed policy. */\nasync function executedismissdialog(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const policy = parsedialogpolicy(step);\n if (!policy) throw new Error(\"A reviewed dialog policy is required.\");\n await installdialogpolicy(tabid, policy, false);\n await harvestdialogs(session, plan, step.id, tabid);\n const answer = policy.answer !== undefined ? ` with the reviewed answer \"${policy.answer}\"` : \"\";\n return { ok: true, summary: `Dialog handler armed${answer} for the next confirm, alert or prompt.` };\n}\n\n/** Executes one reviewed retryaction step: the loop enforces the reviewed bounds, revalidates geometry between attempts and records the outcome. */\nasync function executeretryaction(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const rule = stepoptions(step).retryrule as retryrule | undefined;\n const inner = resolvedinnerstep(step, plan);\n if (!inner) throw new Error(\"The reviewed wrapper step could not be resolved.\");\n const innergate = validatestep(inner, origin);\n if (!innergate.allowed) throw new Error(`The wrapped step is not allowed: ${innergate.reason}`);\n const probe = async (): Promise<{ x: number; y: number } | null> => {\n const probestep: toolstep = { id: `${step.id}probe`, kind: \"readgeometry\", summary: step.summary, risk: \"read\", ...(inner.target ? { target: inner.target } : {}), ...(inner.options ? { options: inner.options } : {}) };\n const output = await dispatchpagestep(probestep, tabid, origin, plan);\n const geometry = output?.details?.geometry as { x?: unknown; y?: unknown } | undefined;\n if (!geometry || typeof geometry.x !== \"number\" || typeof geometry.y !== \"number\" || !Number.isFinite(geometry.x) || !Number.isFinite(geometry.y)) return null;\n return { x: geometry.x, y: geometry.y };\n };\n const execute = async (): Promise<{ ok: boolean; summary: string }> => {\n const output = await dispatchpagestep(inner, tabid, origin, plan);\n return { ok: Boolean(output?.ok), summary: output?.summary ?? \"The wrapped step returned no result.\" };\n };\n const outcome = await runretries(rule ?? { attempts: 1 }, probe, execute);\n const record: retryoutcome = { stepid: step.id, attempts: outcome.attempts, movement: outcome.movement, ok: outcome.ok, at: Date.now() };\n await memory.addretry(record);\n await audit(\"retry\", outcome.summary, { ...(session ? { sessionid: session.id } : {}), planid: plan.id, stepid: step.id });\n return { ok: outcome.ok, summary: outcome.summary, details: { attempts: outcome.attempts, movement: outcome.movement } };\n}\n\n/** Executes one reviewed mapclicks step: the page builds the numbered map and memory stores it under a fresh observation version. */\nasync function executemapclicks(step: toolstep, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const output = await dispatchpagestep(step, tabid, origin, plan);\n if (!output?.ok) return output ?? { ok: false, summary: \"The clickable map was not captured.\" };\n const entries = Array.isArray(output.details?.entries) ? output.details?.entries as mapentry[] : [];\n const version = await memory.nextobservationversion();\n const map: clickablemap = { version, entries, builtat: Date.now() };\n await memory.setmap(map);\n return { ok: true, summary: output.summary, details: { entries, mapversion: version } };\n}\n\n/** Executes one reviewed enterframe step: the background resolves the wrapped step and the bridge routes it inside the same origin frame. */\nasync function executeenterframe(step: toolstep, plan: agentplan, tabid: number, origin: string): Promise<stepoutput | undefined> {\n const inner = resolvedinnerstep(step, plan);\n if (!inner) throw new Error(\"The reviewed frame wrapper step could not be resolved.\");\n const innergate = validatestep(inner, origin);\n if (!innergate.allowed) throw new Error(`The wrapped step is not allowed: ${innergate.reason}`);\n const options = stepoptions(step);\n const inneroptions = inner.options ? stepoptions(inner) : undefined;\n const derived: toolstep = { ...step, options: JSON.stringify({ ...options, kind: inner.kind, ...(inner.target ? { target: inner.target } : {}), ...(inner.value ? { value: inner.value } : {}), ...(inneroptions ? { options: inneroptions } : {}) }) };\n return dispatchpagestep(derived, tabid, origin, plan);\n}\n\n/** Converts one observation interactive inventory into the node summaries the diff engine compares. */\nfunction observationnodes(observationcapture: observation): nodesummary[] {\n return observationcapture.interactive.map(entry => ({ selector: entry.selector, tag: entry.role, text: entry.label, attributes: {} }));\n}\n\nfunction detailarray(details: Record<string, unknown> | undefined, key: string): unknown[] {\n const value = details?.[key];\n return Array.isArray(value) ? value : [];\n}\n\n/** Executes one reviewed diffsnapshots step: the background loads both observation versions, injects their node summaries and attaches the version pair to the diff result. */\nasync function executediffsnapshots(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const options = stepoptions(step);\n const versions = Array.isArray(options.versions) ? options.versions.filter((item): item is number => typeof item === \"number\") : [];\n const baseversion = versions[0];\n const targetversion = versions[1];\n if (baseversion === undefined || targetversion === undefined) throw new Error(\"Two reviewed observation versions are required.\");\n const base = await memory.getobservation(baseversion);\n const target = await memory.getobservation(targetversion);\n if (!base || !target) throw new Error(\"A reviewed observation version has not been captured yet.\");\n const derived: toolstep = { ...step, options: JSON.stringify({ ...options, base: observationnodes(base.observation), target: observationnodes(target.observation) }) };\n const output = await dispatchpagestep(derived, tabid, origin, plan) ?? { ok: false, summary: \"The snapshot diff returned no result.\" };\n const diff: snapshotdiff = {\n baseversion,\n targetversion,\n added: detailarray(output.details, \"added\") as diffentry[],\n removed: detailarray(output.details, \"removed\") as diffentry[],\n changed: detailarray(output.details, \"changed\") as diffentry[],\n at: Date.now(),\n };\n await memory.adddiff(diff);\n await audit(\"diff\", `Diffed observation versions ${baseversion} and ${targetversion}: ${diff.added.length} added, ${diff.removed.length} removed and ${diff.changed.length} changed nodes.`, { ...(session ? { sessionid: session.id } : {}), planid: plan.id, stepid: step.id });\n return { ok: Boolean(output.ok), summary: output.summary, details: { ...(output.details ?? {}), versions: [baseversion, targetversion] } };\n}\n\n/** Executes one reviewed watch step: the registration persists across service worker restarts, the bridge observes for the reviewed lifetime and the observed events land in the step result stream. */\nasync function executewatchstep(step: toolstep, session: agentsession, plan: agentplan, tabid: number, origin: string): Promise<{ output: stepoutput; watch: watchregistration }> {\n const options = stepoptions(step);\n const watchid = typeof options.watchid === \"string\" && options.watchid.trim() ? options.watchid : randomid();\n const scopes = Array.isArray(options.scopes) ? options.scopes.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const events = Array.isArray(options.events) ? options.events.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const lifetime = typeof options.lifetime === \"number\" && Number.isFinite(options.lifetime) && options.lifetime > 0 ? options.lifetime : 0;\n const watch: watchregistration = { watchid, kind: step.kind, stepid: step.id, sessionid: session.id, origin, scopes, events, startedat: Date.now(), lifetime };\n await memory.addwatch(watch);\n await audit(\"watch\", `Watch ${step.kind} registered under id ${watchid} for the reviewed lifetime of ${lifetime} milliseconds inside ${scopes.length > 0 ? `scopes ${scopes.join(\", \")}` : \"the whole document\"}.`, { sessionid: session.id, planid: plan.id, stepid: step.id });\n const output = await dispatchpagestep(step, tabid, origin, plan) ?? { ok: false, summary: \"The watch returned no result.\" };\n await memory.closewatch(watchid, Date.now());\n if (step.kind === \"watchmutate\") {\n for (const entry of detailarray(output.details, \"events\")) {\n if (!entry || typeof entry !== \"object\") continue;\n const record = entry as mutationevent;\n await memory.addmutationevent({ ...record, sessionid: session.id });\n }\n }\n if (step.kind === \"watchfocus\") {\n for (const entry of detailarray(output.details, \"events\")) {\n if (!entry || typeof entry !== \"object\") continue;\n const record = entry as focusevent;\n await memory.addfocusevent({ ...record, sessionid: session.id });\n }\n }\n if (step.kind === \"watchbanner\") {\n for (const entry of detailarray(output.details, \"banners\")) {\n if (!entry || typeof entry !== \"object\") continue;\n const record = entry as bannerreport;\n await memory.addbanner({ ...record, sessionid: session.id });\n }\n }\n await audit(\"watch\", `Watch ${watchid} closed after its reviewed lifetime of ${lifetime} milliseconds.`, { sessionid: session.id, planid: plan.id, stepid: step.id });\n return { output, watch };\n}\n\n/** Refreshes the live page signals of language, template, scroll lock and banner state from observation step evidence. */\nasync function refreshsignals(step: toolstep, output: stepoutput | undefined): Promise<void> {\n const current = await memory.getsignals();\n const next: pagesignals = current ? { ...current, refreshedat: Date.now() } : { refreshedat: Date.now() };\n let changed = false;\n if (step.kind === \"readlang\" || step.kind === \"detectlanguage\") {\n const language = output?.details?.language;\n if (typeof language === \"string\" && language) { next.language = language; changed = true; }\n }\n if (step.kind === \"classifypage\") {\n const template = output?.details?.template;\n if (typeof template === \"string\" && template) { next.template = template; changed = true; }\n }\n if (step.kind === \"detectscrolllock\") {\n const locked = output?.details?.locked;\n if (typeof locked === \"boolean\") { next.scrolllocked = locked; changed = true; }\n }\n if (step.kind === \"watchbanner\") {\n const banners = detailarray(output?.details, \"banners\");\n const first = banners[0] as { kind?: unknown } | undefined;\n if (first && typeof first.kind === \"string\") { next.banner = first.kind; changed = true; }\n }\n if (changed) await memory.setsignals(next);\n}\n\n/** Records the observation evidence of one executed page step: a11y trees, reader articles, template profiles and derived selectors. */\nasync function recordevidence(step: toolstep, output: stepoutput | undefined, session: agentsession | undefined, plan: agentplan | undefined, origin: string): Promise<void> {\n const extra = { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid: step.id };\n if (step.kind === \"a11ytree\" && output?.details?.tree && typeof output.details.tree === \"object\") {\n const version = await memory.nextobservationversion();\n await memory.adda11ytree({ version, tree: output.details.tree as a11ynode, capturedat: Date.now() });\n await audit(\"observation\", `Accessibility tree captured under observation version ${version} with ${output.details.nodecount ?? \"an unknown count of\"} nodes.`, extra);\n }\n if (step.kind === \"readertree\" && output?.details?.article && typeof output.details.article === \"object\") {\n const version = await memory.nextobservationversion();\n const article = output.details.article as readerarticle;\n await memory.addreaderarticle({ version, article, capturedat: Date.now() });\n await audit(\"observation\", `Reader article captured under observation version ${version} with ${article.blocks.length} blocks and ${article.words} words.`, extra);\n }\n if (step.kind === \"classifypage\" && typeof output?.details?.template === \"string\") {\n const fingerprint = typeof output.details.fingerprint === \"string\" ? output.details.fingerprint : \"\";\n const profile: templateprofile = { origin, template: output.details.template, fingerprint, at: Date.now() };\n await memory.addtemplate(profile);\n await audit(\"observation\", `Page template ${profile.template} classified for ${origin}${fingerprint ? ` with fingerprint ${fingerprint}` : \"\"}.`, extra);\n }\n if (step.kind === \"fingerprintsection\" && typeof output?.details?.fingerprint === \"string\") {\n const profile: templateprofile = { origin, template: \"\", fingerprint: output.details.fingerprint, ...(typeof output.details.section === \"string\" ? { section: output.details.section } : {}), at: Date.now() };\n await memory.addtemplate(profile);\n await audit(\"observation\", `Section fingerprint ${profile.fingerprint} computed for ${origin}.`, extra);\n }\n if (step.kind === \"deriveselector\") {\n const candidates = detailarray(output?.details, \"candidates\") as selectorcandidate[];\n const best = candidates[0];\n if (best && typeof best.selector === \"string\" && best.selector) {\n const record: derivedselector = { stepid: step.id, selector: best.selector, strategy: best.strategy, score: best.score, at: Date.now() };\n await memory.addselector(record);\n await audit(\"observation\", `Derived selector ${record.selector} through the ${record.strategy} strategy with stability ${record.score}.`, extra);\n }\n }\n await refreshsignals(step, output);\n}\n\nasync function executestep(stepid: string): Promise<stepoutput> {\n const session = await memory.getsession();\n const plan = await memory.getplan();\n const { tab, origin } = await activecontext();\n const step = plan?.steps.find(candidate => candidate.id === stepid);\n if (!step) throw new Error(\"Reviewed step was not found.\");\n const gate = canexecute({ session, plan, step, tabid: tab.id as number, origin });\n if (!gate.allowed) throw new Error(gate.reason);\n let output: stepoutput | undefined;\n let watchwindow: { startedat: number; lifetime: number } | undefined;\n if (isbrowserkind(step.kind)) {\n const capability = requiredcapability(step.kind);\n if (capability) {\n const granted = await chrome.permissions.contains({ permissions: [capability] } as chrome.permissions.Permissions);\n if (!granted) throw new Error(`The ${capability} capability has not been granted; request it from the review panel.`);\n }\n output = await runbrowseraction(step, tab.id as number, tab.windowId ?? chrome.windows.WINDOW_ID_CURRENT);\n } else if (step.kind === \"keyhold\") {\n output = await executekeyhold(step, session, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"keyrelease\") {\n output = await executekeyrelease(step, session, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"dismissdialog\") {\n output = await executedismissdialog(step, session, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"retryaction\") {\n output = await executeretryaction(step, session, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"mapclicks\") {\n output = await executemapclicks(step, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"enterframe\") {\n output = await executeenterframe(step, plan as agentplan, tab.id as number, origin);\n } else if (watchstepkinds.has(step.kind)) {\n if (!session || !plan || plan.state !== \"approved\") throw new Error(\"Watch kinds refuse to run outside an approved session plan.\");\n const watched = await executewatchstep(step, session, plan, tab.id as number, origin);\n output = watched.output;\n watchwindow = { startedat: watched.watch.startedat, lifetime: watched.watch.lifetime };\n } else if (step.kind === \"diffsnapshots\") {\n output = await executediffsnapshots(step, session, plan as agentplan, tab.id as number, origin);\n } else {\n if (step.target && freshcheckkinds.has(step.kind)) {\n const fresh = await snapshot(tab.id as number);\n if (!fresh.interactive.some(item => item.selector === step.target)) throw new Error(\"The page changed and the target must be reviewed again.\");\n }\n output = await dispatchpagestep(step, tab.id as number, origin, plan);\n }\n await recordevidence(step, output, session, plan, origin);\n const summary = output?.summary ?? \"The page action returned no result.\";\n const resolved = output?.details?.resolvedtarget as resolvedtarget | undefined;\n if (resolved) {\n await memory.addresolution({ stepid, mode: resolved.mode, selector: resolved.selector, label: resolved.label, at: Date.now() });\n }\n const outcome: stepoutcome = { stepid, ok: Boolean(output?.ok), summary, ...(output?.details ? { details: output.details } : {}), at: Date.now() };\n const auditkind = stepauditkind(step, Boolean(output?.ok));\n await audit(auditkind, summary, { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid });\n await memory.addoutcome(outcome);\n if (output?.ok && plan) {\n const base = await memory.getprogress();\n const completed = watchwindow ? recordwatchcompletion(base, plan.id, stepid, watchwindow.startedat, watchwindow.lifetime, Date.now()) : recordstep(base, plan.id, stepid, Date.now());\n const tracked = recordoutcome(completed, plan.id, outcome, Date.now());\n await memory.setprogress(tracked);\n if (iscomplete(tracked, plan) && plan.state === \"approved\") {\n const done = { ...plan, state: \"completed\" as const, completedat: Date.now() };\n await memory.setplan(done);\n await audit(\"complete\", \"Every reviewed step of the approved plan has executed.\", { ...(session ? { sessionid: session.id } : {}), planid: done.id });\n }\n }\n return output ?? { ok: false, summary };\n}\n\n/** Highlights a reviewed target without clicking, typing, navigating or transmitting page data. */\nasync function previewstep(stepid: string): Promise<{ ok: boolean; summary: string; resolvedtarget?: resolvedtarget; candidates?: string[] }> {\n const session = await memory.getsession();\n const plan = await memory.getplan();\n const { tab, origin } = await activecontext();\n const step = plan?.steps.find(candidate => candidate.id === stepid);\n if (!step) throw new Error(\"Reviewed step was not found.\");\n const gate = canpreview({ session, plan, step, tabid: tab.id as number, origin });\n if (!gate.allowed) throw new Error(gate.reason);\n if (!step.target && !stepoptions(step).targetref) throw new Error(\"Only a target-based step can be previewed.\");\n const result = await chrome.scripting.executeScript({ target: { tabId: tab.id as number }, func: (action: toolstep, expectedorigin: string) => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { previewtarget: (step: toolstep, origin: string) => { ok: boolean; summary: string; resolvedtarget?: resolvedtarget; candidates?: string[] } } }).devthinkbridge;\n if (!bridge) throw new Error(\"Devthink page bridge is unavailable.\");\n return bridge.previewtarget(action, expectedorigin);\n }, args: [step, origin] });\n const output = result[0]?.result as { ok: boolean; summary: string; resolvedtarget?: resolvedtarget; candidates?: string[] } | undefined;\n const summary = output?.summary ?? \"The target preview returned no result.\";\n await audit(output?.ok ? \"observe\" : \"error\", summary, { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid });\n return output ?? { ok: false, summary };\n}\n\nasync function pausesession(): Promise<agentsession> {\n const session = await memory.getsession();\n if (!session || session.stoppedat) throw new Error(\"No active browser session exists.\");\n if (session.expiresat <= Date.now()) throw new Error(\"The browser session has expired.\");\n if (session.pausedat) throw new Error(\"The browser session is already paused.\");\n const paused = { ...session, pausedat: Date.now() };\n await memory.setsession(paused);\n await audit(\"pause\", \"The user paused the browser session; no action or preview can run.\", { sessionid: session.id });\n return paused;\n}\n\nasync function resumesession(): Promise<agentsession> {\n const session = await memory.getsession();\n if (!session || session.stoppedat) throw new Error(\"No active browser session exists.\");\n if (session.expiresat <= Date.now()) throw new Error(\"The browser session has expired and cannot be resumed.\");\n if (!session.pausedat) throw new Error(\"The browser session is not paused.\");\n const resumed: agentsession = { id: session.id, tabid: session.tabid, origin: session.origin, startedat: session.startedat, expiresat: session.expiresat, ...(session.grants ? { grants: session.grants } : {}) };\n await memory.setsession(resumed);\n await audit(\"resume\", \"The user resumed the browser session; reviewed actions can run again.\", { sessionid: session.id });\n return resumed;\n}\n\nasync function grantcapability(permission: string): Promise<capabilityreport> {\n if (![\"tabs\", \"downloads\", \"clipboardRead\", \"clipboardWrite\"].includes(permission)) throw new Error(\"Unknown capability.\");\n const granted = await chrome.permissions.request({ permissions: [permission] } as chrome.permissions.Permissions);\n if (!granted) throw new Error(\"The capability grant was declined.\");\n await audit(\"capability\", `Capability ${permission} granted by the user.`);\n return refreshcapabilities();\n}\n\nasync function handlerequest(message: unknown, sender: chrome.runtime.MessageSender): Promise<unknown> {\n if (!extensionpage(sender)) throw new Error(\"Requests are accepted only from Devthink extension pages.\");\n const input = message as { kind?: string; endpoint?: string; objective?: string; stepid?: string; permission?: string };\n switch (input.kind) {\n case \"configure\": {\n const config = normalizeendpoint(input.endpoint ?? \"\");\n const granted = await chrome.permissions.contains({ origins: [hostpattern(config.origin)] });\n if (!granted) throw new Error(\"The endpoint origin has not received optional permission.\");\n await memory.setconfig(config);\n await audit(\"configure\", `Configured user-selected endpoint ${config.origin}.`);\n return config;\n }\n case \"startsession\": return startsession();\n case \"context\": {\n const plan = await memory.getplan();\n const progress = await memory.getprogress();\n const session = await memory.getsession();\n const holds = heldkeys(await memory.getholds());\n const observationversion = await memory.getobservationversion();\n const map = observationversion !== undefined && observationversion > 0 ? await memory.getmap(observationversion) : undefined;\n const a11y = (await memory.geta11ytrees())[0];\n const reader = (await memory.getreaderarticles())[0];\n const signals = await memory.getsignals();\n return { config: await memory.getconfig(), session, plan, progress: plan && progress?.planid === plan.id ? progress : undefined, diagnostic: await memory.getdiagnostic(), audit: await memory.getaudit(), capabilities: await refreshcapabilities(), outcomes: await memory.getoutcomes(), holds: heldkeysreport({ tabid: session?.tabid ?? 0, holds }), dialogs: await memory.getdialogs(), retries: await memory.getretries(), ...(signals ? { signals: signalsreport({ signals }) } : { signals: signalsreport({}) }), banners: await memory.getbanners(), mutationevents: await memory.getmutationevents(), focusevents: await memory.getfocusevents(), diffs: await memory.getdiffs(), selectors: await memory.getselectors(), ...(a11y ? { a11y } : {}), ...(reader ? { reader } : {}), ...(map ? { map } : {}) };\n }\n case \"capabilities\": return refreshcapabilities();\n case \"grantcapability\": return grantcapability(input.permission ?? \"\");\n case \"diagnostic\": return diagnostic();\n case \"proposelocal\": return propose(input.objective ?? \"\", false);\n case \"proposeremote\": return propose(input.objective ?? \"\", true);\n case \"approve\": {\n const plan = await memory.getplan();\n if (!plan || plan.state !== \"pending\") throw new Error(\"Only a pending plan can be approved.\");\n const approved = { ...plan, state: \"approved\" as const, approvedat: Date.now() };\n await memory.setplan(approved);\n const policy = plandialogpolicy(approved);\n if (policy) await memory.setdialogpolicy(policy);\n const current = await memory.getsession();\n await audit(\"approval\", \"The user approved the reviewed plan.\", { ...(current ? { sessionid: current.id } : {}), planid: approved.id });\n return approved;\n }\n case \"reject\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available to reject.\");\n const rejected = { ...plan, state: \"rejected\" as const };\n await memory.setplan(rejected);\n const current = await memory.getsession();\n await audit(\"approval\", \"The user rejected the plan.\", { ...(current ? { sessionid: current.id } : {}), planid: rejected.id });\n return rejected;\n }\n case \"preview\": return previewstep(input.stepid ?? \"\");\n case \"execute\": return executestep(input.stepid ?? \"\");\n case \"outcome\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available for an outcome envelope.\");\n const outcome = (await memory.getoutcomes()).find(candidate => candidate.stepid === (input.stepid ?? \"\"));\n if (!outcome) throw new Error(\"No outcome exists for the reviewed step.\");\n const resolved = outcome.details?.resolvedtarget as resolvedtarget | undefined;\n return JSON.parse(outcomeresponse({ outcome, plan, ...(resolved ? { resolvedtarget: resolved } : {}) }));\n }\n case \"map\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available for a map envelope.\");\n const version = await memory.getobservationversion();\n const map = version !== undefined ? await memory.getmap(version) : undefined;\n if (!map) throw new Error(\"No clickable map has been captured yet.\");\n return JSON.parse(mapresponse({ map, plan }));\n }\n case \"observation\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available for an observation envelope.\");\n const version = await memory.getobservationversion();\n const record = version !== undefined ? await memory.getobservation(version) : undefined;\n if (!record) throw new Error(\"No observation has been captured yet.\");\n return JSON.parse(observationresponse({ observation: record.observation, plan }));\n }\n case \"pausesession\": return pausesession();\n case \"resumesession\": return resumesession();\n case \"stop\": {\n const session = await memory.getsession();\n if (session) await memory.setsession({ ...session, stoppedat: Date.now() });\n const plan = await memory.getplan();\n if (plan && [\"pending\", \"approved\"].includes(plan.state)) await memory.setplan({ ...plan, state: \"cancelled\" });\n await audit(\"stop\", \"The user stopped the browser session.\", { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}) });\n return { stopped: true };\n }\n default: throw new Error(\"Unknown Devthink request.\");\n }\n}\n\nchrome.runtime.onMessage.addListener((message, sender, sendresponse) => {\n handlerequest(message, sender).then(value => sendresponse({ ok: true, value })).catch(error => sendresponse({ ok: false, error: error instanceof Error ? error.message : String(error) }));\n return true;\n});\n\n/** Reconciles persisted watch registrations when the service worker restarts: registrations stay alive in storage, windows that ended while the worker was down are closed and audited, and live windows stay open. */\nasync function reconcilewatches(): Promise<void> {\n for (const watch of await memory.getwatches()) {\n if (watch.closedat !== undefined) continue;\n if (!watchclosed(watch.startedat, watch.lifetime, Date.now())) continue;\n await memory.closewatch(watch.watchid, Date.now());\n await audit(\"watch\", `Watch ${watch.watchid} of ${watch.kind} closed on service worker restart after its reviewed lifetime of ${watch.lifetime} milliseconds.`, { sessionid: watch.sessionid, stepid: watch.stepid });\n }\n}\n\nreconcilewatches().catch(() => { /* a failing storage read retries on the next service worker start; closed windows stay auditable */ });\n\nchrome.runtime.onConnect.addListener(port => {\n if (port.name !== \"devthinksidepanel\" || port.sender?.id !== chrome.runtime.id || !port.sender.url?.startsWith(chrome.runtime.getURL(\"\"))) return port.disconnect();\n port.onMessage.addListener(message => { handlerequest(message, port.sender ?? {}).then(value => port.postMessage({ ok: true, value })).catch(error => port.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) })); });\n});\n"],
5
- "mappings": ";AAYO,IAAM,gBAAN,MAAoB;AAAA,EACzB,YAA6B,SAAwB;AAAxB;AAAA,EAAyB;AAAA,EAAzB;AAAA,EAE7B,MAAM,YAAiD;AAAE,WAAO,KAAK,QAAQ,IAAoB,QAAQ;AAAA,EAAG;AAAA,EAC5G,MAAM,UAAU,OAAsC;AAAE,WAAO,KAAK,QAAQ,IAAI,UAAU,KAAK;AAAA,EAAG;AAAA,EAClG,MAAM,aAAgD;AAAE,WAAO,KAAK,QAAQ,IAAkB,SAAS;AAAA,EAAG;AAAA,EAC1G,MAAM,WAAW,OAAoC;AAAE,WAAO,KAAK,QAAQ,IAAI,WAAW,KAAK;AAAA,EAAG;AAAA,EAClG,MAAM,UAA0C;AAAE,WA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,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC,CAAC;AACzL,SAAO;AACT,CAAC;AAGD,eAAe,mBAAkC;AAC/C,aAAW,SAAS,MAAM,OAAO,WAAW,GAAG;AAC7C,QAAI,MAAM,aAAa,OAAW;AAClC,QAAI,CAAC,YAAY,MAAM,WAAW,MAAM,UAAU,KAAK,IAAI,CAAC,EAAG;AAC/D,UAAM,OAAO,WAAW,MAAM,SAAS,KAAK,IAAI,CAAC;AACjD,UAAM,MAAM,SAAS,SAAS,MAAM,OAAO,OAAO,MAAM,IAAI,oEAAoE,MAAM,QAAQ,kBAAkB,EAAE,WAAW,MAAM,WAAW,QAAQ,MAAM,OAAO,CAAC;AAAA,EACtN;AACF;AAEA,iBAAiB,EAAE,MAAM,MAAM;AAAuG,CAAC;AAEvI,OAAO,QAAQ,UAAU,YAAY,UAAQ;AAC3C,MAAI,KAAK,SAAS,uBAAuB,KAAK,QAAQ,OAAO,OAAO,QAAQ,MAAM,CAAC,KAAK,OAAO,KAAK,WAAW,OAAO,QAAQ,OAAO,EAAE,CAAC,EAAG,QAAO,KAAK,WAAW;AAClK,OAAK,UAAU,YAAY,aAAW;AAAE,kBAAc,SAAS,KAAK,UAAU,CAAC,CAAC,EAAE,KAAK,WAAS,KAAK,YAAY,EAAE,IAAI,MAAM,MAAM,CAAC,CAAC,EAAE,MAAM,WAAS,KAAK,YAAY,EAAE,IAAI,OAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC,CAAC;AAAA,EAAG,CAAC;AAC1P,CAAC;",
6
- "names": ["record", "snapshot", "record", "text", "tabid", "stepoptions", "tabid", "record"]
3
+ "sources": ["../../memory.ts", "../../policy.ts", "../../progress.ts", "../../version.ts", "../../types.ts", "../../protocol.ts", "../browsertabs.ts", "../tabscommand.ts", "../pagedialogs.ts", "../pageinteract.ts", "../pagecontrols.ts", "../pagenav.ts", "../pagenet.ts", "../background.ts"],
4
+ "sourcesContent": ["import type { a11ycapture, agentplan, agentsession, artifactrecord, auditevent, authrecord, bannerreport, capabilityreport, clickablemap, closedtab, controltabstate, curatedlist, derivedselector, diagnosticreport, dialogdecision, dialogpolicy, endpointconfig, focusevent, keyholdstate, mutationevent, navcontrol, navintentrecord, navqueues, navrecord, observationrecord, pagesignals, planprogress, ratelimitstate, readercapture, recenttab, resolutionsummary, retryoutcome, runsettings, safetyverdict, sessionsnapshot, snapshotdiff, stepoutcome, tabbadge, tabgrouprecord, tablayout, tabmeta, tabwatchevent, templateprofile, trailentry, waitprofilerecord, watchregistration } from \"./types.js\";\n\n/** Provides a small storage seam that works in browser, tests and future adapters. */\nexport interface memoryadapter {\n get<T>(key: string): Promise<T | undefined>;\n set<T>(key: string, value: T): Promise<void>;\n}\n\n/**\n * Local memory for sessions, plans, audit evidence and interaction state.\n * Correlated rules for every stored record live in this one seam; each accessor is a one line storage delegation so future backends replace the adapter only.\n */\nexport class sessionmemory {\n constructor(private readonly adapter: memoryadapter) {}\n\n async getconfig(): Promise<endpointconfig | undefined> { return this.adapter.get<endpointconfig>(\"config\"); }\n async setconfig(value: endpointconfig): Promise<void> { return this.adapter.set(\"config\", value); }\n async getsession(): Promise<agentsession | undefined> { return this.adapter.get<agentsession>(\"session\"); }\n async setsession(value: agentsession): Promise<void> { return this.adapter.set(\"session\", value); }\n async getplan(): Promise<agentplan | undefined> { return this.adapter.get<agentplan>(\"plan\"); }\n async setplan(value: agentplan): Promise<void> { return this.adapter.set(\"plan\", value); }\n async getdiagnostic(): Promise<diagnosticreport | undefined> { return this.adapter.get<diagnosticreport>(\"diagnostic\"); }\n async setdiagnostic(value: diagnosticreport): Promise<void> { return this.adapter.set(\"diagnostic\", value); }\n async getprogress(): Promise<planprogress | undefined> { return this.adapter.get<planprogress>(\"progress\"); }\n async setprogress(value: planprogress): Promise<void> { return this.adapter.set(\"progress\", value); }\n async getcapabilities(): Promise<capabilityreport | undefined> { return this.adapter.get<capabilityreport>(\"capabilities\"); }\n async setcapabilities(value: capabilityreport): Promise<void> { return this.adapter.set(\"capabilities\", value); }\n async getsettings(): Promise<runsettings | undefined> { return this.adapter.get<runsettings>(\"settings\"); }\n async setsettings(value: runsettings): Promise<void> { return this.adapter.set(\"settings\", value); }\n async getaudit(): Promise<auditevent[]> { return (await this.adapter.get<auditevent[]>(\"audit\")) ?? []; }\n async getoutcomes(): Promise<stepoutcome[]> { return (await this.adapter.get<stepoutcome[]>(\"outcomes\")) ?? []; }\n\n /** Records one audit event; retention is a user setting and an absent setting keeps every event. */\n async addaudi(event: auditevent): Promise<void> {\n const records = await this.getaudit();\n const combined = [event, ...records];\n const retention = (await this.getsettings())?.auditretention;\n await this.adapter.set(\"audit\", retention === undefined ? combined : combined.slice(0, retention));\n }\n\n /** Records one step outcome; retention is a user setting and an absent setting keeps every outcome. */\n async addoutcome(outcome: stepoutcome): Promise<void> {\n const records = await this.getoutcomes();\n const combined = [outcome, ...records];\n const retention = (await this.getsettings())?.outcomeretention;\n await this.adapter.set(\"outcomes\", retention === undefined ? combined : combined.slice(0, retention));\n }\n\n /** Stores one clickable map under its observation version so every captured map stays available. */\n async setmap(map: clickablemap): Promise<void> { return this.adapter.set(`map${map.version}`, map); }\n\n /** Returns one stored clickable map by its observation version. */\n async getmap(version: number): Promise<clickablemap | undefined> { return this.adapter.get<clickablemap>(`map${version}`); }\n\n /** Advances and persists the observation version counter used to stamp clickable maps. */\n async nextobservationversion(): Promise<number> {\n const current = (await this.adapter.get<number>(\"observationversion\")) ?? 0;\n const next = current + 1;\n await this.adapter.set(\"observationversion\", next);\n return next;\n }\n\n /** Returns the latest observation version used to stamp a clickable map. */\n async getobservationversion(): Promise<number | undefined> { return this.adapter.get<number>(\"observationversion\"); }\n\n /** Returns the key hold registry, persisted so holds survive service worker restarts. */\n async getholds(): Promise<keyholdstate[]> { return (await this.adapter.get<keyholdstate[]>(\"holds\")) ?? []; }\n\n /** Replaces the key hold registry after one press or release transition. */\n async setholds(holds: keyholdstate[]): Promise<void> { return this.adapter.set(\"holds\", holds); }\n\n /** Returns every dialog decision recorded for the audit trail. */\n async getdialogs(): Promise<dialogdecision[]> { return (await this.adapter.get<dialogdecision[]>(\"dialogs\")) ?? []; }\n\n /** Records one dialog decision with the reviewed answer and the observed dialog text. */\n async adddialog(decision: dialogdecision): Promise<void> {\n const records = await this.getdialogs();\n await this.adapter.set(\"dialogs\", [decision, ...records]);\n }\n\n /** Returns every retry outcome recorded with attempts and movement deltas. */\n async getretries(): Promise<retryoutcome[]> { return (await this.adapter.get<retryoutcome[]>(\"retries\")) ?? []; }\n\n /** Records one retry outcome with the attempts made and the movement delta observed. */\n async addretry(outcome: retryoutcome): Promise<void> {\n const records = await this.getretries();\n await this.adapter.set(\"retries\", [outcome, ...records]);\n }\n\n /** Returns every resolution summary stored per target mode. */\n async getresolutions(): Promise<resolutionsummary[]> { return (await this.adapter.get<resolutionsummary[]>(\"resolutions\")) ?? []; }\n\n /** Records one resolution summary for later selector derivation. */\n async addresolution(summary: resolutionsummary): Promise<void> {\n const records = await this.getresolutions();\n await this.adapter.set(\"resolutions\", [summary, ...records]);\n }\n\n /** Returns the reviewed default dialog policy kept for the session auto handler. */\n async getdialogpolicy(): Promise<dialogpolicy | undefined> { return this.adapter.get<dialogpolicy>(\"dialogpolicy\"); }\n\n /** Stores the reviewed default dialog policy of the latest approved plan. */\n async setdialogpolicy(policy: dialogpolicy): Promise<void> { return this.adapter.set(\"dialogpolicy\", policy); }\n\n /** Stores one observation capture under its version so every observation version stays available. */\n async setobservation(record: observationrecord): Promise<void> { return this.adapter.set(`observation${record.version}`, record); }\n\n /** Returns one stored observation version. */\n async getobservation(version: number): Promise<observationrecord | undefined> { return this.adapter.get<observationrecord>(`observation${version}`); }\n\n /** Returns the observation retention window; an absent setting keeps every capture. */\n private async observationretention(): Promise<number | undefined> { return (await this.getsettings())?.observationretention; }\n\n /** Stores one accessibility tree capture; retention is a user setting and an absent setting keeps every tree. */\n async adda11ytree(capture: a11ycapture): Promise<void> {\n const records = await this.geta11ytrees();\n const combined = [capture, ...records];\n const retention = await this.observationretention();\n await this.adapter.set(\"a11ytrees\", retention === undefined ? combined : combined.slice(0, retention));\n }\n\n /** Returns every stored accessibility tree capture, newest first. */\n async geta11ytrees(): Promise<a11ycapture[]> { return (await this.adapter.get<a11ycapture[]>(\"a11ytrees\")) ?? []; }\n\n /** Stores one reader article capture; retention is a user setting and an absent setting keeps every article. */\n async addreaderarticle(capture: readercapture): Promise<void> {\n const records = await this.getreaderarticles();\n const combined = [capture, ...records];\n const retention = await this.observationretention();\n await this.adapter.set(\"readerarticles\", retention === undefined ? combined : combined.slice(0, retention));\n }\n\n /** Returns every stored reader article capture, newest first. */\n async getreaderarticles(): Promise<readercapture[]> { return (await this.adapter.get<readercapture[]>(\"readerarticles\")) ?? []; }\n\n /** Records one dom mutation observed inside a reviewed watch. */\n async addmutationevent(event: mutationevent): Promise<void> {\n const records = await this.getmutationevents();\n await this.adapter.set(\"mutationevents\", [event, ...records]);\n }\n\n /** Returns the mutation event stream of every reviewed watch. */\n async getmutationevents(): Promise<mutationevent[]> { return (await this.adapter.get<mutationevent[]>(\"mutationevents\")) ?? []; }\n\n /** Records one focus change observed inside a reviewed watch. */\n async addfocusevent(event: focusevent): Promise<void> {\n const records = await this.getfocusevents();\n await this.adapter.set(\"focusevents\", [event, ...records]);\n }\n\n /** Returns the focus event stream of every reviewed watch. */\n async getfocusevents(): Promise<focusevent[]> { return (await this.adapter.get<focusevent[]>(\"focusevents\")) ?? []; }\n\n /** Records one consent banner observed by a reviewed banner watch. */\n async addbanner(event: bannerreport): Promise<void> {\n const records = await this.getbanners();\n await this.adapter.set(\"banners\", [event, ...records]);\n }\n\n /** Returns every consent banner report observed so far. */\n async getbanners(): Promise<bannerreport[]> { return (await this.adapter.get<bannerreport[]>(\"banners\")) ?? []; }\n\n /** Records one snapshot diff between two observation versions. */\n async adddiff(diff: snapshotdiff): Promise<void> {\n const records = await this.getdiffs();\n await this.adapter.set(\"diffs\", [diff, ...records]);\n }\n\n /** Returns every stored snapshot diff, newest first. */\n async getdiffs(): Promise<snapshotdiff[]> { return (await this.adapter.get<snapshotdiff[]>(\"diffs\")) ?? []; }\n\n /** Records one derived selector with its stability score for reuse. */\n async addselector(selector: derivedselector): Promise<void> {\n const records = await this.getselectors();\n await this.adapter.set(\"selectors\", [selector, ...records]);\n }\n\n /** Returns every stored derived selector with its stability score, newest first. */\n async getselectors(): Promise<derivedselector[]> { return (await this.adapter.get<derivedselector[]>(\"selectors\")) ?? []; }\n\n /** Records one detected template class or section fingerprint for its origin. */\n async addtemplate(profile: templateprofile): Promise<void> {\n const records = await this.gettemplates();\n await this.adapter.set(\"templates\", [profile, ...records]);\n }\n\n /** Returns every stored template class and section fingerprint, newest first. */\n async gettemplates(): Promise<templateprofile[]> { return (await this.adapter.get<templateprofile[]>(\"templates\")) ?? []; }\n\n /** Records one watch registration so it survives service worker restarts. */\n async addwatch(watch: watchregistration): Promise<void> {\n const records = await this.getwatches();\n await this.adapter.set(\"watches\", [watch, ...records]);\n }\n\n /** Returns every watch registration, newest first, including closed windows. */\n async getwatches(): Promise<watchregistration[]> { return (await this.adapter.get<watchregistration[]>(\"watches\")) ?? []; }\n\n /** Closes one watch registration by watch id once its reviewed lifetime window ends. */\n async closewatch(watchid: string, closedat: number): Promise<void> {\n const records = await this.getwatches();\n await this.adapter.set(\"watches\", records.map(watch => watch.watchid === watchid && watch.closedat === undefined ? { ...watch, closedat } : watch));\n }\n\n /** Returns the live page signals of language, template, scroll lock and banner state. */\n async getsignals(): Promise<pagesignals | undefined> { return this.adapter.get<pagesignals>(\"signals\"); }\n\n /** Replaces the live page signals after an observation step refreshes them. */\n async setsignals(signals: pagesignals): Promise<void> { return this.adapter.set(\"signals\", signals); }\n\n /** Appends one navigation trail entry of a session with its url, title, step ref and timestamp. */\n async addtrailentry(sessionid: string, entry: trailentry): Promise<void> {\n const records = await this.gettrail(sessionid);\n await this.adapter.set(`trail${sessionid}`, [...records, entry]);\n }\n\n /** Returns the navigation trail of a session, oldest first. */\n async gettrail(sessionid: string): Promise<trailentry[]> { return (await this.adapter.get<trailentry[]>(`trail${sessionid}`)) ?? []; }\n\n /** Stores one wait profile for an origin with user configured values, replacing the previous profile of that origin. */\n async setwaitprofile(record: waitprofilerecord): Promise<void> {\n const records = (await this.getwaitprofiles()).filter(item => item.origin !== record.origin);\n await this.adapter.set(\"waitprofiles\", [...records, record]);\n }\n\n /** Returns every stored wait profile with its origin and user configured values, newest first. */\n async getwaitprofiles(): Promise<waitprofilerecord[]> { return (await this.adapter.get<waitprofilerecord[]>(\"waitprofiles\")) ?? []; }\n\n /** Records one navigation step with its redirect chain and final url. */\n async addnavrecord(record: navrecord): Promise<void> {\n const records = await this.getnavrecords();\n await this.adapter.set(\"navrecords\", [record, ...records]);\n }\n\n /** Returns every stored navigation record with redirect chains and final urls, newest first. */\n async getnavrecords(): Promise<navrecord[]> { return (await this.adapter.get<navrecord[]>(\"navrecords\")) ?? []; }\n\n /** Records one navigation intent detected from a plan for audit review. */\n async addnavintent(record: navintentrecord): Promise<void> {\n const records = await this.getnavintents();\n await this.adapter.set(\"navintents\", [record, ...records]);\n }\n\n /** Returns every stored navigation intent record, newest first. */\n async getnavintents(): Promise<navintentrecord[]> { return (await this.adapter.get<navintentrecord[]>(\"navintents\")) ?? []; }\n\n /** Replaces the rate limit window state of one domain. */\n async setratestate(state: ratelimitstate): Promise<void> {\n const records = (await this.getratestates()).filter(item => item.domain !== state.domain);\n await this.adapter.set(\"ratestates\", [...records, state]);\n }\n\n /** Returns every rate limit window state per domain. */\n async getratestates(): Promise<ratelimitstate[]> { return (await this.adapter.get<ratelimitstate[]>(\"ratestates\")) ?? []; }\n\n /** Records one curated link list with its review state before batch opening. */\n async addcurated(list: curatedlist): Promise<void> {\n const records = await this.getcurateds();\n await this.adapter.set(\"curated\", [list, ...records]);\n }\n\n /** Returns every stored curated link list, newest first. */\n async getcurateds(): Promise<curatedlist[]> { return (await this.adapter.get<curatedlist[]>(\"curated\")) ?? []; }\n\n /** Stores reviewed basic auth credentials for one origin, replacing the previous record of that origin. */\n async setauth(record: authrecord): Promise<void> {\n const records = (await this.getauths()).filter(item => item.origin !== record.origin);\n await this.adapter.set(\"auths\", [...records, record]);\n }\n\n /** Returns every stored reviewed basic auth record per origin. */\n async getauths(): Promise<authrecord[]> { return (await this.adapter.get<authrecord[]>(\"auths\")) ?? []; }\n\n /** Records one task artifact routed into the artifact store. */\n async addartifact(record: artifactrecord): Promise<void> {\n const records = await this.getartifacts();\n await this.adapter.set(\"artifacts\", [record, ...records]);\n }\n\n /** Returns every stored task artifact, newest first. */\n async getartifacts(): Promise<artifactrecord[]> { return (await this.adapter.get<artifactrecord[]>(\"artifacts\")) ?? []; }\n\n /** Returns the navigation control state of paused navigation. */\n async getnavcontrol(): Promise<navcontrol | undefined> { return this.adapter.get<navcontrol>(\"navcontrol\"); }\n\n /** Replaces the navigation control state after a pause or resume transition. */\n async setnavcontrol(control: navcontrol): Promise<void> { return this.adapter.set(\"navcontrol\", control); }\n\n /** Records one url safety verdict produced by a checksafe verification. */\n async addsafety(verdict: safetyverdict): Promise<void> {\n const records = await this.getsafeties();\n await this.adapter.set(\"safeties\", [verdict, ...records]);\n }\n\n /** Returns every stored url safety verdict, newest first. */\n async getsafeties(): Promise<safetyverdict[]> { return (await this.adapter.get<safetyverdict[]>(\"safeties\")) ?? []; }\n\n /** Records one recently closed tab so a reopentab step can restore it. */\n async addrecenttab(tab: recenttab): Promise<void> {\n const records = await this.getrecenttabs();\n await this.adapter.set(\"recenttabs\", [tab, ...records]);\n }\n\n /** Returns every recently closed tab, newest first. */\n async getrecenttabs(): Promise<recenttab[]> { return (await this.adapter.get<recenttab[]>(\"recenttabs\")) ?? []; }\n\n /** Returns the queued prefetch and batch open target counts shown in the popup badge. */\n async getnavqueues(): Promise<navqueues | undefined> { return this.adapter.get<navqueues>(\"navqueues\"); }\n\n /** Replaces the queued prefetch and batch open target counts. */\n async setnavqueues(queues: navqueues): Promise<void> { return this.adapter.set(\"navqueues\", queues); }\n\n /** Returns the last known navigation state of a tab, kept across service worker restarts. */\n async getnavstate(tabid: number): Promise<navrecord | undefined> { return this.adapter.get<navrecord>(`navstate${tabid}`); }\n\n /** Replaces the last known navigation state of a tab. */\n async setnavstate(tabid: number, state: navrecord): Promise<void> { return this.adapter.set(`navstate${tabid}`, state); }\n\n /** Stores one named tab layout with its window bounds and group states, replacing the previous layout of that name. */\n async setlayout(layout: tablayout): Promise<void> {\n const records = (await this.getlayouts()).filter(item => item.name !== layout.name);\n await this.adapter.set(\"layouts\", [layout, ...records]);\n }\n\n /** Returns one saved tab layout by name with its timestamp. */\n async getlayout(name: string): Promise<tablayout | undefined> { return (await this.getlayouts()).find(item => item.name === name); }\n\n /** Returns every saved tab layout with its window bounds and group states. */\n async getlayouts(): Promise<tablayout[]> { return (await this.adapter.get<tablayout[]>(\"layouts\")) ?? []; }\n\n /** Stores one tab group definition with its color choice and member tabs, replacing the previous definition of that name. */\n async settabgroup(group: tabgrouprecord): Promise<void> {\n const records = (await this.gettabgroups()).filter(item => item.name !== group.name);\n await this.adapter.set(\"tabgroups\", [...records, group]);\n }\n\n /** Returns every stored tab group definition with its color choice, newest first. */\n async gettabgroups(): Promise<tabgrouprecord[]> { return (await this.adapter.get<tabgrouprecord[]>(\"tabgroups\")) ?? []; }\n\n /** Records one tabmeta record with task provenance, replacing the previous metadata of that tab. */\n async settabmeta(meta: tabmeta): Promise<void> {\n const records = (await this.gettabmetas()).filter(item => item.tabid !== meta.tabid);\n await this.adapter.set(\"tabmetas\", [...records, meta]);\n }\n\n /** Returns every stored tabmeta record with task provenance. */\n async gettabmetas(): Promise<tabmeta[]> { return (await this.adapter.get<tabmeta[]>(\"tabmetas\")) ?? []; }\n\n /** Records one session snapshot of tabs and windows for later restore. */\n async addsnapshot(snapshot: sessionsnapshot): Promise<void> {\n const records = await this.getsnapshots();\n await this.adapter.set(\"snapshots\", [snapshot, ...records]);\n }\n\n /** Returns every stored session snapshot, newest first. */\n async getsnapshots(): Promise<sessionsnapshot[]> { return (await this.adapter.get<sessionsnapshot[]>(\"snapshots\")) ?? []; }\n\n /** Records one closed tab in the history kept for restoretab and reopenrun. */\n async addclosedtab(tab: closedtab): Promise<void> {\n const records = await this.getclosedtabs();\n await this.adapter.set(\"closedtabs\", [tab, ...records]);\n }\n\n /** Returns the closed tab history, newest first. */\n async getclosedtabs(): Promise<closedtab[]> { return (await this.adapter.get<closedtab[]>(\"closedtabs\")) ?? []; }\n\n /** Stores one badge state per task, replacing the previous badge of that task. */\n async setbadge(badge: tabbadge): Promise<void> {\n const records = (await this.getbadges()).filter(item => item.taskid !== badge.taskid);\n await this.adapter.set(\"badges\", [...records, badge]);\n }\n\n /** Returns every stored badge state per task. */\n async getbadges(): Promise<tabbadge[]> { return (await this.adapter.get<tabbadge[]>(\"badges\")) ?? []; }\n\n /** Records one tab event observed inside a reviewed watchtab registration. */\n async addtabwatchevent(event: tabwatchevent): Promise<void> {\n const records = await this.gettabwatchevents();\n await this.adapter.set(\"tabwatchevents\", [event, ...records]);\n }\n\n /** Returns the tab event stream of every reviewed watchtab registration, newest first. */\n async gettabwatchevents(): Promise<tabwatchevent[]> { return (await this.adapter.get<tabwatchevent[]>(\"tabwatchevents\")) ?? []; }\n\n /** Returns the ids of the scratch windows opened for split work. */\n async getscratchwindows(): Promise<number[]> { return (await this.adapter.get<number[]>(\"scratchwindows\")) ?? []; }\n\n /** Replaces the scratch window id list after one scratch window opens or closes. */\n async setscratchwindows(ids: number[]): Promise<void> { return this.adapter.set(\"scratchwindows\", ids); }\n\n /** Returns the pinned control tab state with the live task feed. */\n async getcontroltab(): Promise<controltabstate | undefined> { return this.adapter.get<controltabstate>(\"controltab\"); }\n\n /** Replaces the pinned control tab state. */\n async setcontroltab(state: controltabstate): Promise<void> { return this.adapter.set(\"controltab\", state); }\n}\n\n/** Creates identifiers locally without a network dependency. */\nexport function randomid(): string {\n return crypto.randomUUID();\n}\n", "import type { actionkind, agentplan, agentsession, endpointconfig, observationmode, policyevaluation, runsettings, safetyverdict, toolstep } from \"./types.js\";\n\nconst sensitiveactions = new Set<actionkind>([\"click\", \"type\", \"navigate\", \"select\", \"presskey\", \"drag\", \"drop\", \"upload\", \"clear\", \"check\", \"uncheck\", \"toggle\", \"submit\", \"reload\", \"back\", \"forward\", \"writestorage\", \"setattribute\", \"removeattribute\", \"evaluate\", \"tabcreate\", \"tabactivate\", \"tabclose\", \"tabreload\", \"windowcreate\", \"windowclose\", \"windowresize\", \"downloadfile\", \"clickpoint\", \"shiftclick\", \"dismissdialog\", \"enterframe\", \"typetime\", \"appendtext\", \"setvalue\", \"typeedit\", \"keyhold\", \"keyrelease\", \"submitsearch\", \"selectmulti\", \"chooseradio\", \"setslider\", \"setdate\", \"setcolor\", \"openlink\", \"openprivate\", \"reloadcache\", \"stopnav\", \"followlink\", \"spanav\", \"rewritequery\", \"setfragment\", \"navlist\", \"navprofile\", \"handleauth\", \"printpdf\", \"prefetch\", \"preconnect\", \"deeplink\", \"reopentab\", \"pausenav\", \"navrate\", \"openclipboard\", \"batchopen\", \"duplicatetab\", \"closepattern\", \"pintab\", \"mutetab\", \"movetab\", \"movetabwindow\", \"grouptabs\", \"colorgroup\", \"collapsegroup\", \"discardtab\", \"reloadtabs\", \"zoomin\", \"zoomout\", \"switchtab\", \"maximizewindow\", \"minimizewindow\", \"restorewindow\", \"focuswindow\", \"scratchwindow\", \"incognitowindow\", \"restoretab\", \"restorelayout\", \"reopenrun\", \"badgetab\"]);\nconst interactionactions = new Set<actionkind>([\"focus\", \"scroll\", \"hover\", \"clickdeep\", \"rightclick\", \"doubleclick\", \"scrollpage\", \"scrollby\", \"scrollend\", \"scrolltop\", \"fullscreen\", \"zoomset\", \"movepointer\", \"clicktext\", \"clickaria\", \"clickname\", \"expanddetails\", \"pierceshadow\", \"retryaction\"]);\nconst readactions = new Set<actionkind>([\"observe\", \"inspect\", \"extract\", \"wait\", \"waitfor\", \"waittext\", \"readattribute\", \"readstyle\", \"readgeometry\", \"readvalue\", \"readtext\", \"readhtml\", \"countelements\", \"readtable\", \"readlinks\", \"readimages\", \"readmeta\", \"readforms\", \"readstorage\", \"highlight\", \"tablist\", \"windowlist\", \"tabsnapshot\", \"mapclicks\", \"verifyvisible\", \"verifyenabled\", \"resolvexpath\", \"a11ytree\", \"readvisible\", \"readertree\", \"detectlists\", \"detecttables\", \"readjson\", \"watchmutate\", \"waitquiet\", \"watchbanner\", \"detectinfinitescroll\", \"detectvirtual\", \"detectlazy\", \"readscrollpos\", \"readlang\", \"readoutline\", \"countpages\", \"listshadow\", \"listframes\", \"classifypage\", \"fingerprintsection\", \"diffsnapshots\", \"readselection\", \"watchfocus\", \"detectsticky\", \"detectscrolllock\", \"readopengraph\", \"detectlanguage\", \"deriveselector\", \"waitload\", \"waiturl\", \"spawait\", \"detecthttp\", \"readredirects\", \"readfinalurl\", \"trailaudit\", \"navintent\", \"checksafe\", \"querytabs\", \"watchtab\", \"findclones\", \"searchtabs\", \"listaudio\", \"snapshotsession\", \"savelayout\", \"attachmeta\"]);\nconst allowedactions = new Set<actionkind>([...sensitiveactions, ...interactionactions, ...readactions]);\nconst watchactions = new Set<actionkind>([\"watchmutate\", \"watchbanner\", \"watchfocus\", \"watchtab\"]);\nconst targetactions = new Set<actionkind>([\"inspect\", \"focus\", \"click\", \"type\", \"scroll\", \"select\", \"hover\", \"clickdeep\", \"rightclick\", \"doubleclick\", \"drag\", \"drop\", \"upload\", \"clear\", \"check\", \"uncheck\", \"toggle\", \"submit\", \"readattribute\", \"readstyle\", \"readgeometry\", \"readvalue\", \"readtext\", \"readhtml\", \"countelements\", \"readtable\", \"highlight\", \"setattribute\", \"removeattribute\", \"waitfor\", \"shiftclick\", \"typetime\", \"appendtext\", \"setvalue\", \"typeedit\", \"submitsearch\", \"selectmulti\", \"chooseradio\", \"setslider\", \"setdate\", \"setcolor\", \"expanddetails\", \"verifyvisible\", \"verifyenabled\", \"pierceshadow\", \"deriveselector\", \"fingerprintsection\"]);\nconst valueactions = new Set<actionkind>([\"presskey\", \"drag\", \"drop\", \"upload\", \"readattribute\", \"removeattribute\", \"waittext\", \"evaluate\", \"zoomset\", \"tabactivate\", \"tabclose\", \"tabreload\", \"windowclose\", \"windowresize\", \"tabcreate\", \"windowcreate\", \"downloadfile\", \"typetime\", \"appendtext\", \"setvalue\", \"typeedit\", \"keyhold\", \"keyrelease\", \"chooseradio\", \"setslider\", \"setdate\", \"setcolor\", \"followlink\", \"setfragment\", \"handleauth\", \"navintent\", \"openclipboard\", \"checksafe\", \"reopentab\", \"spanav\", \"duplicatetab\", \"pintab\", \"mutetab\", \"movetab\", \"movetabwindow\", \"searchtabs\", \"badgetab\", \"attachmeta\", \"focuswindow\", \"maximizewindow\", \"minimizewindow\", \"restorewindow\", \"incognitowindow\"]);\nconst tabscommandactions = new Set<actionkind>([\"querytabs\", \"duplicatetab\", \"closepattern\", \"pintab\", \"mutetab\", \"movetab\", \"movetabwindow\", \"grouptabs\", \"colorgroup\", \"collapsegroup\", \"discardtab\", \"reloadtabs\", \"zoomin\", \"zoomout\", \"watchtab\", \"switchtab\", \"maximizewindow\", \"minimizewindow\", \"restorewindow\", \"focuswindow\", \"scratchwindow\", \"incognitowindow\", \"restoretab\", \"savelayout\", \"restorelayout\", \"findclones\", \"searchtabs\", \"badgetab\", \"attachmeta\", \"listaudio\", \"reopenrun\", \"snapshotsession\"]);\nconst layoutmutationactions = new Set<actionkind>([\"grouptabs\", \"colorgroup\", \"collapsegroup\", \"savelayout\", \"restorelayout\"]);\n/** Chromium tab group colors accepted as reviewed group color choices. */\nconst groupcolors = [\"grey\", \"blue\", \"red\", \"yellow\", \"green\", \"pink\", \"purple\", \"cyan\", \"orange\"];\n\n/** Normalizes a user supplied HTTPS endpoint without preserving a provider lock-in. */\nexport function normalizeendpoint(value: string): endpointconfig {\n const endpoint = new URL(value.trim());\n if (endpoint.protocol !== \"https:\") throw new Error(\"Devthink accepts HTTPS endpoints only.\");\n if (endpoint.username || endpoint.password) throw new Error(\"Endpoint credentials are not allowed in the URL.\");\n return { endpoint: endpoint.toString(), origin: endpoint.origin, configuredat: Date.now() };\n}\n\n/** Creates the exact optional host pattern requested from Chromium. */\nexport function hostpattern(origin: string): string {\n const parsed = new URL(origin);\n if (parsed.protocol !== \"https:\") throw new Error(\"Only HTTPS origins can be granted.\");\n return `${parsed.origin}/*`;\n}\n\n/** True when the action kind observes the page over a reviewed lifetime window. */\nexport function iswatchkind(kind: actionkind): boolean {\n return watchactions.has(kind);\n}\n\n/** Grades the observation mode of a kind: passive capture, watched lifetimes or diffing passes. */\nexport function observationmodeof(kind: actionkind): observationmode {\n if (watchactions.has(kind) || kind === \"waitquiet\") return \"watching\";\n if (kind === \"diffsnapshots\") return \"diffing\";\n return \"passive\";\n}\n\n/** Defines action risk from the fixed local allowlist. */\nexport function actionrisk(kind: actionkind): \"read\" | \"interaction\" | \"sensitive\" {\n if (!allowedactions.has(kind)) throw new Error(\"Unsupported browser action.\");\n if (sensitiveactions.has(kind)) return \"sensitive\";\n return interactionactions.has(kind) ? \"interaction\" : \"read\";\n}\n\n/** True when the action kind accepts a css selector target or a reviewed targetref. */\nexport function needstarget(kind: actionkind): boolean {\n return targetactions.has(kind);\n}\n\n/** Parses the reviewed JSON options of a step; malformed payloads are rejected early. */\nexport function parseoptions(step: toolstep): Record<string, unknown> {\n if (step.options === undefined) return {};\n let parsed: unknown;\n try { parsed = JSON.parse(step.options); } catch { throw new Error(\"Step options must be a JSON object.\"); }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new Error(\"Step options must be a JSON object.\");\n return parsed as Record<string, unknown>;\n}\n\n/** Maps an action kind to the optional browser permission it requires, if any. */\nexport function requiredcapability(kind: actionkind): string | undefined {\n if (kind === \"tablist\") return \"tabs\";\n if (kind === \"downloadfile\") return \"downloads\";\n if (kind === \"openclipboard\") return \"clipboardRead\";\n if (kind === \"openlink\" || kind === \"openprivate\" || kind === \"navlist\" || kind === \"batchopen\" || kind === \"reopentab\" || kind === \"deeplink\") return \"tabs\";\n if (tabscommandactions.has(kind)) return \"tabs\";\n return undefined;\n}\n\n/** True when the kind commands tabs or windows beyond the active tab and needs the optional tabs capability. */\nexport function istabscommandkind(kind: actionkind): boolean {\n return tabscommandactions.has(kind);\n}\n\n/** True when the kind mutates tab groups or layouts and therefore stays inside the active session. */\nexport function islayoutkind(kind: actionkind): boolean {\n return layoutmutationactions.has(kind);\n}\n\n/** Restricts group and layout mutations to the active session: they refuse without a live session. */\nexport function layoutmutationgranted(session: agentsession | undefined, now: number): policyevaluation {\n if (!session || session.stoppedat || session.expiresat <= now) return { allowed: false, reason: \"Group and layout mutations stay inside the active session.\" };\n return { allowed: true };\n}\n\n/** Requires explicit review before closing a window that holds more than one task tab. */\nexport function windowclosegate(tasktabcount: number, reviewed: boolean): policyevaluation {\n if (tasktabcount > 1 && !reviewed) return { allowed: false, reason: `The window holds ${tasktabcount} task tabs and needs explicit review before it closes.` };\n return { allowed: true };\n}\n\n/** Reads the user configured concurrent task tab ceiling; an absent value never refuses a tab. */\nexport function tasktabceiling(settings: runsettings | undefined): number | undefined {\n const ceiling = settings?.tasktabceiling;\n return typeof ceiling === \"number\" && Number.isFinite(ceiling) && ceiling >= 0 ? ceiling : undefined;\n}\n\n/** Parses the reviewed wait duration of a wait step with no upper bound. */\nexport function waitduration(step: toolstep): number {\n const requested = step.value ? Number.parseInt(step.value, 10) : 250;\n if (!Number.isFinite(requested) || requested < 0) throw new Error(\"Wait duration must be zero or a positive number of milliseconds.\");\n return requested;\n}\n\nfunction isnumericid(value: unknown): value is string {\n return typeof value === \"string\" && /^\\d+$/.test(value);\n}\n\nfunction numericoption(options: Record<string, unknown>, key: string): boolean {\n return options[key] === undefined || (typeof options[key] === \"number\" && Number.isFinite(options[key] as number));\n}\n\n/** True when an optional numeric option is absent or a finite number of zero or more. */\nfunction nonnegativeoption(options: Record<string, unknown>, key: string): boolean {\n return numericoption(options, key) && !(typeof options[key] === \"number\" && (options[key] as number) < 0);\n}\n\nfunction isnonempty(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction ispoint(value: unknown): boolean {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const point = value as Record<string, unknown>;\n return typeof point.x === \"number\" && Number.isFinite(point.x) && typeof point.y === \"number\" && Number.isFinite(point.y);\n}\n\n/** Grades a resolution match count: zero is absent, one is resolved and more than one is refused as ambiguous. */\nexport function resolutionverdict(count: number): \"absent\" | \"resolved\" | \"ambiguous\" {\n if (!Number.isFinite(count) || count <= 0) return \"absent\";\n return count === 1 ? \"resolved\" : \"ambiguous\";\n}\n\n/** Validates the reviewed targetref grammar of every resolution mode and rejects empty references. */\nexport function validatetargetref(reference: unknown): policyevaluation {\n if (!reference || typeof reference !== \"object\" || Array.isArray(reference)) return { allowed: false, reason: \"The reviewed target reference must be an object.\" };\n const ref = reference as Record<string, unknown>;\n if (ref.mode === \"selector\") return isnonempty(ref.selector) ? { allowed: true } : { allowed: false, reason: \"The selector target reference needs a non-empty selector.\" };\n if (ref.mode === \"text\") return isnonempty(ref.text) ? { allowed: true } : { allowed: false, reason: \"The text target reference needs non-empty text.\" };\n if (ref.mode === \"aria\") {\n if (!isnonempty(ref.role)) return { allowed: false, reason: \"The aria target reference needs a non-empty role.\" };\n return isnonempty(ref.name) ? { allowed: true } : { allowed: false, reason: \"The aria target reference needs a non-empty name.\" };\n }\n if (ref.mode === \"name\") return isnonempty(ref.name) ? { allowed: true } : { allowed: false, reason: \"The name target reference needs a non-empty name.\" };\n if (ref.mode === \"xpath\") return isnonempty(ref.xpath) ? { allowed: true } : { allowed: false, reason: \"The xpath target reference needs a non-empty expression.\" };\n if (ref.mode === \"index\") {\n const index = ref.index;\n return typeof index === \"number\" && Number.isInteger(index) && index >= 1 ? { allowed: true } : { allowed: false, reason: \"The index target reference needs a positive integer map number.\" };\n }\n if (ref.mode === \"point\") {\n const pointok = typeof ref.x === \"number\" && Number.isFinite(ref.x) && typeof ref.y === \"number\" && Number.isFinite(ref.y);\n return pointok ? { allowed: true } : { allowed: false, reason: \"The point target reference needs numeric x and y coordinates.\" };\n }\n return { allowed: false, reason: \"The target reference mode must be selector, text, aria, name, xpath, index or point.\" };\n}\n\n/** True when the session origin grants cover the given origin; a session without grants only allows its own origin. */\nexport function origingranted(session: agentsession | undefined, origin: string): boolean {\n if (!session) return false;\n const grants = session.grants ?? [session.origin];\n return grants.includes(origin);\n}\n\n/** Decides whether an unreviewed origin may open: the session grants cover it or a safe checksafe verdict vouches for it. */\nexport function originverified(url: string, grants: string[], verdicts: safetyverdict[]): policyevaluation {\n let origin = \"\";\n try { origin = new URL(url).origin; } catch { return { allowed: false, reason: \"The reviewed navigation URL is invalid.\" }; }\n if (grants.includes(origin)) return { allowed: true };\n const covered = verdicts.find(verdict => verdict.safe && (verdict.url === url || (safeorigin(verdict.url) === origin)));\n if (covered) return { allowed: true };\n return { allowed: false, reason: `The origin ${origin} is outside the session grants and has no safe checksafe verdict; run checksafe and review it first.` };\n}\n\nfunction safeorigin(url: string): string {\n try { return new URL(url).origin; } catch { return \"\"; }\n}\n\n/** Refuses navigation that would move a granted task tab outside the session origin grants until the user consents. */\nexport function navigationgranted(session: agentsession | undefined, url: string): policyevaluation {\n let origin = \"\";\n try { origin = new URL(url).origin; } catch { return { allowed: false, reason: \"The reviewed navigation URL is invalid.\" }; }\n if (origingranted(session, origin)) return { allowed: true };\n return { allowed: false, reason: `Navigation to ${origin} leaves the task tab origins and needs the user consent of a session grant first.` };\n}\n\n/** Validates the reviewed inner step of a retry or frame wrapper against the same rules as a top-level step. */\nfunction validateinnerstep(options: Record<string, unknown>, origin: string): policyevaluation {\n const stepid = options.stepid;\n const kind = options.kind;\n if (isnonempty(stepid)) {\n if (kind !== undefined) return { allowed: false, reason: \"The reviewed wrapper must reference a step id or an inline step, not both.\" };\n return { allowed: true };\n }\n if (typeof kind !== \"string\" || !kind.trim()) return { allowed: false, reason: \"A reviewed step id or inline step kind is required in options.\" };\n if (kind === \"retryaction\" || kind === \"enterframe\") return { allowed: false, reason: \"The reviewed inner step cannot be another wrapper kind.\" };\n if (!allowedactions.has(kind as actionkind)) return { allowed: false, reason: \"The reviewed inner step kind is unsupported.\" };\n const inneroptions = options.options;\n if (inneroptions !== undefined && (!inneroptions || typeof inneroptions !== \"object\" || Array.isArray(inneroptions))) return { allowed: false, reason: \"The reviewed inner step options must be an object.\" };\n const inner: toolstep = {\n id: \"inner\",\n kind: kind as actionkind,\n summary: \"Reviewed inner step.\",\n risk: actionrisk(kind as actionkind),\n ...(isnonempty(options.target) ? { target: options.target } : {}),\n ...(isnonempty(options.value) ? { value: options.value } : {}),\n ...(inneroptions !== undefined ? { options: JSON.stringify(inneroptions) } : {}),\n };\n return validatestep(inner, origin);\n}\n\n/** True when a reviewed https url parses. */\nfunction ishttpsurl(value: unknown): value is string {\n if (typeof value !== \"string\" || !value.trim()) return false;\n try { return new URL(value).protocol === \"https:\"; } catch { return false; }\n}\n\n/** Validates the reviewed navtarget grammar of a navigation step. */\nfunction validatenavtarget(value: unknown, kind: string): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed navtarget with a url is required in options.\" };\n const target = value as Record<string, unknown>;\n if (!ishttpsurl(target.url)) return { allowed: false, reason: \"The reviewed navtarget url must use HTTPS.\" };\n const container = target.container ?? \"tab\";\n if (container !== \"current\" && container !== \"tab\" && container !== \"window\" && container !== \"private\") return { allowed: false, reason: \"The reviewed navtarget container must be current, tab, window or private.\" };\n if (target.position !== undefined && target.position !== \"adjacent\" && target.position !== \"end\") return { allowed: false, reason: \"The reviewed navtarget position must be adjacent or end.\" };\n if (kind === \"openprivate\" && container !== \"private\") return { allowed: false, reason: \"The openprivate step requires the private container.\" };\n if (kind === \"openlink\" && container === \"private\") return { allowed: false, reason: \"The openlink step cannot open the private container; use openprivate.\" };\n return { allowed: true };\n}\n\n/** Validates the reviewed waitprofile grammar with its load signals, thresholds and per origin overrides. */\nfunction validatewaitprofile(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed waitprofile with load signals is required in options.\" };\n const profile = value as Record<string, unknown>;\n if (!Array.isArray(profile.signals) || profile.signals.length === 0 || !profile.signals.every(signal => isnonempty(signal))) return { allowed: false, reason: \"The reviewed waitprofile needs a non-empty list of load signals.\" };\n if (!nonnegativeoption(profile, \"idle\")) return { allowed: false, reason: \"The reviewed waitprofile idle threshold must be zero or a positive number of milliseconds.\" };\n if (!nonnegativeoption(profile, \"timeout\")) return { allowed: false, reason: \"The reviewed waitprofile timeout must be zero or a positive number of milliseconds.\" };\n if (profile.overrides !== undefined) {\n if (!Array.isArray(profile.overrides) || profile.overrides.length === 0) return { allowed: false, reason: \"The reviewed waitprofile overrides must be a non-empty list when present.\" };\n for (const entry of profile.overrides) {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return { allowed: false, reason: \"Every reviewed waitprofile override must be an object with an origin.\" };\n const override = entry as Record<string, unknown>;\n if (!ishttpsurl(override.origin)) return { allowed: false, reason: \"Every reviewed waitprofile override origin must use HTTPS.\" };\n if (override.signals !== undefined && (!Array.isArray(override.signals) || !override.signals.every(signal => isnonempty(signal)))) return { allowed: false, reason: \"The reviewed waitprofile override signals must be a list of non-empty strings.\" };\n if (!nonnegativeoption(override, \"idle\") || !nonnegativeoption(override, \"timeout\")) return { allowed: false, reason: \"The reviewed waitprofile override thresholds must be zero or positive numbers.\" };\n }\n }\n return { allowed: true };\n}\n\n/** Validates the reviewed urlpattern grammar with its match mode plus query and fragment parts. */\nexport function validateurlpattern(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed urlpattern is required in options.\" };\n const pattern = value as Record<string, unknown>;\n if (pattern.mode !== \"exact\" && pattern.mode !== \"prefix\" && pattern.mode !== \"host\" && pattern.mode !== \"pattern\") return { allowed: false, reason: \"The reviewed urlpattern mode must be exact, prefix, host or pattern.\" };\n if (!ishttpsurl(pattern.url)) return { allowed: false, reason: \"The reviewed urlpattern url must use HTTPS.\" };\n if (pattern.query !== undefined) {\n if (!pattern.query || typeof pattern.query !== \"object\" || Array.isArray(pattern.query)) return { allowed: false, reason: \"The reviewed urlpattern query part must be an object of parameter names and values.\" };\n for (const item of Object.values(pattern.query)) if (typeof item !== \"string\") return { allowed: false, reason: \"The reviewed urlpattern query values must be strings.\" };\n }\n if (pattern.fragment !== undefined && !isnonempty(pattern.fragment)) return { allowed: false, reason: \"The reviewed urlpattern fragment must be a non-empty string.\" };\n return { allowed: true };\n}\n\n/** Validates a reviewed non-empty list of HTTPS urls in options. */\nfunction validateurllist(options: Record<string, unknown>, key: string): policyevaluation {\n const urls = options[key];\n if (!Array.isArray(urls) || urls.length === 0 || !urls.every(url => ishttpsurl(url))) return { allowed: false, reason: `A reviewed non-empty list of HTTPS urls is required in options as ${key}.` };\n return { allowed: true };\n}\n\n/** Validates the reviewed ratelimit grammar of a navrate step; the window and ceiling stay user configured with no hardcoded cap. */\nfunction validateratelimit(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed ratelimit with a window and a ceiling is required in options.\" };\n const limit = value as Record<string, unknown>;\n if (limit.domain !== undefined && !isnonempty(limit.domain)) return { allowed: false, reason: \"The reviewed ratelimit domain must be a non-empty string.\" };\n if (typeof limit.window !== \"number\" || !Number.isFinite(limit.window) || limit.window <= 0) return { allowed: false, reason: \"The reviewed ratelimit window must be a positive number of milliseconds with no code ceiling.\" };\n if (typeof limit.ceiling !== \"number\" || !Number.isInteger(limit.ceiling) || limit.ceiling < 1) return { allowed: false, reason: \"The reviewed ratelimit ceiling must be a positive integer with no code ceiling.\" };\n return { allowed: true };\n}\n\n/** Validates the reviewed tabquery grammar with url, title, id and pattern matchers; at least one matcher is required. */\nexport function validatetabquery(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed tabquery with at least one matcher is required in options.\" };\n const query = value as Record<string, unknown>;\n const hasmatcher = query.url !== undefined || query.title !== undefined || query.id !== undefined || query.pattern !== undefined;\n if (!hasmatcher) return { allowed: false, reason: \"The reviewed tabquery needs a url, title, id or pattern matcher.\" };\n if (query.url !== undefined && !isnonempty(query.url)) return { allowed: false, reason: \"The reviewed tabquery url matcher must be a non-empty string.\" };\n if (query.title !== undefined && !isnonempty(query.title)) return { allowed: false, reason: \"The reviewed tabquery title matcher must be a non-empty string.\" };\n if (query.pattern !== undefined && !isnonempty(query.pattern)) return { allowed: false, reason: \"The reviewed tabquery pattern matcher must be a non-empty string.\" };\n if (query.id !== undefined && (typeof query.id !== \"number\" || !Number.isInteger(query.id) || query.id < 0)) return { allowed: false, reason: \"The reviewed tabquery id matcher must be a non-negative integer tab id.\" };\n return { allowed: true };\n}\n\n/** Validates a reviewed group color choice against the Chromium tab group palette. */\nfunction validategroupcolor(value: unknown): boolean {\n return typeof value === \"string\" && (groupcolors as string[]).includes(value);\n}\n\n/** Validates a reviewed list of numeric browser ids in options. */\nfunction validateidlist(options: Record<string, unknown>, key: string): boolean {\n const ids = options[key];\n return Array.isArray(ids) && ids.length > 0 && ids.every(id => typeof id === \"number\" && Number.isInteger(id) && id >= 0);\n}\n\n/** Validates the reviewed tab and window parameter grammar of the tabs and windows command family. */\nfunction validatetabsgrammar(step: toolstep, options: Record<string, unknown>): policyevaluation {\n const kind = step.kind;\n if (kind === \"querytabs\" || kind === \"closepattern\") {\n const querycheck = validatetabquery(options.tabquery);\n if (!querycheck.allowed) return querycheck;\n if (kind === \"closepattern\" && options.reviewed !== true) return { allowed: false, reason: \"The close pattern needs the explicit reviewed flag before any tab closes.\" };\n }\n if (kind === \"duplicatetab\" || kind === \"pintab\" || kind === \"mutetab\" || kind === \"movetab\" || kind === \"movetabwindow\" || kind === \"badgetab\" || kind === \"attachmeta\") {\n if (!isnumericid(step.value)) return { allowed: false, reason: \"A numeric browser tab id is required.\" };\n }\n if (kind === \"focuswindow\" || kind === \"maximizewindow\" || kind === \"minimizewindow\" || kind === \"restorewindow\") {\n if (!isnumericid(step.value)) return { allowed: false, reason: \"A numeric browser window id is required.\" };\n }\n if (kind === \"pintab\" && typeof options.pinned !== \"boolean\") return { allowed: false, reason: \"A reviewed pinned flag is required in options.\" };\n if (kind === \"mutetab\" && typeof options.muted !== \"boolean\") return { allowed: false, reason: \"A reviewed muted flag is required in options.\" };\n if (kind === \"movetab\") {\n if (typeof options.index !== \"number\" || !Number.isInteger(options.index) || options.index < 0) return { allowed: false, reason: \"A reviewed non-negative target index is required in options.\" };\n }\n if (kind === \"movetabwindow\") {\n if (typeof options.windowid !== \"number\" || !Number.isInteger(options.windowid) || options.windowid < 0) return { allowed: false, reason: \"A reviewed target window id is required in options.\" };\n }\n if (kind === \"grouptabs\") {\n const group = options.group;\n if (!group || typeof group !== \"object\" || Array.isArray(group)) return { allowed: false, reason: \"A reviewed group with a name is required in options.\" };\n const spec = group as Record<string, unknown>;\n if (!isnonempty(spec.name)) return { allowed: false, reason: \"The reviewed group needs a non-empty name.\" };\n if (!validategroupcolor(spec.color)) return { allowed: false, reason: \"The reviewed group color must be a Chromium tab group color.\" };\n if (!validateidlist(spec, \"tabids\")) return { allowed: false, reason: \"The reviewed group needs a non-empty list of member tab ids.\" };\n }\n if (kind === \"colorgroup\") {\n if (!isnonempty(options.name)) return { allowed: false, reason: \"A reviewed group name is required in options.\" };\n if (!validategroupcolor(options.color)) return { allowed: false, reason: \"The reviewed group color must be a Chromium tab group color.\" };\n }\n if (kind === \"collapsegroup\") {\n if (!isnonempty(options.name)) return { allowed: false, reason: \"A reviewed group name is required in options.\" };\n if (typeof options.collapsed !== \"boolean\") return { allowed: false, reason: \"A reviewed collapsed flag is required in options.\" };\n }\n if (kind === \"discardtab\" || kind === \"reloadtabs\") {\n if (!isnumericid(step.value) && !validateidlist(options, \"tabs\")) return { allowed: false, reason: \"A numeric tab id or a reviewed list of tab ids is required.\" };\n }\n if (kind === \"zoomin\" || kind === \"zoomout\") {\n if (options.step !== undefined && (typeof options.step !== \"number\" || !Number.isFinite(options.step) || options.step <= 0)) return { allowed: false, reason: \"The reviewed zoom step must be a positive number with no code ceiling.\" };\n if (step.value !== undefined && step.value !== \"\" && !isnumericid(step.value)) return { allowed: false, reason: \"The reviewed zoom target must be a numeric tab id.\" };\n }\n if (kind === \"switchtab\") {\n if (options.direction !== \"next\" && options.direction !== \"previous\") return { allowed: false, reason: \"A reviewed switch direction of next or previous is required in options.\" };\n }\n if (kind === \"restorewindow\") {\n const bounds = options.bounds;\n if (bounds !== undefined) {\n if (!bounds || typeof bounds !== \"object\" || Array.isArray(bounds)) return { allowed: false, reason: \"The reviewed window bounds must be an object.\" };\n const shape = bounds as Record<string, unknown>;\n for (const field of [\"left\", \"top\", \"width\", \"height\"]) {\n if (typeof shape[field] !== \"number\" || !Number.isFinite(shape[field])) return { allowed: false, reason: \"The reviewed window bounds need numeric left, top, width and height.\" };\n }\n }\n }\n if (kind === \"scratchwindow\") {\n if (step.value !== undefined && step.value !== \"\" && !ishttpsurl(step.value)) return { allowed: false, reason: \"The reviewed scratch window url must use HTTPS.\" };\n }\n if (kind === \"incognitowindow\" && !ishttpsurl(step.value)) return { allowed: false, reason: \"A reviewed HTTPS url is required to open an incognito window.\" };\n if (kind === \"restoretab\" && step.value !== undefined && step.value !== \"\" && !ishttpsurl(step.value)) return { allowed: false, reason: \"The reviewed restore url must use HTTPS.\" };\n if (kind === \"savelayout\" || kind === \"restorelayout\") {\n if (!isnonempty(options.name)) return { allowed: false, reason: \"A reviewed layout name is required in options.\" };\n }\n if (kind === \"badgetab\") {\n if (!isnonempty(options.label)) return { allowed: false, reason: \"A reviewed badge label is required in options.\" };\n if (options.taskid !== undefined && !isnonempty(options.taskid)) return { allowed: false, reason: \"The reviewed badge task id must be a non-empty string.\" };\n }\n if (kind === \"attachmeta\") {\n const labels = options.labels;\n const taskrefs = options.taskrefs;\n const haslabels = Array.isArray(labels) && labels.length > 0 && labels.every(label => isnonempty(label));\n const hastaskrefs = Array.isArray(taskrefs) && taskrefs.length > 0 && taskrefs.every(ref => isnonempty(ref));\n if (!haslabels && !hastaskrefs) return { allowed: false, reason: \"Reviewed labels or task refs are required in options to attach metadata.\" };\n if (options.provenance !== undefined && !isnonempty(options.provenance)) return { allowed: false, reason: \"The reviewed provenance must be a non-empty string.\" };\n }\n if (kind === \"reopenrun\" && !isnonempty(options.run)) return { allowed: false, reason: \"A reviewed run id is required in options to reopen its tabs.\" };\n return { allowed: true };\n}\n\n/** Validates a single proposal against the active tab origin and local policy. */\nexport function validatestep(step: toolstep, origin: string): policyevaluation {\n if (!allowedactions.has(step.kind)) return { allowed: false, reason: \"Unsupported action kind.\" };\n if (!step.summary.trim()) return { allowed: false, reason: \"A human-readable action summary is required.\" };\n let options: Record<string, unknown>;\n try { options = parseoptions(step); } catch { return { allowed: false, reason: \"Step options must be a JSON object.\" }; }\n const hastargetref = options.targetref !== undefined;\n if (targetactions.has(step.kind) && !step.target?.trim() && !hastargetref) return { allowed: false, reason: \"A page target is required.\" };\n if (valueactions.has(step.kind) && !step.value?.trim()) return { allowed: false, reason: \"A reviewed value is required.\" };\n if (step.kind === \"select\" && !step.value?.trim()) return { allowed: false, reason: \"A reviewed option value is required.\" };\n if (step.kind === \"navigate\" && !step.value) return { allowed: false, reason: \"A navigation URL is required.\" };\n if (hastargetref) {\n const reference = validatetargetref(options.targetref);\n if (!reference.allowed) return reference;\n }\n if (step.kind === \"wait\") {\n try { waitduration(step); } catch { return { allowed: false, reason: \"Wait duration must be zero or a positive number of milliseconds.\" }; }\n }\n if (step.kind === \"navigate\") {\n try {\n if (new URL(step.value ?? \"\").origin !== origin) return { allowed: false, reason: \"Navigation must remain within the approved origin.\" };\n } catch {\n return { allowed: false, reason: \"Navigation URL is invalid.\" };\n }\n }\n if (step.kind === \"tabcreate\" || step.kind === \"windowcreate\" || step.kind === \"downloadfile\") {\n try {\n const url = new URL(step.value ?? \"\");\n if (url.protocol !== \"https:\") return { allowed: false, reason: \"The reviewed URL must use HTTPS.\" };\n } catch {\n return { allowed: false, reason: \"The reviewed URL is invalid.\" };\n }\n }\n if (step.kind === \"tabactivate\" || step.kind === \"tabclose\" || step.kind === \"tabreload\" || step.kind === \"windowclose\" || step.kind === \"windowresize\") {\n if (!isnumericid(step.value)) return { allowed: false, reason: \"A numeric browser id is required.\" };\n }\n if (step.kind === \"zoomset\") {\n const zoom = Number(step.value);\n if (!Number.isFinite(zoom) || zoom <= 0) return { allowed: false, reason: \"The reviewed zoom must be a positive number.\" };\n }\n if (step.kind === \"setattribute\" || step.kind === \"writestorage\") {\n const keyname = step.kind === \"setattribute\" ? \"name\" : \"key\";\n if (typeof options[keyname] !== \"string\" || !(options[keyname] as string).trim()) return { allowed: false, reason: `A reviewed ${keyname} is required in options.` };\n if (typeof options.value !== \"string\") return { allowed: false, reason: \"A reviewed value is required in options.\" };\n }\n if (step.kind === \"windowresize\") {\n if (typeof options.width !== \"number\" || typeof options.height !== \"number\" || !Number.isFinite(options.width) || !Number.isFinite(options.height)) return { allowed: false, reason: \"Reviewed width and height numbers are required in options.\" };\n }\n if ((step.kind === \"scrollpage\" || step.kind === \"scrollby\") && (!numericoption(options, \"x\") || !numericoption(options, \"y\"))) return { allowed: false, reason: \"Scroll amounts must be numbers in options.\" };\n if (step.kind === \"waitfor\" && options.timeout !== undefined && (typeof options.timeout !== \"number\" || options.timeout < 0)) return { allowed: false, reason: \"The waitfor timeout must be zero or a positive number of milliseconds.\" };\n if (step.kind === \"movepointer\") {\n const path = options.pointpath;\n if (!path || typeof path !== \"object\" || Array.isArray(path)) return { allowed: false, reason: \"A reviewed pointpath with start and end points is required in options.\" };\n const points = path as Record<string, unknown>;\n if (!ispoint(points.start) || !ispoint(points.end)) return { allowed: false, reason: \"The reviewed pointpath needs numeric start and end points.\" };\n if (points.waypoints !== undefined && (!Array.isArray(points.waypoints) || !points.waypoints.every(waypoint => ispoint(waypoint)))) return { allowed: false, reason: \"The reviewed pointpath waypoints must be numeric points.\" };\n if (!nonnegativeoption(points, \"duration\")) return { allowed: false, reason: \"The reviewed pointpath duration must be zero or a positive number of milliseconds.\" };\n const speed = options.speedprofile;\n if (speed !== undefined) {\n if (!speed || typeof speed !== \"object\" || Array.isArray(speed)) return { allowed: false, reason: \"The reviewed speed profile must be an object.\" };\n const profile = speed as Record<string, unknown>;\n if (profile.easing !== undefined && profile.easing !== \"linear\" && profile.easing !== \"easeinout\") return { allowed: false, reason: \"The reviewed easing must be linear or easeinout.\" };\n if (!nonnegativeoption(profile, \"peak\")) return { allowed: false, reason: \"The reviewed peak velocity must be zero or a positive number.\" };\n if (!nonnegativeoption(profile, \"jitter\")) return { allowed: false, reason: \"The reviewed jitter window must be zero or a positive number of milliseconds.\" };\n }\n }\n if (step.kind === \"clickpoint\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"point\")) return { allowed: false, reason: \"A reviewed point target reference is required in options.\" };\n if (step.kind === \"clicktext\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"text\")) return { allowed: false, reason: \"A reviewed text target reference is required in options.\" };\n if (step.kind === \"clickaria\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"aria\")) return { allowed: false, reason: \"A reviewed aria target reference is required in options.\" };\n if (step.kind === \"clickname\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"name\")) return { allowed: false, reason: \"A reviewed name target reference is required in options.\" };\n if (step.kind === \"resolvexpath\" && (!hastargetref || (options.targetref as Record<string, unknown>).mode !== \"xpath\")) return { allowed: false, reason: \"A reviewed xpath target reference is required in options.\" };\n if (step.kind === \"typetime\" && options.delay !== undefined && (typeof options.delay !== \"number\" || !Number.isFinite(options.delay) || options.delay < 0)) return { allowed: false, reason: \"The reviewed per keystroke delay must be zero or a positive number of milliseconds.\" };\n if (step.kind === \"submitsearch\") {\n if (!isnonempty(options.results)) return { allowed: false, reason: \"A reviewed results region selector is required in options.\" };\n if (options.timeout !== undefined && (typeof options.timeout !== \"number\" || !Number.isFinite(options.timeout) || options.timeout < 0)) return { allowed: false, reason: \"The submitsearch timeout must be zero or a positive number of milliseconds.\" };\n }\n if (step.kind === \"selectmulti\") {\n const values = options.values;\n if (!Array.isArray(values) || values.length === 0 || !values.every(value => isnonempty(value))) return { allowed: false, reason: \"A reviewed list of option values is required in options.\" };\n }\n if (step.kind === \"setslider\") {\n const slider = Number(step.value);\n if (!Number.isFinite(slider)) return { allowed: false, reason: \"The reviewed slider value must be a number.\" };\n }\n if (step.kind === \"setdate\" && !/^\\d{4}-\\d{2}-\\d{2}$/.test(step.value ?? \"\")) return { allowed: false, reason: \"The reviewed date must use the yyyy-mm-dd form.\" };\n if (step.kind === \"setcolor\" && !/^#[0-9a-fA-F]{6}$/.test(step.value ?? \"\")) return { allowed: false, reason: \"The reviewed color must use the #rrggbb form.\" };\n if (step.kind === \"keyhold\" && options.holdid !== undefined && !isnonempty(options.holdid)) return { allowed: false, reason: \"The reviewed hold id must be a non-empty string.\" };\n if (step.kind === \"dismissdialog\") {\n const accept = options.accept;\n const answer = options.answer;\n if (accept === undefined && !isnonempty(answer)) return { allowed: false, reason: \"A reviewed accept flag or prompt answer is required in options.\" };\n if (accept !== undefined && typeof accept !== \"boolean\") return { allowed: false, reason: \"The reviewed dialog accept flag must be a boolean.\" };\n if (answer !== undefined && !isnonempty(answer)) return { allowed: false, reason: \"The reviewed prompt answer must be a non-empty string.\" };\n }\n if (step.kind === \"pierceshadow\" && options.shadow !== undefined) {\n if (!Array.isArray(options.shadow) || !options.shadow.every(item => isnonempty(item))) return { allowed: false, reason: \"The reviewed shadow path must be a list of non-empty selectors.\" };\n }\n if (step.kind === \"enterframe\") {\n const path = options.framepath;\n if (!Array.isArray(path) || path.length === 0 || !path.every(item => typeof item === \"number\" && Number.isInteger(item) && item >= 0)) return { allowed: false, reason: \"A reviewed frame path of frame indexes is required in options.\" };\n return validateinnerstep(options, origin);\n }\n if (step.kind === \"retryaction\") {\n const inner = validateinnerstep(options, origin);\n if (!inner.allowed) return inner;\n const rule = options.retryrule;\n if (!rule || typeof rule !== \"object\" || Array.isArray(rule)) return { allowed: false, reason: \"A reviewed retry rule with attempts is required in options.\" };\n const retry = rule as Record<string, unknown>;\n if (typeof retry.attempts !== \"number\" || !Number.isInteger(retry.attempts) || retry.attempts < 1) return { allowed: false, reason: \"The reviewed retry attempts must be a positive integer with no code ceiling.\" };\n if (!nonnegativeoption(retry, \"settle\")) return { allowed: false, reason: \"The reviewed retry settle window must be zero or a positive number of milliseconds.\" };\n if (!nonnegativeoption(retry, \"tolerance\")) return { allowed: false, reason: \"The reviewed retry movement tolerance must be zero or a positive number of pixels.\" };\n }\n if (watchactions.has(step.kind)) {\n if (typeof options.lifetime !== \"number\" || !Number.isFinite(options.lifetime) || options.lifetime <= 0) return { allowed: false, reason: \"A reviewed watch lifetime window in milliseconds is required in options.\" };\n if (options.scopes !== undefined && (!Array.isArray(options.scopes) || !options.scopes.every(scope => isnonempty(scope)))) return { allowed: false, reason: \"The reviewed watch scopes must be a list of non-empty selectors.\" };\n if (options.events !== undefined && (!Array.isArray(options.events) || !options.events.every(event => isnonempty(event)))) return { allowed: false, reason: \"The reviewed watch event kinds must be a list of non-empty strings.\" };\n if (!nonnegativeoption(options, \"poll\")) return { allowed: false, reason: \"The reviewed watch poll interval must be zero or a positive number of milliseconds.\" };\n }\n if (step.kind === \"waitquiet\") {\n const rule = options.quietrule;\n if (!rule || typeof rule !== \"object\" || Array.isArray(rule)) return { allowed: false, reason: \"A reviewed quietrule with an idle threshold is required in options.\" };\n const quiet = rule as Record<string, unknown>;\n if (typeof quiet.idle !== \"number\" || !Number.isFinite(quiet.idle) || quiet.idle <= 0) return { allowed: false, reason: \"The reviewed quiet idle threshold must be a positive number of milliseconds with no code ceiling.\" };\n if (!nonnegativeoption(quiet, \"poll\")) return { allowed: false, reason: \"The reviewed quiet poll interval must be zero or a positive number of milliseconds.\" };\n if (!nonnegativeoption(quiet, \"timeout\")) return { allowed: false, reason: \"The reviewed quiet timeout must be zero or a positive number of milliseconds.\" };\n }\n if (step.kind === \"diffsnapshots\") {\n const versions = options.versions;\n if (!Array.isArray(versions) || versions.length !== 2 || !versions.every(version => typeof version === \"number\" && Number.isInteger(version) && version >= 1)) return { allowed: false, reason: \"Two reviewed observation version numbers are required in options.\" };\n }\n if (step.kind === \"openlink\" || step.kind === \"openprivate\" || step.kind === \"deeplink\") {\n const targetcheck = validatenavtarget(options.navtarget, step.kind);\n if (!targetcheck.allowed) return targetcheck;\n if (step.kind === \"deeplink\") {\n const app = options.app;\n if (!isnonempty(app)) return { allowed: false, reason: \"A reviewed deep link app pattern is required in options.\" };\n const params = options.params;\n if (params !== undefined && (!params || typeof params !== \"object\" || Array.isArray(params) || !Object.values(params).every(item => typeof item === \"string\"))) return { allowed: false, reason: \"The reviewed deep link params must be an object of string values.\" };\n }\n }\n if (step.kind === \"waitload\" && !nonnegativeoption(options, \"timeout\")) return { allowed: false, reason: \"The waitload timeout must be zero or a positive number of milliseconds.\" };\n if (step.kind === \"waiturl\" || step.kind === \"spawait\") {\n if (step.kind === \"waiturl\") {\n const patterncheck = validateurlpattern(options.urlpattern);\n if (!patterncheck.allowed) return patterncheck;\n }\n if (!nonnegativeoption(options, \"timeout\")) return { allowed: false, reason: \"The wait timeout must be zero or a positive number of milliseconds.\" };\n if (!nonnegativeoption(options, \"poll\")) return { allowed: false, reason: \"The wait poll interval must be zero or a positive number of milliseconds.\" };\n }\n if (step.kind === \"followlink\") {\n if (options.fragment !== undefined && typeof options.fragment !== \"boolean\") return { allowed: false, reason: \"The reviewed followlink fragment flag must be a boolean.\" };\n }\n if (step.kind === \"spanav\") {\n if (options.routepattern !== undefined) {\n const routecheck = validateurlpattern(options.routepattern);\n if (!routecheck.allowed) return routecheck;\n }\n if (!nonnegativeoption(options, \"timeout\")) return { allowed: false, reason: \"The spanav route timeout must be zero or a positive number of milliseconds.\" };\n }\n if (step.kind === \"rewritequery\") {\n const set = options.set;\n const remove = options.remove;\n if (set === undefined && remove === undefined) return { allowed: false, reason: \"Reviewed query parameters to set or remove are required in options.\" };\n if (set !== undefined && (!set || typeof set !== \"object\" || Array.isArray(set) || !Object.values(set).every(item => typeof item === \"string\"))) return { allowed: false, reason: \"The reviewed query parameters to set must be an object of string values.\" };\n if (remove !== undefined && (!Array.isArray(remove) || !remove.every(item => isnonempty(item)))) return { allowed: false, reason: \"The reviewed query parameters to remove must be a list of non-empty names.\" };\n }\n if (step.kind === \"navlist\") {\n const listcheck = validateurllist(options, \"urls\");\n if (!listcheck.allowed) return listcheck;\n }\n if (step.kind === \"navprofile\") {\n const profilecheck = validatewaitprofile(options.waitprofile);\n if (!profilecheck.allowed) return profilecheck;\n }\n if (step.kind === \"handleauth\" && !ishttpsurl(step.value)) return { allowed: false, reason: \"A reviewed HTTPS origin or url is required as the auth target.\" };\n if (step.kind === \"printpdf\" && options.name !== undefined && !isnonempty(options.name)) return { allowed: false, reason: \"The reviewed artifact name must be a non-empty string.\" };\n if (step.kind === \"prefetch\") {\n const listcheck = validateurllist(options, \"urls\");\n if (!listcheck.allowed) return listcheck;\n }\n if (step.kind === \"preconnect\") {\n const origins = options.origins;\n if (!Array.isArray(origins) || origins.length === 0 || !origins.every(originurl => ishttpsurl(originurl))) return { allowed: false, reason: \"A reviewed non-empty list of HTTPS origins is required in options.\" };\n }\n if (step.kind === \"reopentab\" && step.value !== undefined && !ishttpsurl(step.value)) return { allowed: false, reason: \"The reviewed reopen url must use HTTPS.\" };\n if (step.kind === \"navrate\") {\n const limitcheck = validateratelimit(options.ratelimit);\n if (!limitcheck.allowed) return limitcheck;\n }\n if (step.kind === \"checksafe\" && !ishttpsurl(step.value)) return { allowed: false, reason: \"A reviewed HTTPS url is required for the safety check.\" };\n if (step.kind === \"batchopen\") {\n const listcheck = validateurllist(options, \"urls\");\n if (!listcheck.allowed) return listcheck;\n }\n if (istabscommandkind(step.kind)) {\n const tabscheck = validatetabsgrammar(step, options);\n if (!tabscheck.allowed) return tabscheck;\n }\n if (step.kind === \"tabcreate\") {\n if (options.background !== undefined && typeof options.background !== \"boolean\") return { allowed: false, reason: \"The reviewed background flag must be a boolean.\" };\n if (options.window !== undefined && (typeof options.window !== \"number\" || !Number.isInteger(options.window) || options.window < 0)) return { allowed: false, reason: \"The reviewed target window id must be a non-negative integer.\" };\n }\n if (step.kind === \"windowcreate\") {\n for (const field of [\"left\", \"top\", \"width\", \"height\"]) {\n if (options[field] !== undefined && (typeof options[field] !== \"number\" || !Number.isFinite(options[field]))) return { allowed: false, reason: `The reviewed window ${field} must be a number.` };\n }\n if (options.state !== undefined && ![\"normal\", \"maximized\", \"minimized\", \"fullscreen\"].includes(options.state as string)) return { allowed: false, reason: \"The reviewed window state must be normal, maximized, minimized or fullscreen.\" };\n }\n return { allowed: true };\n}\n\n/** Shared session gate: a live, unpaused session that still matches the active tab. */\nfunction sessiongate(input: { session: agentsession | undefined; tabid: number; origin: string; now: number; action: string }): policyevaluation {\n if (!input.session || input.session.stoppedat) return { allowed: false, reason: \"No active browser session exists.\" };\n if (input.session.expiresat <= input.now) return { allowed: false, reason: \"The browser session has expired.\" };\n if (input.session.pausedat) return { allowed: false, reason: `The browser session is paused and cannot ${input.action}.` };\n if (input.session.tabid !== input.tabid || input.session.origin !== input.origin) return { allowed: false, reason: `The ${input.action} is outside the approved tab or origin.` };\n return { allowed: true };\n}\n\n/** Applies the consent gate immediately before an action reaches the page bridge. */\nexport function canexecute(input: { session: agentsession | undefined; plan: agentplan | undefined; step: toolstep; tabid: number; origin: string; now?: number; verdicts?: safetyverdict[] }): policyevaluation {\n const now = input.now ?? Date.now();\n const gate = sessiongate({ session: input.session, tabid: input.tabid, origin: input.origin, now, action: \"execute an action\" });\n if (!gate.allowed) return gate;\n if (!input.plan || input.plan.state !== \"approved\") return { allowed: false, reason: \"The plan has not received explicit approval.\" };\n if (input.plan.expiresat <= now) return { allowed: false, reason: \"The approved plan has expired.\" };\n if ((input.step.kind === \"pierceshadow\" || input.step.kind === \"enterframe\") && !origingranted(input.session, input.origin)) return { allowed: false, reason: \"The shadow or frame step is outside the session origin grants.\" };\n if (input.step.kind === \"readjson\" && !origingranted(input.session, input.origin)) return { allowed: false, reason: \"The json state read is outside the session origin grants.\" };\n if (input.step.kind === \"navlist\") {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(input.step); } catch { options = {}; }\n for (const url of Array.isArray(options.urls) ? options.urls : []) {\n if (typeof url !== \"string\") continue;\n const navigation = navigationgranted(input.session, url);\n if (!navigation.allowed) return navigation;\n }\n }\n if (islayoutkind(input.step.kind) && !layoutmutationgranted(input.session, now).allowed) return { allowed: false, reason: \"Group and layout mutations stay inside the active session.\" };\n if (input.step.kind === \"openlink\" || input.step.kind === \"openprivate\" || input.step.kind === \"batchopen\" || input.step.kind === \"prefetch\" || input.step.kind === \"deeplink\" || input.step.kind === \"reopentab\") {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(input.step); } catch { options = {}; }\n const grammar = validatestep(input.step, input.origin);\n if (!grammar.allowed) return grammar;\n const grants = input.session?.grants ?? [input.session?.origin ?? input.origin];\n const targets: unknown[] = input.step.kind === \"batchopen\" || input.step.kind === \"prefetch\" ? (Array.isArray(options.urls) ? options.urls : []) : input.step.kind === \"reopentab\" ? [input.step.value] : [(options.navtarget as Record<string, unknown> | undefined)?.url];\n for (const target of targets) {\n if (typeof target !== \"string\" || !target) continue;\n const verified = originverified(target, grants, input.verdicts ?? []);\n if (!verified.allowed) return verified;\n }\n }\n return validatestep(input.step, input.origin);\n}\n\n/** Allows a non-mutating, temporary target preview during plan review. */\nexport function canpreview(input: { session: agentsession | undefined; plan: agentplan | undefined; step: toolstep; tabid: number; origin: string; now?: number }): policyevaluation {\n const now = input.now ?? Date.now();\n const gate = sessiongate({ session: input.session, tabid: input.tabid, origin: input.origin, now, action: \"preview a target\" });\n if (!gate.allowed) return gate;\n if (!input.plan || ![\"pending\", \"approved\"].includes(input.plan.state)) return { allowed: false, reason: \"Only a reviewed pending or approved plan can be previewed.\" };\n if (input.plan.expiresat <= now) return { allowed: false, reason: \"The reviewed plan has expired.\" };\n let options: Record<string, unknown> = {};\n try { options = parseoptions(input.step); } catch { options = {}; }\n if (!targetactions.has(input.step.kind) && options.targetref === undefined) return { allowed: false, reason: \"Only a target-based action can be previewed.\" };\n return validatestep(input.step, input.origin);\n}\n", "import type { agentplan, planprogress, stepoutcome } from \"./types.js\";\n\n/**\n * Execution-progress logics for reviewed plans.\n * Every correlated rule for step completion, outcome history, deduplication and plan closure lives in this file.\n */\n\n/** Returns a fresh progress record for a plan that has not executed any step yet. */\nexport function emptyprogress(planid: string, now: number): planprogress {\n return { planid, completedsteps: [], updatedat: now };\n}\n\n/** Records one successfully executed step; repeated executions of the same step stay deduplicated. */\nexport function recordstep(progress: planprogress | undefined, planid: string, stepid: string, now: number): planprogress {\n const base = progress && progress.planid === planid ? progress : emptyprogress(planid, now);\n if (base.completedsteps.includes(stepid)) return { ...base, updatedat: now };\n return { planid, completedsteps: [...base.completedsteps, stepid], updatedat: now };\n}\n\n/** Records one structured step outcome beside the completion log; outcomes are never truncated. */\nexport function recordoutcome(progress: planprogress | undefined, planid: string, outcome: stepoutcome, now: number): planprogress {\n const base = progress && progress.planid === planid ? progress : emptyprogress(planid, now);\n return { ...base, outcomes: [...(base.outcomes ?? []), outcome], updatedat: now };\n}\n\n/** True only when every step of the plan has a recorded, successful execution. */\nexport function iscomplete(progress: planprogress | undefined, plan: agentplan): boolean {\n if (!progress || progress.planid !== plan.id) return false;\n const required = plan.steps.map(step => step.id);\n return required.length > 0 && required.every(id => progress.completedsteps.includes(id));\n}\n\n/** Clears progress whenever a different plan replaces the tracked one while preserving prior history snapshots. */\nexport function resetforplan(progress: planprogress | undefined, plan: agentplan, now: number): planprogress {\n if (progress && progress.planid === plan.id) return progress;\n if (!progress) return emptyprogress(plan.id, now);\n const snapshot: planprogress = { planid: progress.planid, completedsteps: progress.completedsteps, ...(progress.outcomes ? { outcomes: progress.outcomes } : {}), updatedat: progress.updatedat };\n return { planid: plan.id, completedsteps: [], outcomes: [], prior: [...(progress.prior ?? []), snapshot], updatedat: now };\n}\n\n/** True when a reviewed watch lifetime window has closed at the given time. */\nexport function watchclosed(startedat: number, lifetime: number, now: number): boolean {\n return now >= startedat + lifetime;\n}\n\n/** Records one watch step as completed only once its reviewed lifetime window has closed. */\nexport function recordwatchcompletion(progress: planprogress | undefined, planid: string, stepid: string, startedat: number, lifetime: number, now: number): planprogress {\n const base = progress && progress.planid === planid ? progress : emptyprogress(planid, now);\n if (!watchclosed(startedat, lifetime, now)) return base;\n return recordstep(base, planid, stepid, now);\n}\n\n/** One navlist entry completion record with its index, url and outcome. */\nexport interface naventry {\n index: number;\n url: string;\n ok: boolean;\n}\n\n/** Records one navlist entry as it completes, beside the step outcome log, so the trail shows current url and remaining count. */\nexport function recordnaventry(progress: planprogress | undefined, planid: string, stepid: string, entry: naventry, now: number): planprogress {\n const base = progress && progress.planid === planid ? progress : emptyprogress(planid, now);\n const outcome: stepoutcome = { stepid, ok: entry.ok, summary: `Navigation list entry ${entry.index + 1} of ${entry.url} ${entry.ok ? \"completed\" : \"failed\"}.`, details: { naventry: entry }, at: now };\n return recordoutcome(base, planid, outcome, now);\n}\n\n/** Returns every recorded navlist entry completion of one step, oldest first. */\nexport function naventries(progress: planprogress | undefined, planid: string, stepid: string): naventry[] {\n if (!progress || progress.planid !== planid) return [];\n return (progress.outcomes ?? []).filter(outcome => outcome.stepid === stepid && outcome.details?.naventry !== undefined).map(outcome => outcome.details?.naventry as naventry);\n}\n\n/** Assigns one tab to the running task so progress tracks work across its tabs. */\nexport function assigntasktab(progress: planprogress | undefined, planid: string, tabid: number, now: number): planprogress {\n const base = progress && progress.planid === planid ? progress : emptyprogress(planid, now);\n if ((base.tasktabs ?? []).includes(tabid)) return { ...base, updatedat: now };\n return { ...base, tasktabs: [...(base.tasktabs ?? []), tabid], updatedat: now };\n}\n\n/** Releases one task tab when its work inside the running task ends. */\nexport function releasetasktab(progress: planprogress | undefined, planid: string, tabid: number, now: number): planprogress {\n const base = progress && progress.planid === planid ? progress : emptyprogress(planid, now);\n const remaining = (base.tasktabs ?? []).filter(id => id !== tabid);\n const { tasktabs: released, ...rest } = base;\n void released;\n return { ...rest, ...(remaining.length > 0 ? { tasktabs: remaining } : {}), updatedat: now };\n}\n\n/** Returns the tabs assigned to the running task, in assignment order. */\nexport function tasktabs(progress: planprogress | undefined, planid: string): number[] {\n if (!progress || progress.planid !== planid) return [];\n return progress.tasktabs ?? [];\n}\n", "/** Canonical package version synchronized from package.json. */\nexport const packageversion = \"1.1.36\" as const;\n", "/** Shared contracts for every Devthink target. */\nimport { packageversion } from \"./version.js\";\n\nexport const protocolversion = packageversion;\n\n/** Every reviewed action kind. Read kinds observe, interaction kinds move focus, sensitive kinds change page or browser state. */\nexport type actionkind =\n | \"observe\" | \"inspect\" | \"extract\" | \"wait\" | \"waitfor\" | \"waittext\"\n | \"readattribute\" | \"readstyle\" | \"readgeometry\" | \"readvalue\" | \"readtext\" | \"readhtml\"\n | \"countelements\" | \"readtable\" | \"readlinks\" | \"readimages\" | \"readmeta\" | \"readforms\"\n | \"readstorage\" | \"highlight\" | \"tablist\" | \"windowlist\" | \"tabsnapshot\"\n | \"focus\" | \"scroll\" | \"hover\" | \"clickdeep\" | \"rightclick\" | \"doubleclick\"\n | \"scrollpage\" | \"scrollby\" | \"scrollend\" | \"scrolltop\" | \"fullscreen\" | \"zoomset\"\n | \"click\" | \"type\" | \"navigate\" | \"select\" | \"presskey\" | \"drag\" | \"drop\" | \"upload\"\n | \"clear\" | \"check\" | \"uncheck\" | \"toggle\" | \"submit\" | \"reload\" | \"back\" | \"forward\"\n | \"writestorage\" | \"setattribute\" | \"removeattribute\" | \"evaluate\"\n | \"tabcreate\" | \"tabactivate\" | \"tabclose\" | \"tabreload\"\n | \"windowcreate\" | \"windowclose\" | \"windowresize\" | \"downloadfile\"\n | \"movepointer\" | \"clickpoint\" | \"shiftclick\" | \"clicktext\" | \"clickaria\" | \"clickname\"\n | \"resolvexpath\" | \"typetime\" | \"appendtext\" | \"setvalue\" | \"typeedit\"\n | \"keyhold\" | \"keyrelease\" | \"submitsearch\" | \"selectmulti\" | \"chooseradio\"\n | \"setslider\" | \"setdate\" | \"setcolor\" | \"expanddetails\" | \"dismissdialog\"\n | \"pierceshadow\" | \"enterframe\" | \"retryaction\"\n | \"mapclicks\" | \"verifyvisible\" | \"verifyenabled\"\n | \"a11ytree\" | \"readvisible\" | \"readertree\" | \"detectlists\" | \"detecttables\"\n | \"readjson\" | \"watchmutate\" | \"waitquiet\" | \"watchbanner\" | \"detectinfinitescroll\"\n | \"detectvirtual\" | \"detectlazy\" | \"readscrollpos\" | \"readlang\" | \"readoutline\"\n | \"countpages\" | \"listshadow\" | \"listframes\" | \"classifypage\" | \"fingerprintsection\"\n | \"diffsnapshots\" | \"readselection\" | \"watchfocus\" | \"detectsticky\" | \"detectscrolllock\"\n | \"readopengraph\" | \"detectlanguage\" | \"deriveselector\"\n | \"openlink\" | \"openprivate\" | \"reloadcache\" | \"stopnav\" | \"waitload\" | \"waiturl\"\n | \"followlink\" | \"spanav\" | \"spawait\" | \"rewritequery\" | \"setfragment\" | \"navlist\"\n | \"navprofile\" | \"detecthttp\" | \"readredirects\" | \"readfinalurl\" | \"handleauth\" | \"printpdf\"\n | \"prefetch\" | \"preconnect\" | \"deeplink\" | \"reopentab\" | \"trailaudit\" | \"pausenav\"\n | \"navintent\" | \"navrate\" | \"openclipboard\" | \"checksafe\" | \"batchopen\"\n | \"querytabs\" | \"duplicatetab\" | \"closepattern\" | \"pintab\" | \"mutetab\" | \"movetab\"\n | \"movetabwindow\" | \"grouptabs\" | \"colorgroup\" | \"collapsegroup\" | \"discardtab\"\n | \"reloadtabs\" | \"zoomin\" | \"zoomout\" | \"watchtab\" | \"switchtab\" | \"maximizewindow\"\n | \"minimizewindow\" | \"restorewindow\" | \"focuswindow\" | \"scratchwindow\" | \"incognitowindow\"\n | \"restoretab\" | \"savelayout\" | \"restorelayout\" | \"findclones\" | \"searchtabs\"\n | \"badgetab\" | \"attachmeta\" | \"listaudio\" | \"reopenrun\" | \"snapshotsession\";\n\nexport type actionrisk = \"read\" | \"interaction\" | \"sensitive\";\nexport type planstate = \"draft\" | \"pending\" | \"approved\" | \"rejected\" | \"expired\" | \"completed\" | \"cancelled\";\nexport type auditkind = \"configure\" | \"session\" | \"observe\" | \"proposal\" | \"approval\" | \"action\" | \"error\" | \"stop\" | \"pause\" | \"resume\" | \"complete\" | \"capability\" | \"tab\" | \"window\" | \"download\" | \"pointer\" | \"dialog\" | \"hold\" | \"retry\" | \"observation\" | \"watch\" | \"diff\" | \"navigation\" | \"redirect\" | \"auth\" | \"prefetch\" | \"rate\" | \"group\" | \"layout\" | \"discard\" | \"badge\";\n\n/** Observation mode classes: passive capture, watched lifetimes and diffing passes. */\nexport type observationmode = \"passive\" | \"watching\" | \"diffing\";\n\nexport interface toolstep {\n id: string;\n kind: actionkind;\n target?: string;\n value?: string;\n /** Reviewed JSON parameters such as modifiers, amounts or coordinates. */\n options?: string;\n summary: string;\n risk: actionrisk;\n}\n\nexport interface agentplan {\n id: string;\n objective: string;\n origin: string;\n steps: toolstep[];\n createdat: number;\n expiresat: number;\n state: planstate;\n approvedat?: number;\n completedat?: number;\n}\n\nexport interface agentsession {\n id: string;\n tabid: number;\n origin: string;\n startedat: number;\n expiresat: number;\n stoppedat?: number;\n pausedat?: number;\n /** Origins granted to this session; prepared for multi origin work. */\n grants?: string[];\n}\n\nexport interface endpointconfig {\n endpoint: string;\n origin: string;\n configuredat: number;\n}\n\nexport interface observation {\n /** Observation schema version for forward compatibility. */\n schemaversion: number;\n url: string;\n title: string;\n textpreview: string;\n textlength: number;\n forms: Array<{ label: string; type: string; name: string; options?: string[] }>;\n interactive: Array<{ selector: string; role: string; label: string }>;\n capturedat: number;\n /** Observation mode of this capture: passive, watching or diffing. */\n mode?: observationmode;\n /** Accessibility tree section captured by the page walker. */\n a11y?: a11ynode;\n /** Reader view article section extracted by the text density heuristic. */\n reader?: readerarticle;\n /** Repeated list patterns detected on the page. */\n listpattern?: listpattern[];\n /** Data table shapes detected on the page. */\n tableshape?: tableshape[];\n /** Snapshot diff section attached when two observation versions are compared. */\n diff?: snapshotdiff;\n}\n\nexport interface auditevent {\n id: string;\n kind: auditkind;\n at: number;\n summary: string;\n sessionid?: string;\n planid?: string;\n stepid?: string;\n}\n\nexport interface diagnosticreport {\n id: string;\n sessionid: string;\n origin: string;\n capturedat: number;\n tabid: number;\n title: string;\n textlength: number;\n interactivecount: number;\n formcount: number;\n bridgeavailable: boolean;\n}\n\n/** Live report of the optional browser capabilities the user has granted. */\nexport interface capabilityreport {\n tabs: boolean;\n downloads: boolean;\n clipboardread: boolean;\n clipboardwrite: boolean;\n reportedat: number;\n}\n\n/** Structured result of one executed step, kept with configurable retention. */\nexport interface stepoutcome {\n stepid: string;\n ok: boolean;\n summary: string;\n details?: Record<string, unknown>;\n at: number;\n}\n\n/** User chosen retention windows; an absent value keeps everything forever. */\nexport interface runsettings {\n auditretention?: number;\n outcomeretention?: number;\n /** Retention window for stored observation captures such as a11y trees and reader articles. */\n observationretention?: number;\n /** User configured ceiling on concurrent task tabs; an absent value never refuses a tab. */\n tasktabceiling?: number;\n /** True when the pinned control tab with the live task feed stays open. */\n controltab?: boolean;\n}\n\nexport interface proposalrequest {\n objective: string;\n session: agentsession;\n observation: observation;\n capabilities: capabilityreport;\n}\n\nexport interface planproposal {\n version: typeof protocolversion;\n plan: agentplan;\n}\n\nexport interface policyevaluation {\n allowed: boolean;\n reason?: string;\n}\n\n/** Tracks which reviewed steps of one plan have already executed locally. */\nexport interface planprogress {\n planid: string;\n completedsteps: string[];\n outcomes?: stepoutcome[];\n /** Tabs assigned to the running task so progress tracks work across its tabs. */\n tasktabs?: number[];\n /** Prior progress snapshots preserved when a new plan replaces the tracked one. */\n prior?: planprogress[];\n updatedat: number;\n}\n\n/** Modes that address one element during target resolution. */\nexport type targetmode = \"selector\" | \"text\" | \"aria\" | \"name\" | \"xpath\" | \"index\" | \"point\";\n\n/** Reviewed element reference resolved by the page bridge at preview and execution time. */\nexport interface targetref {\n mode: targetmode;\n selector?: string;\n text?: string;\n role?: string;\n name?: string;\n xpath?: string;\n index?: number;\n x?: number;\n y?: number;\n}\n\n/** One point on a reviewed pointer path. */\nexport interface pointref {\n x: number;\n y: number;\n}\n\n/** Reviewed pointer path between two points through optional waypoints. */\nexport interface pointpath {\n start: pointref;\n end: pointref;\n waypoints?: pointref[];\n duration?: number;\n}\n\n/** Reviewed pointer speed shape with an easing curve, peak velocity and a jitter window. */\nexport interface speedprofile {\n easing?: \"linear\" | \"easeinout\";\n peak?: number;\n jitter?: number;\n}\n\n/** One key held down across steps under a hold id, with tab and step provenance. */\nexport interface keyholdstate {\n holdid: string;\n key: string;\n modifiers?: string[];\n tabid?: number;\n stepid?: string;\n pressedat: number;\n releasedat?: number;\n}\n\n/** Reviewed answers for confirm, alert and prompt dialogs; prompts need a reviewed answer. */\nexport interface dialogpolicy {\n accept: boolean;\n answer?: string;\n}\n\n/** Ordered frame indexes that address targets inside same origin iframes. */\nexport type framepath = number[];\n\n/** Ordered host selectors that address targets across open shadow roots. */\nexport type shadowpath = string[];\n\n/** Reviewed retry bounds with an attempt count that carries no hardcoded ceiling. */\nexport interface retryrule {\n attempts: number;\n settle?: number;\n tolerance?: number;\n}\n\n/** One numbered clickable element of a clickablemap. */\nexport interface mapentry {\n number: number;\n selector: string;\n role: string;\n label: string;\n mode: targetmode;\n}\n\n/** Numbered map of every clickable element captured inside one observation version. */\nexport interface clickablemap {\n version: number;\n entries: mapentry[];\n builtat: number;\n}\n\n/** Matched element summary attached to step results and review envelopes. */\nexport interface resolvedtarget {\n mode: targetmode;\n selector: string;\n tag: string;\n label: string;\n geometry: { x: number; y: number; width: number; height: number };\n candidates?: string[];\n}\n\n/** One dialog answered by the reviewed dialog policy, kept for the audit trail. */\nexport interface dialogdecision {\n id: string;\n dialog: string;\n text: string;\n accept: boolean;\n answer?: string;\n sessionid?: string;\n at: number;\n}\n\n/** One retry execution record with the attempts made and the movement delta observed between them. */\nexport interface retryoutcome {\n stepid: string;\n attempts: number;\n movement: number;\n ok: boolean;\n at: number;\n}\n\n/** Resolution summary stored per target mode for later selector derivation. */\nexport interface resolutionsummary {\n stepid: string;\n mode: targetmode;\n selector: string;\n label: string;\n at: number;\n}\n\n/** One accessibility tree node with role, accessible name, states, value and child refs. */\nexport interface a11ynode {\n role: string;\n name: string;\n states: string[];\n value?: string;\n childcount: number;\n children: a11ynode[];\n}\n\n/** One reader view article with title, byline, blocks and text statistics. */\nexport interface readerarticle {\n title: string;\n byline: string;\n blocks: Array<{ kind: string; text: string; words: number }>;\n words: number;\n characters: number;\n}\n\n/** One detected repeated list with its shared item selector, repeat count and samples. */\nexport interface listpattern {\n container: string;\n itemselector: string;\n repeat: number;\n samples: string[];\n}\n\n/** One detected data table shape with header row, column specs and caption. */\nexport interface tableshape {\n selector: string;\n headers: string[];\n columns: Array<{ label: string; cells: number }>;\n rows: number;\n caption: string;\n}\n\n/** One embedded json state payload extracted from an inline script. */\nexport interface jsonstate {\n scripturl: string;\n rootpath: string;\n payload: unknown;\n}\n\n/** Reviewed watch registration with selector scopes, event kinds and a lifetime window. */\nexport interface mutationwatch {\n watchid?: string;\n scopes?: string[];\n events?: string[];\n lifetime: number;\n}\n\n/** Reviewed network quiet rule with an idle threshold, poll interval and timeout. */\nexport interface quietrule {\n idle: number;\n poll?: number;\n timeout?: number;\n}\n\n/** One dom mutation observed inside a reviewed watch, with a timestamp and target path. */\nexport interface mutationevent {\n watchid: string;\n event: string;\n targetpath: string;\n sessionid?: string;\n at: number;\n}\n\n/** One focus change observed inside a reviewed focus watch, with a timestamp and target path. */\nexport interface focusevent {\n watchid: string;\n kind: \"focus\" | \"blur\";\n targetpath: string;\n sessionid?: string;\n at: number;\n}\n\n/** One consent banner observed by a reviewed banner watch, with its controls. */\nexport interface bannerreport {\n kind: string;\n selector: string;\n text: string;\n controls: string[];\n sessionid?: string;\n at: number;\n}\n\n/** One node change inside a snapshot diff. */\nexport interface diffentry {\n kind: \"added\" | \"removed\" | \"changed\";\n selector: string;\n summary: string;\n}\n\n/** One snapshot diff between two stored observation versions. */\nexport interface snapshotdiff {\n baseversion: number;\n targetversion: number;\n added: diffentry[];\n removed: diffentry[];\n changed: diffentry[];\n at: number;\n}\n\n/** One derived selector candidate with its strategy and stability score. */\nexport interface selectorcandidate {\n selector: string;\n strategy: string;\n score: number;\n}\n\n/** One derived selector stored with its stability score for reuse. */\nexport interface derivedselector {\n stepid: string;\n selector: string;\n strategy: string;\n score: number;\n at: number;\n}\n\n/** One watch registration persisted so watches survive service worker restarts. */\nexport interface watchregistration {\n watchid: string;\n kind: actionkind;\n stepid: string;\n sessionid: string;\n origin: string;\n scopes: string[];\n events: string[];\n startedat: number;\n lifetime: number;\n closedat?: number;\n}\n\n/** One stored observation capture under its version. */\nexport interface observationrecord {\n version: number;\n observation: observation;\n}\n\n/** One stored accessibility tree capture. */\nexport interface a11ycapture {\n version: number;\n tree: a11ynode;\n capturedat: number;\n}\n\n/** One stored reader article capture. */\nexport interface readercapture {\n version: number;\n article: readerarticle;\n capturedat: number;\n}\n\n/** Live page signals refreshed after observation steps: language, template, scroll lock and banner state. */\nexport interface pagesignals {\n language?: string;\n template?: string;\n scrolllocked?: boolean;\n banner?: string;\n refreshedat: number;\n}\n\n/** One detected template class or section fingerprint stored per origin. */\nexport interface templateprofile {\n origin: string;\n template: string;\n fingerprint: string;\n section?: string;\n at: number;\n}\n\n/** Reviewed navigation target with its url, container, position and private flag. */\nexport interface navtarget {\n url: string;\n container: \"current\" | \"tab\" | \"window\" | \"private\";\n position?: \"adjacent\" | \"end\";\n private: boolean;\n}\n\n/** Reviewed per origin override of one wait profile. */\nexport interface waitoverride {\n origin: string;\n signals?: string[];\n idle?: number;\n timeout?: number;\n}\n\n/** Reviewed wait profile with load signals, thresholds and per origin overrides. */\nexport interface waitprofile {\n signals: string[];\n idle?: number;\n timeout?: number;\n overrides?: waitoverride[];\n}\n\n/** Reviewed url pattern with a match mode plus required query and fragment parts. */\nexport interface urlpattern {\n mode: \"exact\" | \"prefix\" | \"host\" | \"pattern\";\n url: string;\n query?: Record<string, string>;\n fragment?: string;\n}\n\n/** One redirect hop of a redirect chain with its url, status and timestamp. */\nexport interface redirecthop {\n url: string;\n status: number;\n at: number;\n}\n\n/** One observed redirect chain with hops, statuses and timing. */\nexport interface redirectchain {\n hops: redirecthop[];\n startedat: number;\n endedat: number;\n}\n\n/** One navigation trail entry with url, title, step ref and timestamp. */\nexport interface trailentry {\n url: string;\n title: string;\n stepid?: string;\n at: number;\n}\n\n/** Reviewed per domain navigation rate limit with a window and a user configured ceiling. */\nexport interface ratelimit {\n domain: string;\n window: number;\n ceiling: number;\n}\n\n/** Live navigation state of a tab: load phase, final url and redirect chain. */\nexport interface navstate {\n phase: \"idle\" | \"loading\" | \"interactive\" | \"complete\";\n finalurl?: string;\n redirects?: redirectchain;\n}\n\n/** One stored wait profile applied per origin with user configured values. */\nexport interface waitprofilerecord {\n origin: string;\n profile: waitprofile;\n at: number;\n}\n\n/** One stored navigation record with the redirect chain and final url of one navigation step. */\nexport interface navrecord {\n stepid: string;\n sessionid?: string;\n origin: string;\n finalurl: string;\n chain: redirectchain;\n at: number;\n}\n\n/** One recorded navigation intent detected from a plan, kept for audit review. */\nexport interface navintentrecord {\n id: string;\n intent: string;\n origin: string;\n sessionid?: string;\n stepid?: string;\n at: number;\n}\n\n/** One rate limit window state per domain with the reviewed limit and the hit count. */\nexport interface ratelimitstate {\n domain: string;\n limit: ratelimit;\n openedat: number;\n count: number;\n}\n\n/** One curated link of a batch open list with its safety verdict and review state. */\nexport interface curatedlink {\n url: string;\n verdict: \"safe\" | \"unsafe\" | \"unknown\";\n reasons: string[];\n}\n\n/** One curated link list stored with its review state before batch opening. */\nexport interface curatedlist {\n id: string;\n links: curatedlink[];\n reviewedat?: number;\n at: number;\n}\n\n/** Reviewed basic auth credentials for one origin, stored only after explicit review. */\nexport interface authrecord {\n origin: string;\n username: string;\n password: string;\n reviewedat: number;\n}\n\n/** One url safety verdict produced by a checksafe verification. */\nexport interface safetyverdict {\n url: string;\n safe: boolean;\n reasons: string[];\n at: number;\n}\n\n/** One task artifact routed into the artifact store by a printpdf step. */\nexport interface artifactrecord {\n id: string;\n kind: string;\n name: string;\n stepid: string;\n at: number;\n}\n\n/** Navigation control state: paused navigation while a consent prompt is open. */\nexport interface navcontrol {\n pausedat?: number;\n reason?: string;\n updatedat: number;\n}\n\n/** One recently closed tab remembered so a reopentab step can restore it. */\nexport interface recenttab {\n url: string;\n tabid: number;\n closedat: number;\n}\n\n/** Queued navigation targets of prefetch and batch open steps, shown in the popup badge. */\nexport interface navqueues {\n prefetch: number;\n batchopen: number;\n updatedat: number;\n}\n\n/** Reviewed tab query with url, title, id and pattern matchers resolved against the live tab set. */\nexport interface tabquery {\n url?: string;\n title?: string;\n id?: number;\n pattern?: string;\n}\n\n/** Reviewed tab group definition with name, color, member tabs and collapse state. */\nexport interface tabgroupspec {\n name: string;\n color: string;\n tabids: number[];\n collapsed: boolean;\n}\n\n/** One stored tab group definition with its color choice and member tabs. */\nexport interface tabgrouprecord {\n groupid: string;\n name: string;\n color: string;\n tabids: number[];\n collapsed: boolean;\n savedat: number;\n}\n\n/** Window bounds of one window state or saved layout. */\nexport interface windowbounds {\n left: number;\n top: number;\n width: number;\n height: number;\n}\n\n/** Live or saved window state with bounds, maximize state and profile kind. */\nexport interface windowstate {\n bounds: windowbounds;\n maximized: boolean;\n profile: \"normal\" | \"incognito\" | \"scratch\";\n}\n\n/** One tab position inside a saved layout, carrying its window and pin state. */\nexport interface layouttab {\n url: string;\n title: string;\n pinned: boolean;\n index: number;\n windowid: number;\n}\n\n/** One saved tab layout with name, tabs, groups, positions and window bounds. */\nexport interface tablayout {\n name: string;\n tabs: layouttab[];\n groups: tabgroupspec[];\n windows: Array<{ windowid: number; state: windowstate }>;\n savedat: number;\n}\n\n/** Per tab task metadata with task refs, provenance and free text labels. */\nexport interface tabmeta {\n tabid: number;\n taskrefs: string[];\n provenance: string;\n labels: string[];\n at: number;\n}\n\n/** One per tab task status badge set by a badgetab step or refreshed from live progress. */\nexport interface tabbadge {\n tabid: number;\n taskid: string;\n label: string;\n setat: number;\n}\n\n/** One tab report entry carrying audio state and metadata per tab. */\nexport interface tabreportentry {\n tabid: number;\n url: string;\n title: string;\n index: number;\n windowid: number;\n active: boolean;\n pinned: boolean;\n audible: boolean;\n muted: boolean;\n discarded: boolean;\n meta?: tabmeta;\n}\n\n/** Tab report payload with matched tabs, groups and badges. */\nexport interface tabreport {\n matches: tabreportentry[];\n groups: tabgroupspec[];\n badges: tabbadge[];\n}\n\n/** One session snapshot of tabs and windows captured for later restore. */\nexport interface sessionsnapshot {\n id: string;\n sessionid?: string;\n layout: tablayout;\n capturedat: number;\n}\n\n/** One closed tab history entry kept for restoretab and reopenrun. */\nexport interface closedtab {\n url: string;\n title: string;\n tabid: number;\n windowid: number;\n closedat: number;\n}\n\n/** One tab event observed inside a reviewed watchtab registration. */\nexport interface tabwatchevent {\n watchid: string;\n event: \"title\" | \"activated\" | \"closed\";\n tabid: number;\n detail?: string;\n at: number;\n}\n\n/** Pinned control tab state carrying the live task feed. */\nexport interface controltabstate {\n tabid: number;\n enabled: boolean;\n updatedat: number;\n}\n", "import { actionrisk, parseoptions, validatestep } from \"./policy.js\";\nimport { protocolversion, type agentplan, type bannerreport, type clickablemap, type focusevent, type keyholdstate, type mutationevent, type navstate, type observation, type pagesignals, type planproposal, type proposalrequest, type resolvedtarget, type safetyverdict, type selectorcandidate, type snapshotdiff, type stepoutcome, type tablayout, type tabreport, type toolstep, type trailentry } from \"./types.js\";\n\nfunction record(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Protocol message must be an object.\");\n return value as Record<string, unknown>;\n}\n\nfunction text(value: unknown, field: string): string {\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`${field} must be a non-empty string.`);\n return value.trim();\n}\n\n/**\n * Reviewed options grammar shared by every step kind.\n *\n * A step may carry a JSON `options` object with the following reviewed fields:\n * - `targetref`: element addressing without a css selector, with `mode` one of `selector`, `text`, `aria`, `name`, `xpath`, `index` or `point`; the text mode carries `text`, the aria mode carries `role` plus `name`, the name mode carries `name`, the xpath mode carries `xpath`, the index mode carries a one based clickable map `index`, and the point mode carries viewport `x` and `y` coordinates.\n * - `pointpath`: pointer travel between two points, with `start` and `end` points, optional `waypoints` and a `duration` in milliseconds.\n * - `speedprofile`: pointer speed shape with `easing` (`linear` or `easeinout`), a `peak` velocity in pixels per second and a `jitter` window in milliseconds.\n * - `framepath`: ordered frame indexes routing a step inside same origin iframes.\n * - `shadow`: ordered host selectors addressing a target across open shadow roots.\n * - `retryrule`: retry bounds with `attempts`, a `settle` window in milliseconds and a movement `tolerance` in pixels; attempts carry no code ceiling.\n * - `dialogpolicy`: dialog answers with an `accept` flag and a reviewed prompt `answer` string.\n * - wrapper steps (`retryaction`, `enterframe`) reference an inner step by `stepid` or inline with `kind`, `target`, `value` and an `options` object.\n * - control kinds add reviewed `delay`, `values`, `results`, `timeout`, `holdid` and `modifiers` fields.\n * - watch kinds (`watchmutate`, `watchbanner`, `watchfocus`) carry a reviewed `lifetime` window in milliseconds, optional selector `scopes`, optional event kind filters `events` and an optional `poll` interval; the lifetime window carries no code ceiling.\n * - `waitquiet` carries a reviewed `quietrule` with a positive `idle` threshold in milliseconds, an optional `poll` interval and an optional `timeout`; every value carries no code ceiling.\n * - `diffsnapshots` carries exactly two reviewed observation `versions` to compare.\n * - navigation kinds carry the navigation parameter grammar: `navtarget` with a `url`, a `container` (`current`, `tab`, `window` or `private`), a `position` (`adjacent` or `end`) and a `private` flag; `waitprofile` with non-empty load `signals`, optional `idle` and `timeout` thresholds and per origin `overrides`; and `urlpattern` with a `mode` (`exact`, `prefix`, `host` or `pattern`), a `url`, optional `query` parameter expectations and an optional `fragment`.\n * - `waiturl` and `spawait` carry a reviewed `urlpattern`, `timeout` and `poll`; `spanav` carries an optional `routepattern`, `followlink` an optional `fragment` flag, `rewritequery` reviewed `set` and `remove` query edits, `navlist`/`prefetch`/`batchopen` reviewed `urls` lists, `preconnect` reviewed `origins`, `navrate` a reviewed `ratelimit` with `domain`, `window` and `ceiling` (never capped in code), and `deeplink` a reviewed `app` pattern with `params`.\n * - observation kinds attach structured evidence to step details: a11y trees, reader articles, list patterns, table shapes, pagination estimates, watch event records, quiet probe samples, snapshot diffs and derived selector candidates with stability scores.\n * - navigation steps attach structured evidence to step details: load phases and ready states, final urls after redirects, redirect chains with statuses and timing, http error, offline and certificate interstitial states, safety verdicts and navlist entry completions.\n * - the tabs and windows command family adds its parameter grammar: `tabquery` with url, title, id and pattern matchers (at least one matcher required, patterns use `*` and `**` wildcards); `group` with a `name`, a Chromium tab group `color`, member `tabids` and a `collapsed` flag; `layout` names for `savelayout` and `restorelayout`; reviewed `pinned`, `muted`, `index`, `windowid`, `direction`, `step`, `bounds`, `label`, `labels`, `taskrefs`, `provenance` and `run` fields; `tabcreate` gains reviewed `background` and `window` options and `windowcreate` gains reviewed `left`, `top`, `width`, `height` and `state` options; `closepattern` requires the explicit `reviewed` flag before any tab closes.\n * - tab command steps attach structured evidence to step details: tab reports with matched tabs carrying audio state and metadata, group registries, badge states, layout snapshots, clone warnings, discard candidates and watchtab event records.\n *\n * Ambiguous text, aria or name resolutions are refused at execution time with the candidate list so the user can choose.\n */\n\n/** Validates agent output before it becomes a locally reviewable plan. Plans may carry any number of steps. */\nexport function parseproposal(value: unknown, origin: string): planproposal {\n const root = record(value);\n if (root.version !== protocolversion) throw new Error(\"Unsupported protocol version.\");\n const planinput = record(root.plan);\n const stepsinput = planinput.steps;\n if (!Array.isArray(stepsinput) || stepsinput.length === 0) throw new Error(\"A plan needs at least one step.\");\n const steps: toolstep[] = stepsinput.map((input, index) => {\n const candidate = record(input);\n const kind = text(candidate.kind, `step ${index + 1} kind`) as toolstep[\"kind\"];\n const step: toolstep = {\n id: typeof candidate.id === \"string\" ? candidate.id : crypto.randomUUID(),\n kind,\n summary: text(candidate.summary, `step ${index + 1} summary`),\n risk: actionrisk(kind),\n ...(typeof candidate.target === \"string\" ? { target: candidate.target } : {}),\n ...(typeof candidate.value === \"string\" ? { value: candidate.value } : {}),\n ...(typeof candidate.options === \"string\" ? { options: candidate.options } : {}),\n };\n const evaluation = validatestep(step, origin);\n if (!evaluation.allowed) throw new Error(evaluation.reason);\n return step;\n });\n for (const step of steps) {\n if (step.kind !== \"retryaction\" && step.kind !== \"enterframe\") continue;\n const options = parseoptions(step);\n if (typeof options.stepid === \"string\" && !steps.some(candidate => candidate.id === options.stepid)) throw new Error(\"A retry or frame wrapper references an unknown step id.\");\n }\n const createdat = Date.now();\n const expiresat = typeof planinput.expiresat === \"number\" ? planinput.expiresat : createdat + 10 * 60 * 1000;\n const plan: agentplan = {\n id: typeof planinput.id === \"string\" ? planinput.id : crypto.randomUUID(),\n objective: text(planinput.objective, \"objective\"),\n origin,\n steps,\n createdat,\n expiresat,\n state: \"pending\",\n };\n if (plan.expiresat <= createdat) throw new Error(\"Plan expiry must be in the future.\");\n return { version: protocolversion, plan };\n}\n\n/** Shapes the only data that may be sent to a user-configured agent endpoint. */\nexport function requestbody(input: proposalrequest): string {\n return JSON.stringify({ version: protocolversion, objective: input.objective, session: input.session, observation: input.observation, capabilities: input.capabilities });\n}\n\n/** Wraps one executed step outcome in the versioned response envelope for callers, attaching the matched element summary for review. */\nexport function outcomeresponse(input: { outcome: stepoutcome; plan: agentplan; resolvedtarget?: resolvedtarget }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, outcome: input.outcome, ...(input.resolvedtarget ? { resolvedtarget: input.resolvedtarget } : {}) });\n}\n\n/** Wraps a clickable map payload with numbered entries in the versioned response envelope. */\nexport function mapresponse(input: { map: clickablemap; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, map: input.map });\n}\n\n/** Reports the keys currently held on one tab for the live context envelope, refreshed per step. */\nexport function heldkeysreport(input: { tabid: number; holds: keyholdstate[] }): { version: typeof protocolversion; tabid: number; heldkeys: keyholdstate[] } {\n return { version: protocolversion, tabid: input.tabid, heldkeys: input.holds };\n}\n\n/** Wraps one observation capture with its a11y, reader, listpattern, tableshape and diff sections in the versioned response envelope. */\nexport function observationresponse(input: { observation: observation; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, observation: input.observation });\n}\n\n/** Wraps mutation, focus and banner event records with their timestamps and target paths in the versioned response envelope. */\nexport function eventresponse(input: { events: Array<mutationevent | focusevent | bannerreport>; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, events: input.events });\n}\n\n/** Wraps one snapshot diff with its added, removed and changed nodes and its two observation versions in the versioned response envelope. */\nexport function diffresponse(input: { diff: snapshotdiff; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, diff: input.diff });\n}\n\n/** Reports the detected page language, template class, scroll lock and banner state in the live context envelope. */\nexport function signalsreport(input: { signals?: pagesignals }): { version: typeof protocolversion; language?: string; template?: string; scrolllocked?: boolean; banner?: string } {\n const signals = input.signals;\n return {\n version: protocolversion,\n ...(signals && signals.language !== undefined ? { language: signals.language } : {}),\n ...(signals && signals.template !== undefined ? { template: signals.template } : {}),\n ...(signals && signals.scrolllocked !== undefined ? { scrolllocked: signals.scrolllocked } : {}),\n ...(signals && signals.banner !== undefined ? { banner: signals.banner } : {}),\n };\n}\n\n/** Wraps derived selector candidates with their stability scores in the versioned response envelope. */\nexport function selectorresponse(input: { candidates: selectorcandidate[]; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, candidates: input.candidates });\n}\n\n/** Wraps the live navigation state with its load phase, final url and redirect chain in the versioned response envelope. */\nexport function navstateresponse(input: { navstate: navstate; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, navstate: input.navstate });\n}\n\n/** Carries the navigation trail of a session with its visited urls, titles and step refs in the session context envelope. */\nexport function trailreport(input: { sessionid?: string; trail: trailentry[] }): { version: typeof protocolversion; sessionid?: string; trail: trailentry[] } {\n return { version: protocolversion, ...(input.sessionid ? { sessionid: input.sessionid } : {}), trail: input.trail };\n}\n\n/** Wraps url safety verdicts with their reasons in the versioned response envelope for external link review. */\nexport function safetyresponse(input: { verdicts: safetyverdict[]; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, verdicts: input.verdicts });\n}\n\n/** Wraps one tab report with its matched tabs, groups and badges in the versioned response envelope. */\nexport function tabreportresponse(input: { report: tabreport; plan: agentplan }): string {\n return JSON.stringify({ version: protocolversion, planid: input.plan.id, planstate: input.plan.state, report: input.report });\n}\n\n/** Carries the saved tab layouts with their window bounds and group states in the session context envelope. */\nexport function layoutreport(input: { layouts: tablayout[] }): { version: typeof protocolversion; layouts: tablayout[] } {\n return { version: protocolversion, layouts: input.layouts };\n}\n", "import type { capabilityreport, toolstep } from \"../types.js\";\n\n/**\n * Browser-level command surface for reviewed steps.\n * Every correlated rule for tab, window, zoom, snapshot and download actions plus capability negotiation lives in this file.\n */\n\nexport type browserresult = { ok: boolean; summary: string; details?: Record<string, unknown> };\n\nconst browserkinds: ReadonlySet<string> = new Set([\"tablist\", \"tabcreate\", \"tabactivate\", \"tabclose\", \"tabreload\", \"tabsnapshot\", \"windowlist\", \"windowcreate\", \"windowclose\", \"zoomset\", \"windowresize\", \"downloadfile\"]);\n\n/** True when the kind executes against browser-level surfaces instead of the page. */\nexport function isbrowserkind(kind: string): boolean {\n return browserkinds.has(kind);\n}\n\n/** Builds the live capability report from the optional permissions the user granted. */\nexport async function readcapabilities(): Promise<capabilityreport> {\n const [tabs, downloads, clipboardread, clipboardwrite] = await Promise.all([\n chrome.permissions.contains({ permissions: [\"tabs\"] }),\n chrome.permissions.contains({ permissions: [\"downloads\"] }),\n chrome.permissions.contains({ permissions: [\"clipboardRead\"] }),\n chrome.permissions.contains({ permissions: [\"clipboardWrite\"] }),\n ]);\n return { tabs, downloads, clipboardread, clipboardwrite, reportedat: Date.now() };\n}\n\nfunction stepoptions(step: toolstep): Record<string, unknown> {\n if (!step.options) return {};\n try {\n const parsed = JSON.parse(step.options);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};\n } catch { return {}; }\n}\n\nfunction tabid(step: toolstep): number {\n return Number.parseInt(step.value ?? \"\", 10);\n}\n\n/** Executes one reviewed browser-level action kind against the live browser. */\nexport async function runbrowseraction(step: toolstep, sessiontabid: number, windowid: number): Promise<browserresult> {\n const options = stepoptions(step);\n switch (step.kind) {\n case \"tablist\": {\n const tabs = await chrome.tabs.query({});\n return { ok: true, summary: `Listed ${tabs.length} open tab${tabs.length === 1 ? \"\" : \"s\"}.`, details: { tabs: tabs.map(tab => ({ id: tab.id ?? 0, index: tab.index, title: tab.title ?? \"\", url: tab.url ?? \"\", active: tab.active, pinned: tab.pinned, audible: tab.audible ?? false })) } };\n }\n case \"tabcreate\": {\n const targetwindow = typeof options.window === \"number\" && Number.isFinite(options.window) ? options.window : undefined;\n const created = await chrome.tabs.create({ url: step.value, active: options.active !== false && options.background !== true, pinned: options.pinned === true, ...(targetwindow !== undefined ? { windowId: targetwindow } : {}) });\n return { ok: true, summary: `Opened a new tab for ${step.value}${options.background === true ? \" in the background without activating it\" : \"\"}.`, details: { tabid: created?.id ?? 0, ...(targetwindow !== undefined ? { windowid: targetwindow } : {}), ...(options.background === true ? { background: true } : {}) } };\n }\n case \"tabactivate\": {\n await chrome.tabs.update(tabid(step), { active: true });\n return { ok: true, summary: `Activated tab ${tabid(step)}.` };\n }\n case \"tabclose\": {\n await chrome.tabs.remove(tabid(step));\n return { ok: true, summary: `Closed tab ${tabid(step)}.` };\n }\n case \"tabreload\": {\n await chrome.tabs.reload(tabid(step), { bypassCache: options.bypasscache === true });\n return { ok: true, summary: `Reloaded tab ${tabid(step)}.` };\n }\n case \"tabsnapshot\": {\n const shot = await chrome.tabs.captureVisibleTab(windowid, { format: \"png\" });\n return { ok: true, summary: \"Captured the visible area of the active tab.\", details: { shot } };\n }\n case \"windowlist\": {\n const windows = await chrome.windows.getAll();\n return { ok: true, summary: `Listed ${windows.length} open window${windows.length === 1 ? \"\" : \"s\"}.`, details: { windows: windows.map(item => ({ id: item.id ?? 0, type: item.type, state: item.state ?? \"\", focused: item.focused })) } };\n }\n case \"windowcreate\": {\n const bounds = [\"left\", \"top\", \"width\", \"height\"].filter(field => typeof options[field] === \"number\");\n const geometry = Object.fromEntries(bounds.map(field => [field, options[field]])) as Record<string, number>;\n const state = typeof options.state === \"string\" && [\"normal\", \"maximized\", \"minimized\", \"fullscreen\"].includes(options.state) ? options.state : undefined;\n const created = await chrome.windows.create({ url: step.value ?? \"about:blank\", ...(Object.keys(geometry).length > 0 ? geometry : {}), ...(state !== undefined ? { state: state as chrome.windows.WindowState } : {}) });\n return { ok: true, summary: `Opened a new window for ${step.value}.`, details: { windowid: created?.id ?? 0, ...(Object.keys(geometry).length > 0 ? { bounds: geometry } : {}), ...(state !== undefined ? { state } : {}) } };\n }\n case \"windowclose\": {\n await chrome.windows.remove(tabid(step));\n return { ok: true, summary: `Closed window ${tabid(step)}.` };\n }\n case \"zoomset\": {\n const zoom = Number(step.value);\n await chrome.tabs.setZoom(sessiontabid, zoom);\n return { ok: true, summary: `Set the tab zoom to ${zoom}.` };\n }\n case \"windowresize\": {\n await chrome.windows.update(tabid(step), { width: options.width as number, height: options.height as number });\n return { ok: true, summary: `Resized window ${tabid(step)}.` };\n }\n case \"downloadfile\": {\n const downloadid = await chrome.downloads.download({ url: step.value ?? \"\" });\n return { ok: true, summary: `Started the download of ${step.value}.`, details: { downloadid } };\n }\n default: return { ok: false, summary: \"Unsupported browser action.\" };\n }\n}\n", "import type { tabgrouprecord, tablayout, tabquery, tabwatchevent, toolstep } from \"../types.js\";\nimport { parseoptions } from \"../policy.js\";\nimport { assigntasktab, tasktabs } from \"../progress.js\";\nimport type { planprogress } from \"../types.js\";\n\n/**\n * Tabs and windows command logics for reviewed steps.\n * Every correlated rule for tab queries, clone detection, group membership, layouts, snapshots, watchers, badges, discard candidates, switcher order, zoom steps and the task tab budget lives in this file.\n */\n\n/** One serializable live tab shape resolved against the browser tab set. */\nexport interface tabshape {\n tabid: number;\n url: string;\n title: string;\n index: number;\n windowid: number;\n active: boolean;\n pinned: boolean;\n audible: boolean;\n muted: boolean;\n discarded: boolean;\n}\n\n/** One serializable live window shape with bounds, state and profile kind. */\nexport interface windowshape {\n windowid: number;\n left: number;\n top: number;\n width: number;\n height: number;\n state: \"normal\" | \"maximized\" | \"minimized\" | \"fullscreen\";\n incognito: boolean;\n focused: boolean;\n}\n\n/** Reads the reviewed tabquery of a tabs and windows command step; null when the step reviews none. */\nexport function parsetabquery(step: toolstep): tabquery | null {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const value = options.tabquery;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const query = value as Record<string, unknown>;\n return {\n ...(typeof query.url === \"string\" && query.url ? { url: query.url } : {}),\n ...(typeof query.title === \"string\" && query.title ? { title: query.title } : {}),\n ...(typeof query.id === \"number\" && Number.isInteger(query.id) && query.id >= 0 ? { id: query.id } : {}),\n ...(typeof query.pattern === \"string\" && query.pattern ? { pattern: query.pattern } : {}),\n };\n}\n\n/** Matches one reviewed wildcard pattern against a url; `*` spans one path segment and `**` spans any part. */\nexport function tabpatternmatches(pattern: string, url: string): boolean {\n const source = pattern.split(\"**\").map(part => part.split(\"*\").map(piece => piece.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")).join(\"[^/]*\")).join(\".*\");\n return new RegExp(`^${source}$`).test(url);\n}\n\n/** Resolves one reviewed tabquery against the live tab set: every matcher that exists must hold. */\nexport function querymatches(query: tabquery, tabs: tabshape[]): tabshape[] {\n return tabs.filter(tab => {\n if (query.id !== undefined && tab.tabid !== query.id) return false;\n if (query.url !== undefined && tab.url !== query.url) return false;\n if (query.title !== undefined && !tab.title.toLowerCase().includes(query.title.toLowerCase())) return false;\n if (query.pattern !== undefined && !tabpatternmatches(query.pattern, tab.url)) return false;\n return true;\n });\n}\n\n/** Normalizes one url for clone comparison by dropping the fragment and trailing slashes. */\nexport function normalizedtaburl(url: string): string {\n let normalized = url;\n const hash = normalized.indexOf(\"#\");\n if (hash >= 0) normalized = normalized.slice(0, hash);\n while (normalized.length > 1 && normalized.endsWith(\"/\")) normalized = normalized.slice(0, -1);\n return normalized;\n}\n\n/** One clone warning: a normalized url shared by more than one open tab. */\nexport interface clonewarning {\n url: string;\n tabids: number[];\n}\n\n/** Detects duplicate tabs by normalized url comparison and returns every url held by more than one tab. */\nexport function clonetabs(tabs: tabshape[]): clonewarning[] {\n const groups = new Map<string, number[]>();\n for (const tab of tabs) {\n if (!tab.url) continue;\n const key = normalizedtaburl(tab.url);\n groups.set(key, [...(groups.get(key) ?? []), tab.tabid]);\n }\n return [...groups.entries()].filter(([, tabids]) => tabids.length > 1).map(([url, tabids]) => ({ url, tabids }));\n}\n\n/** Searches across open tabs by title and url, case insensitive, returning matches in live order. */\nexport function searchtabmatches(tabs: tabshape[], text: string): tabshape[] {\n const needle = text.trim().toLowerCase();\n if (!needle) return [];\n return tabs.filter(tab => tab.title.toLowerCase().includes(needle) || tab.url.toLowerCase().includes(needle));\n}\n\n/** Lists the tabs that are playing audio: audible or muted but still playing. */\nexport function audiotabs(tabs: tabshape[]): tabshape[] {\n return tabs.filter(tab => tab.audible || (tab.muted && tab.audible));\n}\n\n/** Returns the inactive, unpinned and not yet discarded tabs a discardtab step may release. */\nexport function discardcandidates(tabs: tabshape[]): tabshape[] {\n return tabs.filter(tab => !tab.active && !tab.pinned && !tab.discarded && tab.url.length > 0);\n}\n\n/** Restores discarded tabs on demand without losing their urls; every discarded tab keeps its url for reload. */\nexport function restorediscarded(tabs: tabshape[]): Array<{ tabid: number; url: string }> {\n return tabs.filter(tab => tab.discarded && tab.url.length > 0).map(tab => ({ tabid: tab.tabid, url: tab.url }));\n}\n\n/** Captures one tab layout with name, tabs, groups, positions and window bounds from the live browser state. */\nexport function buildlayout(name: string, tabs: tabshape[], windows: windowshape[], groups: tabgrouprecord[], scratchwindowids: number[], at: number): tablayout {\n return {\n name,\n tabs: tabs.map(tab => ({ url: tab.url, title: tab.title, pinned: tab.pinned, index: tab.index, windowid: tab.windowid })),\n groups: groups.map(group => ({ name: group.name, color: group.color, tabids: group.tabids.filter(tabid => tabs.some(tab => tab.tabid === tabid)), collapsed: group.collapsed })),\n windows: windows.map(item => ({ windowid: item.windowid, state: { bounds: { left: item.left, top: item.top, width: item.width, height: item.height }, maximized: item.state === \"maximized\", profile: item.incognito ? \"incognito\" : scratchwindowids.includes(item.windowid) ? \"scratch\" : \"normal\" } })),\n savedat: at,\n };\n}\n\n/** Plans the restore of one saved layout: only urls that are not already open come back, in layout order. */\nexport function layoutrestoreplan(layout: tablayout, openurls: string[]): string[] {\n const open = new Set(openurls.map(url => normalizedtaburl(url)));\n return layout.tabs.map(tab => tab.url).filter(url => url.length > 0 && !open.has(normalizedtaburl(url)));\n}\n\n/** Keeps tabgroup membership through moves: member ids survive, their order follows the live tab order and closed members drop out. */\nexport function regroupaftermoves(groups: tabgrouprecord[], tabs: tabshape[], at: number): tabgrouprecord[] {\n const order = new Map(tabs.map(tab => [tab.tabid, tab.index]));\n return groups.map(group => {\n const members = group.tabids.filter(tabid => order.has(tabid));\n if (members.length === 0) return group;\n const ordered = [...members].sort((left, right) => (order.get(left) ?? 0) - (order.get(right) ?? 0));\n return ordered.length === group.tabids.length && ordered.every((tabid, index) => tabid === group.tabids[index]) ? group : { ...group, tabids: ordered, savedat: at };\n });\n}\n\n/** Renames one stored tab group while keeping its color choice, member tabs and collapse state. */\nexport function renamegroup(groups: tabgrouprecord[], name: string, newname: string, at: number): tabgrouprecord[] {\n return groups.map(group => group.name === name ? { ...group, name: newname, savedat: at } : group);\n}\n\n/** Counts the task tabs that live inside one window so the close gate can demand review. */\nexport function tasktabsinwindow(tabs: tabshape[], windowid: number, tasktabids: number[]): number {\n const tasks = new Set(tasktabids);\n return tabs.filter(tab => tab.windowid === windowid && tasks.has(tab.tabid)).length;\n}\n\n/** Selects the tabs a reviewed closepattern may close; the session tab itself is always refused protection. */\nexport function closeselection(query: tabquery, tabs: tabshape[], sessiontabid: number): { targets: tabshape[]; refused: tabshape[] } {\n const matches = querymatches(query, tabs);\n return {\n targets: matches.filter(tab => tab.tabid !== sessiontabid),\n refused: matches.filter(tab => tab.tabid === sessiontabid),\n };\n}\n\n/** Applies one reviewed zoom step with no code ceiling; a step never crosses zero, so it keeps the current zoom instead. */\nexport function zoomstep(current: number, direction: \"in\" | \"out\", step: number): number {\n const next = direction === \"in\" ? current + step : current - step;\n return next > 0 ? Number(next.toFixed(4)) : current;\n}\n\n/** Resolves the neighbor tab index a switchtab step activates, wrapping at both ends of the window. */\nexport function switchtarget(tabs: tabshape[], direction: \"next\" | \"previous\", currentindex: number): number | undefined {\n if (tabs.length === 0) return undefined;\n const offset = direction === \"next\" ? 1 : -1;\n return (currentindex + offset + tabs.length) % tabs.length;\n}\n\n/** Orders the quick switcher list by recency with filter keys; unseen tabs follow in live index order. */\nexport function switcherlist(tabs: tabshape[], recency: Array<{ tabid: number; at: number }>, filter: string): tabshape[] {\n const needle = filter.trim().toLowerCase();\n const matches = needle ? tabs.filter(tab => tab.title.toLowerCase().includes(needle) || tab.url.toLowerCase().includes(needle)) : [...tabs];\n const lastrun = new Map(recency.map(entry => [entry.tabid, entry.at]));\n return [...matches].sort((left, right) => {\n const leftat = lastrun.get(left.tabid) ?? -1;\n const rightat = lastrun.get(right.tabid) ?? -1;\n if (leftat !== rightat) return rightat - leftat;\n return left.index - right.index;\n });\n}\n\n/** Dispatches the tab events of one watchtab registration into the step result, honoring the reviewed event filters. */\nexport function watchtabdispatch(events: tabwatchevent[], watchid: string, filters: string[]): tabwatchevent[] {\n const allowed = filters.length > 0 ? new Set(filters) : undefined;\n return events.filter(event => event.watchid === watchid && (allowed === undefined || allowed.has(event.event)));\n}\n\n/** Computes the per task badge from the live progress state of the task. */\nexport function badgefromprogress(completed: number, total: number): { label: string; done: boolean } {\n if (total <= 0) return { label: \"idle\", done: false };\n if (completed >= total) return { label: \"done\", done: true };\n return { label: `${completed}/${total}`, done: false };\n}\n\n/** Grades the concurrent task tab budget: a user configured ceiling refuses, an absent ceiling never refuses. */\nexport function tasktabgauge(used: number, ceiling: number | undefined): { used: number; ceiling: number | undefined; over: boolean } {\n return { used, ceiling, over: ceiling !== undefined && used > ceiling };\n}\n\n/** True when a window profile inherits the session origin grants; incognito windows stay separated. */\nexport function windowprofilegrants(profile: \"normal\" | \"incognito\" | \"scratch\"): boolean {\n return profile !== \"incognito\";\n}\n\n/** Assigns every task tab of the plan progress, used when tabmeta routing records a tab for the plan steps. */\nexport function assigntasktabs(progress: planprogress | undefined, planid: string, tabids: number[], now: number): planprogress {\n let next = progress;\n for (const tabid of tabids) next = assigntasktab(next, planid, tabid, now);\n return next ?? { planid, completedsteps: [], tasktabs: [], updatedat: now };\n}\n\n/** Returns the task tabs tracked by one plan progress, used for window close review and badge refresh. */\nexport function trackedtasktabs(progress: planprogress | undefined, planid: string): number[] {\n return tasktabs(progress, planid);\n}\n", "import type { dialogpolicy, toolstep } from \"../types.js\";\nimport { parseoptions } from \"../policy.js\";\n\n/**\n * Dialog policy logics for reviewed steps.\n * Every correlated rule for policy parsing, dialog answers, main world handler installation and observed dialog harvesting lives in this file.\n * The isolated world cannot override window.confirm, window.alert or window.prompt, so the background installs these wrappers through the scripting api in the main world.\n */\n\n/** One dialog observed by the main world handler, recorded on the shared document. */\nexport interface observeddialog {\n dialog: string;\n text: string;\n result: string | boolean | null;\n at: number;\n}\n\n/** Parses the reviewed dialog policy from step options; prompts need a reviewed answer. */\nexport function parsedialogpolicy(step: toolstep): dialogpolicy | null {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { return null; }\n const accept = options.accept;\n const answer = options.answer;\n if (typeof accept !== \"boolean\" && typeof answer !== \"string\") return null;\n return { accept: accept === true, ...(typeof answer === \"string\" && answer.trim() ? { answer } : {}) };\n}\n\n/** Decides how the reviewed policy answers one dialog kind; a prompt without a reviewed answer is dismissed. */\nexport function dialoganswer(policy: dialogpolicy, dialog: \"confirm\" | \"alert\" | \"prompt\"): { accept: boolean; answer?: string } {\n if (dialog === \"prompt\") {\n if (policy.answer === undefined || policy.answer === \"\") return { accept: false };\n return { accept: policy.accept !== false, ...(policy.answer !== undefined ? { answer: policy.answer } : {}) };\n }\n return { accept: policy.accept };\n}\n\n/** Reads and clears the dialog log the main world handler recorded on the shared document. */\nexport function harvestdialoglog(root: Document): observeddialog[] {\n const raw = root.documentElement.dataset.devthinkdialoglog;\n if (!raw) return [];\n delete root.documentElement.dataset.devthinkdialoglog;\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((item): item is observeddialog => Boolean(item) && typeof item === \"object\" && typeof (item as Record<string, unknown>).dialog === \"string\");\n } catch { return []; }\n}\n\n/** Installs confirm, alert and prompt wrappers in the page main world answering per the reviewed policy; runs through chrome.scripting with world main. */\nexport function installdialoghandler(accept: boolean, answer: string, persistent: boolean): void {\n const world = globalThis as typeof globalThis & { devthinkoriginaldialogs?: { confirm: (text?: string) => boolean; alert: (text?: string) => void; prompt: (text?: string, defaultvalue?: string) => string | null } };\n const originals = world.devthinkoriginaldialogs ?? { confirm: window.confirm.bind(window), alert: window.alert.bind(window), prompt: window.prompt.bind(window) };\n world.devthinkoriginaldialogs = originals;\n const decide = (dialog: string): { accept: boolean; answer: string | null } => {\n if (dialog === \"prompt\") return answer ? { accept: true, answer } : { accept: false, answer: null };\n return { accept, answer: null };\n };\n const record = (dialog: string, text: string, result: string | boolean | null): void => {\n try {\n const root = document.documentElement;\n const log = JSON.parse(root.dataset.devthinkdialoglog ?? \"[]\") as unknown[];\n log.push({ dialog, text, result, at: Date.now() });\n root.dataset.devthinkdialoglog = JSON.stringify(log);\n } catch { /* a locked down page refuses dataset writes; the handler still answers */ }\n };\n window.confirm = (text?: string): boolean => {\n const decision = decide(\"confirm\");\n record(\"confirm\", text ?? \"\", decision.accept);\n if (!persistent) window.confirm = originals.confirm;\n return decision.accept;\n };\n window.alert = (text?: string): void => {\n record(\"alert\", text ?? \"\", true);\n if (!persistent) window.alert = originals.alert;\n };\n window.prompt = (text?: string, defaultvalue?: string): string | null => {\n const decision = decide(\"prompt\");\n const outcome = decision.accept ? (decision.answer ?? defaultvalue ?? \"\") : null;\n record(\"prompt\", text ?? \"\", outcome);\n if (!persistent) window.prompt = originals.prompt;\n return outcome;\n };\n}\n", "import type { retryrule, toolstep } from \"../types.js\";\nimport { parseoptions } from \"../policy.js\";\nimport type { stepresult } from \"./pageactions.js\";\nimport { describeframes, queryscoped, queryshadowchain, resolvestep, targetsummary, walkframepath } from \"./pageresolve.js\";\nimport { dispatchclick, ensurevisible } from \"./pagepointer.js\";\n\n/**\n * Resolution driven interactions for reviewed steps.\n * Every correlated rule for text, aria and name clicks, shadow piercing, frame routing, wrapper step extraction and the retry loop lives in this file.\n */\n\n/** Reads the reviewed options of a step without throwing on malformed payloads. */\nfunction optionsof(step: toolstep): Record<string, unknown> {\n try { return parseoptions(step); } catch { return {}; }\n}\n\n/** Extracts the reviewed inner step of a retry or frame wrapper from its inline options. */\nexport function innerstep(step: toolstep): toolstep | null {\n const options = optionsof(step);\n const kind = options.kind;\n if (typeof kind !== \"string\" || !kind.trim()) return null;\n const inneroptions = options.options;\n return {\n id: `${step.id}inner`,\n kind: kind as toolstep[\"kind\"],\n summary: step.summary,\n risk: step.risk,\n ...(typeof options.target === \"string\" ? { target: options.target } : {}),\n ...(typeof options.value === \"string\" ? { value: options.value } : {}),\n ...(inneroptions && typeof inneroptions === \"object\" && !Array.isArray(inneroptions) ? { options: JSON.stringify(inneroptions) } : {}),\n };\n}\n\nfunction pointdistance(a: { x: number; y: number }, b: { x: number; y: number }): number {\n return Math.hypot(b.x - a.x, b.y - a.y);\n}\n\nfunction settle(delay: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, delay));\n}\n\nexport interface retryoutcomeplan {\n ok: boolean;\n attempts: number;\n movement: number;\n summary: string;\n}\n\n/** Runs the reviewed retry loop: each failed attempt waits the settle window, revalidates the target geometry and reruns only when the element moved beyond the tolerance. */\nexport async function runretries(rule: retryrule, probe: () => Promise<{ x: number; y: number } | null>, execute: (attempt: number) => Promise<{ ok: boolean; summary: string }>): Promise<retryoutcomeplan> {\n const attempts = Math.max(1, Number.isFinite(rule.attempts) ? Math.floor(rule.attempts) : 1);\n const tolerance = typeof rule.tolerance === \"number\" && Number.isFinite(rule.tolerance) ? rule.tolerance : 0;\n const settles = typeof rule.settle === \"number\" && Number.isFinite(rule.settle) ? rule.settle : 0;\n let previous = await probe();\n let movement = 0;\n let made = 0;\n let last = \"\";\n for (let attempt = 1; attempt <= attempts; attempt += 1) {\n made = attempt;\n const result = await execute(attempt);\n last = result.summary;\n if (result.ok) return { ok: true, attempts: made, movement, summary: `Retry interaction succeeded on attempt ${made} after ${movement.toFixed(1)} pixels of observed movement.` };\n if (attempt >= attempts) break;\n if (settles > 0) await settle(settles);\n const current = await probe();\n if (!current) { previous = null; continue; }\n if (previous) {\n const delta = pointdistance(previous, current);\n movement = Math.max(movement, delta);\n if (delta <= tolerance) return { ok: false, attempts: made, movement, summary: `The target stayed within the reviewed tolerance of ${tolerance} pixels; retry stopped after attempt ${made}. ${last}` };\n }\n previous = current;\n }\n return { ok: false, attempts: made, movement, summary: `Retry interaction failed after ${made} attempt${made === 1 ? \"\" : \"s\"} with ${movement.toFixed(1)} pixels of observed movement. ${last}` };\n}\n\n/** Dispatches one reviewed click on a resolved element and reports the target mode used. */\nfunction clickresolved(stepkind: string, resolution: ReturnType<typeof resolvestep>): stepresult {\n if (resolution.status === \"ambiguous\") return { ok: false, summary: `The reviewed ${resolution.mode} reference matched ${resolution.candidates.length} elements: ${resolution.candidates.join(\"; \")}.`, details: { mode: resolution.mode, candidates: resolution.candidates } };\n if (resolution.status !== \"resolved\") return { ok: false, summary: \"The reviewed target is no longer available.\" };\n ensurevisible(resolution.element);\n dispatchclick(resolution.element);\n return { ok: true, summary: `Clicked ${resolution.target.label || resolution.target.tag} resolved by ${stepkind} ${resolution.target.mode} mode.`, details: { mode: resolution.target.mode, resolvedtarget: resolution.target } };\n}\n\n/** Runs one resolution driven interaction: text, aria and name clicks, shadow piercing and frame routing. */\nexport function runinteractstep(step: toolstep, expectedorigin: string, dispatch: (inner: toolstep, origin: string, root?: Document) => stepresult | Promise<stepresult>): stepresult | Promise<stepresult> {\n if (step.kind === \"clicktext\" || step.kind === \"clickaria\" || step.kind === \"clickname\") {\n return clickresolved(step.kind, resolvestep(step, document));\n }\n if (step.kind === \"pierceshadow\") {\n const options = optionsof(step);\n const shadow = Array.isArray(options.shadow) ? options.shadow.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const element = shadow.length > 0 ? queryshadowchain(document, shadow) : queryscoped(document, step.target ?? \"\");\n if (!(element instanceof HTMLElement)) return { ok: false, summary: \"The reviewed shadow target is not available.\" };\n ensurevisible(element);\n dispatchclick(element);\n const summary = targetsummary(\"selector\", element);\n return { ok: true, summary: `Clicked ${summary.label || summary.tag} resolved through ${shadow.length > 0 ? \"the reviewed shadow path\" : \"open shadow roots\"}.`, details: { mode: \"selector\", resolvedtarget: summary } };\n }\n if (step.kind === \"enterframe\") {\n const options = optionsof(step);\n const path = Array.isArray(options.framepath) ? options.framepath.filter((item): item is number => typeof item === \"number\" && Number.isInteger(item) && item >= 0) : [];\n const walk = walkframepath(describeframes(document), path);\n if (!walk.ok) return { ok: false, summary: walk.reason };\n const framedocument = walk.document.live;\n if (!framedocument) return { ok: false, summary: \"The reviewed frame document is not available.\" };\n const inner = innerstep(step);\n if (!inner) return { ok: false, summary: \"The reviewed inner step is absent.\" };\n return dispatch(inner, expectedorigin, framedocument);\n }\n return { ok: false, summary: \"Unsupported interaction action.\" };\n}\n", "import type { keyholdstate, toolstep } from \"../types.js\";\nimport { parseoptions } from \"../policy.js\";\nimport type { stepresult } from \"./pageactions.js\";\nimport { clean } from \"./pageresolve.js\";\n\n/**\n * Field and control interactions for reviewed steps.\n * Every correlated rule for timed typing, value setting, key holds, search submission, multi selects, radio choices, sliders, dates, colors, details sections and the hold registry lives in this file.\n */\n\n/** Builds the per keystroke schedule of one reviewed typetime step. */\nexport function typetimeschedule(text: string, delay: number): Array<{ key: string; delay: number }> {\n return [...text].map((character, position) => ({ key: character, delay: position === 0 ? 0 : delay }));\n}\n\n/** Appends reviewed text to the current field value. */\nexport function appendvalue(current: string, addition: string): string {\n return current + addition;\n}\n\n/** Event order delivered after one reviewed value change. */\nexport function valueevents(): string[] {\n return [\"input\", \"change\"];\n}\n\n/** Splits reviewed multi select values into present and missing entries against the declared options. */\nexport function multichoices(values: string[], options: Array<{ value: string; label: string }>): { present: string[]; missing: string[] } {\n const present: string[] = [];\n const missing: string[] = [];\n for (const value of values) {\n const option = options.find(candidate => candidate.value === value || candidate.label === value);\n if (option) present.push(option.value);\n else missing.push(value);\n }\n return { present, missing };\n}\n\n/** Picks the reviewed radio input by value or label from one radio group; the index of the match or minus one. */\nexport function radiochoice(inputs: Array<{ value: string; label: string }>, choice: string): number {\n return inputs.findIndex(candidate => candidate.value === choice || candidate.label === choice);\n}\n\n/** Clamps one reviewed slider value to the declared range and step grid. */\nexport function slidervalue(requested: number, min: number, max: number, step: number): number {\n const lower = Math.min(min, max);\n const upper = Math.max(min, max);\n const clamped = Math.min(upper, Math.max(lower, requested));\n if (!Number.isFinite(step) || step <= 0) return clamped;\n return Math.round((clamped - lower) / step) * step + lower;\n}\n\n/** Validates and normalizes one reviewed yyyy-mm-dd date. */\nexport function datevalue(requested: string): string | null {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(requested)) return null;\n const parts = requested.split(\"-\").map(part => Number.parseInt(part, 10));\n const year = parts[0];\n const month = parts[1];\n const day = parts[2];\n if (!year || !month || !day || month < 1 || month > 12 || day < 1 || day > 31) return null;\n return requested;\n}\n\n/** Validates and normalizes one reviewed #rrggbb color. */\nexport function colorvalue(requested: string): string | null {\n if (!/^#[0-9a-fA-F]{6}$/.test(requested)) return null;\n return requested.toLowerCase();\n}\n\n/** Decides whether one reviewed details section still needs opening. */\nexport function expandstate(open: boolean): { open: boolean; changed: boolean } {\n return open ? { open: true, changed: false } : { open: true, changed: true };\n}\n\n/** Records one held key under its hold id; a repeated active hold id is refused. */\nexport function presshold(holds: keyholdstate[], hold: keyholdstate): { holds: keyholdstate[]; ok: boolean } {\n if (holds.some(existing => existing.holdid === hold.holdid && existing.releasedat === undefined)) return { holds, ok: false };\n return { holds: [...holds, hold], ok: true };\n}\n\n/** Releases one held key by hold id, keeping the release timestamp. */\nexport function releasehold(holds: keyholdstate[], holdid: string, releasedat: number): { holds: keyholdstate[]; released?: keyholdstate } {\n let released: keyholdstate | undefined;\n const next = holds.map(hold => {\n if (hold.holdid !== holdid || hold.releasedat !== undefined) return hold;\n released = { ...hold, releasedat };\n return released;\n });\n return { holds: next, ...(released ? { released } : {}) };\n}\n\n/** Returns the keys currently held, optionally filtered to one tab. */\nexport function heldkeys(holds: keyholdstate[], tabid?: number): keyholdstate[] {\n return holds.filter(hold => hold.releasedat === undefined && (tabid === undefined || hold.tabid === undefined || hold.tabid === tabid));\n}\n\nfunction events(target: Element): void {\n target.dispatchEvent(new Event(\"input\", { bubbles: true }));\n target.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n\nfunction modifiers(options: Record<string, unknown>): string[] {\n return Array.isArray(options.modifiers) ? options.modifiers.filter((item): item is string => typeof item === \"string\") : [];\n}\n\nfunction keyevent(type: \"keydown\" | \"keyup\", key: string, mods: string[]): KeyboardEvent {\n const code = key.length === 1 ? `Key${key.toUpperCase()}` : key;\n return new KeyboardEvent(type, { key, code, bubbles: true, cancelable: true, composed: true, ctrlKey: mods.includes(\"ctrl\"), shiftKey: mods.includes(\"shift\"), altKey: mods.includes(\"alt\"), metaKey: mods.includes(\"meta\") });\n}\n\nfunction fieldlike(target: Element | null): HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null {\n return target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement ? target : null;\n}\n\nfunction receiver(target: Element | null): HTMLElement {\n return target instanceof HTMLElement ? target : document.activeElement instanceof HTMLElement ? document.activeElement : document.body;\n}\n\nfunction wait(delay: number): Promise<void> {\n return new Promise(resolve => window.setTimeout(resolve, delay));\n}\n\n/** Focuses the reviewed target before typing; an explicit reviewed focus option forces or suppresses the focus. */\nfunction focuswhenneeded(target: Element, options: Record<string, unknown>): void {\n if (!(target instanceof HTMLElement)) return;\n if (options.focus === false) return;\n if (options.focus === true || document.activeElement !== target) target.focus();\n}\n\nfunction pollfor(predicate: () => boolean, description: string, timeout: number): Promise<stepresult> {\n return new Promise(resolve => {\n const started = Date.now();\n const check = (): void => {\n if (predicate()) { resolve({ ok: true, summary: `${description} is now present on the page.` }); return; }\n if (timeout > 0 && Date.now() - started >= timeout) { resolve({ ok: false, summary: `${description} did not appear within ${timeout} milliseconds.` }); return; }\n window.setTimeout(check, 100);\n };\n check();\n });\n}\n\n/** Runs one reviewed control interaction after the background policy gate and a fresh target check; frame routed steps receive their frame document as the root. */\nexport function runpagecontrol(step: toolstep, target: Element | null, root: Document = document): stepresult | Promise<stepresult> {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n switch (step.kind) {\n case \"typetime\": {\n const field = fieldlike(target);\n if (!field) return { ok: false, summary: \"Target cannot receive timed text.\" };\n const text = step.value ?? \"\";\n const delay = typeof options.delay === \"number\" && options.delay > 0 ? options.delay : 0;\n focuswhenneeded(field, options);\n const schedule = typetimeschedule(text, delay);\n return (async (): Promise<stepresult> => {\n for (const entry of schedule) {\n await wait(entry.delay);\n field.dispatchEvent(keyevent(\"keydown\", entry.key, []));\n field.dispatchEvent(new KeyboardEvent(\"keypress\", { key: entry.key, bubbles: true, cancelable: true }));\n field.value = `${field.value}${entry.key}`;\n field.dispatchEvent(new Event(\"input\", { bubbles: true }));\n }\n field.dispatchEvent(new Event(\"change\", { bubbles: true }));\n return { ok: true, summary: `Typed ${text.length} character${text.length === 1 ? \"\" : \"s\"} with a per keystroke delay of ${delay} milliseconds.` };\n })();\n }\n case \"appendtext\": {\n const field = fieldlike(target);\n if (!field) return { ok: false, summary: \"Target cannot hold a value.\" };\n focuswhenneeded(field, options);\n field.value = appendvalue(field.value, step.value ?? \"\");\n events(field);\n return { ok: true, summary: \"Reviewed text appended to the current field value.\" };\n }\n case \"setvalue\": {\n const field = fieldlike(target);\n if (!field) return { ok: false, summary: \"Target cannot hold a value.\" };\n focuswhenneeded(field, options);\n field.value = step.value ?? \"\";\n events(field);\n return { ok: true, summary: `Field value set through the dom property with ${valueevents().join(\" and \")} events.` };\n }\n case \"typeedit\": {\n if (!(target instanceof HTMLElement) || !target.isContentEditable) return { ok: false, summary: \"Target is not a content editable region.\" };\n focuswhenneeded(target, options);\n const text = step.value ?? \"\";\n return (async (): Promise<stepresult> => {\n for (const character of [...text]) {\n target.dispatchEvent(new InputEvent(\"beforeinput\", { bubbles: true, cancelable: true, data: character, inputType: \"insertText\" }));\n target.append(document.createTextNode(character));\n target.dispatchEvent(new InputEvent(\"input\", { bubbles: true, data: character, inputType: \"insertText\" }));\n }\n return { ok: true, summary: `Typed ${text.length} character${text.length === 1 ? \"\" : \"s\"} into the content editable region.` };\n })();\n }\n case \"keyhold\": {\n const key = step.value ?? \"\";\n const mods = modifiers(options);\n receiver(target).dispatchEvent(keyevent(\"keydown\", key, mods));\n const holdid = typeof options.holdid === \"string\" && options.holdid ? options.holdid : \"\";\n return { ok: true, summary: `Key ${key} pressed and held${holdid ? ` under hold id ${holdid}` : \"\"}.`, details: { ...(holdid ? { holdid } : {}), modifiers: mods } };\n }\n case \"keyrelease\": {\n const key = step.value ?? \"\";\n const mods = modifiers(options);\n receiver(target).dispatchEvent(keyevent(\"keyup\", key, mods));\n return { ok: true, summary: `Key ${key} released.`, details: { modifiers: mods } };\n }\n case \"submitsearch\": {\n const field = fieldlike(target);\n if (!field) return { ok: false, summary: \"Target is not a search field.\" };\n const results = typeof options.results === \"string\" ? options.results : \"\";\n const timeout = typeof options.timeout === \"number\" ? options.timeout : 0;\n focuswhenneeded(field, options);\n field.dispatchEvent(keyevent(\"keydown\", \"Enter\", []));\n field.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \"Enter\", bubbles: true, cancelable: true }));\n field.dispatchEvent(keyevent(\"keyup\", \"Enter\", []));\n return pollfor(() => Boolean(document.querySelector(results)), `Results region ${results}`, timeout);\n }\n case \"selectmulti\": {\n if (!(target instanceof HTMLSelectElement) || !target.multiple) return { ok: false, summary: \"Target is not a multi select control.\" };\n const choices = [...target.options].map(option => ({ value: option.value, label: clean(option.textContent || option.value) }));\n const requested = Array.isArray(options.values) ? options.values.filter((item): item is string => typeof item === \"string\") : [];\n const outcome = multichoices(requested, choices);\n if (outcome.missing.length > 0) return { ok: false, summary: `Reviewed option${outcome.missing.length === 1 ? \"\" : \"s\"} ${outcome.missing.join(\", \")} ${outcome.missing.length === 1 ? \"is\" : \"are\"} not part of the select control.` };\n for (const option of target.options) option.selected = outcome.present.includes(option.value);\n events(target);\n return { ok: true, summary: `Selected ${outcome.present.length} reviewed option${outcome.present.length === 1 ? \"\" : \"s\"} in the multi select control.`, details: { selected: outcome.present } };\n }\n case \"chooseradio\": {\n const radios = target instanceof HTMLInputElement && target.type === \"radio\"\n ? [...root.querySelectorAll<HTMLInputElement>(`input[type=radio][name=\"${CSS.escape(target.name)}\"]`)]\n : target ? [...(target as ParentNode).querySelectorAll<HTMLInputElement>(\"input[type=radio]\")] : [];\n if (radios.length === 0) return { ok: false, summary: \"No radio group owns the reviewed target.\" };\n const inputs = radios.map(radio => ({ value: radio.value, label: radio.labels && radio.labels.length > 0 ? clean(radio.labels[0]?.textContent || \"\") || radio.value : radio.value }));\n const index = radiochoice(inputs, step.value ?? \"\");\n const chosen = radios[index];\n if (!chosen) return { ok: false, summary: \"The reviewed radio option is not part of the group.\" };\n chosen.checked = true;\n events(chosen);\n return { ok: true, summary: `Picked reviewed radio option ${step.value}.`, details: { value: chosen.value } };\n }\n case \"setslider\": {\n if (!(target instanceof HTMLInputElement) || target.type !== \"range\") return { ok: false, summary: \"Target is not a range slider.\" };\n const requested = Number(step.value);\n if (!Number.isFinite(requested)) return { ok: false, summary: \"The reviewed slider value is not a number.\" };\n focuswhenneeded(target, options);\n const value = slidervalue(requested, Number(target.min), Number(target.max), Number(target.step));\n target.value = String(value);\n events(target);\n return { ok: true, summary: `Slider dragged to the reviewed value ${value}.`, details: { value } };\n }\n case \"setdate\": {\n if (!(target instanceof HTMLInputElement) || target.type !== \"date\") return { ok: false, summary: \"Target is not a date input.\" };\n const value = datevalue(step.value ?? \"\");\n if (value === null) return { ok: false, summary: \"The reviewed date is invalid.\" };\n focuswhenneeded(target, options);\n target.value = value;\n events(target);\n return { ok: true, summary: `Date input set to ${value}.`, details: { value } };\n }\n case \"setcolor\": {\n if (!(target instanceof HTMLInputElement) || target.type !== \"color\") return { ok: false, summary: \"Target is not a color input.\" };\n const value = colorvalue(step.value ?? \"\");\n if (value === null) return { ok: false, summary: \"The reviewed color is invalid.\" };\n focuswhenneeded(target, options);\n target.value = value;\n events(target);\n return { ok: true, summary: `Color input set to ${value}.`, details: { value } };\n }\n case \"expanddetails\": {\n const details = target instanceof HTMLElement ? target.closest(\"details\") : null;\n if (!details) return { ok: false, summary: \"Target is not inside a details section.\" };\n const outcome = expandstate(details.open);\n details.open = outcome.open;\n return { ok: true, summary: outcome.changed ? \"Collapsed details section opened.\" : \"Details section was already open.\", details: { changed: outcome.changed } };\n }\n default: return { ok: false, summary: \"Unsupported control action.\" };\n }\n}\n", "import type { navtarget, toolstep, urlpattern, waitoverride, waitprofile } from \"../types.js\";\nimport { parseoptions } from \"../policy.js\";\nimport type { stepresult } from \"./pageactions.js\";\n\n/**\n * Page navigation logics for reviewed steps.\n * Every correlated rule for navigation targets, container resolution, wait profiles, url patterns, link following, spa routing, query rewriting, deep links and recent tabs lives in this file.\n */\n\n/** One link shape matched by followlink and spanav, serializable for fixtures. */\nexport interface linkshape {\n text: string;\n href: string;\n selector: string;\n}\n\n/** One collected load signal sample with the signals that held true at its time. */\nexport interface signalsample {\n at: number;\n signals: string[];\n}\n\n/** Resolved container plan of one navigation target across tabs, windows and private profiles. */\nexport interface containerplan {\n kind: \"current\" | \"tab\" | \"window\" | \"private\";\n incognito: boolean;\n windowid?: number;\n position: \"adjacent\" | \"end\";\n}\n\n/** Reads the reviewed navtarget of a navigation step; null when the step reviews none. */\nexport function parsenavtarget(step: toolstep): navtarget | null {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const value = options.navtarget;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const target = value as Record<string, unknown>;\n if (typeof target.url !== \"string\" || !target.url) return null;\n const container = target.container === \"current\" || target.container === \"window\" || target.container === \"private\" ? target.container : \"tab\";\n return {\n url: target.url,\n container,\n ...(target.position === \"end\" ? { position: \"end\" } : { position: \"adjacent\" }),\n private: container === \"private\" || target.private === true,\n };\n}\n\n/** Resolves the container plan of one navigation target: the current task tab, a new tab, a new window or a private window profile separated from normal windows. */\nexport function resolvecontainer(target: navtarget, windows: Array<{ id: number; incognito: boolean; focused: boolean }>): containerplan {\n if (target.container === \"current\") return { kind: \"current\", incognito: false, position: target.position ?? \"adjacent\" };\n if (target.container === \"private\" || target.private) return { kind: \"private\", incognito: true, position: target.position ?? \"adjacent\" };\n if (target.container === \"window\") {\n const focused = windows.find(item => item.focused);\n return { kind: \"window\", incognito: false, ...(focused ? { windowid: focused.id } : {}), position: target.position ?? \"adjacent\" };\n }\n const normal = windows.find(item => !item.incognito && item.focused) ?? windows.find(item => !item.incognito);\n return { kind: \"tab\", incognito: false, ...(normal ? { windowid: normal.id } : {}), position: target.position ?? \"adjacent\" };\n}\n\n/** Reads the reviewed waitprofile of a navprofile step; null when the step reviews none. */\nexport function parsewaitprofile(step: toolstep): waitprofile | null {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const value = options.waitprofile;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const profile = value as Record<string, unknown>;\n const signals = Array.isArray(profile.signals) ? profile.signals.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n if (signals.length === 0) return null;\n const overrides: waitoverride[] = [];\n if (Array.isArray(profile.overrides)) {\n for (const item of profile.overrides) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const override = item as Record<string, unknown>;\n if (typeof override.origin !== \"string\" || !override.origin) continue;\n const overridesignals = Array.isArray(override.signals) ? override.signals.filter((entry): entry is string => typeof entry === \"string\" && entry.trim().length > 0) : undefined;\n overrides.push({\n origin: override.origin,\n ...(overridesignals && overridesignals.length > 0 ? { signals: overridesignals } : {}),\n ...(typeof override.idle === \"number\" && Number.isFinite(override.idle) && override.idle >= 0 ? { idle: override.idle } : {}),\n ...(typeof override.timeout === \"number\" && Number.isFinite(override.timeout) && override.timeout >= 0 ? { timeout: override.timeout } : {}),\n });\n }\n }\n return {\n signals,\n ...(typeof profile.idle === \"number\" && Number.isFinite(profile.idle) && profile.idle >= 0 ? { idle: profile.idle } : {}),\n ...(typeof profile.timeout === \"number\" && Number.isFinite(profile.timeout) && profile.timeout >= 0 ? { timeout: profile.timeout } : {}),\n ...(overrides.length > 0 ? { overrides } : {}),\n };\n}\n\n/** Resolves the effective signals and thresholds of one wait profile for an origin by folding the per origin overrides in. */\nexport function profilefororigin(profile: waitprofile, origin: string): { signals: string[]; idle: number; timeout: number } {\n let signals = [...profile.signals];\n let idle = profile.idle ?? 0;\n let timeout = profile.timeout ?? 0;\n for (const override of profile.overrides ?? []) {\n if (!override.origin || new URL(override.origin).origin !== origin) continue;\n if (override.signals && override.signals.length > 0) signals = [...override.signals];\n if (override.idle !== undefined) idle = override.idle;\n if (override.timeout !== undefined) timeout = override.timeout;\n }\n return { signals, idle, timeout };\n}\n\n/** Maps a document ready state onto the live navigation load phase. */\nexport function loadphase(readystate: string): \"loading\" | \"interactive\" | \"complete\" {\n if (readystate === \"interactive\") return \"interactive\";\n if (readystate === \"complete\") return \"complete\";\n return \"loading\";\n}\n\n/** Decides the wait outcome of a wait profile from collected load signal samples: every required signal must hold in the latest sample inside the timeout. */\nexport function evaluatesignals(required: string[], samples: signalsample[], timeout: number): { ok: boolean; satisfied: string[]; waited: number; samples: number } {\n const start = samples[0]?.at ?? 0;\n const last = samples[samples.length - 1];\n const waited = Math.max(0, (last?.at ?? 0) - start);\n const held = last?.signals ?? [];\n const satisfied = required.filter(signal => held.includes(signal));\n if (required.length > 0 && satisfied.length === required.length) return { ok: true, satisfied, waited, samples: samples.length };\n if (timeout > 0 && waited >= timeout) return { ok: false, satisfied, waited, samples: samples.length };\n return { ok: false, satisfied, waited, samples: samples.length };\n}\n\n/** Reads the reviewed urlpattern of a waiturl, spanav or spawait step; null when the step reviews none. */\nexport function parseurlpattern(step: toolstep, key: string = \"urlpattern\"): urlpattern | null {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const value = options[key];\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const pattern = value as Record<string, unknown>;\n if (typeof pattern.url !== \"string\" || !pattern.url) return null;\n const mode = pattern.mode === \"exact\" || pattern.mode === \"host\" || pattern.mode === \"pattern\" ? pattern.mode : \"prefix\";\n const query: Record<string, string> = {};\n if (pattern.query && typeof pattern.query === \"object\" && !Array.isArray(pattern.query)) {\n for (const [name, item] of Object.entries(pattern.query as Record<string, unknown>)) if (typeof item === \"string\") query[name] = item;\n }\n return {\n mode,\n url: pattern.url,\n ...(Object.keys(query).length > 0 ? { query } : {}),\n ...(typeof pattern.fragment === \"string\" && pattern.fragment ? { fragment: pattern.fragment } : {}),\n };\n}\n\n/** Matches a wildcard path segment against one url path segment. */\nfunction segmentmatches(pattern: string, actual: string): boolean {\n if (pattern === \"*\" || pattern === \"**\") return true;\n if (!pattern.includes(\"*\")) return pattern === actual;\n const parts = pattern.split(\"*\");\n let index = 0;\n for (let position = 0; position < parts.length; position += 1) {\n const part = parts[position] as string;\n if (part === \"\") continue;\n const found = actual.indexOf(part, index);\n if (found < 0) return false;\n if (position === 0 && found !== 0) return false;\n index = found + part.length;\n }\n const last = parts[parts.length - 1] as string;\n return last === \"\" || actual.endsWith(last);\n}\n\n/** Matches one url against a reviewed urlpattern by mode plus required query and fragment parts. */\nexport function urlmatches(url: string, pattern: urlpattern): boolean {\n let parsed: URL;\n try { parsed = new URL(url); } catch { return false; }\n let expected: URL;\n try { expected = new URL(pattern.url); } catch { return false; }\n if (pattern.mode === \"exact\" && parsed.toString() !== expected.toString()) return false;\n if (pattern.mode === \"prefix\" && !parsed.toString().startsWith(pattern.url)) return false;\n if (pattern.mode === \"host\" && parsed.origin !== expected.origin) return false;\n if (pattern.mode === \"pattern\") {\n if (parsed.origin !== expected.origin) return false;\n const expectedsegments = expected.pathname.split(\"/\").filter(segment => segment !== \"\");\n const actualsegments = parsed.pathname.split(\"/\").filter(segment => segment !== \"\");\n if (expectedsegments.includes(\"**\")) {\n const cut = expectedsegments.indexOf(\"**\");\n const head = expectedsegments.slice(0, cut);\n const tail = expectedsegments.slice(cut + 1);\n if (actualsegments.length < head.length + tail.length) return false;\n if (!head.every((segment, position) => segmentmatches(segment, actualsegments[position] ?? \"\"))) return false;\n if (!tail.every((segment, position) => segmentmatches(segment, actualsegments[actualsegments.length - tail.length + position] ?? \"\"))) return false;\n } else if (expectedsegments.length !== actualsegments.length || !expectedsegments.every((segment, position) => segmentmatches(segment, actualsegments[position] ?? \"\"))) return false;\n }\n const values = parsed.searchParams;\n for (const [name, value] of Object.entries(pattern.query ?? {})) {\n if (!values.has(name)) return false;\n if (value !== \"*\" && values.get(name) !== value) return false;\n }\n if (pattern.fragment !== undefined && parsed.hash.slice(1) !== pattern.fragment) return false;\n return true;\n}\n\n/** Reads the current query parameters of a url. */\nfunction readquery(url: string): Record<string, string> {\n const values: Record<string, string> = {};\n try {\n for (const [name, value] of new URL(url).searchParams.entries()) values[name] = value;\n } catch { /* an unparseable url has no readable parameters */ }\n return values;\n}\n\n/** Result of one query rewrite with the parameters read, written and the new url. */\nexport interface queryrewriteoutcome {\n url: string;\n before: Record<string, string>;\n after: Record<string, string>;\n set: string[];\n removed: string[];\n}\n\n/** Rewrites the query parameters of one url: reviewed values are set, reviewed names removed and the rest preserved. */\nexport function rewritequeryurl(url: string, set: Record<string, string>, remove: string[]): queryrewriteoutcome {\n const parsed = new URL(url);\n const before = readquery(url);\n for (const name of remove) parsed.searchParams.delete(name);\n for (const [name, value] of Object.entries(set)) parsed.searchParams.set(name, value);\n parsed.hash = \"\";\n return { url: parsed.toString(), before, after: readquery(parsed.toString()), set: Object.keys(set), removed: [...remove] };\n}\n\n/** Applies one reviewed fragment to a url, keeping every other part untouched. */\nexport function fragmenturl(url: string, fragment: string): string {\n const parsed = new URL(url);\n parsed.hash = fragment.replace(/^#/, \"\");\n return parsed.toString();\n}\n\n/** Matches links by their visible text, case insensitively, refusing ambiguity through multiple matches. */\nexport function matchlinktext(links: linkshape[], text: string): linkshape[] {\n const wanted = text.trim().toLowerCase();\n return links.filter(link => link.text.trim().toLowerCase() === wanted);\n}\n\n/** Matches links by their href fragment when the reviewed option asks for fragment resolution. */\nexport function matchlinkfragment(links: linkshape[], fragment: string): linkshape[] {\n const wanted = fragment.trim().replace(/^#/, \"\");\n return links.filter(link => {\n try { return new URL(link.href, \"https://example.invalid\").hash.replace(/^#/, \"\") === wanted; } catch { return false; }\n });\n}\n\n/** Builds a deep link into a common web app from a reviewed app pattern and its string params; unknown apps are refused. */\nexport function deeplinkurl(app: string, params: Record<string, string>): string | null {\n const value = (name: string): string | undefined => {\n const item = params[name];\n return typeof item === \"string\" && item.trim() ? item.trim() : undefined;\n };\n switch (app.trim().toLowerCase()) {\n case \"github\": {\n const owner = value(\"owner\");\n const repo = value(\"repo\");\n if (!owner || !repo) return null;\n const path = value(\"path\");\n return `https://github.com/${owner}/${repo}${path ? `/${path.replace(/^\\/+/, \"\")}` : \"\"}`;\n }\n case \"youtube\": {\n const id = value(\"id\");\n if (id) return `https://www.youtube.com/watch?v=${encodeURIComponent(id)}`;\n const search = value(\"search\");\n if (search) return `https://www.youtube.com/results?search_query=${encodeURIComponent(search)}`;\n return null;\n }\n case \"maps\": {\n const query = value(\"query\");\n if (!query) return null;\n return `https://www.google.com/maps/search/${encodeURIComponent(query)}`;\n }\n case \"wikipedia\": {\n const title = value(\"title\");\n if (!title) return null;\n const language = value(\"language\") ?? \"en\";\n return `https://${language}.wikipedia.org/wiki/${encodeURIComponent(title.replace(/\\s+/g, \"_\"))}`;\n }\n case \"amazon\": {\n const search = value(\"search\");\n if (!search) return null;\n return `https://www.amazon.com/s?k=${encodeURIComponent(search)}`;\n }\n case \"x\": {\n const user = value(\"user\");\n if (!user) return null;\n return `https://x.com/${user.replace(/^@/, \"\")}`;\n }\n default: return null;\n }\n}\n\n/** True when the current url of a single page app changed without a reload, keeping the origin. */\nexport function spauroutechanged(previousurl: string, currenturl: string): boolean {\n if (previousurl === currenturl) return false;\n try {\n return new URL(previousurl).origin === new URL(currenturl).origin;\n } catch { return false; }\n}\n\n/** Picks the most recently closed tab whose url is no longer open; null when every recent tab is already restored. */\nexport function pickrecenttab(recenttabs: Array<{ url: string; tabid: number; closedat: number }>, openurls: string[]): { url: string; tabid: number; closedat: number } | null {\n return recenttabs.find(tab => !openurls.includes(tab.url)) ?? null;\n}\n\nfunction wait(ms: number): Promise<void> {\n return new Promise(resolve => window.setTimeout(resolve, ms));\n}\n\nfunction stepoptions(step: toolstep): Record<string, unknown> {\n try { return parseoptions(step); } catch { return {}; }\n}\n\nfunction collectlinks(root: Document): linkshape[] {\n return [...root.querySelectorAll(\"a[href]\")].map(element => ({\n text: element.textContent?.trim() ?? \"\",\n href: element instanceof HTMLAnchorElement ? element.href : element.getAttribute(\"href\") ?? \"\",\n selector: element.getAttribute(\"href\") ?? \"\",\n }));\n}\n\n/** Resolves the reviewed link of a followlink or spanav step by visible text or href fragment, refusing links outside the allowed origins. */\nfunction resolvelink(step: toolstep, root: Document): { ok: true; element: HTMLAnchorElement } | { ok: false; summary: string } {\n const options = stepoptions(step);\n const allowedorigins = Array.isArray(options.allowedorigins) ? options.allowedorigins.filter((item): item is string => typeof item === \"string\") : [];\n const links = collectlinks(root);\n const matches = options.fragment === true ? matchlinkfragment(links, step.value ?? \"\") : matchlinktext(links, step.value ?? \"\");\n if (matches.length === 0) return { ok: false, summary: `No link matches the reviewed reference \"${step.value ?? \"\"}\".` };\n if (matches.length > 1) return { ok: false, summary: `The reviewed link reference matched ${matches.length} links; review a unique one.` };\n const element = [...root.querySelectorAll(\"a[href]\")].find(candidate => (candidate instanceof HTMLAnchorElement ? candidate.href : candidate.getAttribute(\"href\") ?? \"\") === matches[0]?.href);\n if (!(element instanceof HTMLAnchorElement)) return { ok: false, summary: \"The reviewed link is no longer available.\" };\n if (allowedorigins.length > 0) {\n let origin = \"\";\n try { origin = new URL(element.href).origin; } catch { origin = \"\"; }\n if (!allowedorigins.includes(origin)) return { ok: false, summary: `The reviewed link leaves the session origin grants for ${origin}.` };\n }\n return { ok: true, element };\n}\n\n/** Waits for the page load event and reports the ready state and load phase. */\nasync function runwaitload(step: toolstep): Promise<stepresult> {\n const options = stepoptions(step);\n const timeout = typeof options.timeout === \"number\" && Number.isFinite(options.timeout) && options.timeout > 0 ? options.timeout : 0;\n const started = Date.now();\n for (;;) {\n const phase = loadphase(document.readyState);\n if (phase === \"complete\") return { ok: true, summary: `The page load event fired and the document is complete after ${Date.now() - started} milliseconds.`, details: { phase, readystate: document.readyState, waited: Date.now() - started } };\n if (timeout > 0 && Date.now() - started >= timeout) return { ok: false, summary: `The page did not reach the complete load phase within the reviewed timeout of ${timeout} milliseconds.`, details: { phase, readystate: document.readyState, waited: Date.now() - started } };\n await wait(50);\n }\n}\n\n/** Waits until the current url matches the reviewed urlpattern. */\nasync function runwaiturl(step: toolstep): Promise<stepresult> {\n const options = stepoptions(step);\n const pattern = parseurlpattern(step);\n if (!pattern) return { ok: false, summary: \"A reviewed urlpattern is required.\" };\n const timeout = typeof options.timeout === \"number\" && Number.isFinite(options.timeout) && options.timeout > 0 ? options.timeout : 0;\n const poll = typeof options.poll === \"number\" && Number.isFinite(options.poll) && options.poll > 0 ? options.poll : 100;\n const started = Date.now();\n for (;;) {\n if (urlmatches(location.href, pattern)) return { ok: true, summary: `The url matched the reviewed ${pattern.mode} pattern after ${Date.now() - started} milliseconds.`, details: { url: location.href, mode: pattern.mode, waited: Date.now() - started } };\n if (timeout > 0 && Date.now() - started >= timeout) return { ok: false, summary: `The url did not match the reviewed ${pattern.mode} pattern within the reviewed timeout of ${timeout} milliseconds.`, details: { url: location.href, mode: pattern.mode, waited: Date.now() - started } };\n await wait(poll);\n }\n}\n\n/** Follows one reviewed link, reporting the href travelled to. */\nasync function runfollowlink(step: toolstep, root: Document): Promise<stepresult> {\n const resolution = resolvelink(step, root);\n if (!resolution.ok) return { ok: false, summary: resolution.summary };\n const href = resolution.element.href;\n resolution.element.click();\n return { ok: true, summary: `Followed the reviewed link to ${href}.`, details: { href } };\n}\n\n/** Navigates a single page app by clicking the reviewed control and waiting for the route change without a reload. */\nasync function runspanav(step: toolstep, root: Document): Promise<stepresult> {\n const options = stepoptions(step);\n const resolution = resolvelink(step, root);\n if (!resolution.ok) return { ok: false, summary: resolution.summary };\n const timeout = typeof options.timeout === \"number\" && Number.isFinite(options.timeout) && options.timeout > 0 ? options.timeout : 0;\n const pattern = parseurlpattern(step, \"routepattern\");\n const before = location.href;\n resolution.element.click();\n const started = Date.now();\n for (;;) {\n const changed = spauroutechanged(before, location.href);\n const matched = pattern ? urlmatches(location.href, pattern) : changed;\n if (matched) return { ok: true, summary: `The single page app route changed to ${location.href} without a reload.`, details: { from: before, to: location.href, waited: Date.now() - started } };\n if (timeout > 0 && Date.now() - started >= timeout) return { ok: false, summary: `The single page app route did not change within the reviewed timeout of ${timeout} milliseconds.`, details: { from: before, to: location.href, waited: Date.now() - started } };\n await wait(50);\n }\n}\n\n/** Waits for a url change inside a single page app without a reload, through popstate, hashchange and history polling. */\nasync function runspawait(step: toolstep): Promise<stepresult> {\n const options = stepoptions(step);\n const timeout = typeof options.timeout === \"number\" && Number.isFinite(options.timeout) && options.timeout > 0 ? options.timeout : 0;\n const poll = typeof options.poll === \"number\" && Number.isFinite(options.poll) && options.poll > 0 ? options.poll : 100;\n const pattern = parseurlpattern(step);\n const before = location.href;\n const started = Date.now();\n let detected = false;\n const onroute = (): void => { if (spauroutechanged(before, location.href)) detected = true; };\n window.addEventListener(\"popstate\", onroute);\n window.addEventListener(\"hashchange\", onroute);\n try {\n for (;;) {\n if (pattern ? urlmatches(location.href, pattern) : detected || spauroutechanged(before, location.href)) {\n return { ok: true, summary: `The single page app url changed to ${location.href} without a reload.`, details: { from: before, to: location.href, waited: Date.now() - started } };\n }\n if (timeout > 0 && Date.now() - started >= timeout) return { ok: false, summary: `The single page app url did not change within the reviewed timeout of ${timeout} milliseconds.`, details: { from: before, to: location.href, waited: Date.now() - started } };\n await wait(poll);\n }\n } finally {\n window.removeEventListener(\"popstate\", onroute);\n window.removeEventListener(\"hashchange\", onroute);\n }\n}\n\n/** Reads and rewrites the query parameters of the current url with pushstate, reporting the parameters read and the new url. */\nfunction runrewritequery(step: toolstep): stepresult {\n const options = stepoptions(step);\n const set: Record<string, string> = {};\n if (options.set && typeof options.set === \"object\" && !Array.isArray(options.set)) {\n for (const [name, value] of Object.entries(options.set as Record<string, unknown>)) if (typeof value === \"string\") set[name] = value;\n }\n const remove = Array.isArray(options.remove) ? options.remove.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const outcome = rewritequeryurl(location.href, set, remove);\n history.pushState(history.state, document.title, outcome.url);\n return { ok: true, summary: `Rewrote ${outcome.set.length + outcome.removed.length} query parameter${outcome.set.length + outcome.removed.length === 1 ? \"\" : \"s\"}; the url is now ${outcome.url}.`, details: { url: outcome.url, before: outcome.before, after: outcome.after, set: outcome.set, removed: outcome.removed } };\n}\n\n/** Sets the reviewed url fragment and scrolls to its anchor with smooth behavior. */\nasync function runsetfragment(step: toolstep): Promise<stepresult> {\n const fragment = (step.value ?? \"\").replace(/^#/, \"\");\n if (!fragment) return { ok: false, summary: \"A reviewed fragment is required.\" };\n const url = fragmenturl(location.href, fragment);\n history.pushState(history.state, document.title, url);\n const anchor = document.getElementById(fragment);\n anchor?.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n return { ok: true, summary: `Set the url fragment to ${fragment} and scrolled to its anchor.`, details: { url, fragment, anchored: Boolean(anchor) } };\n}\n\n/** Stops a pending navigation by halting the document load. */\nfunction runstopnav(): stepresult {\n window.stop();\n return { ok: true, summary: \"Stopped the pending navigation of the page.\" };\n}\n\n/** Prefetches the reviewed urls by injecting prefetch hints into the document head. */\nfunction runprefetch(step: toolstep): stepresult {\n const options = stepoptions(step);\n const urls = Array.isArray(options.urls) ? options.urls.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n if (urls.length === 0) return { ok: false, summary: \"A reviewed list of prefetch urls is required.\" };\n for (const url of urls) {\n const hint = document.createElement(\"link\");\n hint.rel = \"prefetch\";\n hint.href = url;\n document.head.append(hint);\n }\n return { ok: true, summary: `Queued ${urls.length} prefetch hint${urls.length === 1 ? \"\" : \"s\"}.`, details: { urls } };\n}\n\n/** Preconnects to the reviewed origins by injecting preconnect hints into the document head. */\nfunction runpreconnect(step: toolstep): stepresult {\n const options = stepoptions(step);\n const origins = Array.isArray(options.origins) ? options.origins.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n if (origins.length === 0) return { ok: false, summary: \"A reviewed list of preconnect origins is required.\" };\n for (const origin of origins) {\n const hint = document.createElement(\"link\");\n hint.rel = \"preconnect\";\n hint.href = origin;\n document.head.append(hint);\n }\n return { ok: true, summary: `Opened ${origins.length} preconnect hint${origins.length === 1 ? \"\" : \"s\"}.`, details: { origins } };\n}\n\n/** Prints the page through the browser print pipeline; the artifact routing happens in the background. */\nfunction runprintpdf(): stepresult {\n window.print();\n return { ok: true, summary: \"Sent the page to the browser print pipeline.\" };\n}\n\n/** Runs one reviewed page navigation kind inside the page world. */\nexport function runpagenav(step: toolstep, root: Document = document): stepresult | Promise<stepresult> {\n switch (step.kind) {\n case \"waitload\": return runwaitload(step);\n case \"waiturl\": return runwaiturl(step);\n case \"followlink\": return runfollowlink(step, root);\n case \"spanav\": return runspanav(step, root);\n case \"spawait\": return runspawait(step);\n case \"rewritequery\": return runrewritequery(step);\n case \"setfragment\": return runsetfragment(step);\n case \"stopnav\": return runstopnav();\n case \"prefetch\": return runprefetch(step);\n case \"preconnect\": return runpreconnect(step);\n case \"printpdf\": return runprintpdf();\n default: return { ok: false, summary: \"Unsupported navigation action.\" };\n }\n}\n", "import type { authrecord, curatedlink, redirectchain, redirecthop, ratelimit, ratelimitstate, safetyverdict, toolstep } from \"../types.js\";\nimport { parseoptions } from \"../policy.js\";\n\n/**\n * Navigation network state logics for reviewed steps.\n * Every correlated rule for redirect chain assembly, http error and interstitial classification, per domain rate limit windows, url safety verdicts, curated batch lists, prefetch verification, preconnect origins and basic auth credential gating lives in this file.\n */\n\n/** One navigation watch event as observed from browser navigation listeners, serializable for fixtures. */\nexport interface navwatchevent {\n event: \"beforenavigate\" | \"committed\" | \"completed\" | \"error\" | \"urlchange\";\n url: string;\n timestamp: number;\n status?: number;\n redirect?: boolean;\n error?: string;\n}\n\n/** Assembles one redirect chain from navigation watch events: successive url changes become hops with statuses and timing, and the chain closes on completion or error. */\nexport function buildredirectchain(events: navwatchevent[]): redirectchain {\n const hops: redirecthop[] = [];\n let startedat = 0;\n let endedat = 0;\n let open = false;\n for (const event of events) {\n if (event.event === \"beforenavigate\") {\n hops.length = 0;\n startedat = event.timestamp;\n endedat = event.timestamp;\n open = true;\n hops.push({ url: event.url, status: event.status ?? 0, at: event.timestamp });\n continue;\n }\n if (!open) continue;\n endedat = event.timestamp;\n if (event.event === \"urlchange\" || event.redirect || (event.event === \"committed\" && hops[hops.length - 1]?.url !== event.url)) {\n if (hops[hops.length - 1]?.url === event.url && typeof event.status === \"number\") hops[hops.length - 1] = { url: event.url, status: event.status, at: event.timestamp };\n else hops.push({ url: event.url, status: event.status ?? 0, at: event.timestamp });\n continue;\n }\n if (event.event === \"committed\" && typeof event.status === \"number\" && hops[hops.length - 1]) {\n hops[hops.length - 1] = { url: event.url, status: event.status, at: event.timestamp };\n continue;\n }\n if (event.event === \"completed\" || event.event === \"error\") {\n if (event.event === \"completed\" && hops[hops.length - 1] && hops[hops.length - 1]?.url !== event.url) hops.push({ url: event.url, status: event.status ?? 200, at: event.timestamp });\n if (event.event === \"completed\" && typeof event.status === \"number\" && hops[hops.length - 1]) hops[hops.length - 1] = { url: event.url, status: event.status, at: event.timestamp };\n open = false;\n }\n }\n return { hops, startedat, endedat: endedat || startedat };\n}\n\n/** Returns the final url of a redirect chain: the url of its last hop. */\nexport function finalurl(chain: redirectchain): string {\n return chain.hops[chain.hops.length - 1]?.url ?? \"\";\n}\n\n/** Counts the redirect hops of a chain, ignoring the first and the final urls when no intermediary hop exists. */\nexport function redirectcount(chain: redirectchain): number {\n return Math.max(0, chain.hops.length - 1);\n}\n\n/** Classifies a navigation url change: a full load, a spa route change without reload, a reload or no change. */\nexport function classifynavchange(previousurl: string, currenturl: string, status: string | undefined): \"load\" | \"route\" | \"reload\" | \"none\" {\n if (previousurl === currenturl) return status === \"loading\" ? \"reload\" : \"none\";\n try {\n if (new URL(previousurl).origin !== new URL(currenturl).origin) return \"load\";\n } catch { return \"load\"; }\n return status === \"loading\" ? \"load\" : \"route\";\n}\n\n/** One classified http state of a navigation: http error, offline and certificate interstitial flags with reasons. */\nexport interface httpstate {\n httperror: boolean;\n offline: boolean;\n certificate: boolean;\n reasons: string[];\n}\n\n/** Detects the http error, offline and certificate interstitial states from the offline flag, error strings and observed statuses. */\nexport function detecthttpstate(input: { offline: boolean; errors?: string[]; statuses?: number[] }): httpstate {\n const reasons: string[] = [];\n let httperror = false;\n let certificate = false;\n const errors = input.errors ?? [];\n const statuses = input.statuses ?? [];\n for (const error of errors) {\n if (/CERT|SSL|TLS|privacy bad|your connection is not private/i.test(error)) { certificate = true; httperror = true; reasons.push(`certificate interstitial: ${error}`); continue; }\n if (/ERR_NAME_NOT_RESOLVED|ERR_CONNECTION|ERR_TIMED_OUT|ERR_INTERNET_DISCONNECTED|ERR_ADDRESS_UNREACHABLE|ERR_NETWORK/i.test(error)) { httperror = true; reasons.push(`network error: ${error}`); continue; }\n httperror = true;\n reasons.push(`navigation error: ${error}`);\n }\n for (const status of statuses) {\n if (status >= 400 && status < 600) { httperror = true; reasons.push(`http status ${status}`); }\n }\n if (input.offline) reasons.push(\"browser reports offline\");\n return { httperror, offline: input.offline, certificate, reasons };\n}\n\n/** Applies the certificate interstitial policy: interstitials are reported for review, never bypassed. */\nexport function interstitialpolicy(state: httpstate): { interstitial: boolean; bypass: boolean; guidance: string } {\n if (state.certificate) return { interstitial: true, bypass: false, guidance: \"A certificate interstitial was detected; Devthink reports it for review and never bypasses it.\" };\n if (state.httperror) return { interstitial: true, bypass: false, guidance: \"An http error state was detected and is reported for review.\" };\n return { interstitial: false, bypass: false, guidance: \"No interstitial was detected.\" };\n}\n\n/** Reads the reviewed ratelimit of a navrate step; null when the step reviews none. */\nexport function parseratelimit(step: toolstep): ratelimit | null {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const value = options.ratelimit;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const limit = value as Record<string, unknown>;\n const window = typeof limit.window === \"number\" && Number.isFinite(limit.window) && limit.window > 0 ? limit.window : 0;\n const ceiling = typeof limit.ceiling === \"number\" && Number.isInteger(limit.ceiling) && limit.ceiling >= 1 ? limit.ceiling : 0;\n if (window <= 0 || ceiling < 1) return null;\n const domain = typeof limit.domain === \"string\" && limit.domain.trim() ? limit.domain.trim() : \"\";\n return { domain, window, ceiling };\n}\n\n/** Reads the domain of a url for rate limit accounting. */\nexport function domainof(url: string): string {\n try { return new URL(url).hostname; } catch { return \"\"; }\n}\n\n/** Returns the live rate limit window state of one domain, opening a fresh window when the reviewed window has elapsed. */\nexport function ratewindow(state: ratelimitstate | undefined, limit: ratelimit, now: number): ratelimitstate {\n if (state && state.domain === limit.domain && state.limit.window === limit.window && state.limit.ceiling === limit.ceiling && now < state.openedat + limit.window) return state;\n return { domain: limit.domain, limit, openedat: now, count: 0 };\n}\n\n/** Decides whether one more navigation fits inside the reviewed per domain rate limit window. */\nexport function rateallows(state: ratelimitstate, now: number): { allowed: boolean; remaining: number; retryafter: number } {\n const elapsed = now - state.openedat;\n const remaining = Math.max(0, state.limit.ceiling - state.count);\n const retryafter = Math.max(0, state.limit.window - elapsed);\n return { allowed: remaining > 0, remaining, retryafter };\n}\n\n/** Records one navigation hit inside the live rate limit window of a domain. */\nexport function recordratehit(state: ratelimitstate, now: number): ratelimitstate {\n return { ...state, count: state.count + 1, ...(state.count + 1 === 1 ? { openedat: now } : {}) };\n}\n\n/** Verifies one url for safety: HTTPS only, no embedded credentials and no private network or raw ip targets. */\nexport function checksafe(url: string): safetyverdict {\n const reasons: string[] = [];\n let safe = true;\n let parsed: URL;\n try { parsed = new URL(url); } catch { return { url, safe: false, reasons: [\"the url does not parse\"], at: 0 }; }\n if (parsed.protocol !== \"https:\") { safe = false; reasons.push(\"the url must use HTTPS\"); }\n if (parsed.username || parsed.password) { safe = false; reasons.push(\"the url carries embedded credentials\"); }\n const host = parsed.hostname.toLowerCase();\n const privatelist = [\"localhost\", \"127.0.0.1\", \"0.0.0.0\", \"::1\", \"[::1]\"];\n if (privatelist.includes(host) || /^10\\./.test(host) || /^192\\.168\\./.test(host) || /^172\\.(1[6-9]|2\\d|3[01])\\./.test(host) || /^169\\.254\\./.test(host)) { safe = false; reasons.push(`the host ${host} is a private network target`); }\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(host) || /^\\[?[0-9a-f:]+\\]?$/i.test(host)) { safe = false; reasons.push(`the host ${host} is a raw address without a domain`); }\n return { url, safe, reasons, at: 0 };\n}\n\n/** Builds the curated link list of a batchopen step from per url safety verdicts. */\nexport function curatelinks(urls: string[], verifier: (url: string) => safetyverdict): curatedlink[] {\n return urls.map(url => {\n const verdict = verifier(url);\n return { url, verdict: verdict.safe ? \"safe\" : \"unsafe\", reasons: verdict.reasons };\n });\n}\n\n/** Splits a curated link list into the urls batch opening may open and the unsafe ones it refuses. */\nexport function batchopenset(links: curatedlink[]): { open: string[]; refused: Array<{ url: string; reasons: string[] }> } {\n const open: string[] = [];\n const refused: Array<{ url: string; reasons: string[] }> = [];\n for (const link of links) {\n if (link.verdict === \"safe\") open.push(link.url);\n else refused.push({ url: link.url, reasons: link.reasons });\n }\n return { open, refused };\n}\n\n/** Verifies prefetch candidates against the session grants: only granted urls may be prefetched. */\nexport function prefetchcandidates(urls: string[], grants: string[]): { allowed: string[]; refused: string[] } {\n const allowed: string[] = [];\n const refused: string[] = [];\n for (const url of urls) {\n let origin = \"\";\n try { origin = new URL(url).origin; } catch { refused.push(url); continue; }\n if (grants.includes(origin)) allowed.push(url);\n else refused.push(url);\n }\n return { allowed, refused };\n}\n\n/** Deduplicates the preconnect origins of one preconnect step. */\nexport function preconnectorigins(origins: string[]): string[] {\n return [...new Set(origins.map(origin => origin.trim()).filter(Boolean))];\n}\n\n/** Finds the reviewed basic auth credentials of one origin; the auth flow refuses to run without them. */\nexport function authfor(auths: authrecord[], url: string): authrecord | undefined {\n let origin = \"\";\n try { origin = new URL(url).origin; } catch { return undefined; }\n return auths.find(record => record.origin === origin);\n}\n", "import { randomid, sessionmemory } from \"../memory.js\";\nimport { canexecute, canpreview, hostpattern, islayoutkind, istabscommandkind, layoutmutationgranted, navigationgranted, normalizeendpoint, originverified, parseoptions, requiredcapability, tasktabceiling, validatestep, windowclosegate } from \"../policy.js\";\nimport { assigntasktab, iscomplete, recordnaventry, recordoutcome, recordstep, recordwatchcompletion, resetforplan, tasktabs, watchclosed } from \"../progress.js\";\nimport { heldkeysreport, layoutreport, mapresponse, navstateresponse, observationresponse, outcomeresponse, parseproposal, requestbody, safetyresponse, signalsreport, trailreport } from \"../protocol.js\";\nimport type { a11ynode, agentplan, agentsession, artifactrecord, auditevent, authrecord, bannerreport, capabilityreport, clickablemap, closedtab, controltabstate, curatedlink, curatedlist, derivedselector, diagnosticreport, diffentry, dialogdecision, dialogpolicy, focusevent, keyholdstate, mapentry, mutationevent, navcontrol, navintentrecord, navqueues, navrecord, navstate, observation, pagesignals, readerarticle, ratelimit, ratelimitstate, recenttab, resolvedtarget, retryoutcome, retryrule, safetyverdict, selectorcandidate, sessionsnapshot, snapshotdiff, stepoutcome, tabbadge, tabgrouprecord, tablayout, tabmeta, tabreport, tabreportentry, tabwatchevent, templateprofile, toolstep, trailentry, waitprofilerecord, watchregistration } from \"../types.js\";\nimport { isbrowserkind, readcapabilities, runbrowseraction } from \"./browsertabs.js\";\nimport { assigntasktabs, audiotabs, badgefromprogress, buildlayout, clonetabs, closeselection, discardcandidates, layoutrestoreplan, parsetabquery, querymatches, regroupaftermoves, restorediscarded, searchtabmatches, switchtarget, tasktabgauge, tasktabsinwindow, trackedtasktabs, watchtabdispatch, windowprofilegrants, zoomstep, type tabshape, type windowshape } from \"./tabscommand.js\";\nimport { dialoganswer, installdialoghandler, parsedialogpolicy, type observeddialog } from \"./pagedialogs.js\";\nimport { innerstep, runretries } from \"./pageinteract.js\";\nimport { heldkeys, presshold, releasehold } from \"./pagecontrols.js\";\nimport type { nodesummary } from \"./pagewatch.js\";\nimport { deeplinkurl, parsenavtarget, parsewaitprofile, pickrecenttab, profilefororigin, resolvecontainer } from \"./pagenav.js\";\nimport { authfor, batchopenset, buildredirectchain, checksafe, classifynavchange, curatelinks, detecthttpstate, domainof, finalurl, interstitialpolicy, navwatchevent, parseratelimit, prefetchcandidates, preconnectorigins, rateallows, ratewindow, recordratehit } from \"./pagenet.js\";\n\nconst sessionduration = 15 * 60 * 1000;\nconst freshcheckkinds: ReadonlySet<string> = new Set([\"focus\", \"inspect\", \"click\", \"type\", \"scroll\", \"select\", \"hover\"]);\nconst pointerkinds: ReadonlySet<string> = new Set([\"movepointer\", \"clickpoint\", \"shiftclick\", \"clicktext\", \"clickaria\", \"clickname\", \"pierceshadow\"]);\nconst watchstepkinds: ReadonlySet<string> = new Set([\"watchmutate\", \"watchbanner\", \"watchfocus\"]);\nconst observationstepkinds: ReadonlySet<string> = new Set([\"a11ytree\", \"readvisible\", \"readertree\", \"detectlists\", \"detecttables\", \"readjson\", \"detectinfinitescroll\", \"detectvirtual\", \"detectlazy\", \"readscrollpos\", \"readlang\", \"readoutline\", \"countpages\", \"listshadow\", \"listframes\", \"classifypage\", \"fingerprintsection\", \"readselection\", \"detectsticky\", \"detectscrolllock\", \"readopengraph\", \"detectlanguage\", \"deriveselector\"]);\nconst navigationstepkinds: ReadonlySet<string> = new Set([\"openlink\", \"openprivate\", \"reloadcache\", \"stopnav\", \"waitload\", \"waiturl\", \"followlink\", \"spanav\", \"spawait\", \"rewritequery\", \"setfragment\", \"navlist\", \"navprofile\", \"detecthttp\", \"readredirects\", \"readfinalurl\", \"handleauth\", \"printpdf\", \"prefetch\", \"preconnect\", \"deeplink\", \"reopentab\", \"trailaudit\", \"pausenav\", \"navintent\", \"navrate\", \"openclipboard\", \"checksafe\", \"batchopen\"]);\nconst pausenavkinds: ReadonlySet<string> = new Set([\"openlink\", \"openprivate\", \"followlink\", \"spanav\", \"navlist\", \"openclipboard\", \"batchopen\", \"prefetch\", \"preconnect\", \"deeplink\", \"reopentab\"]);\nconst ratecheckedkinds: ReadonlySet<string> = new Set([\"openlink\", \"openprivate\", \"followlink\", \"spanav\", \"navlist\", \"openclipboard\", \"batchopen\", \"deeplink\", \"reopentab\"]);\n/** Internal evidence capture cadence for navigation records; not a policy cap on any reviewed value. */\nconst evidencepoll = 100;\n/** Internal evidence capture window used while a tab settles after a navigation; not a policy cap on any reviewed value. */\nconst evidencesettle = 5000;\n\nconst chromestorage = {\n async get<T>(key: string): Promise<T | undefined> { return (await chrome.storage.local.get(key))[key] as T | undefined; },\n async set<T>(key: string, value: T): Promise<void> { await chrome.storage.local.set({ [key]: value }); },\n};\nconst memory = new sessionmemory(chromestorage);\n\ntype stepoutput = { ok: boolean; summary: string; details?: Record<string, unknown> };\n\nfunction extensionpage(sender: chrome.runtime.MessageSender): boolean {\n return sender.id === chrome.runtime.id && Boolean(sender.url?.startsWith(chrome.runtime.getURL(\"\")));\n}\n\nasync function audit(kind: auditevent[\"kind\"], summary: string, extra: Partial<auditevent> = {}): Promise<void> {\n await memory.addaudi({ id: randomid(), kind, at: Date.now(), summary, ...extra });\n}\n\n/** Reads the reviewed options of a step without throwing on malformed payloads. */\nfunction stepoptions(step: toolstep): Record<string, unknown> {\n try { return parseoptions(step); } catch { return {}; }\n}\n\n/** Refreshes and persists the capability report negotiated through the permissions api. */\nasync function refreshcapabilities(): Promise<capabilityreport> {\n const report = await readcapabilities();\n await memory.setcapabilities(report);\n return report;\n}\n\nasync function activecontext(): Promise<{ tab: chrome.tabs.Tab; origin: string }> {\n const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });\n if (!tab?.id || !tab.url) throw new Error(\"No active web tab is available.\");\n const origin = new URL(tab.url).origin;\n if (!origin.startsWith(\"https://\")) throw new Error(\"Devthink can work with HTTPS pages only.\");\n return { tab, origin };\n}\n\nasync function snapshot(tabid: number): Promise<observation> {\n await chrome.scripting.executeScript({ target: { tabId: tabid }, files: [\"pagebridge.js\"] });\n const result = await chrome.scripting.executeScript({ target: { tabId: tabid }, func: () => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { capturesnapshot: () => observation } }).devthinkbridge;\n if (!bridge) throw new Error(\"Devthink page bridge is unavailable.\");\n return bridge.capturesnapshot();\n } });\n const value = result[0]?.result;\n if (!value) throw new Error(\"The page did not return an observation.\");\n const observationcapture = value as observation;\n const version = await memory.nextobservationversion();\n await memory.setobservation({ version, observation: observationcapture });\n return observationcapture;\n}\n\n/** Finds the reviewed dialog policy of a plan, if the user reviewed a dismissdialog step. */\nfunction plandialogpolicy(plan: agentplan | undefined): dialogpolicy | null {\n const step = plan?.steps.find(candidate => candidate.kind === \"dismissdialog\");\n return step ? parsedialogpolicy(step) : null;\n}\n\n/** Installs the reviewed dialog handler in the main world of one tab; the isolated world cannot override window dialogs. */\nasync function installdialogpolicy(tabid: number, policy: dialogpolicy, persistent: boolean): Promise<void> {\n await chrome.scripting.executeScript({\n target: { tabId: tabid },\n world: \"MAIN\",\n func: installdialoghandler,\n args: [policy.accept, policy.answer ?? \"\", persistent],\n });\n}\n\n/** Applies the reviewed dialog policy before any step dispatch so unexpected dialogs cannot block the page. */\nasync function ensuredialoghandler(plan: agentplan | undefined, tabid: number): Promise<void> {\n const policy = plandialogpolicy(plan) ?? await memory.getdialogpolicy();\n if (!policy) return;\n try { await installdialogpolicy(tabid, policy, true); } catch { /* the page may refuse scripting; the step still dispatches */ }\n}\n\n/** Reads observed dialogs from the page and records each as an audited dialog decision with the reviewed answer. */\nasync function harvestdialogs(session: agentsession | undefined, plan: agentplan | undefined, stepid: string, tabid: number): Promise<void> {\n const policy = plandialogpolicy(plan) ?? await memory.getdialogpolicy();\n let observed: observeddialog[] = [];\n try {\n const result = await chrome.scripting.executeScript({ target: { tabId: tabid }, func: () => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { readdialogs?: () => unknown[] } }).devthinkbridge;\n return bridge?.readdialogs ? bridge.readdialogs() : [];\n } });\n const value = result[0]?.result;\n if (Array.isArray(value)) observed = value as observeddialog[];\n } catch { /* the page may refuse scripting; no dialogs can be harvested */ }\n for (const entry of observed) {\n const reviewed = policy ? dialoganswer(policy, ([\"confirm\", \"alert\", \"prompt\"] as const).includes(entry.dialog as \"confirm\" | \"alert\" | \"prompt\") ? entry.dialog as \"confirm\" | \"alert\" | \"prompt\" : \"confirm\") : undefined;\n const decision: dialogdecision = {\n id: randomid(),\n dialog: entry.dialog,\n text: entry.text,\n accept: reviewed ? reviewed.accept : entry.result !== null && entry.result !== false,\n ...(reviewed?.answer !== undefined ? { answer: reviewed.answer } : {}),\n ...(session ? { sessionid: session.id } : {}),\n at: Number.isFinite(entry.at) ? entry.at : Date.now(),\n };\n await memory.adddialog(decision);\n await audit(\"dialog\", `Dialog ${decision.dialog} answered ${decision.accept ? \"accept\" : \"dismiss\"}${decision.answer ? ` with the reviewed answer \"${decision.answer}\"` : \"\"} for dialog text \"${decision.text.slice(0, 120)}\".`, { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid });\n }\n}\n\n/** Dispatches one reviewed page step through the page bridge after arming the reviewed dialog handler. */\nasync function dispatchpagestep(step: toolstep, tabid: number, origin: string, plan?: agentplan): Promise<stepoutput | undefined> {\n const session = await memory.getsession();\n const activeplan = plan ?? await memory.getplan();\n await ensuredialoghandler(activeplan, tabid);\n const result = await chrome.scripting.executeScript({ target: { tabId: tabid }, func: (action: toolstep, expectedorigin: string) => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { performstep: (input: toolstep, origin: string) => Promise<{ ok: boolean; summary: string; details?: Record<string, unknown> }> } }).devthinkbridge;\n if (!bridge) throw new Error(\"Devthink page bridge is unavailable.\");\n return bridge.performstep(action, expectedorigin);\n }, args: [step, origin] });\n await harvestdialogs(session, activeplan, step.id, tabid);\n return result[0]?.result as stepoutput | undefined;\n}\n\nasync function startsession(): Promise<agentsession> {\n const { tab, origin } = await activecontext();\n const session: agentsession = { id: randomid(), tabid: tab.id as number, origin, startedat: Date.now(), expiresat: Date.now() + sessionduration, grants: [origin] };\n await memory.setsession(session);\n await audit(\"session\", `Session started for ${origin}.`, { sessionid: session.id });\n const policy = await memory.getdialogpolicy();\n if (policy) {\n try { await installdialogpolicy(session.tabid, policy, true); } catch { /* the auto handler is best effort until the page accepts scripting */ }\n }\n return session;\n}\n\nasync function diagnostic(): Promise<diagnosticreport> {\n const session = await memory.getsession();\n const { tab, origin } = await activecontext();\n if (!session || session.stoppedat || session.expiresat <= Date.now() || session.tabid !== tab.id || session.origin !== origin) throw new Error(\"Start a current session for this active tab before diagnostics.\");\n const observation = await snapshot(session.tabid);\n const report: diagnosticreport = { id: randomid(), sessionid: session.id, origin, capturedat: Date.now(), tabid: session.tabid, title: observation.title, textlength: observation.textlength, interactivecount: observation.interactive.length, formcount: observation.forms.length, bridgeavailable: true };\n await memory.setdiagnostic(report);\n await audit(\"observe\", \"Structured diagnostics captured for the approved active tab.\", { sessionid: session.id });\n return report;\n}\n\nfunction localplan(objective: string, session: agentsession): agentplan {\n const now = Date.now();\n return { id: randomid(), objective, origin: session.origin, steps: [{ id: randomid(), kind: \"observe\", summary: \"Capture a complete semantic snapshot of the approved active tab.\", risk: \"read\" }], createdat: now, expiresat: now + sessionduration, state: \"pending\" };\n}\n\nasync function propose(objective: string, remote: boolean): Promise<agentplan> {\n if (!objective.trim()) throw new Error(\"An objective is required.\");\n const session = await memory.getsession();\n if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error(\"Start a current browser session before requesting a plan.\");\n const { tab, origin } = await activecontext();\n if (session.tabid !== tab.id || session.origin !== origin) throw new Error(\"The selected tab or origin no longer matches the approved session.\");\n const observation = await snapshot(session.tabid);\n const capabilities = await refreshcapabilities();\n const config = await memory.getconfig();\n let plan = localplan(objective.trim(), session);\n if (remote) {\n if (!config) throw new Error(\"Configure an approved HTTPS endpoint before requesting a remote proposal.\");\n const response = await fetch(config.endpoint, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, credentials: \"omit\", body: requestbody({ objective: objective.trim(), session, observation, capabilities }) });\n if (!response.ok) throw new Error(`Proposal endpoint returned ${response.status}.`);\n plan = parseproposal(await response.json(), session.origin).plan;\n }\n await memory.setplan(plan);\n await memory.setprogress(resetforplan(await memory.getprogress(), plan, Date.now()));\n await audit(\"proposal\", `Plan proposed with ${plan.steps.length} reviewed step${plan.steps.length === 1 ? \"\" : \"s\"}.`, { sessionid: session.id, planid: plan.id });\n return plan;\n}\n\nfunction browserauditkind(step: toolstep): auditevent[\"kind\"] {\n if (step.kind === \"downloadfile\") return \"download\";\n if (step.kind.startsWith(\"window\")) return \"window\";\n return \"tab\";\n}\n\n/** Maps one page step to its audit kind, covering the pointer, dialog, hold, retry, observation, watch, diff, navigation and tabs command event families. */\nfunction stepauditkind(step: toolstep, ok: boolean): auditevent[\"kind\"] {\n if (isbrowserkind(step.kind)) return browserauditkind(step);\n if (istabscommandkind(step.kind)) {\n if (step.kind === \"grouptabs\" || step.kind === \"colorgroup\" || step.kind === \"collapsegroup\") return \"group\";\n if (step.kind === \"savelayout\" || step.kind === \"restorelayout\" || step.kind === \"snapshotsession\" || step.kind === \"reopenrun\") return \"layout\";\n if (step.kind === \"discardtab\") return \"discard\";\n if (step.kind === \"badgetab\") return \"badge\";\n if (step.kind === \"watchtab\") return \"watch\";\n if (step.kind === \"maximizewindow\" || step.kind === \"minimizewindow\" || step.kind === \"restorewindow\" || step.kind === \"focuswindow\" || step.kind === \"scratchwindow\" || step.kind === \"incognitowindow\") return \"window\";\n return \"tab\";\n }\n if (step.kind === \"dismissdialog\") return \"dialog\";\n if (step.kind === \"keyhold\" || step.kind === \"keyrelease\") return \"hold\";\n if (step.kind === \"retryaction\") return \"retry\";\n if (pointerkinds.has(step.kind)) return \"pointer\";\n if (watchstepkinds.has(step.kind)) return \"watch\";\n if (step.kind === \"diffsnapshots\") return \"diff\";\n if (step.kind === \"readredirects\" || step.kind === \"readfinalurl\" || step.kind === \"detecthttp\") return \"redirect\";\n if (step.kind === \"handleauth\") return \"auth\";\n if (step.kind === \"prefetch\" || step.kind === \"preconnect\") return \"prefetch\";\n if (step.kind === \"navrate\") return \"rate\";\n if (navigationstepkinds.has(step.kind)) return \"navigation\";\n if (observationstepkinds.has(step.kind)) return \"observation\";\n return ok ? \"action\" : \"error\";\n}\n\n/** Resolves the reviewed inner step of a retry or frame wrapper from a step id or inline options. */\nfunction resolvedinnerstep(step: toolstep, plan: agentplan): toolstep | null {\n const options = stepoptions(step);\n if (typeof options.stepid === \"string\" && options.stepid.trim()) {\n return plan.steps.find(candidate => candidate.id === options.stepid) ?? null;\n }\n return innerstep(step);\n}\n\n/** Executes one reviewed key hold: the page dispatches the keydown and the registry keeps the hold across steps. */\nasync function executekeyhold(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const output = await dispatchpagestep(step, tabid, origin, plan);\n if (!output?.ok) return output ?? { ok: false, summary: \"The key hold was not delivered.\" };\n const options = stepoptions(step);\n const holdid = typeof options.holdid === \"string\" && options.holdid.trim() ? options.holdid : randomid();\n const modifiers = Array.isArray(options.modifiers) ? options.modifiers.filter((item): item is string => typeof item === \"string\") : [];\n const hold: keyholdstate = { holdid, key: step.value ?? \"\", ...(modifiers.length > 0 ? { modifiers } : {}), tabid, stepid: step.id, pressedat: Date.now() };\n const next = presshold(await memory.getholds(), hold);\n if (!next.ok) return { ok: false, summary: `Hold id ${holdid} is already held.` };\n await memory.setholds(next.holds);\n await audit(\"hold\", `Key ${hold.key} held under hold id ${holdid} pressed at ${new Date(hold.pressedat).toISOString()}.`, { ...(session ? { sessionid: session.id } : {}), planid: plan.id, stepid: step.id });\n return { ok: true, summary: `Key ${hold.key} held under hold id ${holdid}.`, details: { holdid } };\n}\n\n/** Executes one reviewed key release: the held key receives its keyup and the registry records the release. */\nasync function executekeyrelease(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const holdid = step.value ?? \"\";\n const holds = await memory.getholds();\n const held = holds.find(candidate => candidate.holdid === holdid && candidate.releasedat === undefined);\n if (!held) throw new Error(`No held key matches hold id ${holdid}.`);\n const modifiers = held.modifiers ?? [];\n const dispatchstep: toolstep = { ...step, value: held.key, options: JSON.stringify({ ...(modifiers.length > 0 ? { modifiers } : {}) }) };\n const output = await dispatchpagestep(dispatchstep, tabid, origin, plan);\n const releasedat = Date.now();\n const transition = releasehold(holds, holdid, releasedat);\n await memory.setholds(transition.holds);\n await audit(\"hold\", `Key ${held.key} released from hold id ${holdid} at ${new Date(releasedat).toISOString()} after ${Math.max(0, releasedat - held.pressedat)} milliseconds.`, { ...(session ? { sessionid: session.id } : {}), planid: plan.id, stepid: step.id });\n return { ok: output?.ok ?? false, summary: output?.summary ?? \"Key release delivered.\", details: { holdid } };\n}\n\n/** Executes one reviewed dismissdialog step: one-shot main world wrappers answer the next dialog per the reviewed policy. */\nasync function executedismissdialog(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const policy = parsedialogpolicy(step);\n if (!policy) throw new Error(\"A reviewed dialog policy is required.\");\n await installdialogpolicy(tabid, policy, false);\n await harvestdialogs(session, plan, step.id, tabid);\n const answer = policy.answer !== undefined ? ` with the reviewed answer \"${policy.answer}\"` : \"\";\n return { ok: true, summary: `Dialog handler armed${answer} for the next confirm, alert or prompt.` };\n}\n\n/** Executes one reviewed retryaction step: the loop enforces the reviewed bounds, revalidates geometry between attempts and records the outcome. */\nasync function executeretryaction(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const rule = stepoptions(step).retryrule as retryrule | undefined;\n const inner = resolvedinnerstep(step, plan);\n if (!inner) throw new Error(\"The reviewed wrapper step could not be resolved.\");\n const innergate = validatestep(inner, origin);\n if (!innergate.allowed) throw new Error(`The wrapped step is not allowed: ${innergate.reason}`);\n const probe = async (): Promise<{ x: number; y: number } | null> => {\n const probestep: toolstep = { id: `${step.id}probe`, kind: \"readgeometry\", summary: step.summary, risk: \"read\", ...(inner.target ? { target: inner.target } : {}), ...(inner.options ? { options: inner.options } : {}) };\n const output = await dispatchpagestep(probestep, tabid, origin, plan);\n const geometry = output?.details?.geometry as { x?: unknown; y?: unknown } | undefined;\n if (!geometry || typeof geometry.x !== \"number\" || typeof geometry.y !== \"number\" || !Number.isFinite(geometry.x) || !Number.isFinite(geometry.y)) return null;\n return { x: geometry.x, y: geometry.y };\n };\n const execute = async (): Promise<{ ok: boolean; summary: string }> => {\n const output = await dispatchpagestep(inner, tabid, origin, plan);\n return { ok: Boolean(output?.ok), summary: output?.summary ?? \"The wrapped step returned no result.\" };\n };\n const outcome = await runretries(rule ?? { attempts: 1 }, probe, execute);\n const record: retryoutcome = { stepid: step.id, attempts: outcome.attempts, movement: outcome.movement, ok: outcome.ok, at: Date.now() };\n await memory.addretry(record);\n await audit(\"retry\", outcome.summary, { ...(session ? { sessionid: session.id } : {}), planid: plan.id, stepid: step.id });\n return { ok: outcome.ok, summary: outcome.summary, details: { attempts: outcome.attempts, movement: outcome.movement } };\n}\n\n/** Executes one reviewed mapclicks step: the page builds the numbered map and memory stores it under a fresh observation version. */\nasync function executemapclicks(step: toolstep, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const output = await dispatchpagestep(step, tabid, origin, plan);\n if (!output?.ok) return output ?? { ok: false, summary: \"The clickable map was not captured.\" };\n const entries = Array.isArray(output.details?.entries) ? output.details?.entries as mapentry[] : [];\n const version = await memory.nextobservationversion();\n const map: clickablemap = { version, entries, builtat: Date.now() };\n await memory.setmap(map);\n return { ok: true, summary: output.summary, details: { entries, mapversion: version } };\n}\n\n/** Executes one reviewed enterframe step: the background resolves the wrapped step and the bridge routes it inside the same origin frame. */\nasync function executeenterframe(step: toolstep, plan: agentplan, tabid: number, origin: string): Promise<stepoutput | undefined> {\n const inner = resolvedinnerstep(step, plan);\n if (!inner) throw new Error(\"The reviewed frame wrapper step could not be resolved.\");\n const innergate = validatestep(inner, origin);\n if (!innergate.allowed) throw new Error(`The wrapped step is not allowed: ${innergate.reason}`);\n const options = stepoptions(step);\n const inneroptions = inner.options ? stepoptions(inner) : undefined;\n const derived: toolstep = { ...step, options: JSON.stringify({ ...options, kind: inner.kind, ...(inner.target ? { target: inner.target } : {}), ...(inner.value ? { value: inner.value } : {}), ...(inneroptions ? { options: inneroptions } : {}) }) };\n return dispatchpagestep(derived, tabid, origin, plan);\n}\n\n/** Converts one observation interactive inventory into the node summaries the diff engine compares. */\nfunction observationnodes(observationcapture: observation): nodesummary[] {\n return observationcapture.interactive.map(entry => ({ selector: entry.selector, tag: entry.role, text: entry.label, attributes: {} }));\n}\n\nfunction detailarray(details: Record<string, unknown> | undefined, key: string): unknown[] {\n const value = details?.[key];\n return Array.isArray(value) ? value : [];\n}\n\n/** Executes one reviewed diffsnapshots step: the background loads both observation versions, injects their node summaries and attaches the version pair to the diff result. */\nasync function executediffsnapshots(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n const options = stepoptions(step);\n const versions = Array.isArray(options.versions) ? options.versions.filter((item): item is number => typeof item === \"number\") : [];\n const baseversion = versions[0];\n const targetversion = versions[1];\n if (baseversion === undefined || targetversion === undefined) throw new Error(\"Two reviewed observation versions are required.\");\n const base = await memory.getobservation(baseversion);\n const target = await memory.getobservation(targetversion);\n if (!base || !target) throw new Error(\"A reviewed observation version has not been captured yet.\");\n const derived: toolstep = { ...step, options: JSON.stringify({ ...options, base: observationnodes(base.observation), target: observationnodes(target.observation) }) };\n const output = await dispatchpagestep(derived, tabid, origin, plan) ?? { ok: false, summary: \"The snapshot diff returned no result.\" };\n const diff: snapshotdiff = {\n baseversion,\n targetversion,\n added: detailarray(output.details, \"added\") as diffentry[],\n removed: detailarray(output.details, \"removed\") as diffentry[],\n changed: detailarray(output.details, \"changed\") as diffentry[],\n at: Date.now(),\n };\n await memory.adddiff(diff);\n await audit(\"diff\", `Diffed observation versions ${baseversion} and ${targetversion}: ${diff.added.length} added, ${diff.removed.length} removed and ${diff.changed.length} changed nodes.`, { ...(session ? { sessionid: session.id } : {}), planid: plan.id, stepid: step.id });\n return { ok: Boolean(output.ok), summary: output.summary, details: { ...(output.details ?? {}), versions: [baseversion, targetversion] } };\n}\n\n/** Executes one reviewed watch step: the registration persists across service worker restarts, the bridge observes for the reviewed lifetime and the observed events land in the step result stream. */\nasync function executewatchstep(step: toolstep, session: agentsession, plan: agentplan, tabid: number, origin: string): Promise<{ output: stepoutput; watch: watchregistration }> {\n const options = stepoptions(step);\n const watchid = typeof options.watchid === \"string\" && options.watchid.trim() ? options.watchid : randomid();\n const scopes = Array.isArray(options.scopes) ? options.scopes.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const events = Array.isArray(options.events) ? options.events.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const lifetime = typeof options.lifetime === \"number\" && Number.isFinite(options.lifetime) && options.lifetime > 0 ? options.lifetime : 0;\n const watch: watchregistration = { watchid, kind: step.kind, stepid: step.id, sessionid: session.id, origin, scopes, events, startedat: Date.now(), lifetime };\n await memory.addwatch(watch);\n await audit(\"watch\", `Watch ${step.kind} registered under id ${watchid} for the reviewed lifetime of ${lifetime} milliseconds inside ${scopes.length > 0 ? `scopes ${scopes.join(\", \")}` : \"the whole document\"}.`, { sessionid: session.id, planid: plan.id, stepid: step.id });\n const output = await dispatchpagestep(step, tabid, origin, plan) ?? { ok: false, summary: \"The watch returned no result.\" };\n await memory.closewatch(watchid, Date.now());\n if (step.kind === \"watchmutate\") {\n for (const entry of detailarray(output.details, \"events\")) {\n if (!entry || typeof entry !== \"object\") continue;\n const record = entry as mutationevent;\n await memory.addmutationevent({ ...record, sessionid: session.id });\n }\n }\n if (step.kind === \"watchfocus\") {\n for (const entry of detailarray(output.details, \"events\")) {\n if (!entry || typeof entry !== \"object\") continue;\n const record = entry as focusevent;\n await memory.addfocusevent({ ...record, sessionid: session.id });\n }\n }\n if (step.kind === \"watchbanner\") {\n for (const entry of detailarray(output.details, \"banners\")) {\n if (!entry || typeof entry !== \"object\") continue;\n const record = entry as bannerreport;\n await memory.addbanner({ ...record, sessionid: session.id });\n }\n }\n await audit(\"watch\", `Watch ${watchid} closed after its reviewed lifetime of ${lifetime} milliseconds.`, { sessionid: session.id, planid: plan.id, stepid: step.id });\n return { output, watch };\n}\n\n/** Refreshes the live page signals of language, template, scroll lock and banner state from observation step evidence. */\nasync function refreshsignals(step: toolstep, output: stepoutput | undefined): Promise<void> {\n const current = await memory.getsignals();\n const next: pagesignals = current ? { ...current, refreshedat: Date.now() } : { refreshedat: Date.now() };\n let changed = false;\n if (step.kind === \"readlang\" || step.kind === \"detectlanguage\") {\n const language = output?.details?.language;\n if (typeof language === \"string\" && language) { next.language = language; changed = true; }\n }\n if (step.kind === \"classifypage\") {\n const template = output?.details?.template;\n if (typeof template === \"string\" && template) { next.template = template; changed = true; }\n }\n if (step.kind === \"detectscrolllock\") {\n const locked = output?.details?.locked;\n if (typeof locked === \"boolean\") { next.scrolllocked = locked; changed = true; }\n }\n if (step.kind === \"watchbanner\") {\n const banners = detailarray(output?.details, \"banners\");\n const first = banners[0] as { kind?: unknown } | undefined;\n if (first && typeof first.kind === \"string\") { next.banner = first.kind; changed = true; }\n }\n if (changed) await memory.setsignals(next);\n}\n\n/** Records the observation evidence of one executed page step: a11y trees, reader articles, template profiles and derived selectors. */\nasync function recordevidence(step: toolstep, output: stepoutput | undefined, session: agentsession | undefined, plan: agentplan | undefined, origin: string): Promise<void> {\n const extra = { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid: step.id };\n if (step.kind === \"a11ytree\" && output?.details?.tree && typeof output.details.tree === \"object\") {\n const version = await memory.nextobservationversion();\n await memory.adda11ytree({ version, tree: output.details.tree as a11ynode, capturedat: Date.now() });\n await audit(\"observation\", `Accessibility tree captured under observation version ${version} with ${output.details.nodecount ?? \"an unknown count of\"} nodes.`, extra);\n }\n if (step.kind === \"readertree\" && output?.details?.article && typeof output.details.article === \"object\") {\n const version = await memory.nextobservationversion();\n const article = output.details.article as readerarticle;\n await memory.addreaderarticle({ version, article, capturedat: Date.now() });\n await audit(\"observation\", `Reader article captured under observation version ${version} with ${article.blocks.length} blocks and ${article.words} words.`, extra);\n }\n if (step.kind === \"classifypage\" && typeof output?.details?.template === \"string\") {\n const fingerprint = typeof output.details.fingerprint === \"string\" ? output.details.fingerprint : \"\";\n const profile: templateprofile = { origin, template: output.details.template, fingerprint, at: Date.now() };\n await memory.addtemplate(profile);\n await audit(\"observation\", `Page template ${profile.template} classified for ${origin}${fingerprint ? ` with fingerprint ${fingerprint}` : \"\"}.`, extra);\n }\n if (step.kind === \"fingerprintsection\" && typeof output?.details?.fingerprint === \"string\") {\n const profile: templateprofile = { origin, template: \"\", fingerprint: output.details.fingerprint, ...(typeof output.details.section === \"string\" ? { section: output.details.section } : {}), at: Date.now() };\n await memory.addtemplate(profile);\n await audit(\"observation\", `Section fingerprint ${profile.fingerprint} computed for ${origin}.`, extra);\n }\n if (step.kind === \"deriveselector\") {\n const candidates = detailarray(output?.details, \"candidates\") as selectorcandidate[];\n const best = candidates[0];\n if (best && typeof best.selector === \"string\" && best.selector) {\n const record: derivedselector = { stepid: step.id, selector: best.selector, strategy: best.strategy, score: best.score, at: Date.now() };\n await memory.addselector(record);\n await audit(\"observation\", `Derived selector ${record.selector} through the ${record.strategy} strategy with stability ${record.score}.`, extra);\n }\n }\n await refreshsignals(step, output);\n}\n\n/** Live navigation watch buffers per tab, rebuilt on every new navigation of the tab. */\nconst navbuffers = new Map<number, navwatchevent[]>();\n/** Last known urls per tab so closed tabs can be remembered for reopentab steps. */\nconst lastknownurls = new Map<number, string>();\n\n/** Tracks one tab update into the navigation watch buffer, the spa route trail, the last known url and the live title memory. */\nasync function tracktabupdate(tabid: number, changeinfo: { url?: string; status?: string; title?: string }): Promise<void> {\n const now = Date.now();\n const url = typeof changeinfo.url === \"string\" ? changeinfo.url : undefined;\n const status = changeinfo.status;\n if (typeof changeinfo.title === \"string\" && changeinfo.title) {\n lastknowntitles.set(tabid, changeinfo.title);\n await recordtabwatchevent(\"title\", tabid, changeinfo.title);\n }\n const previous = lastknownurls.get(tabid);\n if (status === \"loading\" && url) {\n navbuffers.set(tabid, [{ event: \"beforenavigate\", url, timestamp: now }]);\n lastknownurls.set(tabid, url);\n return;\n }\n const buffer = navbuffers.get(tabid) ?? [];\n if (url) {\n const kind = classifynavchange(previous ?? url, url, status);\n buffer.push({ event: kind === \"route\" ? \"urlchange\" : \"committed\", url, timestamp: now, redirect: kind === \"route\" });\n if (kind === \"route\" && previous) {\n const session = await memory.getsession();\n if (session && !session.stoppedat && session.tabid === tabid) {\n await memory.addtrailentry(session.id, { url, title: \"\", at: now });\n }\n }\n lastknownurls.set(tabid, url);\n }\n if (status === \"complete\") buffer.push({ event: \"completed\", url: lastknownurls.get(tabid) ?? \"\", timestamp: now, status: 200 });\n navbuffers.set(tabid, buffer);\n}\n\nchrome.tabs.onUpdated.addListener((tabid, changeinfo) => { void tracktabupdate(tabid, changeinfo); });\n\n/** Records the activation of a tab into every live watchtab registration. */\nchrome.tabs.onActivated.addListener(activeinfo => { void recordtabwatchevent(\"activated\", activeinfo.tabId); });\n\n/** Remembers the last known url and title of a closed tab so restoretab and reopenrun can restore it. */\nchrome.tabs.onRemoved.addListener(tabid => {\n const url = lastknownurls.get(tabid);\n const title = lastknowntitles.get(tabid) ?? \"\";\n const windowid = 0;\n if (url) {\n void memory.addrecenttab({ url, tabid, closedat: Date.now() });\n void memory.addclosedtab({ url, title, tabid, windowid, closedat: Date.now() });\n }\n void recordtabwatchevent(\"closed\", tabid, url);\n lastknownurls.delete(tabid);\n lastknowntitles.delete(tabid);\n navbuffers.delete(tabid);\n});\n\n/** Records one completed navigation: the redirect chain from the watch buffer, the final url, the per tab state and the navigation trail entry. */\nasync function recordnavigation(step: toolstep, session: agentsession | undefined, tabid: number): Promise<navrecord> {\n const started = Date.now();\n let tab = await chrome.tabs.get(tabid).catch(() => undefined);\n while (tab && tab.status !== \"complete\" && Date.now() - started < evidencesettle) {\n await new Promise(resolve => setTimeout(resolve, evidencepoll));\n tab = await chrome.tabs.get(tabid).catch(() => undefined);\n }\n const url = tab?.url ?? lastknownurls.get(tabid) ?? \"\";\n const title = tab?.title ?? \"\";\n const chain = buildredirectchain(navbuffers.get(tabid) ?? []);\n const record: navrecord = {\n stepid: step.id,\n ...(session ? { sessionid: session.id } : {}),\n origin: session?.origin ?? (url ? new URL(url).origin : \"\"),\n finalurl: finalurl(chain) || url,\n chain,\n at: Date.now(),\n };\n await memory.addnavrecord(record);\n await memory.setnavstate(tabid, record);\n if (session && url) await memory.addtrailentry(session.id, { url, title, stepid: step.id, at: Date.now() });\n return record;\n}\n\n/** Appends the session origin grants to the options of a page navigation step so the bridge can refuse out-of-grant links. */\nfunction injectallowedorigins(step: toolstep, session: agentsession | undefined): toolstep {\n const allowedorigins = session?.grants ?? (session ? [session.origin] : []);\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n return { ...step, options: JSON.stringify({ ...options, allowedorigins }) };\n}\n\n/** Enforces the reviewed per domain navigation rate limit before one navigation runs. */\nasync function enforceratelimit(url: string, stepid: string, sessionid: string | undefined): Promise<void> {\n const domain = domainof(url);\n if (!domain) return;\n const states = await memory.getratestates();\n const stored = states.find(item => item.domain === domain);\n if (!stored) return;\n const live = ratewindow(stored, stored.limit, Date.now());\n const decision = rateallows(live, Date.now());\n if (!decision.allowed) {\n await audit(\"rate\", `The navigation rate limit of ${live.limit.ceiling} per ${live.limit.window} milliseconds for ${domain} was exceeded; the navigation was refused.`, { ...(sessionid ? { sessionid } : {}), stepid });\n throw new Error(`The navigation rate limit for ${domain} has been reached; retry after ${Math.ceil(decision.retryafter / 1000)} seconds.`);\n }\n await memory.setratestate(recordratehit(live, Date.now()));\n await audit(\"rate\", `Navigation to ${url} counted against the reviewed rate limit of ${live.limit.ceiling} per ${live.limit.window} milliseconds for ${domain}; ${decision.remaining - 1} remaining.`, { ...(sessionid ? { sessionid } : {}), stepid });\n}\n\n/** Refuses navigation while the reviewed navigation pause is armed for an open consent prompt. */\nasync function refusenavpause(step: toolstep): Promise<void> {\n if (!pausenavkinds.has(step.kind)) return;\n const control = await memory.getnavcontrol();\n if (control?.pausedat) throw new Error(control.reason ? `Navigation is paused: ${control.reason}` : \"Navigation is paused while a consent prompt is open; resume navigation first.\");\n}\n\n/** Opens one reviewed navigation target in its resolved container across tabs, windows and private profiles. */\nasync function opencontainer(step: toolstep, session: agentsession | undefined, url: string, container: \"current\" | \"tab\" | \"window\" | \"private\", position: \"adjacent\" | \"end\"): Promise<stepoutput> {\n const windows = await chrome.windows.getAll().catch(() => [] as Array<{ id?: number; incognito?: boolean; focused?: boolean }>);\n const plan = resolvecontainer({ url, container, position, private: container === \"private\" }, windows.map(item => ({ id: item.id ?? 0, incognito: item.incognito ?? false, focused: item.focused ?? false })));\n const extra = { ...(session ? { sessionid: session.id } : {}), stepid: step.id };\n if (plan.kind === \"current\" && session) {\n const tabid = session.tabid;\n await chrome.tabs.update(tabid, { url });\n const record = await recordnavigation(step, session, tabid);\n await audit(\"navigation\", `Navigated the task tab to ${url}.`, extra);\n return { ok: true, summary: `Navigated the task tab to ${url}.`, details: { container: plan.kind, url, finalurl: record.finalurl, hops: record.chain.hops.length } };\n }\n if (plan.kind === \"private\" || plan.kind === \"window\") {\n const created = await chrome.windows.create({ url, incognito: plan.incognito });\n await audit(\"navigation\", `Opened ${plan.kind === \"private\" ? \"a private window\" : \"a new window\"} for ${url}${plan.kind === \"private\" ? \" separated from normal windows\" : \"\"}.`, extra);\n return { ok: true, summary: `Opened ${plan.kind === \"private\" ? \"a private window\" : \"a new window\"} for ${url}.`, details: { container: plan.kind, url, windowid: created?.id ?? 0, incognito: plan.incognito } };\n }\n const created = await chrome.tabs.create({ url, ...(plan.windowid !== undefined ? { windowId: plan.windowid } : {}), active: true });\n await audit(\"navigation\", `Opened a new tab for ${url} without leaving the current page.`, extra);\n return { ok: true, summary: `Opened a new tab for ${url}.`, details: { container: \"tab\", url, tabid: created?.id ?? 0, position: plan.position } };\n}\n\n/** Verifies one url against the session grants and the stored checksafe verdicts before it opens. */\nasync function verifyopenurl(url: string, session: agentsession | undefined): Promise<void> {\n const grants = session?.grants ?? (session ? [session.origin] : []);\n const verified = originverified(url, grants, await memory.getsafeties());\n if (!verified.allowed) throw new Error(verified.reason);\n}\n\n/** Executes one reviewed openlink or openprivate step from its navtarget container. */\nasync function executeopenlink(step: toolstep, session: agentsession | undefined): Promise<stepoutput> {\n const target = parsenavtarget(step);\n if (!target) throw new Error(\"A reviewed navtarget is required.\");\n await refusenavpause(step);\n await enforceratelimit(target.url, step.id, session?.id);\n await verifyopenurl(target.url, session);\n return opencontainer(step, session, target.url, target.container, target.position ?? \"adjacent\");\n}\n\n/** Executes one reviewed deeplink step by building the deep link and opening it in the reviewed container. */\nasync function executedeeplink(step: toolstep, session: agentsession | undefined): Promise<stepoutput> {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const params: Record<string, string> = {};\n if (options.params && typeof options.params === \"object\" && !Array.isArray(options.params)) {\n for (const [name, value] of Object.entries(options.params as Record<string, unknown>)) if (typeof value === \"string\") params[name] = value;\n }\n const url = deeplinkurl(typeof options.app === \"string\" ? options.app : \"\", params);\n if (!url) throw new Error(\"The reviewed deep link pattern is not a known web app.\");\n await refusenavpause(step);\n await enforceratelimit(url, step.id, session?.id);\n await verifyopenurl(url, session);\n const target = parsenavtarget(step);\n const container = target?.container === \"window\" ? \"window\" : target?.container === \"private\" ? \"private\" : target?.container === \"current\" ? \"current\" : \"tab\";\n const output = await opencontainer(step, session, url, container, target?.position ?? \"adjacent\");\n return { ...output, details: { ...(output.details ?? {}), app: options.app, deeplink: url } };\n}\n\n/** Executes one reviewed reopentab step: the most recently closed tab url is restored in a new tab. */\nasync function executereopentab(step: toolstep, session: agentsession | undefined): Promise<stepoutput> {\n await refusenavpause(step);\n let url = step.value;\n if (!url) {\n const tabs = await chrome.tabs.query({}).catch(() => [] as Array<{ url?: string }>);\n const openurls = tabs.map(tab => tab.url ?? \"\").filter(Boolean);\n const recent = pickrecenttab(await memory.getrecenttabs(), openurls);\n if (!recent) throw new Error(\"No recently closed tab is available to reopen.\");\n url = recent.url;\n }\n await enforceratelimit(url, step.id, session?.id);\n await verifyopenurl(url, session);\n const created = await chrome.tabs.create({ url, active: true });\n await audit(\"navigation\", `Reopened the recently closed tab ${url}.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: true, summary: `Reopened ${url} in a new tab.`, details: { url, tabid: created?.id ?? 0 } };\n}\n\n/** Waits until one tab reports the complete load status, bounded by the internal evidence window. */\nasync function waitforcomplete(tabid: number): Promise<boolean> {\n const started = Date.now();\n for (;;) {\n const tab = await chrome.tabs.get(tabid).catch(() => undefined);\n if (!tab) return false;\n if (tab.status === \"complete\") return true;\n if (Date.now() - started >= evidencesettle) return false;\n await new Promise(resolve => setTimeout(resolve, evidencepoll));\n }\n}\n\n/** Records one navlist entry completion in the plan progress. */\nasync function recordnaventryoutcome(step: toolstep, plan: agentplan, entry: { index: number; url: string; ok: boolean }): Promise<void> {\n const base = await memory.getprogress();\n await memory.setprogress(recordnaventry(base, plan.id, step.id, entry, Date.now()));\n}\n\n/** Executes one reviewed navlist step: the reviewed urls are navigated sequentially, each entry recorded as it completes. */\nasync function executenavlist(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number): Promise<stepoutput> {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const urls = Array.isArray(options.urls) ? options.urls.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n if (urls.length === 0) throw new Error(\"A reviewed list of navigation urls is required.\");\n await refusenavpause(step);\n let completed = 0;\n let failed = \"\";\n for (let index = 0; index < urls.length; index += 1) {\n const url = urls[index] as string;\n const entrygate = navigationgranted(session, url);\n if (!entrygate.allowed) {\n failed = entrygate.reason ?? \"The navigation list entry was refused.\";\n await recordnaventryoutcome(step, plan, { index, url, ok: false });\n break;\n }\n try {\n await enforceratelimit(url, step.id, session?.id);\n await refusenavpause(step);\n await chrome.tabs.update(tabid, { url });\n await waitforcomplete(tabid);\n await recordnavigation(step, session, tabid);\n completed += 1;\n await recordnaventryoutcome(step, plan, { index, url, ok: true });\n } catch (error) {\n failed = error instanceof Error ? error.message : String(error);\n await recordnaventryoutcome(step, plan, { index, url, ok: false });\n break;\n }\n }\n const remaining = urls.length - completed;\n const ok = failed === \"\" && completed === urls.length;\n return {\n ok,\n summary: ok\n ? `Navigated the reviewed list of ${urls.length} url${urls.length === 1 ? \"\" : \"s\"} sequentially.`\n : `The navigation list stopped after ${completed} of ${urls.length} entries: ${failed}`,\n details: { completed, remaining, urls },\n };\n}\n\n/** Applies one reviewed per site wait profile during navigation and stores it per origin for the following steps. */\nasync function executenavprofile(step: toolstep, session: agentsession | undefined, origin: string): Promise<stepoutput> {\n const profile = parsewaitprofile(step);\n if (!profile) throw new Error(\"A reviewed waitprofile is required.\");\n const record: waitprofilerecord = { origin, profile, at: Date.now() };\n await memory.setwaitprofile(record);\n const effective = profilefororigin(profile, origin);\n await audit(\"navigation\", `Wait profile applied for ${origin} with signals ${effective.signals.join(\", \")}${effective.idle > 0 ? `, idle ${effective.idle}ms` : \"\"}${effective.timeout > 0 ? ` and timeout ${effective.timeout}ms` : \"\"}.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: true, summary: `Applied the reviewed wait profile for ${origin} during navigation.`, details: { origin, signals: effective.signals, idle: effective.idle, timeout: effective.timeout, overrides: (profile.overrides ?? []).map(override => override.origin) } };\n}\n\n/** Detects the http error, offline and certificate interstitial states of the session tab. */\nasync function executedetecthttp(session: agentsession | undefined, tabid: number): Promise<stepoutput> {\n const records = await memory.getnavrecords();\n const buffer = navbuffers.get(tabid) ?? [];\n const errors = buffer.filter(event => event.error !== undefined).map(event => event.error as string);\n const statuses = (records[0]?.chain.hops ?? []).map(hop => hop.status).filter(status => status > 0);\n const state = detecthttpstate({ offline: !navigator.onLine, errors, statuses });\n const policy = interstitialpolicy(state);\n return {\n ok: true,\n summary: state.httperror || state.offline\n ? `Detected ${state.reasons.length} navigation problem${state.reasons.length === 1 ? \"\" : \"s\"}: ${state.reasons.join(\"; \")}.`\n : \"No http error, offline state or certificate interstitial was detected.\",\n details: { httperror: state.httperror, offline: state.offline, certificate: state.certificate, reasons: state.reasons, interstitial: policy.interstitial, bypass: policy.bypass, guidance: policy.guidance },\n };\n}\n\n/** Returns the redirect chain of the latest navigation step with its statuses and timing. */\nasync function executereadredirects(session: agentsession | undefined): Promise<stepoutput> {\n const record = (await memory.getnavrecords()).find(item => !session || item.sessionid === session.id);\n if (!record) return { ok: false, summary: \"No navigation has been recorded yet.\", details: { chain: { hops: [], startedat: 0, endedat: 0 } } };\n return { ok: true, summary: `The latest navigation travelled ${Math.max(0, record.chain.hops.length - 1)} redirect${record.chain.hops.length - 1 === 1 ? \"\" : \"s\"} to ${record.finalurl}.`, details: { chain: record.chain, finalurl: record.finalurl, duration: record.chain.endedat - record.chain.startedat } };\n}\n\n/** Captures the final url after redirects of the latest navigation step. */\nasync function executereadfinalurl(session: agentsession | undefined): Promise<stepoutput> {\n const record = (await memory.getnavrecords()).find(item => !session || item.sessionid === session.id);\n if (!record) return { ok: false, summary: \"No navigation has been recorded yet.\", details: { finalurl: \"\" } };\n return { ok: true, summary: `The final url after redirects is ${record.finalurl}.`, details: { finalurl: record.finalurl, hops: record.chain.hops } };\n}\n\n/** Answers a basic auth prompt from stored reviewed credentials; the flow refuses to run without them. */\nasync function executehandleauth(step: toolstep, session: agentsession | undefined): Promise<stepoutput> {\n const auths = await memory.getauths();\n const record = authfor(auths, step.value ?? \"\");\n if (!record) throw new Error(`No reviewed basic auth credentials are stored for ${step.value ?? \"\"}; store them from the side panel first.`);\n await audit(\"auth\", `Basic auth credentials for ${record.origin} reviewed as ${record.username} were armed for the auth prompt; the password stays out of every step detail.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: true, summary: `Armed the reviewed basic auth credentials of ${record.username} for ${record.origin}.`, details: { origin: record.origin, username: record.username, reviewedat: record.reviewedat, armed: true } };\n}\n\n/** Prints the page through the browser print pipeline and routes the artifact record into the task artifact store. */\nasync function executeprintpdf(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const output = await dispatchpagestep(step, tabid, origin, plan);\n const name = typeof options.name === \"string\" && options.name ? options.name : `${step.id}.pdf`;\n const artifact: artifactrecord = { id: randomid(), kind: \"printpdf\", name, stepid: step.id, at: Date.now() };\n await memory.addartifact(artifact);\n await audit(\"navigation\", `Printed the page to pdf through the browser print pipeline and routed the artifact ${name} into the task artifact store.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: output?.ok ?? false, summary: output?.summary ?? \"The print pipeline returned no result.\", details: { ...(output?.details ?? {}), artifact } };\n}\n\n/** Verifies the prefetch candidates against the session grants and queues the granted ones as page hints. */\nasync function executeprefetch(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const urls = Array.isArray(options.urls) ? options.urls.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const grants = session?.grants ?? (session ? [session.origin] : []);\n const verdict = prefetchcandidates(urls, grants);\n if (verdict.allowed.length === 0) throw new Error(\"No prefetch candidate is covered by the session grants.\");\n await refusenavpause(step);\n const derived: toolstep = { ...step, options: JSON.stringify({ ...options, urls: verdict.allowed }) };\n const output = await dispatchpagestep(derived, tabid, origin, plan);\n await memory.setnavqueues({ prefetch: verdict.allowed.length, batchopen: (await memory.getnavqueues())?.batchopen ?? 0, updatedat: Date.now() });\n await refreshbadge();\n await audit(\"prefetch\", `Prefetched ${verdict.allowed.length} predicted next page${verdict.allowed.length === 1 ? \"\" : \"s\"} verified against the session grants${verdict.refused.length > 0 ? ` and refused ${verdict.refused.length} candidate${verdict.refused.length === 1 ? \"\" : \"s\"} outside the grants` : \"\"}.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: Boolean(output?.ok), summary: output?.summary ?? \"The prefetch step returned no result.\", details: { ...(output?.details ?? {}), allowed: verdict.allowed, refused: verdict.refused } };\n}\n\n/** Preconnects to the reviewed expected origins. */\nasync function executepreconnect(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const origins = preconnectorigins(Array.isArray(options.origins) ? options.origins.filter((item): item is string => typeof item === \"string\") : []);\n await refusenavpause(step);\n const output = await dispatchpagestep({ ...step, options: JSON.stringify({ ...options, origins }) }, tabid, origin, plan);\n await audit(\"prefetch\", `Preconnected to ${origins.length} expected origin${origins.length === 1 ? \"\" : \"s\"}: ${origins.join(\", \")}.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: Boolean(output?.ok), summary: output?.summary ?? \"The preconnect step returned no result.\", details: { ...(output?.details ?? {}), origins } };\n}\n\n/** Opens a url read from the clipboard on the explicit consent of the approved step. */\nasync function executeopenclipboard(step: toolstep, session: agentsession | undefined): Promise<stepoutput> {\n await refusenavpause(step);\n const text = await navigator.clipboard.readText();\n let url = \"\";\n try { url = new URL(text.trim()).toString(); } catch { throw new Error(\"The clipboard does not hold a valid url.\"); }\n if (!url.startsWith(\"https://\")) throw new Error(\"The clipboard url must use HTTPS.\");\n await enforceratelimit(url, step.id, session?.id);\n await verifyopenurl(url, session);\n const output = await opencontainer(step, session, url, \"tab\", \"adjacent\");\n await audit(\"navigation\", `Opened the clipboard url ${url} on the explicit consent of the reviewed step.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ...output, details: { ...(output.details ?? {}), url } };\n}\n\n/** Verifies one url for safety and stores the verdict for review. */\nasync function executechecksafe(step: toolstep, session: agentsession | undefined, planid: string | undefined): Promise<stepoutput> {\n const verdict = { ...checksafe(step.value ?? \"\"), at: Date.now() };\n await memory.addsafety(verdict);\n await audit(\"navigation\", `Safety check of ${verdict.url} returned ${verdict.safe ? \"safe\" : \"unsafe\"}${verdict.reasons.length > 0 ? `: ${verdict.reasons.join(\"; \")}` : \"\"}.`, { ...(session ? { sessionid: session.id } : {}), ...(planid ? { planid } : {}), stepid: step.id });\n return { ok: true, summary: verdict.safe ? `The url ${verdict.url} passed every safety check.` : `The url ${verdict.url} is unsafe: ${verdict.reasons.join(\"; \")}.`, details: { verdict } };\n}\n\n/** Opens one curated link list with per url safety checks; any unsafe url refuses the whole batch. */\nasync function executebatchopen(step: toolstep, session: agentsession | undefined): Promise<stepoutput> {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const urls = Array.isArray(options.urls) ? options.urls.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const links: curatedlink[] = curatelinks(urls, url => ({ ...checksafe(url), at: Date.now() }));\n const curated: curatedlist = { id: randomid(), links, at: Date.now() };\n await memory.addcurated(curated);\n const set = batchopenset(links);\n if (set.refused.length > 0) {\n await memory.setnavqueues({ prefetch: (await memory.getnavqueues())?.prefetch ?? 0, batchopen: set.refused.length, updatedat: Date.now() });\n await refreshbadge();\n await audit(\"navigation\", `Batch open refused for ${set.refused.length} unsafe url${set.refused.length === 1 ? \"\" : \"s\"}; the curated list waits for review.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: false, summary: `The batch was refused because ${set.refused.length} of ${links.length} urls are unsafe; review the curated list before opening.`, details: { curated, refused: set.refused } };\n }\n await refusenavpause(step);\n const opened: number[] = [];\n for (const url of set.open) {\n await enforceratelimit(url, step.id, session?.id);\n const created = await chrome.tabs.create({ url, active: opened.length === 0 });\n opened.push(created?.id ?? 0);\n if (session) await memory.addtrailentry(session.id, { url, title: \"\", stepid: step.id, at: Date.now() });\n }\n await memory.addcurated({ ...curated, reviewedat: Date.now() });\n await memory.setnavqueues({ prefetch: (await memory.getnavqueues())?.prefetch ?? 0, batchopen: 0, updatedat: Date.now() });\n await refreshbadge();\n await audit(\"navigation\", `Batch opened ${set.open.length} curated url${set.open.length === 1 ? \"\" : \"s\"} after per url safety checks.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: true, summary: `Opened ${set.open.length} curated url${set.open.length === 1 ? \"\" : \"s\"} after per url safety checks.`, details: { curated, tabids: opened } };\n}\n\n/** Toggles the navigation pause that holds navigation while a consent prompt is open. */\nasync function executepausenav(step: toolstep, session: agentsession | undefined): Promise<stepoutput> {\n const control = await memory.getnavcontrol();\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n if (control?.pausedat) {\n await memory.setnavcontrol({ updatedat: Date.now() });\n await audit(\"resume\", `Navigation resumed after ${Date.now() - control.pausedat} milliseconds of pause.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: true, summary: \"Navigation resumed; reviewed navigation steps can run again.\", details: { paused: false } };\n }\n const reason = typeof options.reason === \"string\" && options.reason ? options.reason : \"a consent prompt is open\";\n await memory.setnavcontrol({ pausedat: Date.now(), reason, updatedat: Date.now() });\n await audit(\"pause\", `Navigation paused while ${reason}.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: true, summary: `Navigation paused while ${reason}.`, details: { paused: true, reason } };\n}\n\n/** Records the navigation intent detected from the plan for audit review. */\nasync function executenavintent(step: toolstep, session: agentsession | undefined, origin: string): Promise<stepoutput> {\n const record: navintentrecord = { id: randomid(), intent: step.value ?? \"\", origin, ...(session ? { sessionid: session.id } : {}), stepid: step.id, at: Date.now() };\n await memory.addnavintent(record);\n await audit(\"navigation\", `Navigation intent \"${record.intent}\" recorded for ${origin}.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: true, summary: `Recorded the navigation intent \"${record.intent}\".`, details: { intent: record.intent, origin, at: record.at } };\n}\n\n/** Applies the reviewed per domain navigation rate limit and reports the live window state. */\nasync function executenavrate(step: toolstep, session: agentsession | undefined, origin: string): Promise<stepoutput> {\n const limit = parseratelimit(step);\n if (!limit) throw new Error(\"A reviewed ratelimit is required.\");\n if (!limit.domain) limit.domain = domainof(origin) || origin;\n const states = await memory.getratestates();\n const stored = states.find(item => item.domain === limit.domain);\n const live = ratewindow(stored, limit, Date.now());\n const decision = rateallows(live, Date.now());\n await memory.setratestate(live);\n await audit(\"rate\", `Navigation rate limit of ${limit.ceiling} per ${limit.window} milliseconds applied for ${limit.domain}; ${decision.remaining} navigation${decision.remaining === 1 ? \"\" : \"s\"} remaining in the window.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: true, summary: `Applied the reviewed navigation rate limit for ${limit.domain}.`, details: { domain: limit.domain, window: limit.window, ceiling: limit.ceiling, count: live.count, remaining: decision.remaining, retryafter: decision.retryafter } };\n}\n\n/** Restores the navigation trail of the session for audit. */\nasync function executetrailaudit(session: agentsession | undefined): Promise<stepoutput> {\n if (!session) throw new Error(\"No active browser session exists.\");\n const trail = await memory.gettrail(session.id);\n return { ok: true, summary: `The navigation trail of the session holds ${trail.length} visited url${trail.length === 1 ? \"\" : \"s\"}.`, details: { trail } };\n}\n\n/** Dispatches one reviewed navigation kind: page world steps go through the bridge, container and state steps stay in the background. */\nasync function executenavigationkind(step: toolstep, session: agentsession | undefined, plan: agentplan, tabid: number, origin: string): Promise<stepoutput> {\n switch (step.kind) {\n case \"openlink\": return executeopenlink(step, session);\n case \"openprivate\": return executeopenlink(step, session);\n case \"deeplink\": return executedeeplink(step, session);\n case \"reopentab\": return executereopentab(step, session);\n case \"reloadcache\": {\n await refusenavpause(step);\n await chrome.tabs.reload(tabid, { bypassCache: true });\n const record = await recordnavigation(step, session, tabid);\n await audit(\"navigation\", `Reloaded the page bypassing the cache.`, { ...(session ? { sessionid: session.id } : {}), stepid: step.id });\n return { ok: true, summary: \"Reloaded the page bypassing the cache.\", details: { bypasscache: true, finalurl: record.finalurl } };\n }\n case \"navlist\": return executenavlist(step, session, plan, tabid);\n case \"navprofile\": return executenavprofile(step, session, origin);\n case \"detecthttp\": return executedetecthttp(session, tabid);\n case \"readredirects\": return executereadredirects(session);\n case \"readfinalurl\": return executereadfinalurl(session);\n case \"handleauth\": return executehandleauth(step, session);\n case \"printpdf\": return executeprintpdf(step, session, plan, tabid, origin);\n case \"prefetch\": return executeprefetch(step, session, plan, tabid, origin);\n case \"preconnect\": return executepreconnect(step, session, plan, tabid, origin);\n case \"checksafe\": return executechecksafe(step, session, plan.id);\n case \"batchopen\": return executebatchopen(step, session);\n case \"pausenav\": return executepausenav(step, session);\n case \"navintent\": return executenavintent(step, session, origin);\n case \"navrate\": return executenavrate(step, session, origin);\n case \"trailaudit\": return executetrailaudit(session);\n case \"openclipboard\": return executeopenclipboard(step, session);\n default: {\n await refusenavpause(step);\n if (ratecheckedkinds.has(step.kind)) await enforceratelimit(origin, step.id, session?.id);\n const derived = injectallowedorigins(step, session);\n const output = await dispatchpagestep(derived, tabid, origin, plan);\n if (step.kind === \"followlink\" || step.kind === \"spanav\") {\n const record = await recordnavigation(step, session, tabid);\n return { ...(output ?? { ok: false, summary: \"The navigation step returned no result.\" }), details: { ...((output ?? {}).details ?? {}), finalurl: record.finalurl, hops: record.chain.hops.length } };\n }\n return output ?? { ok: false, summary: \"The navigation step returned no result.\" };\n }\n }\n}\n\n/** Live tab set of the whole browser resolved into the serializable tabshape contract. */\nasync function livetabs(): Promise<tabshape[]> {\n const tabs = await chrome.tabs.query({}).catch(() => [] as chrome.tabs.Tab[]);\n return tabs.map(tab => ({\n tabid: tab.id ?? 0,\n url: tab.url ?? \"\",\n title: tab.title ?? \"\",\n index: tab.index,\n windowid: tab.windowId ?? 0,\n active: tab.active,\n pinned: tab.pinned,\n audible: tab.audible ?? false,\n muted: tab.mutedInfo?.muted ?? false,\n discarded: tab.discarded ?? false,\n }));\n}\n\n/** Live window set resolved into the serializable windowshape contract. */\nasync function livewindows(): Promise<windowshape[]> {\n const windows = await chrome.windows.getAll().catch(() => [] as chrome.windows.Window[]);\n return windows.map(item => ({\n windowid: item.id ?? 0,\n left: item.left ?? 0,\n top: item.top ?? 0,\n width: item.width ?? 0,\n height: item.height ?? 0,\n state: item.state === \"maximized\" || item.state === \"minimized\" || item.state === \"fullscreen\" ? item.state : \"normal\",\n incognito: item.incognito ?? false,\n focused: item.focused,\n }));\n}\n\n/** Live watchtab event buffers per watch id, filled by the tab event listeners and read by the step executor. */\nconst tabwatchbuffers = new Map<string, tabwatchevent[]>();\n/** Last known titles per tab so closed tabs keep their title inside the closed tab history. */\nconst lastknowntitles = new Map<number, string>();\n\n/** Records one tab event into every live watchtab registration and its step stream buffer. */\nasync function recordtabwatchevent(event: \"title\" | \"activated\" | \"closed\", tabid: number, detail?: string): Promise<void> {\n const now = Date.now();\n for (const watch of await memory.getwatches()) {\n if (watch.closedat !== undefined || watch.kind !== \"watchtab\") continue;\n if (watchclosed(watch.startedat, watch.lifetime, now)) continue;\n if (watch.events.length > 0 && !watch.events.includes(event)) continue;\n const record: tabwatchevent = { watchid: watch.watchid, event, tabid, ...(detail !== undefined ? { detail } : {}), at: now };\n await memory.addtabwatchevent(record);\n tabwatchbuffers.set(watch.watchid, [...(tabwatchbuffers.get(watch.watchid) ?? []), record]);\n }\n}\n\n/** Builds one tab report with matched tabs carrying audio state and metadata, the group registry and the badge states. */\nasync function buildtabreport(matches: tabshape[]): Promise<tabreport> {\n const [groups, badges, metas] = await Promise.all([memory.gettabgroups(), memory.getbadges(), memory.gettabmetas()]);\n const metabytab = new Map(metas.map(meta => [meta.tabid, meta]));\n const entries: tabreportentry[] = matches.map(tab => ({\n tabid: tab.tabid,\n url: tab.url,\n title: tab.title,\n index: tab.index,\n windowid: tab.windowid,\n active: tab.active,\n pinned: tab.pinned,\n audible: tab.audible,\n muted: tab.muted,\n discarded: tab.discarded,\n ...(metabytab.has(tab.tabid) ? { meta: metabytab.get(tab.tabid) as tabmeta } : {}),\n }));\n return { matches: entries, groups: groups.map(group => ({ name: group.name, color: group.color, tabids: group.tabids, collapsed: group.collapsed })), badges };\n}\n\n/** Reads the numeric tab ids a reviewed tabs and windows command step addresses, from the value or the reviewed list. */\nfunction commandtabids(step: toolstep, options: Record<string, unknown>): number[] {\n const listed = Array.isArray(options.tabs) ? options.tabs.filter((item): item is number => typeof item === \"number\" && Number.isInteger(item) && item >= 0) : [];\n const single = step.value && /^\\d+$/.test(step.value) ? [Number.parseInt(step.value, 10)] : [];\n return listed.length > 0 ? listed : single;\n}\n\n/** Executes one reviewed tabs and windows command kind against the live browser surface with persistence and audits. */\nasync function executetabscommand(step: toolstep, session: agentsession | undefined, plan: agentplan, sessiontabid: number): Promise<stepoutput> {\n const options = stepoptions(step);\n const extra = { ...(session ? { sessionid: session.id } : {}), planid: plan.id, stepid: step.id };\n const windowid = step.value && /^\\d+$/.test(step.value) ? Number.parseInt(step.value, 10) : 0;\n const layoutgate = layoutmutationgranted(session, Date.now());\n if (islayoutkind(step.kind) && !layoutgate.allowed) throw new Error(layoutgate.reason ?? \"Group and layout mutations stay inside the active session.\");\n switch (step.kind) {\n case \"querytabs\": {\n const query = parsetabquery(step);\n if (!query) throw new Error(\"A reviewed tabquery is required.\");\n const matches = querymatches(query, await livetabs());\n const report = await buildtabreport(matches);\n await audit(\"tab\", `Queried the live tab set and matched ${matches.length} tab${matches.length === 1 ? \"\" : \"s\"}.`, extra);\n return { ok: true, summary: `Matched ${matches.length} open tab${matches.length === 1 ? \"\" : \"s\"} by the reviewed tabquery.`, details: { report, matches: matches.length } };\n }\n case \"duplicatetab\": {\n const source = Number.parseInt(step.value ?? \"\", 10);\n const created = await chrome.tabs.duplicate(source);\n await audit(\"tab\", `Duplicated tab ${source} with its history into tab ${created?.id ?? 0}.`, extra);\n return { ok: true, summary: `Duplicated tab ${source} with its history.`, details: { sourcetab: source, tabid: created?.id ?? 0 } };\n }\n case \"closepattern\": {\n const query = parsetabquery(step);\n if (!query) throw new Error(\"A reviewed tabquery is required.\");\n const tabs = await livetabs();\n const selection = closeselection(query, tabs, session?.tabid ?? sessiontabid);\n if (selection.refused.length > 0) throw new Error(\"The close pattern matches the session tab itself; review the pattern so the session tab survives.\");\n if (selection.targets.length === 0) return { ok: true, summary: \"The reviewed close pattern matched no tab outside the session tab.\", details: { closed: 0 } };\n for (const target of selection.targets) await chrome.tabs.remove(target.tabid).catch(() => undefined);\n await audit(\"tab\", `Closed ${selection.targets.length} tab${selection.targets.length === 1 ? \"\" : \"s\"} matching the reviewed close pattern.`, extra);\n return { ok: true, summary: `Closed ${selection.targets.length} tab${selection.targets.length === 1 ? \"\" : \"s\"} matching the reviewed pattern.`, details: { closed: selection.targets.length, urls: selection.targets.map(tab => tab.url) } };\n }\n case \"pintab\": {\n const target = Number.parseInt(step.value ?? \"\", 10);\n await chrome.tabs.update(target, { pinned: options.pinned === true });\n await audit(\"tab\", `${options.pinned === true ? \"Pinned\" : \"Unpinned\"} tab ${target} by the reviewed flag.`, extra);\n return { ok: true, summary: `${options.pinned === true ? \"Pinned\" : \"Unpinned\"} tab ${target}.`, details: { tabid: target, pinned: options.pinned === true } };\n }\n case \"mutetab\": {\n const target = Number.parseInt(step.value ?? \"\", 10);\n await chrome.tabs.update(target, { muted: options.muted === true });\n await audit(\"tab\", `${options.muted === true ? \"Muted\" : \"Unmuted\"} tab ${target} by the reviewed flag.`, extra);\n return { ok: true, summary: `${options.muted === true ? \"Muted\" : \"Unmuted\"} tab ${target}.`, details: { tabid: target, muted: options.muted === true } };\n }\n case \"movetab\": {\n const target = Number.parseInt(step.value ?? \"\", 10);\n await chrome.tabs.move(target, { index: options.index as number });\n const groups = regroupaftermoves(await memory.gettabgroups(), await livetabs(), Date.now());\n for (const group of groups) await memory.settabgroup(group);\n await audit(\"tab\", `Moved tab ${target} to index ${options.index} inside its window; group membership is kept.`, extra);\n return { ok: true, summary: `Moved tab ${target} to index ${options.index}.`, details: { tabid: target, index: options.index } };\n }\n case \"movetabwindow\": {\n const target = Number.parseInt(step.value ?? \"\", 10);\n await chrome.tabs.move(target, { windowId: options.windowid as number, index: -1 });\n const groups = regroupaftermoves(await memory.gettabgroups(), await livetabs(), Date.now());\n for (const group of groups) await memory.settabgroup(group);\n await audit(\"tab\", `Moved tab ${target} across windows into window ${options.windowid}; group membership is kept.`, extra);\n return { ok: true, summary: `Moved tab ${target} into window ${options.windowid}.`, details: { tabid: target, windowid: options.windowid } };\n }\n case \"grouptabs\": {\n const group = options.group as { name?: unknown; color?: unknown; tabids?: unknown };\n const record: tabgrouprecord = { groupid: randomid(), name: String(group.name ?? \"\"), color: String(group.color ?? \"grey\"), tabids: Array.isArray(group.tabids) ? group.tabids.filter((item): item is number => typeof item === \"number\") : [], collapsed: false, savedat: Date.now() };\n await memory.settabgroup(record);\n await audit(\"group\", `Grouped ${record.tabids.length} tab${record.tabids.length === 1 ? \"\" : \"s\"} under the reviewed name ${record.name} with color ${record.color}; membership lives in the Devthink group registry.`, extra);\n return { ok: true, summary: `Grouped ${record.tabids.length} tab${record.tabids.length === 1 ? \"\" : \"s\"} under ${record.name}.`, details: { group: record } };\n }\n case \"colorgroup\": {\n const groups = await memory.gettabgroups();\n const target = groups.find(group => group.name === options.name);\n if (!target) throw new Error(`No tab group named ${options.name} is stored yet.`);\n const updated: tabgrouprecord = { ...target, color: String(options.color), savedat: Date.now() };\n await memory.settabgroup(updated);\n await audit(\"group\", `Set the color of tab group ${updated.name} to ${updated.color}.`, extra);\n return { ok: true, summary: `Set the color of group ${updated.name} to ${updated.color}.`, details: { group: updated } };\n }\n case \"collapsegroup\": {\n const groups = await memory.gettabgroups();\n const target = groups.find(group => group.name === options.name);\n if (!target) throw new Error(`No tab group named ${options.name} is stored yet.`);\n const updated: tabgrouprecord = { ...target, collapsed: options.collapsed === true, savedat: Date.now() };\n await memory.settabgroup(updated);\n await audit(\"group\", `${updated.collapsed ? \"Collapsed\" : \"Expanded\"} tab group ${updated.name}.`, extra);\n return { ok: true, summary: `${updated.collapsed ? \"Collapsed\" : \"Expanded\"} group ${updated.name}.`, details: { group: updated } };\n }\n case \"discardtab\": {\n const ids = commandtabids(step, options);\n if (ids.length === 0) throw new Error(\"A numeric tab id or a reviewed list of tab ids is required.\");\n const candidates = discardcandidates(await livetabs()).filter(tab => ids.includes(tab.tabid));\n const discarded: number[] = [];\n const urls: Array<{ tabid: number; url: string }> = [];\n for (const candidate of candidates) {\n const result = await chrome.tabs.discard(candidate.tabid).catch(() => undefined);\n if (result) { discarded.push(candidate.tabid); urls.push({ tabid: candidate.tabid, url: candidate.url }); }\n }\n await audit(\"discard\", `Discarded ${discarded.length} inactive tab${discarded.length === 1 ? \"\" : \"s\"} to save memory; the urls survive for on demand restore.`, extra);\n return { ok: discarded.length > 0, summary: `Discarded ${discarded.length} inactive tab${discarded.length === 1 ? \"\" : \"s\"}; their urls stay available for restore.`, details: { discarded, urls, refused: ids.filter(id => !discarded.includes(id)) } };\n }\n case \"reloadtabs\": {\n const ids = commandtabids(step, options);\n if (ids.length === 0) throw new Error(\"A numeric tab id or a reviewed list of tab ids is required.\");\n for (const id of ids) await chrome.tabs.reload(id).catch(() => undefined);\n await audit(\"tab\", `Reloaded ${ids.length} reviewed tab${ids.length === 1 ? \"\" : \"s\"}.`, extra);\n return { ok: true, summary: `Reloaded ${ids.length} tab${ids.length === 1 ? \"\" : \"s\"}.`, details: { tabs: ids } };\n }\n case \"zoomin\":\n case \"zoomout\": {\n const target = step.value && /^\\d+$/.test(step.value) ? Number.parseInt(step.value, 10) : sessiontabid;\n const current = await chrome.tabs.getZoom(target);\n const next = zoomstep(current, step.kind === \"zoomin\" ? \"in\" : \"out\", typeof options.step === \"number\" && options.step > 0 ? options.step : 0.1);\n await chrome.tabs.setZoom(target, next);\n await audit(\"tab\", `Zoomed tab ${target} ${step.kind === \"zoomin\" ? \"in\" : \"out\"} from ${current} to ${next} by the reviewed step.`, extra);\n return { ok: true, summary: `Zoomed tab ${target} ${step.kind === \"zoomin\" ? \"in\" : \"out\"} to ${next}.`, details: { tabid: target, from: current, to: next, step: typeof options.step === \"number\" ? options.step : 0.1 } };\n }\n case \"switchtab\": {\n const direction = options.direction === \"previous\" ? \"previous\" : \"next\";\n const focusedwindow = (await livewindows()).find(item => item.focused)?.windowid ?? 0;\n const windowtabs = (await livetabs()).filter(tab => tab.windowid === focusedwindow);\n const active = windowtabs.find(tab => tab.active);\n const target = switchtarget(windowtabs, direction, active?.index ?? 0);\n const totab = windowtabs.find(tab => tab.index === target);\n if (!totab) throw new Error(\"No neighbor tab is available to switch to.\");\n await chrome.tabs.update(totab.tabid, { active: true });\n await audit(\"tab\", `Switched to the ${direction} tab ${totab.tabid}.`, extra);\n return { ok: true, summary: `Switched to the ${direction} tab.`, details: { tabid: totab.tabid, direction } };\n }\n case \"maximizewindow\": {\n await chrome.windows.update(windowid, { state: \"maximized\" });\n await audit(\"window\", `Maximized window ${windowid}.`, extra);\n return { ok: true, summary: `Maximized window ${windowid}.`, details: { windowid, state: \"maximized\" } };\n }\n case \"minimizewindow\": {\n await chrome.windows.update(windowid, { state: \"minimized\" });\n await audit(\"window\", `Minimized window ${windowid}.`, extra);\n return { ok: true, summary: `Minimized window ${windowid}.`, details: { windowid, state: \"minimized\" } };\n }\n case \"restorewindow\": {\n const bounds = options.bounds as { left?: number; top?: number; width?: number; height?: number } | undefined;\n await chrome.windows.update(windowid, { state: \"normal\", ...(bounds && typeof bounds.left === \"number\" ? { left: bounds.left } : {}), ...(bounds && typeof bounds.top === \"number\" ? { top: bounds.top } : {}), ...(bounds && typeof bounds.width === \"number\" ? { width: bounds.width } : {}), ...(bounds && typeof bounds.height === \"number\" ? { height: bounds.height } : {}) });\n await audit(\"window\", `Restored window ${windowid} to its reviewed bounds.`, extra);\n return { ok: true, summary: `Restored window ${windowid} to its reviewed bounds.`, details: { windowid, bounds: bounds ?? null } };\n }\n case \"focuswindow\": {\n await chrome.windows.update(windowid, { focused: true });\n await audit(\"window\", `Focused window ${windowid}.`, extra);\n return { ok: true, summary: `Focused window ${windowid}.`, details: { windowid } };\n }\n case \"scratchwindow\": {\n const url = typeof step.value === \"string\" && step.value ? step.value : \"about:blank\";\n const created = await chrome.windows.create({ url });\n const window = created?.id ?? 0;\n await memory.setscratchwindows([...(await memory.getscratchwindows()), window]);\n await audit(\"window\", `Opened a scratch window ${window} for split work.`, extra);\n return { ok: true, summary: `Opened a scratch window for split work.`, details: { windowid: window, url } };\n }\n case \"incognitowindow\": {\n const created = await chrome.windows.create({ url: step.value ?? \"\", incognito: true });\n await audit(\"window\", `Opened an incognito window ${created?.id ?? 0} for ${step.value} on the explicit reviewed request; the window stays separated from the session grant inheritance.`, extra);\n return { ok: true, summary: `Opened an incognito window for ${step.value} on explicit request.`, details: { windowid: created?.id ?? 0, url: step.value, grantsinherited: windowprofilegrants(\"incognito\") } };\n }\n case \"restoretab\": {\n const open = (await livetabs()).map(tab => tab.url).filter(Boolean);\n let url = step.value && /^https:\\/\\//.test(step.value) ? step.value : undefined;\n if (!url) {\n const closed = (await memory.getclosedtabs()).find(entry => !open.includes(entry.url));\n if (!closed) throw new Error(\"No closed tab is available to restore from the session history.\");\n url = closed.url;\n }\n const created = await chrome.tabs.create({ url, active: true });\n await audit(\"tab\", `Restored the closed tab ${url} from the session history.`, extra);\n return { ok: true, summary: `Restored ${url} from the closed tab history.`, details: { url, tabid: created?.id ?? 0 } };\n }\n case \"savelayout\": {\n const name = typeof options.name === \"string\" ? options.name : \"\";\n const [tabs, windows, groups, scratch] = await Promise.all([livetabs(), livewindows(), memory.gettabgroups(), memory.getscratchwindows()]);\n const layout = buildlayout(name, tabs, windows, groups, scratch, Date.now());\n await memory.setlayout(layout);\n await audit(\"layout\", `Saved the tab layout ${name} with ${layout.tabs.length} tab${layout.tabs.length === 1 ? \"\" : \"s\"}, ${layout.groups.length} group${layout.groups.length === 1 ? \"\" : \"s\"} and ${layout.windows.length} window bound${layout.windows.length === 1 ? \"\" : \"s\"}.`, extra);\n return { ok: true, summary: `Saved the tab layout ${name}.`, details: { layout } };\n }\n case \"restorelayout\": {\n const name = typeof options.name === \"string\" ? options.name : \"\";\n const layout = await memory.getlayout(name);\n if (!layout) throw new Error(`No tab layout named ${name} is stored yet.`);\n const open = (await livetabs()).map(tab => tab.url).filter(Boolean);\n const urls = layoutrestoreplan(layout, open);\n const created: number[] = [];\n for (const url of urls) {\n const tab = await chrome.tabs.create({ url, active: created.length === 0 });\n created.push(tab?.id ?? 0);\n }\n await audit(\"layout\", `Restored the tab layout ${name}: ${created.length} tab${created.length === 1 ? \"\" : \"s\"} reopened, ${layout.tabs.length - created.length} already open.`, extra);\n return { ok: true, summary: `Restored the tab layout ${name}.`, details: { name, reopened: created.length, alreadyopen: layout.tabs.length - created.length, tabs: created } };\n }\n case \"findclones\": {\n const clones = clonetabs(await livetabs());\n await audit(\"tab\", `Detected ${clones.length} duplicate url group${clones.length === 1 ? \"\" : \"s\"} across the open tabs.`, extra);\n return { ok: true, summary: clones.length === 0 ? \"No duplicate tab was detected by normalized url comparison.\" : `Detected ${clones.length} duplicate url group${clones.length === 1 ? \"\" : \"s\"}.`, details: { clones } };\n }\n case \"searchtabs\": {\n const matches = searchtabmatches(await livetabs(), step.value ?? \"\");\n await audit(\"tab\", `Searched the open tabs and matched ${matches.length} tab${matches.length === 1 ? \"\" : \"s\"} for \"${step.value}\".`, extra);\n return { ok: true, summary: `Matched ${matches.length} open tab${matches.length === 1 ? \"\" : \"s\"} for \"${step.value}\".`, details: { matches } };\n }\n case \"badgetab\": {\n const target = Number.parseInt(step.value ?? \"\", 10);\n const badge: tabbadge = { tabid: target, taskid: typeof options.taskid === \"string\" && options.taskid ? options.taskid : plan.id, label: typeof options.label === \"string\" ? options.label : \"\", setat: Date.now() };\n await memory.setbadge(badge);\n await refreshbadge();\n await audit(\"badge\", `Set the task badge of tab ${target} to ${badge.label} for task ${badge.taskid}.`, extra);\n return { ok: true, summary: `Set the badge of tab ${target} to ${badge.label}.`, details: { badge } };\n }\n case \"attachmeta\": {\n const target = Number.parseInt(step.value ?? \"\", 10);\n const meta: tabmeta = {\n tabid: target,\n taskrefs: Array.isArray(options.taskrefs) ? options.taskrefs.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [],\n provenance: typeof options.provenance === \"string\" && options.provenance ? options.provenance : \"plan step\",\n labels: Array.isArray(options.labels) ? options.labels.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [],\n at: Date.now(),\n };\n await memory.settabmeta(meta);\n await memory.setprogress(assigntasktab(await memory.getprogress(), plan.id, target, Date.now()));\n await audit(\"tab\", `Attached metadata to tab ${target} with ${meta.labels.length} label${meta.labels.length === 1 ? \"\" : \"s\"} and ${meta.taskrefs.length} task ref${meta.taskrefs.length === 1 ? \"\" : \"s\"}; the tab joins the task progress.`, extra);\n return { ok: true, summary: `Attached metadata to tab ${target} for task routing.`, details: { meta } };\n }\n case \"listaudio\": {\n const playing = audiotabs(await livetabs());\n await audit(\"tab\", `Listed ${playing.length} tab${playing.length === 1 ? \"\" : \"s\"} that are playing audio.`, extra);\n return { ok: true, summary: `${playing.length} tab${playing.length === 1 ? \" is\" : \"s are\"} playing audio.`, details: { audio: playing } };\n }\n case \"reopenrun\": {\n const run = typeof options.run === \"string\" ? options.run : \"\";\n const snapshots = await memory.getsnapshots();\n const snapshot = snapshots.find(item => item.sessionid === run) ?? snapshots.find(item => item.id === run);\n if (!snapshot) throw new Error(`No stored session snapshot exists for the run ${run}.`);\n const open = (await livetabs()).map(tab => tab.url).filter(Boolean);\n const urls = layoutrestoreplan(snapshot.layout, open);\n const created: number[] = [];\n for (const url of urls) {\n const tab = await chrome.tabs.create({ url, active: created.length === 0 });\n created.push(tab?.id ?? 0);\n }\n await audit(\"layout\", `Reopened ${created.length} tab${created.length === 1 ? \"\" : \"s\"} of the previous run ${run}.`, extra);\n return { ok: true, summary: `Reopened ${created.length} tab${created.length === 1 ? \"\" : \"s\"} of the previous run.`, details: { run, reopened: created.length, tabs: created } };\n }\n case \"snapshotsession\": {\n const [tabs, windows, groups, scratch] = await Promise.all([livetabs(), livewindows(), memory.gettabgroups(), memory.getscratchwindows()]);\n const layout = buildlayout(`session ${new Date().toISOString()}`, tabs, windows, groups, scratch, Date.now());\n const snapshot: sessionsnapshot = { id: randomid(), ...(session ? { sessionid: session.id } : {}), layout, capturedat: Date.now() };\n await memory.addsnapshot(snapshot);\n await audit(\"layout\", `Captured the full session snapshot with ${layout.tabs.length} tab${layout.tabs.length === 1 ? \"\" : \"s\"} and ${layout.windows.length} window${layout.windows.length === 1 ? \"\" : \"s\"}.`, extra);\n return { ok: true, summary: `Captured the session snapshot of ${layout.tabs.length} tabs and ${layout.windows.length} windows.`, details: { snapshot } };\n }\n case \"watchtab\": {\n const lifetime = typeof options.lifetime === \"number\" && Number.isFinite(options.lifetime) && options.lifetime > 0 ? options.lifetime : 0;\n if (lifetime <= 0) throw new Error(\"A reviewed watch lifetime window in milliseconds is required in options.\");\n const events = Array.isArray(options.events) ? options.events.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0) : [];\n const watchid = typeof options.watchid === \"string\" && options.watchid.trim() ? options.watchid : randomid();\n const watch: watchregistration = { watchid, kind: \"watchtab\", stepid: step.id, sessionid: session?.id ?? plan.id, origin: session?.origin ?? plan.origin, scopes: [], events, startedat: Date.now(), lifetime };\n await memory.addwatch(watch);\n await audit(\"watch\", `Watchtab registered under id ${watchid} for the reviewed lifetime of ${lifetime} milliseconds${events.length > 0 ? ` over events ${events.join(\", \")}` : \" over title, activation and closure events\"}.`, extra);\n await new Promise(resolve => setTimeout(resolve, lifetime));\n const observed = watchtabdispatch(tabwatchbuffers.get(watchid) ?? [], watchid, events);\n await memory.closewatch(watchid, Date.now());\n tabwatchbuffers.delete(watchid);\n await audit(\"watch\", `Watchtab ${watchid} closed after its reviewed lifetime of ${lifetime} milliseconds with ${observed.length} observed event${observed.length === 1 ? \"\" : \"s\"}.`, extra);\n return { ok: true, summary: `Observed ${observed.length} tab event${observed.length === 1 ? \"\" : \"s\"} inside the reviewed lifetime.`, details: { watchid, events: observed } };\n }\n default: return { ok: false, summary: \"Unsupported tabs and windows command.\" };\n }\n}\n\n/** Enforces the reviewed window close: a window that holds more than one task tab needs the explicit reviewed flag. */\nasync function enforcewindowreview(step: toolstep, session: agentsession | undefined, plan: agentplan | undefined): Promise<void> {\n const windowid = step.value && /^\\d+$/.test(step.value) ? Number.parseInt(step.value, 10) : 0;\n const progress = plan ? await memory.getprogress() : undefined;\n const tasktabids = plan ? trackedtasktabs(progress, plan.id) : [];\n const count = tasktabsinwindow(await livetabs(), windowid, tasktabids);\n const gate = windowclosegate(count, stepoptions(step).reviewed === true);\n if (!gate.allowed) throw new Error(gate.reason ?? \"The window close needs explicit review.\");\n if (session && count > 0) await audit(\"window\", `Window ${windowid} closes while holding ${count} task tab${count === 1 ? \"\" : \"s\"} under the explicit reviewed flag.`, { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid: step.id });\n}\n\n/** Refreshes the per task badges from the live progress state of each task tab. */\nasync function updatetaskbadges(plan: agentplan | undefined, progress: Awaited<ReturnType<typeof memory.getprogress>>): Promise<void> {\n if (!plan || !progress || progress.planid !== plan.id) return;\n const state = badgefromprogress(progress.completedsteps.length, plan.steps.length);\n for (const tabid of tasktabs(progress, plan.id)) {\n await memory.setbadge({ tabid, taskid: plan.id, label: state.label, setat: Date.now() });\n }\n}\n\n/** Opens or closes the pinned control tab with the live task feed when the user enables it. */\nasync function togglecontroltab(enabled: boolean): Promise<controltabstate> {\n const current = await memory.getcontroltab();\n if (current && current.tabid) await chrome.tabs.remove(current.tabid).catch(() => undefined);\n if (!enabled) {\n const closed: controltabstate = { tabid: 0, enabled: false, updatedat: Date.now() };\n await memory.setcontroltab(closed);\n await audit(\"tab\", \"The pinned control tab was closed.\");\n return closed;\n }\n const created = await chrome.tabs.create({ url: chrome.runtime.getURL(\"sidepanel.html\"), pinned: true, active: false });\n const state: controltabstate = { tabid: created?.id ?? 0, enabled: true, updatedat: Date.now() };\n await memory.setcontroltab(state);\n await audit(\"tab\", `The pinned control tab ${state.tabid} was opened with the live task feed.`);\n return state;\n}\n\n/** Refreshes the popup badge with the queued prefetch and batch open target counts plus the tabs with active tasks. */\nasync function refreshbadge(): Promise<void> {\n const queues = await memory.getnavqueues();\n const badges = await memory.getbadges();\n const tasktabs = new Set(badges.map(badge => badge.tabid)).size;\n const total = (queues?.prefetch ?? 0) + (queues?.batchopen ?? 0) + tasktabs;\n await chrome.action.setBadgeText({ text: total > 0 ? String(total) : \"\" }).catch(() => { /* the badge is cosmetic and may be unavailable */ });\n}\n\nasync function executestep(stepid: string): Promise<stepoutput> {\n const session = await memory.getsession();\n const plan = await memory.getplan();\n const { tab, origin } = await activecontext();\n const step = plan?.steps.find(candidate => candidate.id === stepid);\n if (!step) throw new Error(\"Reviewed step was not found.\");\n const gate = canexecute({ session, plan, step, tabid: tab.id as number, origin, verdicts: await memory.getsafeties() });\n if (!gate.allowed) throw new Error(gate.reason);\n const capability = requiredcapability(step.kind);\n if (capability) {\n const granted = await chrome.permissions.contains({ permissions: [capability] } as chrome.permissions.Permissions);\n if (!granted) throw new Error(`The ${capability} capability has not been granted; request it from the review panel.`);\n }\n let output: stepoutput | undefined;\n let watchwindow: { startedat: number; lifetime: number } | undefined;\n if (step.kind === \"windowclose\") {\n await enforcewindowreview(step, session, plan);\n }\n if (istabscommandkind(step.kind)) {\n output = await executetabscommand(step, session, plan as agentplan, tab.id as number);\n } else if (isbrowserkind(step.kind)) {\n output = await runbrowseraction(step, tab.id as number, tab.windowId ?? chrome.windows.WINDOW_ID_CURRENT);\n } else if (step.kind === \"keyhold\") {\n output = await executekeyhold(step, session, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"keyrelease\") {\n output = await executekeyrelease(step, session, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"dismissdialog\") {\n output = await executedismissdialog(step, session, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"retryaction\") {\n output = await executeretryaction(step, session, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"mapclicks\") {\n output = await executemapclicks(step, plan as agentplan, tab.id as number, origin);\n } else if (step.kind === \"enterframe\") {\n output = await executeenterframe(step, plan as agentplan, tab.id as number, origin);\n } else if (watchstepkinds.has(step.kind)) {\n if (!session || !plan || plan.state !== \"approved\") throw new Error(\"Watch kinds refuse to run outside an approved session plan.\");\n const watched = await executewatchstep(step, session, plan, tab.id as number, origin);\n output = watched.output;\n watchwindow = { startedat: watched.watch.startedat, lifetime: watched.watch.lifetime };\n } else if (step.kind === \"diffsnapshots\") {\n output = await executediffsnapshots(step, session, plan as agentplan, tab.id as number, origin);\n } else if (navigationstepkinds.has(step.kind)) {\n output = await executenavigationkind(step, session, plan as agentplan, tab.id as number, origin);\n } else {\n if (step.target && freshcheckkinds.has(step.kind)) {\n const fresh = await snapshot(tab.id as number);\n if (!fresh.interactive.some(item => item.selector === step.target)) throw new Error(\"The page changed and the target must be reviewed again.\");\n }\n output = await dispatchpagestep(step, tab.id as number, origin, plan);\n }\n if ([\"navigate\", \"back\", \"forward\"].includes(step.kind)) await recordnavigation(step, session, tab.id as number);\n await recordevidence(step, output, session, plan, origin);\n if (output?.ok && plan && typeof output.details?.tabid === \"number\") {\n await memory.setprogress(assigntasktab(await memory.getprogress(), plan.id, output.details.tabid as number, Date.now()));\n }\n const summary = output?.summary ?? \"The page action returned no result.\";\n const resolved = output?.details?.resolvedtarget as resolvedtarget | undefined;\n if (resolved) {\n await memory.addresolution({ stepid, mode: resolved.mode, selector: resolved.selector, label: resolved.label, at: Date.now() });\n }\n const outcome: stepoutcome = { stepid, ok: Boolean(output?.ok), summary, ...(output?.details ? { details: output.details } : {}), at: Date.now() };\n const auditkind = stepauditkind(step, Boolean(output?.ok));\n await audit(auditkind, summary, { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid });\n await memory.addoutcome(outcome);\n if (output?.ok && plan) {\n const base = await memory.getprogress();\n const completed = watchwindow ? recordwatchcompletion(base, plan.id, stepid, watchwindow.startedat, watchwindow.lifetime, Date.now()) : recordstep(base, plan.id, stepid, Date.now());\n const tracked = recordoutcome(completed, plan.id, outcome, Date.now());\n await memory.setprogress(tracked);\n await updatetaskbadges(plan, tracked);\n await refreshbadge();\n if (iscomplete(tracked, plan) && plan.state === \"approved\") {\n const done = { ...plan, state: \"completed\" as const, completedat: Date.now() };\n await memory.setplan(done);\n await audit(\"complete\", \"Every reviewed step of the approved plan has executed.\", { ...(session ? { sessionid: session.id } : {}), planid: done.id });\n }\n }\n return output ?? { ok: false, summary };\n}\n\n/** Highlights a reviewed target without clicking, typing, navigating or transmitting page data. */\nasync function previewstep(stepid: string): Promise<{ ok: boolean; summary: string; resolvedtarget?: resolvedtarget; candidates?: string[] }> {\n const session = await memory.getsession();\n const plan = await memory.getplan();\n const { tab, origin } = await activecontext();\n const step = plan?.steps.find(candidate => candidate.id === stepid);\n if (!step) throw new Error(\"Reviewed step was not found.\");\n const gate = canpreview({ session, plan, step, tabid: tab.id as number, origin });\n if (!gate.allowed) throw new Error(gate.reason);\n if (!step.target && !stepoptions(step).targetref) throw new Error(\"Only a target-based step can be previewed.\");\n const result = await chrome.scripting.executeScript({ target: { tabId: tab.id as number }, func: (action: toolstep, expectedorigin: string) => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { previewtarget: (step: toolstep, origin: string) => { ok: boolean; summary: string; resolvedtarget?: resolvedtarget; candidates?: string[] } } }).devthinkbridge;\n if (!bridge) throw new Error(\"Devthink page bridge is unavailable.\");\n return bridge.previewtarget(action, expectedorigin);\n }, args: [step, origin] });\n const output = result[0]?.result as { ok: boolean; summary: string; resolvedtarget?: resolvedtarget; candidates?: string[] } | undefined;\n const summary = output?.summary ?? \"The target preview returned no result.\";\n await audit(output?.ok ? \"observe\" : \"error\", summary, { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid });\n return output ?? { ok: false, summary };\n}\n\nasync function pausesession(): Promise<agentsession> {\n const session = await memory.getsession();\n if (!session || session.stoppedat) throw new Error(\"No active browser session exists.\");\n if (session.expiresat <= Date.now()) throw new Error(\"The browser session has expired.\");\n if (session.pausedat) throw new Error(\"The browser session is already paused.\");\n const paused = { ...session, pausedat: Date.now() };\n await memory.setsession(paused);\n await audit(\"pause\", \"The user paused the browser session; no action or preview can run.\", { sessionid: session.id });\n return paused;\n}\n\nasync function resumesession(): Promise<agentsession> {\n const session = await memory.getsession();\n if (!session || session.stoppedat) throw new Error(\"No active browser session exists.\");\n if (session.expiresat <= Date.now()) throw new Error(\"The browser session has expired and cannot be resumed.\");\n if (!session.pausedat) throw new Error(\"The browser session is not paused.\");\n const resumed: agentsession = { id: session.id, tabid: session.tabid, origin: session.origin, startedat: session.startedat, expiresat: session.expiresat, ...(session.grants ? { grants: session.grants } : {}) };\n await memory.setsession(resumed);\n await audit(\"resume\", \"The user resumed the browser session; reviewed actions can run again.\", { sessionid: session.id });\n return resumed;\n}\n\nasync function grantcapability(permission: string): Promise<capabilityreport> {\n if (![\"tabs\", \"downloads\", \"clipboardRead\", \"clipboardWrite\"].includes(permission)) throw new Error(\"Unknown capability.\");\n const granted = await chrome.permissions.request({ permissions: [permission] } as chrome.permissions.Permissions);\n if (!granted) throw new Error(\"The capability grant was declined.\");\n await audit(\"capability\", `Capability ${permission} granted by the user.`);\n return refreshcapabilities();\n}\n\nasync function handlerequest(message: unknown, sender: chrome.runtime.MessageSender): Promise<unknown> {\n if (!extensionpage(sender)) throw new Error(\"Requests are accepted only from Devthink extension pages.\");\n const input = message as { kind?: string; endpoint?: string; objective?: string; stepid?: string; permission?: string };\n switch (input.kind) {\n case \"configure\": {\n const config = normalizeendpoint(input.endpoint ?? \"\");\n const granted = await chrome.permissions.contains({ origins: [hostpattern(config.origin)] });\n if (!granted) throw new Error(\"The endpoint origin has not received optional permission.\");\n await memory.setconfig(config);\n await audit(\"configure\", `Configured user-selected endpoint ${config.origin}.`);\n return config;\n }\n case \"startsession\": return startsession();\n case \"context\": {\n const plan = await memory.getplan();\n const progress = await memory.getprogress();\n const session = await memory.getsession();\n const holds = heldkeys(await memory.getholds());\n const observationversion = await memory.getobservationversion();\n const map = observationversion !== undefined && observationversion > 0 ? await memory.getmap(observationversion) : undefined;\n const a11y = (await memory.geta11ytrees())[0];\n const reader = (await memory.getreaderarticles())[0];\n const signals = await memory.getsignals();\n const trail = session ? await memory.gettrail(session.id) : [];\n const navrecords = await memory.getnavrecords();\n const ratestates = await memory.getratestates();\n const safeties = await memory.getsafeties();\n const curated = await memory.getcurateds();\n const waitprofiles = await memory.getwaitprofiles();\n const auths = (await memory.getauths()).map(record => ({ origin: record.origin, username: record.username, reviewedat: record.reviewedat }));\n const navcontrol = await memory.getnavcontrol();\n const navqueues = await memory.getnavqueues();\n const artifacts = await memory.getartifacts();\n const tabs = await livetabs().catch(() => [] as tabshape[]);\n const windows = await livewindows().catch(() => [] as windowshape[]);\n const layouts = await memory.getlayouts();\n const tabgroups = await memory.gettabgroups();\n const tabmetas = await memory.gettabmetas();\n const badges = await memory.getbadges();\n const snapshots = await memory.getsnapshots();\n const closedtabs = await memory.getclosedtabs();\n const controltab = await memory.getcontroltab();\n const tabwatchevents = await memory.gettabwatchevents();\n const clones = clonetabs(tabs);\n const taskgauge = tasktabgauge(tabs.filter(tab => badges.some(badge => badge.tabid === tab.tabid)).length, tasktabceiling(await memory.getsettings()));\n const report: tabreport = await buildtabreport(tabs);\n const livetab = session ? await chrome.tabs.get(session.tabid).catch(() => undefined) : undefined;\n const waitprofile = session ? waitprofiles.find(record => record.origin === session.origin) : undefined;\n const livestate: navstate = { phase: livetab?.status === \"loading\" ? \"loading\" : \"complete\", ...(navrecords[0] ? { finalurl: navrecords[0].finalurl, redirects: navrecords[0].chain } : {}) };\n return { config: await memory.getconfig(), session, plan, progress: plan && progress?.planid === plan.id ? progress : undefined, diagnostic: await memory.getdiagnostic(), audit: await memory.getaudit(), capabilities: await refreshcapabilities(), outcomes: await memory.getoutcomes(), holds: heldkeysreport({ tabid: session?.tabid ?? 0, holds }), dialogs: await memory.getdialogs(), retries: await memory.getretries(), ...(signals ? { signals: signalsreport({ signals }) } : { signals: signalsreport({}) }), banners: await memory.getbanners(), mutationevents: await memory.getmutationevents(), focusevents: await memory.getfocusevents(), diffs: await memory.getdiffs(), selectors: await memory.getselectors(), ...(a11y ? { a11y } : {}), ...(reader ? { reader } : {}), ...(map ? { map } : {}), trail: trailreport({ ...(session ? { sessionid: session.id } : {}), trail }), navrecords, ratestates, safeties, curated, waitprofiles, auths, navcontrol, navqueues, artifacts, navstate: livestate, ...(waitprofile ? { waitprofile } : {}), offline: !navigator.onLine, tabs, windows, layouts: layoutreport({ layouts }), tabgroups, tabmetas, badges, snapshots, closedtabs, tabwatchevents, clones, tasktabgauge: taskgauge, ...(controltab ? { controltab } : {}), tabreport: report };\n }\n case \"capabilities\": return refreshcapabilities();\n case \"grantcapability\": return grantcapability(input.permission ?? \"\");\n case \"diagnostic\": return diagnostic();\n case \"proposelocal\": return propose(input.objective ?? \"\", false);\n case \"proposeremote\": return propose(input.objective ?? \"\", true);\n case \"approve\": {\n const plan = await memory.getplan();\n if (!plan || plan.state !== \"pending\") throw new Error(\"Only a pending plan can be approved.\");\n const approved = { ...plan, state: \"approved\" as const, approvedat: Date.now() };\n await memory.setplan(approved);\n const policy = plandialogpolicy(approved);\n if (policy) await memory.setdialogpolicy(policy);\n const current = await memory.getsession();\n await audit(\"approval\", \"The user approved the reviewed plan.\", { ...(current ? { sessionid: current.id } : {}), planid: approved.id });\n return approved;\n }\n case \"reject\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available to reject.\");\n const rejected = { ...plan, state: \"rejected\" as const };\n await memory.setplan(rejected);\n const current = await memory.getsession();\n await audit(\"approval\", \"The user rejected the plan.\", { ...(current ? { sessionid: current.id } : {}), planid: rejected.id });\n return rejected;\n }\n case \"preview\": return previewstep(input.stepid ?? \"\");\n case \"execute\": return executestep(input.stepid ?? \"\");\n case \"outcome\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available for an outcome envelope.\");\n const outcome = (await memory.getoutcomes()).find(candidate => candidate.stepid === (input.stepid ?? \"\"));\n if (!outcome) throw new Error(\"No outcome exists for the reviewed step.\");\n const resolved = outcome.details?.resolvedtarget as resolvedtarget | undefined;\n return JSON.parse(outcomeresponse({ outcome, plan, ...(resolved ? { resolvedtarget: resolved } : {}) }));\n }\n case \"map\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available for a map envelope.\");\n const version = await memory.getobservationversion();\n const map = version !== undefined ? await memory.getmap(version) : undefined;\n if (!map) throw new Error(\"No clickable map has been captured yet.\");\n return JSON.parse(mapresponse({ map, plan }));\n }\n case \"observation\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available for an observation envelope.\");\n const version = await memory.getobservationversion();\n const record = version !== undefined ? await memory.getobservation(version) : undefined;\n if (!record) throw new Error(\"No observation has been captured yet.\");\n return JSON.parse(observationresponse({ observation: record.observation, plan }));\n }\n case \"pausesession\": return pausesession();\n case \"resumesession\": return resumesession();\n case \"storeauth\": {\n const session = await memory.getsession();\n if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error(\"Basic auth credentials are stored only behind the consent gate of an active session.\");\n const inputauth = message as { origin?: string; username?: string; password?: string };\n const origin = new URL(inputauth.origin ?? \"\").origin;\n if (!origin.startsWith(\"https://\")) throw new Error(\"Basic auth credentials need an HTTPS origin.\");\n if (!inputauth.username?.trim() || !inputauth.password) throw new Error(\"Basic auth credentials need a username and a password.\");\n const record: authrecord = { origin, username: inputauth.username.trim(), password: inputauth.password, reviewedat: Date.now() };\n await memory.setauth(record);\n await audit(\"auth\", `Basic auth credentials for ${origin} stored after explicit review; the password never leaves local storage.`, { sessionid: session.id });\n return { origin: record.origin, username: record.username, reviewedat: record.reviewedat };\n }\n case \"checksafe\": {\n const inputurl = message as { url?: string };\n const verdict = { ...checksafe(inputurl.url ?? \"\"), at: Date.now() };\n await memory.addsafety(verdict);\n const session = await memory.getsession();\n await audit(\"navigation\", `Safety check of ${verdict.url} returned ${verdict.safe ? \"safe\" : \"unsafe\"}${verdict.reasons.length > 0 ? `: ${verdict.reasons.join(\"; \")}` : \"\"}.`, { ...(session ? { sessionid: session.id } : {}) });\n return verdict;\n }\n case \"navstate\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available for a navstate envelope.\");\n const record = (await memory.getnavrecords())[0];\n const session = await memory.getsession();\n const livetab = session ? await chrome.tabs.get(session.tabid).catch(() => undefined) : undefined;\n const state: navstate = { phase: livetab?.status === \"loading\" ? \"loading\" : \"complete\", ...(record ? { finalurl: record.finalurl, redirects: record.chain } : {}) };\n return JSON.parse(navstateresponse({ navstate: state, plan }));\n }\n case \"safeties\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available for a safety envelope.\");\n return JSON.parse(safetyresponse({ verdicts: await memory.getsafeties(), plan }));\n }\n case \"jumptotab\": {\n const inputtab = message as { tabid?: number };\n if (typeof inputtab.tabid !== \"number\") throw new Error(\"A numeric tab id is required to jump.\");\n await chrome.tabs.update(inputtab.tabid, { active: true }).catch(() => { throw new Error(\"The tab to jump to is no longer open.\"); });\n await audit(\"tab\", `The review panel jumped to tab ${inputtab.tabid}.`);\n return { tabid: inputtab.tabid };\n }\n case \"tabsearch\": {\n const inputsearch = message as { text?: string };\n const granted = await chrome.permissions.contains({ permissions: [\"tabs\"] } as chrome.permissions.Permissions);\n if (!granted) throw new Error(\"The tabs capability has not been granted; request it from the review panel.\");\n const matches = searchtabmatches(await livetabs(), inputsearch.text ?? \"\");\n await audit(\"tab\", `The review panel searched the open tabs for \"${inputsearch.text ?? \"\"}\" and matched ${matches.length} tab${matches.length === 1 ? \"\" : \"s\"}.`);\n return { matches };\n }\n case \"savelayout\": {\n const session = await memory.getsession();\n const gate = layoutmutationgranted(session, Date.now());\n if (!gate.allowed) throw new Error(gate.reason);\n const inputlayout = message as { name?: string };\n if (!inputlayout.name?.trim()) throw new Error(\"A layout name is required.\");\n const [tabs, windows, groups, scratch] = await Promise.all([livetabs(), livewindows(), memory.gettabgroups(), memory.getscratchwindows()]);\n const layout = buildlayout(inputlayout.name.trim(), tabs, windows, groups, scratch, Date.now());\n await memory.setlayout(layout);\n await audit(\"layout\", `The review panel saved the tab layout ${layout.name} with ${layout.tabs.length} tabs and ${layout.windows.length} window bounds.`, { ...(session ? { sessionid: session.id } : {}) });\n return layout;\n }\n case \"restorelayout\": {\n const session = await memory.getsession();\n const gate = layoutmutationgranted(session, Date.now());\n if (!gate.allowed) throw new Error(gate.reason);\n const inputlayout = message as { name?: string };\n const layout = await memory.getlayout(inputlayout.name ?? \"\");\n if (!layout) throw new Error(`No tab layout named ${inputlayout.name ?? \"\"} is stored yet.`);\n const open = (await livetabs()).map(tab => tab.url).filter(Boolean);\n const urls = layoutrestoreplan(layout, open);\n const opened: number[] = [];\n for (const url of urls) {\n const created = await chrome.tabs.create({ url, active: opened.length === 0 });\n opened.push(created?.id ?? 0);\n }\n await audit(\"layout\", `The review panel restored the tab layout ${layout.name}: ${opened.length} tab${opened.length === 1 ? \"\" : \"s\"} reopened.`, { ...(session ? { sessionid: session.id } : {}) });\n return { name: layout.name, reopened: opened.length };\n }\n case \"restoresnapshot\": {\n const session = await memory.getsession();\n if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error(\"Snapshot restore stays behind the consent gate of an active session.\");\n const inputsnapshot = message as { id?: string };\n const snapshot = (await memory.getsnapshots()).find(item => item.id === inputsnapshot.id);\n if (!snapshot) throw new Error(\"No stored session snapshot matches the requested id.\");\n const open = (await livetabs()).map(tab => tab.url).filter(Boolean);\n const urls = layoutrestoreplan(snapshot.layout, open);\n const opened: number[] = [];\n for (const url of urls) {\n const created = await chrome.tabs.create({ url, active: opened.length === 0 });\n opened.push(created?.id ?? 0);\n }\n await audit(\"layout\", `The review panel restored the session snapshot ${snapshot.id}: ${opened.length} tab${opened.length === 1 ? \"\" : \"s\"} reopened.`, { sessionid: session.id });\n return { id: snapshot.id, reopened: opened.length };\n }\n case \"controltab\": {\n const inputcontrol = message as { enabled?: boolean };\n const state = await togglecontroltab(inputcontrol.enabled === true);\n const settings = await memory.getsettings();\n await memory.setsettings({ ...settings, controltab: state.enabled });\n return state;\n }\n case \"settasktabceiling\": {\n const inputceiling = message as { ceiling?: number };\n const settings = await memory.getsettings();\n const ceiling = typeof inputceiling.ceiling === \"number\" && Number.isFinite(inputceiling.ceiling) && inputceiling.ceiling >= 0 ? inputceiling.ceiling : undefined;\n await memory.setsettings({ ...settings, ...(ceiling !== undefined ? { tasktabceiling: ceiling } : {}) });\n await audit(\"configure\", `The user set the concurrent task tab ceiling to ${ceiling === undefined ? \"no ceiling\" : ceiling}; the value stays a user choice with no code cap.`);\n return { tasktabceiling: ceiling };\n }\n case \"windowstate\": {\n const inputwindow = message as { windowid?: number; state?: string };\n if (typeof inputwindow.windowid !== \"number\" || !inputwindow.state || ![\"normal\", \"maximized\", \"minimized\", \"fullscreen\"].includes(inputwindow.state)) throw new Error(\"A numeric window id and a known window state are required.\");\n await chrome.windows.update(inputwindow.windowid, { state: inputwindow.state as chrome.windows.WindowState });\n await audit(\"window\", `The popup set window ${inputwindow.windowid} to the ${inputwindow.state} state.`);\n return { windowid: inputwindow.windowid, state: inputwindow.state };\n }\n case \"closewindow\": {\n const inputclose = message as { windowid?: number; reviewed?: boolean };\n if (typeof inputclose.windowid !== \"number\") throw new Error(\"A numeric window id is required.\");\n const session = await memory.getsession();\n const plan = await memory.getplan();\n const progress = plan ? await memory.getprogress() : undefined;\n const tasktabids = plan && progress ? trackedtasktabs(progress, plan.id) : [];\n const count = tasktabsinwindow(await livetabs(), inputclose.windowid, tasktabids);\n const gate = windowclosegate(count, inputclose.reviewed === true);\n if (!gate.allowed) throw new Error(gate.reason);\n await chrome.windows.remove(inputclose.windowid);\n await audit(\"window\", `The review panel closed window ${inputclose.windowid}${count > 0 ? ` while holding ${count} task tab${count === 1 ? \"\" : \"s\"} under explicit review` : \"\"}.`, { ...(session ? { sessionid: session.id } : {}) });\n return { windowid: inputclose.windowid, closed: true };\n }\n case \"stop\": {\n const session = await memory.getsession();\n if (session) await memory.setsession({ ...session, stoppedat: Date.now() });\n const plan = await memory.getplan();\n if (plan && [\"pending\", \"approved\"].includes(plan.state)) await memory.setplan({ ...plan, state: \"cancelled\" });\n await audit(\"stop\", \"The user stopped the browser session.\", { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}) });\n return { stopped: true };\n }\n default: throw new Error(\"Unknown Devthink request.\");\n }\n}\n\nchrome.runtime.onMessage.addListener((message, sender, sendresponse) => {\n handlerequest(message, sender).then(value => sendresponse({ ok: true, value })).catch(error => sendresponse({ ok: false, error: error instanceof Error ? error.message : String(error) }));\n return true;\n});\n\n/** Reconciles persisted watch registrations when the service worker restarts: registrations stay alive in storage, windows that ended while the worker was down are closed and audited, and live windows stay open. */\nasync function reconcilewatches(): Promise<void> {\n for (const watch of await memory.getwatches()) {\n if (watch.closedat !== undefined) continue;\n if (!watchclosed(watch.startedat, watch.lifetime, Date.now())) continue;\n await memory.closewatch(watch.watchid, Date.now());\n await audit(\"watch\", `Watch ${watch.watchid} of ${watch.kind} closed on service worker restart after its reviewed lifetime of ${watch.lifetime} milliseconds.`, { sessionid: watch.sessionid, stepid: watch.stepid });\n }\n}\n\nreconcilewatches().catch(() => { /* a failing storage read retries on the next service worker start; closed windows stay auditable */ });\n\nchrome.runtime.onConnect.addListener(port => {\n if (port.name !== \"devthinksidepanel\" || port.sender?.id !== chrome.runtime.id || !port.sender.url?.startsWith(chrome.runtime.getURL(\"\"))) return port.disconnect();\n port.onMessage.addListener(message => { handlerequest(message, port.sender ?? {}).then(value => port.postMessage({ ok: true, value })).catch(error => port.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) })); });\n});\n"],
5
+ "mappings": ";AAYO,IAAM,gBAAN,MAAoB;AAAA,EACzB,YAA6B,SAAwB;AAAxB;AAAA,EAAyB;AAAA,EAAzB;AAAA,EAE7B,MAAM,YAAiD;AAAE,WAAO,KAAK,QAAQ,IAAoB,QAAQ;AAAA,EAAG;AAAA,EAC5G,MAAM,UAAU,OAAsC;AAAE,WAAO,KAAK,QAAQ,IAAI,UAAU,KAAK;AAAA,E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", "record", "created", "text", "window", "snapshot", "tasktabs"]
7
7
  }