@wenathlan/extension 1.1.38 → 1.1.39

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
3
  "sources": ["../../policy.ts", "../popup.ts"],
4
- "sourcesContent": ["import type { actionkind, agentplan, agentsession, endpointconfig, fieldkind, formprofile, observationmode, policyevaluation, runsettings, safetyverdict, toolstep, transformrule } 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\", \"fillform\", \"filllabel\", \"fillplaceholder\", \"submitform\", \"retryform\", \"runwizard\", \"selectchain\", \"picktypeahead\", \"pickdate\", \"attachfile\", \"fillcard\", \"fillcode\", \"consentpassword\", \"exportcsv\", \"exportjson\", \"exportexcel\", \"copytable\", \"pushsheets\", \"streamdisk\", \"paginateextract\", \"resumeextract\"]);\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\", \"detectfields\", \"generatevalues\", \"saveprofiles\", \"asksubmit\", \"readerrors\", \"skiphoneypot\", \"detectlogin\", \"detecttemplate\", \"handoffcaptcha\", \"scrapetable\", \"importcsv\", \"looprows\", \"transformvalues\", \"deduperows\", \"mergepages\", \"stamplerows\", \"previewgrid\", \"logprovenance\"]);\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\", \"submitform\", \"retryform\", \"selectchain\", \"picktypeahead\", \"pickdate\", \"attachfile\", \"fillcode\", \"consentpassword\", \"scrapetable\", \"paginateextract\"]);\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\", \"asksubmit\", \"selectchain\", \"picktypeahead\", \"pickdate\", \"attachfile\", \"fillcode\", \"consentpassword\"]);\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 formactions = new Set<actionkind>([\"fillform\", \"filllabel\", \"fillplaceholder\", \"detectfields\", \"generatevalues\", \"saveprofiles\", \"asksubmit\", \"submitform\", \"readerrors\", \"retryform\", \"runwizard\", \"selectchain\", \"picktypeahead\", \"pickdate\", \"attachfile\", \"handoffcaptcha\", \"fillcard\", \"fillcode\", \"consentpassword\", \"skiphoneypot\", \"detectlogin\", \"detecttemplate\"]);\n/** Extraction, transform, export and provenance kinds of the forms and data part two family. */\nconst datasetactions = new Set<actionkind>([\"scrapetable\", \"exportcsv\", \"exportjson\", \"exportexcel\", \"copytable\", \"pushsheets\", \"importcsv\", \"looprows\", \"transformvalues\", \"deduperows\", \"paginateextract\", \"mergepages\", \"stamplerows\", \"previewgrid\", \"streamdisk\", \"resumeextract\", \"logprovenance\"]);\n/** Export kinds that move extracted data out of local memory to disk, the clipboard or a reviewed sheet endpoint. */\nconst exportactions = new Set<actionkind>([\"exportcsv\", \"exportjson\", \"exportexcel\", \"copytable\", \"pushsheets\", \"streamdisk\"]);\n/** Field kinds the form grammar accepts inside records, profiles and value rules. */\nconst fieldkinds: fieldkind[] = [\"text\", \"email\", \"phone\", \"date\", \"number\", \"select\", \"check\", \"radio\", \"file\", \"password\", \"card\", \"code\"];\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 === \"copytable\") return \"clipboardWrite\";\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/** True when the kind belongs to the forms and data family. */\nexport function isformkind(kind: actionkind): boolean {\n return formactions.has(kind);\n}\n\n/** True when the kind belongs to the extraction, transform, export and provenance family. */\nexport function isdatasetkind(kind: actionkind): boolean {\n return datasetactions.has(kind);\n}\n\n/** True when the kind exports extracted data out of local memory to disk, the clipboard or a reviewed sheet endpoint. */\nexport function isexportkind(kind: actionkind): boolean {\n return exportactions.has(kind);\n}\n\n/** Refuses any export that would leave local memory while the session origin grants do not cover the active origin. */\nexport function exportgranted(session: agentsession | undefined, origin: string): policyevaluation {\n if (!origingranted(session, origin)) return { allowed: false, reason: `The export of extracted data from ${origin} needs the session origin grants before it leaves local memory.` };\n return { allowed: true };\n}\n\n/** Validates the reviewed fieldmatch grammar of one form field entry. */\nexport function validatefieldmatch(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed field match is required in options.\" };\n const match = value as Record<string, unknown>;\n if (match.mode !== \"label\" && match.mode !== \"placeholder\" && match.mode !== \"arialabel\" && match.mode !== \"name\") return { allowed: false, reason: \"The reviewed field match mode must be label, placeholder, arialabel or name.\" };\n const key = match.mode === \"label\" ? \"label\" : match.mode === \"placeholder\" ? \"placeholder\" : match.mode === \"arialabel\" ? \"arialabel\" : \"name\";\n if (!isnonempty(match[key])) return { allowed: false, reason: `The reviewed ${match.mode} field match needs a non-empty ${key}.` };\n return { allowed: true };\n}\n\n/** Validates a reviewed structured form record; password entries are refused because passwords need the explicit consentpassword consent. */\nexport function validateformrecord(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed form record with entries is required in options.\" };\n const record = value as Record<string, unknown>;\n if (record.form !== undefined && !isnonempty(record.form)) return { allowed: false, reason: \"The reviewed form record form selector must be a non-empty string.\" };\n if (!Array.isArray(record.entries) || record.entries.length === 0) return { allowed: false, reason: \"The reviewed form record needs a non-empty list of entries.\" };\n for (const item of record.entries) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return { allowed: false, reason: \"Every reviewed form record entry must be an object.\" };\n const entry = item as Record<string, unknown>;\n const matchcheck = validatefieldmatch(entry.match);\n if (!matchcheck.allowed) return matchcheck;\n if (typeof entry.kind !== \"string\" || !fieldkinds.includes(entry.kind as fieldkind)) return { allowed: false, reason: \"Every reviewed form record entry needs a known field kind.\" };\n if (typeof entry.value !== \"string\") return { allowed: false, reason: \"Every reviewed form record entry needs a string value.\" };\n if (entry.kind === \"password\") return { allowed: false, reason: \"Password entries are refused inside form records; use consentpassword with a reviewed consent ref.\" };\n }\n return { allowed: true };\n}\n\n/** Validates the reviewed valuegen grammar of a generatevalues step. */\nexport function validatevaluegen(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed valuegen rule with a field kind is required in options.\" };\n const rule = value as Record<string, unknown>;\n if (typeof rule.kind !== \"string\" || !fieldkinds.includes(rule.kind as fieldkind)) return { allowed: false, reason: \"The reviewed valuegen kind must be a known field kind.\" };\n if (rule.locale !== undefined && !isnonempty(rule.locale)) return { allowed: false, reason: \"The reviewed valuegen locale must be a non-empty string.\" };\n if (rule.seed !== undefined && (typeof rule.seed !== \"number\" || !Number.isFinite(rule.seed))) return { allowed: false, reason: \"The reviewed valuegen seed must be a finite number.\" };\n return { allowed: true };\n}\n\n/** Validates a reviewed list of label or placeholder value pairs for filllabel and fillplaceholder steps. */\nfunction validatefieldpairs(options: Record<string, unknown>, mode: \"label\" | \"placeholder\"): policyevaluation {\n const pairs = options.fields;\n if (!Array.isArray(pairs) || pairs.length === 0) return { allowed: false, reason: \"A reviewed non-empty list of field pairs is required in options.\" };\n for (const item of pairs) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return { allowed: false, reason: \"Every reviewed field pair must be an object.\" };\n const pair = item as Record<string, unknown>;\n if (!isnonempty(pair[mode])) return { allowed: false, reason: `Every reviewed field pair needs a non-empty ${mode}.` };\n if (typeof pair.value !== \"string\" || !pair.value.trim()) return { allowed: false, reason: \"Every reviewed field pair needs a non-empty value.\" };\n }\n return { allowed: true };\n}\n\n/** Validates the reviewed card segment grammar of a fillcard step. */\nfunction validatecardsegments(value: unknown): policyevaluation {\n if (!Array.isArray(value) || value.length === 0) return { allowed: false, reason: \"A reviewed non-empty list of card segments is required in options.\" };\n for (const item of value) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return { allowed: false, reason: \"Every reviewed card segment must be an object.\" };\n const segment = item as Record<string, unknown>;\n const matchcheck = validatefieldmatch(segment.match);\n if (!matchcheck.allowed) return matchcheck;\n if (typeof segment.value !== \"string\" || !segment.value.trim()) return { allowed: false, reason: \"Every reviewed card segment needs a non-empty value.\" };\n }\n return { allowed: true };\n}\n\n/** Validates the reviewed forms and data parameter grammar of the form family. */\nfunction validateformgrammar(step: toolstep, options: Record<string, unknown>): policyevaluation {\n const kind = step.kind;\n if (kind === \"fillform\" || (kind === \"saveprofiles\" && options.formrecord !== undefined)) {\n const recordcheck = validateformrecord(options.formrecord);\n if (!recordcheck.allowed) return recordcheck;\n }\n if (kind === \"filllabel\" || kind === \"fillplaceholder\") {\n const paircheck = validatefieldpairs(options, kind === \"filllabel\" ? \"label\" : \"placeholder\");\n if (!paircheck.allowed) return paircheck;\n }\n if (kind === \"generatevalues\" && options.valuegen !== undefined) {\n const rulecheck = validatevaluegen(options.valuegen);\n if (!rulecheck.allowed) return rulecheck;\n }\n if (kind === \"saveprofiles\" && !isnonempty(options.name)) return { allowed: false, reason: \"A reviewed profile name is required in options.\" };\n if (kind === \"submitform\" && !isnonempty(options.consentref)) return { allowed: false, reason: \"A reviewed consent ref of an approved asksubmit ticket is required in options.\" };\n if (kind === \"retryform\") {\n const backoff = options.backoff;\n if (!backoff || typeof backoff !== \"object\" || Array.isArray(backoff)) return { allowed: false, reason: \"A reviewed backoff rule with wait and factor is required in options.\" };\n const rule = backoff as Record<string, unknown>;\n if (typeof rule.wait !== \"number\" || !Number.isFinite(rule.wait) || rule.wait <= 0) return { allowed: false, reason: \"The reviewed retry backoff wait must be a positive number of milliseconds with no code ceiling.\" };\n if (typeof rule.factor !== \"number\" || !Number.isFinite(rule.factor) || rule.factor < 1) return { allowed: false, reason: \"The reviewed retry backoff factor must be one or greater with no code ceiling.\" };\n if (options.attempts !== undefined && (typeof options.attempts !== \"number\" || !Number.isInteger(options.attempts) || options.attempts < 1)) return { allowed: false, reason: \"The reviewed retry attempts must be a positive integer with no code ceiling.\" };\n }\n if (kind === \"runwizard\" && options.steps !== undefined && (typeof options.steps !== \"number\" || !Number.isInteger(options.steps) || options.steps < 1)) return { allowed: false, reason: \"The reviewed wizard step count must be a positive integer with no code ceiling.\" };\n if (kind === \"selectchain\") {\n if (!isnonempty(options.child)) return { allowed: false, reason: \"A reviewed child selector of the dependent control is required in options.\" };\n if (!nonnegativeoption(options, \"wait\")) return { allowed: false, reason: \"The reviewed dependent wait must be zero or a positive number of milliseconds.\" };\n }\n if (kind === \"picktypeahead\") {\n if (!isnonempty(options.pick)) return { allowed: false, reason: \"A reviewed suggestion entry to pick is required in options.\" };\n if (!nonnegativeoption(options, \"timeout\")) return { allowed: false, reason: \"The reviewed typeahead timeout must be zero or a positive number of milliseconds.\" };\n }\n if (kind === \"pickdate\" && !/^\\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 (kind === \"fillcard\") {\n const segmentcheck = validatecardsegments(options.segments);\n if (!segmentcheck.allowed) return segmentcheck;\n if (!nonnegativeoption(options, \"pause\")) return { allowed: false, reason: \"The reviewed card typing pause must be zero or a positive number of milliseconds.\" };\n }\n if (kind === \"fillcode\" && !isnonempty(options.source)) return { allowed: false, reason: \"A reviewed one time code source is required in options.\" };\n if (kind === \"consentpassword\" && !isnonempty(options.consentref)) return { allowed: false, reason: \"A reviewed consent ref is required in options before any password is filled.\" };\n return { allowed: true };\n}\n\n/** Validates one reviewed transform rule: a supported expression, source columns and a target column. */\nexport function validatetransformrule(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed transform rule with an expression, sources and a target is required in options.\" };\n const rule = value as Record<string, unknown>;\n const expression = rule.expression;\n if (typeof expression !== \"string\" || !/^(trim|upper|lower|number|prefix|suffix|replace)(?::.+)?$/.test(expression)) return { allowed: false, reason: \"The reviewed transform expression must be trim, upper, lower, number, prefix, suffix or replace with an optional argument.\" };\n if (expression.startsWith(\"replace\") && !expression.slice(\"replace\".length).includes(\"=>\")) return { allowed: false, reason: \"The reviewed replace expression needs the from=>to separator.\" };\n if (expression.startsWith(\"replace\") && expression.slice(\"replace:\".length).split(\"=>\")[0] === \"\") return { allowed: false, reason: \"The reviewed replace expression needs a non-empty from part.\" };\n if (!Array.isArray(rule.sources) || rule.sources.length === 0 || !rule.sources.every(source => isnonempty(source))) return { allowed: false, reason: \"Every reviewed transform rule needs a non-empty list of source columns.\" };\n if (!isnonempty(rule.target)) return { allowed: false, reason: \"Every reviewed transform rule needs a non-empty target column.\" };\n return { allowed: true };\n}\n\n/** Validates a reviewed dataset id list in options. */\nfunction validatedatasetids(options: Record<string, unknown>, key: string): policyevaluation {\n const ids = options[key];\n if (!Array.isArray(ids) || ids.length === 0 || !ids.every(id => isnonempty(id))) return { allowed: false, reason: `A reviewed non-empty list of dataset ids is required in options as ${key}.` };\n return { allowed: true };\n}\n\n/** Validates the reviewed extraction, transform, export and provenance parameter grammar of the data family. */\nfunction validatedatagrammar(step: toolstep, options: Record<string, unknown>, origin: string): policyevaluation {\n const kind = step.kind;\n if (kind === \"scrapetable\") {\n if (options.name !== undefined && !isnonempty(options.name)) return { allowed: false, reason: \"The reviewed dataset name must be a non-empty string.\" };\n if (options.rowlimit !== undefined && (typeof options.rowlimit !== \"number\" || !Number.isInteger(options.rowlimit) || options.rowlimit < 1)) return { allowed: false, reason: \"The reviewed row limit must be a positive integer with no code ceiling.\" };\n }\n if (kind === \"paginateextract\") {\n if (!isnonempty(options.next)) return { allowed: false, reason: \"A reviewed next control selector is required in options.\" };\n if (options.pages !== undefined && (typeof options.pages !== \"number\" || !Number.isInteger(options.pages) || options.pages < 1)) return { allowed: false, reason: \"The reviewed page count must be a positive integer with no code ceiling.\" };\n if (!nonnegativeoption(options, \"wait\")) return { allowed: false, reason: \"The reviewed row freshness wait must be zero or a positive number of milliseconds.\" };\n }\n if (kind === \"exportcsv\" || kind === \"exportjson\" || kind === \"exportexcel\" || kind === \"copytable\" || kind === \"streamdisk\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (options.name !== undefined && !isnonempty(options.name)) return { allowed: false, reason: \"The reviewed artifact name must be a non-empty string.\" };\n }\n if (kind === \"exportcsv\" && options.delimiter !== undefined && (typeof options.delimiter !== \"string\" || options.delimiter.length !== 1)) return { allowed: false, reason: \"The reviewed csv delimiter must be a single character.\" };\n if (kind === \"streamdisk\" && (typeof options.chunk !== \"number\" || !Number.isInteger(options.chunk) || options.chunk < 1)) return { allowed: false, reason: \"The reviewed streaming chunk size must be a positive integer with no code ceiling.\" };\n if (kind === \"pushsheets\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (!isnonempty(options.sheet)) return { allowed: false, reason: \"A reviewed sheet endpoint url is required in options.\" };\n if (!ishttpsurl(options.sheet)) return { allowed: false, reason: \"The reviewed sheet endpoint url must use HTTPS.\" };\n if (options.reviewed !== true) return { allowed: false, reason: \"The sheet push needs the explicit reviewed flag before any data leaves local memory.\" };\n }\n if (kind === \"importcsv\") {\n if (typeof options.csv !== \"string\" || !options.csv.trim()) return { allowed: false, reason: \"Reviewed csv content is required in options.\" };\n if (options.name !== undefined && !isnonempty(options.name)) return { allowed: false, reason: \"The reviewed dataset name must be a non-empty string.\" };\n if (options.mapping !== undefined) {\n const mapping = options.mapping;\n if (!mapping || typeof mapping !== \"object\" || Array.isArray(mapping) || !Object.values(mapping).every(item => typeof item === \"string\")) return { allowed: false, reason: \"The reviewed csv column mapping must be an object of string values.\" };\n }\n }\n if (kind === \"looprows\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (options.variable !== undefined && !isnonempty(options.variable)) return { allowed: false, reason: \"The reviewed row variable name must be a non-empty string.\" };\n const inner = validateinnerstep(options, origin);\n if (!inner.allowed) return inner;\n }\n if (kind === \"transformvalues\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n const rules = options.rules;\n if (!Array.isArray(rules) || rules.length === 0) return { allowed: false, reason: \"A reviewed non-empty list of transform rules is required in options.\" };\n for (const item of rules) {\n const rulecheck = validatetransformrule(item);\n if (!rulecheck.allowed) return rulecheck;\n }\n }\n if (kind === \"deduperows\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n const keys = options.keys;\n if (!Array.isArray(keys) || keys.length === 0 || !keys.every(key => isnonempty(key))) return { allowed: false, reason: \"A reviewed non-empty list of dedupe column keys is required in options.\" };\n }\n if (kind === \"mergepages\") {\n const listcheck = validatedatasetids(options, \"datasets\");\n if (!listcheck.allowed) return listcheck;\n }\n if (kind === \"stamplerows\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (options.url !== undefined && !ishttpsurl(options.url)) return { allowed: false, reason: \"The reviewed source url must use HTTPS.\" };\n }\n if (kind === \"previewgrid\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (options.sample !== undefined && (typeof options.sample !== \"number\" || !Number.isInteger(options.sample) || options.sample < 1)) return { allowed: false, reason: \"The reviewed sample row count must be a positive integer with no code ceiling.\" };\n }\n if (kind === \"resumeextract\" && !isnonempty(options.session)) return { allowed: false, reason: \"A reviewed extract session id is required in options.\" };\n if (kind === \"logprovenance\" && !isnonempty(options.artifact)) return { allowed: false, reason: \"A reviewed artifact id or name is required in options.\" };\n return { allowed: true };\n}\n\n/** Requires an asksubmit review step before every form submission step. */\nexport function submitreviewgranted(steps: toolstep[], submitid: string): policyevaluation {\n const position = steps.findIndex(candidate => candidate.id === submitid);\n const asked = steps.some((candidate, index) => candidate.kind === \"asksubmit\" && (position === -1 || index < position));\n return asked ? { allowed: true } : { allowed: false, reason: \"Form submission requires an asksubmit review step before it.\" };\n}\n\n/** Requires a reviewed consent ref before any password field is filled. */\nexport function passwordconsentgranted(step: toolstep): policyevaluation {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const consentref = options.consentref;\n if (typeof consentref !== \"string\" || !consentref.trim()) return { allowed: false, reason: \"A password fill requires a reviewed consent ref in options.\" };\n return { allowed: true };\n}\n\n/** True when a numeric value passes the Luhn checksum used by card networks. */\nfunction luhnvalid(digits: string): boolean {\n let sum = 0;\n let double = false;\n for (let index = digits.length - 1; index >= 0; index -= 1) {\n let value = Number.parseInt(digits[index] ?? \"\", 10);\n if (!Number.isFinite(value)) return false;\n if (double) { value *= 2; if (value > 9) value -= 9; }\n sum += value;\n double = !double;\n }\n return sum % 10 === 0;\n}\n\n/** Refuses generated values that look like real card numbers or personal identifiers; test prefixed card values stay allowed. */\nexport function generatedvalueallowed(value: string): policyevaluation {\n const compact = value.replace(/[\\s-]/g, \"\");\n if (/^\\d{13,19}$/.test(compact) && luhnvalid(compact) && !compact.startsWith(\"4111\")) return { allowed: false, reason: \"The generated value looks like a real card number and is refused; generated card values use the 4111 test prefix.\" };\n if (/^\\d{3}-\\d{2}-\\d{4}$/.test(value.trim())) return { allowed: false, reason: \"The generated value looks like a personal identifier and is refused.\" };\n return { allowed: true };\n}\n\n/** Requires the origin grants of a saved profile to cover the origin before its values fill a page. */\nexport function profilegrantgranted(profile: formprofile, origin: string): policyevaluation {\n if (!profile.grants.includes(origin)) return { allowed: false, reason: `The saved profile ${profile.name} is not granted to ${origin}; add the origin to the profile grants first.` };\n return { allowed: true };\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\" || kind === \"looprows\") 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 (isformkind(step.kind)) {\n const formcheck = validateformgrammar(step, options);\n if (!formcheck.allowed) return formcheck;\n }\n if (isdatasetkind(step.kind)) {\n const datacheck = validatedatagrammar(step, options, origin);\n if (!datacheck.allowed) return datacheck;\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 (isexportkind(input.step.kind)) {\n const exportgate = exportgranted(input.session, input.origin);\n if (!exportgate.allowed) return exportgate;\n }\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 === \"submitform\" || input.step.kind === \"retryform\") {\n if (!input.plan) return { allowed: false, reason: \"Form submission requires an asksubmit review step before it.\" };\n const reviewgate = submitreviewgranted(input.plan.steps, input.step.id);\n if (!reviewgate.allowed) return reviewgate;\n }\n if (input.step.kind === \"consentpassword\") {\n const consentgate = passwordconsentgranted(input.step);\n if (!consentgate.allowed) return consentgate;\n }\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 { hostpattern, normalizeendpoint } from \"../policy.js\";\nimport type { capabilityreport, captchahandoff, dataset, dialogdecision, keyholdstate, navqueues, navstate, streamstate, tabbadge, waitprofilerecord } from \"../types.js\";\nimport type { windowshape } from \"./tabscommand.js\";\n\ntype pagesignallike = { language?: string; template?: string; scrolllocked?: boolean; banner?: string };\n\nconst endpointinput = document.querySelector<HTMLInputElement>(\"#endpoint\");\nconst statusnode = document.querySelector<HTMLElement>(\"#status\");\nconst capabilitiesnode = document.querySelector<HTMLElement>(\"#capabilities\");\nconst livenode = document.querySelector<HTMLElement>(\"#livelogic\");\nconst navstatenode = document.querySelector<HTMLElement>(\"#navstate\");\nconst windowlayoutnode = document.querySelector<HTMLElement>(\"#windowlayout\");\nconst captchastatenode = document.querySelector<HTMLElement>(\"#captchastate\");\nconst datasetstatenode = document.querySelector<HTMLElement>(\"#datasetstate\");\nconst windowcontrols = document.querySelector<HTMLElement>(\"#windowcontrols\");\nconst connectbutton = document.querySelector<HTMLButtonElement>(\"#connect\");\nconst sessionbutton = document.querySelector<HTMLButtonElement>(\"#session\");\nconst pausebutton = document.querySelector<HTMLButtonElement>(\"#pause\");\nconst stopbutton = document.querySelector<HTMLButtonElement>(\"#stop\");\nconst openbutton = document.querySelector<HTMLButtonElement>(\"#openpanel\");\n\nfunction status(message: string, error = false): void { if (statusnode) { statusnode.textContent = message; statusnode.dataset.state = error ? \"error\" : \"ready\"; } }\nasync function request(message: unknown): Promise<unknown> { const response = await chrome.runtime.sendMessage(message) as { ok: boolean; value?: unknown; error?: string }; if (!response.ok) throw new Error(response.error); return response.value; }\n\nfunction pauselabel(paused: boolean): string { return paused ? \"Resume session\" : \"Pause session\"; }\n\n/** Renders the live optional capability set the user has granted. */\nfunction rendercapabilities(report?: capabilityreport): void {\n if (!capabilitiesnode) return;\n if (!report) { capabilitiesnode.textContent = \"Capabilities unknown.\"; return; }\n const granted = [`tabs ${report.tabs ? \"granted\" : \"absent\"}`, `downloads ${report.downloads ? \"granted\" : \"absent\"}`, `clipboard read ${report.clipboardread ? \"granted\" : \"absent\"}`, `clipboard write ${report.clipboardwrite ? \"granted\" : \"absent\"}`];\n capabilitiesnode.textContent = `Optional capabilities: ${granted.join(\" \u00B7 \")}.`;\n}\n\n/** Renders the currently held keys and the dialogs answered by the reviewed policy. */\nfunction renderlivestate(holds?: keyholdstate[], dialogs?: dialogdecision[], signals?: pagesignallike): void {\n if (!livenode) return;\n const held = (holds ?? []).filter(hold => hold.releasedat === undefined);\n const heldsummary = held.length > 0 ? held.map(hold => `${hold.key}${hold.holdid ? ` (${hold.holdid})` : \"\"}`).join(\", \") : \"none\";\n const dialogsummary = (dialogs ?? []).length > 0 ? `${dialogs?.length} answered` : \"none\";\n const pages = signals && (signals.language !== undefined || signals.template !== undefined || signals.scrolllocked !== undefined)\n ? [signals.language !== undefined ? `language ${signals.language || \"unknown\"}` : \"\", signals.template !== undefined ? `template ${signals.template}` : \"\", signals.scrolllocked !== undefined ? `scroll lock ${signals.scrolllocked ? \"on\" : \"off\"}` : \"\"].filter(Boolean).join(\" \u00B7 \")\n : \"unknown\";\n livenode.textContent = `Held keys: ${heldsummary} \u00B7 Open dialogs answered: ${dialogsummary} \u00B7 Page signals: ${pages}.`;\n}\n\n/** Renders the load phase, offline state, active wait profile and queued navigation targets of the session tab. */\nfunction rendernavstate(state?: navstate, offline?: boolean, profile?: waitprofilerecord, queues?: navqueues): void {\n if (!navstatenode) return;\n const phase = state?.phase ? `load phase ${state.phase}` : \"load phase unknown\";\n const offlinestate = offline === undefined ? \"connectivity unknown\" : offline ? \"offline\" : \"online\";\n const wait = profile ? `wait profile ${profile.profile.signals.join(\"+\")}` : \"no wait profile\";\n const queued = queues ? `queued targets ${queues.prefetch + queues.batchopen} (${queues.prefetch} prefetch \u00B7 ${queues.batchopen} batch open)` : \"no queued targets\";\n navstatenode.textContent = `Navigation: ${phase} \u00B7 ${offlinestate} \u00B7 ${wait} \u00B7 ${queued}.`;\n}\n\n/** Renders the current window layout and the quick window state buttons. */\nfunction renderwindowlayout(windows?: windowshape[], badges?: tabbadge[]): void {\n if (!windowlayoutnode || !windowcontrols) return;\n windowlayoutnode.textContent = windows === undefined\n ? \"Window layout: unknown.\"\n : `Window layout: ${windows.length} window${windows.length === 1 ? \"\" : \"s\"}${windows.length > 0 ? ` (${windows.map(item => `${item.windowid}: ${item.state}${item.incognito ? \" incognito\" : \"\"}`).join(\" \u00B7 \")})` : \"\"} \u00B7 ${new Set((badges ?? []).map(badge => badge.tabid)).size} tab${new Set((badges ?? []).map(badge => badge.tabid)).size === 1 ? \"\" : \"s\"} with active tasks.`;\n windowcontrols.replaceChildren();\n for (const item of (windows ?? []).slice(0, 4)) {\n for (const state of [\"maximized\", \"minimized\", \"normal\"] as const) {\n const quick = document.createElement(\"button\");\n quick.type = \"button\";\n quick.className = \"secondary\";\n quick.textContent = `${state === \"normal\" ? \"restore\" : state} ${item.windowid}`;\n quick.addEventListener(\"click\", () => request({ kind: \"windowstate\", windowid: item.windowid, state }).then(() => { status(`Window ${item.windowid} set to ${state}.`); return restore(); }).catch(error => status(error instanceof Error ? error.message : String(error), true)));\n windowcontrols.append(quick);\n }\n }\n}\n\n/** Renders the captcha handoff state while a plan waits for the user. */\nfunction rendercaptchastate(captchas?: captchahandoff[]): void {\n if (!captchastatenode) return;\n const open = (captchas ?? []).find(handoff => !handoff.resolved);\n if (open) { captchastatenode.dataset.state = \"error\"; captchastatenode.textContent = `Captcha handoff open on ${open.origin}; the plan waits until you resolve it in the review panel.`; return; }\n delete captchastatenode.dataset.state;\n captchastatenode.textContent = \"Captcha handoff: none.\";\n}\n\n/** Renders the active dataset row count and the stream state of the session. */\nfunction renderdatasetstate(datasets?: dataset[], streams?: streamstate[]): void {\n if (!datasetstatenode) return;\n const rows = (datasets ?? []).reduce((total, datasetvalue) => total + datasetvalue.rows.length, 0);\n const count = datasets?.length ?? 0;\n const stream = (streams ?? []).find(item => item.done !== true) ?? (streams ?? [])[0];\n const streamsummary = stream ? ` \u00B7 stream ${stream.name} chunk ${stream.chunk} of ${stream.chunks}${stream.done ? \" complete\" : \"\"}` : \"\";\n datasetstatenode.textContent = count === 0 ? \"Datasets: none collected yet.\" : `Datasets: ${count} collected (${rows} row${rows === 1 ? \"\" : \"s\"})${streamsummary}.`;\n}\n\nasync function restore(): Promise<void> {\n const context = await request({ kind: \"context\" }) as { config?: { endpoint: string }; session?: { stoppedat?: number; pausedat?: number; expiresat: number }; capabilities?: capabilityreport; holds?: { heldkeys: keyholdstate[] }; dialogs?: dialogdecision[]; signals?: pagesignallike; navstate?: navstate; offline?: boolean; waitprofile?: waitprofilerecord; navqueues?: navqueues; windows?: windowshape[]; badges?: tabbadge[]; captchas?: captchahandoff[]; datasets?: dataset[]; streams?: streamstate[] };\n if (endpointinput && context.config) endpointinput.value = context.config.endpoint;\n rendercapabilities(context.capabilities);\n renderlivestate(context.holds?.heldkeys, context.dialogs, context.signals);\n rendernavstate(context.navstate, context.offline, context.waitprofile, context.navqueues);\n renderwindowlayout(context.windows, context.badges);\n rendercaptchastate(context.captchas);\n renderdatasetstate(context.datasets, context.streams);\n const active = context.session && !context.session.stoppedat && context.session.expiresat > Date.now();\n if (pausebutton) { pausebutton.disabled = !active; pausebutton.textContent = pauselabel(Boolean(context.session?.pausedat)); }\n if (active && context.session?.pausedat) status(\"Session paused. Reviewed actions are blocked until resume.\");\n else status(active ? \"Session active. Review the plan in the side panel.\" : \"No active browser session.\");\n}\n\nconnectbutton?.addEventListener(\"click\", async () => {\n try {\n const config = normalizeendpoint(endpointinput?.value ?? \"\");\n const granted = await chrome.permissions.request({ origins: [hostpattern(config.origin)] });\n if (!granted) throw new Error(\"Origin permission was not granted.\");\n await request({ kind: \"configure\", endpoint: config.endpoint });\n status(`Endpoint approved for ${config.origin}.`);\n } catch (error) { status(error instanceof Error ? error.message : String(error), true); }\n});\nsessionbutton?.addEventListener(\"click\", async () => { try { await request({ kind: \"startsession\" }); status(\"Session started for the active HTTPS tab.\"); await restore(); } catch (error) { status(error instanceof Error ? error.message : String(error), true); } });\npausebutton?.addEventListener(\"click\", async () => { try { const context = await request({ kind: \"context\" }) as { session?: { pausedat?: number } }; await request({ kind: context.session?.pausedat ? \"resumesession\" : \"pausesession\" }); await restore(); } catch (error) { status(error instanceof Error ? error.message : String(error), true); } });\nstopbutton?.addEventListener(\"click\", async () => { try { await request({ kind: \"stop\" }); status(\"Session stopped. No action can continue.\"); await restore(); } catch (error) { status(error instanceof Error ? error.message : String(error), true); } });\nopenbutton?.addEventListener(\"click\", () => chrome.sidePanel.open({ windowId: chrome.windows.WINDOW_ID_CURRENT }));\nrestore().catch(error => status(error instanceof Error ? error.message : String(error), true));\n"],
5
- "mappings": ";AAEA,IAAM,mBAAmB,oBAAI,IAAgB,CAAC,SAAS,QAAQ,YAAY,UAAU,YAAY,QAAQ,QAAQ,UAAU,SAAS,SAAS,WAAW,UAAU,UAAU,UAAU,QAAQ,WAAW,gBAAgB,gBAAgB,mBAAmB,YAAY,aAAa,eAAe,YAAY,aAAa,gBAAgB,eAAe,gBAAgB,gBAAgB,cAAc,cAAc,iBAAiB,cAAc,YAAY,cAAc,YAAY,YAAY,WAAW,cAAc,gBAAgB,eAAe,eAAe,aAAa,WAAW,YAAY,YAAY,eAAe,eAAe,WAAW,cAAc,UAAU,gBAAgB,eAAe,WAAW,cAAc,cAAc,YAAY,YAAY,cAAc,YAAY,aAAa,YAAY,WAAW,iBAAiB,aAAa,gBAAgB,gBAAgB,UAAU,WAAW,WAAW,iBAAiB,aAAa,cAAc,iBAAiB,cAAc,cAAc,UAAU,WAAW,aAAa,kBAAkB,kBAAkB,iBAAiB,eAAe,iBAAiB,mBAAmB,cAAc,iBAAiB,aAAa,YAAY,YAAY,aAAa,mBAAmB,cAAc,aAAa,aAAa,eAAe,iBAAiB,YAAY,cAAc,YAAY,YAAY,mBAAmB,aAAa,cAAc,eAAe,aAAa,cAAc,cAAc,mBAAmB,eAAe,CAAC;AACr+C,IAAM,qBAAqB,oBAAI,IAAgB,CAAC,SAAS,UAAU,SAAS,aAAa,cAAc,eAAe,cAAc,YAAY,aAAa,aAAa,cAAc,WAAW,eAAe,aAAa,aAAa,aAAa,iBAAiB,gBAAgB,aAAa,CAAC;AACxS,IAAM,cAAc,oBAAI,IAAgB,CAAC,WAAW,W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,WAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,IAAI;AAAA,EAAG;AAAE,CAAC;AAC3P,YAAY,iBAAiB,SAAS,MAAM,OAAO,UAAU,KAAK,EAAE,UAAU,OAAO,QAAQ,kBAAkB,CAAC,CAAC;AACjH,QAAQ,EAAE,MAAM,WAAS,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,IAAI,CAAC;",
4
+ "sourcesContent": ["import type { actionkind, agentplan, agentsession, cleanuprule, downloadspec, endpointconfig, fieldkind, formprofile, mimefilter, observationmode, policyevaluation, quarantineentry, runsettings, safetyverdict, toolstep, transformrule } 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\", \"fillform\", \"filllabel\", \"fillplaceholder\", \"submitform\", \"retryform\", \"runwizard\", \"selectchain\", \"picktypeahead\", \"pickdate\", \"attachfile\", \"fillcard\", \"fillcode\", \"consentpassword\", \"exportcsv\", \"exportjson\", \"exportexcel\", \"copytable\", \"pushsheets\", \"streamdisk\", \"paginateextract\", \"resumeextract\", \"batchdownload\", \"pausedownload\", \"resumedownload\", \"interceptmime\", \"readclipboard\", \"writeclipboard\", \"copyscreen\", \"quarantinedownload\", \"scanvirus\", \"cleanupartifacts\"]);\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\", \"detectfields\", \"generatevalues\", \"saveprofiles\", \"asksubmit\", \"readerrors\", \"skiphoneypot\", \"detectlogin\", \"detecttemplate\", \"handoffcaptcha\", \"scrapetable\", \"importcsv\", \"looprows\", \"transformvalues\", \"deduperows\", \"mergepages\", \"stamplerows\", \"previewgrid\", \"logprovenance\", \"verifydownload\", \"exportnetlog\", \"namecaptures\"]);\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\", \"submitform\", \"retryform\", \"selectchain\", \"picktypeahead\", \"pickdate\", \"attachfile\", \"fillcode\", \"consentpassword\", \"scrapetable\", \"paginateextract\"]);\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\", \"asksubmit\", \"selectchain\", \"picktypeahead\", \"pickdate\", \"attachfile\", \"fillcode\", \"consentpassword\", \"pausedownload\", \"resumedownload\", \"verifydownload\", \"writeclipboard\", \"quarantinedownload\", \"scanvirus\"]);\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 formactions = new Set<actionkind>([\"fillform\", \"filllabel\", \"fillplaceholder\", \"detectfields\", \"generatevalues\", \"saveprofiles\", \"asksubmit\", \"submitform\", \"readerrors\", \"retryform\", \"runwizard\", \"selectchain\", \"picktypeahead\", \"pickdate\", \"attachfile\", \"handoffcaptcha\", \"fillcard\", \"fillcode\", \"consentpassword\", \"skiphoneypot\", \"detectlogin\", \"detecttemplate\"]);\n/** Extraction, transform, export and provenance kinds of the forms and data part two family. */\nconst datasetactions = new Set<actionkind>([\"scrapetable\", \"exportcsv\", \"exportjson\", \"exportexcel\", \"copytable\", \"pushsheets\", \"importcsv\", \"looprows\", \"transformvalues\", \"deduperows\", \"paginateextract\", \"mergepages\", \"stamplerows\", \"previewgrid\", \"streamdisk\", \"resumeextract\", \"logprovenance\"]);\n/** Export kinds that move extracted data out of local memory to disk, the clipboard or a reviewed sheet endpoint. */\nconst exportactions = new Set<actionkind>([\"exportcsv\", \"exportjson\", \"exportexcel\", \"copytable\", \"pushsheets\", \"streamdisk\"]);\n/** Files, clipboard and downloads kinds of the batch queue, interception, clipboard, quarantine, naming and cleanup family. */\nconst filesactions = new Set<actionkind>([\"batchdownload\", \"pausedownload\", \"resumedownload\", \"verifydownload\", \"interceptmime\", \"exportnetlog\", \"readclipboard\", \"writeclipboard\", \"copyscreen\", \"quarantinedownload\", \"scanvirus\", \"namecaptures\", \"cleanupartifacts\"]);\n/** Field kinds the form grammar accepts inside records, profiles and value rules. */\nconst fieldkinds: fieldkind[] = [\"text\", \"email\", \"phone\", \"date\", \"number\", \"select\", \"check\", \"radio\", \"file\", \"password\", \"card\", \"code\"];\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 === \"copytable\") return \"clipboardWrite\";\n if (kind === \"batchdownload\" || kind === \"pausedownload\" || kind === \"resumedownload\" || kind === \"verifydownload\" || kind === \"interceptmime\" || kind === \"quarantinedownload\" || kind === \"scanvirus\") return \"downloads\";\n if (kind === \"readclipboard\") return \"clipboardRead\";\n if (kind === \"writeclipboard\" || kind === \"copyscreen\") return \"clipboardWrite\";\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/** True when the kind belongs to the forms and data family. */\nexport function isformkind(kind: actionkind): boolean {\n return formactions.has(kind);\n}\n\n/** True when the kind belongs to the extraction, transform, export and provenance family. */\nexport function isdatasetkind(kind: actionkind): boolean {\n return datasetactions.has(kind);\n}\n\n/** True when the kind exports extracted data out of local memory to disk, the clipboard or a reviewed sheet endpoint. */\nexport function isexportkind(kind: actionkind): boolean {\n return exportactions.has(kind);\n}\n\n/** True when the kind belongs to the files, clipboard and downloads family. */\nexport function isfileskind(kind: actionkind): boolean {\n return filesactions.has(kind);\n}\n\n/** Refuses any export that would leave local memory while the session origin grants do not cover the active origin. */\nexport function exportgranted(session: agentsession | undefined, origin: string): policyevaluation {\n if (!origingranted(session, origin)) return { allowed: false, reason: `The export of extracted data from ${origin} needs the session origin grants before it leaves local memory.` };\n return { allowed: true };\n}\n\n/** Validates the reviewed fieldmatch grammar of one form field entry. */\nexport function validatefieldmatch(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed field match is required in options.\" };\n const match = value as Record<string, unknown>;\n if (match.mode !== \"label\" && match.mode !== \"placeholder\" && match.mode !== \"arialabel\" && match.mode !== \"name\") return { allowed: false, reason: \"The reviewed field match mode must be label, placeholder, arialabel or name.\" };\n const key = match.mode === \"label\" ? \"label\" : match.mode === \"placeholder\" ? \"placeholder\" : match.mode === \"arialabel\" ? \"arialabel\" : \"name\";\n if (!isnonempty(match[key])) return { allowed: false, reason: `The reviewed ${match.mode} field match needs a non-empty ${key}.` };\n return { allowed: true };\n}\n\n/** Validates a reviewed structured form record; password entries are refused because passwords need the explicit consentpassword consent. */\nexport function validateformrecord(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed form record with entries is required in options.\" };\n const record = value as Record<string, unknown>;\n if (record.form !== undefined && !isnonempty(record.form)) return { allowed: false, reason: \"The reviewed form record form selector must be a non-empty string.\" };\n if (!Array.isArray(record.entries) || record.entries.length === 0) return { allowed: false, reason: \"The reviewed form record needs a non-empty list of entries.\" };\n for (const item of record.entries) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return { allowed: false, reason: \"Every reviewed form record entry must be an object.\" };\n const entry = item as Record<string, unknown>;\n const matchcheck = validatefieldmatch(entry.match);\n if (!matchcheck.allowed) return matchcheck;\n if (typeof entry.kind !== \"string\" || !fieldkinds.includes(entry.kind as fieldkind)) return { allowed: false, reason: \"Every reviewed form record entry needs a known field kind.\" };\n if (typeof entry.value !== \"string\") return { allowed: false, reason: \"Every reviewed form record entry needs a string value.\" };\n if (entry.kind === \"password\") return { allowed: false, reason: \"Password entries are refused inside form records; use consentpassword with a reviewed consent ref.\" };\n }\n return { allowed: true };\n}\n\n/** Validates the reviewed valuegen grammar of a generatevalues step. */\nexport function validatevaluegen(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed valuegen rule with a field kind is required in options.\" };\n const rule = value as Record<string, unknown>;\n if (typeof rule.kind !== \"string\" || !fieldkinds.includes(rule.kind as fieldkind)) return { allowed: false, reason: \"The reviewed valuegen kind must be a known field kind.\" };\n if (rule.locale !== undefined && !isnonempty(rule.locale)) return { allowed: false, reason: \"The reviewed valuegen locale must be a non-empty string.\" };\n if (rule.seed !== undefined && (typeof rule.seed !== \"number\" || !Number.isFinite(rule.seed))) return { allowed: false, reason: \"The reviewed valuegen seed must be a finite number.\" };\n return { allowed: true };\n}\n\n/** Validates a reviewed list of label or placeholder value pairs for filllabel and fillplaceholder steps. */\nfunction validatefieldpairs(options: Record<string, unknown>, mode: \"label\" | \"placeholder\"): policyevaluation {\n const pairs = options.fields;\n if (!Array.isArray(pairs) || pairs.length === 0) return { allowed: false, reason: \"A reviewed non-empty list of field pairs is required in options.\" };\n for (const item of pairs) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return { allowed: false, reason: \"Every reviewed field pair must be an object.\" };\n const pair = item as Record<string, unknown>;\n if (!isnonempty(pair[mode])) return { allowed: false, reason: `Every reviewed field pair needs a non-empty ${mode}.` };\n if (typeof pair.value !== \"string\" || !pair.value.trim()) return { allowed: false, reason: \"Every reviewed field pair needs a non-empty value.\" };\n }\n return { allowed: true };\n}\n\n/** Validates the reviewed card segment grammar of a fillcard step. */\nfunction validatecardsegments(value: unknown): policyevaluation {\n if (!Array.isArray(value) || value.length === 0) return { allowed: false, reason: \"A reviewed non-empty list of card segments is required in options.\" };\n for (const item of value) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return { allowed: false, reason: \"Every reviewed card segment must be an object.\" };\n const segment = item as Record<string, unknown>;\n const matchcheck = validatefieldmatch(segment.match);\n if (!matchcheck.allowed) return matchcheck;\n if (typeof segment.value !== \"string\" || !segment.value.trim()) return { allowed: false, reason: \"Every reviewed card segment needs a non-empty value.\" };\n }\n return { allowed: true };\n}\n\n/** Validates the reviewed forms and data parameter grammar of the form family. */\nfunction validateformgrammar(step: toolstep, options: Record<string, unknown>): policyevaluation {\n const kind = step.kind;\n if (kind === \"fillform\" || (kind === \"saveprofiles\" && options.formrecord !== undefined)) {\n const recordcheck = validateformrecord(options.formrecord);\n if (!recordcheck.allowed) return recordcheck;\n }\n if (kind === \"filllabel\" || kind === \"fillplaceholder\") {\n const paircheck = validatefieldpairs(options, kind === \"filllabel\" ? \"label\" : \"placeholder\");\n if (!paircheck.allowed) return paircheck;\n }\n if (kind === \"generatevalues\" && options.valuegen !== undefined) {\n const rulecheck = validatevaluegen(options.valuegen);\n if (!rulecheck.allowed) return rulecheck;\n }\n if (kind === \"saveprofiles\" && !isnonempty(options.name)) return { allowed: false, reason: \"A reviewed profile name is required in options.\" };\n if (kind === \"submitform\" && !isnonempty(options.consentref)) return { allowed: false, reason: \"A reviewed consent ref of an approved asksubmit ticket is required in options.\" };\n if (kind === \"retryform\") {\n const backoff = options.backoff;\n if (!backoff || typeof backoff !== \"object\" || Array.isArray(backoff)) return { allowed: false, reason: \"A reviewed backoff rule with wait and factor is required in options.\" };\n const rule = backoff as Record<string, unknown>;\n if (typeof rule.wait !== \"number\" || !Number.isFinite(rule.wait) || rule.wait <= 0) return { allowed: false, reason: \"The reviewed retry backoff wait must be a positive number of milliseconds with no code ceiling.\" };\n if (typeof rule.factor !== \"number\" || !Number.isFinite(rule.factor) || rule.factor < 1) return { allowed: false, reason: \"The reviewed retry backoff factor must be one or greater with no code ceiling.\" };\n if (options.attempts !== undefined && (typeof options.attempts !== \"number\" || !Number.isInteger(options.attempts) || options.attempts < 1)) return { allowed: false, reason: \"The reviewed retry attempts must be a positive integer with no code ceiling.\" };\n }\n if (kind === \"runwizard\" && options.steps !== undefined && (typeof options.steps !== \"number\" || !Number.isInteger(options.steps) || options.steps < 1)) return { allowed: false, reason: \"The reviewed wizard step count must be a positive integer with no code ceiling.\" };\n if (kind === \"selectchain\") {\n if (!isnonempty(options.child)) return { allowed: false, reason: \"A reviewed child selector of the dependent control is required in options.\" };\n if (!nonnegativeoption(options, \"wait\")) return { allowed: false, reason: \"The reviewed dependent wait must be zero or a positive number of milliseconds.\" };\n }\n if (kind === \"picktypeahead\") {\n if (!isnonempty(options.pick)) return { allowed: false, reason: \"A reviewed suggestion entry to pick is required in options.\" };\n if (!nonnegativeoption(options, \"timeout\")) return { allowed: false, reason: \"The reviewed typeahead timeout must be zero or a positive number of milliseconds.\" };\n }\n if (kind === \"pickdate\" && !/^\\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 (kind === \"fillcard\") {\n const segmentcheck = validatecardsegments(options.segments);\n if (!segmentcheck.allowed) return segmentcheck;\n if (!nonnegativeoption(options, \"pause\")) return { allowed: false, reason: \"The reviewed card typing pause must be zero or a positive number of milliseconds.\" };\n }\n if (kind === \"fillcode\" && !isnonempty(options.source)) return { allowed: false, reason: \"A reviewed one time code source is required in options.\" };\n if (kind === \"consentpassword\" && !isnonempty(options.consentref)) return { allowed: false, reason: \"A reviewed consent ref is required in options before any password is filled.\" };\n return { allowed: true };\n}\n\n/** Validates one reviewed transform rule: a supported expression, source columns and a target column. */\nexport function validatetransformrule(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed transform rule with an expression, sources and a target is required in options.\" };\n const rule = value as Record<string, unknown>;\n const expression = rule.expression;\n if (typeof expression !== \"string\" || !/^(trim|upper|lower|number|prefix|suffix|replace)(?::.+)?$/.test(expression)) return { allowed: false, reason: \"The reviewed transform expression must be trim, upper, lower, number, prefix, suffix or replace with an optional argument.\" };\n if (expression.startsWith(\"replace\") && !expression.slice(\"replace\".length).includes(\"=>\")) return { allowed: false, reason: \"The reviewed replace expression needs the from=>to separator.\" };\n if (expression.startsWith(\"replace\") && expression.slice(\"replace:\".length).split(\"=>\")[0] === \"\") return { allowed: false, reason: \"The reviewed replace expression needs a non-empty from part.\" };\n if (!Array.isArray(rule.sources) || rule.sources.length === 0 || !rule.sources.every(source => isnonempty(source))) return { allowed: false, reason: \"Every reviewed transform rule needs a non-empty list of source columns.\" };\n if (!isnonempty(rule.target)) return { allowed: false, reason: \"Every reviewed transform rule needs a non-empty target column.\" };\n return { allowed: true };\n}\n\n/** Validates a reviewed dataset id list in options. */\nfunction validatedatasetids(options: Record<string, unknown>, key: string): policyevaluation {\n const ids = options[key];\n if (!Array.isArray(ids) || ids.length === 0 || !ids.every(id => isnonempty(id))) return { allowed: false, reason: `A reviewed non-empty list of dataset ids is required in options as ${key}.` };\n return { allowed: true };\n}\n\n/** Validates the reviewed extraction, transform, export and provenance parameter grammar of the data family. */\nfunction validatedatagrammar(step: toolstep, options: Record<string, unknown>, origin: string): policyevaluation {\n const kind = step.kind;\n if (kind === \"scrapetable\") {\n if (options.name !== undefined && !isnonempty(options.name)) return { allowed: false, reason: \"The reviewed dataset name must be a non-empty string.\" };\n if (options.rowlimit !== undefined && (typeof options.rowlimit !== \"number\" || !Number.isInteger(options.rowlimit) || options.rowlimit < 1)) return { allowed: false, reason: \"The reviewed row limit must be a positive integer with no code ceiling.\" };\n }\n if (kind === \"paginateextract\") {\n if (!isnonempty(options.next)) return { allowed: false, reason: \"A reviewed next control selector is required in options.\" };\n if (options.pages !== undefined && (typeof options.pages !== \"number\" || !Number.isInteger(options.pages) || options.pages < 1)) return { allowed: false, reason: \"The reviewed page count must be a positive integer with no code ceiling.\" };\n if (!nonnegativeoption(options, \"wait\")) return { allowed: false, reason: \"The reviewed row freshness wait must be zero or a positive number of milliseconds.\" };\n }\n if (kind === \"exportcsv\" || kind === \"exportjson\" || kind === \"exportexcel\" || kind === \"copytable\" || kind === \"streamdisk\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (options.name !== undefined && !isnonempty(options.name)) return { allowed: false, reason: \"The reviewed artifact name must be a non-empty string.\" };\n }\n if (kind === \"exportcsv\" && options.delimiter !== undefined && (typeof options.delimiter !== \"string\" || options.delimiter.length !== 1)) return { allowed: false, reason: \"The reviewed csv delimiter must be a single character.\" };\n if (kind === \"streamdisk\" && (typeof options.chunk !== \"number\" || !Number.isInteger(options.chunk) || options.chunk < 1)) return { allowed: false, reason: \"The reviewed streaming chunk size must be a positive integer with no code ceiling.\" };\n if (kind === \"pushsheets\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (!isnonempty(options.sheet)) return { allowed: false, reason: \"A reviewed sheet endpoint url is required in options.\" };\n if (!ishttpsurl(options.sheet)) return { allowed: false, reason: \"The reviewed sheet endpoint url must use HTTPS.\" };\n if (options.reviewed !== true) return { allowed: false, reason: \"The sheet push needs the explicit reviewed flag before any data leaves local memory.\" };\n }\n if (kind === \"importcsv\") {\n if (typeof options.csv !== \"string\" || !options.csv.trim()) return { allowed: false, reason: \"Reviewed csv content is required in options.\" };\n if (options.name !== undefined && !isnonempty(options.name)) return { allowed: false, reason: \"The reviewed dataset name must be a non-empty string.\" };\n if (options.mapping !== undefined) {\n const mapping = options.mapping;\n if (!mapping || typeof mapping !== \"object\" || Array.isArray(mapping) || !Object.values(mapping).every(item => typeof item === \"string\")) return { allowed: false, reason: \"The reviewed csv column mapping must be an object of string values.\" };\n }\n }\n if (kind === \"looprows\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (options.variable !== undefined && !isnonempty(options.variable)) return { allowed: false, reason: \"The reviewed row variable name must be a non-empty string.\" };\n const inner = validateinnerstep(options, origin);\n if (!inner.allowed) return inner;\n }\n if (kind === \"transformvalues\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n const rules = options.rules;\n if (!Array.isArray(rules) || rules.length === 0) return { allowed: false, reason: \"A reviewed non-empty list of transform rules is required in options.\" };\n for (const item of rules) {\n const rulecheck = validatetransformrule(item);\n if (!rulecheck.allowed) return rulecheck;\n }\n }\n if (kind === \"deduperows\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n const keys = options.keys;\n if (!Array.isArray(keys) || keys.length === 0 || !keys.every(key => isnonempty(key))) return { allowed: false, reason: \"A reviewed non-empty list of dedupe column keys is required in options.\" };\n }\n if (kind === \"mergepages\") {\n const listcheck = validatedatasetids(options, \"datasets\");\n if (!listcheck.allowed) return listcheck;\n }\n if (kind === \"stamplerows\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (options.url !== undefined && !ishttpsurl(options.url)) return { allowed: false, reason: \"The reviewed source url must use HTTPS.\" };\n }\n if (kind === \"previewgrid\") {\n if (!isnonempty(options.dataset)) return { allowed: false, reason: \"A reviewed dataset id is required in options.\" };\n if (options.sample !== undefined && (typeof options.sample !== \"number\" || !Number.isInteger(options.sample) || options.sample < 1)) return { allowed: false, reason: \"The reviewed sample row count must be a positive integer with no code ceiling.\" };\n }\n if (kind === \"resumeextract\" && !isnonempty(options.session)) return { allowed: false, reason: \"A reviewed extract session id is required in options.\" };\n if (kind === \"logprovenance\" && !isnonempty(options.artifact)) return { allowed: false, reason: \"A reviewed artifact id or name is required in options.\" };\n return { allowed: true };\n}\n\n/** Validates a reviewed batch download specification: a non-empty HTTPS url list, an optional filename rule and an optional completion criterion. */\nexport function validatedownloadspec(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed downloadspec with a url list is required in options.\" };\n const spec = value as Record<string, unknown>;\n if (!Array.isArray(spec.urls) || spec.urls.length === 0 || !spec.urls.every(url => ishttpsurl(url))) return { allowed: false, reason: \"The reviewed downloadspec needs a non-empty list of HTTPS urls.\" };\n if (spec.filename !== undefined && !isnonempty(spec.filename)) return { allowed: false, reason: \"The reviewed downloadspec filename rule must be a non-empty string.\" };\n if (spec.complete !== undefined && spec.complete !== \"size\" && spec.complete !== \"checksum\") return { allowed: false, reason: \"The reviewed downloadspec completion criterion must be size or checksum.\" };\n return { allowed: true };\n}\n\n/** Validates a reviewed mime interception filter: include and exclude patterns plus the deny default for unlisted mime types. */\nexport function validatemimefilter(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed mimefilter with include and exclude patterns is required in options.\" };\n const filter = value as Record<string, unknown>;\n if (!Array.isArray(filter.include) || filter.include.length === 0 || !filter.include.every(pattern => isnonempty(pattern))) return { allowed: false, reason: \"The reviewed mimefilter needs a non-empty list of include patterns.\" };\n if (filter.exclude !== undefined && (!Array.isArray(filter.exclude) || !filter.exclude.every(pattern => isnonempty(pattern)))) return { allowed: false, reason: \"The reviewed mimefilter exclude patterns must be a list of non-empty strings.\" };\n if (filter.default !== \"deny\" && filter.default !== \"allow\") return { allowed: false, reason: \"The reviewed mimefilter needs the deny or allow default for unlisted mime types.\" };\n return { allowed: true };\n}\n\n/** Validates one reviewed cleanup rule: a positive age window with no code ceiling, an artifact kind and a keep policy. */\nexport function validatecleanuprule(value: unknown): policyevaluation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { allowed: false, reason: \"A reviewed cleanuprule with an age, a kind and a keep policy is required.\" };\n const rule = value as Record<string, unknown>;\n if (typeof rule.age !== \"number\" || !Number.isFinite(rule.age) || rule.age <= 0) return { allowed: false, reason: \"The reviewed cleanup age window must be a positive number of milliseconds with no code ceiling.\" };\n if (!isnonempty(rule.kind)) return { allowed: false, reason: \"The reviewed cleanup rule needs a non-empty artifact kind, or any to match every kind.\" };\n if (rule.keep !== \"none\" && rule.keep !== \"latest\" && rule.keep !== \"all\") return { allowed: false, reason: \"The reviewed cleanup keep policy must be none, latest or all.\" };\n return { allowed: true };\n}\n\n/** Validates the reviewed files, clipboard and downloads parameter grammar; batch sizes, concurrent windows and cleanup ages stay user configured with no code ceilings. */\nfunction validatefilesgrammar(step: toolstep, options: Record<string, unknown>): policyevaluation {\n const kind = step.kind;\n if (kind === \"batchdownload\") {\n const speccheck = validatedownloadspec(options.downloadspec);\n if (!speccheck.allowed) return speccheck;\n if (options.concurrent !== undefined && (typeof options.concurrent !== \"number\" || !Number.isInteger(options.concurrent) || options.concurrent < 1)) return { allowed: false, reason: \"The reviewed concurrent download window must be a positive integer with no code ceiling.\" };\n }\n if (kind === \"pausedownload\" || kind === \"resumedownload\" || kind === \"verifydownload\" || kind === \"quarantinedownload\" || kind === \"scanvirus\") {\n if (!isnonempty(step.value)) return { allowed: false, reason: \"A reviewed download or quarantine reference is required.\" };\n if (kind === \"verifydownload\") {\n if (options.checksum !== undefined && !isnonempty(options.checksum)) return { allowed: false, reason: \"The reviewed expected checksum must be a non-empty string.\" };\n if (options.bytes !== undefined && (typeof options.bytes !== \"number\" || !Number.isFinite(options.bytes) || options.bytes < 0)) return { allowed: false, reason: \"The reviewed expected size must be zero or a positive number of bytes.\" };\n }\n if (kind === \"scanvirus\" && options.scanner !== undefined && !isnonempty(options.scanner)) return { allowed: false, reason: \"The reviewed scanner name must be a non-empty string.\" };\n if (kind === \"quarantinedownload\" && options.reason !== undefined && !isnonempty(options.reason)) return { allowed: false, reason: \"The reviewed quarantine reason must be a non-empty string.\" };\n }\n if (kind === \"interceptmime\") {\n const filtercheck = validatemimefilter(options.mimefilter);\n if (!filtercheck.allowed) return filtercheck;\n }\n if (kind === \"readclipboard\") {\n if (!isnonempty(options.consentref)) return { allowed: false, reason: \"A clipboard read requires a reviewed consent ref of an approved consent prompt in options.\" };\n if (options.prompt !== undefined && !isnonempty(options.prompt)) return { allowed: false, reason: \"The reviewed clipboard consent prompt must be a non-empty string.\" };\n }\n if (kind === \"exportnetlog\" && options.stepid !== undefined && !isnonempty(options.stepid)) return { allowed: false, reason: \"The reviewed netlog step filter must be a non-empty step id.\" };\n if (kind === \"namecaptures\") {\n if (!isnonempty(options.task)) return { allowed: false, reason: \"A reviewed task id is required in options for capture naming.\" };\n if (options.steps !== undefined && (!Array.isArray(options.steps) || options.steps.length === 0 || !options.steps.every(item => isnonempty(item)))) return { allowed: false, reason: \"The reviewed capture steps must be a non-empty list of step ids when present.\" };\n if (options.extension !== undefined && !isnonempty(options.extension)) return { allowed: false, reason: \"The reviewed capture extension must be a non-empty string.\" };\n }\n if (kind === \"cleanupartifacts\" && options.rules !== undefined) {\n const rules = options.rules;\n if (!Array.isArray(rules) || rules.length === 0) return { allowed: false, reason: \"The reviewed cleanup rules must be a non-empty list when present.\" };\n for (const item of rules) {\n const rulecheck = validatecleanuprule(item);\n if (!rulecheck.allowed) return rulecheck;\n }\n }\n return { allowed: true };\n}\n\n/** Requires an approved consent prompt before any clipboard read; every read consumes its own prompt. */\nexport function clipboardconsentgranted(step: toolstep): policyevaluation {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const consentref = options.consentref;\n if (typeof consentref !== \"string\" || !consentref.trim()) return { allowed: false, reason: \"A clipboard read requires a reviewed consent ref in options.\" };\n return { allowed: true };\n}\n\n/** Refuses to release any quarantined file before a clean scan verdict exists. */\nexport function quarantinereleasegranted(entry: quarantineentry): policyevaluation {\n if (entry.scan !== \"clean\") return { allowed: false, reason: `The quarantined file ${entry.path} cannot leave quarantine with the ${entry.scan} scan verdict; only a clean verdict releases it.` };\n return { allowed: true };\n}\n\n/** Refuses downloads and download interception that fall outside the session origin grants. */\nexport function downloadgranted(session: agentsession | undefined, url: string): policyevaluation {\n let origin = \"\";\n try { origin = new URL(url).origin; } catch { return { allowed: false, reason: \"The reviewed download URL is invalid.\" }; }\n if (!origingranted(session, origin)) return { allowed: false, reason: `The download from ${origin} leaves the session origin grants and needs a session grant first.` };\n return { allowed: true };\n}\n\n/** Masks a clipboard payload for every log line; the full text never persists anywhere. */\nexport function maskclipboard(payload: string): string {\n return `[clipboard payload of ${payload.length} character${payload.length === 1 ? \"\" : \"s\"}]`;\n}\n\n/** Requires an asksubmit review step before every form submission step. */\nexport function submitreviewgranted(steps: toolstep[], submitid: string): policyevaluation {\n const position = steps.findIndex(candidate => candidate.id === submitid);\n const asked = steps.some((candidate, index) => candidate.kind === \"asksubmit\" && (position === -1 || index < position));\n return asked ? { allowed: true } : { allowed: false, reason: \"Form submission requires an asksubmit review step before it.\" };\n}\n\n/** Requires a reviewed consent ref before any password field is filled. */\nexport function passwordconsentgranted(step: toolstep): policyevaluation {\n let options: Record<string, unknown> = {};\n try { options = parseoptions(step); } catch { options = {}; }\n const consentref = options.consentref;\n if (typeof consentref !== \"string\" || !consentref.trim()) return { allowed: false, reason: \"A password fill requires a reviewed consent ref in options.\" };\n return { allowed: true };\n}\n\n/** True when a numeric value passes the Luhn checksum used by card networks. */\nfunction luhnvalid(digits: string): boolean {\n let sum = 0;\n let double = false;\n for (let index = digits.length - 1; index >= 0; index -= 1) {\n let value = Number.parseInt(digits[index] ?? \"\", 10);\n if (!Number.isFinite(value)) return false;\n if (double) { value *= 2; if (value > 9) value -= 9; }\n sum += value;\n double = !double;\n }\n return sum % 10 === 0;\n}\n\n/** Refuses generated values that look like real card numbers or personal identifiers; test prefixed card values stay allowed. */\nexport function generatedvalueallowed(value: string): policyevaluation {\n const compact = value.replace(/[\\s-]/g, \"\");\n if (/^\\d{13,19}$/.test(compact) && luhnvalid(compact) && !compact.startsWith(\"4111\")) return { allowed: false, reason: \"The generated value looks like a real card number and is refused; generated card values use the 4111 test prefix.\" };\n if (/^\\d{3}-\\d{2}-\\d{4}$/.test(value.trim())) return { allowed: false, reason: \"The generated value looks like a personal identifier and is refused.\" };\n return { allowed: true };\n}\n\n/** Requires the origin grants of a saved profile to cover the origin before its values fill a page. */\nexport function profilegrantgranted(profile: formprofile, origin: string): policyevaluation {\n if (!profile.grants.includes(origin)) return { allowed: false, reason: `The saved profile ${profile.name} is not granted to ${origin}; add the origin to the profile grants first.` };\n return { allowed: true };\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\" || kind === \"looprows\") 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 (isformkind(step.kind)) {\n const formcheck = validateformgrammar(step, options);\n if (!formcheck.allowed) return formcheck;\n }\n if (isdatasetkind(step.kind)) {\n const datacheck = validatedatagrammar(step, options, origin);\n if (!datacheck.allowed) return datacheck;\n }\n if (isfileskind(step.kind)) {\n const filescheck = validatefilesgrammar(step, options);\n if (!filescheck.allowed) return filescheck;\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 (isexportkind(input.step.kind)) {\n const exportgate = exportgranted(input.session, input.origin);\n if (!exportgate.allowed) return exportgate;\n }\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 === \"submitform\" || input.step.kind === \"retryform\") {\n if (!input.plan) return { allowed: false, reason: \"Form submission requires an asksubmit review step before it.\" };\n const reviewgate = submitreviewgranted(input.plan.steps, input.step.id);\n if (!reviewgate.allowed) return reviewgate;\n }\n if (input.step.kind === \"consentpassword\") {\n const consentgate = passwordconsentgranted(input.step);\n if (!consentgate.allowed) return consentgate;\n }\n if (input.step.kind === \"readclipboard\") {\n const clipgate = clipboardconsentgranted(input.step);\n if (!clipgate.allowed) return clipgate;\n }\n if (input.step.kind === \"interceptmime\" && !origingranted(input.session, input.origin)) return { allowed: false, reason: \"The download interception is outside the session origin grants.\" };\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 { hostpattern, normalizeendpoint } from \"../policy.js\";\nimport type { capabilityreport, captchahandoff, clipboardconsentrecord, dataset, dialogdecision, downloadrecord, keyholdstate, navqueues, navstate, quarantineentry, streamstate, tabbadge, waitprofilerecord } from \"../types.js\";\nimport type { windowshape } from \"./tabscommand.js\";\n\ntype pagesignallike = { language?: string; template?: string; scrolllocked?: boolean; banner?: string };\n\nconst endpointinput = document.querySelector<HTMLInputElement>(\"#endpoint\");\nconst statusnode = document.querySelector<HTMLElement>(\"#status\");\nconst capabilitiesnode = document.querySelector<HTMLElement>(\"#capabilities\");\nconst livenode = document.querySelector<HTMLElement>(\"#livelogic\");\nconst navstatenode = document.querySelector<HTMLElement>(\"#navstate\");\nconst windowlayoutnode = document.querySelector<HTMLElement>(\"#windowlayout\");\nconst captchastatenode = document.querySelector<HTMLElement>(\"#captchastate\");\nconst datasetstatenode = document.querySelector<HTMLElement>(\"#datasetstate\");\nconst downloadstatenode = document.querySelector<HTMLElement>(\"#downloadstate\");\nconst clipboardstatenode = document.querySelector<HTMLElement>(\"#clipboardstate\");\nconst windowcontrols = document.querySelector<HTMLElement>(\"#windowcontrols\");\nconst connectbutton = document.querySelector<HTMLButtonElement>(\"#connect\");\nconst sessionbutton = document.querySelector<HTMLButtonElement>(\"#session\");\nconst pausebutton = document.querySelector<HTMLButtonElement>(\"#pause\");\nconst stopbutton = document.querySelector<HTMLButtonElement>(\"#stop\");\nconst openbutton = document.querySelector<HTMLButtonElement>(\"#openpanel\");\n\nfunction status(message: string, error = false): void { if (statusnode) { statusnode.textContent = message; statusnode.dataset.state = error ? \"error\" : \"ready\"; } }\nasync function request(message: unknown): Promise<unknown> { const response = await chrome.runtime.sendMessage(message) as { ok: boolean; value?: unknown; error?: string }; if (!response.ok) throw new Error(response.error); return response.value; }\n\nfunction pauselabel(paused: boolean): string { return paused ? \"Resume session\" : \"Pause session\"; }\n\n/** Renders the live optional capability set the user has granted. */\nfunction rendercapabilities(report?: capabilityreport): void {\n if (!capabilitiesnode) return;\n if (!report) { capabilitiesnode.textContent = \"Capabilities unknown.\"; return; }\n const granted = [`tabs ${report.tabs ? \"granted\" : \"absent\"}`, `downloads ${report.downloads ? \"granted\" : \"absent\"}`, `clipboard read ${report.clipboardread ? \"granted\" : \"absent\"}`, `clipboard write ${report.clipboardwrite ? \"granted\" : \"absent\"}`];\n capabilitiesnode.textContent = `Optional capabilities: ${granted.join(\" \u00B7 \")}.`;\n}\n\n/** Renders the currently held keys and the dialogs answered by the reviewed policy. */\nfunction renderlivestate(holds?: keyholdstate[], dialogs?: dialogdecision[], signals?: pagesignallike): void {\n if (!livenode) return;\n const held = (holds ?? []).filter(hold => hold.releasedat === undefined);\n const heldsummary = held.length > 0 ? held.map(hold => `${hold.key}${hold.holdid ? ` (${hold.holdid})` : \"\"}`).join(\", \") : \"none\";\n const dialogsummary = (dialogs ?? []).length > 0 ? `${dialogs?.length} answered` : \"none\";\n const pages = signals && (signals.language !== undefined || signals.template !== undefined || signals.scrolllocked !== undefined)\n ? [signals.language !== undefined ? `language ${signals.language || \"unknown\"}` : \"\", signals.template !== undefined ? `template ${signals.template}` : \"\", signals.scrolllocked !== undefined ? `scroll lock ${signals.scrolllocked ? \"on\" : \"off\"}` : \"\"].filter(Boolean).join(\" \u00B7 \")\n : \"unknown\";\n livenode.textContent = `Held keys: ${heldsummary} \u00B7 Open dialogs answered: ${dialogsummary} \u00B7 Page signals: ${pages}.`;\n}\n\n/** Renders the load phase, offline state, active wait profile and queued navigation targets of the session tab. */\nfunction rendernavstate(state?: navstate, offline?: boolean, profile?: waitprofilerecord, queues?: navqueues): void {\n if (!navstatenode) return;\n const phase = state?.phase ? `load phase ${state.phase}` : \"load phase unknown\";\n const offlinestate = offline === undefined ? \"connectivity unknown\" : offline ? \"offline\" : \"online\";\n const wait = profile ? `wait profile ${profile.profile.signals.join(\"+\")}` : \"no wait profile\";\n const queued = queues ? `queued targets ${queues.prefetch + queues.batchopen} (${queues.prefetch} prefetch \u00B7 ${queues.batchopen} batch open)` : \"no queued targets\";\n navstatenode.textContent = `Navigation: ${phase} \u00B7 ${offlinestate} \u00B7 ${wait} \u00B7 ${queued}.`;\n}\n\n/** Renders the current window layout and the quick window state buttons. */\nfunction renderwindowlayout(windows?: windowshape[], badges?: tabbadge[]): void {\n if (!windowlayoutnode || !windowcontrols) return;\n windowlayoutnode.textContent = windows === undefined\n ? \"Window layout: unknown.\"\n : `Window layout: ${windows.length} window${windows.length === 1 ? \"\" : \"s\"}${windows.length > 0 ? ` (${windows.map(item => `${item.windowid}: ${item.state}${item.incognito ? \" incognito\" : \"\"}`).join(\" \u00B7 \")})` : \"\"} \u00B7 ${new Set((badges ?? []).map(badge => badge.tabid)).size} tab${new Set((badges ?? []).map(badge => badge.tabid)).size === 1 ? \"\" : \"s\"} with active tasks.`;\n windowcontrols.replaceChildren();\n for (const item of (windows ?? []).slice(0, 4)) {\n for (const state of [\"maximized\", \"minimized\", \"normal\"] as const) {\n const quick = document.createElement(\"button\");\n quick.type = \"button\";\n quick.className = \"secondary\";\n quick.textContent = `${state === \"normal\" ? \"restore\" : state} ${item.windowid}`;\n quick.addEventListener(\"click\", () => request({ kind: \"windowstate\", windowid: item.windowid, state }).then(() => { status(`Window ${item.windowid} set to ${state}.`); return restore(); }).catch(error => status(error instanceof Error ? error.message : String(error), true)));\n windowcontrols.append(quick);\n }\n }\n}\n\n/** Renders the captcha handoff state while a plan waits for the user. */\nfunction rendercaptchastate(captchas?: captchahandoff[]): void {\n if (!captchastatenode) return;\n const open = (captchas ?? []).find(handoff => !handoff.resolved);\n if (open) { captchastatenode.dataset.state = \"error\"; captchastatenode.textContent = `Captcha handoff open on ${open.origin}; the plan waits until you resolve it in the review panel.`; return; }\n delete captchastatenode.dataset.state;\n captchastatenode.textContent = \"Captcha handoff: none.\";\n}\n\n/** Renders the active dataset row count and the stream state of the session. */\nfunction renderdatasetstate(datasets?: dataset[], streams?: streamstate[]): void {\n if (!datasetstatenode) return;\n const rows = (datasets ?? []).reduce((total, datasetvalue) => total + datasetvalue.rows.length, 0);\n const count = datasets?.length ?? 0;\n const stream = (streams ?? []).find(item => item.done !== true) ?? (streams ?? [])[0];\n const streamsummary = stream ? ` \u00B7 stream ${stream.name} chunk ${stream.chunk} of ${stream.chunks}${stream.done ? \" complete\" : \"\"}` : \"\";\n datasetstatenode.textContent = count === 0 ? \"Datasets: none collected yet.\" : `Datasets: ${count} collected (${rows} row${rows === 1 ? \"\" : \"s\"})${streamsummary}.`;\n}\n\n/** Renders the live batch download states and the quarantined files awaiting scan verdicts. */\nfunction renderdownloadstate(downloads?: downloadrecord[], quarantines?: quarantineentry[]): void {\n if (!downloadstatenode) return;\n const states = (downloads ?? []).filter(record => record.state === \"running\" || record.state === \"queued\" || record.state === \"paused\");\n const completed = (downloads ?? []).filter(record => record.state === \"complete\").length;\n const failed = (downloads ?? []).filter(record => record.state === \"failed\").length;\n const pending = (quarantines ?? []).filter(entry => entry.scan === \"pending\").length;\n const parts = [\n states.length > 0 ? `${states.length} in flight (${states.map(record => record.state).join(\" \u00B7 \")})` : \"\",\n completed > 0 ? `${completed} completed` : \"\",\n failed > 0 ? `${failed} failed` : \"\",\n pending > 0 ? `${pending} quarantined awaiting scan` : \"\",\n ].filter(Boolean);\n downloadstatenode.textContent = (downloads ?? []).length === 0 && pending === 0 ? \"Downloads: none.\" : `Downloads: ${parts.join(\" \u00B7 \") || \"none active\"}.`;\n}\n\n/** Renders the clipboard consent state while a read waits for the user approval. */\nfunction renderclipboardstate(consents?: clipboardconsentrecord[]): void {\n if (!clipboardstatenode) return;\n const waiting = (consents ?? []).filter(record => record.approved === undefined);\n if (waiting.length > 0) {\n clipboardstatenode.dataset.state = \"error\";\n clipboardstatenode.textContent = `Clipboard consent: ${waiting.length} read prompt${waiting.length === 1 ? \"\" : \"s\"} waiting for your approval in the review panel.`;\n return;\n }\n delete clipboardstatenode.dataset.state;\n clipboardstatenode.textContent = \"Clipboard consent: none waiting.\";\n}\n\nasync function restore(): Promise<void> {\n const context = await request({ kind: \"context\" }) as { config?: { endpoint: string }; session?: { stoppedat?: number; pausedat?: number; expiresat: number }; capabilities?: capabilityreport; holds?: { heldkeys: keyholdstate[] }; dialogs?: dialogdecision[]; signals?: pagesignallike; navstate?: navstate; offline?: boolean; waitprofile?: waitprofilerecord; navqueues?: navqueues; windows?: windowshape[]; badges?: tabbadge[]; captchas?: captchahandoff[]; datasets?: dataset[]; streams?: streamstate[]; downloads?: downloadrecord[]; clipconsents?: clipboardconsentrecord[]; quarantines?: quarantineentry[] };\n if (endpointinput && context.config) endpointinput.value = context.config.endpoint;\n rendercapabilities(context.capabilities);\n renderlivestate(context.holds?.heldkeys, context.dialogs, context.signals);\n rendernavstate(context.navstate, context.offline, context.waitprofile, context.navqueues);\n renderwindowlayout(context.windows, context.badges);\n rendercaptchastate(context.captchas);\n renderdatasetstate(context.datasets, context.streams);\n renderdownloadstate(context.downloads, context.quarantines);\n renderclipboardstate(context.clipconsents);\n const active = context.session && !context.session.stoppedat && context.session.expiresat > Date.now();\n if (pausebutton) { pausebutton.disabled = !active; pausebutton.textContent = pauselabel(Boolean(context.session?.pausedat)); }\n if (active && context.session?.pausedat) status(\"Session paused. Reviewed actions are blocked until resume.\");\n else status(active ? \"Session active. Review the plan in the side panel.\" : \"No active browser session.\");\n}\n\nconnectbutton?.addEventListener(\"click\", async () => {\n try {\n const config = normalizeendpoint(endpointinput?.value ?? \"\");\n const granted = await chrome.permissions.request({ origins: [hostpattern(config.origin)] });\n if (!granted) throw new Error(\"Origin permission was not granted.\");\n await request({ kind: \"configure\", endpoint: config.endpoint });\n status(`Endpoint approved for ${config.origin}.`);\n } catch (error) { status(error instanceof Error ? error.message : String(error), true); }\n});\nsessionbutton?.addEventListener(\"click\", async () => { try { await request({ kind: \"startsession\" }); status(\"Session started for the active HTTPS tab.\"); await restore(); } catch (error) { status(error instanceof Error ? error.message : String(error), true); } });\npausebutton?.addEventListener(\"click\", async () => { try { const context = await request({ kind: \"context\" }) as { session?: { pausedat?: number } }; await request({ kind: context.session?.pausedat ? \"resumesession\" : \"pausesession\" }); await restore(); } catch (error) { status(error instanceof Error ? error.message : String(error), true); } });\nstopbutton?.addEventListener(\"click\", async () => { try { await request({ kind: \"stop\" }); status(\"Session stopped. No action can continue.\"); await restore(); } catch (error) { status(error instanceof Error ? error.message : String(error), true); } });\nopenbutton?.addEventListener(\"click\", () => chrome.sidePanel.open({ windowId: chrome.windows.WINDOW_ID_CURRENT }));\nrestore().catch(error => status(error instanceof Error ? error.message : String(error), true));\n"],
5
+ "mappings": ";AAEA,IAAM,mBAAmB,oBAAI,IAAgB,CAAC,SAAS,QAAQ,YAAY,UAAU,YAAY,QAAQ,QAAQ,UAAU,SAAS,SAAS,WAAW,UAAU,UAAU,UAAU,QAAQ,WAAW,gBAAgB,gBAAgB,mBAAmB,YAAY,aAAa,eAAe,YAAY,aAAa,gBAAgB,eAAe,gBAAgB,gBAAgB,cAAc,cAAc,iBAAiB,cAAc,YAAY,cAAc,YAAY,YAAY,WAAW,cAAc,gBAAgB,eAAe,eAAe,aAAa,WAAW,YAAY,YAAY,eAAe,eAAe,WAAW,cAAc,UAAU,gBAAgB,eAAe,WAAW,cAAc,cAAc,YAAY,YAAY,cAAc,YAAY,aAAa,YAAY,WAAW,iBAAiB,aAAa,gBAAgB,gBAAgB,UAAU,WAAW,WAAW,iBAAiB,aAAa,cAAc,iBAAiB,cAAc,cAAc,UAAU,WAAW,aAAa,kBAAkB,kBAAkB,iBAAiB,eAAe,iBAAiB,mBAAmB,cAAc,iBAAiB,aAAa,YAAY,YAAY,aAAa,mBAAmB,cAAc,aAAa,aAAa,eAAe,iBAAiB,YAAY,cAAc,YAAY,YAAY,mBAAmB,aAAa,cAAc,eAAe,aAAa,cAAc,cAAc,mBAAmB,iBAAiB,iBAAiB,iBAAiB,kBAAkB,iBAAiB,iBAAiB,kBAAkB,cAAc,sBAAsB,aAAa,kBAAkB,CAAC;AAClp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AAM,QAAQ;AAAA,EAAG,SAAS,OAAO;AAAE,WAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,IAAI;AAAA,EAAG;AAAE,CAAC;AACzV,YAAY,iBAAiB,SAAS,YAAY;AAAE,MAAI;AAAE,UAAM,QAAQ,EAAE,MAAM,OAAO,CAAC;AAAG,WAAO,0CAA0C;AAAG,UAAM,QAAQ;AAAA,EAAG,SAAS,OAAO;AAAE,WAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,IAAI;AAAA,EAAG;AAAE,CAAC;AAC3P,YAAY,iBAAiB,SAAS,MAAM,OAAO,UAAU,KAAK,EAAE,UAAU,OAAO,QAAQ,kBAAkB,CAAC,CAAC;AACjH,QAAQ,EAAE,MAAM,WAAS,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,IAAI,CAAC;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,5 @@
1
1
  <!doctype html>
2
2
  <html lang="en">
3
3
  <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Devthink review</title><link rel="stylesheet" href="style.css"></head>
4
- <body><main class="wide"><header><p class="eyebrow">REVIEW GATE</p><h1>Plan before action</h1><p>Every browser operation remains blocked until the user reviews and approves it here.</p></header><label for="objective">Objective</label><textarea id="objective" rows="4" placeholder="Describe a browser task to turn into a reviewable plan."></textarea><div class="actions"><button id="localplan">Create local observation plan</button><button id="remoteplan" class="secondary">Ask configured endpoint</button><button id="diagnostic" class="secondary">Capture local diagnostics</button></div><p id="status" role="status">Loading session state.</p><p id="capabilitiestext" role="status" class="muted">Optional capabilities unknown.</p><section><h2>Current plan</h2><progress id="planprogress" max="1" value="0"></progress><div id="plan" class="panel"></div></section><section><h2>Clickable map</h2><ol id="map" class="audit maplist"></ol></section><section><h2>Navigation trail</h2><ol id="trail" class="audit"></ol></section><section><h2>Navigation state</h2><div id="navigation" class="panel"></div></section><section><h2>Tabs and windows</h2><div id="tabswindows" class="panel"></div></section><section><h2>Forms and data</h2><div id="forms" class="panel"></div></section><section><h2>Datasets</h2><div id="datasets" class="panel"></div></section><section><h2>Consent banners</h2><div id="banners" class="panel"></div></section><section><h2>Accessibility tree</h2><div id="a11y" class="panel"></div></section><section><h2>Reader view</h2><div id="reader" class="panel"></div></section><section><h2>Detected shapes</h2><ol id="detections" class="audit maplist"></ol></section><section><h2>Watch stream</h2><ol id="stream" class="audit"></ol></section><section><h2>Snapshot diffs</h2><div id="diffs" class="panel"></div></section><section><h2>Derived selectors</h2><ol id="selectors" class="audit maplist"></ol></section><section><h2>Structured diagnostics</h2><ul id="diagnostics" class="audit"></ul></section><section><h2>Local audit</h2><ol id="audit" class="audit"></ol></section></main><script type="module" src="sidepanel.js"></script></body>
4
+ <body><main class="wide"><header><p class="eyebrow">REVIEW GATE</p><h1>Plan before action</h1><p>Every browser operation remains blocked until the user reviews and approves it here.</p></header><label for="objective">Objective</label><textarea id="objective" rows="4" placeholder="Describe a browser task to turn into a reviewable plan."></textarea><div class="actions"><button id="localplan">Create local observation plan</button><button id="remoteplan" class="secondary">Ask configured endpoint</button><button id="diagnostic" class="secondary">Capture local diagnostics</button></div><p id="status" role="status">Loading session state.</p><p id="capabilitiestext" role="status" class="muted">Optional capabilities unknown.</p><section><h2>Current plan</h2><progress id="planprogress" max="1" value="0"></progress><div id="plan" class="panel"></div></section><section><h2>Clickable map</h2><ol id="map" class="audit maplist"></ol></section><section><h2>Navigation trail</h2><ol id="trail" class="audit"></ol></section><section><h2>Navigation state</h2><div id="navigation" class="panel"></div></section><section><h2>Tabs and windows</h2><div id="tabswindows" class="panel"></div></section><section><h2>Forms and data</h2><div id="forms" class="panel"></div></section><section><h2>Files and downloads</h2><div id="files" class="panel"></div></section><section><h2>Datasets</h2><div id="datasets" class="panel"></div></section><section><h2>Consent banners</h2><div id="banners" class="panel"></div></section><section><h2>Accessibility tree</h2><div id="a11y" class="panel"></div></section><section><h2>Reader view</h2><div id="reader" class="panel"></div></section><section><h2>Detected shapes</h2><ol id="detections" class="audit maplist"></ol></section><section><h2>Watch stream</h2><ol id="stream" class="audit"></ol></section><section><h2>Snapshot diffs</h2><div id="diffs" class="panel"></div></section><section><h2>Derived selectors</h2><ol id="selectors" class="audit maplist"></ol></section><section><h2>Structured diagnostics</h2><ul id="diagnostics" class="audit"></ul></section><section><h2>Local audit</h2><ol id="audit" class="audit"></ol></section></main><script type="module" src="sidepanel.js"></script></body>
5
5
  </html>