@matterfact/embed 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/redact.ts","../src/adapters/hoist.ts","../src/adapters/hoist-runtime.ts","../src/adapters/registry.ts","../src/dom/a11y.ts","../src/dom/refs.ts","../src/dom/snapshot.ts","../src/context.ts","../src/protocol.ts","../src/geometry.ts","../src/loader.ts"],"names":["walk","document","isDisabled","getRole","computeAccessibleName","childrenOf","quote","isInaccessible","readSitemap","snapshot","yaml","truncated","snapshotRegion","resolveRef","w"],"mappings":";;;;;;;;;;;;;;;AA0BO,SAAS,OAAO,IAAA,EAAsB;AAC3C,EAAA,IAAI,GAAA,GAAM,IAAA;AACV,EAAA,KAAA,MAAW,MAAM,GAAA,EAAK,GAAA,GAAM,GAAA,CAAI,OAAA,CAAQ,IAAI,YAAY,CAAA;AACxD,EAAA,OAAO,GAAA;AACT;AA9BA,IASM,GAAA;AATN,IAAA,WAAA,GAAA,KAAA,CAAA;AAAA,EAAA,eAAA,GAAA;AASA,IAAM,GAAA,GAAM;AAAA,MACV,iCAAA;AAAA;AAAA,MACA,yBAAA;AAAA;AAAA,MACA,gCAAA;AAAA;AAAA,MACA,aAAA;AAAA;AAAA,MACA,4DAAA;AAAA;AAAA,MACA,oDAAA;AAAA;AAAA,MACA;AAAA;AAAA,KACF;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACwDO,SAAS,YACd,IAAA,EACqB;AACrB,EAAA,IAAI,EAAA;AACJ,EAAA,IAAI;AACF,IAAA,EAAA,GAAK,IAAA,EAAK;AAAA,EACZ,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,IAAI,CAAC,IAAI,OAAO,IAAA;AAChB,EAAA,MAAM,aACJ,CAAC,CAAC,EAAA,CAAG,KAAA,CAAM,QACX,EAAA,CAAG,KAAA,CAAM,MAAA,GAAS,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AA,CAAK,MAAA,CAAO,OAAO,CAAA;AAAA,MAC3D;AACA,MAAA,OAAO,CAAA;AAAA,IACT,CAAC,CAAA,CAAA;AACD,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA,EAYQ,KAAA,GAAQ;AACd,IAAA,MAAM,UAAU,IAAA,CAAK,KAAA;AACrB,IAAA,IAAA,CAAK,QAAQ,EAAC;AACd,IAAA,KAAA,MAAW,CAAA,IAAK,OAAA,EAAS,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA,EAKA,OAAA,GAAU;AACR,IAAA,MAAA,CAAO,mBAAA,CAAoB,SAAA,EAAW,IAAA,CAAK,SAAS,CAAA;AACpD,IAAA,MAAA,CAAO,mBAAA,CAAoB,QAAA,EAAU,IAAA,CAAK,gBAAgB,CAAA;AAC1D,IAAA,IAAA,CAAK,QAAQ,MAAA,EAAO;AACpB,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAMb,IAAA,KAAK,KAAK,OAAA,EAAS,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM,CAAA;AAAA,EACzC;AACF;AAOO,SAAS,MAAM,MAAA,EAAiC;AACrD,EAAA,MAAM,IAAA,GAAO,IAAI,SAAA,CAAU,MAAM,CAAA;AACjC,EAAA,IAAA,CAAK,KAAA,EAAM;AACX,EAAA,OAAO,IAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * Redaction, split out of context.ts so it can be imported by both context.ts\n * (the DOM-walking eye) and the Hoist adapter (adapters/hoist.ts) without the\n * latter creating an import cycle back into context.ts.\n *\n * Re-exported from context.ts (`export { redact } from './redact'`) so every\n * existing importer of `redact` from `./context` keeps working unchanged.\n */\n\nconst PII = [\n /\\b[\\w.+-]+@[\\w-]+\\.[\\w.]{2,}\\b/g, // email\n /\\b(?:\\d[ -]?){13,19}\\b/g, // card-ish\n /\\b\\d{3}[- ]?\\d{2}[- ]?\\d{4}\\b/g, // ssn — dashed, spaced, OR bare 9 digits\n /\\b\\d{9,}\\b/g, // long bare digit runs: account / MRN / routing numbers\n /(?:\\+?\\d{1,2}[\\s.-]?)?\\(?\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}\\b/g, // us phone\n /\\b(?:sk|pk|rk|ak)_(?:live|test)_[A-Za-z0-9]{8,}\\b/g, // stripe-style api keys\n /\\beyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+\\b/g, // jwt\n];\n\n/**\n * Scrub before anything leaves the page — not after it arrives.\n *\n * A compromised widget, or a bug in ours, must not be able to retroactively obtain\n * a customer's users' email addresses. The only way to guarantee that is to never\n * put them on the wire.\n */\nexport function redact(text: string): string {\n let out = text;\n for (const re of PII) out = out.replace(re, '[redacted]');\n return out;\n}\n","/**\n * The Hoist adapter — a pure transform from a `HoistRuntime` (already read out of\n * `window.XH` by hoist-runtime.ts) into the context/snapshot shapes context.ts sends\n * over the bridge.\n *\n * This file never touches `window` or `XH` itself — see hoist-runtime.ts for the only\n * code that does — so every function here is a plain, fully unit-testable transform\n * against a plain object. That split is what keeps this file degrade-safe: it can be\n * exhaustively tested without a real Hoist app, and hoist-runtime.ts's own try/catch\n * (via detectHoist) is the one place a live-model surprise can ever throw.\n */\n\n// From ./redact, not ./context: context.ts (Task 7) imports THIS module, so importing\n// from ./context here would be a cycle. redact.ts holds no other context.ts state, so\n// this is the clean fix rather than a same-cycle-but-runtime-safe workaround. context.ts\n// still re-exports `redact`, so every pre-existing importer is unaffected.\nimport { redact } from '../redact';\nimport type { HostTool, PageContext } from '../protocol';\n\nexport interface HoistRoute {\n name: string;\n path: string;\n params: Record<string, unknown>;\n}\nexport interface HoistColumn {\n field: string;\n header: string;\n}\nexport type HoistRow = Record<string, unknown>;\nexport interface HoistGrid {\n id: string;\n title: string;\n columns: HoistColumn[];\n selected: HoistRow[];\n rows: HoistRow[];\n totalCount: number;\n}\nexport interface HoistChart {\n id: string;\n title: string;\n series: { name: string; data: number[] }[];\n}\n/** A navigable destination in the host app: a human label + a deep-link path. */\nexport interface HoistDestination {\n label: string;\n path: string;\n /**\n * The fully-qualified router route name (e.g. `default.company.ticker.ownership`) —\n * what `hoist.navigate` actually hands `XH.navigate`/`XH.router.navigate`. The LABEL\n * is what the agent sees and picks from (the tool arg is `destination`, a label); the\n * name is resolved from it internally, never exposed as an arg the model fills in.\n */\n name: string;\n /** True for the destination the user is currently on (per nav level). */\n current?: boolean;\n}\n/** One level of site navigation (a Hoist TabContainer): the top app tabs, the\n * per-section sidebar, etc. */\nexport interface HoistNavGroup {\n label: string;\n items: HoistDestination[];\n}\nexport interface HoistRuntime {\n route: HoistRoute;\n grids: HoistGrid[];\n charts: HoistChart[];\n /** The site map — navigable destinations, grouped by nav level. */\n nav: HoistNavGroup[];\n}\n\n/** Read the runtime through `read`, but never let a Hoist-side error reach context.ts.\n * Returns null when there is nothing worth sending, so the caller falls back to the\n * generic DOM walker. */\nexport function detectHoist(\n read: () => HoistRuntime | null,\n): HoistRuntime | null {\n let rt: HoistRuntime | null;\n try {\n rt = read();\n } catch {\n return null;\n }\n if (!rt) return null;\n const worthwhile =\n !!rt.route.name ||\n rt.grids.length > 0 ||\n rt.charts.length > 0 ||\n rt.nav.length > 0;\n return worthwhile ? rt : null;\n}\n\n/* ─────────────────────────── grid rendering ────────────────────────────── */\n\n/** Collapse whitespace, then redact, then truncate, then escape — in that order.\n * The order matches dom/snapshot.ts's `sanitize()`: truncate first and a value\n * containing PII can be cut through the middle of it, the regex no longer\n * matches, and the fragment before the cut ships unredacted. Collapsing\n * whitespace first also means an embedded newline can never survive into the\n * YAML as a fabricated sibling line. */\nfunction quote(s: string, max = 120): string {\n const clean = redact(s.replace(/\\s+/g, ' ').trim());\n const capped = clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;\n return `\"${capped.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/** One field value → a short, redacted, quoted cell string. */\nfunction cell(value: unknown): string {\n const s = value == null ? '' : String(value);\n return `- cell ${quote(s)}`;\n}\n\nfunction pushRow(\n row: HoistRow,\n cols: HoistColumn[],\n out: string[],\n pad: string,\n): void {\n out.push(`${pad}- row:`);\n for (const c of cols) out.push(`${pad} ${cell(row[c.field])}`);\n}\n\nexport function renderGrid(\n grid: HoistGrid,\n rowCap: number,\n out: string[],\n depth: number,\n): void {\n const pad = ' '.repeat(depth);\n out.push(`${pad}- table ${quote(grid.title || 'grid')}:`);\n\n out.push(`${pad} - rowgroup \"columns\":`);\n for (const c of grid.columns)\n out.push(`${pad} - columnheader ${quote(c.header || c.field)}`);\n\n if (grid.selected.length) {\n out.push(`${pad} - rowgroup \"selected\":`);\n for (const r of grid.selected) pushRow(r, grid.columns, out, `${pad} `);\n }\n\n const shown = grid.rows.slice(0, Math.max(0, rowCap));\n out.push(`${pad} - rowgroup \"rows\":`);\n for (const r of shown) pushRow(r, grid.columns, out, `${pad} `);\n\n out.push(\n `${pad} - text: ${quote(`showing ${shown.length} of ${grid.totalCount} rows`)}`,\n );\n}\n\n/* ─────────────────────────── chart rendering ───────────────────────────── */\n\nfunction seriesSummary(name: string, data: number[]): string {\n if (!data.length) return `series ${name}: 0 points`;\n // Looped, not Math.min(...data)/Math.max(...data): spreading a large series into\n // call arguments hits the engine's argument-count ceiling (RangeError) well within\n // the size of a normal intraday/tick series. See adapters/hoist.test.ts's 200k-point\n // case.\n let min = data[0];\n let max = data[0];\n for (const n of data) {\n if (n < min) min = n;\n if (n > max) max = n;\n }\n const last = data[data.length - 1];\n return `series ${name}: ${data.length} points, min ${min}, max ${max}, last ${last}`;\n}\n\nexport function renderChart(\n chart: HoistChart,\n out: string[],\n depth: number,\n): void {\n const pad = ' '.repeat(depth);\n out.push(`${pad}- figure ${quote(chart.title || 'chart')}:`);\n for (const s of chart.series) {\n out.push(`${pad} - text: ${quote(seriesSummary(s.name, s.data))}`);\n }\n}\n\n/* ─────────────────────────── site-map rendering ────────────────────────── */\n\nexport function renderNav(\n groups: HoistNavGroup[],\n out: string[],\n depth: number,\n): void {\n const pad = ' '.repeat(depth);\n for (const g of groups) {\n if (!g.items.length) continue;\n out.push(`${pad}- navigation ${quote(g.label)}:`);\n for (const d of g.items) {\n const mark = d.current ? ' [current]' : '';\n // The path is a deep-link the agent can hand the user. Redact it like any value,\n // but leave it after the arrow rather than as a quoted YAML name.\n out.push(`${pad} - link ${quote(d.label)}${mark} → ${redact(d.path)}`);\n }\n }\n}\n\n/* ─────────────────────────── navigate tool (Layer 3) ───────────────────── */\n\n/** The host's policy for agent-driven actions, keyed by tool family. Read from\n * `window.matterfact.hoist.actions` by hoist-runtime.ts's `readActionsConfig`\n * (the `<MatterfactAgent actions>` React prop is sugar that writes that same\n * global — see react.tsx's `writeActionsGlobal`); `'off'` is the default — the\n * tool is opt-in, never advertised unless a host turns it on. */\nexport interface HoistActionsConfig {\n navigate: 'off' | 'confirm' | 'auto';\n}\n\n/** Every destination across every nav level, flattened — the universe `hoist.navigate`\n * is bounded to (its enum) and what `executeHostTool` looks the agent's chosen label\n * up against. */\nexport function flattenDestinations(rt: HoistRuntime): HoistDestination[] {\n return rt.nav.flatMap((g) => g.items);\n}\n\n/**\n * The `hoist.navigate` tool: lets the agent send the user to a destination in the\n * CURRENT site map. The arg is `destination` — the human LABEL the agent already sees\n * in the sitemap (e.g. \"Ownership\"), never a raw route name; the loader resolves the\n * label to a route name internally (see executeHostTool). The enum is exactly the\n * labels `readSitemap` found on THIS page, so the model cannot name a destination that\n * doesn't exist here — the injection bound this tool relies on.\n */\nexport function buildNavigateTool(\n rt: HoistRuntime,\n policy: 'confirm' | 'auto',\n): HostTool {\n const destinations = flattenDestinations(rt);\n const bySection = rt.nav\n .filter((g) => g.items.length)\n .map((g) => `${g.label} (${g.items.map((d) => d.label).join(', ')})`)\n .join('; ');\n return {\n name: 'hoist.navigate',\n description: redact(\n 'Navigate the user to a destination in the app. \"destination\" must be one of ' +\n `the destinations currently available, grouped by section: ${bySection || '(none available)'}.`,\n ),\n inputSchema: {\n type: 'object',\n properties: {\n destination: {\n type: 'string',\n enum: destinations.map((d) => d.label),\n },\n params: { type: 'object' },\n },\n required: ['destination'],\n },\n readOnly: false,\n // 'confirm' policy ⇒ the widget must show a confirm card every call; 'auto' ⇒ it\n // may call without asking. See the confirm field's doc comment on HostTool.\n confirm: policy === 'auto' ? 'auto' : 'required',\n };\n}\n\n/* ─────────────────────────── top-level transforms ──────────────────────── */\n\nexport function buildHoistContext(rt: HoistRuntime): PageContext {\n const selected = rt.grids.reduce((n, g) => n + g.selected.length, 0);\n const view = rt.route.name || rt.route.path || 'this view';\n const bits = [`Viewing ${view}`];\n if (selected) bits.push(`${selected} selected`);\n if (rt.grids.length) bits.push(`${rt.grids.length} grid(s)`);\n if (rt.charts.length) bits.push(`${rt.charts.length} chart(s)`);\n return {\n route: rt.route.name ? redact(rt.route.name) : undefined,\n description: redact(`${bits.join(', ')}.`),\n };\n}\n\nexport function renderHoistSnapshot(\n rt: HoistRuntime,\n rowCap: number,\n): { yaml: string; truncated: boolean } {\n const out: string[] = [];\n // Nav LEADS. It's the most stable part of the page — it barely changes as the user\n // works within a view — so emitting it first keeps the snapshot's prefix stable\n // across turns (better prompt caching) and orients the agent before the volatile\n // grid/chart data.\n renderNav(rt.nav, out, 0);\n let truncated = false;\n for (const g of rt.grids) {\n if (g.rows.length > rowCap) truncated = true;\n renderGrid(g, rowCap, out, 0);\n }\n for (const c of rt.charts) renderChart(c, out, 0);\n return { yaml: out.join('\\n'), truncated };\n}\n","/**\n * The only module that touches `window.XH`.\n *\n * Everything here is defensive by construction: every field read is optional-chained\n * and falls back to an empty/zero value, so a Hoist version whose shape drifts from\n * what's confirmed below degrades to missing fields rather than a thrown error. The\n * one place a genuine surprise (e.g. `XH` itself being a stub) could still throw is\n * caught one layer up, by `detectHoist()` in ./hoist — this module does not try/catch.\n *\n * The accessors below are CONFIRMED against a live ActivistHub instance (see\n * adapters/HOIST-CONTRACT.md). Two findings shaped this file:\n * 1. Model discovery uses the global `XH.getModels(className)` lookup, NOT the\n * Inspector — `XH.inspectorService.activeInstances` is empty unless the dev\n * Inspector UI is toggled on, so it's useless as an ambient source.\n * 2. Grid columns can be GROUPED: `gridModel.columns` holds ColumnGroups (no field,\n * a `.children` array) whose leaves carry the real `colId`. We read the flat leaf\n * set via `getVisibleLeafColumns()` and prefix each leaf's header with its group\n * (\"5Y\" group + \"Value\" leaf -> \"5Y Value\") so the columns aren't ambiguous.\n */\n\nimport type {\n HoistRuntime,\n HoistGrid,\n HoistChart,\n HoistColumn,\n HoistRow,\n HoistNavGroup,\n HoistDestination,\n HoistActionsConfig,\n} from './hoist';\nimport { buildNavigateTool, flattenDestinations } from './hoist';\nimport type { HostTool, ToolCall } from '../protocol';\nimport { redact } from '../redact';\n\nexport function readHoistConfig(win: unknown): {\n rows: number;\n excludeModels: string[];\n} {\n const cfg = (\n win as {\n matterfact?: { hoist?: { rows?: number; excludeModels?: string[] } };\n }\n )?.matterfact?.hoist;\n const ex = cfg?.excludeModels;\n return {\n rows: typeof cfg?.rows === 'number' && cfg.rows >= 0 ? cfg.rows : 50,\n excludeModels: Array.isArray(ex) ? ex : [],\n };\n}\n\n// ── model discovery ──────────────────────────────────────────────────────────\n// Confirmed: `XH.getModels(className)` returns every mounted model of that class\n// (a native Hoist ModelSelector form). It also returns empty / off-view grids that\n// happen to be mounted — those are dropped by `hasContent` in readHoistRuntime.\nfunction getModelsByClass(XH: any, name: string): any[] {\n const models = typeof XH?.getModels === 'function' ? XH.getModels(name) : [];\n return Array.isArray(models) ? models : [];\n}\n\nfunction className(m: any): string {\n return m?.constructor?.name ?? '';\n}\n\nfunction modelId(m: any): string {\n return String(m?.xhId ?? m?.id ?? m?.modelId ?? '');\n}\n\nfunction headerOf(c: any): string {\n return String(c?.headerName ?? c?.displayName ?? c?.field ?? c?.colId ?? '');\n}\n\n// Walk the full column tree (a ColumnGroup has a `.children` array and no field) to\n// map each leaf colId -> its group-qualified header, so a leaf headed \"Value\" under a\n// \"5Y\" group reads as \"5Y Value\" rather than an ambiguous bare \"Value\".\nfunction collectHeaders(\n cols: any[],\n prefix: string[],\n out: Map<string, string>,\n): void {\n for (const c of Array.isArray(cols) ? cols : []) {\n const children = c?.children;\n if (Array.isArray(children) && children.length) {\n collectHeaders(children, [...prefix, headerOf(c)], out);\n } else {\n const id = String(c?.colId ?? c?.field ?? '');\n if (id) out.set(id, [...prefix, headerOf(c)].filter(Boolean).join(' '));\n }\n }\n}\n\n// Prefer getVisibleLeafColumns() — flat, hidden-aware, real colIds — over the raw\n// `columns` tree (which contains groups without fields). Falls back to `columns` for\n// a Hoist without that method.\nfunction readColumns(g: any): HoistColumn[] {\n const leaves =\n typeof g?.getVisibleLeafColumns === 'function'\n ? g.getVisibleLeafColumns()\n : Array.isArray(g?.columns)\n ? g.columns\n : [];\n const headers = new Map<string, string>();\n collectHeaders(Array.isArray(g?.columns) ? g.columns : [], [], headers);\n return (Array.isArray(leaves) ? leaves : [])\n .map((c: any) => {\n const field = String(c?.colId ?? c?.field ?? '');\n return { field, header: headers.get(field) || headerOf(c) };\n })\n .filter((c: HoistColumn) => c.field);\n}\n\nfunction readRow(rec: any, cols: HoistColumn[]): HoistRow {\n const row: HoistRow = {};\n for (const c of cols)\n row[c.field] =\n typeof rec?.get === 'function' ? rec.get(c.field) : rec?.data?.[c.field];\n return row;\n}\n\nfunction readGrid(g: any): HoistGrid {\n const columns = readColumns(g);\n const records = Array.isArray(g?.store?.records) ? g.store.records : [];\n return {\n id: modelId(g),\n title: String(g?.title ?? ''),\n columns,\n selected: (Array.isArray(g?.selectedRecords) ? g.selectedRecords : []).map(\n (r: any) => readRow(r, columns),\n ),\n rows: records.map((r: any) => readRow(r, columns)),\n totalCount:\n typeof g?.store?.allCount === 'number'\n ? g.store.allCount\n : records.length,\n };\n}\n\n// An off-view / not-yet-loaded grid (no rows AND nothing selected) is one that\n// XH.getModels still returns but that carries no page-context value — drop it.\nfunction hasContent(g: HoistGrid): boolean {\n return g.totalCount > 0 || g.selected.length > 0;\n}\n\nfunction readChart(c: any): HoistChart {\n // Confirmed: series data points can be [timestamp, value] tuples (not bare numbers) —\n // extract the value (`d[1]` / `d.y`) so min/max/last summarise values, not timestamps.\n const series = c?.series ?? c?.highchartsConfig?.series ?? [];\n return {\n id: modelId(c),\n title: String(c?.title ?? c?.highchartsConfig?.title?.text ?? ''),\n series: (Array.isArray(series) ? series : []).map((s: any) => ({\n name: String(s?.name ?? ''),\n data: (Array.isArray(s?.data) ? s.data : [])\n .map((d: any) => (typeof d === 'number' ? d : Number(d?.y ?? d?.[1])))\n .filter((n: number) => Number.isFinite(n)),\n })),\n };\n}\n\n/* ─────────────────────────────── site map ──────────────────────────────── */\n\nfunction humanize(seg: string): string {\n return seg\n .replace(/[_-]+/g, ' ')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n .trim();\n}\n\nfunction childrenOf(node: any): any[] {\n const k = node?.children;\n return k ? (Array.isArray(k) ? k : Array.from(k)) : [];\n}\n\n// Map each route's LAST segment -> { path, fully-qualified name }, by walking the\n// router5 tree and building a deep-link path for each with the current params.\nfunction routeIndex(\n XH: any,\n params: Record<string, unknown>,\n): Map<string, { path: string; name: string }> {\n const router = XH?.router;\n const root = router?.rootNode ?? router?.config?.rootNode;\n const out = new Map<string, { path: string; name: string }>();\n if (!router || typeof router.buildPath !== 'function' || !root) return out;\n const walk = (node: any, prefix: string) => {\n for (const c of childrenOf(node)) {\n const seg = String(c?.name ?? '');\n if (!seg) continue;\n const name = prefix ? `${prefix}.${seg}` : seg;\n let path = '';\n try {\n path = router.buildPath(name, params);\n } catch {\n path = '';\n }\n if (path && !out.has(seg)) out.set(seg, { path, name });\n walk(c, name);\n }\n };\n walk(root, '');\n return out;\n}\n\n// The site map: each Hoist TabContainerModel is one nav level (top app tabs, the\n// per-section sidebar, …). Its tabs give the exact human labels + the active tab;\n// the router gives each tab id its deep-link path. Route names ≠ display labels\n// (e.g. `governanceScorecard` shows as \"Governance Risk\"), so the tab TITLE wins.\nfunction readSitemap(\n XH: any,\n excluded: (m: any) => boolean,\n origin: string,\n): HoistNavGroup[] {\n const params = (XH?.routerState?.params ?? {}) as Record<string, unknown>;\n const currentName = String(XH?.routerState?.name ?? '');\n const routes = routeIndex(XH, params);\n if (!routes.size) return [];\n\n const groups: HoistNavGroup[] = [];\n for (const tc of getModelsByClass(XH, 'TabContainerModel')) {\n if (excluded(tc)) continue;\n const tabs = Array.isArray(tc?.tabs) ? tc.tabs : [];\n const activeTabId = String(tc?.activeTabId ?? '');\n const items: HoistDestination[] = [];\n let companyScoped = false;\n for (const t of tabs) {\n const id = String(t?.id ?? '');\n const r = routes.get(id);\n if (!id || !r) continue;\n if (r.name.includes('.company.ticker.')) companyScoped = true;\n items.push({\n // Redact HERE, at the source — not in a downstream renderer. This is the\n // one place a Hoist tab TITLE (host-page text, so potentially PII-shaped)\n // becomes a `HoistDestination.label`, and that label is what EVERY\n // consumer uses verbatim: renderNav's YAML, buildNavigateTool's\n // description AND its inputSchema.enum, and executeHostTool's\n // `.find(d => d.label === destination)` lookup. Redacting once here keeps\n // all of them consistent by construction — an enum built from an\n // ALREADY-redacted label can never leak PII a sibling renderer scrubbed\n // (see Important #1), and a destination arg matching the redacted string\n // (the only thing the agent ever saw) still resolves.\n label: redact(String(t?.title ?? '') || humanize(id)),\n // ABSOLUTE, against the HOST page's origin — not the router's bare path.\n // This path's only job is to be a link the agent can hand the user, and\n // the agent's answer renders inside our widget iframe, which is on OUR\n // origin: a bare \"/research\" there resolves to app.matterfact.com/research\n // (a dead link to the wrong app), which is exactly what shipped before.\n // The adapter runs in the host page, so its own origin is the right one.\n path: origin && r.path.startsWith('/') ? origin + r.path : r.path,\n // The fully-qualified route name — what hoist.navigate hands XH.navigate.\n // Always present: `r` only exists here because routes.get(id) resolved.\n name: r.name,\n current: id === activeTabId || r.name === currentName,\n });\n }\n if (!items.length) continue;\n const ticker = String(params.ticker ?? '');\n const label = companyScoped\n ? ticker\n ? `Company · ${ticker}`\n : 'Company'\n : 'Site';\n groups.push({ label, items });\n }\n return groups;\n}\n\nexport function readHoistRuntime(\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): HoistRuntime | null {\n const XH = (win as { XH?: any })?.XH;\n if (!XH) return null;\n const { excludeModels } = readHoistConfig(win);\n const excluded = (m: any) =>\n excludeModels.includes(className(m)) || excludeModels.includes(modelId(m));\n\n const rs = XH.routerState ?? {};\n return {\n route: {\n name: String(rs.name ?? ''),\n path: String(rs.path ?? ''),\n params: rs.params ?? {},\n },\n grids: getModelsByClass(XH, 'GridModel')\n .filter((m) => !excluded(m))\n .map(readGrid)\n .filter(hasContent),\n charts: getModelsByClass(XH, 'ChartModel')\n .filter((m) => !excluded(m))\n .map(readChart)\n .filter((c) => c.series.length > 0),\n nav: readSitemap(\n XH,\n excluded,\n String(\n (win as { location?: { origin?: string } })?.location?.origin ?? '',\n ),\n ),\n };\n}\n\n/* ─────────────────────────── actions / tools (Layer 3) ─────────────────── */\n\n/** Read the host's action policy from `window.matterfact.hoist.actions`. Defaults to\n * `{navigate:'off'}` — agent-driven navigation is opt-in, and any value other than\n * the two known policies degrades to `'off'` rather than advertising a tool under an\n * unrecognized policy. */\nexport function readActionsConfig(win: unknown): HoistActionsConfig {\n const navigate = (\n win as {\n matterfact?: { hoist?: { actions?: { navigate?: unknown } } };\n }\n )?.matterfact?.hoist?.actions?.navigate;\n return {\n navigate: navigate === 'confirm' || navigate === 'auto' ? navigate : 'off',\n };\n}\n\n/**\n * The tools this page currently offers the agent — today, just `hoist.navigate` when\n * a Hoist app is detected and the host has turned navigation on via\n * `window.matterfact.hoist.actions` (`readActionsConfig` above) — the SAME read\n * `executeHostTool` re-checks at call time, so advertise and execute can never\n * disagree about the current policy.\n *\n * Degrade-safe by construction: no `window.XH`, `navigate:'off'` (the default), no\n * detectable runtime, or a `getModels`/router surprise ⇒ `[]`, never a throw — so a\n * caller can call this unconditionally without its own try/catch.\n */\nexport function advertiseTools(\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): HostTool[] {\n try {\n const XH = (win as { XH?: unknown })?.XH;\n if (!XH) return [];\n const { navigate } = readActionsConfig(win);\n if (navigate === 'off') return [];\n const rt = readHoistRuntime(win);\n if (!rt) return [];\n return [buildNavigateTool(rt, navigate)];\n } catch {\n return [];\n }\n}\n\n/**\n * Run a host tool call. Two enforcement points, both re-checked fresh on every call —\n * never against anything the widget claims was advertised earlier, which a\n * compromised or merely-stale widget could lie about:\n *\n * 1. the host's CURRENT action policy (`readActionsConfig`) — a widget that cached\n * an advertisement from before the host flipped `actions.navigate` to `'off'`\n * (e.g. entering a regulated flow) must be refused, not just un-advertised;\n * 2. the destination, against the LIVE current sitemap.\n *\n * That is the \"loader route-bound\" guarantee the confirm card (Wave 2) sits on top\n * of, not a substitute for it.\n *\n * Degrade-safe and NEVER throws: any surprise (bad args, XH/router missing or\n * throwing) becomes `{ok:false, error}`, never an exception into context.ts. The\n * error text itself is redacted too — a thrown Error can plausibly embed host-page\n * detail, same as the success path's `result`.\n */\nexport function executeHostTool(\n call: ToolCall,\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): { ok: boolean; result?: unknown; error?: string } {\n try {\n if (call.name !== 'hoist.navigate') {\n return { ok: false, error: 'unknown tool' };\n }\n // Execute-time policy re-check (defense-in-depth): `advertiseTools` already\n // gates on this at advertise time, but that is not an access-control decision\n // this function may assume still holds — the widget calling in is exactly the\n // thing this whole module treats as untrustworthy. See the doc comment above.\n if (readActionsConfig(win).navigate === 'off') {\n return { ok: false, error: 'navigation is disabled' };\n }\n\n const destination = String(call.args?.destination ?? '');\n const rt = readHoistRuntime(win);\n const item = rt\n ? flattenDestinations(rt).find((d) => d.label === destination)\n : undefined;\n if (!item) return { ok: false, error: 'unknown destination' };\n\n const XH = (win as { XH?: any })?.XH;\n // Merge: the CURRENT route's params first, then whatever the agent explicitly\n // supplied on top. A company subroute (e.g. Ownership) needs the current\n // `ticker` param to resolve correctly even though the agent never saw or passed\n // it; an agent-supplied key still wins on conflict (spread order).\n const params = {\n ...(XH?.routerState?.params ?? {}),\n ...((call.args?.params as Record<string, unknown> | undefined) ?? {}),\n };\n if (typeof XH?.navigate === 'function') {\n XH.navigate(item.name, params);\n } else if (typeof XH?.router?.navigate === 'function') {\n XH.router.navigate(item.name, params);\n } else {\n return { ok: false, error: 'navigation unavailable' };\n }\n return { ok: true, result: redact(`navigated to ${destination}`) };\n } catch (e) {\n return {\n ok: false,\n error: redact(e instanceof Error ? e.message : 'navigate failed'),\n };\n }\n}\n","/**\n * The host-tool registry — the ONE place the three tool classes are merged into the\n * single list the widget advertises, and the ONE execution path for calling any of\n * them.\n *\n * Three classes, distinguished by who owns the contract and who runs the code:\n *\n * - `hoist.*` matterfact-defined, matterfact-implemented. The loader adapter runs\n * them (today: `hoist.navigate`). Gated on `window.XH` + the host's\n * `hoist.actions` policy. See `hoist-runtime.ts`.\n * - `mf.*` matterfact-defined, HOST-implemented. WE fix the name, schema and\n * agent semantics (the description is authored HERE, not per\n * integration); the host supplies the function via `resolve.*`. Today:\n * `mf.resolveDocument`, `mf.resolveArtifact`.\n * - `app.*` host-defined, host-implemented. Anything the host advertises via\n * `tools`. Normalised into the `app.` namespace so it can never shadow\n * ours.\n *\n * Everything downstream (the widget's confirm gate, the backend dispatcher) is already\n * generic over \"a tool with a name/schema/confirm and a call round-trip\" — this module\n * is purely the loader-side composition + dispatch, so `hoist-runtime.ts` stays one\n * adapter rather than the whole surface.\n *\n * SECURITY: `mf.*`/`app.*` handlers are HOST code. Their results and error strings pass\n * through `redact()` before leaving the page, exactly like the hoist adapter's; a\n * handler that throws or hangs becomes a normal `{ok:false}` result, never an exception\n * into `context.ts`. And the SERVER decides which of these an app may actually expose\n * (the `host_tools` policy) — advertising here is necessary but not sufficient.\n */\nimport type { HostTool, MatterfactEvent, ToolCall, ToolEvent } from '../protocol';\nimport { redact } from '../redact';\nimport { advertiseTools, executeHostTool } from './hoist-runtime';\n\n/** Advertised metadata rides EVERY turn's model context and is host-supplied. Bound\n * the count; the backend caps it too (defense in depth). */\nexport const MAX_TOOLS = 16;\n\n/** A host `mf.*`/`app.*` handler is host code — bound it so a hung promise surfaces as\n * a normal declined result INSIDE the backend's own ~60s wait, never eating it. */\nexport const HOST_HANDLER_TIMEOUT_MS = 30_000;\n\nexport type ToolClass = 'hoist' | 'mf' | 'app';\n\n/** A host-supplied resolver: matterfact fixes the contract, the host implements it. */\nexport interface HostResolvers {\n document?: (args: {\n doctype: string;\n key: string;\n }) => Promise<{ id: string; label: string; href?: string }>;\n artifact?: (args: {\n slug: string;\n }) => Promise<{ id: string; owner: string; token: string; label: string }>;\n}\n\n/** A host-defined tool (the `tools` prop): a WebMCP-shaped descriptor plus its handler. */\nexport interface HostToolDef {\n name: string;\n description: string;\n inputSchema?: Record<string, unknown>;\n confirm?: 'auto' | 'required';\n handler: (args: Record<string, unknown>) => unknown | Promise<unknown>;\n}\n\ninterface MatterfactGlobal {\n resolve?: HostResolvers;\n tools?: HostToolDef[];\n onToolEvent?: (e: ToolEvent) => void;\n onEvent?: (e: MatterfactEvent) => void;\n}\n\nfunction mfGlobal(win: unknown): MatterfactGlobal {\n return (\n (win as { matterfact?: MatterfactGlobal } | undefined)?.matterfact ?? {}\n );\n}\n\nexport function toolClass(name: string): ToolClass {\n if (name.startsWith('hoist.')) return 'hoist';\n if (name.startsWith('mf.')) return 'mf';\n return 'app';\n}\n\n/** Fire the host's unified `onEvent` telemetry hook, swallowing any throw. A host\n * telemetry callback is host code: a throw here must not fail a call, advertise, or\n * anything else on the path. */\nexport function emitEvent(win: unknown, e: MatterfactEvent): void {\n const cb = mfGlobal(win).onEvent;\n if (typeof cb !== 'function') return;\n try {\n cb(e);\n } catch {\n /* a host telemetry callback must never break the call path */\n }\n}\n\n/** Fire tool telemetry on BOTH the unified `onEvent` (tagged `type:'tool'`) and the\n * legacy `onToolEvent` shim (untagged). Each is independently throw-guarded, so a\n * throwing hook on one never starves the other or the call path. */\nexport function emitToolEvent(win: unknown, e: ToolEvent): void {\n emitEvent(win, { type: 'tool', ...e });\n const cb = mfGlobal(win).onToolEvent;\n if (typeof cb !== 'function') return;\n try {\n cb(e);\n } catch {\n /* legacy shim: a host telemetry callback must never break the call path */\n }\n}\n\n/* ───────────────────────────── mf.* contracts ──────────────────────────── */\n\n/**\n * The `mf.*` tool descriptors. Authored HERE so the agent's understanding of them is\n * ours and lives in one place — an integration spends no instruction budget teaching\n * what they mean. Only advertised for the resolvers the host actually supplied.\n */\nfunction mfTools(win: unknown): HostTool[] {\n const { document, artifact } = mfGlobal(win).resolve ?? {};\n const out: HostTool[] = [];\n if (typeof document === 'function') {\n out.push({\n name: 'mf.resolveDocument',\n description:\n 'Resolve a matterfact document (dossier, report, briefing) that is NOT on the ' +\n 'current page to a concrete id. Call it with the document type and a key (e.g. a ' +\n 'ticker) when the site map shows the document lives on another route. Returns ' +\n '{id, label, href}. Cite the result inline as ' +\n '<MFRef kind=\"document\" id=\"<id>\" label=\"<label>\" /> — it renders as a chip that ' +\n 'opens the document in the side panel; href is its \"open on page\" deeplink.',\n inputSchema: {\n type: 'object',\n properties: {\n doctype: { type: 'string' },\n key: { type: 'string' },\n },\n required: ['doctype', 'key'],\n },\n readOnly: true,\n confirm: 'auto',\n });\n }\n if (typeof artifact === 'function') {\n out.push({\n name: 'mf.resolveArtifact',\n description:\n 'Resolve a matterfact artifact (an interactive board) that is NOT co-embedded on ' +\n 'the current page to a read grant. Call it with the artifact slug. Returns ' +\n '{id, owner, token, label}; the grant is applied for you. Cite the result inline ' +\n 'as <MFRef kind=\"artifact\" id=\"<id>\" label=\"<label>\" /> — it renders as a chip ' +\n 'that opens the artifact in the side panel.',\n inputSchema: {\n type: 'object',\n properties: { slug: { type: 'string' } },\n required: ['slug'],\n },\n readOnly: true,\n confirm: 'auto',\n });\n }\n return out;\n}\n\n/* ───────────────────────────── app.* host tools ────────────────────────── */\n\nconst APP_NAME_RE = /^[A-Za-z0-9._-]+$/;\n\n/** Normalise a host tool name into the `app.` namespace so it can never collide with\n * `hoist.*`/`mf.*`. A name already prefixed `app.` is kept; anything else is prefixed.\n * Names outside the safe charset are dropped by the caller. */\nfunction appName(name: string): string {\n return name.startsWith('app.') ? name : `app.${name}`;\n}\n\nfunction appTools(win: unknown): HostTool[] {\n const defs = mfGlobal(win).tools;\n if (!Array.isArray(defs)) return [];\n const out: HostTool[] = [];\n for (const d of defs) {\n const raw = (d?.name ?? '').trim();\n if (!raw || typeof d.handler !== 'function') continue;\n const name = appName(raw);\n if (!APP_NAME_RE.test(name)) continue;\n out.push({\n name,\n description: String(d.description ?? `Run the host tool ${name}.`),\n inputSchema: d.inputSchema ?? { type: 'object', properties: {} },\n readOnly: false,\n confirm: d.confirm === 'auto' ? 'auto' : 'required',\n });\n }\n return out;\n}\n\n/* ───────────────────────────── advertise ───────────────────────────────── */\n\n/**\n * The merged tool list this page offers the agent: hoist adapter tools, then the\n * `mf.*` contracts for supplied resolvers, then host `app.*` tools. matterfact-defined\n * names win on collision (an `app.*` normalisation can't produce one, but a host that\n * literally named a tool `mf.foo` in `app.` space still can't shadow a real `mf.*`).\n * Deduped by name, first-wins, capped at MAX_TOOLS.\n *\n * Degrade-safe: any surprise ⇒ the entries built so far, never a throw — a caller can\n * call this unconditionally.\n */\nexport function advertise(\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): HostTool[] {\n const merged: HostTool[] = [];\n const seen = new Set<string>();\n const push = (tools: HostTool[]) => {\n for (const t of tools) {\n if (seen.has(t.name)) continue;\n seen.add(t.name);\n merged.push(t);\n }\n };\n try {\n push(advertiseTools(win));\n } catch {\n /* hoist adapter already degrade-safe; belt and suspenders */\n }\n try {\n push(mfTools(win));\n push(appTools(win));\n } catch {\n /* fall through with whatever merged so far */\n }\n return merged.slice(0, MAX_TOOLS);\n}\n\n/* ───────────────────────────── execute ─────────────────────────────────── */\n\nfunction timeout(ms: number): Promise<never> {\n return new Promise((_, reject) =>\n setTimeout(() => reject(new Error('host tool timed out')), ms),\n );\n}\n\n/** Redact anything a host handler returns before it can leave the page. Strings are\n * scrubbed directly; structured results are JSON round-tripped through the scrubber so\n * an email tucked in a field can't ride out. */\nfunction redactResult(value: unknown): unknown {\n if (value === undefined || value === null) return value;\n if (typeof value === 'string') return redact(value);\n try {\n return JSON.parse(redact(JSON.stringify(value)));\n } catch {\n return redact(String(value));\n }\n}\n\n/**\n * Run one host tool call. Dispatches by class:\n * - `hoist.*` → the existing adapter (keeps its OWN execute-time policy + route\n * re-checks — this module does not second-guess it);\n * - `mf.*` → the matching `resolve.*` function;\n * - `app.*` → the matching host `tools[].handler`.\n *\n * Handlers are read FRESH off the global on every call (so a host swapping a handler\n * body never needs a remount) and bounded at HOST_HANDLER_TIMEOUT_MS. NEVER throws:\n * any surprise becomes `{ok:false, error}`, redacted.\n */\nexport async function execute(\n call: ToolCall,\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): Promise<{ ok: boolean; result?: unknown; error?: string }> {\n const cls = toolClass(call.name);\n try {\n if (cls === 'hoist') {\n // Synchronous adapter; keep its result/redaction exactly as-is.\n return executeHostTool(call, win);\n }\n\n const handler = resolveHandler(win, call.name);\n if (!handler) return { ok: false, error: 'unknown tool' };\n\n const result = await Promise.race([\n Promise.resolve(handler(call.args ?? {})),\n timeout(HOST_HANDLER_TIMEOUT_MS),\n ]);\n return { ok: true, result: redactResult(result) };\n } catch (e) {\n return {\n ok: false,\n error: redact(e instanceof Error ? e.message : 'host tool failed'),\n };\n }\n}\n\n/** The host function backing an `mf.*`/`app.*` name, or undefined. */\nfunction resolveHandler(\n win: unknown,\n name: string,\n): ((args: Record<string, unknown>) => unknown) | undefined {\n const mf = mfGlobal(win);\n if (name === 'mf.resolveDocument') return mf.resolve?.document as never;\n if (name === 'mf.resolveArtifact') return mf.resolve?.artifact as never;\n if (name.startsWith('app.')) {\n const def = (mf.tools ?? []).find((d) => appName((d?.name ?? '').trim()) === name);\n return def?.handler;\n }\n return undefined;\n}\n","import {\n computeAccessibleName,\n getRole,\n isDisabled,\n} from 'dom-accessibility-api';\n\n/**\n * Role, name, visibility, interactability, state.\n *\n * WHAT WE ADOPTED: role and accessible name come from `dom-accessibility-api`\n * (MIT, zero deps) — the engine behind testing-library's `getByRole`. Accessible\n * name is a genuinely hard spec (accname walks aria-labelledby graphs, ::before\n * content, <label> associations, alt/title fallbacks, and recursive\n * name-from-content) and a hand-rolled version is wrong in ways you only discover\n * on a customer's page.\n *\n * WHAT WE BUILT: everything below that. Visibility and pointer-events are ~20 lines\n * from first principles (see `isVisible`/`receivesPointerEvents`) and the state\n * reads are direct DOM/ARIA reads, so we vendored nothing and took on no\n * Apache-2.0 attribution obligation.\n */\n\n/** A memoised `getComputedStyle`, shaped to be passed straight to accname. */\nexport type StyleOf = typeof window.getComputedStyle;\n\n/**\n * One computed style per element per snapshot.\n *\n * Not a micro-optimisation: `computeAccessibleName` calls back into\n * getComputedStyle for every descendant it walks while building a name from\n * content, so on a page of nested divs the uncached cost is quadratic-ish. The\n * cache is per-snapshot (a fresh WeakMap each walk), so it can never go stale\n * across snapshots.\n */\nexport function createStyleCache(): StyleOf {\n const cache = new WeakMap<Element, CSSStyleDeclaration>();\n return ((el: Element, pseudo?: string | null): CSSStyleDeclaration => {\n // Pseudo-element lookups are rare and must not poison the element cache.\n if (pseudo) return window.getComputedStyle(el, pseudo);\n let style = cache.get(el);\n if (!style) {\n style = window.getComputedStyle(el);\n cache.set(el, style);\n }\n return style;\n }) as StyleOf;\n}\n\n/**\n * Does this environment do layout at all?\n *\n * In a browser the root element always has a box. In jsdom — which has no layout\n * engine — *everything* reports zero client rects, so a box-based visibility check\n * would hide the entire page and our tests would assert on an empty snapshot. So we\n * feature-detect layout once per walk and fall back to style-only visibility when\n * there is none. This is a test-environment concession, stated out loud rather than\n * hidden behind a mock.\n */\nexport function hasLayout(): boolean {\n return document.documentElement.getClientRects().length > 0;\n}\n\n/**\n * Visible enough to be worth telling the agent about.\n *\n * `display` and `visibility` are read from the computed style, which already\n * accounts for inheritance — and because the walk is top-down and prunes whole\n * subtrees, we never pay for an ancestor walk. `display: contents` is the one\n * subtlety: such an element generates no box of its own but its children do, so it\n * must not be treated as invisible or we would drop a real subtree.\n */\nexport function isVisible(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n const display = style.display;\n if (display === 'none') return false;\n\n const visibility = style.visibility;\n if (visibility === 'hidden' || visibility === 'collapse') return false;\n\n // `opacity: 0` is a standard \"hide from sight, keep for a11y\" technique. It still\n // reports a box, so the area check below misses it. We treat fully-transparent as\n // hidden; a partially-transparent element is genuinely on screen.\n if (Number(style.opacity) === 0) return false;\n\n // A `display: contents` element generates no box of its own but its children do,\n // so it must not be judged by its own (nonexistent) geometry — we let it through\n // and test each child on its own merits.\n if (layout && display !== 'contents') {\n // Area, not merely \"has a box\": `width:0;height:0;overflow:hidden` is one of the\n // commonest ways to hide a thing, and such an element still reports a client\n // rect. This is the check Playwright's own isVisible() makes.\n const box = el.getBoundingClientRect();\n if (box.width <= 0 || box.height <= 0) return false;\n\n // The sr-only / visually-hidden family: `clip: rect(0 0 0 0)` and its modern\n // `clip-path: inset(50%)` shrink the element to nothing while keeping a 1px box,\n // and `position:absolute; left:-9999px` parks it far off any real page. All three\n // are \"screen-reader only\" idioms — present for a11y, not for sight — so an agent\n // reading the page should skip them too. (getClientRects().length === 0 catches\n // the clipped ones; the far-offscreen check catches the parked ones.)\n if (el.getClientRects().length === 0) return false;\n if (box.right < -2000 || box.bottom < -2000) return false;\n }\n\n return true;\n}\n\n/**\n * Can a pointer actually reach it?\n *\n * `pointer-events` is an INHERITED property, so the computed value on the element\n * already encodes every ancestor's `pointer-events: none` — and correctly honours a\n * descendant that opts back in with `pointer-events: auto`. That is the whole check:\n * no ancestor walk, no hit-test. We deliberately do NOT test for occlusion (is\n * something painted on top of it) the way Playwright's actionability check does —\n * we are describing the page, not clicking it, and an element under a sticky header\n * is still worth telling the agent about.\n */\nexport function receivesPointerEvents(style: CSSStyleDeclaration): boolean {\n return style.pointerEvents !== 'none';\n}\n\n/** Roles that are inherently operable. */\nconst INTERACTIVE_ROLES = new Set([\n 'button',\n 'checkbox',\n 'combobox',\n 'link',\n 'listbox',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'searchbox',\n 'slider',\n 'spinbutton',\n 'switch',\n 'tab',\n 'textbox',\n 'treeitem',\n]);\n\n/** Tags that are operable regardless of what role they compute to. */\nconst INTERACTIVE_TAGS = new Set([\n 'BUTTON',\n 'INPUT',\n 'SELECT',\n 'TEXTAREA',\n 'SUMMARY',\n]);\n\n/** `contenteditable` — present and not explicitly \"false\" (covers \"\", \"true\", \"plaintext-only\"). */\nexport function isEditable(el: Element): boolean {\n const v = el.getAttribute('contenteditable');\n return v !== null && v !== 'false';\n}\n\n/**\n * Is this element something the user can operate?\n *\n * THIS IS THE INTERESTING FUNCTION, so here is the reasoning in full.\n *\n * The obvious way to answer it — ask the DOM what event listeners are attached —\n * IS NOT AVAILABLE. `getEventListeners()` exists only inside DevTools (and via CDP).\n * We are ordinary page JS on a customer's website, so every `addEventListener` a\n * React, Vue or Svelte app ever registered is, to us, completely invisible. This is\n * precisely where the browser-use style of in-page DOM extraction degrades on real\n * apps: it cannot see a single handler, so it either misses the app's controls or\n * guesses wildly. We therefore never ask \"does it have a handler\"; we ask \"does it\n * PRESENT ITSELF as operable\", in four descending tiers of confidence:\n *\n * 1. TAG SEMANTICS (certain). button, input, select, textarea, summary, a[href].\n * 2. COMPUTED ROLE (certain). role=button|link|checkbox|… whether implicit or\n * author-supplied. A div with role=\"button\" is a\n * button as far as the platform, a screen reader,\n * and the user are concerned.\n * 3. FOCUSABILITY (strong). tabindex >= 0, or contenteditable. An app that\n * made a div keyboard-reachable did so on purpose.\n * 4. `cursor: pointer` (WEAK). Last resort, and the reason for the guard below.\n *\n * Tier 4 needs care, because `cursor` is INHERITED: a card with `cursor: pointer`\n * makes every span, every icon and every text node inside it report `pointer` too,\n * and a naive check would mint a ref for each of them and drown the snapshot. So we\n * only count the element that *introduced* the pointer cursor — the one whose parent\n * did not already have it. That is almost exactly the clickable card itself.\n */\nexport function isInteractive(\n el: Element,\n role: string | null,\n style: CSSStyleDeclaration,\n parentStyle: CSSStyleDeclaration | null,\n): boolean {\n const tag = el.tagName;\n\n // 1. tag semantics\n // An <a href> is interactive, but a hrefless <a> is NOT a dead end — it may be a\n // JS-nav link, an <a role=\"button\">, or a Bootstrap `.btn` anchor. So href is a\n // positive signal, not a gate: fall through to the role/tabindex/cursor tiers\n // rather than returning false and dropping every SPA link.\n if (tag === 'A' && el.hasAttribute('href')) return true;\n if (INTERACTIVE_TAGS.has(tag)) return true;\n\n // 2. computed role\n if (role !== null && INTERACTIVE_ROLES.has(role)) return true;\n\n // 3. focusability\n const tabindex = el.getAttribute('tabindex');\n if (tabindex !== null && Number(tabindex) >= 0) return true;\n if (isEditable(el)) return true;\n\n // 4. cursor: pointer, but only where it originates (see above)\n if (style.cursor === 'pointer' && parentStyle?.cursor !== 'pointer')\n return true;\n\n return false;\n}\n\n/**\n * Roles whose accessible name IS their text content (ARIA \"Name From: contents\").\n *\n * This is the exact list from the ARIA spec, and it earns its place: it is what tells\n * the walk that the \"Export CSV\" inside `<button>Export CSV</button>` has ALREADY been\n * emitted, as the button's name, and must not be repeated as a child text node.\n *\n * The tempting shortcut — \"skip any text that appears inside the parent's name\" — is\n * wrong, and wrong in a way that silently deletes content: a card labelled\n * `aria-label=\"Acme Corp order\"` containing the text \"Acme Corp\" would lose it,\n * because one is a substring of the other by coincidence. Ask the role, not the string.\n */\nexport const NAME_FROM_CONTENT = new Set([\n 'button',\n 'cell',\n 'checkbox',\n 'columnheader',\n 'gridcell',\n 'heading',\n 'link',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'row',\n 'rowheader',\n 'switch',\n 'tab',\n 'tooltip',\n 'treeitem',\n]);\n\n/* ─────────────────────────────── state ────────────────────────────────── */\n\n/** Roles whose content IS the user's data. We report that a value exists, never what it is. */\nconst VALUE_ROLES = new Set(['textbox', 'searchbox', 'spinbutton']);\n\n/**\n * Roles we refuse to descend into, because their children/content ARE the value.\n *\n * A `<textarea>`'s child text node is literally what the user typed; a\n * contenteditable's subtree is the document they are writing. Refusing to walk in is\n * how \"never emit a value\" is enforced STRUCTURALLY, rather than by remembering to\n * filter at every emit site.\n *\n * `<select>` is deliberately NOT here. Its options are a bounded, author-defined\n * enumeration — the affordance the agent most needs (\"what can I set this to\"), not\n * the free-text user data the opaque rule exists to contain. The snapshot emits them\n * directly instead (capped, selected one marked): see emitSelectOptions in\n * snapshot.ts.\n */\nconst OPAQUE_TAGS = new Set(['INPUT', 'TEXTAREA']);\n\nexport function isOpaque(el: Element): boolean {\n return OPAQUE_TAGS.has(el.tagName) || isEditable(el);\n}\n\n/**\n * Has the user put something in this field?\n *\n * `.value` is read and immediately thrown away — only its LENGTH escapes. This is\n * the single most useful bit about a form (\"is the email box already filled in?\")\n * and the single most dangerous string on the page, so it is reduced to one bit at\n * the point of reading and never travels.\n */\nfunction isFilled(el: Element, role: string): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA') {\n if (!VALUE_ROLES.has(role)) return false; // checkbox.value is \"on\" — meaningless\n return ((el as HTMLInputElement).value ?? '').length > 0;\n }\n if (isEditable(el)) return (el.textContent ?? '').trim().length > 0;\n return false;\n}\n\nfunction ariaFlag(el: Element, attr: string): 'true' | 'mixed' | null {\n const v = el.getAttribute(attr);\n if (v === 'true') return 'true';\n if (v === 'mixed') return 'mixed';\n return null;\n}\n\n/**\n * The bracketed attributes, in Playwright's order:\n * [checked] [disabled] [expanded] [level=N] [pressed] [selected]\n * plus our one addition, [filled] — see isFilled. `[ref=eN]` is appended by the\n * caller and always comes last.\n */\nexport function states(el: Element, role: string): string {\n const out: string[] = [];\n const tag = el.tagName;\n\n // checked\n if (tag === 'INPUT' && (role === 'checkbox' || role === 'radio')) {\n if ((el as HTMLInputElement).checked) out.push('[checked]');\n } else {\n const checked = ariaFlag(el, 'aria-checked');\n if (checked === 'mixed') out.push('[checked=mixed]');\n else if (checked === 'true') out.push('[checked]');\n }\n\n // disabled — dom-accessibility-api handles fieldset/optgroup inheritance and aria-disabled\n if (isDisabled(el)) out.push('[disabled]');\n\n // expanded — <summary> reflects its parent <details>, which has no ARIA attribute\n const expanded = el.getAttribute('aria-expanded');\n if (expanded === 'true' || expanded === 'false') {\n if (expanded === 'true') out.push('[expanded]');\n } else if (tag === 'SUMMARY') {\n const details = el.parentElement;\n if (\n details?.tagName === 'DETAILS' &&\n (details as HTMLDetailsElement).open\n ) {\n out.push('[expanded]');\n }\n }\n\n // level\n if (role === 'heading') {\n const aria = el.getAttribute('aria-level');\n const level = aria ? Number(aria) : Number(tag[1]);\n if (Number.isFinite(level) && level > 0) out.push(`[level=${level}]`);\n }\n\n // pressed\n const pressed = ariaFlag(el, 'aria-pressed');\n if (pressed === 'mixed') out.push('[pressed=mixed]');\n else if (pressed === 'true') out.push('[pressed]');\n\n // selected\n if (el.getAttribute('aria-selected') === 'true') out.push('[selected]');\n\n // filled (ours — a boolean, never the value)\n if (isFilled(el, role)) out.push('[filled]');\n\n return out.join(' ');\n}\n\n/* ─────────────────────────── role & name ──────────────────────────────── */\n\n/**\n * The computed role, with one correction.\n *\n * `getRole` follows HTML-AAM and returns null for a contenteditable div — but every\n * real browser exposes it to assistive tech as a textbox, and that is what it is to\n * the user and to the agent. We say textbox.\n */\nexport function roleOf(el: Element): string | null {\n if (isEditable(el)) return 'textbox';\n return getRole(el);\n}\n\n/**\n * Selector for anything whose CONTENT is the user's data — a form control, a\n * contenteditable, a valued widget, or a host-marked private region.\n */\nconst UNTRUSTED_CONTENT =\n 'input,textarea,select,[contenteditable=\"\"],[contenteditable=\"true\"],[aria-valuetext],[data-mf-private]';\n\n/**\n * Would computing this element's ACCESSIBLE NAME read the user's data?\n *\n * This is the leak the structural `isOpaque` walk cannot see. `computeAccessibleName`\n * runs its OWN descendant walk, inside dom-accessibility-api, that knows nothing about\n * our opaque set or `data-mf-private` — it will happily read `input.value`,\n * `aria-valuetext`, a contenteditable's text, or a private subtree, and fold it into\n * the name of a name-from-content ANCESTOR or any `aria-labelledby` referrer. So a\n * value our walk refuses to enter re-enters through the parent's name.\n *\n * Two vectors, both handled:\n * - name-from-content: the name is built from descendant text. If any descendant is\n * untrusted, the name is tainted.\n * - aria-labelledby: the name is pulled from a referenced element. If any referent\n * is (or contains) untrusted content, the name is tainted.\n *\n * `aria-label` and `title` are author-written static strings; a site that copies its\n * own secret into one is exposing it deliberately and we cannot defend that. The\n * automatic-computation vectors are the ones we must close.\n */\nfunction nameIsUntrusted(el: Element): boolean {\n const labelledby = el.getAttribute('aria-labelledby');\n if (labelledby) {\n for (const id of labelledby.split(/\\s+/)) {\n if (!id) continue;\n const ref = el.ownerDocument.getElementById(id);\n if (!ref) continue;\n if (\n ref.matches(UNTRUSTED_CONTENT) ||\n ref.querySelector(UNTRUSTED_CONTENT)\n ) {\n return true;\n }\n }\n return false;\n }\n // No explicit label attributes → the name, if any, is name-from-content.\n if (el.hasAttribute('aria-label')) return false;\n return el.querySelector(UNTRUSTED_CONTENT) !== null;\n}\n\nexport function nameOf(el: Element, styleOf: StyleOf): string {\n const name = computeAccessibleName(el, {\n getComputedStyle: styleOf,\n // jsdom logs a console error if you claim pseudo-element support it doesn't have.\n computedStyleSupportsPseudoElements: false,\n });\n if (!name) return '';\n\n // A tainted name would leak a value or a private string. Drop it entirely and let\n // the element stand on its role + ref. Losing a name costs the agent a little\n // context; keeping a leaked one is a breach. The trade is not close.\n if (nameIsUntrusted(el)) {\n // Preserve an explicit author label if one exists and is not itself the taint —\n // aria-labelledby taints were already caught above, so any aria-label here is safe.\n return el.getAttribute('aria-label') || '';\n }\n return name;\n}\n","import type { ElementRef } from '../protocol';\n\n/**\n * Element handles.\n *\n * The mechanism is Playwright's, deliberately (see protocol.ts): the agent never\n * learns a selector, it learns `e12`, and `e12` is turned back into an element\n * HERE, in the page, by us.\n *\n * Three properties matter and all are load-bearing:\n *\n * 1. THE MAP IS A WeakMap, NOT AN EXPANDO ON THE ELEMENT. An earlier version\n * stamped `el._mfRef`. Non-enumerable, so invisible to `Object.keys`/spreads/\n * `JSON.stringify` — but STILL reachable via `Object.getOwnPropertyNames` and\n * `Reflect.ownKeys`, and, worse, it parked the element's accessible name on the\n * customer's live DOM node indefinitely. A `WeakMap<Element, RefEntry>` mutates\n * nothing on their objects, is invisible to every enumeration and serialization\n * API without exception, cannot collide with a property the host already has,\n * and still gives us node-identity survival across GC for free.\n *\n * 2. A REF IS REGENERATED WHEN ROLE OR NAME CHANGES. Frameworks recycle DOM nodes:\n * a virtualised list scrolls, and the <button> that said \"Approve\" is the very\n * same node that now says \"Delete\". Keying the ref on (role, name) means that\n * node gets a NEW id and the old id resolves to nothing.\n *\n * 3. A REF IS SCOPED TO ONE SNAPSHOT GENERATION. (2) is necessary but not\n * sufficient: two icon-only \"Delete\" buttons in a virtualised table have the\n * SAME (role, name), so a recycled node whose role+name are unchanged would keep\n * its ref and silently retarget a different logical row. So a ref also carries\n * the generation it was minted in, and resolveRef refuses a ref from an older\n * generation — the agent must re-snapshot to get a fresh, valid handle. Loud\n * staleness beats silent retargeting.\n */\n\ninterface RefEntry {\n id: ElementRef;\n /** role + name at mint time. Changes here invalidate the ref. */\n key: string;\n /** The snapshot generation this ref belongs to. */\n gen: number;\n}\n\n/**\n * Monotonic across snapshots, never reused — like Playwright's. An id is only ever\n * handed out once in a page's lifetime, so a stale ref can never be *silently*\n * correct by colliding with a newer element; it just resolves to null.\n */\nlet counter = 0;\n\n/** Bumped once per full snapshot. A ref is only valid within its own generation. */\nlet generation = 0;\n\n/**\n * Element identity, off the host's objects entirely. Keyed by element so a recycled\n * node is recognised across snapshots; the entry carries the (role,name) key and the\n * generation for the two staleness checks above.\n */\nconst entries = new WeakMap<Element, RefEntry>();\n\n/** id -> element, for resolution. Rebuilt each generation from exactly what was emitted. */\nconst registry = new Map<ElementRef, Element>();\n\n/** Called once per FULL snapshot, before the walk. A region read does NOT call this. */\nexport function beginSnapshot(): void {\n generation++;\n registry.clear();\n}\n\n/**\n * Mint (or reuse) the ref for an element and register it for resolution.\n * Only ever called for elements that are visible AND receive pointer events.\n */\nexport function refFor(el: Element, role: string, name: string): ElementRef {\n const key = `${role} ${name}`;\n\n let entry = entries.get(el);\n if (!entry || entry.key !== key) {\n entry = { id: `e${++counter}`, key, gen: generation };\n entries.set(el, entry);\n } else {\n // Same node, same identity — carry it into the current generation so a fresh\n // snapshot re-validates a still-present element rather than orphaning it.\n entry.gen = generation;\n }\n\n registry.set(entry.id, el);\n return entry.id;\n}\n\n/**\n * Turn a ref back into an element.\n *\n * Three ways this returns null, each deliberate:\n * - unknown id (never minted, or from a cleared generation) → not in the registry;\n * - the element left the page → `isConnected` is false. A detached node still\n * answers every question (role, name, a zero box), so without this an action\n * would silently no-op against a ghost;\n * - the ref is from an OLDER generation → its entry.gen has been superseded. This is\n * what stops a recycled-node retarget: the agent is told the handle is stale and\n * must re-snapshot, rather than acting on the wrong row.\n */\nexport function resolveRef(ref: ElementRef): Element | null {\n const el = registry.get(ref);\n if (!el) return null;\n if (!el.isConnected) {\n registry.delete(ref);\n return null;\n }\n const entry = entries.get(el);\n if (!entry || entry.id !== ref || entry.gen !== generation) return null;\n return el;\n}\n\n/** Test-only: reset counters so refs are deterministic per test. */\nexport function __resetRefs(): void {\n counter = 0;\n generation = 0;\n registry.clear();\n}\n\n/**\n * Drop every ref's resolvability, without touching `counter`/`generation` — an old\n * id must never come back valid after this (unlike `__resetRefs`, which is test-only\n * determinism and would let ids collide again). Called from `context.ts`'s `stop()`\n * so a ref minted before a `pageContext:false` opt-out (or before an unmount) can't\n * be resolved afterward — belt-and-suspenders alongside `sendRegion`'s own\n * `pageContextOn` gate, in case a stale ref is ever replayed.\n */\nexport function clearRefs(): void {\n registry.clear();\n}\n","import { isDisabled, isInaccessible } from 'dom-accessibility-api';\n\nimport { isPrivate, redact } from '../context';\nimport {\n createStyleCache,\n hasLayout,\n isInteractive,\n NAME_FROM_CONTENT,\n isOpaque,\n isVisible,\n nameOf,\n receivesPointerEvents,\n roleOf,\n states,\n type StyleOf,\n} from './a11y';\nimport { beginSnapshot, refFor } from './refs';\n\nexport { resolveRef, clearRefs } from './refs';\n\n/**\n * The page, as the agent sees it.\n *\n * We emit Playwright's ARIA-snapshot YAML, and that choice is the point of this\n * file. It is not our format: it is the one the frontier models have seen most, via\n * playwright-mcp, so a model already knows how to read it and already knows that\n * `[ref=e12]` is the thing you hand back to act. Inventing our own dialect here\n * would cost us capability for nothing.\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - list:\n * - listitem:\n * - link \"Order #1043\" [ref=e8]\n * - text: \"Unpaid\"\n * - button \"Export CSV\" [ref=e12]\n *\n * Not raw HTML: a real page is tens of thousands of tokens of div soup, gives the\n * model nothing to act with, and is a prompt-injection firehose.\n */\n\n/* ─────────────────────────────── budgets ──────────────────────────────── */\n\n/**\n * These exist because the failure they prevent is not \"the snapshot is big\", it is\n * \"the agent confidently tells the user about a button that does not exist\". A model\n * given a silently-cut-off page has no way to know it was cut off, so it fills the\n * gap. Hence: hard caps, and `truncated: true` travels with the payload so the agent\n * can be TOLD it is not seeing everything.\n *\n * The two caps do different jobs, and conflating them is how you get a bad snapshot:\n *\n * MAX_LINES bounds the MODEL'S CONTEXT. 800 lines of ARIA YAML is ~12 KB, a few\n * thousand tokens — a dense dashboard, and about as much page as is useful to\n * reason over at once.\n *\n * MAX_NODES bounds the MAIN THREAD. It counts elements *visited*, most of which are\n * the wrapper divs of a modern app and emit nothing at all. Measured in Chrome on a\n * deeply-nested 52k-element table, visiting 4000 nodes costs ~25ms of walk. Set it\n * to 1500 (a tempting round number) and a div-soup page truncates at ~460 lines —\n * we would stop while HALF the line budget was still unspent, and tell the agent it\n * could not see a page we had simply given up on early.\n */\nconst MAX_NODES = 4000;\nconst MAX_LINES = 800;\nconst MAX_NAME = 120;\nconst MAX_TEXT = 120;\n/**\n * Max `<option>`s emitted per `<select>` before the rest is summarised. A country or\n * timezone picker runs to hundreds; the option list is an affordance to show, not a\n * reason to spend the line budget. The selected option is always in the first slice\n * in practice, but if a huge list has its selection past the cap the \"+N more\"\n * marker tells the agent it isn't seeing every choice.\n */\nconst MAX_OPTIONS = 25;\n\n/* ─────────────────────────────── model ────────────────────────────────── */\n\ninterface AriaNode {\n role: string;\n /** Raw accessible name. Redacted and truncated at render time, not here. */\n name: string;\n /** Pre-rendered bracket attributes, `[checked] [ref=e5]`. */\n props: string;\n children: (AriaNode | string)[];\n}\n\ninterface Walk {\n styleOf: StyleOf;\n layout: boolean;\n nodes: number;\n lines: number;\n truncated: boolean;\n /** Called for every element that gets a ref, so a caller can note which are on screen. */\n onRef?: (ref: string, el: Element) => void;\n}\n\n/** Elements that carry no meaning of their own: their children stand in for them. */\nconst TRANSPARENT = new Set(['generic', 'presentation', 'none']);\n\n/**\n * Never walked. `<script>`/`<style>`/`<noscript>` are the obvious ones; `<svg>` is\n * here because its innards are hundreds of `<path>` nodes of pure noise — any title\n * it carries is already folded into its parent's accessible name by accname.\n */\nconst SKIP_TAGS = new Set([\n 'SCRIPT',\n 'STYLE',\n 'NOSCRIPT',\n 'TEMPLATE',\n 'SVG',\n 'HEAD',\n 'LINK',\n 'META',\n 'BASE',\n]);\n\n/* ─────────────────────────────── walking ──────────────────────────────── */\n\n/** False once any budget is spent — the caller stops and we mark the snapshot truncated. */\nfunction withinBudget(w: Walk): boolean {\n if (w.nodes >= MAX_NODES || w.lines >= MAX_LINES) {\n w.truncated = true;\n return false;\n }\n return true;\n}\n\n/**\n * Is this element ours?\n *\n * The widget must never appear in its own snapshot: the agent describing its own\n * chat window back to itself is both useless and a lovely little feedback loop.\n */\nfunction isOurs(el: Element): boolean {\n return el.id === 'matterfact-embed' || el.hasAttribute('data-mf-embed');\n}\n\n/**\n * Hidden from assistive tech — and therefore from us.\n *\n * This is `isInaccessible()`'s rule set applied ONE NODE AT A TIME, top-down.\n * `isInaccessible()` itself walks every ancestor on every call, which over a whole\n * tree is the O(n·depth) blow-up the budget forbids; because we descend from the\n * root and prune the entire subtree the moment a node is hidden, the composition of\n * these local checks is exactly equivalent and costs O(1) per node. (We still call\n * the real thing once, on the root, as a backstop.)\n */\nfunction isHidden(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n if (el.getAttribute('aria-hidden') === 'true') return true;\n if (el.hasAttribute('hidden') || el.hasAttribute('inert')) return true;\n return !isVisible(el, style, layout);\n}\n\n/**\n * The nodes a parent should walk.\n *\n * An open shadow root REPLACES its host's light children — those only reach the\n * screen by being slotted, and we pick them up when we hit the `<slot>` that pulls\n * them in. Walking both would emit every web component's contents twice. A closed\n * shadow root is opaque to us by design, exactly as it is to the rest of the page.\n */\nfunction childrenOf(el: Element): ArrayLike<Node> {\n if (el.shadowRoot) return el.shadowRoot.childNodes;\n if (el.tagName === 'SLOT') {\n const assigned = (el as HTMLSlotElement).assignedNodes({ flatten: true });\n // An unfilled slot renders its own fallback content.\n if (assigned.length) return assigned;\n }\n return el.childNodes;\n}\n\n/** ArrayLike + index loop, not for-of: a NodeList needs `DOM.Iterable`, and copying one to iterate it allocates an array per element for nothing. */\nfunction visitChildren(\n el: Element,\n parent: AriaNode,\n style: CSSStyleDeclaration,\n w: Walk,\n): void {\n const children = childrenOf(el);\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (child) visitNode(child, parent, style, w);\n }\n}\n\nfunction visitText(node: Text, parent: AriaNode, w: Walk): void {\n const text = (node.nodeValue ?? '').replace(/\\s+/g, ' ').trim();\n if (!text) return;\n\n // The text of a button, a link or a heading IS its accessible name — we already\n // emitted it on the parent's line, and repeating it as a child would double the\n // tokens and imply a second, separate thing on the page. Decided by ROLE, never by\n // string-matching against the name (see NAME_FROM_CONTENT).\n if (NAME_FROM_CONTENT.has(parent.role)) return;\n\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(text);\n}\n\n/**\n * A native `<select>`, expanded into its options.\n *\n * The generic walk can't do this: a closed select's `<option>`s have no layout box,\n * so isVisible would prune them. Yet the options are exactly the affordance the agent\n * needs — \"what can I set this to\" — and, unlike an `<input>` value, they are a\n * bounded, author-defined set rather than free text the user typed. So we emit them,\n * and mark the selected one: it names one of the choices we are ALREADY showing, so\n * it reveals nothing a human looking at the control wouldn't see. Labels are redacted\n * at render time like every other name; the list is capped; a select the host deems\n * sensitive is hidden the usual way (`data-mf-private`) and never reaches here.\n *\n * `.options` is the flat HTMLOptionsCollection, so `<optgroup>` nesting is already\n * flattened for us; `<select multiple>` (role listbox) works through the same path.\n */\n/** One option, in Playwright's shape: `- option \"label\" [disabled] [selected]`. The\n * name is trimmed so a whitespace-only option renders `- option` (no \"\"). Disabled is\n * `:disabled` (which catches an <optgroup disabled> that isDisabled/opt.disabled miss)\n * OR isDisabled (which adds aria-disabled). Bracket order matches states(): [disabled]\n * before [selected]. */\nfunction optionNode(opt: HTMLOptionElement): AriaNode {\n const disabled = opt.matches(':disabled') || isDisabled(opt);\n return {\n role: 'option',\n name: (opt.label || opt.textContent || '').trim(),\n props:\n (disabled ? ' [disabled]' : '') + (opt.selected ? ' [selected]' : ''),\n children: [],\n };\n}\n\nfunction emitSelectOptions(\n select: HTMLSelectElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const options = select.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n // The selected option IS the field's current value — the one option the agent most\n // needs. In a long list (country, timezone) the selection can sit past the cap, so\n // the front slice above would show none marked [selected]. Surface any selected\n // option that fell outside the cap regardless, and don't double-count it as hidden.\n let extraSelected = 0;\n const selected = select.selectedOptions;\n for (let i = 0; i < selected.length; i++) {\n const opt = selected[i];\n if (opt && opt.index >= shown && !isPrivate(opt)) {\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(optionNode(opt));\n extraSelected++;\n }\n }\n const remaining = options.length - shown - extraSelected;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\n/**\n * An `<input list=\"…\">`'s datalist suggestions.\n *\n * Same affordance as a `<select>`'s options — a bounded, author-defined set the user\n * can pick — but surfaced under the (still value-opaque) input, because the\n * `<datalist>` element is display:none, so the generic walk never reaches it. The\n * input's own value stays hidden; only the suggestion labels are emitted (redacted at\n * render like every name, and capped). No [selected] — a datalist has no current\n * choice, only completions.\n */\nfunction emitDatalistOptions(\n input: HTMLInputElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const list = input.list as HTMLDataListElement | null;\n if (!list) return;\n const options = list.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n const remaining = options.length - shown;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\nfunction visitElement(\n el: Element,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (!withinBudget(w)) return;\n if (SKIP_TAGS.has(el.tagName) || isOurs(el)) return;\n\n // Privacy first, before we so much as compute a style: `data-mf-private` and\n // password/hidden inputs take their whole subtree with them.\n if (isPrivate(el)) return;\n\n w.nodes++;\n\n const style = w.styleOf(el);\n if (isHidden(el, style, w.layout)) return;\n\n const role = roleOf(el);\n const transparent = role === null || TRANSPARENT.has(role);\n const interactive = isInteractive(el, role, style, parentStyle);\n\n // A div with a click handler is invisible to us (no getEventListeners), but a div\n // that is FOCUSABLE, or that flips the cursor to a pointer, is announcing itself.\n // Playwright emits those as `- generic [ref=eN]` and so do we: without this, every\n // custom card, chip and icon-button on a modern app would be unreachable.\n if (transparent && !interactive) {\n visitChildren(el, parent, style, w);\n return;\n }\n\n const emittedRole = role === null || TRANSPARENT.has(role) ? 'generic' : role;\n const name = nameOf(el, w.styleOf);\n\n // Refs are for things you can act on. Static text does not get one — it would be a\n // handle the agent can only ever misuse, and it doubles the size of the snapshot.\n let ref = '';\n if (interactive && receivesPointerEvents(style)) {\n const r = refFor(el, emittedRole, name);\n ref = ` [ref=${r}]`;\n w.onRef?.(r, el);\n }\n\n const state = states(el, emittedRole);\n const node: AriaNode = {\n role: emittedRole,\n name,\n props: (state ? ` ${state}` : '') + ref,\n children: [],\n };\n\n w.lines++;\n parent.children.push(node);\n\n // A native <select>: emit its options — the affordance the opaque rule used to\n // hide — instead of walking its (layout-less, hence prune-able) children.\n if (el.tagName === 'SELECT') {\n emitSelectOptions(el as HTMLSelectElement, node, w);\n return;\n }\n\n // An <input list=\"…\">: surface its datalist suggestions (the affordance) under the\n // input, then fall through to the opaque return — the value itself is never emitted.\n if (el.tagName === 'INPUT' && (el as HTMLInputElement).list) {\n emitDatalistOptions(el as HTMLInputElement, node, w);\n }\n\n // isOpaque: an <input>, <textarea> or contenteditable. Its content IS the user's\n // data, so we do not walk into it — the value cannot leak because we never go and\n // look at it. See a11y.ts.\n if (isOpaque(el)) return;\n\n visitChildren(el, node, style, w);\n}\n\nfunction visitNode(\n node: Node,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (node.nodeType === 3 /* TEXT_NODE */) {\n visitText(node as Text, parent, w);\n } else if (node.nodeType === 1 /* ELEMENT_NODE */) {\n visitElement(node as Element, parent, parentStyle, w);\n }\n // Comments, CDATA, processing instructions: nothing to say.\n}\n\n/* ────────────────────────────── rendering ─────────────────────────────── */\n\n/**\n * Redact, then truncate — in that order, and the order is the point.\n *\n * Truncate first and a 130-character line containing an email address gets cut\n * through the middle of it, the regex no longer matches, and you have shipped\n * `jane.doe@acmecorp` to the model. Redaction runs on the whole string, every time,\n * before anything is thrown away.\n */\nfunction sanitize(text: string, max: number): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n const clean = redact(collapsed);\n return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;\n}\n\nfunction quote(text: string): string {\n return `\"${text.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\nfunction render(\n children: (AriaNode | string)[],\n depth: number,\n out: string[],\n): void {\n const pad = ' '.repeat(depth);\n for (const child of children) {\n if (typeof child === 'string') {\n out.push(`${pad}- text: ${quote(sanitize(child, MAX_TEXT))}`);\n continue;\n }\n const name = child.name ? ` ${quote(sanitize(child.name, MAX_NAME))}` : '';\n const head = `${pad}- ${child.role}${name}${child.props}`;\n if (child.children.length) {\n out.push(`${head}:`);\n render(child.children, depth + 1, out);\n } else {\n out.push(head);\n }\n }\n}\n\n/* ─────────────────────────────── entry ────────────────────────────────── */\n\n/**\n * Walk the page and render it. Called by context.ts, which redacts the result a\n * second time on the way out — the belt to this file's braces.\n */\nfunction walk(\n root: Element,\n onRef?: (ref: string, el: Element) => void,\n): { yaml: string; truncated: boolean } {\n const styleOf = createStyleCache();\n const w: Walk = {\n styleOf,\n layout: hasLayout(),\n nodes: 0,\n lines: 0,\n truncated: false,\n onRef,\n };\n\n // The one call to the real isInaccessible(): a cheap backstop on the root, where\n // the ancestor walk costs nothing.\n if (isInaccessible(root, { getComputedStyle: styleOf })) {\n return { yaml: '', truncated: false };\n }\n\n const tree: AriaNode = { role: '', name: '', props: '', children: [] };\n visitChildren(root, tree, styleOf(root), w);\n\n const lines: string[] = [];\n render(tree.children, 0, lines);\n\n // An in-band marker, not just the out-of-band `truncated` flag. The YAML is what\n // lands in the prompt; a backend template that injects the tree but forgets to\n // surface the flag would hand the model a page that simply stops, and the model\n // fills the gap. This line is inside the payload, so it cannot be dropped on the\n // way to the prompt. (Depth-first, so what is missing is the BOTTOM of the page.)\n //\n // It REPLACES the last emitted line rather than appending — the marker is part of\n // the line budget, not an exemption from it. The final line was a truncated node\n // anyway (see MAX_LINES), so nothing meaningful is lost.\n if (w.truncated && lines.length) {\n lines[lines.length - 1] =\n '- text: \"… (snapshot truncated — more of the page is below)\"';\n }\n\n return { yaml: lines.join('\\n'), truncated: w.truncated };\n}\n\n/**\n * The full page. Mints a fresh generation of refs (beginSnapshot), so any ref the\n * agent held from a previous snapshot is now stale and resolves to null — which is\n * correct: the page may have changed under it.\n *\n * `visibleRefs` is the viewport slice — the refs whose element is actually on screen.\n * That is the \"where is your attention\" signal, and it lets the focus context name\n * the handful of things in view out of the whole tree.\n */\nexport function snapshot(): {\n yaml: string;\n truncated: boolean;\n visibleRefs: string[];\n} {\n const root = document.body;\n if (!root) return { yaml: '', truncated: false, visibleRefs: [] };\n\n beginSnapshot();\n\n const visibleRefs: string[] = [];\n const vh = window.innerHeight || 0;\n const vw = window.innerWidth || 0;\n const result = walk(root, (ref, el) => {\n const r = el.getBoundingClientRect();\n // On screen = its box intersects the viewport. Cheap; the walk already forced\n // layout, so getBoundingClientRect here is reading a warm value.\n if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) {\n visibleRefs.push(ref);\n }\n });\n\n return { ...result, visibleRefs };\n}\n\n/**\n * Zoom in on one ref — the a11y sub-tree under it.\n *\n * This is the pull half: the agent has the focus context and a shallow page, and when\n * it wants the detail of a specific table or form it asks for that region rather than\n * us re-sending the whole page. It does NOT call beginSnapshot — that would clear the\n * ref map and invalidate the very ref being asked about — so the refs it mints join\n * the current generation.\n */\nexport function snapshotRegion(root: Element): {\n yaml: string;\n truncated: boolean;\n} {\n if (!root.isConnected) return { yaml: '', truncated: false };\n return walk(root);\n}\n","import type {\n ActivityEvent,\n FocusContext,\n HostToWidget,\n PageContext,\n PageEntity,\n SiteMapEntry,\n ToolCall,\n} from './protocol';\nimport { redact } from './redact';\nimport {\n detectHoist,\n buildHoistContext,\n renderHoistSnapshot,\n} from './adapters/hoist';\nimport {\n readHoistRuntime,\n readHoistConfig,\n} from './adapters/hoist-runtime';\n// The registry composes the hoist adapter with the mf.*/app.* tool sources and is the\n// single advertise/execute surface — context.ts talks to it, not to the hoist adapter\n// directly. See adapters/registry.ts.\nimport { advertise, execute, emitToolEvent, toolClass } from './adapters/registry';\n\n// Re-exported so every existing importer of `redact` from `./context` (e.g.\n// dom/snapshot.ts) keeps working unchanged — see redact.ts for why the\n// definition itself lives in its own module.\nexport { redact } from './redact';\n\n/** The origin serving our chat — how we tell OUR embedded content from the host's own\n * iframes. Set by start(); empty until then, which just means we spot nothing. */\nlet widgetOrigin = '';\n\n/**\n * The eye.\n *\n * Everything in this module can see the customer's page. It is a SEPARATE CHUNK,\n * loaded only when someone actually opens the chat — so a page whose visitors never\n * click the widget pays nothing for any of it, and a security reviewer can read\n * exactly one file to know what we look at.\n *\n * The rules, which are not negotiable:\n *\n * NEVER captured — no config enables it: the value of any <input>, <textarea> or\n * contenteditable; anything inside a password field; cookies; localStorage;\n * sessionStorage; the raw DOM; screenshots; network traffic; anything inside an\n * element marked `data-mf-private`.\n *\n * The agent never gets a selector and never touches the DOM. It gets refs. A ref\n * is resolved to an element HERE, in the page, by us.\n */\n\ntype Send = (msg: HostToWidget) => void;\n\nconst MAX_ACTIVITY = 40;\n\nlet send: Send | null = null;\nlet activitySeq = 0;\nconst activity: ActivityEvent[] = [];\nlet lastUrl = '';\n/** Set once by `start()`. False ⇒ the host opted out of ALL page observation — every\n * exported entry point below that would otherwise read or send the page checks this. */\nlet pageContextOn = true;\n\n/**\n * A host callback that returns the DECLARED page context on demand — the pull-based\n * counterpart to the static `window.matterfact.context` global. Symmetric with\n * `AuthTokenProvider`: the React `<MatterfactAgent getPageContext>` prop supplies it; the\n * `<script>` loader uses `window.matterfact.getPageContext` instead (see resolveDeclaredContext).\n */\nexport type PageContextProvider = () =>\n | PageContext\n | null\n | undefined\n | Promise<PageContext | null | undefined>;\n/** The programmatic pull callback, set by `start()`. Read fresh on every publish. */\nlet contextProvider: PageContextProvider | undefined;\n\n/* ─────────────────────────── teardown state ───────────────────────────── */\n\n/**\n * Everything below is module-global bookkeeping so `stop()` (see `start()`, bottom of\n * file) can undo exactly what `start()`/`watchNavigation()` installed — remove every\n * listener, restore `history` to what it was before we wrapped it, and forget any\n * DOM-walk module we pulled in. All of this outlives a single `EmbedHost`; see\n * `stop()`'s doc comment for why that's the bug this exists to close.\n */\n\n/** The `fire` closure `watchNavigation()` handed to `popstate` — the only handle we\n * have to remove that listener again. */\nlet navFire: (() => void) | null = null;\n/** The `history.pushState`/`replaceState` this module wrapped, captured so `stop()`\n * can restore them EXACTLY rather than re-wrapping (which is how the old code\n * double-fired navigation on a second `start()`). */\nlet origPushState: History['pushState'] | null = null;\nlet origReplaceState: History['replaceState'] | null = null;\n/** Set once `sendSnapshot`/`sendRegion`/`readFocus` actually pull in the DOM-walk\n * chunk (`./dom/snapshot`) — never imported eagerly, so `stop()` doesn't pay for a\n * chunk that a host who only ever opted out (and never opened a snapshot) never\n * loaded in the first place. */\nlet snapshotModule: { clearRefs: () => void } | null = null;\n\n/* ─────────────────────────── redaction ────────────────────────────────── */\n// redact() now lives in ./redact — see that file's doc comment. Re-exported\n// above; imported here for local use throughout this module.\n\n/** Anything the host has marked private, or that is inherently sensitive, is out. */\nexport function isPrivate(el: Element): boolean {\n if (el.closest('[data-mf-private]')) return true;\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const t = (el as HTMLInputElement).type;\n if (t === 'password' || t === 'hidden') return true;\n }\n return false;\n}\n\n/* ───────────────────────── page context ───────────────────────────────── */\n\n/**\n * What the page says about itself.\n *\n * A host that declares nothing still gets URL + title, which is what every other\n * embeddable assistant on the market offers in total. The interesting fields\n * (`route`, `description`, `entities`) are host-declared, because only the host\n * knows that `/o/8813` is \"the Acme Corp order, 3 items, unpaid\".\n *\n * Declared via a global the host sets before we load:\n * window.matterfact = { context: { route: '/orders/:id', description: '...', entities: [...] } }\n */\n/**\n * matterfact content embedded IN the host page — today, artifact iframes.\n *\n * A cross-origin iframe is opaque: `contentDocument` throws, so the DOM snapshot walks\n * straight past an embedded artifact and the agent is blind to the very thing the page\n * is built around. It reads the page as empty and asks which URL you mean.\n *\n * We don't need to see inside, and shouldn't want to. The artifact's ID is right there\n * in the src, and the agent can already resolve `artifacts/<id>/` in its session — the\n * same path an `@`-mention uses. So we report the ID and let the backend fetch the real\n * thing, which beats scraping a rendering of it: it gets the data, not the picture.\n *\n * Matched by ORIGIN, not by path shape: a customer is perfectly entitled to their own\n * /artifacts/ route, and it isn't ours.\n */\n/** The artifact slug from a matterfact artifact path, or null. Matches both the\n * chrome-free embed route (/embed/artifacts/<slug>) and the bare /artifacts/<slug>. */\nexport function artifactIdFromPath(pathname: string): string | null {\n const m = pathname.match(/^\\/(?:embed\\/)?artifacts\\/(.+?)\\/?$/);\n return m ? decodeURIComponent(m[1]) : null;\n}\n\nfunction embeddedMatterfactEntities(): PageEntity[] {\n if (!widgetOrigin) return [];\n const out: PageEntity[] = [];\n for (const frame of Array.from(document.querySelectorAll('iframe'))) {\n let u: URL;\n try {\n u = new URL(frame.getAttribute('src') || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== widgetOrigin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n if (out.some((e) => e.id === id)) continue; // same artifact twice = once\n // No url field: the agent reaches an artifact by ID (`artifacts/<id>/`), never by\n // fetching the page, and an artifact URL can carry a share token we've no business\n // forwarding. The id is the whole useful payload.\n out.push({\n kind: 'artifact',\n id,\n label: redact(frame.getAttribute('title') || '') || id,\n });\n }\n return out;\n}\n\n/**\n * Frames we can see the existence of but nothing inside — someone else's cross-origin\n * embed. Worth one line: \"there is a thing here I cannot read\" is a true and useful\n * statement, and much better than the agent confidently describing a page while missing\n * the widget the user is actually asking about.\n */\nfunction opaqueFrameCount(): number {\n return Array.from(document.querySelectorAll('iframe')).filter((f) => {\n try {\n const u = new URL(f.getAttribute('src') || '', location.href);\n return u.origin !== location.origin && u.origin !== widgetOrigin;\n } catch {\n return false;\n }\n }).length;\n}\n\n/**\n * Merge the host's DECLARED context with what we auto-detect. Auto-detected fields\n * (url/path/title/locale, co-embedded artifact entities, opaque-frame count) are additive:\n * a declared value wins where they overlap (the `...declared` spread), and found entities\n * append to declared ones.\n */\nexport function buildPageContext(declared: PageContext): PageContext {\n const found = embeddedMatterfactEntities();\n const opaque = opaqueFrameCount();\n\n return {\n // Path only. A query string is where session ids, tokens and email addresses\n // live; it is not ours to take.\n url: location.origin + location.pathname,\n path: location.pathname,\n title: redact(document.title),\n locale: document.documentElement.lang || undefined,\n ...declared,\n // After the spread: what we FOUND is additive to what the host DECLARED, never a\n // replacement. A host that declares its own entities still gets the artifacts we\n // spotted, and vice versa.\n entities: [...(declared.entities ?? []), ...found],\n data: {\n ...(declared.data ?? {}),\n ...(opaque ? { opaque_frames: opaque } : {}),\n },\n };\n}\n\n/** Back-compat: build context from the static `window.matterfact.context` global only (sync). */\nexport function readPageContext(): PageContext {\n return buildPageContext(\n (window as { matterfact?: { context?: PageContext } }).matterfact\n ?.context ?? {},\n );\n}\n\n/**\n * Resolve the host's DECLARED context, preferring a pull callback over the static global so\n * a virtualized SPA can hand us fresh context per turn. First non-null wins:\n * 1. the programmatic `getPageContext` provider (React `<MatterfactAgent getPageContext>`),\n * 2. the `<script>`-loader global `window.matterfact.getPageContext()`,\n * 3. the static `window.matterfact.context`.\n */\nasync function resolveDeclaredContext(): Promise<PageContext> {\n const mf = (\n window as {\n matterfact?: {\n context?: PageContext;\n getPageContext?: PageContextProvider;\n };\n }\n ).matterfact;\n if (contextProvider) {\n const c = await contextProvider();\n if (c) return c;\n }\n if (mf?.getPageContext) {\n const c = await mf.getPageContext();\n if (c) return c;\n }\n // Hoist auto-detection: a framework-shaped context source, below explicit host\n // declarations but above the static global. Degrade-safe (detectHoist swallows).\n const hoist = detectHoist(() => readHoistRuntime());\n if (hoist) return buildHoistContext(hoist);\n return mf?.context ?? {};\n}\n\n/**\n * Publish the current declared+detected context as `host.context`. Async because the pull\n * callback may be (a host might read a store). Rapid calls just re-publish — for idempotent\n * context, last-writer-wins is fine. No-op when the host opted out of page observation.\n */\nasync function publishContext() {\n if (!pageContextOn) return;\n const declared = await resolveDeclaredContext();\n send?.({ type: 'host.context', context: buildPageContext(declared) });\n}\n\n/**\n * Answer a `widget.requestContext` (the pull path): publish context AND the site map NOW,\n * so a turn assembled right after carries both as they are — not as of the last route\n * change. The site map matters here as much as the context: the loader's nav hook fires\n * synchronously during `pushState`, BEFORE a React host has re-rendered with the new\n * route's map, so a nav-time push can be a render stale. Re-publishing at turn-assembly\n * (after the host has settled) is what makes it fresh. No-op when page observation is off.\n */\nexport function provideContext() {\n void publishContext();\n publishSitemap();\n}\n\n/* ─────────────────────── artifact grants (backend-only) ────────────────── */\n\nexport interface ArtifactGrantSrc {\n id: string;\n owner: string;\n token: string;\n}\n\n/** Read-only capability grants from co-embedded artifact iframes, for the backend to\n * materialize their data. Separate from entities on purpose: the token must never ride\n * ambient (rendered) context, only this backend-only channel. */\nexport function grantsFromIframeSrcs(\n srcs: string[],\n origin: string,\n): ArtifactGrantSrc[] {\n const out: ArtifactGrantSrc[] = [];\n for (const raw of srcs) {\n let u: URL;\n try {\n u = new URL(raw || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== origin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n const owner = u.searchParams.get('owner') || '';\n const token = u.searchParams.get('t') || '';\n if (!owner || !token) continue;\n if (out.some((g) => g.id === id)) continue;\n out.push({ id, owner, token });\n }\n return out;\n}\n\n/**\n * Grants DECLARED by the host — `window.matterfact.artifacts` (the\n * `<MatterfactAgent artifacts>` prop mirrors onto it). Same wire shape as a scanned\n * iframe grant, so a board is reachable from a route where its iframe isn't mounted\n * WITHOUT hidden zero-size iframes smuggling the token into the DOM. Degrade-safe:\n * anything malformed is skipped, never thrown.\n */\nexport function readDeclaredGrants(): ArtifactGrantSrc[] {\n const declared = (\n window as {\n matterfact?: {\n artifacts?: Array<{ slug?: string; owner?: string; token?: string }>;\n };\n }\n ).matterfact?.artifacts;\n if (!Array.isArray(declared)) return [];\n const out: ArtifactGrantSrc[] = [];\n for (const a of declared) {\n const id = (a?.slug || '').trim();\n const owner = (a?.owner || '').trim();\n const token = (a?.token || '').trim();\n if (!id || !owner || !token) continue;\n if (out.some((g) => g.id === id)) continue;\n out.push({ id, owner, token });\n }\n return out;\n}\n\nfunction readArtifactGrants(): ArtifactGrantSrc[] {\n if (!widgetOrigin) return [];\n const srcs = Array.from(document.querySelectorAll('iframe')).map(\n (f) => f.getAttribute('src') || '',\n );\n const scanned = grantsFromIframeSrcs(srcs, widgetOrigin);\n // A live co-embedded iframe on THIS page wins over a declared grant for the same\n // slug (its token is the one the visible board is actually spending); declared\n // grants fill in the boards that aren't mounted here.\n const out = [...scanned];\n for (const g of readDeclaredGrants()) {\n if (!out.some((s) => s.id === g.id)) out.push(g);\n }\n return out;\n}\n\nfunction publishArtifactGrants() {\n send?.({ type: 'host.artifactGrants', grants: readArtifactGrants() });\n}\n\n/* ─────────────────────────── site map ─────────────────────────────────── */\n\n/**\n * The host's DECLARED site map — its routes, annotated with a content class so the\n * agent knows which carry matterfact content and of what kind. Read from the\n * `window.matterfact.sitemap` global; the React `<MatterfactAgent sitemap>` prop writes\n * it there, symmetric with `context`/`actions`. Classification only — no per-instance\n * ids, never a capability token (those ride `host.context`/`host.artifactGrants`).\n */\nfunction readSitemap(): SiteMapEntry[] {\n const s = (window as { matterfact?: { sitemap?: SiteMapEntry[] } }).matterfact\n ?.sitemap;\n return Array.isArray(s) ? s : [];\n}\n\nfunction publishSitemap() {\n if (!pageContextOn) return;\n const sitemap = readSitemap();\n // Omit an empty map rather than send `[]` on every load — most hosts declare none.\n if (sitemap.length) send?.({ type: 'host.sitemap', sitemap });\n}\n\n/**\n * Navigate the HOST page to one of its OWN routes — the \"open on page\" deeplink from\n * a co-embedded document's side-panel viewer. The widget is a cross-origin iframe and\n * can't navigate the top window itself, so it asks us (via `widget.navigate`).\n *\n * Guarded to the host's OWN origin: resolve the href against the host location and\n * refuse anything on a different origin or a non-http(s) scheme. The href originates\n * in page context the host itself declared, so this is defense-in-depth — the widget\n * must never be able to send the host off-site. Lives in this lazy chunk (not the\n * eager loader stub) to stay off the every-page budget.\n */\nexport function navigateHost(href: unknown): void {\n if (typeof href !== 'string' || !href) return;\n let target: URL;\n try {\n target = new URL(href, location.href);\n } catch {\n return;\n }\n if (target.protocol !== 'http:' && target.protocol !== 'https:') return;\n if (target.origin !== location.origin) return;\n location.assign(target.href);\n}\n\n/* ────────────────────────── activity ──────────────────────────────────── */\n\nfunction pushActivity(e: Omit<ActivityEvent, 'seq' | 'ts'>) {\n activity.push({ ...e, seq: ++activitySeq, ts: Date.now() });\n if (activity.length > MAX_ACTIVITY) activity.shift();\n send?.({ type: 'host.activity', events: [activity[activity.length - 1]] });\n}\n\n/**\n * A short, human-readable label for what got clicked.\n *\n * Shaped after PostHog's autocapture, not after a session-replay frame: rrweb would\n * give us `{source:2, type:2, id:417, x:210, y:88}` — no text, no role, no href,\n * meaningless to a model without the full DOM snapshot it deltas against. One line\n * of \"clicked button 'Export CSV'\" is worth more and costs less.\n */\n/**\n * The accessible NAME of a form control — never its value.\n *\n * A control has no `innerText`, so the generic path below misses it. We look where a\n * control's name actually lives: `aria-label`, then a `<label for>` or a wrapping\n * `<label>`, then `placeholder`. `placeholder` is a LABEL, not a value — it is the\n * hint shown when the field is empty (\"Order number or customer\"), so it is safe.\n */\nfunction controlLabel(el: Element): string {\n const aria = el.getAttribute('aria-label');\n if (aria) return aria;\n\n const id = el.id;\n if (id) {\n const forLabel = document.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n const t = forLabel?.textContent?.trim();\n if (t) return t;\n }\n const wrapping = el.closest('label')?.textContent?.trim();\n if (wrapping) return wrapping;\n\n const placeholder = el.getAttribute('placeholder');\n if (placeholder) return placeholder;\n\n return '';\n}\n\nconst FORM_CONTROLS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);\n\nfunction describe(el: Element): string {\n const role = el.getAttribute('role') || el.tagName.toLowerCase();\n const label =\n el.getAttribute('aria-label') ||\n (FORM_CONTROLS.has(el.tagName)\n ? controlLabel(el)\n : (el as HTMLElement).innerText?.trim().slice(0, 60)) ||\n el.getAttribute('title') ||\n '';\n return label ? `${role} \"${redact(label)}\"` : role;\n}\n\n/**\n * Elements a click is worth recording. Deliberately tight: the point of the activity\n * stream is INTENT (\"the user chose to export\"), and a click on a heading, a label,\n * a card gutter, or blank page is not intent, it is noise. We only log a click that\n * lands on something actionable.\n */\nconst ACTIONABLE =\n 'a[href],button,input,select,textarea,summary,' +\n '[role=\"button\"],[role=\"link\"],[role=\"menuitem\"],[role=\"tab\"],[role=\"option\"],' +\n '[role=\"checkbox\"],[role=\"switch\"],[role=\"radio\"],[onclick],[tabindex]';\n\nfunction onClick(ev: Event) {\n const target = ev.target as Element | null;\n if (!target || !(target instanceof Element)) return;\n\n // Clicking a <label> operates the control it labels — record THAT, not \"clicked\n // label\", so the event reads as the user's actual intent.\n const label = target.closest('label');\n const labelled = label\n ? (label.getAttribute('for') &&\n document.getElementById(label.getAttribute('for')!)) ||\n label.querySelector('input,select,textarea')\n : null;\n\n const actionable = labelled ?? target.closest(ACTIONABLE);\n // No actionable target — a click on text, a gutter, or blank space. That is not an\n // action; dropping it is the whole fix for the click-log noise.\n if (!actionable || isPrivate(actionable)) return;\n\n pushActivity({ type: 'click', summary: `clicked ${describe(actionable)}` });\n}\n\nfunction onSubmit(ev: Event) {\n const el = ev.target as Element | null;\n if (!el || isPrivate(el)) return;\n // The FORM was submitted — never its values.\n pushActivity({ type: 'submit', summary: `submitted ${describe(el)}` });\n}\n\n/**\n * A form field changed.\n *\n * The rule is the same as everywhere else and the temptation here is sharpest:\n * record THAT a field changed and WHICH field (its label), never WHAT it was\n * changed to. `change` fires on exactly the elements whose values are off-limits.\n *\n * One safe exception: a <select>, a checkbox, or a radio chose from a fixed, visible\n * set of options the agent can already see in the snapshot — \"Unpaid\", \"Shipped\".\n * That is a user *choice*, not typed data, so the chosen option's LABEL is fair to\n * include and is the useful part (\"filtered status to Shipped\"). Free-text and\n * numeric inputs get their label only.\n */\nfunction onChange(ev: Event) {\n const el = ev.target as (HTMLElement & { type?: string }) | null;\n if (!el || !(el instanceof Element) || isPrivate(el)) return;\n\n const tag = el.tagName;\n const type = (el as HTMLInputElement).type;\n\n // Never a password/hidden field, and isPrivate already covered data-mf-private.\n if (tag === 'INPUT' && (type === 'password' || type === 'hidden')) return;\n\n let summary = `changed ${describe(el)}`;\n\n if (tag === 'SELECT') {\n const opt = (el as HTMLSelectElement).selectedOptions[0]?.text;\n if (opt) summary = `${describe(el)} → \"${redact(opt)}\"`;\n } else if (type === 'checkbox' || type === 'radio') {\n summary = `${(el as HTMLInputElement).checked ? 'checked' : 'unchecked'} ${describe(el)}`;\n }\n\n pushActivity({ type: 'input', summary });\n}\n\n/**\n * SPA navigation. There is no event for `pushState`, so we wrap it — a 20-line job\n * that no library does better.\n */\nfunction watchNavigation() {\n const fire = () => {\n const url = location.pathname;\n if (url === lastUrl) return;\n lastUrl = url;\n pushActivity({ type: 'nav', summary: `navigated to ${url}` });\n void publishContext();\n publishArtifactGrants();\n // The site map can change without a reload (a virtualized SPA) and `current`\n // moves with the route, so re-publish it on navigation like context/grants.\n publishSitemap();\n // Re-advertise host.tools too (Minor #2): the enum `hoist.navigate` carries is\n // bound to the CURRENT sitemap, and start() only ever advertised it ONCE. A\n // route that gained or lost destinations must not leave the widget holding a\n // stale enum forever. Unlike start()'s one-shot emit (gated on tools.length),\n // this fires even when the result is `[]` — the whole point is to CLEAR a\n // tool the widget cached from before this navigation, not just to add one.\n publishTools();\n };\n // Captured so stop() can remove exactly this listener, and so history.pushState/\n // replaceState get restored to what they were before we wrapped them — never\n // re-wrapped on top of an existing wrap (that was the pre-existing bug: a second\n // start() used to wrap the ALREADY-wrapped methods, double-firing every nav).\n navFire = fire;\n\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = history[name];\n if (name === 'pushState') origPushState = orig as History['pushState'];\n else origReplaceState = orig as History['replaceState'];\n history[name] = function (\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const r = orig.apply(this, args);\n fire();\n return r;\n } as History[typeof name];\n }\n window.addEventListener('popstate', fire);\n}\n\n/* ─────────────────────────── focal context ────────────────────────────── */\n\n/**\n * Where the user's attention is, right now.\n *\n * This is the \"knows what you're doing\" layer, and it is deliberately small so it can\n * ride on every turn — where the full snapshot cannot. It is also the most sensitive:\n * `selection` is whatever the user highlighted, which could be their own email, so it\n * is redacted and respects data-mf-private like everything else. Focus and the\n * viewport are labels and refs — never a value.\n *\n * Held so the last-known focus can travel with a turn even between the (throttled)\n * push updates.\n */\nlet lastFocus: FocusContext = {};\n\nasync function readFocus(): Promise<FocusContext> {\n const focus: FocusContext = {};\n\n // Selection — the single strongest \"this is what I'm asking about\" signal.\n const sel = window.getSelection?.();\n if (sel && !sel.isCollapsed) {\n const anchor = sel.anchorNode?.parentElement ?? null;\n // Don't lift a selection out of a private region, and cap it — a user can select\n // the whole page.\n if (!anchor || !anchor.closest('[data-mf-private]')) {\n const text = sel.toString().trim().slice(0, 500);\n if (text) focus.selection = redact(text);\n }\n }\n\n // The control they're working in — its label, never its contents.\n const active = document.activeElement;\n if (\n active &&\n active !== document.body &&\n !isPrivate(active) &&\n !active.closest('[data-mf-private]')\n ) {\n const { snapshot } = await loadSnapshotModule();\n void snapshot; // ensure the chunk that owns refFor is loaded before we describe\n focus.focused = {\n label: redact(describeControl(active)),\n role: active.getAttribute('role') || active.tagName.toLowerCase(),\n };\n }\n\n const doc = document.documentElement;\n const scrollable = doc.scrollHeight - doc.clientHeight;\n focus.scroll =\n scrollable > 0 ? Math.round((doc.scrollTop / scrollable) * 100) / 100 : 0;\n\n return focus;\n}\n\n/** A label for whatever is focused, reusing the same value-blind rules as activity. */\nfunction describeControl(el: Element): string {\n return describe(el);\n}\n\n/** The one place any of the three call sites below reach into the DOM-walk chunk —\n * so `stop()` has a single `snapshotModule` to check without importing anything\n * itself (see the teardown-state block above). */\nasync function loadSnapshotModule() {\n const m = await import('./dom/snapshot');\n snapshotModule = m;\n return m;\n}\n\nlet focusTimer: ReturnType<typeof setTimeout> | null = null;\n\n/** Coalesce a burst of selection/focus/scroll events into one push. */\nfunction scheduleFocus() {\n if (focusTimer) return;\n focusTimer = setTimeout(async () => {\n focusTimer = null;\n lastFocus = await readFocus();\n send?.({ type: 'host.focus', focus: lastFocus });\n }, 250);\n}\n\n/* ───────────────────────────── snapshot ───────────────────────────────── */\n\nlet snapshotSeq = 0;\n\nexport async function sendSnapshot(emit: Send) {\n // pageContext: false ⇒ no snapshot, ever — a `widget.requestSnapshot` must not be\n // able to reintroduce the page observation the host explicitly turned off.\n if (!pageContextOn) return;\n\n // Hoist-first: on an XH Hoist SPA, the live models are a richer and cheaper source\n // of truth than scraping role-less div soup. detectHoist() is degrade-safe (never\n // throws here), so an absent/broken window.XH falls straight through to the\n // generic a11y walk below, unchanged.\n const hoist = detectHoist(() => readHoistRuntime());\n if (hoist) {\n const { rows } = readHoistConfig(\n typeof window !== 'undefined' ? window : undefined,\n );\n const { yaml, truncated } = renderHoistSnapshot(hoist, rows);\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // Refs are out of scope for Layer 1 (they arrive with the interactive channel in\n // Layer 3) — a Hoist snapshot never mints [ref=eN] handles, so nothing is visible\n // by ref.\n lastFocus = { ...lastFocus, visibleRefs: [] };\n emit({ type: 'host.focus', focus: lastFocus });\n return;\n }\n\n // The a11y walk is itself lazily imported: a host that only ever declares\n // PageContext and never lets the agent look at the page never downloads it.\n const { snapshot } = await loadSnapshotModule();\n const { yaml, truncated, visibleRefs } = snapshot();\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // The viewport slice rides with the focus context so the agent can tell the few\n // things on screen from the whole tree it just received.\n lastFocus = { ...lastFocus, visibleRefs };\n emit({ type: 'host.focus', focus: lastFocus });\n}\n\n/**\n * Zoom in on one ref — the pull half of the model. The agent asks; we resolve the ref\n * to a live element and return just its sub-tree.\n */\nexport async function sendRegion(ref: string, emit: Send) {\n // Mirrors sendSnapshot's guard: a `widget.readRegion` for a ref minted before\n // opt-out must not pull a live DOM subtree just because the ref is still\n // resolvable (see refs.ts's `clearRefs`, which `stop()` also uses as a backstop).\n if (!pageContextOn) return;\n const { snapshotRegion, resolveRef } = await loadSnapshotModule();\n const el = resolveRef(ref);\n if (!el) {\n emit({\n type: 'host.region',\n ref,\n yaml: '(this element is no longer on the page)',\n });\n return;\n }\n const { yaml } = snapshotRegion(el);\n emit({ type: 'host.region', ref, yaml: redact(yaml) });\n}\n\n/* ───────────────────────────── tools ──────────────────────────────────── */\n\n/**\n * Tools the page's ADAPTER (today: Hoist) exposes to the agent, and the sole\n * execution path for calling one.\n *\n * The page's content is untrusted — text on it can try to instruct the agent — and\n * the moment the agent can act, a bad answer becomes a bad ACTION. Several things\n * hold that line, and all of them live HERE (in the page, where we control what\n * actually happens), not in the widget, which can be lied to:\n *\n * - a tool is only ever ADVERTISED (`advertiseTools`) when the HOST opted in via\n * `window.matterfact.hoist.actions` — default 'off';\n * - this function itself refuses to even attempt a call when the host opted out\n * of page observation (`pageContext:false`) — see the `pageContextOn` guard\n * below, mirroring every sibling in this file;\n * - `executeHostTool` (adapters/hoist-runtime.ts) RE-CHECKS the host's current\n * action policy AND re-validates the destination against the LIVE page state,\n * on every call — never trusting what the widget claims was advertised, or\n * that the policy it was advertised UNDER still holds. A tool not marked\n * `readOnly` also carries a `confirm` policy the widget must gate on — see\n * HostTool's doc comment in protocol.ts.\n */\nexport async function callTool(call: ToolCall, emit: Send) {\n // Mirrors every sibling in this file (sendSnapshot, sendRegion, publishContext):\n // pageContext:false means the host opted out of ALL page observation, and a tool\n // call is exactly that — it would read the live Hoist runtime just like a\n // snapshot does. UNLIKE those siblings, this still REPLIES (ok:false) rather than\n // silently no-op-ing: the widget's callTool() is awaiting a specific callId, and\n // a call that never gets a host.toolResult hangs until its own timeout instead of\n // failing fast.\n if (!pageContextOn) {\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: false,\n error: 'host tools are disabled',\n });\n return;\n }\n const win = typeof window !== 'undefined' ? window : undefined;\n const cls = toolClass(call.name);\n const startedAt = Date.now();\n emitToolEvent(win, {\n phase: 'call',\n name: call.name,\n toolClass: cls,\n args: call.args,\n });\n const r = await execute(call, win);\n emitToolEvent(win, {\n phase: 'result',\n name: call.name,\n toolClass: cls,\n ok: r.ok,\n error: r.error,\n ms: Date.now() - startedAt,\n });\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: r.ok,\n result: r.result,\n error: r.error,\n });\n}\n\n/* ───────────────────────────── stop / start ───────────────────────────── */\n\n/**\n * The opposite number of `start()` — remove every listener it (or `watchNavigation`)\n * installed, restore `history.pushState`/`replaceState` to what they were before we\n * wrapped them, and forget the module-level `send`/`activity`/focus state. Nothing\n * here is a filter over what gets sent afterward — there is simply nothing left\n * installed to send anything.\n *\n * Why this has to exist at all: everything `start()` installs is MODULE-GLOBAL, and\n * this module outlives any single `EmbedHost`. React remounts `EmbedHost` whenever\n * ANY of its identity-defining props change (react.tsx's effect deps: publishableKey,\n * widgetOrigin, surface, theme, inline, pageContext, dev) — including just a theme\n * swap, not only a deliberate opt-out. Before this fix, a remount's `start()` call\n * only ever ADDED listeners; the previous mount's were still attached and kept firing\n * into the module `send`, which the new `start()` had just repointed at the NEW\n * widget. Net effect: open once with pageContext on, then remount for any reason\n * (including `pageContext: false`) and the new widget silently keeps receiving\n * clicks/nav/focus collected by the old mount's still-live listeners.\n *\n * Called from two places: the top of `start()` (idempotency — a second `start()`\n * never doubles up, which also fixes the pre-existing double history-wrap /\n * double-`fire()`-per-navigation bug), and `EmbedHost.destroy()` in loader.ts (a\n * plain unmount with no remount still has to stop, not just wait for a `start()`\n * that may never come).\n */\nexport function stop(): void {\n document.removeEventListener('click', onClick, { capture: true });\n document.removeEventListener('submit', onSubmit, { capture: true });\n document.removeEventListener('change', onChange, { capture: true });\n document.removeEventListener('selectionchange', scheduleFocus);\n document.removeEventListener('focusin', scheduleFocus, { capture: true });\n window.removeEventListener('scroll', scheduleFocus, { capture: true });\n\n if (navFire) {\n window.removeEventListener('popstate', navFire);\n navFire = null;\n }\n // Restore, don't re-wrap: this is what stops a repeated start() from wrapping an\n // already-wrapped pushState/replaceState (the old double-fire-per-nav bug).\n if (origPushState) {\n history.pushState = origPushState;\n origPushState = null;\n }\n if (origReplaceState) {\n history.replaceState = origReplaceState;\n origReplaceState = null;\n }\n\n if (focusTimer) {\n clearTimeout(focusTimer);\n focusTimer = null;\n }\n\n send = null;\n contextProvider = undefined;\n activity.length = 0;\n lastFocus = {};\n widgetOrigin = '';\n\n // Belt-and-suspenders alongside sendRegion's own pageContextOn check (see above):\n // an old ref minted while observation was on must not stay resolvable afterward.\n // Only touches the DOM-walk chunk if it was ever actually loaded — see\n // loadSnapshotModule's doc comment.\n snapshotModule?.clearRefs();\n}\n\n/**\n * @param pageContext Whether to observe the host page at all. Default `true`. False is\n * the loader's `pageContext: false` opt-out reaching all the way down here: skip every\n * bit of page reading below — no declared/found context, no artifact grants, no nav/\n * click/submit/change/focus observers — so there is nothing to send and nothing that\n * could later be asked for (see `widget.requestSnapshot` in loader.ts). Theme detection\n * is unaffected: it reads an OS media query, never the page, so it isn't page context.\n *\n * The host's action policy (`{navigate:'off'|'confirm'|'auto'}`) is NOT a parameter\n * here — unlike `pageContext`/`provider`, it has exactly one source,\n * `window.matterfact.hoist.actions`, read fresh by `advertiseTools`/`readActionsConfig`\n * (adapters/hoist-runtime.ts) at both advertise time (below, and watchNavigation's\n * re-advertisement) and execute time (`executeHostTool`, via `callTool`) — so the two\n * can never disagree about the current policy the way an eagerly-threaded override\n * could.\n */\nexport function start(\n emit: Send,\n origin?: string,\n pageContext = true,\n provider?: PageContextProvider,\n) {\n // Idempotent: undo whatever a PREVIOUS start() installed before this one installs\n // anything. Without this, a remount (see stop()'s doc comment) leaves the old\n // mount's listeners live, writing into the `send` this call is about to reassign.\n stop();\n\n send = emit;\n widgetOrigin = origin || '';\n lastUrl = location.pathname;\n pageContextOn = pageContext;\n contextProvider = provider;\n\n if (pageContextOn) {\n void publishContext();\n publishArtifactGrants();\n publishSitemap();\n watchNavigation();\n\n // Passive + capture: we observe, we never interfere with the host's own handling.\n document.addEventListener('click', onClick, {\n capture: true,\n passive: true,\n });\n document.addEventListener('submit', onSubmit, {\n capture: true,\n passive: true,\n });\n // `change` fires on blur/commit for text inputs and immediately for select/\n // checkbox/radio — not on every keystroke, which is what we want: a settled\n // choice, not a stream of partial values.\n document.addEventListener('change', onChange, {\n capture: true,\n passive: true,\n });\n\n // Focal context: what the user is attending to. Coalesced (scheduleFocus), because\n // selectionchange and scroll fire in torrents.\n document.addEventListener('selectionchange', scheduleFocus, {\n passive: true,\n });\n document.addEventListener('focusin', scheduleFocus, {\n capture: true,\n passive: true,\n });\n window.addEventListener('scroll', scheduleFocus, {\n capture: true,\n passive: true,\n });\n }\n\n const theme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light';\n emit({ type: 'host.theme', mode: theme });\n\n // Tool advertisement — after theme, at the very end of start(). Gated on\n // pageContextOn like every other Hoist-runtime read (sendSnapshot mirrors this):\n // the site map the hoist adapter reads from is live page state, not something a\n // pageContext:false host agreed to expose. Skipped entirely (no empty host.tools)\n // rather than advertising nothing on every single load — advertise() itself is\n // degrade-safe and never throws, so this needs no try/catch of its own.\n if (pageContextOn) {\n const w = typeof window !== 'undefined' ? window : undefined;\n const tools = advertise(w);\n if (tools.length) {\n emit({ type: 'host.tools', tools });\n for (const t of tools) {\n emitToolEvent(w, {\n phase: 'advertise',\n name: t.name,\n toolClass: toolClass(t.name),\n });\n }\n }\n }\n}\n\n/** Advertise the merged tool list on the wire and fire the host's onToolEvent so its\n * telemetry (and the dev panel) sees the current set. Shared by start()'s first emit's\n * navigation re-advertisement; fires even on `[]` to CLEAR a tool cached before a nav. */\nfunction publishTools() {\n const win = typeof window !== 'undefined' ? window : undefined;\n const tools = advertise(win);\n send?.({ type: 'host.tools', tools });\n for (const t of tools) {\n emitToolEvent(win, {\n phase: 'advertise',\n name: t.name,\n toolClass: toolClass(t.name),\n });\n }\n}\n","/**\n * The matterfact embed bridge protocol.\n *\n * This is the contract between the HOST PAGE (a customer's site, running our\n * loader) and the WIDGET (our chat, running in a cross-origin iframe on\n * app.matterfact.com).\n *\n * Two things to understand before changing anything here:\n *\n * 1. THE IFRAME CANNOT SEE THE PAGE. It is cross-origin — that is the entire\n * point of it. So every fact about the host page (its URL, its DOM, what the\n * user just did) reaches the agent only because the LOADER, which runs as\n * ordinary page JS and *can* see it, chose to send it. The loader is the eye;\n * the widget is the mouth.\n *\n * 2. THIS CONTRACT OUTLIVES THE IFRAME. The next tier is an in-page React SDK\n * with no iframe at all — and it will speak exactly this. If the message\n * shapes are right, \"deeper integration\" is a transport swap (postMessage ->\n * direct call), not a rewrite. So model the DOMAIN here, not the plumbing.\n */\n\n// v3 (2026-07): adds `host.sitemap` (a structured, content-annotated site map),\n// `widget.navigate` (deeplink the host to one of its own routes), and `widget.chat`\n// (content-free chat-turn telemetry forwarded to the host's `onEvent`). All additive —\n// a peer that doesn't know a message simply never sends/handles it — so this is a\n// capability signal, not a breaking change. No code branches on the version number.\nexport const PROTOCOL_VERSION = 3;\n\n/** Every message is namespaced so we never collide with the host page's own postMessage traffic. */\nexport const CHANNEL = 'mf-embed';\n\n/* ────────────────────────────── refs ──────────────────────────────────── */\n\n/**\n * A handle on a real element in the host page.\n *\n * Format and semantics are lifted from Playwright's ARIA snapshot (`ref=e12`),\n * for a specific reason: it is the element-handle syntax the frontier models have\n * seen most, via playwright-mcp. We are not being original here on purpose.\n *\n * The ref is an in-page expando plus a snapshot-scoped Map — never an attribute,\n * so it is invisible to the host page's CSS, its serialization, and its own\n * mutation observers. It is resolved back to an element by the LOADER; the agent\n * never touches the DOM, and never learns a selector.\n */\nexport type ElementRef = string; // 'e12'\n\n/* ──────────────────────────── host → widget ───────────────────────────── */\n\n/** Ambient facts about the page. Cheap, sent on every navigation. */\nexport interface PageContext {\n url?: string;\n /** A route PATTERN ('/orders/:id') beats a raw path — it tells the agent what KIND of page this is. */\n route?: string;\n path?: string;\n title?: string;\n locale?: string;\n /** 1–2 sentences, written the way you'd brief a colleague. The highest-value field by far. */\n description?: string;\n /** Things the page is about. These also become @-mentionable in the composer, for free. */\n entities?: PageEntity[];\n /** Allowlisted only. Never a dump of app state. */\n data?: Record<string, unknown>;\n}\n\nexport interface PageEntity {\n /** Host kinds are namespaced (`x:ticker`) so they can never collide with matterfact's own. */\n kind: string;\n id: string;\n label: string;\n /** Pre-rendered, agent-readable. Keep it short. */\n text?: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * How a route's content is classified, for the annotated site map.\n *\n * The host DECORATES the site map we auto-derive (see `SiteMapEntry`) so the agent\n * knows which routes carry MATTERFACT content and of what kind — app-wide awareness\n * it can navigate toward. This is CLASSIFICATION only: no per-instance ids, and never\n * a capability token. The concrete artifact/document on the CURRENT page still arrives\n * via `host.context` entities / `host.artifactGrants`, resolved per page.\n *\n * - `mf-artifact` — a co-embedded matterfact artifact (its slug); the token stays on\n * the live iframe / grant, never here.\n * - `mf-document` — a matterfact document (dossier/report), resolved to an MF_DOC_ID\n * host-side per page.\n * - `host-data` — the host's own data; not a matterfact entity.\n */\nexport type ContentClass =\n | { kind: 'mf-artifact'; slug: string }\n | { kind: 'mf-document'; doctype: string }\n | { kind: 'host-data' };\n\n/**\n * One route in the annotated site map: the path pattern + label we derived, plus the\n * host's content classification. `current` marks the route the user is on.\n */\nexport interface SiteMapEntry {\n /** Route pattern or path, e.g. '/app/company/:ticker/dossier'. */\n path: string;\n /** Human label for the route ('Company Dossier'). */\n label?: string;\n /** The host's classification of this route's content, when it annotated it. */\n content?: ContentClass;\n current?: boolean;\n}\n\n/** A co-embedded artifact's read-only capability, for the backend to materialize its\n * data. Backend-only — never rendered. `token` is the artifact's own embed token. */\nexport interface ArtifactGrant {\n id: string;\n owner: string;\n token: string;\n}\n\n/**\n * A DECLARED artifact grant — the `<MatterfactAgent artifacts>` prop (or\n * `window.matterfact.artifacts`). Same wire shape as a grant discovered by scanning\n * co-embedded `<MatterfactArtifact>` iframes, plus an optional `label`; it feeds the\n * SAME `host.artifactGrants` channel. This is how a host makes a board reachable from\n * a route where its iframe ISN'T mounted, without hidden zero-size iframes smuggling\n * the token into the DOM. The token stays in the grant channel, never in message text.\n */\nexport interface DeclaredArtifact {\n slug: string;\n owner: string;\n token: string;\n label?: string;\n}\n\n/**\n * One host-tool lifecycle event, surfaced to the host via `onToolEvent` (and the dev\n * panel) — the host's own telemetry hook. Fired loader-side; a throwing or slow\n * callback here NEVER blocks or breaks the call path.\n *\n * - `advertise` — the merged tool list changed (fired with the new set's names).\n * - `call` — a tool call is about to run (`args` present).\n * - `result` — the call settled (`ok`/`error`/`ms`).\n */\nexport interface ToolEvent {\n phase: 'advertise' | 'call' | 'result';\n name: string;\n toolClass: 'hoist' | 'mf' | 'app';\n args?: unknown;\n ok?: boolean;\n error?: string;\n ms?: number;\n}\n\n/**\n * One embed lifecycle event, surfaced to the host via `onEvent` — the host's single\n * telemetry hook. Fired loader-side (lifecycle) and widget-side (chat); a throwing or\n * slow callback NEVER blocks or breaks the mount/call/auth/run path.\n *\n * - `ready` — the widget connected (protocol handshake done).\n * - `open`/`close` — the corner widget was opened/closed. (Inline has no open event —\n * the host's own panel is the open/close control.)\n * - `navigate` — the agent deeplinked the host to one of its own routes.\n * - `auth` — host-auth passthrough: `required` (widget asked), `granted` (a\n * token was handed over), `failed` (no provider result / the provider threw).\n * - `error` — the widget failed to mount / load.\n * - `chat` — a chat-turn moment. Content-free: phase + opaque chatId only.\n * - `tool` — a host-tool lifecycle event (the `ToolEvent` shape, tagged). Also\n * still delivered untagged to the legacy `onToolEvent` hook for back-compat.\n */\nexport type MatterfactEvent =\n | { type: 'ready' }\n | { type: 'open' }\n | { type: 'close' }\n | { type: 'navigate'; href: string }\n | { type: 'auth'; phase: 'required' | 'granted' | 'failed' }\n | { type: 'error'; message: string }\n | { type: 'chat'; phase: 'message' | 'response-start' | 'response-end'; chatId?: string }\n | ({ type: 'tool' } & ToolEvent);\n\n/**\n * A snapshot of the page as the agent sees it.\n *\n * `yaml` is Playwright's ARIA-snapshot rendering — role, accessible name, state,\n * and a ref on anything interactable:\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - button \"Export CSV\" [ref=e9]\n *\n * NOT raw HTML. A real page is tens of thousands of tokens of div soup, it gives\n * the model no handle to act with, and it is a prompt-injection firehose. The\n * a11y tree is a tenth the size and is the only signal that survives in-page —\n * `getEventListeners()` is DevTools-only, so listener-sniffing (the browser-use\n * approach) cannot see a single React handler on a real customer's app.\n */\nexport interface DomSnapshot {\n yaml: string;\n /** Monotonic. A ref is only valid within the snapshot that minted it. */\n seq: number;\n /** True when the walk hit its node budget and stopped. The agent must be told it is not seeing everything. */\n truncated: boolean;\n}\n\n/**\n * Where the user's attention is RIGHT NOW.\n *\n * This is the difference between an assistant that can read your page and one that\n * knows what you're doing. A full DOM snapshot answers \"what is on this screen\"; this\n * answers \"what are you looking at and working in\" — which is what a colleague\n * leaning over reads first. It is small, so it rides on every turn, where the full\n * snapshot does not.\n *\n * Every field here is a LABEL or a REF, never a value. `selection` is the sharpest\n * intent signal there is (\"this is the thing I'm asking about\"), and for exactly that\n * reason it is also where a user might have highlighted their own email — so it is\n * redacted and honours data-mf-private like everything else.\n */\nexport interface FocusContext {\n /** Text the user has selected. The single strongest \"I'm asking about this\" signal. Redacted. */\n selection?: string;\n /** The control the user is working IN — by label and ref, never its contents. */\n focused?: { ref?: ElementRef; label: string; role: string };\n /** The refs currently in the viewport: the handful of things actually on screen, out of the whole tree. */\n visibleRefs?: ElementRef[];\n /** How far down the page they are, 0–1. A cheap proxy for \"which part am I reading\". */\n scroll?: number;\n}\n\n/** Something the user did. Shaped after PostHog's autocapture — one readable line, not a replay frame. */\nexport interface ActivityEvent {\n seq: number;\n ts: number;\n type: 'nav' | 'click' | 'input' | 'submit' | 'selection' | 'custom';\n /** Human-readable: 'clicked button \"Export CSV\"'. Semantic, not coordinates. */\n summary: string;\n ref?: ElementRef;\n data?: Record<string, unknown>;\n}\n\n/**\n * A tool the HOST page exposes to the agent.\n *\n * Deliberately shaped as a superset of WebMCP (`navigator.modelContext`, W3C\n * WebML CG draft / Chrome origin trial). A customer who adopts WebMCP should be\n * able to hand us their existing tool declarations unchanged.\n */\nexport interface HostTool {\n name: string;\n description: string;\n /** JSON Schema. */\n inputSchema: Record<string, unknown>;\n /**\n * A read-only tool may run without asking. Anything that MUTATES the page\n * requires the user to confirm, every time — see the note on ToolCall.\n */\n readOnly?: boolean;\n /**\n * The tiered confirm policy, set by the host (e.g. `window.matterfact.hoist.actions`):\n * `'required'` ⇒ the widget must show a confirm card and get the user's approval\n * before every call; `'auto'` ⇒ it may call without asking. Absent for a tool that\n * predates this policy (treat as `'required'` — the safer default).\n */\n confirm?: 'auto' | 'required';\n}\n\nexport type HostToWidget =\n | { type: 'host.ready'; protocol: number; origin: string }\n | { type: 'host.context'; context: PageContext }\n | { type: 'host.focus'; focus: FocusContext }\n | { type: 'host.snapshot'; snapshot: DomSnapshot }\n | { type: 'host.region'; ref: ElementRef; yaml: string }\n | { type: 'host.activity'; events: ActivityEvent[] }\n | { type: 'host.artifactGrants'; grants: ArtifactGrant[] }\n /**\n * The annotated site map — the app's routes with the host's content\n * classification. Sent on mount and re-sent on navigation (a virtualized SPA can\n * change what's routable). Distinct from the per-page `host.context`: this is the\n * whole app's structure, so the agent can reason about and navigate toward MF\n * content the user isn't currently looking at.\n */\n | { type: 'host.sitemap'; sitemap: SiteMapEntry[] }\n | { type: 'host.tools'; tools: HostTool[] }\n | {\n type: 'host.toolResult';\n callId: string;\n ok: boolean;\n result?: unknown;\n error?: string;\n }\n | { type: 'host.auth'; token: string; expiresAt: number }\n | { type: 'host.theme'; mode: 'light' | 'dark' }\n /**\n * Where the widget currently IS. Sent on mount and after anything that moves it\n * (drag, snap, mode change, viewport resize).\n *\n * The widget cannot work this out for itself — it can't see the viewport, and the\n * loader owns the box. Without it the widget renders its launcher against a stale\n * guess: a launcher dragged to the left edge kept drawing its circle bottom-RIGHT\n * inside a left-anchored box, so the circle jumped as soon as the box grew for the\n * hover pill. `growth` is the direction the pill/menu/panel must open (toward the\n * viewport centre); `mode` decides whether the launcher is a circle or an edge tab.\n */\n | {\n type: 'host.geometry';\n mode: 'float' | 'dock';\n dockSide: 'left' | 'right';\n growth: 'tl' | 'tr' | 'bl' | 'br';\n };\n\n/* ──────────────────────────── widget → host ───────────────────────────── */\n\n/**\n * The agent asking the host to do something.\n *\n * THE SECURITY MODEL, stated once: the page's content is UNTRUSTED. Text on the\n * page can try to instruct the agent, and the moment the agent can act, that stops\n * being a bad answer and becomes a bad ACTION. So:\n *\n * - v1 is READ-ONLY. `snapshot` and `activity` flow; no tool mutates the page.\n * - A tool that is not `readOnly` must be confirmed by the USER, every call. Not\n * \"unless the host opts out\" — every call. The trigger may have been written by\n * the page.\n * - The host is the enforcement point, not the widget. The widget can be lied to;\n * the loader runs in the page and decides what actually happens.\n */\nexport interface ToolCall {\n callId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\nexport type WidgetToHost =\n | { type: 'widget.ready'; protocol: number }\n /**\n * Ask for the FULL page snapshot. This is the agent PULLING detail, not us pushing\n * it: the focus context rides on every turn, but the whole tree is fetched only\n * when the agent decides it needs to look — cheaper, and it reads what's relevant\n * to the question instead of drowning in the footer nav every turn.\n */\n | { type: 'widget.requestSnapshot' }\n /**\n * Pull the DECLARED page context fresh, right now. The host answers with `host.context`.\n *\n * Declared context (`window.matterfact.context`, or a `getPageContext()` callback) is\n * otherwise only published on load and on URL navigation, so in a virtualized SPA it goes\n * stale on any non-navigation state change (a team switch, a filter edit, a selection).\n * The widget pulls it at turn-assembly time — symmetric with `widget.requestSnapshot` —\n * so every turn carries the current context, not the context as of the last route change.\n */\n | { type: 'widget.requestContext' }\n /** Zoom in: the a11y sub-tree under one ref (a table, a form, a card the agent cares about). */\n | { type: 'widget.readRegion'; ref: ElementRef }\n | { type: 'widget.callTool'; call: ToolCall }\n /** Chat opened/closed — the loader resizes the iframe and starts/stops observing. */\n | { type: 'widget.setOpen'; open: boolean }\n | { type: 'widget.resize'; height: number }\n /**\n * Dock / undock the open panel.\n *\n * Docked is a FULL-HEIGHT SIDE PANEL on the launcher's own side — left corners dock\n * to the left edge, right corners to the right, unless `setDockSide` overrides it.\n * This replaces the old `setExpanded`, which was hardcoded to the right edge and so\n * threw the panel across the screen whenever the launcher sat on the left.\n *\n * The loader owns the box, so only it can do this — `widget.resize` (height-only)\n * can neither widen the panel nor move it to an edge.\n */\n | { type: 'widget.setMode'; mode: 'float' | 'dock' }\n /** Which edge the tab and its panel live on. */\n | { type: 'widget.setDockSide'; side: 'left' | 'right' }\n /** Place the FLOATING launcher at a specific corner (the menu's snap picker). */\n | { type: 'widget.snapCorner'; corner: 'tl' | 'tr' | 'bl' | 'br' }\n /**\n * Resize the COLLAPSED launcher's host box so the widget can paint outside the 56px\n * circle — the hover pill (`{w:180,h:56}`) or the context menu (its own box). The\n * iframe clips to the host box, so anything beside the circle is invisible until the\n * host makes room. `{w:56,h:56}` returns to the bare circle. Ignored while open.\n */\n | { type: 'widget.setLauncherRegion'; w: number; h: number }\n /**\n * User resize of the floating panel, via the grip on its inner corner.\n *\n * Same contract as the launcher drag below, and for the same reason: the press is\n * captured by the iframe, so the host cannot see the moves. The widget tracks the\n * gesture and sends SCREEN-coordinate deltas; the loader owns the sizing, the\n * per-corner sign of the delta, and the clamp.\n */\n | { type: 'widget.resizeStart' }\n | { type: 'widget.resizeMove'; dx: number; dy: number }\n | { type: 'widget.resizeEnd' }\n /**\n * Launcher drag. The widget tracks the gesture; the host only moves the element.\n *\n * It has to be this way round, and the reason is easy to get wrong: a press that starts\n * inside an iframe is implicitly captured by that iframe, so every pointermove and the\n * pointerup belong to the widget's document until the button comes up. The host cannot\n * see them at all — not even through an overlay of its own, because capture beats hit\n * testing. So the host cannot take over a drag mid-gesture; it can only be told.\n *\n * `dx`/`dy` are deltas in SCREEN coordinates, which is the other half of the trick:\n * client coordinates are measured against the iframe's own viewport, and the iframe is\n * being moved under the cursor as the drag proceeds — so the pointer would appear to\n * stop moving and the launcher would stall after one step. Screen coordinates are\n * absolute and immune to that feedback loop.\n */\n | { type: 'widget.dragStart' }\n | { type: 'widget.dragMove'; dx: number; dy: number }\n | { type: 'widget.dragEnd' }\n /** Put the launcher back in the default corner and forget the saved size/dock. */\n | { type: 'widget.resetPos' }\n /** Get out of the way until the page reloads (a menu action, not a setting). */\n | { type: 'widget.hide' }\n /** The widget has no session; the host must run the hosted-login popup. */\n | { type: 'widget.needsAuth' }\n /**\n * Deeplink the host to one of its OWN routes — the \"open on page\" control on a\n * co-embedded document's side-panel viewer. The widget is a cross-origin iframe and\n * can't navigate the top window itself, so it asks the loader, which resolves the\n * href against the host location and refuses anything off the host's own origin.\n */\n | { type: 'widget.navigate'; href: string }\n /**\n * A chat-turn lifecycle moment, forwarded by the loader to the host's `onEvent`.\n * Content-free: `phase` + an opaque `chatId`, never message text. Additive.\n */\n | {\n type: 'widget.chat';\n phase: 'message' | 'response-start' | 'response-end';\n chatId?: string;\n };\n\n/* ───────────────────────────── envelope ───────────────────────────────── */\n\n/**\n * Everything on the wire is wrapped.\n *\n * `channel` keeps us out of the host page's own postMessage traffic (and out of\n * every other widget's). The receiver ALSO checks `event.origin` against an\n * allowlist and `event.source` against the expected window, on every single\n * message — a namespace is not a security boundary, it is a politeness.\n */\nexport interface Envelope<T> {\n channel: typeof CHANNEL;\n protocol: number;\n /** Correlates a response to its request; absent for notifications. */\n id?: string;\n payload: T;\n}\n\nexport function envelope<T>(payload: T, id?: string): Envelope<T> {\n return {\n channel: CHANNEL,\n protocol: PROTOCOL_VERSION,\n ...(id ? { id } : {}),\n payload,\n };\n}\n\nexport function isEnvelope(data: unknown): data is Envelope<unknown> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { channel?: unknown }).channel === CHANNEL\n );\n}\n","/**\n * Pure geometry for the embed launcher/panel.\n *\n * No DOM, no React — every function here is a total map from numbers/strings to\n * numbers/strings. That is deliberate: the loader attaches a CLOSED shadow root, so\n * the iframe inside it is unreachable from a test. Keeping the whole positioning\n * model in pure functions is what makes it verifiable at all; `loader.ts` is then a\n * thin applier that sets the returned box on the light-DOM host element.\n *\n * There are two MODES, and the mode decides both how the widget rests and how it opens:\n *\n * dock (default) — the launcher is a TAB flush against a side edge, and opening\n * gives a full-height side panel on that edge. This is the shape\n * most hosts want: it reads as part of the app, not as a bubble\n * floating over it.\n * float — the launcher is a CIRCLE the user can put anywhere, and opening\n * gives a panel anchored near it.\n *\n * In float the position is FREE. A corner is only recorded when the user drops the\n * launcher near one (see `snapOrFree`), because a snap that always fires isn't a\n * convenience, it's a constraint — you could never place the thing mid-edge. Recording\n * the corner when it IS snapped is what lets it stay in that corner across a viewport\n * resize, where a raw x/y would drift.\n */\n\nexport type Corner = 'tl' | 'tr' | 'bl' | 'br';\nexport type DockSide = 'left' | 'right';\nexport type Mode = 'float' | 'dock';\n\nexport interface EmbedGeometry {\n mode: Mode;\n /** float: the corner it snapped to, or null when freely placed. */\n corner: Corner | null;\n /** float: free launcher top-left, used only when `corner` is null. */\n x: number;\n y: number;\n floatW: number;\n floatH: number;\n dockSide: DockSide;\n /** dock: the tab's top offset along its edge. */\n tabY: number;\n dockW: number;\n}\n\n/**\n * A set of fixed-position box properties to apply to the host `<div>`.\n * Exactly two of top/right/bottom/left carry a px value; the other two are 'auto',\n * so the box stays pinned to the edges it grows away from.\n */\nexport interface BoxStyle {\n top: string;\n right: string;\n bottom: string;\n left: string;\n width: string;\n height: string;\n}\n\nexport const MARGIN = 20;\nexport const LAUNCHER = 56;\nexport const PILL_W = 180;\n/** How close to a corner a drop must land before it snaps. Generous enough to feel\n * magnetic, small enough that the middle of an edge is still reachable. */\nexport const SNAP_RADIUS = 96;\n/**\n * The docked launcher tab.\n *\n * Wide enough to carry the logo mark, and clearly TALLER than it is wide so the shape\n * still reads as a tab on the page edge. The ratio is the thing that matters: at a\n * near-square size any inner radius rounds it into a lozenge, which is what \"squished\n * circle\" looks like.\n */\nexport const TAB_W = 44;\nexport const TAB_H = 132;\n/**\n * How close to a SIDE edge a drop must land to become a docked tab. Dragging the tab\n * away from the edge is therefore how you float it, and dragging the circle back to an\n * edge is how you dock it — the placement follows where you put the thing, so there is\n * no mode switch to go hunting for.\n */\nexport const EDGE_DOCK = 64;\nexport const DEFAULT_FLOAT_W = 420;\nexport const DEFAULT_FLOAT_H = 640;\nexport const MIN_FLOAT_W = 320;\nexport const MIN_FLOAT_H = 420;\nexport const DEFAULT_DOCK_W = 600;\nexport const MIN_DOCK_W = 320;\n\nconst CORNERS: readonly Corner[] = ['tl', 'tr', 'bl', 'br'];\n\nexport function defaultGeometry(): EmbedGeometry {\n return {\n // Dock is the default: a side panel reads as part of the host app.\n mode: 'dock',\n corner: 'br',\n x: 0,\n y: 0,\n floatW: DEFAULT_FLOAT_W,\n floatH: DEFAULT_FLOAT_H,\n dockSide: 'right',\n tabY: 0, // 0 => centre it (see tabTop)\n dockW: DEFAULT_DOCK_W,\n };\n}\n\nfunction clamp(n: number, lo: number, hi: number): number {\n return Math.min(Math.max(n, lo), hi);\n}\n\n/** Where a snapped corner puts the launcher's top-left. */\nfunction cornerOrigin(\n corner: Corner,\n w: number,\n h: number,\n vw: number,\n vh: number,\n): { x: number; y: number } {\n return {\n x: corner[1] === 'l' ? MARGIN : vw - MARGIN - w,\n y: corner[0] === 't' ? MARGIN : vh - MARGIN - h,\n };\n}\n\n/** The launcher's top-left in float mode: its snapped corner, else its free spot. */\nexport function launcherOrigin(\n g: EmbedGeometry,\n vw: number,\n vh: number,\n): { x: number; y: number } {\n if (g.corner) return cornerOrigin(g.corner, LAUNCHER, LAUNCHER, vw, vh);\n return {\n x: clamp(g.x, MARGIN, Math.max(MARGIN, vw - MARGIN - LAUNCHER)),\n y: clamp(g.y, MARGIN, Math.max(MARGIN, vh - MARGIN - LAUNCHER)),\n };\n}\n\n/**\n * Which way things grow from the launcher: toward the viewport centre.\n *\n * Distinct from `geometry.corner` on purpose — a FREELY placed launcher has no corner,\n * but its pill, menu and panel still have to open inward or they'd run off the page.\n */\nexport function growthCorner(g: EmbedGeometry, vw: number, vh: number): Corner {\n if (g.corner) return g.corner;\n const o = launcherOrigin(g, vw, vh);\n return nearestCorner(o.x + LAUNCHER / 2, o.y + LAUNCHER / 2, vw, vh);\n}\n\n/** Which quadrant a point is in. */\nexport function nearestCorner(\n cx: number,\n cy: number,\n vw: number,\n vh: number,\n): Corner {\n return `${cy < vh / 2 ? 't' : 'b'}${cx < vw / 2 ? 'l' : 'r'}` as Corner;\n}\n\n/**\n * Resolve a drop: snap to a corner only if it landed NEAR one, else keep it where the\n * user put it (clamped on-screen). Returns the fields to merge into the geometry.\n */\nexport function snapOrFree(\n x: number,\n y: number,\n vw: number,\n vh: number,\n): { corner: Corner | null; x: number; y: number } {\n const cx = clamp(x, MARGIN, Math.max(MARGIN, vw - MARGIN - LAUNCHER));\n const cy = clamp(y, MARGIN, Math.max(MARGIN, vh - MARGIN - LAUNCHER));\n for (const corner of CORNERS) {\n const o = cornerOrigin(corner, LAUNCHER, LAUNCHER, vw, vh);\n if (Math.hypot(cx - o.x, cy - o.y) <= SNAP_RADIUS) {\n return { corner, x: cx, y: cy };\n }\n }\n return { corner: null, x: cx, y: cy };\n}\n\n/** Is this box close enough to a side edge to be docked? The live half of the drag. */\nexport function edgeDock(x: number, w: number, vw: number): DockSide | null {\n if (x <= EDGE_DOCK) return 'left';\n if (x + w >= vw - EDGE_DOCK) return 'right';\n return null;\n}\n\n/**\n * The point a drag MOVES — the widget's logical anchor, not its painted box.\n *\n * They differ once the panel is open: the box is the whole panel, but what the geometry\n * stores (and what a corner drop resolves) is the launcher's own origin. Dragging by the\n * box's top-left would shift the widget by the panel's size the moment you grabbed it.\n */\nexport function dragAnchor(\n g: EmbedGeometry,\n vw: number,\n vh: number,\n): { x: number; y: number } {\n if (g.mode === 'dock') {\n return { x: g.dockSide === 'left' ? 0 : vw - TAB_W, y: tabTop(g, vh) };\n }\n return launcherOrigin(g, vw, vh);\n}\n\n/**\n * The widget's painted horizontal extent for the state it is in.\n *\n * Derived, not measured: `getBoundingClientRect` is unavailable before layout (and is\n * all-zeros under jsdom), and the loader already knows every input. This is what the\n * edge test reads — \"dragged to the side\" is about the box you can see touching the\n * edge, which for an open panel is nowhere near its anchor.\n */\nexport function visibleBox(\n g: EmbedGeometry,\n open: boolean,\n vw: number,\n vh: number,\n): { x: number; w: number } {\n if (g.mode === 'dock') {\n const w = open\n ? Math.min(Math.max(g.dockW, MIN_DOCK_W), Math.max(0, vw - 2 * MARGIN))\n : TAB_W;\n return { x: g.dockSide === 'left' ? 0 : vw - w, w };\n }\n const o = launcherOrigin(g, vw, vh);\n if (!open) return { x: o.x, w: LAUNCHER };\n const { w } = clampSize(g.floatW, g.floatH, vw, vh, MIN_FLOAT_W, MIN_FLOAT_H);\n // A right-growing panel hangs LEFT off the launcher, so its left edge is the\n // launcher's right edge minus the panel width.\n return {\n x: growthCorner(g, vw, vh)[1] === 'r' ? o.x + LAUNCHER - w : o.x,\n w,\n };\n}\n\n/**\n * Resolve a drop into a PLACEMENT — which mode the widget lands in, and where.\n *\n * Two different measurements, deliberately:\n * - the EDGE test uses the widget's visible box, because \"dragged to the side\" is\n * about what you can see touching the edge. Testing the anchor instead means a\n * 420px-wide panel whose right edge is already against the screen refuses to dock,\n * since its anchor is still 400px away.\n * - the CORNER test uses the anchor, because that is what a corner placement stores.\n *\n * Priority matters, and corner beats edge on purpose: every corner is also within reach\n * of a side edge, so checking the edge first would make corner-snapping unreachable and\n * quietly turn the floating circle into a tab whenever you aimed for a corner.\n */\nexport function placeDrop(\n anchorX: number,\n anchorY: number,\n boxLeft: number,\n boxW: number,\n vw: number,\n vh: number,\n):\n | { mode: 'float'; corner: Corner | null; x: number; y: number }\n | { mode: 'dock'; dockSide: DockSide; tabY: number } {\n const snapped = snapOrFree(anchorX, anchorY, vw, vh);\n if (snapped.corner) return { mode: 'float', ...snapped };\n const side = edgeDock(boxLeft, boxW, vw);\n if (side) {\n return {\n mode: 'dock',\n dockSide: side,\n tabY: clamp(anchorY, 0, Math.max(0, vh - TAB_H)),\n };\n }\n return { mode: 'float', ...snapped };\n}\n\nexport function dockSideForCorner(corner: Corner): DockSide {\n return corner[1] === 'l' ? 'left' : 'right';\n}\n\nexport function effectiveDockSide(g: EmbedGeometry): DockSide {\n return g.dockSide;\n}\n\n/**\n * Fit a size inside the viewport.\n *\n * Order matters: the minimum is applied FIRST and the viewport cap LAST, so on a\n * viewport smaller than the minimum the VIEWPORT wins. That is the whole point — a\n * panel that honoured its minimum past the viewport edge would hang off the page.\n */\nexport function clampSize(\n w: number,\n h: number,\n vw: number,\n vh: number,\n minW: number,\n minH: number,\n): { w: number; h: number } {\n return {\n w: Math.min(Math.max(w, minW), Math.max(0, vw - 2 * MARGIN)),\n h: Math.min(Math.max(h, minH), Math.max(0, vh - 2 * MARGIN)),\n };\n}\n\n/**\n * Apply a resize drag to the float size. The grip sits on the panel's INNER corner\n * (the one facing viewport centre), so dragging it away from the anchored corner\n * grows the panel — which flips the sign of the delta per corner. Unclamped.\n */\nexport function applyResizeDelta(\n corner: Corner,\n startW: number,\n startH: number,\n dx: number,\n dy: number,\n): { w: number; h: number } {\n const wSign = corner[1] === 'r' ? -1 : 1; // right-anchored grows on -dx\n const hSign = corner[0] === 'b' ? -1 : 1; // bottom-anchored grows on -dy\n return { w: startW + wSign * dx, h: startH + hSign * dy };\n}\n\n/** Widen/narrow a docked panel by dragging its inner edge. */\nexport function applyDockResizeDelta(\n side: DockSide,\n startW: number,\n dx: number,\n): number {\n return side === 'right' ? startW - dx : startW + dx;\n}\n\nexport function parseGeometry(raw: string | null): EmbedGeometry | null {\n if (!raw) return null;\n try {\n const p = JSON.parse(raw) as Partial<EmbedGeometry>;\n // Pre-mode values (and the even older {right,bottom}) are dropped rather than\n // guessed at — there is no honest mapping from them onto this model.\n if (!p || (p.mode !== 'float' && p.mode !== 'dock')) return null;\n const d = defaultGeometry();\n const num = (v: unknown, dv: number) => (typeof v === 'number' ? v : dv);\n return {\n mode: p.mode,\n corner: CORNERS.includes(p.corner as Corner)\n ? (p.corner as Corner)\n : null,\n x: num(p.x, d.x),\n y: num(p.y, d.y),\n floatW: num(p.floatW, d.floatW),\n floatH: num(p.floatH, d.floatH),\n dockSide: p.dockSide === 'left' ? 'left' : 'right',\n tabY: num(p.tabY, d.tabY),\n dockW: num(p.dockW, d.dockW),\n };\n } catch {\n return null;\n }\n}\n\nexport function serializeGeometry(g: EmbedGeometry): string {\n return JSON.stringify(g);\n}\n\n/* ─────────────────────────── box builders ─────────────────────────────── */\n\nconst px = (n: number) => `${n}px`;\n\n/**\n * Pin the box by the two edges nearest the growth corner, so it grows inward.\n * Works for a snapped launcher and a freely-placed one alike: the anchor is always\n * the launcher's own top-left plus its size, expressed from whichever edges it grows\n * away from.\n */\nfunction boxAt(\n ox: number,\n oy: number,\n w: number,\n h: number,\n corner: Corner,\n vw: number,\n vh: number,\n): BoxStyle {\n const right = corner[1] === 'r';\n const bottom = corner[0] === 'b';\n // The anchored edges are measured from the LAUNCHER's own far side, so the launcher\n // stays put while the box grows past it...\n const rawX = right ? vw - (ox + LAUNCHER) : ox;\n const rawY = bottom ? vh - (oy + LAUNCHER) : oy;\n // ...but only as far as the viewport allows. Clamping the SIZE is not enough: a\n // launcher parked mid-page opens a 640px panel that grows straight off the top, and\n // the panel's header — the only way to close, dock or drag it — goes with it. So the\n // pinned offset is clamped too, which shifts the panel back into view while keeping\n // it as close to the launcher as it can be.\n const x = clamp(rawX, MARGIN, Math.max(MARGIN, vw - MARGIN - w));\n const y = clamp(rawY, MARGIN, Math.max(MARGIN, vh - MARGIN - h));\n return {\n top: bottom ? 'auto' : px(y),\n bottom: bottom ? px(y) : 'auto',\n left: right ? 'auto' : px(x),\n right: right ? px(x) : 'auto',\n width: px(w),\n height: px(h),\n };\n}\n\n/** The tab's top offset; a stored 0 means \"centre it\". */\nfunction tabTop(g: EmbedGeometry, vh: number): number {\n const max = Math.max(0, vh - TAB_H);\n return clamp(g.tabY || Math.round((vh - TAB_H) / 2), 0, max);\n}\n\n/** The docked launcher: a slim tab flush against its edge (no margin — it hugs). */\nexport function tabBox(g: EmbedGeometry, vw: number, vh: number): BoxStyle {\n const left = g.dockSide === 'left';\n return {\n top: px(tabTop(g, vh)),\n bottom: 'auto',\n left: left ? '0px' : 'auto',\n right: left ? 'auto' : '0px',\n width: px(TAB_W),\n height: px(TAB_H),\n };\n}\n\n/**\n * ANY float-mode box — the circle, the hover pill, the menu region, the open panel.\n *\n * They are all the same shape: a box of size w×h anchored at the launcher and growing\n * inward. One function rather than four wrappers, because this module is bundled into\n * the per-page loader stub and four near-identical bodies is pure weight.\n */\nexport function floatChrome(\n g: EmbedGeometry,\n w: number,\n h: number,\n vw: number,\n vh: number,\n /**\n * Override the growth direction. Used to FREEZE it for the length of a drag: growth\n * is derived from which half of the viewport the launcher is in, so dragging an open\n * panel across the middle would otherwise flip the side it grows from and jump the\n * panel by its own width. Held still, it tracks the cursor.\n */\n growth?: Corner,\n): BoxStyle {\n const o = launcherOrigin(g, vw, vh);\n return boxAt(o.x, o.y, w, h, growth ?? growthCorner(g, vw, vh), vw, vh);\n}\n\n/** The region the docked tab grows into for its context menu — hugging its edge. */\nexport function dockChrome(\n g: EmbedGeometry,\n w: number,\n h: number,\n vw: number,\n vh: number,\n): BoxStyle {\n const left = g.dockSide === 'left';\n return {\n top: px(tabTop(g, vh)),\n bottom: 'auto',\n left: left ? '0px' : 'auto',\n right: left ? 'auto' : '0px',\n width: px(w),\n height: px(h),\n };\n}\n\n/** The collapsed launcher for the current mode: dock → tab, float → circle. */\nexport function launcherBox(\n g: EmbedGeometry,\n vw: number,\n vh: number,\n): BoxStyle {\n return g.mode === 'dock'\n ? tabBox(g, vw, vh)\n : floatChrome(g, LAUNCHER, LAUNCHER, vw, vh);\n}\n\n/** The floating open panel, anchored at the launcher and clamped on-screen. */\nexport function floatBox(\n g: EmbedGeometry,\n vw: number,\n vh: number,\n growth?: Corner,\n): BoxStyle {\n const f = clampSize(g.floatW, g.floatH, vw, vh, MIN_FLOAT_W, MIN_FLOAT_H);\n return floatChrome(g, f.w, f.h, vw, vh, growth);\n}\n\n/** Full-height side panel flush against its edge. */\nexport function dockBox(g: EmbedGeometry, vw: number, _vh: number): BoxStyle {\n const w = Math.min(\n Math.max(g.dockW, MIN_DOCK_W),\n Math.max(0, vw - 2 * MARGIN),\n );\n const left = g.dockSide === 'left';\n return {\n top: '0px',\n bottom: '0px',\n height: 'auto',\n left: left ? '0px' : 'auto',\n right: left ? 'auto' : '0px',\n width: px(w),\n };\n}\n","import {\n CHANNEL,\n PROTOCOL_VERSION,\n envelope,\n isEnvelope,\n type HostToWidget,\n type MatterfactEvent,\n type WidgetToHost,\n} from './protocol';\n// Type-only: erased at build, so it does NOT pull the lazy ./context chunk eagerly.\nimport type { PageContextProvider } from './context';\nimport {\n applyDockResizeDelta,\n applyResizeDelta,\n clampSize,\n defaultGeometry,\n dockBox,\n floatBox,\n growthCorner,\n tabBox,\n dockChrome,\n floatChrome,\n parseGeometry,\n serializeGeometry,\n dragAnchor,\n visibleBox,\n edgeDock,\n placeDrop,\n LAUNCHER,\n MARGIN,\n MIN_DOCK_W,\n MIN_FLOAT_H,\n MIN_FLOAT_W,\n DEFAULT_DOCK_W,\n type BoxStyle,\n type Corner,\n type EmbedGeometry,\n} from './geometry';\n\n/**\n * The matterfact embed loader.\n *\n * <script src=\"https://cdn.matterfact.com/embed.js\"\n * data-key=\"pk_live_acme_...\"\n * defer></script>\n *\n * This file runs on EVERY page load of a customer's site, so it is deliberately\n * tiny and deliberately dumb:\n *\n * - zero dependencies\n * - it does NOT read the DOM. The snapshot/activity code is a separate chunk,\n * fetched only when the user actually opens the chat. A customer should pay\n * nothing for a widget nobody clicked.\n * - it does NOT bundle React, or a CSS framework, or an RPC library.\n *\n * `iframe-resizer` is the thing you will be tempted to reach for here. It is\n * GPL-3.0 and cannot ship in this file. The ResizeObserver bridge below is the\n * fifteen lines it would have cost you anyway.\n */\n\n/** Returns a token this matterfact deployment's auth provider trusts (Firebase idToken,\n * Entra token, …). May be async; return null when there's no signed-in user. */\nexport type AuthTokenProvider = () => string | null | Promise<string | null>;\n\nexport interface LoaderConfig {\n publishableKey: string;\n /** Origin of the widget. Overridable for dev/self-hosted; defaults to production. */\n origin: string;\n theme: 'light' | 'dark' | 'auto';\n /** Optional label identifying THIS embedding, when one app embeds the agent in more\n * than one place (e.g. \"orders\" vs \"support\"). Stamped on runs/threads so usage and\n * history can be told apart per surface. Free-form; the app_id (from the session)\n * is the trusted half. */\n surface: string;\n /**\n * OPTIONAL host-auth passthrough, for TRUSTED first-party embeds (the admin portal,\n * EMC). When set, the host page already holds a token this deployment's auth provider\n * trusts (its Firebase idToken, an Entra token, …); the loader hands it to the widget\n * on `widget.needsAuth` instead of opening a sign-in popup. The backend still verifies\n * the token, so identity can't be forged — this only skips a redundant second sign-in.\n * Called on demand (so tokens can refresh). Absent ⇒ the popup/inline sign-in flow.\n * The `<script>` loader has no config here; it reads window.matterfact.getEmbedAuthToken\n * instead (see provideAuth).\n */\n authTokenProvider?: AuthTokenProvider;\n /**\n * OPTIONAL pull callback for DECLARED page context, for a host whose context changes\n * without a URL navigation (a virtualized SPA: team switch, filter edit, selection). The\n * widget calls it at turn-assembly time (via `widget.requestContext`), so every turn\n * carries current context instead of context as of the last route change. Symmetric with\n * `authTokenProvider`. The `<script>` loader has no config here; it reads\n * `window.matterfact.getPageContext` instead (see resolveDeclaredContext in context.ts).\n * Absent ⇒ falls back to the static `window.matterfact.context`.\n */\n pageContextProvider?: PageContextProvider;\n /**\n * Render INTO this element instead of floating in the corner — for a host that has its\n * own side panel, tool drawer or tab and wants the agent to live there.\n *\n * This inverts who owns the chrome. In corner mode the widget owns everything: it draws\n * its own launcher and it tells us how big to be (setOpen/setDocked/resize). Inside\n * someone else's panel, both are theirs — a widget that resized its host's drawer, or\n * drew a second floating bubble inside it, is just broken. So here we fill the\n * container, ignore the size messages, and the widget skips the launcher and renders\n * the chat directly.\n *\n * The host also owns visibility: showing and hiding their own panel IS the open/close\n * control, so there is nothing for us to add.\n */\n container?: HTMLElement | null;\n /**\n * Turn off ALL host-page observation — no `host.context`, no `host.focus`, no\n * `host.snapshot`, no `host.activity`, no `host.artifactGrants`. Not a filter on what\n * gets sent: when this is false the loader never installs the DOM/nav/focus/activity\n * observers in the first place, and an inbound `widget.requestSnapshot` is ignored\n * rather than answered. Default `true` — seeing the page is the widget's whole value\n * proposition; this is the escape hatch for a host that wants agent chat with nothing\n * about the page ever reaching it.\n */\n pageContext?: boolean;\n /**\n * Force dev mode (see `devRequested()` below) without needing `?mfdev=1` on the host\n * URL. This is the programmatic equivalent of that trigger, not a replacement for it —\n * the URL param still works untouched; `mount()` ORs the two together.\n */\n dev?: boolean;\n}\n\nconst DEFAULT_ORIGIN = 'https://app.matterfact.com';\n\n/**\n * Has someone asked to see what the widget is doing? `?mfdev=1` on the HOST page.\n *\n * Driven by the host's own URL rather than a `data-` attribute on purpose: an engineer\n * debugging a page they didn't write can add a query param, but they cannot redeploy the\n * customer's site to change a script tag. It's also ephemeral — it lasts exactly as long\n * as that URL, so nobody can leave it on by accident.\n *\n * This only surfaces what the widget already collects FROM THE PAGE IT'S ON, to the\n * person whose page it is. It grants no access: the session, the origin allowlist and\n * the route scope are all enforced server-side and none of them consult this.\n */\nfunction devRequested(): boolean {\n try {\n return new URLSearchParams(location.search).get('mfdev') === '1';\n } catch {\n return false;\n }\n}\n\nfunction readConfig(): LoaderConfig | null {\n // `document.currentScript` is null inside a module or after async execution, so\n // fall back to finding our own tag by src.\n const el =\n (document.currentScript as HTMLScriptElement | null) ??\n document.querySelector<HTMLScriptElement>('script[data-key][src*=\"embed\"]');\n\n const publishableKey = el?.dataset.key;\n if (!publishableKey) {\n console.error('[matterfact] missing data-key on the embed script tag');\n return null;\n }\n // `data-container=\"#panel\"` renders into the host's own element instead of the\n // corner. A selector rather than an element, because a script tag can't hand us a\n // reference — and if it doesn't resolve we fall back to the corner rather than\n // vanish: a widget nobody can find looks identical to a broken install.\n const sel = el?.dataset.container;\n const container = sel ? document.querySelector<HTMLElement>(sel) : null;\n if (sel && !container) {\n console.error(\n `[matterfact] data-container=\"${sel}\" matched nothing; falling back to the corner`,\n );\n }\n\n // `data-page-context=\"off\"` (also \"false\" / \"0\") disables all page observation.\n // Anything else — including the attribute being absent — leaves it on. Lowercased\n // once before comparing: a privacy toggle that silently stays ON for \"Off\" or\n // \"FALSE\" (a customer's templating/CMS can easily produce either, unintentionally)\n // is exactly the wrong direction for this to fail in.\n const pageContextAttr = el?.dataset.pageContext?.toLowerCase();\n\n return {\n publishableKey,\n origin: el?.dataset.origin || DEFAULT_ORIGIN,\n theme: (el?.dataset.theme as LoaderConfig['theme']) || 'auto',\n surface: el?.dataset.surface || '',\n container,\n pageContext:\n pageContextAttr !== 'off' &&\n pageContextAttr !== 'false' &&\n pageContextAttr !== '0',\n // No `data-dev` — see the `dev` field's doc comment: the URL trigger is the\n // point for the script-tag path, so there is deliberately no script-tag knob here.\n // No `data-actions` either: the action policy lives entirely in the lazy chunk,\n // read straight off `window.matterfact.hoist.actions` by hoist-runtime.ts's\n // readActionsConfig() — see LoaderConfig's class doc and MatterfactAgentProps.actions\n // (react.tsx) for the one remaining way to SET that global programmatically.\n };\n}\n\nconst POS_KEY = 'mf.embed.pos';\n\nclass EmbedHost {\n private iframe: HTMLIFrameElement | null = null;\n private shadow: ShadowRoot | null = null;\n /** Buffered until the widget says it's listening — postMessage before load is dropped silently. */\n private queue: HostToWidget[] = [];\n private ready = false;\n private open = false;\n /** The persisted box: launcher corner, float size, dock state/side/width. */\n private geo: EmbedGeometry = defaultGeometry();\n /** Float size at resizeStart; resizeMove deltas apply against it (they're cumulative). */\n private resizeBase: { w: number; h: number } | null = null;\n /** Docked width at resizeStart — the docked panel resizes in one axis only. */\n private dockBase = DEFAULT_DOCK_W;\n /** The widget's logical anchor when the drag began, and where it is now. Deltas arrive\n * cumulative from the press, so the current spot is simply origin + delta — no need to\n * read the box back, which stops being the thing we're moving the moment it docks. */\n private dragFrom: { x: number; y: number } | null = null;\n private dragAt = { x: 0, y: 0 };\n /** The painted box when the drag began — the edge test measures what you can SEE\n * touching the screen edge, which is not the anchor once the panel is open. */\n private dragBox = { x: 0, w: 0 };\n /** Growth direction frozen for the drag — see floatChrome's `growth` param. */\n private dragGrowth: Corner | null = null;\n /**\n * Has this drag been clear of the dock band yet?\n *\n * The resting position is INSIDE the band — a corner-anchored widget sits MARGIN\n * (20px) from the edge, well within EDGE_DOCK (64px) — so without this, picking one\n * up docked it instantly, before it had moved anywhere. Docking now requires\n * ENTERING the band rather than merely starting in it.\n */\n private dragLeftBand = false;\n /** Loaded on first open. Holds everything that touches the customer's DOM. */\n private context: Promise<typeof import('./context')> | null = null;\n /** The host element; kept so `destroy()` can remove it (React lifecycle). */\n private hostEl: HTMLDivElement | null = null;\n /** Rendering into the host's own element: they own the box, the chrome and visibility. */\n private readonly inline: boolean;\n /** Host-auth storm guard (see provideAuth). Counts getAuthToken calls; past a cap we stop\n * calling the provider, rather than joining the storm. This host instance OUTLIVES iframe\n * reloads, so — unlike anything in the widget — the counter survives the very reload loop\n * that drives the storm. (Kept tiny on purpose: this file has a hard per-page size budget;\n * the widget side carries the windowed/retry-after-settle half.) Terse name = fewer bytes\n * in the stub; it is the host-auth request count. */\n private ac = 0;\n\n constructor(private config: LoaderConfig) {\n this.inline = !!config.container;\n }\n\n mount() {\n // A CLOSED shadow root, on a container that resets every inherited property.\n //\n // We are a guest on someone else's page. Their CSS must not reach into us, our\n // CSS must not leak out, and their JS should not be able to walk into our tree\n // by accident (closed mode: `host.shadowRoot` is null). `contain` stops our\n // layout/paint from invalidating theirs.\n const host = document.createElement('div');\n this.hostEl = host;\n host.id = 'matterfact-embed';\n\n if (this.inline) {\n // The container's box IS the widget's box. No fixed positioning, no z-index\n // scramble, no drag: where this sits is the host's layout problem, which is the\n // entire point of asking for it.\n host.style.cssText = [\n 'all: initial',\n 'position: relative',\n 'display: block',\n 'width: 100%',\n 'height: 100%',\n 'contain: layout style',\n ].join(';');\n this.config.container!.appendChild(host);\n } else {\n this.geo = this.readGeometry();\n host.style.cssText = [\n 'all: initial',\n 'position: fixed',\n // Below the max so a host that genuinely needs to cover us (a modal, a cookie\n // banner they are legally obliged to show) still can.\n 'z-index: 2147483000',\n 'contain: layout style',\n // The host element owns the BOX now (position AND size); the iframe fills it.\n // Transitioning the box is what makes the corner snap and the open/dock read as\n // motion rather than a jump. Suppressed during drag/resize (see those handlers).\n 'transition: width .18s ease, height .18s ease, top .18s ease,' +\n ' right .18s ease, bottom .18s ease, left .18s ease',\n ].join(';');\n document.body.appendChild(host);\n }\n\n this.shadow = host.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n // Shared prefix, then only what differs. This ships on every page load and the stub\n // has ~no headroom, so the two modes must not each carry a whole stylesheet.\n //\n // Inline fills the host's box and adds nothing: no radius, no shadow. Their panel\n // already has whatever chrome they chose; ours would sit inside it looking like a\n // mistake.\n // The iframe simply FILLS the host element, in both modes. The host owns every\n // dimension, so all the geometry lives in one place (and stays observable in the\n // light DOM — this shadow root is closed, so nothing in here can be inspected).\n // Only the corner treatment differs, switched off the host's data-mode: a circle\n // while it's the launcher, a card once it's a pill, menu or panel.\n //\n // Hairline ring + soft ambient: the widget must read as a crisp shape on ANY host\n // background, including pure white where a shadow alone bleeds.\n // Only the OPEN panel is a surface of ours. While collapsed the widget draws its\n // own shapes — the tab, the circle, the menu — onto the host's page, so the iframe\n // must not paint a card behind them: the host box grows to make room for the menu,\n // and a background there shows up as a slab hanging off the launcher.\n style.textContent =\n ':host{all:initial}' +\n 'iframe{border:0;display:block;width:100%;height:100%;background:transparent}' +\n (this.inline\n ? ''\n : // color-scheme only on the OPEN panel — on a collapsed launcher it makes the\n // UA paint an opaque canvas base behind our shapes.\n ':host([data-mode=\"float\"]) iframe,:host([data-mode=\"dock\"]) iframe' +\n '{color-scheme:light dark}' +\n ':host([data-mode=\"float\"]) iframe{border-radius:12px;' +\n 'box-shadow:0 0 0 1px #00000014,0 8px 40px #00000029}' +\n ':host([data-mode=\"dock\"]) iframe{box-shadow:0 0 0 1px #00000014,' +\n '0 8px 40px #00000029}' +\n ':host([data-mode=\"dock\"][data-flush=\"right\"]) iframe' +\n '{border-radius:12px 0 0 12px}' +\n ':host([data-mode=\"dock\"][data-flush=\"left\"]) iframe' +\n '{border-radius:0 12px 12px 0}');\n this.shadow.appendChild(style);\n\n const iframe = document.createElement('iframe');\n iframe.title = 'matterfact assistant';\n //\n // `allow-same-origin` is REQUIRED, and leaving it out is the trap.\n //\n // Without it the framed document gets an OPAQUE origin: its postMessage arrives\n // as `event.origin === \"null\"`, so our own origin check rejects the handshake and\n // the bridge silently never connects. It also denies the widget any storage at\n // all — no session, no auth, ever.\n //\n // The familiar warning — \"allow-scripts + allow-same-origin lets the frame escape\n // its sandbox\" — is about a frame that is SAME-ORIGIN WITH THE FRAMER, which can\n // then reach up and delete its own sandbox attribute. Ours is cross-origin to the\n // host by construction (that is the entire security model), so it cannot touch\n // this element. What the sandbox still buys us is real: no top-level navigation,\n // no downloads, no pointer lock.\n // `allow-downloads` lets the chat save a file in place. Every download path\n // is an in-place `<a download>`.click(); WITHOUT this flag a sandboxed frame\n // blocks that and the browser falls back to opening the file in a new tab.\n // It is a sandbox flag, not a permissions-policy `allow` token.\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads',\n );\n // Powerful features need an explicit permissions-policy grant: a cross-origin\n // frame is granted NONE by default, so without `allow` they are hard-blocked\n // no matter what the user approves.\n // - microphone: dictation's getUserMedia.\n // - clipboard-write: the \"Copy\" button on a chat message calls\n // navigator.clipboard.writeText, which throws NotAllowedError without it.\n // The bare tokens scope each grant to the iframe's own origin (the app), not\n // the host page. A host page can still deny either via its own\n // Permissions-Policy response header — outside our control, which is why the\n // in-app copy path also degrades gracefully rather than throwing.\n iframe.setAttribute('allow', 'microphone; clipboard-write');\n iframe.src =\n `${this.config.origin}/embed/chat?k=${encodeURIComponent(\n this.config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}` +\n (this.config.surface\n ? `&s=${encodeURIComponent(this.config.surface)}`\n : '') +\n // Either trigger works: the URL param (no redeploy needed) OR the config's\n // programmatic `dev` (the React prop). See both doc comments above.\n (devRequested() || this.config.dev ? '&dev=1' : '') +\n (this.inline ? '&inline=1' : '');\n this.iframe = iframe;\n this.shadow.appendChild(iframe);\n\n window.addEventListener('message', this.onMessage);\n if (!this.inline) {\n // A viewport change can strand a saved box off-page (a laptop undocked from an\n // external monitor is the common one), so re-clamp and re-anchor on resize.\n window.addEventListener('resize', this.onViewportResize);\n this.place();\n }\n }\n\n /**\n * Every message is checked twice, on every single message — not once at setup.\n *\n * `channel` is a namespace, not a boundary. The origin and source checks are the\n * boundary: any frame on the page can postMessage us, and a page with an ad iframe\n * on it has plenty of frames.\n */\n private onMessage = (event: MessageEvent) => {\n if (event.origin !== this.config.origin) return;\n if (event.source !== this.iframe?.contentWindow) return;\n if (!isEnvelope(event.data)) return;\n\n this.handle(event.data.payload as WidgetToHost);\n };\n\n /**\n * Test seam. The shadow root is CLOSED, so a test cannot reach the iframe to forge a\n * source-valid MessageEvent — this routes a message through the identical logic\n * without weakening the origin/source checks above, which stay the only real door.\n */\n __testHandle(msg: WidgetToHost) {\n this.handle(msg);\n }\n\n /**\n * The eager stub's own emit-and-swallow for the host's `onEvent` telemetry hook.\n * Deliberately does NOT import the registry's `emitEvent`: pulling the lazy ./context\n * chunk (where the registry lives) into the size-budgeted stub would blow it, so this\n * ~5-line duplication across the bundle boundary is intentional. Host telemetry is\n * host code — a throw here must never break the widget.\n */\n private emit(e: MatterfactEvent) {\n const cb = (\n globalThis as { matterfact?: { onEvent?: (e: MatterfactEvent) => void } }\n ).matterfact?.onEvent;\n if (typeof cb !== 'function') return;\n try {\n cb(e);\n } catch {\n /* host telemetry must never break the widget */\n }\n }\n\n private handle(msg: WidgetToHost) {\n switch (msg.type) {\n case 'widget.ready':\n this.ready = true;\n this.send({\n type: 'host.ready',\n protocol: PROTOCOL_VERSION,\n origin: location.origin,\n });\n // Theme NOW, not on first open. It used to ride in with the lazy context\n // chunk, which is only fetched when the chat is opened — so a collapsed\n // launcher sat in the wrong colours until you interacted with it.\n this.send({ type: 'host.theme', mode: this.themeMode() });\n this.flush();\n // Inline has no \"open\" event to hang this off — the chat is visible the moment\n // the host renders their panel, so the eye has to load now or the agent is\n // blind to the page for the whole session. The corner keeps its lazy load: a\n // page whose visitors never click still pays nothing.\n if (this.inline) void this.loadContext();\n this.emit({ type: 'ready' });\n break;\n\n case 'widget.setOpen':\n // Host telemetry sees the open/close moment regardless of placement (the inline\n // guard below only skips the popup SIZING, which is meaningless inline).\n this.emit({ type: msg.open ? 'open' : 'close' });\n // Inline: the host's panel IS the open/close control. There's no popup to size.\n if (this.inline) break;\n this.open = msg.open;\n this.place();\n // The DOM code is fetched HERE — the first time someone actually opens the\n // chat — and never on a page where they don't.\n if (msg.open) void this.loadContext();\n break;\n\n case 'widget.setMode':\n // Inline: the host owns the box; float/dock is not ours to choose.\n if (this.inline) break;\n this.geo.mode = msg.mode;\n this.writeGeometry(this.geo);\n this.place();\n break;\n\n case 'widget.setDockSide':\n if (this.inline) break;\n this.geo.dockSide = msg.side;\n this.writeGeometry(this.geo);\n this.place();\n break;\n\n case 'widget.snapCorner':\n if (this.inline) break;\n // Snapping is a FLOAT affordance; the picker only shows in float mode.\n this.geo.corner = msg.corner;\n this.writeGeometry(this.geo);\n this.place();\n break;\n\n case 'widget.setLauncherRegion': {\n // Only meaningful while collapsed — open, the panel is already bigger than any\n // pill or menu, and growing the box would fight the panel's own size.\n if (this.inline || this.open) break;\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n if (msg.w <= LAUNCHER && msg.h <= LAUNCHER) {\n // Back to the bare launcher — place() already knows how to draw it.\n this.place();\n } else {\n const region =\n this.geo.mode === 'dock'\n ? dockChrome(this.geo, msg.w, msg.h, vw, vh)\n : floatChrome(this.geo, msg.w, msg.h, vw, vh);\n this.applyBox(region, msg.h > LAUNCHER ? 'menu' : 'pill');\n }\n break;\n }\n\n case 'widget.resize':\n // Inline: the container's height is the host's business, and an auto-grow here\n // would fight their layout every time the transcript got longer.\n if (this.inline) break;\n // Content height auto-grow, for the FLOATING panel only. Docked, the edges own\n // the height; and a manual resize has already written floatH, which place()\n // would restore on the next call anyway.\n if (this.hostEl && this.open && this.geo.mode === 'float') {\n this.hostEl.style.height = `${Math.min(\n msg.height,\n Math.max(0, window.innerHeight - 2 * MARGIN),\n )}px`;\n }\n break;\n\n case 'widget.resizeStart':\n if (this.inline) break;\n this.resizeBase = { w: this.geo.floatW, h: this.geo.floatH };\n this.dockBase = this.geo.dockW;\n // The box must track the pointer exactly; an eased transition lags behind it.\n if (this.hostEl) this.hostEl.style.transition = 'none';\n break;\n\n case 'widget.resizeMove': {\n if (this.inline || !this.resizeBase) break;\n if (this.geo.mode === 'dock') {\n // Docked, only the WIDTH is the user's — the edges own the height.\n const w = applyDockResizeDelta(\n this.geo.dockSide,\n this.dockBase,\n msg.dx,\n );\n this.geo.dockW = Math.min(\n Math.max(w, MIN_DOCK_W),\n Math.max(0, window.innerWidth - 2 * MARGIN),\n );\n } else {\n const next = applyResizeDelta(\n growthCorner(this.geo, window.innerWidth, window.innerHeight),\n this.resizeBase.w,\n this.resizeBase.h,\n msg.dx,\n msg.dy,\n );\n const fit = clampSize(\n next.w,\n next.h,\n window.innerWidth,\n window.innerHeight,\n MIN_FLOAT_W,\n MIN_FLOAT_H,\n );\n this.geo.floatW = fit.w;\n this.geo.floatH = fit.h;\n }\n this.place();\n break;\n }\n\n case 'widget.resizeEnd':\n if (this.inline) break;\n this.resizeBase = null;\n if (this.hostEl) this.hostEl.style.transition = '';\n this.writeGeometry(this.geo);\n break;\n\n case 'widget.requestContext':\n // The pull path for declared context — re-read it now (via getPageContext if the\n // host supplied one) and re-publish `host.context`. No-op if pageContext is off.\n void this.loadContext().then((m) => m.provideContext());\n break;\n\n case 'widget.requestSnapshot':\n // pageContext: false ⇒ `sendSnapshot` itself no-ops (see context.ts) rather\n // than gating here — this file is the size-budgeted stub, and the check\n // costs nothing extra in the lazy chunk that already owns the DOM read.\n void this.loadContext().then((m) => m.sendSnapshot(this.send));\n break;\n\n case 'widget.readRegion':\n void this.loadContext().then((m) => m.sendRegion(msg.ref, this.send));\n break;\n\n case 'widget.callTool':\n void this.loadContext().then((m) => m.callTool(msg.call, this.send));\n break;\n\n // Everything below is LAUNCHER chrome: there is no launcher inline (the widget\n // doesn't draw one), and moving or hiding the host's own panel from inside it\n // would be us redecorating their app. An older cached loader could still be told\n // any of these by a newer widget, so they're guarded rather than assumed absent.\n case 'widget.dragStart':\n if (this.inline) break;\n this.dragFrom = dragAnchor(\n this.geo,\n window.innerWidth,\n window.innerHeight,\n );\n this.dragAt = { ...this.dragFrom };\n this.dragLeftBand = false;\n this.dragGrowth = growthCorner(\n this.geo,\n window.innerWidth,\n window.innerHeight,\n );\n this.dragBox = visibleBox(\n this.geo,\n this.open,\n window.innerWidth,\n window.innerHeight,\n );\n // Follow the pointer 1:1 while dragging; the ease is for the snap on release.\n if (this.hostEl) this.hostEl.style.transition = 'none';\n break;\n\n case 'widget.dragMove': {\n if (this.inline || !this.dragFrom) break;\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n this.dragAt = {\n x: this.dragFrom.x + msg.dx,\n y: this.dragFrom.y + msg.dy,\n };\n // Switch placement DURING the drag, not on release: drag toward a side and it\n // becomes the tab under your cursor, drag away and it pops back to the circle.\n // Deliberately only the EDGE test here — running the full drop resolver would\n // also snap corners mid-gesture, yanking the widget away while you're still\n // holding it. Corners are resolved on release, where a jump reads as a snap.\n const side = edgeDock(this.dragBox.x + msg.dx, this.dragBox.w, vw);\n if (!side) this.dragLeftBand = true;\n // A tab is already docked, so it may stay docked without having left first;\n // anything else must have been clear of the band at some point in this drag.\n if (side && (this.dragLeftBand || this.geo.mode === 'dock')) {\n this.geo.mode = 'dock';\n this.geo.dockSide = side;\n this.geo.tabY = Math.max(0, this.dragAt.y);\n } else {\n this.geo.mode = 'float';\n this.geo.corner = null;\n this.geo.x = this.dragAt.x;\n this.geo.y = this.dragAt.y;\n }\n this.place();\n break;\n }\n\n case 'widget.dragEnd': {\n if (this.inline || !this.dragFrom) break;\n // The drop resolves the FULL placement — including the corner snap the live\n // pass deliberately skipped. Restoring the transition first is what makes that\n // final snap animate rather than teleport.\n const at = placeDrop(\n this.dragAt.x,\n this.dragAt.y,\n this.dragBox.x + (this.dragAt.x - this.dragFrom.x),\n this.dragBox.w,\n window.innerWidth,\n window.innerHeight,\n );\n this.geo.mode = at.mode;\n if (at.mode === 'dock') {\n this.geo.dockSide = at.dockSide;\n this.geo.tabY = at.tabY;\n } else {\n this.geo.corner = at.corner;\n this.geo.x = at.x;\n this.geo.y = at.y;\n }\n this.dragFrom = null;\n this.dragGrowth = null;\n if (this.hostEl) this.hostEl.style.transition = '';\n this.place();\n this.writeGeometry(this.geo);\n break;\n }\n\n case 'widget.resetPos':\n if (this.inline) break;\n this.geo = defaultGeometry();\n this.writeGeometry(this.geo);\n this.place();\n break;\n\n case 'widget.hide':\n // Inline: hiding is the host's panel to hide. Blanking their drawer from in\n // here would leave them with an empty box and no way to get it back.\n if (this.inline) break;\n if (this.hostEl) this.hostEl.style.display = 'none';\n break;\n\n case 'widget.needsAuth':\n this.emit({ type: 'auth', phase: 'required' });\n void this.provideAuth();\n break;\n\n case 'widget.navigate':\n this.emit({ type: 'navigate', href: msg.href });\n // Delegated to the lazy context chunk (kept out of the every-page stub —\n // the eager budget is tight). By the time a document deeplink is clicked the\n // chat is open, so context is already loaded.\n void this.loadContext().then((m) => m.navigateHost(msg.href));\n break;\n\n case 'widget.chat':\n // Content-free chat-turn telemetry (phase + opaque chatId), relayed straight\n // to the host's onEvent. Never carries message text.\n this.emit({ type: 'chat', phase: msg.phase, chatId: msg.chatId });\n break;\n }\n }\n\n /**\n * Own a drag for its lifetime.\n *\n * The widget reports the press and then goes quiet: a cross-origin iframe only gets\n * pointer events while the pointer is over it, and a drag leaves that box immediately.\n * So we lay a transparent layer over the whole viewport and track the gesture in the\n * host document, where it can't be lost. The layer also stops the pointer landing on\n * the customer's own UI mid-drag (text selection, hover states, stray clicks).\n *\n * We are the dumb half on purpose — see `widget.dragMove` in the protocol for why the\n * widget has to own the gesture. All we do is take a delta and place the element.\n */\n /** Write a box onto the host element and stamp the mode the shadow CSS keys off. */\n private applyBox(\n box: BoxStyle,\n mode: 'launcher' | 'tab' | 'pill' | 'menu' | 'float' | 'dock',\n ) {\n if (!this.hostEl || this.inline) return;\n const s = this.hostEl.style;\n s.top = box.top;\n s.right = box.right;\n s.bottom = box.bottom;\n s.left = box.left;\n s.width = box.width;\n s.height = box.height;\n this.hostEl.dataset.mode = mode;\n // The flush shapes (tab, docked panel) round only on the side facing the page.\n if (mode === 'tab' || mode === 'dock')\n this.hostEl.dataset.flush = this.geo.dockSide;\n else delete this.hostEl.dataset.flush;\n }\n\n /** Re-apply the box for whatever state we're in: collapsed launcher, float, or dock. */\n /**\n * The growth direction to use RIGHT NOW — frozen while a drag is in flight.\n *\n * Every consumer has to agree on this, which is the bug that made the widget\n * flip-flop under small movements near the viewport centre: the box was frozen but\n * `host.geometry` still published a freshly-derived growth, so the WIDGET kept\n * swapping which corner it drew against (and it animates that), twitching back and\n * forth while the loader held perfectly still.\n */\n private growthNow(): Corner {\n return (\n this.dragGrowth ??\n growthCorner(this.geo, window.innerWidth, window.innerHeight)\n );\n }\n\n private place() {\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n if (!this.open) {\n const dock = this.geo.mode === 'dock';\n this.applyBox(\n dock\n ? tabBox(this.geo, vw, vh)\n : floatChrome(this.geo, LAUNCHER, LAUNCHER, vw, vh, this.growthNow()),\n dock ? 'tab' : 'launcher',\n );\n } else if (this.geo.mode === 'dock') {\n this.applyBox(dockBox(this.geo, vw, vh), 'dock');\n } else {\n this.applyBox(floatBox(this.geo, vw, vh, this.growthNow()), 'float');\n }\n this.publishGeometry();\n }\n\n /**\n * Tell the widget where it is. It can't see the viewport and doesn't own the box, so\n * without this it draws its launcher against a stale guess — which is what made the\n * circle jump when the launcher sat on the left (see `host.geometry` in the protocol).\n */\n private publishGeometry() {\n this.send({\n type: 'host.geometry',\n mode: this.geo.mode,\n dockSide: this.geo.dockSide,\n growth: this.growthNow(),\n });\n }\n\n /** The theme to publish: an explicit data-theme wins, else the OS preference. */\n private themeMode(): 'light' | 'dark' {\n return this.config.theme === 'auto'\n ? matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light'\n : this.config.theme;\n }\n\n private onViewportResize = () => {\n // Re-clamp and re-anchor: a saved box must never be left hanging off a smaller page.\n this.place();\n };\n\n private readGeometry(): EmbedGeometry {\n // First-party storage on the CUSTOMER's origin, so each site remembers its own spot.\n // Never throws: storage is unavailable in some embedding contexts, and a widget that\n // can't remember where it was put is fine — one that fails to mount is not.\n try {\n return parseGeometry(localStorage.getItem(POS_KEY)) ?? defaultGeometry();\n } catch {\n return defaultGeometry();\n }\n }\n\n private writeGeometry(g: EmbedGeometry) {\n try {\n localStorage.setItem(POS_KEY, serializeGeometry(g));\n } catch {\n /* storage denied — the box just won't survive the reload */\n }\n }\n\n /**\n * Answer `widget.needsAuth`. If a trusted first-party host has an auth-token provider,\n * call it and hand the token straight to the widget via `host.auth` — no popup. The\n * provider comes from EITHER the programmatic config (the React `<MatterfactAgent\n * getAuthToken>` prop) OR a global the host page sets for the `<script>` loader:\n *\n * window.matterfact = { getEmbedAuthToken: () => getIdToken(user) };\n *\n * Read fresh at call time (not at readConfig), so a global set after the loader booted\n * — e.g. once the host's auth is ready — is still picked up. `expiresAt: 0`: the widget\n * doesn't cache it, it exchanges the token for a rotating embed session anyway.\n *\n * No provider ⇒ this does nothing. The loader never opens a sign-in popup — the widget\n * owns interactive sign-in (inline Firebase/email, and Microsoft's own MSAL login popup\n * for Entra, then the PKCE token exchange), so the loader must not also fire its stale\n * `/embed/authorize?k=&o=` popup, which the deployed authorize page no longer accepts.\n */\n private async provideAuth() {\n const provider =\n this.config.authTokenProvider ??\n (globalThis as { matterfact?: { getEmbedAuthToken?: AuthTokenProvider } })\n .matterfact?.getEmbedAuthToken;\n if (!provider) return; // the widget owns interactive sign-in; the loader never opens it\n\n // Storm guard. A healthy host-auth flow asks ONCE — the widget exchanges the token for a\n // rotating session and never asks again. A flood of `widget.needsAuth` means the token\n // keeps being rejected (wrong audience/scope) and something is remounting the widget in a\n // loop; calling getAuthToken on every one hammers the host's identity provider (MSAL →\n // login.microsoftonline.com), which can get the app RATE-LIMITED. Past the cap we simply\n // stop calling the provider. Silent + minimal by necessity (hard per-page size budget);\n // the widget-side guard is what surfaces the reason to the user and logs the rejection.\n if (++this.ac > 5) return;\n try {\n const token = await provider();\n if (token) this.send({ type: 'host.auth', token, expiresAt: 0 });\n // One emit either way — a null token is a failure to provide, same as a throw.\n this.emit({ type: 'auth', phase: token ? 'granted' : 'failed' });\n } catch {\n this.emit({ type: 'auth', phase: 'failed' });\n /* no token this time; the widget falls back to its own inline / popup sign-in */\n }\n }\n\n private loadContext() {\n // One chunk, one fetch, cached. Everything that can see the customer's page\n // lives behind this boundary.\n this.context ??= import('./context').then((m) => {\n // The single place the eye actually starts: when pageContext is off, `start()`\n // skips installing every DOM/nav/focus/activity observer — not a filter over\n // what gets sent afterward, nothing is collected in the first place. Passed\n // through raw: `start`'s default parameter is what turns `undefined` (the\n // option omitted) into \"on\".\n m.start(\n this.send,\n this.config.origin,\n this.config.pageContext,\n this.config.pageContextProvider,\n );\n // start() emits the OS-preference theme. An explicit data-theme on the\n // script tag is the host's choice — resend it so it wins over auto-detect\n // (a light-branded site must be able to force a light widget on a dark-OS\n // visitor, and vice versa).\n if (this.config.theme !== 'auto') {\n this.send({ type: 'host.theme', mode: this.config.theme });\n }\n return m;\n });\n return this.context;\n }\n\n private send = (msg: HostToWidget) => {\n if (!this.ready) {\n this.queue.push(msg);\n return;\n }\n // targetOrigin is the widget's exact origin — never '*'. A '*' here would\n // broadcast the customer's page content to whatever happens to be listening.\n this.iframe?.contentWindow?.postMessage(envelope(msg), this.config.origin);\n };\n\n private flush() {\n const pending = this.queue;\n this.queue = [];\n for (const m of pending) this.send(m);\n }\n\n /** Tear down: stop listening and remove the host element. For the React wrapper's\n * unmount — the vanilla `<script>` loader lives for the page's lifetime and never\n * calls this. */\n destroy() {\n window.removeEventListener('message', this.onMessage);\n window.removeEventListener('resize', this.onViewportResize);\n this.hostEl?.remove();\n this.hostEl = null;\n this.iframe = null;\n this.shadow = null;\n this.ready = false;\n // context.ts's listeners/history-patch/ref-registry are module-global and\n // outlive this instance — stop() undoes exactly what start() installed. A no-op\n // if the eye was never loaded (chat never opened, so nothing was ever started).\n // This is the unmount-with-no-remount case; start()'s own stop()-first call\n // (see context.ts) is what protects a REMOUNT, which is why both exist.\n void this.context?.then((m) => m.stop());\n }\n}\n\n/**\n * Programmatic entry — mount the widget from a config object instead of the DOM\n * `<script data-*>`. This is what the React wrapper (`@matterfact/embed/react`) drives;\n * the vanilla loader below reads the script tag and calls this same class.\n */\nexport function mount(config: LoaderConfig): EmbedHost {\n const host = new EmbedHost(config);\n host.mount();\n return host;\n}\n\nexport { EmbedHost, CHANNEL, readConfig };\n"]}
1
+ {"version":3,"sources":["../src/redact.ts","../src/adapters/hoist.ts","../src/adapters/hoist-runtime.ts","../src/adapters/registry.ts","../src/dom/a11y.ts","../src/dom/refs.ts","../src/dom/snapshot.ts","../src/context.ts","../src/protocol.ts","../src/geometry.ts","../src/loader.ts"],"names":["walk","document","isDisabled","getRole","computeAccessibleName","childrenOf","quote","isInaccessible","readSitemap","snapshot","yaml","truncated","snapshotRegion","resolveRef","w"],"mappings":";;;;;;;;;;;;;;;AA0BO,SAAS,OAAO,IAAA,EAAsB;AAC3C,EAAA,IAAI,GAAA,GAAM,IAAA;AACV,EAAA,KAAA,MAAW,MAAM,GAAA,EAAK,GAAA,GAAM,GAAA,CAAI,OAAA,CAAQ,IAAI,YAAY,CAAA;AACxD,EAAA,OAAO,GAAA;AACT;AA9BA,IASM,GAAA;AATN,IAAA,WAAA,GAAA,KAAA,CAAA;AAAA,EAAA,eAAA,GAAA;AASA,IAAM,GAAA,GAAM;AAAA,MACV,iCAAA;AAAA;AAAA,MACA,yBAAA;AAAA;AAAA,MACA,gCAAA;AAAA;AAAA,MACA,aAAA;AAAA;AAAA,MACA,4DAAA;AAAA;AAAA,MACA,oDAAA;AAAA;AAAA,MACA;AAAA;AAAA,KACF;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACwDO,SAAS,YACd,IAAA,EACqB;AACrB,EAAA,IAAI,EAAA;AACJ,EAAA,IAAI;AACF,IAAA,EAAA,GAAK,IAAA,EAAK;AAAA,EACZ,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,IAAI,CAAC,IAAI,OAAO,IAAA;AAChB,EAAA,MAAM,aACJ,CAAC,CAAC,EAAA,CAAG,KAAA,CAAM,QACX,EAAA,CAAG,KAAA,CAAM,MAAA,GAAS,CAAA,IAClB,GAAG,MAAA,CAAO,MAAA,GAAS,CAAA,IACnB,EAAA,CAAG,IAAI,MAAA,GAAS,CAAA;AAClB,EAAA,OAAO,aAAa,EAAA,GAAK,IAAA;AAC3B;AAUA,SAAS,KAAA,CAAM,CAAA,EAAW,GAAA,GAAM,GAAA,EAAa;AAC3C,EAAA,MAAM,KAAA,GAAQ,OAAO,CAAA,CAAE,OAAA,CAAQ,QAAQ,GAAG,CAAA,CAAE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A,EAAS,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA,EAKA,OAAA,GAAU;AACR,IAAA,MAAA,CAAO,mBAAA,CAAoB,SAAA,EAAW,IAAA,CAAK,SAAS,CAAA;AACpD,IAAA,MAAA,CAAO,mBAAA,CAAoB,QAAA,EAAU,IAAA,CAAK,gBAAgB,CAAA;AAC1D,IAAA,IAAA,CAAK,QAAQ,MAAA,EAAO;AACpB,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAMb,IAAA,KAAK,KAAK,OAAA,EAAS,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM,CAAA;AAAA,EACzC;AACF;AAOO,SAAS,MAAM,MAAA,EAAiC;AACrD,EAAA,MAAM,IAAA,GAAO,IAAI,SAAA,CAAU,MAAM,CAAA;AACjC,EAAA,IAAA,CAAK,KAAA,EAAM;AACX,EAAA,OAAO,IAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * Redaction, split out of context.ts so it can be imported by both context.ts\n * (the DOM-walking eye) and the Hoist adapter (adapters/hoist.ts) without the\n * latter creating an import cycle back into context.ts.\n *\n * Re-exported from context.ts (`export { redact } from './redact'`) so every\n * existing importer of `redact` from `./context` keeps working unchanged.\n */\n\nconst PII = [\n /\\b[\\w.+-]+@[\\w-]+\\.[\\w.]{2,}\\b/g, // email\n /\\b(?:\\d[ -]?){13,19}\\b/g, // card-ish\n /\\b\\d{3}[- ]?\\d{2}[- ]?\\d{4}\\b/g, // ssn — dashed, spaced, OR bare 9 digits\n /\\b\\d{9,}\\b/g, // long bare digit runs: account / MRN / routing numbers\n /(?:\\+?\\d{1,2}[\\s.-]?)?\\(?\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}\\b/g, // us phone\n /\\b(?:sk|pk|rk|ak)_(?:live|test)_[A-Za-z0-9]{8,}\\b/g, // stripe-style api keys\n /\\beyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+\\b/g, // jwt\n];\n\n/**\n * Scrub before anything leaves the page — not after it arrives.\n *\n * A compromised widget, or a bug in ours, must not be able to retroactively obtain\n * a customer's users' email addresses. The only way to guarantee that is to never\n * put them on the wire.\n */\nexport function redact(text: string): string {\n let out = text;\n for (const re of PII) out = out.replace(re, '[redacted]');\n return out;\n}\n","/**\n * The Hoist adapter — a pure transform from a `HoistRuntime` (already read out of\n * `window.XH` by hoist-runtime.ts) into the context/snapshot shapes context.ts sends\n * over the bridge.\n *\n * This file never touches `window` or `XH` itself — see hoist-runtime.ts for the only\n * code that does — so every function here is a plain, fully unit-testable transform\n * against a plain object. That split is what keeps this file degrade-safe: it can be\n * exhaustively tested without a real Hoist app, and hoist-runtime.ts's own try/catch\n * (via detectHoist) is the one place a live-model surprise can ever throw.\n */\n\n// From ./redact, not ./context: context.ts (Task 7) imports THIS module, so importing\n// from ./context here would be a cycle. redact.ts holds no other context.ts state, so\n// this is the clean fix rather than a same-cycle-but-runtime-safe workaround. context.ts\n// still re-exports `redact`, so every pre-existing importer is unaffected.\nimport { redact } from '../redact';\nimport type { HostTool, PageContext } from '../protocol';\n\nexport interface HoistRoute {\n name: string;\n path: string;\n params: Record<string, unknown>;\n}\nexport interface HoistColumn {\n field: string;\n header: string;\n}\nexport type HoistRow = Record<string, unknown>;\nexport interface HoistGrid {\n id: string;\n title: string;\n columns: HoistColumn[];\n selected: HoistRow[];\n rows: HoistRow[];\n totalCount: number;\n}\nexport interface HoistChart {\n id: string;\n title: string;\n series: { name: string; data: number[] }[];\n}\n/** A navigable destination in the host app: a human label + a deep-link path. */\nexport interface HoistDestination {\n label: string;\n path: string;\n /**\n * The fully-qualified router route name (e.g. `default.company.ticker.ownership`) —\n * what `hoist.navigate` actually hands `XH.navigate`/`XH.router.navigate`. The LABEL\n * is what the agent sees and picks from (the tool arg is `destination`, a label); the\n * name is resolved from it internally, never exposed as an arg the model fills in.\n */\n name: string;\n /** True for the destination the user is currently on (per nav level). */\n current?: boolean;\n}\n/** One level of site navigation (a Hoist TabContainer): the top app tabs, the\n * per-section sidebar, etc. */\nexport interface HoistNavGroup {\n label: string;\n items: HoistDestination[];\n}\nexport interface HoistRuntime {\n route: HoistRoute;\n grids: HoistGrid[];\n charts: HoistChart[];\n /** The site map — navigable destinations, grouped by nav level. */\n nav: HoistNavGroup[];\n}\n\n/** Read the runtime through `read`, but never let a Hoist-side error reach context.ts.\n * Returns null when there is nothing worth sending, so the caller falls back to the\n * generic DOM walker. */\nexport function detectHoist(\n read: () => HoistRuntime | null,\n): HoistRuntime | null {\n let rt: HoistRuntime | null;\n try {\n rt = read();\n } catch {\n return null;\n }\n if (!rt) return null;\n const worthwhile =\n !!rt.route.name ||\n rt.grids.length > 0 ||\n rt.charts.length > 0 ||\n rt.nav.length > 0;\n return worthwhile ? rt : null;\n}\n\n/* ─────────────────────────── grid rendering ────────────────────────────── */\n\n/** Collapse whitespace, then redact, then truncate, then escape — in that order.\n * The order matches dom/snapshot.ts's `sanitize()`: truncate first and a value\n * containing PII can be cut through the middle of it, the regex no longer\n * matches, and the fragment before the cut ships unredacted. Collapsing\n * whitespace first also means an embedded newline can never survive into the\n * YAML as a fabricated sibling line. */\nfunction quote(s: string, max = 120): string {\n const clean = redact(s.replace(/\\s+/g, ' ').trim());\n const capped = clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;\n return `\"${capped.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/** One field value → a short, redacted, quoted cell string. */\nfunction cell(value: unknown): string {\n const s = value == null ? '' : String(value);\n return `- cell ${quote(s)}`;\n}\n\nfunction pushRow(\n row: HoistRow,\n cols: HoistColumn[],\n out: string[],\n pad: string,\n): void {\n out.push(`${pad}- row:`);\n for (const c of cols) out.push(`${pad} ${cell(row[c.field])}`);\n}\n\nexport function renderGrid(\n grid: HoistGrid,\n rowCap: number,\n out: string[],\n depth: number,\n): void {\n const pad = ' '.repeat(depth);\n out.push(`${pad}- table ${quote(grid.title || 'grid')}:`);\n\n out.push(`${pad} - rowgroup \"columns\":`);\n for (const c of grid.columns)\n out.push(`${pad} - columnheader ${quote(c.header || c.field)}`);\n\n if (grid.selected.length) {\n out.push(`${pad} - rowgroup \"selected\":`);\n for (const r of grid.selected) pushRow(r, grid.columns, out, `${pad} `);\n }\n\n const shown = grid.rows.slice(0, Math.max(0, rowCap));\n out.push(`${pad} - rowgroup \"rows\":`);\n for (const r of shown) pushRow(r, grid.columns, out, `${pad} `);\n\n out.push(\n `${pad} - text: ${quote(`showing ${shown.length} of ${grid.totalCount} rows`)}`,\n );\n}\n\n/* ─────────────────────────── chart rendering ───────────────────────────── */\n\nfunction seriesSummary(name: string, data: number[]): string {\n if (!data.length) return `series ${name}: 0 points`;\n // Looped, not Math.min(...data)/Math.max(...data): spreading a large series into\n // call arguments hits the engine's argument-count ceiling (RangeError) well within\n // the size of a normal intraday/tick series. See adapters/hoist.test.ts's 200k-point\n // case.\n let min = data[0];\n let max = data[0];\n for (const n of data) {\n if (n < min) min = n;\n if (n > max) max = n;\n }\n const last = data[data.length - 1];\n return `series ${name}: ${data.length} points, min ${min}, max ${max}, last ${last}`;\n}\n\nexport function renderChart(\n chart: HoistChart,\n out: string[],\n depth: number,\n): void {\n const pad = ' '.repeat(depth);\n out.push(`${pad}- figure ${quote(chart.title || 'chart')}:`);\n for (const s of chart.series) {\n out.push(`${pad} - text: ${quote(seriesSummary(s.name, s.data))}`);\n }\n}\n\n/* ─────────────────────────── site-map rendering ────────────────────────── */\n\nexport function renderNav(\n groups: HoistNavGroup[],\n out: string[],\n depth: number,\n): void {\n const pad = ' '.repeat(depth);\n for (const g of groups) {\n if (!g.items.length) continue;\n out.push(`${pad}- navigation ${quote(g.label)}:`);\n for (const d of g.items) {\n const mark = d.current ? ' [current]' : '';\n // The path is a deep-link the agent can hand the user. Redact it like any value,\n // but leave it after the arrow rather than as a quoted YAML name.\n out.push(`${pad} - link ${quote(d.label)}${mark} → ${redact(d.path)}`);\n }\n }\n}\n\n/* ─────────────────────────── navigate tool (Layer 3) ───────────────────── */\n\n/** The host's policy for agent-driven actions, keyed by tool family. Read from\n * `window.matterfact.hoist.actions` by hoist-runtime.ts's `readActionsConfig`\n * (the `<MatterfactAgent actions>` React prop is sugar that writes that same\n * global — see react.tsx's `writeActionsGlobal`); `'off'` is the default — the\n * tool is opt-in, never advertised unless a host turns it on. */\nexport interface HoistActionsConfig {\n navigate: 'off' | 'confirm' | 'auto';\n}\n\n/** Every destination across every nav level, flattened — the universe `hoist.navigate`\n * is bounded to (its enum) and what `executeHostTool` looks the agent's chosen label\n * up against. */\nexport function flattenDestinations(rt: HoistRuntime): HoistDestination[] {\n return rt.nav.flatMap((g) => g.items);\n}\n\n/**\n * The `hoist.navigate` tool: lets the agent send the user to a destination in the\n * CURRENT site map. The arg is `destination` — the human LABEL the agent already sees\n * in the sitemap (e.g. \"Ownership\"), never a raw route name; the loader resolves the\n * label to a route name internally (see executeHostTool). The enum is exactly the\n * labels `readSitemap` found on THIS page, so the model cannot name a destination that\n * doesn't exist here — the injection bound this tool relies on.\n */\nexport function buildNavigateTool(\n rt: HoistRuntime,\n policy: 'confirm' | 'auto',\n): HostTool {\n const destinations = flattenDestinations(rt);\n const bySection = rt.nav\n .filter((g) => g.items.length)\n .map((g) => `${g.label} (${g.items.map((d) => d.label).join(', ')})`)\n .join('; ');\n return {\n name: 'hoist.navigate',\n description: redact(\n 'Navigate the user to a destination in the app. \"destination\" must be one of ' +\n `the destinations currently available, grouped by section: ${bySection || '(none available)'}.`,\n ),\n inputSchema: {\n type: 'object',\n properties: {\n destination: {\n type: 'string',\n enum: destinations.map((d) => d.label),\n },\n params: { type: 'object' },\n },\n required: ['destination'],\n },\n readOnly: false,\n // 'confirm' policy ⇒ the widget must show a confirm card every call; 'auto' ⇒ it\n // may call without asking. See the confirm field's doc comment on HostTool.\n confirm: policy === 'auto' ? 'auto' : 'required',\n };\n}\n\n/* ─────────────────────────── top-level transforms ──────────────────────── */\n\nexport function buildHoistContext(rt: HoistRuntime): PageContext {\n const selected = rt.grids.reduce((n, g) => n + g.selected.length, 0);\n const view = rt.route.name || rt.route.path || 'this view';\n const bits = [`Viewing ${view}`];\n if (selected) bits.push(`${selected} selected`);\n if (rt.grids.length) bits.push(`${rt.grids.length} grid(s)`);\n if (rt.charts.length) bits.push(`${rt.charts.length} chart(s)`);\n return {\n route: rt.route.name ? redact(rt.route.name) : undefined,\n description: redact(`${bits.join(', ')}.`),\n };\n}\n\nexport function renderHoistSnapshot(\n rt: HoistRuntime,\n rowCap: number,\n): { yaml: string; truncated: boolean } {\n const out: string[] = [];\n // Nav LEADS. It's the most stable part of the page — it barely changes as the user\n // works within a view — so emitting it first keeps the snapshot's prefix stable\n // across turns (better prompt caching) and orients the agent before the volatile\n // grid/chart data.\n renderNav(rt.nav, out, 0);\n let truncated = false;\n for (const g of rt.grids) {\n if (g.rows.length > rowCap) truncated = true;\n renderGrid(g, rowCap, out, 0);\n }\n for (const c of rt.charts) renderChart(c, out, 0);\n return { yaml: out.join('\\n'), truncated };\n}\n","/**\n * The only module that touches `window.XH`.\n *\n * Everything here is defensive by construction: every field read is optional-chained\n * and falls back to an empty/zero value, so a Hoist version whose shape drifts from\n * what's confirmed below degrades to missing fields rather than a thrown error. The\n * one place a genuine surprise (e.g. `XH` itself being a stub) could still throw is\n * caught one layer up, by `detectHoist()` in ./hoist — this module does not try/catch.\n *\n * The accessors below are CONFIRMED against a live ActivistHub instance (see\n * adapters/HOIST-CONTRACT.md). Two findings shaped this file:\n * 1. Model discovery uses the global `XH.getModels(className)` lookup, NOT the\n * Inspector — `XH.inspectorService.activeInstances` is empty unless the dev\n * Inspector UI is toggled on, so it's useless as an ambient source.\n * 2. Grid columns can be GROUPED: `gridModel.columns` holds ColumnGroups (no field,\n * a `.children` array) whose leaves carry the real `colId`. We read the flat leaf\n * set via `getVisibleLeafColumns()` and prefix each leaf's header with its group\n * (\"5Y\" group + \"Value\" leaf -> \"5Y Value\") so the columns aren't ambiguous.\n */\n\nimport type {\n HoistRuntime,\n HoistGrid,\n HoistChart,\n HoistColumn,\n HoistRow,\n HoistNavGroup,\n HoistDestination,\n HoistActionsConfig,\n} from './hoist';\nimport { buildNavigateTool, flattenDestinations } from './hoist';\nimport type { HostTool, ToolCall } from '../protocol';\nimport { redact } from '../redact';\n\nexport function readHoistConfig(win: unknown): {\n rows: number;\n excludeModels: string[];\n} {\n const cfg = (\n win as {\n matterfact?: { hoist?: { rows?: number; excludeModels?: string[] } };\n }\n )?.matterfact?.hoist;\n const ex = cfg?.excludeModels;\n return {\n rows: typeof cfg?.rows === 'number' && cfg.rows >= 0 ? cfg.rows : 50,\n excludeModels: Array.isArray(ex) ? ex : [],\n };\n}\n\n// ── model discovery ──────────────────────────────────────────────────────────\n// Confirmed: `XH.getModels(className)` returns every mounted model of that class\n// (a native Hoist ModelSelector form). It also returns empty / off-view grids that\n// happen to be mounted — those are dropped by `hasContent` in readHoistRuntime.\nfunction getModelsByClass(XH: any, name: string): any[] {\n const models = typeof XH?.getModels === 'function' ? XH.getModels(name) : [];\n return Array.isArray(models) ? models : [];\n}\n\nfunction className(m: any): string {\n return m?.constructor?.name ?? '';\n}\n\nfunction modelId(m: any): string {\n return String(m?.xhId ?? m?.id ?? m?.modelId ?? '');\n}\n\nfunction headerOf(c: any): string {\n return String(c?.headerName ?? c?.displayName ?? c?.field ?? c?.colId ?? '');\n}\n\n// Walk the full column tree (a ColumnGroup has a `.children` array and no field) to\n// map each leaf colId -> its group-qualified header, so a leaf headed \"Value\" under a\n// \"5Y\" group reads as \"5Y Value\" rather than an ambiguous bare \"Value\".\nfunction collectHeaders(\n cols: any[],\n prefix: string[],\n out: Map<string, string>,\n): void {\n for (const c of Array.isArray(cols) ? cols : []) {\n const children = c?.children;\n if (Array.isArray(children) && children.length) {\n collectHeaders(children, [...prefix, headerOf(c)], out);\n } else {\n const id = String(c?.colId ?? c?.field ?? '');\n if (id) out.set(id, [...prefix, headerOf(c)].filter(Boolean).join(' '));\n }\n }\n}\n\n// Prefer getVisibleLeafColumns() — flat, hidden-aware, real colIds — over the raw\n// `columns` tree (which contains groups without fields). Falls back to `columns` for\n// a Hoist without that method.\nfunction readColumns(g: any): HoistColumn[] {\n const leaves =\n typeof g?.getVisibleLeafColumns === 'function'\n ? g.getVisibleLeafColumns()\n : Array.isArray(g?.columns)\n ? g.columns\n : [];\n const headers = new Map<string, string>();\n collectHeaders(Array.isArray(g?.columns) ? g.columns : [], [], headers);\n return (Array.isArray(leaves) ? leaves : [])\n .map((c: any) => {\n const field = String(c?.colId ?? c?.field ?? '');\n return { field, header: headers.get(field) || headerOf(c) };\n })\n .filter((c: HoistColumn) => c.field);\n}\n\nfunction readRow(rec: any, cols: HoistColumn[]): HoistRow {\n const row: HoistRow = {};\n for (const c of cols)\n row[c.field] =\n typeof rec?.get === 'function' ? rec.get(c.field) : rec?.data?.[c.field];\n return row;\n}\n\nfunction readGrid(g: any): HoistGrid {\n const columns = readColumns(g);\n const records = Array.isArray(g?.store?.records) ? g.store.records : [];\n return {\n id: modelId(g),\n title: String(g?.title ?? ''),\n columns,\n selected: (Array.isArray(g?.selectedRecords) ? g.selectedRecords : []).map(\n (r: any) => readRow(r, columns),\n ),\n rows: records.map((r: any) => readRow(r, columns)),\n totalCount:\n typeof g?.store?.allCount === 'number'\n ? g.store.allCount\n : records.length,\n };\n}\n\n// An off-view / not-yet-loaded grid (no rows AND nothing selected) is one that\n// XH.getModels still returns but that carries no page-context value — drop it.\nfunction hasContent(g: HoistGrid): boolean {\n return g.totalCount > 0 || g.selected.length > 0;\n}\n\nfunction readChart(c: any): HoistChart {\n // Confirmed: series data points can be [timestamp, value] tuples (not bare numbers) —\n // extract the value (`d[1]` / `d.y`) so min/max/last summarise values, not timestamps.\n const series = c?.series ?? c?.highchartsConfig?.series ?? [];\n return {\n id: modelId(c),\n title: String(c?.title ?? c?.highchartsConfig?.title?.text ?? ''),\n series: (Array.isArray(series) ? series : []).map((s: any) => ({\n name: String(s?.name ?? ''),\n data: (Array.isArray(s?.data) ? s.data : [])\n .map((d: any) => (typeof d === 'number' ? d : Number(d?.y ?? d?.[1])))\n .filter((n: number) => Number.isFinite(n)),\n })),\n };\n}\n\n/* ─────────────────────────────── site map ──────────────────────────────── */\n\nfunction humanize(seg: string): string {\n return seg\n .replace(/[_-]+/g, ' ')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n .trim();\n}\n\nfunction childrenOf(node: any): any[] {\n const k = node?.children;\n return k ? (Array.isArray(k) ? k : Array.from(k)) : [];\n}\n\n// Map each route's LAST segment -> { path, fully-qualified name }, by walking the\n// router5 tree and building a deep-link path for each with the current params.\nfunction routeIndex(\n XH: any,\n params: Record<string, unknown>,\n): Map<string, { path: string; name: string }> {\n const router = XH?.router;\n const root = router?.rootNode ?? router?.config?.rootNode;\n const out = new Map<string, { path: string; name: string }>();\n if (!router || typeof router.buildPath !== 'function' || !root) return out;\n const walk = (node: any, prefix: string) => {\n for (const c of childrenOf(node)) {\n const seg = String(c?.name ?? '');\n if (!seg) continue;\n const name = prefix ? `${prefix}.${seg}` : seg;\n let path = '';\n try {\n path = router.buildPath(name, params);\n } catch {\n path = '';\n }\n if (path && !out.has(seg)) out.set(seg, { path, name });\n walk(c, name);\n }\n };\n walk(root, '');\n return out;\n}\n\n// The site map: each Hoist TabContainerModel is one nav level (top app tabs, the\n// per-section sidebar, …). Its tabs give the exact human labels + the active tab;\n// the router gives each tab id its deep-link path. Route names ≠ display labels\n// (e.g. `governanceScorecard` shows as \"Governance Risk\"), so the tab TITLE wins.\nfunction readSitemap(\n XH: any,\n excluded: (m: any) => boolean,\n origin: string,\n): HoistNavGroup[] {\n const params = (XH?.routerState?.params ?? {}) as Record<string, unknown>;\n const currentName = String(XH?.routerState?.name ?? '');\n const routes = routeIndex(XH, params);\n if (!routes.size) return [];\n\n const groups: HoistNavGroup[] = [];\n for (const tc of getModelsByClass(XH, 'TabContainerModel')) {\n if (excluded(tc)) continue;\n const tabs = Array.isArray(tc?.tabs) ? tc.tabs : [];\n const activeTabId = String(tc?.activeTabId ?? '');\n const items: HoistDestination[] = [];\n let companyScoped = false;\n for (const t of tabs) {\n const id = String(t?.id ?? '');\n const r = routes.get(id);\n if (!id || !r) continue;\n if (r.name.includes('.company.ticker.')) companyScoped = true;\n items.push({\n // Redact HERE, at the source — not in a downstream renderer. This is the\n // one place a Hoist tab TITLE (host-page text, so potentially PII-shaped)\n // becomes a `HoistDestination.label`, and that label is what EVERY\n // consumer uses verbatim: renderNav's YAML, buildNavigateTool's\n // description AND its inputSchema.enum, and executeHostTool's\n // `.find(d => d.label === destination)` lookup. Redacting once here keeps\n // all of them consistent by construction — an enum built from an\n // ALREADY-redacted label can never leak PII a sibling renderer scrubbed\n // (see Important #1), and a destination arg matching the redacted string\n // (the only thing the agent ever saw) still resolves.\n label: redact(String(t?.title ?? '') || humanize(id)),\n // ABSOLUTE, against the HOST page's origin — not the router's bare path.\n // This path's only job is to be a link the agent can hand the user, and\n // the agent's answer renders inside our widget iframe, which is on OUR\n // origin: a bare \"/research\" there resolves to app.matterfact.com/research\n // (a dead link to the wrong app), which is exactly what shipped before.\n // The adapter runs in the host page, so its own origin is the right one.\n path: origin && r.path.startsWith('/') ? origin + r.path : r.path,\n // The fully-qualified route name — what hoist.navigate hands XH.navigate.\n // Always present: `r` only exists here because routes.get(id) resolved.\n name: r.name,\n current: id === activeTabId || r.name === currentName,\n });\n }\n if (!items.length) continue;\n const ticker = String(params.ticker ?? '');\n const label = companyScoped\n ? ticker\n ? `Company · ${ticker}`\n : 'Company'\n : 'Site';\n groups.push({ label, items });\n }\n return groups;\n}\n\nexport function readHoistRuntime(\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): HoistRuntime | null {\n const XH = (win as { XH?: any })?.XH;\n if (!XH) return null;\n const { excludeModels } = readHoistConfig(win);\n const excluded = (m: any) =>\n excludeModels.includes(className(m)) || excludeModels.includes(modelId(m));\n\n const rs = XH.routerState ?? {};\n return {\n route: {\n name: String(rs.name ?? ''),\n path: String(rs.path ?? ''),\n params: rs.params ?? {},\n },\n grids: getModelsByClass(XH, 'GridModel')\n .filter((m) => !excluded(m))\n .map(readGrid)\n .filter(hasContent),\n charts: getModelsByClass(XH, 'ChartModel')\n .filter((m) => !excluded(m))\n .map(readChart)\n .filter((c) => c.series.length > 0),\n nav: readSitemap(\n XH,\n excluded,\n String(\n (win as { location?: { origin?: string } })?.location?.origin ?? '',\n ),\n ),\n };\n}\n\n/* ─────────────────────────── actions / tools (Layer 3) ─────────────────── */\n\n/** Read the host's action policy from `window.matterfact.hoist.actions`. Defaults to\n * `{navigate:'off'}` — agent-driven navigation is opt-in, and any value other than\n * the two known policies degrades to `'off'` rather than advertising a tool under an\n * unrecognized policy. */\nexport function readActionsConfig(win: unknown): HoistActionsConfig {\n const navigate = (\n win as {\n matterfact?: { hoist?: { actions?: { navigate?: unknown } } };\n }\n )?.matterfact?.hoist?.actions?.navigate;\n return {\n navigate: navigate === 'confirm' || navigate === 'auto' ? navigate : 'off',\n };\n}\n\n/**\n * The tools this page currently offers the agent — today, just `hoist.navigate` when\n * a Hoist app is detected and the host has turned navigation on via\n * `window.matterfact.hoist.actions` (`readActionsConfig` above) — the SAME read\n * `executeHostTool` re-checks at call time, so advertise and execute can never\n * disagree about the current policy.\n *\n * Degrade-safe by construction: no `window.XH`, `navigate:'off'` (the default), no\n * detectable runtime, or a `getModels`/router surprise ⇒ `[]`, never a throw — so a\n * caller can call this unconditionally without its own try/catch.\n */\nexport function advertiseTools(\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): HostTool[] {\n try {\n const XH = (win as { XH?: unknown })?.XH;\n if (!XH) return [];\n const { navigate } = readActionsConfig(win);\n if (navigate === 'off') return [];\n const rt = readHoistRuntime(win);\n if (!rt) return [];\n return [buildNavigateTool(rt, navigate)];\n } catch {\n return [];\n }\n}\n\n/**\n * Run a host tool call. Two enforcement points, both re-checked fresh on every call —\n * never against anything the widget claims was advertised earlier, which a\n * compromised or merely-stale widget could lie about:\n *\n * 1. the host's CURRENT action policy (`readActionsConfig`) — a widget that cached\n * an advertisement from before the host flipped `actions.navigate` to `'off'`\n * (e.g. entering a regulated flow) must be refused, not just un-advertised;\n * 2. the destination, against the LIVE current sitemap.\n *\n * That is the \"loader route-bound\" guarantee the confirm card (Wave 2) sits on top\n * of, not a substitute for it.\n *\n * Degrade-safe and NEVER throws: any surprise (bad args, XH/router missing or\n * throwing) becomes `{ok:false, error}`, never an exception into context.ts. The\n * error text itself is redacted too — a thrown Error can plausibly embed host-page\n * detail, same as the success path's `result`.\n */\nexport function executeHostTool(\n call: ToolCall,\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): { ok: boolean; result?: unknown; error?: string } {\n try {\n if (call.name !== 'hoist.navigate') {\n return { ok: false, error: 'unknown tool' };\n }\n // Execute-time policy re-check (defense-in-depth): `advertiseTools` already\n // gates on this at advertise time, but that is not an access-control decision\n // this function may assume still holds — the widget calling in is exactly the\n // thing this whole module treats as untrustworthy. See the doc comment above.\n if (readActionsConfig(win).navigate === 'off') {\n return { ok: false, error: 'navigation is disabled' };\n }\n\n const destination = String(call.args?.destination ?? '');\n const rt = readHoistRuntime(win);\n const item = rt\n ? flattenDestinations(rt).find((d) => d.label === destination)\n : undefined;\n if (!item) return { ok: false, error: 'unknown destination' };\n\n const XH = (win as { XH?: any })?.XH;\n // Merge: the CURRENT route's params first, then whatever the agent explicitly\n // supplied on top. A company subroute (e.g. Ownership) needs the current\n // `ticker` param to resolve correctly even though the agent never saw or passed\n // it; an agent-supplied key still wins on conflict (spread order).\n const params = {\n ...(XH?.routerState?.params ?? {}),\n ...((call.args?.params as Record<string, unknown> | undefined) ?? {}),\n };\n if (typeof XH?.navigate === 'function') {\n XH.navigate(item.name, params);\n } else if (typeof XH?.router?.navigate === 'function') {\n XH.router.navigate(item.name, params);\n } else {\n return { ok: false, error: 'navigation unavailable' };\n }\n return { ok: true, result: redact(`navigated to ${destination}`) };\n } catch (e) {\n return {\n ok: false,\n error: redact(e instanceof Error ? e.message : 'navigate failed'),\n };\n }\n}\n","/**\n * The host-tool registry — the ONE place the three tool classes are merged into the\n * single list the widget advertises, and the ONE execution path for calling any of\n * them.\n *\n * Three classes, distinguished by who owns the contract and who runs the code:\n *\n * - `hoist.*` matterfact-defined, matterfact-implemented. The loader adapter runs\n * them (today: `hoist.navigate`). Gated on `window.XH` + the host's\n * `hoist.actions` policy. See `hoist-runtime.ts`.\n * - `mf.*` matterfact-defined, HOST-implemented. WE fix the name, schema and\n * agent semantics (the description is authored HERE, not per\n * integration); the host supplies the function via `resolve.*`. Today:\n * `mf.resolveDocument`, `mf.resolveArtifact`.\n * - `app.*` host-defined, host-implemented. Anything the host advertises via\n * `tools`. Normalised into the `app.` namespace so it can never shadow\n * ours.\n *\n * Everything downstream (the widget's confirm gate, the backend dispatcher) is already\n * generic over \"a tool with a name/schema/confirm and a call round-trip\" — this module\n * is purely the loader-side composition + dispatch, so `hoist-runtime.ts` stays one\n * adapter rather than the whole surface.\n *\n * SECURITY: `mf.*`/`app.*` handlers are HOST code. Their results and error strings pass\n * through `redact()` before leaving the page, exactly like the hoist adapter's; a\n * handler that throws or hangs becomes a normal `{ok:false}` result, never an exception\n * into `context.ts`. And the SERVER decides which of these an app may actually expose\n * (the `host_tools` policy) — advertising here is necessary but not sufficient.\n */\nimport type { HostTool, MatterfactEvent, ToolCall, ToolEvent } from '../protocol';\nimport { redact } from '../redact';\nimport { advertiseTools, executeHostTool } from './hoist-runtime';\n\n/** Advertised metadata rides EVERY turn's model context and is host-supplied. Bound\n * the count; the backend caps it too (defense in depth). */\nexport const MAX_TOOLS = 16;\n\n/** A host `mf.*`/`app.*` handler is host code — bound it so a hung promise surfaces as\n * a normal declined result INSIDE the backend's own ~60s wait, never eating it. */\nexport const HOST_HANDLER_TIMEOUT_MS = 30_000;\n\nexport type ToolClass = 'hoist' | 'mf' | 'app';\n\n/** A host-supplied resolver: matterfact fixes the contract, the host implements it. */\nexport interface HostResolvers {\n document?: (args: {\n doctype: string;\n key: string;\n }) => Promise<{ id: string; label: string; href?: string }>;\n artifact?: (args: {\n slug: string;\n }) => Promise<{ id: string; owner: string; token: string; label: string }>;\n}\n\n/** A host-defined tool (the `tools` prop): a WebMCP-shaped descriptor plus its handler. */\nexport interface HostToolDef {\n name: string;\n description: string;\n inputSchema?: Record<string, unknown>;\n confirm?: 'auto' | 'required';\n handler: (args: Record<string, unknown>) => unknown | Promise<unknown>;\n}\n\ninterface MatterfactGlobal {\n resolve?: HostResolvers;\n tools?: HostToolDef[];\n onToolEvent?: (e: ToolEvent) => void;\n onEvent?: (e: MatterfactEvent) => void;\n}\n\nfunction mfGlobal(win: unknown): MatterfactGlobal {\n return (\n (win as { matterfact?: MatterfactGlobal } | undefined)?.matterfact ?? {}\n );\n}\n\nexport function toolClass(name: string): ToolClass {\n if (name.startsWith('hoist.')) return 'hoist';\n if (name.startsWith('mf.')) return 'mf';\n return 'app';\n}\n\n/** Fire the host's unified `onEvent` telemetry hook, swallowing any throw. A host\n * telemetry callback is host code: a throw here must not fail a call, advertise, or\n * anything else on the path. */\nexport function emitEvent(win: unknown, e: MatterfactEvent): void {\n const cb = mfGlobal(win).onEvent;\n if (typeof cb !== 'function') return;\n try {\n cb(e);\n } catch {\n /* a host telemetry callback must never break the call path */\n }\n}\n\n/** Fire tool telemetry on BOTH the unified `onEvent` (tagged `type:'tool'`) and the\n * legacy `onToolEvent` shim (untagged). Each is independently throw-guarded, so a\n * throwing hook on one never starves the other or the call path. */\nexport function emitToolEvent(win: unknown, e: ToolEvent): void {\n emitEvent(win, { type: 'tool', ...e });\n const cb = mfGlobal(win).onToolEvent;\n if (typeof cb !== 'function') return;\n try {\n cb(e);\n } catch {\n /* legacy shim: a host telemetry callback must never break the call path */\n }\n}\n\n/* ───────────────────────────── mf.* contracts ──────────────────────────── */\n\n/**\n * The `mf.*` tool descriptors. Authored HERE so the agent's understanding of them is\n * ours and lives in one place — an integration spends no instruction budget teaching\n * what they mean. Only advertised for the resolvers the host actually supplied.\n */\nfunction mfTools(win: unknown): HostTool[] {\n const { document, artifact } = mfGlobal(win).resolve ?? {};\n const out: HostTool[] = [];\n if (typeof document === 'function') {\n out.push({\n name: 'mf.resolveDocument',\n description:\n 'Resolve a matterfact document (dossier, report, briefing) that is NOT on the ' +\n 'current page to a concrete id. Call it with the document type and a key (e.g. a ' +\n 'ticker) when the site map shows the document lives on another route. Returns ' +\n '{id, label, href}. Cite the result inline as ' +\n '<MFRef kind=\"document\" id=\"<id>\" label=\"<label>\" /> — it renders as a chip that ' +\n 'opens the document in the side panel; href is its \"open on page\" deeplink.',\n inputSchema: {\n type: 'object',\n properties: {\n doctype: { type: 'string' },\n key: { type: 'string' },\n },\n required: ['doctype', 'key'],\n },\n readOnly: true,\n confirm: 'auto',\n });\n }\n if (typeof artifact === 'function') {\n out.push({\n name: 'mf.resolveArtifact',\n description:\n 'Resolve a matterfact artifact (an interactive board) that is NOT co-embedded on ' +\n 'the current page to a read grant. Call it with the artifact slug. Returns ' +\n '{id, owner, token, label}; the grant is applied for you. Cite the result inline ' +\n 'as <MFRef kind=\"artifact\" id=\"<id>\" label=\"<label>\" /> — it renders as a chip ' +\n 'that opens the artifact in the side panel.',\n inputSchema: {\n type: 'object',\n properties: { slug: { type: 'string' } },\n required: ['slug'],\n },\n readOnly: true,\n confirm: 'auto',\n });\n }\n return out;\n}\n\n/* ───────────────────────────── app.* host tools ────────────────────────── */\n\nconst APP_NAME_RE = /^[A-Za-z0-9._-]+$/;\n\n/** Normalise a host tool name into the `app.` namespace so it can never collide with\n * `hoist.*`/`mf.*`. A name already prefixed `app.` is kept; anything else is prefixed.\n * Names outside the safe charset are dropped by the caller. */\nfunction appName(name: string): string {\n return name.startsWith('app.') ? name : `app.${name}`;\n}\n\nfunction appTools(win: unknown): HostTool[] {\n const defs = mfGlobal(win).tools;\n if (!Array.isArray(defs)) return [];\n const out: HostTool[] = [];\n for (const d of defs) {\n const raw = (d?.name ?? '').trim();\n if (!raw || typeof d.handler !== 'function') continue;\n const name = appName(raw);\n if (!APP_NAME_RE.test(name)) continue;\n out.push({\n name,\n description: String(d.description ?? `Run the host tool ${name}.`),\n inputSchema: d.inputSchema ?? { type: 'object', properties: {} },\n readOnly: false,\n confirm: d.confirm === 'auto' ? 'auto' : 'required',\n });\n }\n return out;\n}\n\n/* ───────────────────────────── advertise ───────────────────────────────── */\n\n/**\n * The merged tool list this page offers the agent: hoist adapter tools, then the\n * `mf.*` contracts for supplied resolvers, then host `app.*` tools. matterfact-defined\n * names win on collision (an `app.*` normalisation can't produce one, but a host that\n * literally named a tool `mf.foo` in `app.` space still can't shadow a real `mf.*`).\n * Deduped by name, first-wins, capped at MAX_TOOLS.\n *\n * Degrade-safe: any surprise ⇒ the entries built so far, never a throw — a caller can\n * call this unconditionally.\n */\nexport function advertise(\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): HostTool[] {\n const merged: HostTool[] = [];\n const seen = new Set<string>();\n const push = (tools: HostTool[]) => {\n for (const t of tools) {\n if (seen.has(t.name)) continue;\n seen.add(t.name);\n merged.push(t);\n }\n };\n try {\n push(advertiseTools(win));\n } catch {\n /* hoist adapter already degrade-safe; belt and suspenders */\n }\n try {\n push(mfTools(win));\n push(appTools(win));\n } catch {\n /* fall through with whatever merged so far */\n }\n return merged.slice(0, MAX_TOOLS);\n}\n\n/* ───────────────────────────── execute ─────────────────────────────────── */\n\nfunction timeout(ms: number): Promise<never> {\n return new Promise((_, reject) =>\n setTimeout(() => reject(new Error('host tool timed out')), ms),\n );\n}\n\n/** Redact anything a host handler returns before it can leave the page. Strings are\n * scrubbed directly; structured results are JSON round-tripped through the scrubber so\n * an email tucked in a field can't ride out. */\nfunction redactResult(value: unknown): unknown {\n if (value === undefined || value === null) return value;\n if (typeof value === 'string') return redact(value);\n try {\n return JSON.parse(redact(JSON.stringify(value)));\n } catch {\n return redact(String(value));\n }\n}\n\n/**\n * Run one host tool call. Dispatches by class:\n * - `hoist.*` → the existing adapter (keeps its OWN execute-time policy + route\n * re-checks — this module does not second-guess it);\n * - `mf.*` → the matching `resolve.*` function;\n * - `app.*` → the matching host `tools[].handler`.\n *\n * Handlers are read FRESH off the global on every call (so a host swapping a handler\n * body never needs a remount) and bounded at HOST_HANDLER_TIMEOUT_MS. NEVER throws:\n * any surprise becomes `{ok:false, error}`, redacted.\n */\nexport async function execute(\n call: ToolCall,\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): Promise<{ ok: boolean; result?: unknown; error?: string }> {\n const cls = toolClass(call.name);\n try {\n if (cls === 'hoist') {\n // Synchronous adapter; keep its result/redaction exactly as-is.\n return executeHostTool(call, win);\n }\n\n const handler = resolveHandler(win, call.name);\n if (!handler) return { ok: false, error: 'unknown tool' };\n\n const result = await Promise.race([\n Promise.resolve(handler(call.args ?? {})),\n timeout(HOST_HANDLER_TIMEOUT_MS),\n ]);\n return { ok: true, result: redactResult(result) };\n } catch (e) {\n return {\n ok: false,\n error: redact(e instanceof Error ? e.message : 'host tool failed'),\n };\n }\n}\n\n/** The host function backing an `mf.*`/`app.*` name, or undefined. */\nfunction resolveHandler(\n win: unknown,\n name: string,\n): ((args: Record<string, unknown>) => unknown) | undefined {\n const mf = mfGlobal(win);\n if (name === 'mf.resolveDocument') return mf.resolve?.document as never;\n if (name === 'mf.resolveArtifact') return mf.resolve?.artifact as never;\n if (name.startsWith('app.')) {\n const def = (mf.tools ?? []).find((d) => appName((d?.name ?? '').trim()) === name);\n return def?.handler;\n }\n return undefined;\n}\n","import {\n computeAccessibleName,\n getRole,\n isDisabled,\n} from 'dom-accessibility-api';\n\n/**\n * Role, name, visibility, interactability, state.\n *\n * WHAT WE ADOPTED: role and accessible name come from `dom-accessibility-api`\n * (MIT, zero deps) — the engine behind testing-library's `getByRole`. Accessible\n * name is a genuinely hard spec (accname walks aria-labelledby graphs, ::before\n * content, <label> associations, alt/title fallbacks, and recursive\n * name-from-content) and a hand-rolled version is wrong in ways you only discover\n * on a customer's page.\n *\n * WHAT WE BUILT: everything below that. Visibility and pointer-events are ~20 lines\n * from first principles (see `isVisible`/`receivesPointerEvents`) and the state\n * reads are direct DOM/ARIA reads, so we vendored nothing and took on no\n * Apache-2.0 attribution obligation.\n */\n\n/** A memoised `getComputedStyle`, shaped to be passed straight to accname. */\nexport type StyleOf = typeof window.getComputedStyle;\n\n/**\n * One computed style per element per snapshot.\n *\n * Not a micro-optimisation: `computeAccessibleName` calls back into\n * getComputedStyle for every descendant it walks while building a name from\n * content, so on a page of nested divs the uncached cost is quadratic-ish. The\n * cache is per-snapshot (a fresh WeakMap each walk), so it can never go stale\n * across snapshots.\n */\nexport function createStyleCache(): StyleOf {\n const cache = new WeakMap<Element, CSSStyleDeclaration>();\n return ((el: Element, pseudo?: string | null): CSSStyleDeclaration => {\n // Pseudo-element lookups are rare and must not poison the element cache.\n if (pseudo) return window.getComputedStyle(el, pseudo);\n let style = cache.get(el);\n if (!style) {\n style = window.getComputedStyle(el);\n cache.set(el, style);\n }\n return style;\n }) as StyleOf;\n}\n\n/**\n * Does this environment do layout at all?\n *\n * In a browser the root element always has a box. In jsdom — which has no layout\n * engine — *everything* reports zero client rects, so a box-based visibility check\n * would hide the entire page and our tests would assert on an empty snapshot. So we\n * feature-detect layout once per walk and fall back to style-only visibility when\n * there is none. This is a test-environment concession, stated out loud rather than\n * hidden behind a mock.\n */\nexport function hasLayout(): boolean {\n return document.documentElement.getClientRects().length > 0;\n}\n\n/**\n * Visible enough to be worth telling the agent about.\n *\n * `display` and `visibility` are read from the computed style, which already\n * accounts for inheritance — and because the walk is top-down and prunes whole\n * subtrees, we never pay for an ancestor walk. `display: contents` is the one\n * subtlety: such an element generates no box of its own but its children do, so it\n * must not be treated as invisible or we would drop a real subtree.\n */\nexport function isVisible(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n const display = style.display;\n if (display === 'none') return false;\n\n const visibility = style.visibility;\n if (visibility === 'hidden' || visibility === 'collapse') return false;\n\n // `opacity: 0` is a standard \"hide from sight, keep for a11y\" technique. It still\n // reports a box, so the area check below misses it. We treat fully-transparent as\n // hidden; a partially-transparent element is genuinely on screen.\n if (Number(style.opacity) === 0) return false;\n\n // A `display: contents` element generates no box of its own but its children do,\n // so it must not be judged by its own (nonexistent) geometry — we let it through\n // and test each child on its own merits.\n if (layout && display !== 'contents') {\n // Area, not merely \"has a box\": `width:0;height:0;overflow:hidden` is one of the\n // commonest ways to hide a thing, and such an element still reports a client\n // rect. This is the check Playwright's own isVisible() makes.\n const box = el.getBoundingClientRect();\n if (box.width <= 0 || box.height <= 0) return false;\n\n // The sr-only / visually-hidden family: `clip: rect(0 0 0 0)` and its modern\n // `clip-path: inset(50%)` shrink the element to nothing while keeping a 1px box,\n // and `position:absolute; left:-9999px` parks it far off any real page. All three\n // are \"screen-reader only\" idioms — present for a11y, not for sight — so an agent\n // reading the page should skip them too. (getClientRects().length === 0 catches\n // the clipped ones; the far-offscreen check catches the parked ones.)\n if (el.getClientRects().length === 0) return false;\n if (box.right < -2000 || box.bottom < -2000) return false;\n }\n\n return true;\n}\n\n/**\n * Can a pointer actually reach it?\n *\n * `pointer-events` is an INHERITED property, so the computed value on the element\n * already encodes every ancestor's `pointer-events: none` — and correctly honours a\n * descendant that opts back in with `pointer-events: auto`. That is the whole check:\n * no ancestor walk, no hit-test. We deliberately do NOT test for occlusion (is\n * something painted on top of it) the way Playwright's actionability check does —\n * we are describing the page, not clicking it, and an element under a sticky header\n * is still worth telling the agent about.\n */\nexport function receivesPointerEvents(style: CSSStyleDeclaration): boolean {\n return style.pointerEvents !== 'none';\n}\n\n/** Roles that are inherently operable. */\nconst INTERACTIVE_ROLES = new Set([\n 'button',\n 'checkbox',\n 'combobox',\n 'link',\n 'listbox',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'searchbox',\n 'slider',\n 'spinbutton',\n 'switch',\n 'tab',\n 'textbox',\n 'treeitem',\n]);\n\n/** Tags that are operable regardless of what role they compute to. */\nconst INTERACTIVE_TAGS = new Set([\n 'BUTTON',\n 'INPUT',\n 'SELECT',\n 'TEXTAREA',\n 'SUMMARY',\n]);\n\n/** `contenteditable` — present and not explicitly \"false\" (covers \"\", \"true\", \"plaintext-only\"). */\nexport function isEditable(el: Element): boolean {\n const v = el.getAttribute('contenteditable');\n return v !== null && v !== 'false';\n}\n\n/**\n * Is this element something the user can operate?\n *\n * THIS IS THE INTERESTING FUNCTION, so here is the reasoning in full.\n *\n * The obvious way to answer it — ask the DOM what event listeners are attached —\n * IS NOT AVAILABLE. `getEventListeners()` exists only inside DevTools (and via CDP).\n * We are ordinary page JS on a customer's website, so every `addEventListener` a\n * React, Vue or Svelte app ever registered is, to us, completely invisible. This is\n * precisely where the browser-use style of in-page DOM extraction degrades on real\n * apps: it cannot see a single handler, so it either misses the app's controls or\n * guesses wildly. We therefore never ask \"does it have a handler\"; we ask \"does it\n * PRESENT ITSELF as operable\", in four descending tiers of confidence:\n *\n * 1. TAG SEMANTICS (certain). button, input, select, textarea, summary, a[href].\n * 2. COMPUTED ROLE (certain). role=button|link|checkbox|… whether implicit or\n * author-supplied. A div with role=\"button\" is a\n * button as far as the platform, a screen reader,\n * and the user are concerned.\n * 3. FOCUSABILITY (strong). tabindex >= 0, or contenteditable. An app that\n * made a div keyboard-reachable did so on purpose.\n * 4. `cursor: pointer` (WEAK). Last resort, and the reason for the guard below.\n *\n * Tier 4 needs care, because `cursor` is INHERITED: a card with `cursor: pointer`\n * makes every span, every icon and every text node inside it report `pointer` too,\n * and a naive check would mint a ref for each of them and drown the snapshot. So we\n * only count the element that *introduced* the pointer cursor — the one whose parent\n * did not already have it. That is almost exactly the clickable card itself.\n */\nexport function isInteractive(\n el: Element,\n role: string | null,\n style: CSSStyleDeclaration,\n parentStyle: CSSStyleDeclaration | null,\n): boolean {\n const tag = el.tagName;\n\n // 1. tag semantics\n // An <a href> is interactive, but a hrefless <a> is NOT a dead end — it may be a\n // JS-nav link, an <a role=\"button\">, or a Bootstrap `.btn` anchor. So href is a\n // positive signal, not a gate: fall through to the role/tabindex/cursor tiers\n // rather than returning false and dropping every SPA link.\n if (tag === 'A' && el.hasAttribute('href')) return true;\n if (INTERACTIVE_TAGS.has(tag)) return true;\n\n // 2. computed role\n if (role !== null && INTERACTIVE_ROLES.has(role)) return true;\n\n // 3. focusability\n const tabindex = el.getAttribute('tabindex');\n if (tabindex !== null && Number(tabindex) >= 0) return true;\n if (isEditable(el)) return true;\n\n // 4. cursor: pointer, but only where it originates (see above)\n if (style.cursor === 'pointer' && parentStyle?.cursor !== 'pointer')\n return true;\n\n return false;\n}\n\n/**\n * Roles whose accessible name IS their text content (ARIA \"Name From: contents\").\n *\n * This is the exact list from the ARIA spec, and it earns its place: it is what tells\n * the walk that the \"Export CSV\" inside `<button>Export CSV</button>` has ALREADY been\n * emitted, as the button's name, and must not be repeated as a child text node.\n *\n * The tempting shortcut — \"skip any text that appears inside the parent's name\" — is\n * wrong, and wrong in a way that silently deletes content: a card labelled\n * `aria-label=\"Acme Corp order\"` containing the text \"Acme Corp\" would lose it,\n * because one is a substring of the other by coincidence. Ask the role, not the string.\n */\nexport const NAME_FROM_CONTENT = new Set([\n 'button',\n 'cell',\n 'checkbox',\n 'columnheader',\n 'gridcell',\n 'heading',\n 'link',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'row',\n 'rowheader',\n 'switch',\n 'tab',\n 'tooltip',\n 'treeitem',\n]);\n\n/* ─────────────────────────────── state ────────────────────────────────── */\n\n/** Roles whose content IS the user's data. We report that a value exists, never what it is. */\nconst VALUE_ROLES = new Set(['textbox', 'searchbox', 'spinbutton']);\n\n/**\n * Roles we refuse to descend into, because their children/content ARE the value.\n *\n * A `<textarea>`'s child text node is literally what the user typed; a\n * contenteditable's subtree is the document they are writing. Refusing to walk in is\n * how \"never emit a value\" is enforced STRUCTURALLY, rather than by remembering to\n * filter at every emit site.\n *\n * `<select>` is deliberately NOT here. Its options are a bounded, author-defined\n * enumeration — the affordance the agent most needs (\"what can I set this to\"), not\n * the free-text user data the opaque rule exists to contain. The snapshot emits them\n * directly instead (capped, selected one marked): see emitSelectOptions in\n * snapshot.ts.\n */\nconst OPAQUE_TAGS = new Set(['INPUT', 'TEXTAREA']);\n\nexport function isOpaque(el: Element): boolean {\n return OPAQUE_TAGS.has(el.tagName) || isEditable(el);\n}\n\n/**\n * Has the user put something in this field?\n *\n * `.value` is read and immediately thrown away — only its LENGTH escapes. This is\n * the single most useful bit about a form (\"is the email box already filled in?\")\n * and the single most dangerous string on the page, so it is reduced to one bit at\n * the point of reading and never travels.\n */\nfunction isFilled(el: Element, role: string): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA') {\n if (!VALUE_ROLES.has(role)) return false; // checkbox.value is \"on\" — meaningless\n return ((el as HTMLInputElement).value ?? '').length > 0;\n }\n if (isEditable(el)) return (el.textContent ?? '').trim().length > 0;\n return false;\n}\n\nfunction ariaFlag(el: Element, attr: string): 'true' | 'mixed' | null {\n const v = el.getAttribute(attr);\n if (v === 'true') return 'true';\n if (v === 'mixed') return 'mixed';\n return null;\n}\n\n/**\n * The bracketed attributes, in Playwright's order:\n * [checked] [disabled] [expanded] [level=N] [pressed] [selected]\n * plus our one addition, [filled] — see isFilled. `[ref=eN]` is appended by the\n * caller and always comes last.\n */\nexport function states(el: Element, role: string): string {\n const out: string[] = [];\n const tag = el.tagName;\n\n // checked\n if (tag === 'INPUT' && (role === 'checkbox' || role === 'radio')) {\n if ((el as HTMLInputElement).checked) out.push('[checked]');\n } else {\n const checked = ariaFlag(el, 'aria-checked');\n if (checked === 'mixed') out.push('[checked=mixed]');\n else if (checked === 'true') out.push('[checked]');\n }\n\n // disabled — dom-accessibility-api handles fieldset/optgroup inheritance and aria-disabled\n if (isDisabled(el)) out.push('[disabled]');\n\n // expanded — <summary> reflects its parent <details>, which has no ARIA attribute\n const expanded = el.getAttribute('aria-expanded');\n if (expanded === 'true' || expanded === 'false') {\n if (expanded === 'true') out.push('[expanded]');\n } else if (tag === 'SUMMARY') {\n const details = el.parentElement;\n if (\n details?.tagName === 'DETAILS' &&\n (details as HTMLDetailsElement).open\n ) {\n out.push('[expanded]');\n }\n }\n\n // level\n if (role === 'heading') {\n const aria = el.getAttribute('aria-level');\n const level = aria ? Number(aria) : Number(tag[1]);\n if (Number.isFinite(level) && level > 0) out.push(`[level=${level}]`);\n }\n\n // pressed\n const pressed = ariaFlag(el, 'aria-pressed');\n if (pressed === 'mixed') out.push('[pressed=mixed]');\n else if (pressed === 'true') out.push('[pressed]');\n\n // selected\n if (el.getAttribute('aria-selected') === 'true') out.push('[selected]');\n\n // filled (ours — a boolean, never the value)\n if (isFilled(el, role)) out.push('[filled]');\n\n return out.join(' ');\n}\n\n/* ─────────────────────────── role & name ──────────────────────────────── */\n\n/**\n * The computed role, with one correction.\n *\n * `getRole` follows HTML-AAM and returns null for a contenteditable div — but every\n * real browser exposes it to assistive tech as a textbox, and that is what it is to\n * the user and to the agent. We say textbox.\n */\nexport function roleOf(el: Element): string | null {\n if (isEditable(el)) return 'textbox';\n return getRole(el);\n}\n\n/**\n * Selector for anything whose CONTENT is the user's data — a form control, a\n * contenteditable, a valued widget, or a host-marked private region.\n */\nconst UNTRUSTED_CONTENT =\n 'input,textarea,select,[contenteditable=\"\"],[contenteditable=\"true\"],[aria-valuetext],[data-mf-private]';\n\n/**\n * Would computing this element's ACCESSIBLE NAME read the user's data?\n *\n * This is the leak the structural `isOpaque` walk cannot see. `computeAccessibleName`\n * runs its OWN descendant walk, inside dom-accessibility-api, that knows nothing about\n * our opaque set or `data-mf-private` — it will happily read `input.value`,\n * `aria-valuetext`, a contenteditable's text, or a private subtree, and fold it into\n * the name of a name-from-content ANCESTOR or any `aria-labelledby` referrer. So a\n * value our walk refuses to enter re-enters through the parent's name.\n *\n * Two vectors, both handled:\n * - name-from-content: the name is built from descendant text. If any descendant is\n * untrusted, the name is tainted.\n * - aria-labelledby: the name is pulled from a referenced element. If any referent\n * is (or contains) untrusted content, the name is tainted.\n *\n * `aria-label` and `title` are author-written static strings; a site that copies its\n * own secret into one is exposing it deliberately and we cannot defend that. The\n * automatic-computation vectors are the ones we must close.\n */\nfunction nameIsUntrusted(el: Element): boolean {\n const labelledby = el.getAttribute('aria-labelledby');\n if (labelledby) {\n for (const id of labelledby.split(/\\s+/)) {\n if (!id) continue;\n const ref = el.ownerDocument.getElementById(id);\n if (!ref) continue;\n if (\n ref.matches(UNTRUSTED_CONTENT) ||\n ref.querySelector(UNTRUSTED_CONTENT)\n ) {\n return true;\n }\n }\n return false;\n }\n // No explicit label attributes → the name, if any, is name-from-content.\n if (el.hasAttribute('aria-label')) return false;\n return el.querySelector(UNTRUSTED_CONTENT) !== null;\n}\n\nexport function nameOf(el: Element, styleOf: StyleOf): string {\n const name = computeAccessibleName(el, {\n getComputedStyle: styleOf,\n // jsdom logs a console error if you claim pseudo-element support it doesn't have.\n computedStyleSupportsPseudoElements: false,\n });\n if (!name) return '';\n\n // A tainted name would leak a value or a private string. Drop it entirely and let\n // the element stand on its role + ref. Losing a name costs the agent a little\n // context; keeping a leaked one is a breach. The trade is not close.\n if (nameIsUntrusted(el)) {\n // Preserve an explicit author label if one exists and is not itself the taint —\n // aria-labelledby taints were already caught above, so any aria-label here is safe.\n return el.getAttribute('aria-label') || '';\n }\n return name;\n}\n","import type { ElementRef } from '../protocol';\n\n/**\n * Element handles.\n *\n * The mechanism is Playwright's, deliberately (see protocol.ts): the agent never\n * learns a selector, it learns `e12`, and `e12` is turned back into an element\n * HERE, in the page, by us.\n *\n * Three properties matter and all are load-bearing:\n *\n * 1. THE MAP IS A WeakMap, NOT AN EXPANDO ON THE ELEMENT. An earlier version\n * stamped `el._mfRef`. Non-enumerable, so invisible to `Object.keys`/spreads/\n * `JSON.stringify` — but STILL reachable via `Object.getOwnPropertyNames` and\n * `Reflect.ownKeys`, and, worse, it parked the element's accessible name on the\n * customer's live DOM node indefinitely. A `WeakMap<Element, RefEntry>` mutates\n * nothing on their objects, is invisible to every enumeration and serialization\n * API without exception, cannot collide with a property the host already has,\n * and still gives us node-identity survival across GC for free.\n *\n * 2. A REF IS REGENERATED WHEN ROLE OR NAME CHANGES. Frameworks recycle DOM nodes:\n * a virtualised list scrolls, and the <button> that said \"Approve\" is the very\n * same node that now says \"Delete\". Keying the ref on (role, name) means that\n * node gets a NEW id and the old id resolves to nothing.\n *\n * 3. A REF IS SCOPED TO ONE SNAPSHOT GENERATION. (2) is necessary but not\n * sufficient: two icon-only \"Delete\" buttons in a virtualised table have the\n * SAME (role, name), so a recycled node whose role+name are unchanged would keep\n * its ref and silently retarget a different logical row. So a ref also carries\n * the generation it was minted in, and resolveRef refuses a ref from an older\n * generation — the agent must re-snapshot to get a fresh, valid handle. Loud\n * staleness beats silent retargeting.\n */\n\ninterface RefEntry {\n id: ElementRef;\n /** role + name at mint time. Changes here invalidate the ref. */\n key: string;\n /** The snapshot generation this ref belongs to. */\n gen: number;\n}\n\n/**\n * Monotonic across snapshots, never reused — like Playwright's. An id is only ever\n * handed out once in a page's lifetime, so a stale ref can never be *silently*\n * correct by colliding with a newer element; it just resolves to null.\n */\nlet counter = 0;\n\n/** Bumped once per full snapshot. A ref is only valid within its own generation. */\nlet generation = 0;\n\n/**\n * Element identity, off the host's objects entirely. Keyed by element so a recycled\n * node is recognised across snapshots; the entry carries the (role,name) key and the\n * generation for the two staleness checks above.\n */\nconst entries = new WeakMap<Element, RefEntry>();\n\n/** id -> element, for resolution. Rebuilt each generation from exactly what was emitted. */\nconst registry = new Map<ElementRef, Element>();\n\n/** Called once per FULL snapshot, before the walk. A region read does NOT call this. */\nexport function beginSnapshot(): void {\n generation++;\n registry.clear();\n}\n\n/**\n * Mint (or reuse) the ref for an element and register it for resolution.\n * Only ever called for elements that are visible AND receive pointer events.\n */\nexport function refFor(el: Element, role: string, name: string): ElementRef {\n const key = `${role} ${name}`;\n\n let entry = entries.get(el);\n if (!entry || entry.key !== key) {\n entry = { id: `e${++counter}`, key, gen: generation };\n entries.set(el, entry);\n } else {\n // Same node, same identity — carry it into the current generation so a fresh\n // snapshot re-validates a still-present element rather than orphaning it.\n entry.gen = generation;\n }\n\n registry.set(entry.id, el);\n return entry.id;\n}\n\n/**\n * Turn a ref back into an element.\n *\n * Three ways this returns null, each deliberate:\n * - unknown id (never minted, or from a cleared generation) → not in the registry;\n * - the element left the page → `isConnected` is false. A detached node still\n * answers every question (role, name, a zero box), so without this an action\n * would silently no-op against a ghost;\n * - the ref is from an OLDER generation → its entry.gen has been superseded. This is\n * what stops a recycled-node retarget: the agent is told the handle is stale and\n * must re-snapshot, rather than acting on the wrong row.\n */\nexport function resolveRef(ref: ElementRef): Element | null {\n const el = registry.get(ref);\n if (!el) return null;\n if (!el.isConnected) {\n registry.delete(ref);\n return null;\n }\n const entry = entries.get(el);\n if (!entry || entry.id !== ref || entry.gen !== generation) return null;\n return el;\n}\n\n/** Test-only: reset counters so refs are deterministic per test. */\nexport function __resetRefs(): void {\n counter = 0;\n generation = 0;\n registry.clear();\n}\n\n/**\n * Drop every ref's resolvability, without touching `counter`/`generation` — an old\n * id must never come back valid after this (unlike `__resetRefs`, which is test-only\n * determinism and would let ids collide again). Called from `context.ts`'s `stop()`\n * so a ref minted before a `pageContext:false` opt-out (or before an unmount) can't\n * be resolved afterward — belt-and-suspenders alongside `sendRegion`'s own\n * `pageContextOn` gate, in case a stale ref is ever replayed.\n */\nexport function clearRefs(): void {\n registry.clear();\n}\n","import { isDisabled, isInaccessible } from 'dom-accessibility-api';\n\nimport { isPrivate, redact } from '../context';\nimport {\n createStyleCache,\n hasLayout,\n isInteractive,\n NAME_FROM_CONTENT,\n isOpaque,\n isVisible,\n nameOf,\n receivesPointerEvents,\n roleOf,\n states,\n type StyleOf,\n} from './a11y';\nimport { beginSnapshot, refFor } from './refs';\n\nexport { resolveRef, clearRefs } from './refs';\n\n/**\n * The page, as the agent sees it.\n *\n * We emit Playwright's ARIA-snapshot YAML, and that choice is the point of this\n * file. It is not our format: it is the one the frontier models have seen most, via\n * playwright-mcp, so a model already knows how to read it and already knows that\n * `[ref=e12]` is the thing you hand back to act. Inventing our own dialect here\n * would cost us capability for nothing.\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - list:\n * - listitem:\n * - link \"Order #1043\" [ref=e8]\n * - text: \"Unpaid\"\n * - button \"Export CSV\" [ref=e12]\n *\n * Not raw HTML: a real page is tens of thousands of tokens of div soup, gives the\n * model nothing to act with, and is a prompt-injection firehose.\n */\n\n/* ─────────────────────────────── budgets ──────────────────────────────── */\n\n/**\n * These exist because the failure they prevent is not \"the snapshot is big\", it is\n * \"the agent confidently tells the user about a button that does not exist\". A model\n * given a silently-cut-off page has no way to know it was cut off, so it fills the\n * gap. Hence: hard caps, and `truncated: true` travels with the payload so the agent\n * can be TOLD it is not seeing everything.\n *\n * The two caps do different jobs, and conflating them is how you get a bad snapshot:\n *\n * MAX_LINES bounds the MODEL'S CONTEXT. 800 lines of ARIA YAML is ~12 KB, a few\n * thousand tokens — a dense dashboard, and about as much page as is useful to\n * reason over at once.\n *\n * MAX_NODES bounds the MAIN THREAD. It counts elements *visited*, most of which are\n * the wrapper divs of a modern app and emit nothing at all. Measured in Chrome on a\n * deeply-nested 52k-element table, visiting 4000 nodes costs ~25ms of walk. Set it\n * to 1500 (a tempting round number) and a div-soup page truncates at ~460 lines —\n * we would stop while HALF the line budget was still unspent, and tell the agent it\n * could not see a page we had simply given up on early.\n */\nconst MAX_NODES = 4000;\nconst MAX_LINES = 800;\nconst MAX_NAME = 120;\nconst MAX_TEXT = 120;\n/**\n * Max `<option>`s emitted per `<select>` before the rest is summarised. A country or\n * timezone picker runs to hundreds; the option list is an affordance to show, not a\n * reason to spend the line budget. The selected option is always in the first slice\n * in practice, but if a huge list has its selection past the cap the \"+N more\"\n * marker tells the agent it isn't seeing every choice.\n */\nconst MAX_OPTIONS = 25;\n\n/* ─────────────────────────────── model ────────────────────────────────── */\n\ninterface AriaNode {\n role: string;\n /** Raw accessible name. Redacted and truncated at render time, not here. */\n name: string;\n /** Pre-rendered bracket attributes, `[checked] [ref=e5]`. */\n props: string;\n children: (AriaNode | string)[];\n}\n\ninterface Walk {\n styleOf: StyleOf;\n layout: boolean;\n nodes: number;\n lines: number;\n truncated: boolean;\n /** Called for every element that gets a ref, so a caller can note which are on screen. */\n onRef?: (ref: string, el: Element) => void;\n}\n\n/** Elements that carry no meaning of their own: their children stand in for them. */\nconst TRANSPARENT = new Set(['generic', 'presentation', 'none']);\n\n/**\n * Never walked. `<script>`/`<style>`/`<noscript>` are the obvious ones; `<svg>` is\n * here because its innards are hundreds of `<path>` nodes of pure noise — any title\n * it carries is already folded into its parent's accessible name by accname.\n */\nconst SKIP_TAGS = new Set([\n 'SCRIPT',\n 'STYLE',\n 'NOSCRIPT',\n 'TEMPLATE',\n 'SVG',\n 'HEAD',\n 'LINK',\n 'META',\n 'BASE',\n]);\n\n/* ─────────────────────────────── walking ──────────────────────────────── */\n\n/** False once any budget is spent — the caller stops and we mark the snapshot truncated. */\nfunction withinBudget(w: Walk): boolean {\n if (w.nodes >= MAX_NODES || w.lines >= MAX_LINES) {\n w.truncated = true;\n return false;\n }\n return true;\n}\n\n/**\n * Is this element ours?\n *\n * The widget must never appear in its own snapshot: the agent describing its own\n * chat window back to itself is both useless and a lovely little feedback loop.\n */\nfunction isOurs(el: Element): boolean {\n return el.id === 'matterfact-embed' || el.hasAttribute('data-mf-embed');\n}\n\n/**\n * Hidden from assistive tech — and therefore from us.\n *\n * This is `isInaccessible()`'s rule set applied ONE NODE AT A TIME, top-down.\n * `isInaccessible()` itself walks every ancestor on every call, which over a whole\n * tree is the O(n·depth) blow-up the budget forbids; because we descend from the\n * root and prune the entire subtree the moment a node is hidden, the composition of\n * these local checks is exactly equivalent and costs O(1) per node. (We still call\n * the real thing once, on the root, as a backstop.)\n */\nfunction isHidden(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n if (el.getAttribute('aria-hidden') === 'true') return true;\n if (el.hasAttribute('hidden') || el.hasAttribute('inert')) return true;\n return !isVisible(el, style, layout);\n}\n\n/**\n * The nodes a parent should walk.\n *\n * An open shadow root REPLACES its host's light children — those only reach the\n * screen by being slotted, and we pick them up when we hit the `<slot>` that pulls\n * them in. Walking both would emit every web component's contents twice. A closed\n * shadow root is opaque to us by design, exactly as it is to the rest of the page.\n */\nfunction childrenOf(el: Element): ArrayLike<Node> {\n if (el.shadowRoot) return el.shadowRoot.childNodes;\n if (el.tagName === 'SLOT') {\n const assigned = (el as HTMLSlotElement).assignedNodes({ flatten: true });\n // An unfilled slot renders its own fallback content.\n if (assigned.length) return assigned;\n }\n return el.childNodes;\n}\n\n/** ArrayLike + index loop, not for-of: a NodeList needs `DOM.Iterable`, and copying one to iterate it allocates an array per element for nothing. */\nfunction visitChildren(\n el: Element,\n parent: AriaNode,\n style: CSSStyleDeclaration,\n w: Walk,\n): void {\n const children = childrenOf(el);\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (child) visitNode(child, parent, style, w);\n }\n}\n\nfunction visitText(node: Text, parent: AriaNode, w: Walk): void {\n const text = (node.nodeValue ?? '').replace(/\\s+/g, ' ').trim();\n if (!text) return;\n\n // The text of a button, a link or a heading IS its accessible name — we already\n // emitted it on the parent's line, and repeating it as a child would double the\n // tokens and imply a second, separate thing on the page. Decided by ROLE, never by\n // string-matching against the name (see NAME_FROM_CONTENT).\n if (NAME_FROM_CONTENT.has(parent.role)) return;\n\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(text);\n}\n\n/**\n * A native `<select>`, expanded into its options.\n *\n * The generic walk can't do this: a closed select's `<option>`s have no layout box,\n * so isVisible would prune them. Yet the options are exactly the affordance the agent\n * needs — \"what can I set this to\" — and, unlike an `<input>` value, they are a\n * bounded, author-defined set rather than free text the user typed. So we emit them,\n * and mark the selected one: it names one of the choices we are ALREADY showing, so\n * it reveals nothing a human looking at the control wouldn't see. Labels are redacted\n * at render time like every other name; the list is capped; a select the host deems\n * sensitive is hidden the usual way (`data-mf-private`) and never reaches here.\n *\n * `.options` is the flat HTMLOptionsCollection, so `<optgroup>` nesting is already\n * flattened for us; `<select multiple>` (role listbox) works through the same path.\n */\n/** One option, in Playwright's shape: `- option \"label\" [disabled] [selected]`. The\n * name is trimmed so a whitespace-only option renders `- option` (no \"\"). Disabled is\n * `:disabled` (which catches an <optgroup disabled> that isDisabled/opt.disabled miss)\n * OR isDisabled (which adds aria-disabled). Bracket order matches states(): [disabled]\n * before [selected]. */\nfunction optionNode(opt: HTMLOptionElement): AriaNode {\n const disabled = opt.matches(':disabled') || isDisabled(opt);\n return {\n role: 'option',\n name: (opt.label || opt.textContent || '').trim(),\n props:\n (disabled ? ' [disabled]' : '') + (opt.selected ? ' [selected]' : ''),\n children: [],\n };\n}\n\nfunction emitSelectOptions(\n select: HTMLSelectElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const options = select.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n // The selected option IS the field's current value — the one option the agent most\n // needs. In a long list (country, timezone) the selection can sit past the cap, so\n // the front slice above would show none marked [selected]. Surface any selected\n // option that fell outside the cap regardless, and don't double-count it as hidden.\n let extraSelected = 0;\n const selected = select.selectedOptions;\n for (let i = 0; i < selected.length; i++) {\n const opt = selected[i];\n if (opt && opt.index >= shown && !isPrivate(opt)) {\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(optionNode(opt));\n extraSelected++;\n }\n }\n const remaining = options.length - shown - extraSelected;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\n/**\n * An `<input list=\"…\">`'s datalist suggestions.\n *\n * Same affordance as a `<select>`'s options — a bounded, author-defined set the user\n * can pick — but surfaced under the (still value-opaque) input, because the\n * `<datalist>` element is display:none, so the generic walk never reaches it. The\n * input's own value stays hidden; only the suggestion labels are emitted (redacted at\n * render like every name, and capped). No [selected] — a datalist has no current\n * choice, only completions.\n */\nfunction emitDatalistOptions(\n input: HTMLInputElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const list = input.list as HTMLDataListElement | null;\n if (!list) return;\n const options = list.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n const remaining = options.length - shown;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\nfunction visitElement(\n el: Element,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (!withinBudget(w)) return;\n if (SKIP_TAGS.has(el.tagName) || isOurs(el)) return;\n\n // Privacy first, before we so much as compute a style: `data-mf-private` and\n // password/hidden inputs take their whole subtree with them.\n if (isPrivate(el)) return;\n\n w.nodes++;\n\n const style = w.styleOf(el);\n if (isHidden(el, style, w.layout)) return;\n\n const role = roleOf(el);\n const transparent = role === null || TRANSPARENT.has(role);\n const interactive = isInteractive(el, role, style, parentStyle);\n\n // A div with a click handler is invisible to us (no getEventListeners), but a div\n // that is FOCUSABLE, or that flips the cursor to a pointer, is announcing itself.\n // Playwright emits those as `- generic [ref=eN]` and so do we: without this, every\n // custom card, chip and icon-button on a modern app would be unreachable.\n if (transparent && !interactive) {\n visitChildren(el, parent, style, w);\n return;\n }\n\n const emittedRole = role === null || TRANSPARENT.has(role) ? 'generic' : role;\n const name = nameOf(el, w.styleOf);\n\n // Refs are for things you can act on. Static text does not get one — it would be a\n // handle the agent can only ever misuse, and it doubles the size of the snapshot.\n let ref = '';\n if (interactive && receivesPointerEvents(style)) {\n const r = refFor(el, emittedRole, name);\n ref = ` [ref=${r}]`;\n w.onRef?.(r, el);\n }\n\n const state = states(el, emittedRole);\n const node: AriaNode = {\n role: emittedRole,\n name,\n props: (state ? ` ${state}` : '') + ref,\n children: [],\n };\n\n w.lines++;\n parent.children.push(node);\n\n // A native <select>: emit its options — the affordance the opaque rule used to\n // hide — instead of walking its (layout-less, hence prune-able) children.\n if (el.tagName === 'SELECT') {\n emitSelectOptions(el as HTMLSelectElement, node, w);\n return;\n }\n\n // An <input list=\"…\">: surface its datalist suggestions (the affordance) under the\n // input, then fall through to the opaque return — the value itself is never emitted.\n if (el.tagName === 'INPUT' && (el as HTMLInputElement).list) {\n emitDatalistOptions(el as HTMLInputElement, node, w);\n }\n\n // isOpaque: an <input>, <textarea> or contenteditable. Its content IS the user's\n // data, so we do not walk into it — the value cannot leak because we never go and\n // look at it. See a11y.ts.\n if (isOpaque(el)) return;\n\n visitChildren(el, node, style, w);\n}\n\nfunction visitNode(\n node: Node,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (node.nodeType === 3 /* TEXT_NODE */) {\n visitText(node as Text, parent, w);\n } else if (node.nodeType === 1 /* ELEMENT_NODE */) {\n visitElement(node as Element, parent, parentStyle, w);\n }\n // Comments, CDATA, processing instructions: nothing to say.\n}\n\n/* ────────────────────────────── rendering ─────────────────────────────── */\n\n/**\n * Redact, then truncate — in that order, and the order is the point.\n *\n * Truncate first and a 130-character line containing an email address gets cut\n * through the middle of it, the regex no longer matches, and you have shipped\n * `jane.doe@acmecorp` to the model. Redaction runs on the whole string, every time,\n * before anything is thrown away.\n */\nfunction sanitize(text: string, max: number): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n const clean = redact(collapsed);\n return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;\n}\n\nfunction quote(text: string): string {\n return `\"${text.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\nfunction render(\n children: (AriaNode | string)[],\n depth: number,\n out: string[],\n): void {\n const pad = ' '.repeat(depth);\n for (const child of children) {\n if (typeof child === 'string') {\n out.push(`${pad}- text: ${quote(sanitize(child, MAX_TEXT))}`);\n continue;\n }\n const name = child.name ? ` ${quote(sanitize(child.name, MAX_NAME))}` : '';\n const head = `${pad}- ${child.role}${name}${child.props}`;\n if (child.children.length) {\n out.push(`${head}:`);\n render(child.children, depth + 1, out);\n } else {\n out.push(head);\n }\n }\n}\n\n/* ─────────────────────────────── entry ────────────────────────────────── */\n\n/**\n * Walk the page and render it. Called by context.ts, which redacts the result a\n * second time on the way out — the belt to this file's braces.\n */\nfunction walk(\n root: Element,\n onRef?: (ref: string, el: Element) => void,\n): { yaml: string; truncated: boolean } {\n const styleOf = createStyleCache();\n const w: Walk = {\n styleOf,\n layout: hasLayout(),\n nodes: 0,\n lines: 0,\n truncated: false,\n onRef,\n };\n\n // The one call to the real isInaccessible(): a cheap backstop on the root, where\n // the ancestor walk costs nothing.\n if (isInaccessible(root, { getComputedStyle: styleOf })) {\n return { yaml: '', truncated: false };\n }\n\n const tree: AriaNode = { role: '', name: '', props: '', children: [] };\n visitChildren(root, tree, styleOf(root), w);\n\n const lines: string[] = [];\n render(tree.children, 0, lines);\n\n // An in-band marker, not just the out-of-band `truncated` flag. The YAML is what\n // lands in the prompt; a backend template that injects the tree but forgets to\n // surface the flag would hand the model a page that simply stops, and the model\n // fills the gap. This line is inside the payload, so it cannot be dropped on the\n // way to the prompt. (Depth-first, so what is missing is the BOTTOM of the page.)\n //\n // It REPLACES the last emitted line rather than appending — the marker is part of\n // the line budget, not an exemption from it. The final line was a truncated node\n // anyway (see MAX_LINES), so nothing meaningful is lost.\n if (w.truncated && lines.length) {\n lines[lines.length - 1] =\n '- text: \"… (snapshot truncated — more of the page is below)\"';\n }\n\n return { yaml: lines.join('\\n'), truncated: w.truncated };\n}\n\n/**\n * The full page. Mints a fresh generation of refs (beginSnapshot), so any ref the\n * agent held from a previous snapshot is now stale and resolves to null — which is\n * correct: the page may have changed under it.\n *\n * `visibleRefs` is the viewport slice — the refs whose element is actually on screen.\n * That is the \"where is your attention\" signal, and it lets the focus context name\n * the handful of things in view out of the whole tree.\n */\nexport function snapshot(): {\n yaml: string;\n truncated: boolean;\n visibleRefs: string[];\n} {\n const root = document.body;\n if (!root) return { yaml: '', truncated: false, visibleRefs: [] };\n\n beginSnapshot();\n\n const visibleRefs: string[] = [];\n const vh = window.innerHeight || 0;\n const vw = window.innerWidth || 0;\n const result = walk(root, (ref, el) => {\n const r = el.getBoundingClientRect();\n // On screen = its box intersects the viewport. Cheap; the walk already forced\n // layout, so getBoundingClientRect here is reading a warm value.\n if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) {\n visibleRefs.push(ref);\n }\n });\n\n return { ...result, visibleRefs };\n}\n\n/**\n * Zoom in on one ref — the a11y sub-tree under it.\n *\n * This is the pull half: the agent has the focus context and a shallow page, and when\n * it wants the detail of a specific table or form it asks for that region rather than\n * us re-sending the whole page. It does NOT call beginSnapshot — that would clear the\n * ref map and invalidate the very ref being asked about — so the refs it mints join\n * the current generation.\n */\nexport function snapshotRegion(root: Element): {\n yaml: string;\n truncated: boolean;\n} {\n if (!root.isConnected) return { yaml: '', truncated: false };\n return walk(root);\n}\n","import type {\n ActivityEvent,\n FocusContext,\n HostToWidget,\n PageContext,\n PageEntity,\n SiteMapEntry,\n ToolCall,\n} from './protocol';\nimport { redact } from './redact';\nimport {\n detectHoist,\n buildHoistContext,\n renderHoistSnapshot,\n} from './adapters/hoist';\nimport {\n readHoistRuntime,\n readHoistConfig,\n} from './adapters/hoist-runtime';\n// The registry composes the hoist adapter with the mf.*/app.* tool sources and is the\n// single advertise/execute surface — context.ts talks to it, not to the hoist adapter\n// directly. See adapters/registry.ts.\nimport { advertise, execute, emitToolEvent, toolClass } from './adapters/registry';\n\n// Re-exported so every existing importer of `redact` from `./context` (e.g.\n// dom/snapshot.ts) keeps working unchanged — see redact.ts for why the\n// definition itself lives in its own module.\nexport { redact } from './redact';\n\n/** The origin serving our chat — how we tell OUR embedded content from the host's own\n * iframes. Set by start(); empty until then, which just means we spot nothing. */\nlet widgetOrigin = '';\n\n/**\n * The eye.\n *\n * Everything in this module can see the customer's page. It is a SEPARATE CHUNK,\n * loaded only when someone actually opens the chat — so a page whose visitors never\n * click the widget pays nothing for any of it, and a security reviewer can read\n * exactly one file to know what we look at.\n *\n * The rules, which are not negotiable:\n *\n * NEVER captured — no config enables it: the value of any <input>, <textarea> or\n * contenteditable; anything inside a password field; cookies; localStorage;\n * sessionStorage; the raw DOM; screenshots; network traffic; anything inside an\n * element marked `data-mf-private`.\n *\n * The agent never gets a selector and never touches the DOM. It gets refs. A ref\n * is resolved to an element HERE, in the page, by us.\n */\n\ntype Send = (msg: HostToWidget) => void;\n\nconst MAX_ACTIVITY = 40;\n\nlet send: Send | null = null;\nlet activitySeq = 0;\nconst activity: ActivityEvent[] = [];\nlet lastUrl = '';\n/** Set once by `start()`. False ⇒ the host opted out of ALL page observation — every\n * exported entry point below that would otherwise read or send the page checks this. */\nlet pageContextOn = true;\n\n/**\n * A host callback that returns the DECLARED page context on demand — the pull-based\n * counterpart to the static `window.matterfact.context` global. Symmetric with\n * `AuthTokenProvider`: the React `<MatterfactAgent getPageContext>` prop supplies it; the\n * `<script>` loader uses `window.matterfact.getPageContext` instead (see resolveDeclaredContext).\n */\nexport type PageContextProvider = () =>\n | PageContext\n | null\n | undefined\n | Promise<PageContext | null | undefined>;\n/** The programmatic pull callback, set by `start()`. Read fresh on every publish. */\nlet contextProvider: PageContextProvider | undefined;\n\n/* ─────────────────────────── teardown state ───────────────────────────── */\n\n/**\n * Everything below is module-global bookkeeping so `stop()` (see `start()`, bottom of\n * file) can undo exactly what `start()`/`watchNavigation()` installed — remove every\n * listener, restore `history` to what it was before we wrapped it, and forget any\n * DOM-walk module we pulled in. All of this outlives a single `EmbedHost`; see\n * `stop()`'s doc comment for why that's the bug this exists to close.\n */\n\n/** The `fire` closure `watchNavigation()` handed to `popstate` — the only handle we\n * have to remove that listener again. */\nlet navFire: (() => void) | null = null;\n/** The `history.pushState`/`replaceState` this module wrapped, captured so `stop()`\n * can restore them EXACTLY rather than re-wrapping (which is how the old code\n * double-fired navigation on a second `start()`). */\nlet origPushState: History['pushState'] | null = null;\nlet origReplaceState: History['replaceState'] | null = null;\n/** Set once `sendSnapshot`/`sendRegion`/`readFocus` actually pull in the DOM-walk\n * chunk (`./dom/snapshot`) — never imported eagerly, so `stop()` doesn't pay for a\n * chunk that a host who only ever opted out (and never opened a snapshot) never\n * loaded in the first place. */\nlet snapshotModule: { clearRefs: () => void } | null = null;\n\n/* ─────────────────────────── redaction ────────────────────────────────── */\n// redact() now lives in ./redact — see that file's doc comment. Re-exported\n// above; imported here for local use throughout this module.\n\n/** Anything the host has marked private, or that is inherently sensitive, is out. */\nexport function isPrivate(el: Element): boolean {\n if (el.closest('[data-mf-private]')) return true;\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const t = (el as HTMLInputElement).type;\n if (t === 'password' || t === 'hidden') return true;\n }\n return false;\n}\n\n/* ───────────────────────── page context ───────────────────────────────── */\n\n/**\n * What the page says about itself.\n *\n * A host that declares nothing still gets URL + title, which is what every other\n * embeddable assistant on the market offers in total. The interesting fields\n * (`route`, `description`, `entities`) are host-declared, because only the host\n * knows that `/o/8813` is \"the Acme Corp order, 3 items, unpaid\".\n *\n * Declared via a global the host sets before we load:\n * window.matterfact = { context: { route: '/orders/:id', description: '...', entities: [...] } }\n */\n/**\n * matterfact content embedded IN the host page — today, artifact iframes.\n *\n * A cross-origin iframe is opaque: `contentDocument` throws, so the DOM snapshot walks\n * straight past an embedded artifact and the agent is blind to the very thing the page\n * is built around. It reads the page as empty and asks which URL you mean.\n *\n * We don't need to see inside, and shouldn't want to. The artifact's ID is right there\n * in the src, and the agent can already resolve `artifacts/<id>/` in its session — the\n * same path an `@`-mention uses. So we report the ID and let the backend fetch the real\n * thing, which beats scraping a rendering of it: it gets the data, not the picture.\n *\n * Matched by ORIGIN, not by path shape: a customer is perfectly entitled to their own\n * /artifacts/ route, and it isn't ours.\n */\n/** The artifact slug from a matterfact artifact path, or null. Matches both the\n * chrome-free embed route (/embed/artifacts/<slug>) and the bare /artifacts/<slug>. */\nexport function artifactIdFromPath(pathname: string): string | null {\n const m = pathname.match(/^\\/(?:embed\\/)?artifacts\\/(.+?)\\/?$/);\n return m ? decodeURIComponent(m[1]) : null;\n}\n\nfunction embeddedMatterfactEntities(): PageEntity[] {\n if (!widgetOrigin) return [];\n const out: PageEntity[] = [];\n for (const frame of Array.from(document.querySelectorAll('iframe'))) {\n let u: URL;\n try {\n u = new URL(frame.getAttribute('src') || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== widgetOrigin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n if (out.some((e) => e.id === id)) continue; // same artifact twice = once\n // No url field: the agent reaches an artifact by ID (`artifacts/<id>/`), never by\n // fetching the page, and an artifact URL can carry a share token we've no business\n // forwarding. The id is the whole useful payload.\n out.push({\n kind: 'artifact',\n id,\n label: redact(frame.getAttribute('title') || '') || id,\n });\n }\n return out;\n}\n\n/**\n * Frames we can see the existence of but nothing inside — someone else's cross-origin\n * embed. Worth one line: \"there is a thing here I cannot read\" is a true and useful\n * statement, and much better than the agent confidently describing a page while missing\n * the widget the user is actually asking about.\n */\nfunction opaqueFrameCount(): number {\n return Array.from(document.querySelectorAll('iframe')).filter((f) => {\n try {\n const u = new URL(f.getAttribute('src') || '', location.href);\n return u.origin !== location.origin && u.origin !== widgetOrigin;\n } catch {\n return false;\n }\n }).length;\n}\n\n/**\n * Merge the host's DECLARED context with what we auto-detect. Auto-detected fields\n * (url/path/title/locale, co-embedded artifact entities, opaque-frame count) are additive:\n * a declared value wins where they overlap (the `...declared` spread), and found entities\n * append to declared ones.\n */\nexport function buildPageContext(declared: PageContext): PageContext {\n const found = embeddedMatterfactEntities();\n const opaque = opaqueFrameCount();\n\n return {\n // Path only. A query string is where session ids, tokens and email addresses\n // live; it is not ours to take.\n url: location.origin + location.pathname,\n path: location.pathname,\n title: redact(document.title),\n locale: document.documentElement.lang || undefined,\n ...declared,\n // After the spread: what we FOUND is additive to what the host DECLARED, never a\n // replacement. A host that declares its own entities still gets the artifacts we\n // spotted, and vice versa.\n entities: [...(declared.entities ?? []), ...found],\n data: {\n ...(declared.data ?? {}),\n ...(opaque ? { opaque_frames: opaque } : {}),\n },\n };\n}\n\n/** Back-compat: build context from the static `window.matterfact.context` global only (sync). */\nexport function readPageContext(): PageContext {\n return buildPageContext(\n (window as { matterfact?: { context?: PageContext } }).matterfact\n ?.context ?? {},\n );\n}\n\n/**\n * Resolve the host's DECLARED context, preferring a pull callback over the static global so\n * a virtualized SPA can hand us fresh context per turn. First non-null wins:\n * 1. the programmatic `getPageContext` provider (React `<MatterfactAgent getPageContext>`),\n * 2. the `<script>`-loader global `window.matterfact.getPageContext()`,\n * 3. the static `window.matterfact.context`.\n */\nasync function resolveDeclaredContext(): Promise<PageContext> {\n const mf = (\n window as {\n matterfact?: {\n context?: PageContext;\n getPageContext?: PageContextProvider;\n };\n }\n ).matterfact;\n if (contextProvider) {\n const c = await contextProvider();\n if (c) return c;\n }\n if (mf?.getPageContext) {\n const c = await mf.getPageContext();\n if (c) return c;\n }\n // Hoist auto-detection: a framework-shaped context source, below explicit host\n // declarations but above the static global. Degrade-safe (detectHoist swallows).\n const hoist = detectHoist(() => readHoistRuntime());\n if (hoist) return buildHoistContext(hoist);\n return mf?.context ?? {};\n}\n\n/**\n * Publish the current declared+detected context as `host.context`. Async because the pull\n * callback may be (a host might read a store). Rapid calls just re-publish — for idempotent\n * context, last-writer-wins is fine. No-op when the host opted out of page observation.\n */\nasync function publishContext() {\n if (!pageContextOn) return;\n const declared = await resolveDeclaredContext();\n send?.({ type: 'host.context', context: buildPageContext(declared) });\n}\n\n/**\n * Answer a `widget.requestContext` (the pull path): publish context AND the site map NOW,\n * so a turn assembled right after carries both as they are — not as of the last route\n * change. The site map matters here as much as the context: the loader's nav hook fires\n * synchronously during `pushState`, BEFORE a React host has re-rendered with the new\n * route's map, so a nav-time push can be a render stale. Re-publishing at turn-assembly\n * (after the host has settled) is what makes it fresh. No-op when page observation is off.\n */\nexport function provideContext() {\n void publishContext();\n publishSitemap();\n}\n\n/* ─────────────────────── artifact grants (backend-only) ────────────────── */\n\nexport interface ArtifactGrantSrc {\n id: string;\n owner: string;\n token: string;\n}\n\n/** Read-only capability grants from co-embedded artifact iframes, for the backend to\n * materialize their data. Separate from entities on purpose: the token must never ride\n * ambient (rendered) context, only this backend-only channel. */\nexport function grantsFromIframeSrcs(\n srcs: string[],\n origin: string,\n): ArtifactGrantSrc[] {\n const out: ArtifactGrantSrc[] = [];\n for (const raw of srcs) {\n let u: URL;\n try {\n u = new URL(raw || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== origin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n const owner = u.searchParams.get('owner') || '';\n const token = u.searchParams.get('t') || '';\n if (!owner || !token) continue;\n if (out.some((g) => g.id === id)) continue;\n out.push({ id, owner, token });\n }\n return out;\n}\n\n/**\n * Grants DECLARED by the host — `window.matterfact.artifacts` (the\n * `<MatterfactAgent artifacts>` prop mirrors onto it). Same wire shape as a scanned\n * iframe grant, so a board is reachable from a route where its iframe isn't mounted\n * WITHOUT hidden zero-size iframes smuggling the token into the DOM. Degrade-safe:\n * anything malformed is skipped, never thrown.\n */\nexport function readDeclaredGrants(): ArtifactGrantSrc[] {\n const declared = (\n window as {\n matterfact?: {\n artifacts?: Array<{ slug?: string; owner?: string; token?: string }>;\n };\n }\n ).matterfact?.artifacts;\n if (!Array.isArray(declared)) return [];\n const out: ArtifactGrantSrc[] = [];\n for (const a of declared) {\n const id = (a?.slug || '').trim();\n const owner = (a?.owner || '').trim();\n const token = (a?.token || '').trim();\n if (!id || !owner || !token) continue;\n if (out.some((g) => g.id === id)) continue;\n out.push({ id, owner, token });\n }\n return out;\n}\n\nfunction readArtifactGrants(): ArtifactGrantSrc[] {\n if (!widgetOrigin) return [];\n const srcs = Array.from(document.querySelectorAll('iframe')).map(\n (f) => f.getAttribute('src') || '',\n );\n const scanned = grantsFromIframeSrcs(srcs, widgetOrigin);\n // A live co-embedded iframe on THIS page wins over a declared grant for the same\n // slug (its token is the one the visible board is actually spending); declared\n // grants fill in the boards that aren't mounted here.\n const out = [...scanned];\n for (const g of readDeclaredGrants()) {\n if (!out.some((s) => s.id === g.id)) out.push(g);\n }\n return out;\n}\n\nfunction publishArtifactGrants() {\n send?.({ type: 'host.artifactGrants', grants: readArtifactGrants() });\n}\n\n/* ─────────────────────────── site map ─────────────────────────────────── */\n\n/**\n * The host's DECLARED site map — its routes, annotated with a content class so the\n * agent knows which carry matterfact content and of what kind. Read from the\n * `window.matterfact.sitemap` global; the React `<MatterfactAgent sitemap>` prop writes\n * it there, symmetric with `context`/`actions`. Classification only — no per-instance\n * ids, never a capability token (those ride `host.context`/`host.artifactGrants`).\n */\nfunction readSitemap(): SiteMapEntry[] {\n const s = (window as { matterfact?: { sitemap?: SiteMapEntry[] } }).matterfact\n ?.sitemap;\n return Array.isArray(s) ? s : [];\n}\n\nfunction publishSitemap() {\n if (!pageContextOn) return;\n const sitemap = readSitemap();\n // Omit an empty map rather than send `[]` on every load — most hosts declare none.\n if (sitemap.length) send?.({ type: 'host.sitemap', sitemap });\n}\n\n/**\n * Navigate the HOST page to one of its OWN routes — the \"open on page\" deeplink from\n * a co-embedded document's side-panel viewer. The widget is a cross-origin iframe and\n * can't navigate the top window itself, so it asks us (via `widget.navigate`).\n *\n * Guarded to the host's OWN origin: resolve the href against the host location and\n * refuse anything on a different origin or a non-http(s) scheme. The href originates\n * in page context the host itself declared, so this is defense-in-depth — the widget\n * must never be able to send the host off-site. Lives in this lazy chunk (not the\n * eager loader stub) to stay off the every-page budget.\n */\nexport function navigateHost(href: unknown): void {\n if (typeof href !== 'string' || !href) return;\n let target: URL;\n try {\n target = new URL(href, location.href);\n } catch {\n return;\n }\n if (target.protocol !== 'http:' && target.protocol !== 'https:') return;\n if (target.origin !== location.origin) return;\n location.assign(target.href);\n}\n\n/* ────────────────────────── activity ──────────────────────────────────── */\n\nfunction pushActivity(e: Omit<ActivityEvent, 'seq' | 'ts'>) {\n activity.push({ ...e, seq: ++activitySeq, ts: Date.now() });\n if (activity.length > MAX_ACTIVITY) activity.shift();\n send?.({ type: 'host.activity', events: [activity[activity.length - 1]] });\n}\n\n/**\n * A short, human-readable label for what got clicked.\n *\n * Shaped after PostHog's autocapture, not after a session-replay frame: rrweb would\n * give us `{source:2, type:2, id:417, x:210, y:88}` — no text, no role, no href,\n * meaningless to a model without the full DOM snapshot it deltas against. One line\n * of \"clicked button 'Export CSV'\" is worth more and costs less.\n */\n/**\n * The accessible NAME of a form control — never its value.\n *\n * A control has no `innerText`, so the generic path below misses it. We look where a\n * control's name actually lives: `aria-label`, then a `<label for>` or a wrapping\n * `<label>`, then `placeholder`. `placeholder` is a LABEL, not a value — it is the\n * hint shown when the field is empty (\"Order number or customer\"), so it is safe.\n */\nfunction controlLabel(el: Element): string {\n const aria = el.getAttribute('aria-label');\n if (aria) return aria;\n\n const id = el.id;\n if (id) {\n const forLabel = document.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n const t = forLabel?.textContent?.trim();\n if (t) return t;\n }\n const wrapping = el.closest('label')?.textContent?.trim();\n if (wrapping) return wrapping;\n\n const placeholder = el.getAttribute('placeholder');\n if (placeholder) return placeholder;\n\n return '';\n}\n\nconst FORM_CONTROLS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);\n\nfunction describe(el: Element): string {\n const role = el.getAttribute('role') || el.tagName.toLowerCase();\n const label =\n el.getAttribute('aria-label') ||\n (FORM_CONTROLS.has(el.tagName)\n ? controlLabel(el)\n : (el as HTMLElement).innerText?.trim().slice(0, 60)) ||\n el.getAttribute('title') ||\n '';\n return label ? `${role} \"${redact(label)}\"` : role;\n}\n\n/**\n * Elements a click is worth recording. Deliberately tight: the point of the activity\n * stream is INTENT (\"the user chose to export\"), and a click on a heading, a label,\n * a card gutter, or blank page is not intent, it is noise. We only log a click that\n * lands on something actionable.\n */\nconst ACTIONABLE =\n 'a[href],button,input,select,textarea,summary,' +\n '[role=\"button\"],[role=\"link\"],[role=\"menuitem\"],[role=\"tab\"],[role=\"option\"],' +\n '[role=\"checkbox\"],[role=\"switch\"],[role=\"radio\"],[onclick],[tabindex]';\n\nfunction onClick(ev: Event) {\n const target = ev.target as Element | null;\n if (!target || !(target instanceof Element)) return;\n\n // Clicking a <label> operates the control it labels — record THAT, not \"clicked\n // label\", so the event reads as the user's actual intent.\n const label = target.closest('label');\n const labelled = label\n ? (label.getAttribute('for') &&\n document.getElementById(label.getAttribute('for')!)) ||\n label.querySelector('input,select,textarea')\n : null;\n\n const actionable = labelled ?? target.closest(ACTIONABLE);\n // No actionable target — a click on text, a gutter, or blank space. That is not an\n // action; dropping it is the whole fix for the click-log noise.\n if (!actionable || isPrivate(actionable)) return;\n\n pushActivity({ type: 'click', summary: `clicked ${describe(actionable)}` });\n}\n\nfunction onSubmit(ev: Event) {\n const el = ev.target as Element | null;\n if (!el || isPrivate(el)) return;\n // The FORM was submitted — never its values.\n pushActivity({ type: 'submit', summary: `submitted ${describe(el)}` });\n}\n\n/**\n * A form field changed.\n *\n * The rule is the same as everywhere else and the temptation here is sharpest:\n * record THAT a field changed and WHICH field (its label), never WHAT it was\n * changed to. `change` fires on exactly the elements whose values are off-limits.\n *\n * One safe exception: a <select>, a checkbox, or a radio chose from a fixed, visible\n * set of options the agent can already see in the snapshot — \"Unpaid\", \"Shipped\".\n * That is a user *choice*, not typed data, so the chosen option's LABEL is fair to\n * include and is the useful part (\"filtered status to Shipped\"). Free-text and\n * numeric inputs get their label only.\n */\nfunction onChange(ev: Event) {\n const el = ev.target as (HTMLElement & { type?: string }) | null;\n if (!el || !(el instanceof Element) || isPrivate(el)) return;\n\n const tag = el.tagName;\n const type = (el as HTMLInputElement).type;\n\n // Never a password/hidden field, and isPrivate already covered data-mf-private.\n if (tag === 'INPUT' && (type === 'password' || type === 'hidden')) return;\n\n let summary = `changed ${describe(el)}`;\n\n if (tag === 'SELECT') {\n const opt = (el as HTMLSelectElement).selectedOptions[0]?.text;\n if (opt) summary = `${describe(el)} → \"${redact(opt)}\"`;\n } else if (type === 'checkbox' || type === 'radio') {\n summary = `${(el as HTMLInputElement).checked ? 'checked' : 'unchecked'} ${describe(el)}`;\n }\n\n pushActivity({ type: 'input', summary });\n}\n\n/**\n * SPA navigation. There is no event for `pushState`, so we wrap it — a 20-line job\n * that no library does better.\n */\nfunction watchNavigation() {\n const fire = () => {\n const url = location.pathname;\n if (url === lastUrl) return;\n lastUrl = url;\n pushActivity({ type: 'nav', summary: `navigated to ${url}` });\n void publishContext();\n publishArtifactGrants();\n // The site map can change without a reload (a virtualized SPA) and `current`\n // moves with the route, so re-publish it on navigation like context/grants.\n publishSitemap();\n // Re-advertise host.tools too (Minor #2): the enum `hoist.navigate` carries is\n // bound to the CURRENT sitemap, and start() only ever advertised it ONCE. A\n // route that gained or lost destinations must not leave the widget holding a\n // stale enum forever. Unlike start()'s one-shot emit (gated on tools.length),\n // this fires even when the result is `[]` — the whole point is to CLEAR a\n // tool the widget cached from before this navigation, not just to add one.\n publishTools();\n };\n // Captured so stop() can remove exactly this listener, and so history.pushState/\n // replaceState get restored to what they were before we wrapped them — never\n // re-wrapped on top of an existing wrap (that was the pre-existing bug: a second\n // start() used to wrap the ALREADY-wrapped methods, double-firing every nav).\n navFire = fire;\n\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = history[name];\n if (name === 'pushState') origPushState = orig as History['pushState'];\n else origReplaceState = orig as History['replaceState'];\n history[name] = function (\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const r = orig.apply(this, args);\n fire();\n return r;\n } as History[typeof name];\n }\n window.addEventListener('popstate', fire);\n}\n\n/* ─────────────────────────── focal context ────────────────────────────── */\n\n/**\n * Where the user's attention is, right now.\n *\n * This is the \"knows what you're doing\" layer, and it is deliberately small so it can\n * ride on every turn — where the full snapshot cannot. It is also the most sensitive:\n * `selection` is whatever the user highlighted, which could be their own email, so it\n * is redacted and respects data-mf-private like everything else. Focus and the\n * viewport are labels and refs — never a value.\n *\n * Held so the last-known focus can travel with a turn even between the (throttled)\n * push updates.\n */\nlet lastFocus: FocusContext = {};\n\nasync function readFocus(): Promise<FocusContext> {\n const focus: FocusContext = {};\n\n // Selection — the single strongest \"this is what I'm asking about\" signal.\n const sel = window.getSelection?.();\n if (sel && !sel.isCollapsed) {\n const anchor = sel.anchorNode?.parentElement ?? null;\n // Don't lift a selection out of a private region, and cap it — a user can select\n // the whole page.\n if (!anchor || !anchor.closest('[data-mf-private]')) {\n const text = sel.toString().trim().slice(0, 500);\n if (text) focus.selection = redact(text);\n }\n }\n\n // The control they're working in — its label, never its contents.\n const active = document.activeElement;\n if (\n active &&\n active !== document.body &&\n !isPrivate(active) &&\n !active.closest('[data-mf-private]')\n ) {\n const { snapshot } = await loadSnapshotModule();\n void snapshot; // ensure the chunk that owns refFor is loaded before we describe\n focus.focused = {\n label: redact(describeControl(active)),\n role: active.getAttribute('role') || active.tagName.toLowerCase(),\n };\n }\n\n const doc = document.documentElement;\n const scrollable = doc.scrollHeight - doc.clientHeight;\n focus.scroll =\n scrollable > 0 ? Math.round((doc.scrollTop / scrollable) * 100) / 100 : 0;\n\n return focus;\n}\n\n/** A label for whatever is focused, reusing the same value-blind rules as activity. */\nfunction describeControl(el: Element): string {\n return describe(el);\n}\n\n/** The one place any of the three call sites below reach into the DOM-walk chunk —\n * so `stop()` has a single `snapshotModule` to check without importing anything\n * itself (see the teardown-state block above). */\nasync function loadSnapshotModule() {\n const m = await import('./dom/snapshot');\n snapshotModule = m;\n return m;\n}\n\nlet focusTimer: ReturnType<typeof setTimeout> | null = null;\n\n/** Coalesce a burst of selection/focus/scroll events into one push. */\nfunction scheduleFocus() {\n if (focusTimer) return;\n focusTimer = setTimeout(async () => {\n focusTimer = null;\n lastFocus = await readFocus();\n send?.({ type: 'host.focus', focus: lastFocus });\n }, 250);\n}\n\n/* ───────────────────────────── snapshot ───────────────────────────────── */\n\nlet snapshotSeq = 0;\n\nexport async function sendSnapshot(emit: Send) {\n // pageContext: false ⇒ no snapshot, ever — a `widget.requestSnapshot` must not be\n // able to reintroduce the page observation the host explicitly turned off.\n if (!pageContextOn) return;\n\n // Hoist-first: on an XH Hoist SPA, the live models are a richer and cheaper source\n // of truth than scraping role-less div soup. detectHoist() is degrade-safe (never\n // throws here), so an absent/broken window.XH falls straight through to the\n // generic a11y walk below, unchanged.\n const hoist = detectHoist(() => readHoistRuntime());\n if (hoist) {\n const { rows } = readHoistConfig(\n typeof window !== 'undefined' ? window : undefined,\n );\n const { yaml, truncated } = renderHoistSnapshot(hoist, rows);\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // Refs are out of scope for Layer 1 (they arrive with the interactive channel in\n // Layer 3) — a Hoist snapshot never mints [ref=eN] handles, so nothing is visible\n // by ref.\n lastFocus = { ...lastFocus, visibleRefs: [] };\n emit({ type: 'host.focus', focus: lastFocus });\n return;\n }\n\n // The a11y walk is itself lazily imported: a host that only ever declares\n // PageContext and never lets the agent look at the page never downloads it.\n const { snapshot } = await loadSnapshotModule();\n const { yaml, truncated, visibleRefs } = snapshot();\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // The viewport slice rides with the focus context so the agent can tell the few\n // things on screen from the whole tree it just received.\n lastFocus = { ...lastFocus, visibleRefs };\n emit({ type: 'host.focus', focus: lastFocus });\n}\n\n/**\n * Zoom in on one ref — the pull half of the model. The agent asks; we resolve the ref\n * to a live element and return just its sub-tree.\n */\nexport async function sendRegion(ref: string, emit: Send) {\n // Mirrors sendSnapshot's guard: a `widget.readRegion` for a ref minted before\n // opt-out must not pull a live DOM subtree just because the ref is still\n // resolvable (see refs.ts's `clearRefs`, which `stop()` also uses as a backstop).\n if (!pageContextOn) return;\n const { snapshotRegion, resolveRef } = await loadSnapshotModule();\n const el = resolveRef(ref);\n if (!el) {\n emit({\n type: 'host.region',\n ref,\n yaml: '(this element is no longer on the page)',\n });\n return;\n }\n const { yaml } = snapshotRegion(el);\n emit({ type: 'host.region', ref, yaml: redact(yaml) });\n}\n\n/* ───────────────────────────── tools ──────────────────────────────────── */\n\n/**\n * Tools the page's ADAPTER (today: Hoist) exposes to the agent, and the sole\n * execution path for calling one.\n *\n * The page's content is untrusted — text on it can try to instruct the agent — and\n * the moment the agent can act, a bad answer becomes a bad ACTION. Several things\n * hold that line, and all of them live HERE (in the page, where we control what\n * actually happens), not in the widget, which can be lied to:\n *\n * - a tool is only ever ADVERTISED (`advertiseTools`) when the HOST opted in via\n * `window.matterfact.hoist.actions` — default 'off';\n * - this function itself refuses to even attempt a call when the host opted out\n * of page observation (`pageContext:false`) — see the `pageContextOn` guard\n * below, mirroring every sibling in this file;\n * - `executeHostTool` (adapters/hoist-runtime.ts) RE-CHECKS the host's current\n * action policy AND re-validates the destination against the LIVE page state,\n * on every call — never trusting what the widget claims was advertised, or\n * that the policy it was advertised UNDER still holds. A tool not marked\n * `readOnly` also carries a `confirm` policy the widget must gate on — see\n * HostTool's doc comment in protocol.ts.\n */\nexport async function callTool(call: ToolCall, emit: Send) {\n // Mirrors every sibling in this file (sendSnapshot, sendRegion, publishContext):\n // pageContext:false means the host opted out of ALL page observation, and a tool\n // call is exactly that — it would read the live Hoist runtime just like a\n // snapshot does. UNLIKE those siblings, this still REPLIES (ok:false) rather than\n // silently no-op-ing: the widget's callTool() is awaiting a specific callId, and\n // a call that never gets a host.toolResult hangs until its own timeout instead of\n // failing fast.\n if (!pageContextOn) {\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: false,\n error: 'host tools are disabled',\n });\n return;\n }\n const win = typeof window !== 'undefined' ? window : undefined;\n const cls = toolClass(call.name);\n const startedAt = Date.now();\n emitToolEvent(win, {\n phase: 'call',\n name: call.name,\n toolClass: cls,\n args: call.args,\n });\n const r = await execute(call, win);\n emitToolEvent(win, {\n phase: 'result',\n name: call.name,\n toolClass: cls,\n ok: r.ok,\n error: r.error,\n ms: Date.now() - startedAt,\n });\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: r.ok,\n result: r.result,\n error: r.error,\n });\n}\n\n/* ───────────────────────────── stop / start ───────────────────────────── */\n\n/**\n * The opposite number of `start()` — remove every listener it (or `watchNavigation`)\n * installed, restore `history.pushState`/`replaceState` to what they were before we\n * wrapped them, and forget the module-level `send`/`activity`/focus state. Nothing\n * here is a filter over what gets sent afterward — there is simply nothing left\n * installed to send anything.\n *\n * Why this has to exist at all: everything `start()` installs is MODULE-GLOBAL, and\n * this module outlives any single `EmbedHost`. React remounts `EmbedHost` whenever\n * ANY of its identity-defining props change (react.tsx's effect deps: publishableKey,\n * widgetOrigin, surface, theme, inline, pageContext, dev) — including just a theme\n * swap, not only a deliberate opt-out. Before this fix, a remount's `start()` call\n * only ever ADDED listeners; the previous mount's were still attached and kept firing\n * into the module `send`, which the new `start()` had just repointed at the NEW\n * widget. Net effect: open once with pageContext on, then remount for any reason\n * (including `pageContext: false`) and the new widget silently keeps receiving\n * clicks/nav/focus collected by the old mount's still-live listeners.\n *\n * Called from two places: the top of `start()` (idempotency — a second `start()`\n * never doubles up, which also fixes the pre-existing double history-wrap /\n * double-`fire()`-per-navigation bug), and `EmbedHost.destroy()` in loader.ts (a\n * plain unmount with no remount still has to stop, not just wait for a `start()`\n * that may never come).\n */\nexport function stop(): void {\n document.removeEventListener('click', onClick, { capture: true });\n document.removeEventListener('submit', onSubmit, { capture: true });\n document.removeEventListener('change', onChange, { capture: true });\n document.removeEventListener('selectionchange', scheduleFocus);\n document.removeEventListener('focusin', scheduleFocus, { capture: true });\n window.removeEventListener('scroll', scheduleFocus, { capture: true });\n\n if (navFire) {\n window.removeEventListener('popstate', navFire);\n navFire = null;\n }\n // Restore, don't re-wrap: this is what stops a repeated start() from wrapping an\n // already-wrapped pushState/replaceState (the old double-fire-per-nav bug).\n if (origPushState) {\n history.pushState = origPushState;\n origPushState = null;\n }\n if (origReplaceState) {\n history.replaceState = origReplaceState;\n origReplaceState = null;\n }\n\n if (focusTimer) {\n clearTimeout(focusTimer);\n focusTimer = null;\n }\n\n send = null;\n contextProvider = undefined;\n activity.length = 0;\n lastFocus = {};\n widgetOrigin = '';\n\n // Belt-and-suspenders alongside sendRegion's own pageContextOn check (see above):\n // an old ref minted while observation was on must not stay resolvable afterward.\n // Only touches the DOM-walk chunk if it was ever actually loaded — see\n // loadSnapshotModule's doc comment.\n snapshotModule?.clearRefs();\n}\n\n/**\n * @param pageContext Whether to observe the host page at all. Default `true`. False is\n * the loader's `pageContext: false` opt-out reaching all the way down here: skip every\n * bit of page reading below — no declared/found context, no artifact grants, no nav/\n * click/submit/change/focus observers — so there is nothing to send and nothing that\n * could later be asked for (see `widget.requestSnapshot` in loader.ts). Theme detection\n * is unaffected: it reads an OS media query, never the page, so it isn't page context.\n *\n * The host's action policy (`{navigate:'off'|'confirm'|'auto'}`) is NOT a parameter\n * here — unlike `pageContext`/`provider`, it has exactly one source,\n * `window.matterfact.hoist.actions`, read fresh by `advertiseTools`/`readActionsConfig`\n * (adapters/hoist-runtime.ts) at both advertise time (below, and watchNavigation's\n * re-advertisement) and execute time (`executeHostTool`, via `callTool`) — so the two\n * can never disagree about the current policy the way an eagerly-threaded override\n * could.\n */\nexport function start(\n emit: Send,\n origin?: string,\n pageContext = true,\n provider?: PageContextProvider,\n) {\n // Idempotent: undo whatever a PREVIOUS start() installed before this one installs\n // anything. Without this, a remount (see stop()'s doc comment) leaves the old\n // mount's listeners live, writing into the `send` this call is about to reassign.\n stop();\n\n send = emit;\n widgetOrigin = origin || '';\n lastUrl = location.pathname;\n pageContextOn = pageContext;\n contextProvider = provider;\n\n if (pageContextOn) {\n void publishContext();\n publishArtifactGrants();\n publishSitemap();\n watchNavigation();\n\n // Passive + capture: we observe, we never interfere with the host's own handling.\n document.addEventListener('click', onClick, {\n capture: true,\n passive: true,\n });\n document.addEventListener('submit', onSubmit, {\n capture: true,\n passive: true,\n });\n // `change` fires on blur/commit for text inputs and immediately for select/\n // checkbox/radio — not on every keystroke, which is what we want: a settled\n // choice, not a stream of partial values.\n document.addEventListener('change', onChange, {\n capture: true,\n passive: true,\n });\n\n // Focal context: what the user is attending to. Coalesced (scheduleFocus), because\n // selectionchange and scroll fire in torrents.\n document.addEventListener('selectionchange', scheduleFocus, {\n passive: true,\n });\n document.addEventListener('focusin', scheduleFocus, {\n capture: true,\n passive: true,\n });\n window.addEventListener('scroll', scheduleFocus, {\n capture: true,\n passive: true,\n });\n }\n\n const theme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light';\n emit({ type: 'host.theme', mode: theme });\n\n // Tool advertisement — after theme, at the very end of start(). Gated on\n // pageContextOn like every other Hoist-runtime read (sendSnapshot mirrors this):\n // the site map the hoist adapter reads from is live page state, not something a\n // pageContext:false host agreed to expose. Skipped entirely (no empty host.tools)\n // rather than advertising nothing on every single load — advertise() itself is\n // degrade-safe and never throws, so this needs no try/catch of its own.\n if (pageContextOn) {\n const w = typeof window !== 'undefined' ? window : undefined;\n const tools = advertise(w);\n if (tools.length) {\n emit({ type: 'host.tools', tools });\n for (const t of tools) {\n emitToolEvent(w, {\n phase: 'advertise',\n name: t.name,\n toolClass: toolClass(t.name),\n });\n }\n }\n }\n}\n\n/** Advertise the merged tool list on the wire and fire the host's onToolEvent so its\n * telemetry (and the dev panel) sees the current set. Shared by start()'s first emit's\n * navigation re-advertisement; fires even on `[]` to CLEAR a tool cached before a nav. */\nfunction publishTools() {\n const win = typeof window !== 'undefined' ? window : undefined;\n const tools = advertise(win);\n send?.({ type: 'host.tools', tools });\n for (const t of tools) {\n emitToolEvent(win, {\n phase: 'advertise',\n name: t.name,\n toolClass: toolClass(t.name),\n });\n }\n}\n","/**\n * The matterfact embed bridge protocol.\n *\n * This is the contract between the HOST PAGE (a customer's site, running our\n * loader) and the WIDGET (our chat, running in a cross-origin iframe on\n * app.matterfact.com).\n *\n * Two things to understand before changing anything here:\n *\n * 1. THE IFRAME CANNOT SEE THE PAGE. It is cross-origin — that is the entire\n * point of it. So every fact about the host page (its URL, its DOM, what the\n * user just did) reaches the agent only because the LOADER, which runs as\n * ordinary page JS and *can* see it, chose to send it. The loader is the eye;\n * the widget is the mouth.\n *\n * 2. THIS CONTRACT OUTLIVES THE IFRAME. The next tier is an in-page React SDK\n * with no iframe at all — and it will speak exactly this. If the message\n * shapes are right, \"deeper integration\" is a transport swap (postMessage ->\n * direct call), not a rewrite. So model the DOMAIN here, not the plumbing.\n */\n\n// v3 (2026-07): adds `host.sitemap` (a structured, content-annotated site map),\n// `widget.navigate` (deeplink the host to one of its own routes), and `widget.chat`\n// (content-free chat-turn telemetry forwarded to the host's `onEvent`). All additive —\n// a peer that doesn't know a message simply never sends/handles it — so this is a\n// capability signal, not a breaking change. No code branches on the version number.\nexport const PROTOCOL_VERSION = 3;\n\n/** Every message is namespaced so we never collide with the host page's own postMessage traffic. */\nexport const CHANNEL = 'mf-embed';\n\n/* ────────────────────────────── refs ──────────────────────────────────── */\n\n/**\n * A handle on a real element in the host page.\n *\n * Format and semantics are lifted from Playwright's ARIA snapshot (`ref=e12`),\n * for a specific reason: it is the element-handle syntax the frontier models have\n * seen most, via playwright-mcp. We are not being original here on purpose.\n *\n * The ref is an in-page expando plus a snapshot-scoped Map — never an attribute,\n * so it is invisible to the host page's CSS, its serialization, and its own\n * mutation observers. It is resolved back to an element by the LOADER; the agent\n * never touches the DOM, and never learns a selector.\n */\nexport type ElementRef = string; // 'e12'\n\n/* ──────────────────────────── host → widget ───────────────────────────── */\n\n/** Ambient facts about the page. Cheap, sent on every navigation. */\nexport interface PageContext {\n url?: string;\n /** A route PATTERN ('/orders/:id') beats a raw path — it tells the agent what KIND of page this is. */\n route?: string;\n path?: string;\n title?: string;\n locale?: string;\n /** 1–2 sentences, written the way you'd brief a colleague. The highest-value field by far. */\n description?: string;\n /** Things the page is about. These also become @-mentionable in the composer, for free. */\n entities?: PageEntity[];\n /** Allowlisted only. Never a dump of app state. */\n data?: Record<string, unknown>;\n}\n\nexport interface PageEntity {\n /** Host kinds are namespaced (`x:ticker`) so they can never collide with matterfact's own. */\n kind: string;\n id: string;\n label: string;\n /** Pre-rendered, agent-readable. Keep it short. */\n text?: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * How a route's content is classified, for the annotated site map.\n *\n * The host DECORATES the site map we auto-derive (see `SiteMapEntry`) so the agent\n * knows which routes carry MATTERFACT content and of what kind — app-wide awareness\n * it can navigate toward. This is CLASSIFICATION only: no per-instance ids, and never\n * a capability token. The concrete artifact/document on the CURRENT page still arrives\n * via `host.context` entities / `host.artifactGrants`, resolved per page.\n *\n * - `mf-artifact` — a co-embedded matterfact artifact (its slug); the token stays on\n * the live iframe / grant, never here.\n * - `mf-document` — a matterfact document (dossier/report), resolved to an MF_DOC_ID\n * host-side per page.\n * - `host-data` — the host's own data; not a matterfact entity.\n */\nexport type ContentClass =\n | { kind: 'mf-artifact'; slug: string }\n | { kind: 'mf-document'; doctype: string }\n | { kind: 'host-data' };\n\n/**\n * One route in the annotated site map: the path pattern + label we derived, plus the\n * host's content classification. `current` marks the route the user is on.\n */\nexport interface SiteMapEntry {\n /** Route pattern or path, e.g. '/app/company/:ticker/dossier'. */\n path: string;\n /** Human label for the route ('Company Dossier'). */\n label?: string;\n /** The host's classification of this route's content, when it annotated it. */\n content?: ContentClass;\n current?: boolean;\n}\n\n/** A co-embedded artifact's read-only capability, for the backend to materialize its\n * data. Backend-only — never rendered. `token` is the artifact's own embed token. */\nexport interface ArtifactGrant {\n id: string;\n owner: string;\n token: string;\n}\n\n/**\n * A DECLARED artifact grant — the `<MatterfactAgent artifacts>` prop (or\n * `window.matterfact.artifacts`). Same wire shape as a grant discovered by scanning\n * co-embedded `<MatterfactArtifact>` iframes, plus an optional `label`; it feeds the\n * SAME `host.artifactGrants` channel. This is how a host makes a board reachable from\n * a route where its iframe ISN'T mounted, without hidden zero-size iframes smuggling\n * the token into the DOM. The token stays in the grant channel, never in message text.\n */\nexport interface DeclaredArtifact {\n slug: string;\n owner: string;\n token: string;\n label?: string;\n}\n\n/**\n * One host-tool lifecycle event, surfaced to the host via `onToolEvent` (and the dev\n * panel) — the host's own telemetry hook. Fired loader-side; a throwing or slow\n * callback here NEVER blocks or breaks the call path.\n *\n * - `advertise` — the merged tool list changed (fired with the new set's names).\n * - `call` — a tool call is about to run (`args` present).\n * - `result` — the call settled (`ok`/`error`/`ms`).\n */\nexport interface ToolEvent {\n phase: 'advertise' | 'call' | 'result';\n name: string;\n toolClass: 'hoist' | 'mf' | 'app';\n args?: unknown;\n ok?: boolean;\n error?: string;\n ms?: number;\n}\n\n/**\n * One embed lifecycle event, surfaced to the host via `onEvent` — the host's single\n * telemetry hook. Fired loader-side (lifecycle) and widget-side (chat); a throwing or\n * slow callback NEVER blocks or breaks the mount/call/auth/run path.\n *\n * - `ready` — the widget connected (protocol handshake done).\n * - `open`/`close` — the corner widget was opened/closed. (Inline has no open event —\n * the host's own panel is the open/close control.)\n * - `navigate` — the agent deeplinked the host to one of its own routes.\n * - `auth` — host-auth passthrough: `required` (widget asked), `granted` (a\n * token was handed over), `failed` (no provider result / the provider threw).\n * - `error` — the widget failed to mount / load.\n * - `chat` — a chat-turn moment. Content-free: phase + opaque chatId only.\n * - `tool` — a host-tool lifecycle event (the `ToolEvent` shape, tagged). Also\n * still delivered untagged to the legacy `onToolEvent` hook for back-compat.\n */\nexport type MatterfactEvent =\n | { type: 'ready' }\n | { type: 'open' }\n | { type: 'close' }\n | { type: 'navigate'; href: string }\n | { type: 'auth'; phase: 'required' | 'granted' | 'failed' }\n | { type: 'error'; message: string }\n | { type: 'chat'; phase: 'message' | 'response-start' | 'response-end'; chatId?: string }\n | ({ type: 'tool' } & ToolEvent);\n\n/**\n * A snapshot of the page as the agent sees it.\n *\n * `yaml` is Playwright's ARIA-snapshot rendering — role, accessible name, state,\n * and a ref on anything interactable:\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - button \"Export CSV\" [ref=e9]\n *\n * NOT raw HTML. A real page is tens of thousands of tokens of div soup, it gives\n * the model no handle to act with, and it is a prompt-injection firehose. The\n * a11y tree is a tenth the size and is the only signal that survives in-page —\n * `getEventListeners()` is DevTools-only, so listener-sniffing (the browser-use\n * approach) cannot see a single React handler on a real customer's app.\n */\nexport interface DomSnapshot {\n yaml: string;\n /** Monotonic. A ref is only valid within the snapshot that minted it. */\n seq: number;\n /** True when the walk hit its node budget and stopped. The agent must be told it is not seeing everything. */\n truncated: boolean;\n}\n\n/**\n * Where the user's attention is RIGHT NOW.\n *\n * This is the difference between an assistant that can read your page and one that\n * knows what you're doing. A full DOM snapshot answers \"what is on this screen\"; this\n * answers \"what are you looking at and working in\" — which is what a colleague\n * leaning over reads first. It is small, so it rides on every turn, where the full\n * snapshot does not.\n *\n * Every field here is a LABEL or a REF, never a value. `selection` is the sharpest\n * intent signal there is (\"this is the thing I'm asking about\"), and for exactly that\n * reason it is also where a user might have highlighted their own email — so it is\n * redacted and honours data-mf-private like everything else.\n */\nexport interface FocusContext {\n /** Text the user has selected. The single strongest \"I'm asking about this\" signal. Redacted. */\n selection?: string;\n /** The control the user is working IN — by label and ref, never its contents. */\n focused?: { ref?: ElementRef; label: string; role: string };\n /** The refs currently in the viewport: the handful of things actually on screen, out of the whole tree. */\n visibleRefs?: ElementRef[];\n /** How far down the page they are, 0–1. A cheap proxy for \"which part am I reading\". */\n scroll?: number;\n}\n\n/** Something the user did. Shaped after PostHog's autocapture — one readable line, not a replay frame. */\nexport interface ActivityEvent {\n seq: number;\n ts: number;\n type: 'nav' | 'click' | 'input' | 'submit' | 'selection' | 'custom';\n /** Human-readable: 'clicked button \"Export CSV\"'. Semantic, not coordinates. */\n summary: string;\n ref?: ElementRef;\n data?: Record<string, unknown>;\n}\n\n/**\n * A tool the HOST page exposes to the agent.\n *\n * Deliberately shaped as a superset of WebMCP (`navigator.modelContext`, W3C\n * WebML CG draft / Chrome origin trial). A customer who adopts WebMCP should be\n * able to hand us their existing tool declarations unchanged.\n */\nexport interface HostTool {\n name: string;\n description: string;\n /** JSON Schema. */\n inputSchema: Record<string, unknown>;\n /**\n * A read-only tool may run without asking. Anything that MUTATES the page\n * requires the user to confirm, every time — see the note on ToolCall.\n */\n readOnly?: boolean;\n /**\n * The tiered confirm policy, set by the host (e.g. `window.matterfact.hoist.actions`):\n * `'required'` ⇒ the widget must show a confirm card and get the user's approval\n * before every call; `'auto'` ⇒ it may call without asking. Absent for a tool that\n * predates this policy (treat as `'required'` — the safer default).\n */\n confirm?: 'auto' | 'required';\n}\n\nexport type HostToWidget =\n | { type: 'host.ready'; protocol: number; origin: string }\n | { type: 'host.context'; context: PageContext }\n | { type: 'host.focus'; focus: FocusContext }\n | { type: 'host.snapshot'; snapshot: DomSnapshot }\n | { type: 'host.region'; ref: ElementRef; yaml: string }\n | { type: 'host.activity'; events: ActivityEvent[] }\n | { type: 'host.artifactGrants'; grants: ArtifactGrant[] }\n /**\n * The annotated site map — the app's routes with the host's content\n * classification. Sent on mount and re-sent on navigation (a virtualized SPA can\n * change what's routable). Distinct from the per-page `host.context`: this is the\n * whole app's structure, so the agent can reason about and navigate toward MF\n * content the user isn't currently looking at.\n */\n | { type: 'host.sitemap'; sitemap: SiteMapEntry[] }\n | { type: 'host.tools'; tools: HostTool[] }\n | {\n type: 'host.toolResult';\n callId: string;\n ok: boolean;\n result?: unknown;\n error?: string;\n }\n | { type: 'host.auth'; token: string; expiresAt: number }\n | { type: 'host.theme'; mode: 'light' | 'dark' }\n /**\n * Where the widget currently IS. Sent on mount and after anything that moves it\n * (drag, snap, mode change, viewport resize).\n *\n * The widget cannot work this out for itself — it can't see the viewport, and the\n * loader owns the box. Without it the widget renders its launcher against a stale\n * guess: a launcher dragged to the left edge kept drawing its circle bottom-RIGHT\n * inside a left-anchored box, so the circle jumped as soon as the box grew for the\n * hover pill. `growth` is the direction the pill/menu/panel must open (toward the\n * viewport centre); `mode` decides whether the launcher is a circle or an edge tab.\n */\n | {\n type: 'host.geometry';\n mode: 'float' | 'dock';\n dockSide: 'left' | 'right';\n growth: 'tl' | 'tr' | 'bl' | 'br';\n };\n\n/* ──────────────────────────── widget → host ───────────────────────────── */\n\n/**\n * The agent asking the host to do something.\n *\n * THE SECURITY MODEL, stated once: the page's content is UNTRUSTED. Text on the\n * page can try to instruct the agent, and the moment the agent can act, that stops\n * being a bad answer and becomes a bad ACTION. So:\n *\n * - v1 is READ-ONLY. `snapshot` and `activity` flow; no tool mutates the page.\n * - A tool that is not `readOnly` must be confirmed by the USER, every call. Not\n * \"unless the host opts out\" — every call. The trigger may have been written by\n * the page.\n * - The host is the enforcement point, not the widget. The widget can be lied to;\n * the loader runs in the page and decides what actually happens.\n */\nexport interface ToolCall {\n callId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\nexport type WidgetToHost =\n | { type: 'widget.ready'; protocol: number }\n /**\n * Ask for the FULL page snapshot. This is the agent PULLING detail, not us pushing\n * it: the focus context rides on every turn, but the whole tree is fetched only\n * when the agent decides it needs to look — cheaper, and it reads what's relevant\n * to the question instead of drowning in the footer nav every turn.\n */\n | { type: 'widget.requestSnapshot' }\n /**\n * Pull the DECLARED page context fresh, right now. The host answers with `host.context`.\n *\n * Declared context (`window.matterfact.context`, or a `getPageContext()` callback) is\n * otherwise only published on load and on URL navigation, so in a virtualized SPA it goes\n * stale on any non-navigation state change (a team switch, a filter edit, a selection).\n * The widget pulls it at turn-assembly time — symmetric with `widget.requestSnapshot` —\n * so every turn carries the current context, not the context as of the last route change.\n */\n | { type: 'widget.requestContext' }\n /** Zoom in: the a11y sub-tree under one ref (a table, a form, a card the agent cares about). */\n | { type: 'widget.readRegion'; ref: ElementRef }\n | { type: 'widget.callTool'; call: ToolCall }\n /** Chat opened/closed — the loader resizes the iframe and starts/stops observing. */\n | { type: 'widget.setOpen'; open: boolean }\n | { type: 'widget.resize'; height: number }\n /**\n * Dock / undock the open panel.\n *\n * Docked is a FULL-HEIGHT SIDE PANEL on the launcher's own side — left corners dock\n * to the left edge, right corners to the right, unless `setDockSide` overrides it.\n * This replaces the old `setExpanded`, which was hardcoded to the right edge and so\n * threw the panel across the screen whenever the launcher sat on the left.\n *\n * The loader owns the box, so only it can do this — `widget.resize` (height-only)\n * can neither widen the panel nor move it to an edge.\n */\n | { type: 'widget.setMode'; mode: 'float' | 'dock' }\n /** Which edge the tab and its panel live on. */\n | { type: 'widget.setDockSide'; side: 'left' | 'right' }\n /** Place the FLOATING launcher at a specific corner (the menu's snap picker). */\n | { type: 'widget.snapCorner'; corner: 'tl' | 'tr' | 'bl' | 'br' }\n /**\n * Resize the COLLAPSED launcher's host box so the widget can paint outside the 56px\n * circle — the hover pill (`{w:180,h:56}`) or the context menu (its own box). The\n * iframe clips to the host box, so anything beside the circle is invisible until the\n * host makes room. `{w:56,h:56}` returns to the bare circle. Ignored while open.\n */\n | { type: 'widget.setLauncherRegion'; w: number; h: number }\n /**\n * User resize of the floating panel, via the grip on its inner corner.\n *\n * Same contract as the launcher drag below, and for the same reason: the press is\n * captured by the iframe, so the host cannot see the moves. The widget tracks the\n * gesture and sends SCREEN-coordinate deltas; the loader owns the sizing, the\n * per-corner sign of the delta, and the clamp.\n */\n | { type: 'widget.resizeStart' }\n | { type: 'widget.resizeMove'; dx: number; dy: number }\n | { type: 'widget.resizeEnd' }\n /**\n * Launcher drag. The widget tracks the gesture; the host only moves the element.\n *\n * It has to be this way round, and the reason is easy to get wrong: a press that starts\n * inside an iframe is implicitly captured by that iframe, so every pointermove and the\n * pointerup belong to the widget's document until the button comes up. The host cannot\n * see them at all — not even through an overlay of its own, because capture beats hit\n * testing. So the host cannot take over a drag mid-gesture; it can only be told.\n *\n * `dx`/`dy` are deltas in SCREEN coordinates, which is the other half of the trick:\n * client coordinates are measured against the iframe's own viewport, and the iframe is\n * being moved under the cursor as the drag proceeds — so the pointer would appear to\n * stop moving and the launcher would stall after one step. Screen coordinates are\n * absolute and immune to that feedback loop.\n */\n | { type: 'widget.dragStart' }\n | { type: 'widget.dragMove'; dx: number; dy: number }\n | { type: 'widget.dragEnd' }\n /** Put the launcher back in the default corner and forget the saved size/dock. */\n | { type: 'widget.resetPos' }\n /** Get out of the way until the page reloads (a menu action, not a setting). */\n | { type: 'widget.hide' }\n /** The widget has no session; the host must run the hosted-login popup. */\n | { type: 'widget.needsAuth' }\n /**\n * Deeplink the host to one of its OWN routes — the \"open on page\" control on a\n * co-embedded document's side-panel viewer. The widget is a cross-origin iframe and\n * can't navigate the top window itself, so it asks the loader, which resolves the\n * href against the host location and refuses anything off the host's own origin.\n */\n | { type: 'widget.navigate'; href: string }\n /**\n * A chat-turn lifecycle moment, forwarded by the loader to the host's `onEvent`.\n * Content-free: `phase` + an opaque `chatId`, never message text. Additive.\n */\n | {\n type: 'widget.chat';\n phase: 'message' | 'response-start' | 'response-end';\n chatId?: string;\n };\n\n/* ───────────────────────────── envelope ───────────────────────────────── */\n\n/**\n * Everything on the wire is wrapped.\n *\n * `channel` keeps us out of the host page's own postMessage traffic (and out of\n * every other widget's). The receiver ALSO checks `event.origin` against an\n * allowlist and `event.source` against the expected window, on every single\n * message — a namespace is not a security boundary, it is a politeness.\n */\nexport interface Envelope<T> {\n channel: typeof CHANNEL;\n protocol: number;\n /** Correlates a response to its request; absent for notifications. */\n id?: string;\n payload: T;\n}\n\nexport function envelope<T>(payload: T, id?: string): Envelope<T> {\n return {\n channel: CHANNEL,\n protocol: PROTOCOL_VERSION,\n ...(id ? { id } : {}),\n payload,\n };\n}\n\nexport function isEnvelope(data: unknown): data is Envelope<unknown> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { channel?: unknown }).channel === CHANNEL\n );\n}\n","/**\n * Pure geometry for the embed launcher/panel.\n *\n * No DOM, no React — every function here is a total map from numbers/strings to\n * numbers/strings. That is deliberate: the loader attaches a CLOSED shadow root, so\n * the iframe inside it is unreachable from a test. Keeping the whole positioning\n * model in pure functions is what makes it verifiable at all; `loader.ts` is then a\n * thin applier that sets the returned box on the light-DOM host element.\n *\n * There are two MODES, and the mode decides both how the widget rests and how it opens:\n *\n * dock (default) — the launcher is a TAB flush against a side edge, and opening\n * gives a full-height side panel on that edge. This is the shape\n * most hosts want: it reads as part of the app, not as a bubble\n * floating over it.\n * float — the launcher is a CIRCLE the user can put anywhere, and opening\n * gives a panel anchored near it.\n *\n * In float the position is FREE. A corner is only recorded when the user drops the\n * launcher near one (see `snapOrFree`), because a snap that always fires isn't a\n * convenience, it's a constraint — you could never place the thing mid-edge. Recording\n * the corner when it IS snapped is what lets it stay in that corner across a viewport\n * resize, where a raw x/y would drift.\n */\n\nexport type Corner = 'tl' | 'tr' | 'bl' | 'br';\nexport type DockSide = 'left' | 'right';\nexport type Mode = 'float' | 'dock';\n\nexport interface EmbedGeometry {\n mode: Mode;\n /** float: the corner it snapped to, or null when freely placed. */\n corner: Corner | null;\n /** float: free launcher top-left, used only when `corner` is null. */\n x: number;\n y: number;\n floatW: number;\n floatH: number;\n dockSide: DockSide;\n /** dock: the tab's top offset along its edge. */\n tabY: number;\n dockW: number;\n}\n\n/**\n * A set of fixed-position box properties to apply to the host `<div>`.\n * Exactly two of top/right/bottom/left carry a px value; the other two are 'auto',\n * so the box stays pinned to the edges it grows away from.\n */\nexport interface BoxStyle {\n top: string;\n right: string;\n bottom: string;\n left: string;\n width: string;\n height: string;\n}\n\nexport const MARGIN = 20;\nexport const LAUNCHER = 56;\nexport const PILL_W = 180;\n/** How close to a corner a drop must land before it snaps. Generous enough to feel\n * magnetic, small enough that the middle of an edge is still reachable. */\nexport const SNAP_RADIUS = 96;\n/**\n * The docked launcher tab.\n *\n * Wide enough to carry the logo mark, and clearly TALLER than it is wide so the shape\n * still reads as a tab on the page edge. The ratio is the thing that matters: at a\n * near-square size any inner radius rounds it into a lozenge, which is what \"squished\n * circle\" looks like.\n */\nexport const TAB_W = 44;\nexport const TAB_H = 132;\n/**\n * How close to a SIDE edge a drop must land to become a docked tab. Dragging the tab\n * away from the edge is therefore how you float it, and dragging the circle back to an\n * edge is how you dock it — the placement follows where you put the thing, so there is\n * no mode switch to go hunting for.\n */\nexport const EDGE_DOCK = 64;\nexport const DEFAULT_FLOAT_W = 420;\nexport const DEFAULT_FLOAT_H = 640;\nexport const MIN_FLOAT_W = 320;\nexport const MIN_FLOAT_H = 420;\nexport const DEFAULT_DOCK_W = 600;\nexport const MIN_DOCK_W = 320;\n\nconst CORNERS: readonly Corner[] = ['tl', 'tr', 'bl', 'br'];\n\nexport function defaultGeometry(): EmbedGeometry {\n return {\n // Dock is the default: a side panel reads as part of the host app.\n mode: 'dock',\n corner: 'br',\n x: 0,\n y: 0,\n floatW: DEFAULT_FLOAT_W,\n floatH: DEFAULT_FLOAT_H,\n dockSide: 'right',\n tabY: 0, // 0 => centre it (see tabTop)\n dockW: DEFAULT_DOCK_W,\n };\n}\n\nfunction clamp(n: number, lo: number, hi: number): number {\n return Math.min(Math.max(n, lo), hi);\n}\n\n/** Where a snapped corner puts the launcher's top-left. */\nfunction cornerOrigin(\n corner: Corner,\n w: number,\n h: number,\n vw: number,\n vh: number,\n): { x: number; y: number } {\n return {\n x: corner[1] === 'l' ? MARGIN : vw - MARGIN - w,\n y: corner[0] === 't' ? MARGIN : vh - MARGIN - h,\n };\n}\n\n/** The launcher's top-left in float mode: its snapped corner, else its free spot. */\nexport function launcherOrigin(\n g: EmbedGeometry,\n vw: number,\n vh: number,\n): { x: number; y: number } {\n if (g.corner) return cornerOrigin(g.corner, LAUNCHER, LAUNCHER, vw, vh);\n return {\n x: clamp(g.x, MARGIN, Math.max(MARGIN, vw - MARGIN - LAUNCHER)),\n y: clamp(g.y, MARGIN, Math.max(MARGIN, vh - MARGIN - LAUNCHER)),\n };\n}\n\n/**\n * Which way things grow from the launcher: toward the viewport centre.\n *\n * Distinct from `geometry.corner` on purpose — a FREELY placed launcher has no corner,\n * but its pill, menu and panel still have to open inward or they'd run off the page.\n */\nexport function growthCorner(g: EmbedGeometry, vw: number, vh: number): Corner {\n if (g.corner) return g.corner;\n const o = launcherOrigin(g, vw, vh);\n return nearestCorner(o.x + LAUNCHER / 2, o.y + LAUNCHER / 2, vw, vh);\n}\n\n/** Which quadrant a point is in. */\nexport function nearestCorner(\n cx: number,\n cy: number,\n vw: number,\n vh: number,\n): Corner {\n return `${cy < vh / 2 ? 't' : 'b'}${cx < vw / 2 ? 'l' : 'r'}` as Corner;\n}\n\n/**\n * Resolve a drop: snap to a corner only if it landed NEAR one, else keep it where the\n * user put it (clamped on-screen). Returns the fields to merge into the geometry.\n */\nexport function snapOrFree(\n x: number,\n y: number,\n vw: number,\n vh: number,\n): { corner: Corner | null; x: number; y: number } {\n const cx = clamp(x, MARGIN, Math.max(MARGIN, vw - MARGIN - LAUNCHER));\n const cy = clamp(y, MARGIN, Math.max(MARGIN, vh - MARGIN - LAUNCHER));\n for (const corner of CORNERS) {\n const o = cornerOrigin(corner, LAUNCHER, LAUNCHER, vw, vh);\n if (Math.hypot(cx - o.x, cy - o.y) <= SNAP_RADIUS) {\n return { corner, x: cx, y: cy };\n }\n }\n return { corner: null, x: cx, y: cy };\n}\n\n/** Is this box close enough to a side edge to be docked? The live half of the drag. */\nexport function edgeDock(x: number, w: number, vw: number): DockSide | null {\n if (x <= EDGE_DOCK) return 'left';\n if (x + w >= vw - EDGE_DOCK) return 'right';\n return null;\n}\n\n/**\n * The point a drag MOVES — the widget's logical anchor, not its painted box.\n *\n * They differ once the panel is open: the box is the whole panel, but what the geometry\n * stores (and what a corner drop resolves) is the launcher's own origin. Dragging by the\n * box's top-left would shift the widget by the panel's size the moment you grabbed it.\n */\nexport function dragAnchor(\n g: EmbedGeometry,\n vw: number,\n vh: number,\n): { x: number; y: number } {\n if (g.mode === 'dock') {\n return { x: g.dockSide === 'left' ? 0 : vw - TAB_W, y: tabTop(g, vh) };\n }\n return launcherOrigin(g, vw, vh);\n}\n\n/**\n * The widget's painted horizontal extent for the state it is in.\n *\n * Derived, not measured: `getBoundingClientRect` is unavailable before layout (and is\n * all-zeros under jsdom), and the loader already knows every input. This is what the\n * edge test reads — \"dragged to the side\" is about the box you can see touching the\n * edge, which for an open panel is nowhere near its anchor.\n */\nexport function visibleBox(\n g: EmbedGeometry,\n open: boolean,\n vw: number,\n vh: number,\n): { x: number; w: number } {\n if (g.mode === 'dock') {\n const w = open\n ? Math.min(Math.max(g.dockW, MIN_DOCK_W), Math.max(0, vw - 2 * MARGIN))\n : TAB_W;\n return { x: g.dockSide === 'left' ? 0 : vw - w, w };\n }\n const o = launcherOrigin(g, vw, vh);\n if (!open) return { x: o.x, w: LAUNCHER };\n const { w } = clampSize(g.floatW, g.floatH, vw, vh, MIN_FLOAT_W, MIN_FLOAT_H);\n // A right-growing panel hangs LEFT off the launcher, so its left edge is the\n // launcher's right edge minus the panel width.\n return {\n x: growthCorner(g, vw, vh)[1] === 'r' ? o.x + LAUNCHER - w : o.x,\n w,\n };\n}\n\n/**\n * Resolve a drop into a PLACEMENT — which mode the widget lands in, and where.\n *\n * Two different measurements, deliberately:\n * - the EDGE test uses the widget's visible box, because \"dragged to the side\" is\n * about what you can see touching the edge. Testing the anchor instead means a\n * 420px-wide panel whose right edge is already against the screen refuses to dock,\n * since its anchor is still 400px away.\n * - the CORNER test uses the anchor, because that is what a corner placement stores.\n *\n * Priority matters, and corner beats edge on purpose: every corner is also within reach\n * of a side edge, so checking the edge first would make corner-snapping unreachable and\n * quietly turn the floating circle into a tab whenever you aimed for a corner.\n */\nexport function placeDrop(\n anchorX: number,\n anchorY: number,\n boxLeft: number,\n boxW: number,\n vw: number,\n vh: number,\n):\n | { mode: 'float'; corner: Corner | null; x: number; y: number }\n | { mode: 'dock'; dockSide: DockSide; tabY: number } {\n const snapped = snapOrFree(anchorX, anchorY, vw, vh);\n if (snapped.corner) return { mode: 'float', ...snapped };\n const side = edgeDock(boxLeft, boxW, vw);\n if (side) {\n return {\n mode: 'dock',\n dockSide: side,\n tabY: clamp(anchorY, 0, Math.max(0, vh - TAB_H)),\n };\n }\n return { mode: 'float', ...snapped };\n}\n\nexport function dockSideForCorner(corner: Corner): DockSide {\n return corner[1] === 'l' ? 'left' : 'right';\n}\n\nexport function effectiveDockSide(g: EmbedGeometry): DockSide {\n return g.dockSide;\n}\n\n/**\n * Fit a size inside the viewport.\n *\n * Order matters: the minimum is applied FIRST and the viewport cap LAST, so on a\n * viewport smaller than the minimum the VIEWPORT wins. That is the whole point — a\n * panel that honoured its minimum past the viewport edge would hang off the page.\n */\nexport function clampSize(\n w: number,\n h: number,\n vw: number,\n vh: number,\n minW: number,\n minH: number,\n): { w: number; h: number } {\n return {\n w: Math.min(Math.max(w, minW), Math.max(0, vw - 2 * MARGIN)),\n h: Math.min(Math.max(h, minH), Math.max(0, vh - 2 * MARGIN)),\n };\n}\n\n/**\n * Apply a resize drag to the float size. The grip sits on the panel's INNER corner\n * (the one facing viewport centre), so dragging it away from the anchored corner\n * grows the panel — which flips the sign of the delta per corner. Unclamped.\n */\nexport function applyResizeDelta(\n corner: Corner,\n startW: number,\n startH: number,\n dx: number,\n dy: number,\n): { w: number; h: number } {\n const wSign = corner[1] === 'r' ? -1 : 1; // right-anchored grows on -dx\n const hSign = corner[0] === 'b' ? -1 : 1; // bottom-anchored grows on -dy\n return { w: startW + wSign * dx, h: startH + hSign * dy };\n}\n\n/** Widen/narrow a docked panel by dragging its inner edge. */\nexport function applyDockResizeDelta(\n side: DockSide,\n startW: number,\n dx: number,\n): number {\n return side === 'right' ? startW - dx : startW + dx;\n}\n\nexport function parseGeometry(raw: string | null): EmbedGeometry | null {\n if (!raw) return null;\n try {\n const p = JSON.parse(raw) as Partial<EmbedGeometry>;\n // Pre-mode values (and the even older {right,bottom}) are dropped rather than\n // guessed at — there is no honest mapping from them onto this model.\n if (!p || (p.mode !== 'float' && p.mode !== 'dock')) return null;\n const d = defaultGeometry();\n const num = (v: unknown, dv: number) => (typeof v === 'number' ? v : dv);\n return {\n mode: p.mode,\n corner: CORNERS.includes(p.corner as Corner)\n ? (p.corner as Corner)\n : null,\n x: num(p.x, d.x),\n y: num(p.y, d.y),\n floatW: num(p.floatW, d.floatW),\n floatH: num(p.floatH, d.floatH),\n dockSide: p.dockSide === 'left' ? 'left' : 'right',\n tabY: num(p.tabY, d.tabY),\n dockW: num(p.dockW, d.dockW),\n };\n } catch {\n return null;\n }\n}\n\nexport function serializeGeometry(g: EmbedGeometry): string {\n return JSON.stringify(g);\n}\n\n/* ─────────────────────────── box builders ─────────────────────────────── */\n\nconst px = (n: number) => `${n}px`;\n\n/**\n * Pin the box by the two edges nearest the growth corner, so it grows inward.\n * Works for a snapped launcher and a freely-placed one alike: the anchor is always\n * the launcher's own top-left plus its size, expressed from whichever edges it grows\n * away from.\n */\nfunction boxAt(\n ox: number,\n oy: number,\n w: number,\n h: number,\n corner: Corner,\n vw: number,\n vh: number,\n): BoxStyle {\n const right = corner[1] === 'r';\n const bottom = corner[0] === 'b';\n // The anchored edges are measured from the LAUNCHER's own far side, so the launcher\n // stays put while the box grows past it...\n const rawX = right ? vw - (ox + LAUNCHER) : ox;\n const rawY = bottom ? vh - (oy + LAUNCHER) : oy;\n // ...but only as far as the viewport allows. Clamping the SIZE is not enough: a\n // launcher parked mid-page opens a 640px panel that grows straight off the top, and\n // the panel's header — the only way to close, dock or drag it — goes with it. So the\n // pinned offset is clamped too, which shifts the panel back into view while keeping\n // it as close to the launcher as it can be.\n const x = clamp(rawX, MARGIN, Math.max(MARGIN, vw - MARGIN - w));\n const y = clamp(rawY, MARGIN, Math.max(MARGIN, vh - MARGIN - h));\n return {\n top: bottom ? 'auto' : px(y),\n bottom: bottom ? px(y) : 'auto',\n left: right ? 'auto' : px(x),\n right: right ? px(x) : 'auto',\n width: px(w),\n height: px(h),\n };\n}\n\n/** The tab's top offset; a stored 0 means \"centre it\". */\nfunction tabTop(g: EmbedGeometry, vh: number): number {\n const max = Math.max(0, vh - TAB_H);\n return clamp(g.tabY || Math.round((vh - TAB_H) / 2), 0, max);\n}\n\n/** The docked launcher: a slim tab flush against its edge (no margin — it hugs). */\nexport function tabBox(g: EmbedGeometry, vw: number, vh: number): BoxStyle {\n const left = g.dockSide === 'left';\n return {\n top: px(tabTop(g, vh)),\n bottom: 'auto',\n left: left ? '0px' : 'auto',\n right: left ? 'auto' : '0px',\n width: px(TAB_W),\n height: px(TAB_H),\n };\n}\n\n/**\n * ANY float-mode box — the circle, the hover pill, the menu region, the open panel.\n *\n * They are all the same shape: a box of size w×h anchored at the launcher and growing\n * inward. One function rather than four wrappers, because this module is bundled into\n * the per-page loader stub and four near-identical bodies is pure weight.\n */\nexport function floatChrome(\n g: EmbedGeometry,\n w: number,\n h: number,\n vw: number,\n vh: number,\n /**\n * Override the growth direction. Used to FREEZE it for the length of a drag: growth\n * is derived from which half of the viewport the launcher is in, so dragging an open\n * panel across the middle would otherwise flip the side it grows from and jump the\n * panel by its own width. Held still, it tracks the cursor.\n */\n growth?: Corner,\n): BoxStyle {\n const o = launcherOrigin(g, vw, vh);\n return boxAt(o.x, o.y, w, h, growth ?? growthCorner(g, vw, vh), vw, vh);\n}\n\n/** The region the docked tab grows into for its context menu — hugging its edge. */\nexport function dockChrome(\n g: EmbedGeometry,\n w: number,\n h: number,\n vw: number,\n vh: number,\n): BoxStyle {\n const left = g.dockSide === 'left';\n return {\n top: px(tabTop(g, vh)),\n bottom: 'auto',\n left: left ? '0px' : 'auto',\n right: left ? 'auto' : '0px',\n width: px(w),\n height: px(h),\n };\n}\n\n/** The collapsed launcher for the current mode: dock → tab, float → circle. */\nexport function launcherBox(\n g: EmbedGeometry,\n vw: number,\n vh: number,\n): BoxStyle {\n return g.mode === 'dock'\n ? tabBox(g, vw, vh)\n : floatChrome(g, LAUNCHER, LAUNCHER, vw, vh);\n}\n\n/** The floating open panel, anchored at the launcher and clamped on-screen. */\nexport function floatBox(\n g: EmbedGeometry,\n vw: number,\n vh: number,\n growth?: Corner,\n): BoxStyle {\n const f = clampSize(g.floatW, g.floatH, vw, vh, MIN_FLOAT_W, MIN_FLOAT_H);\n return floatChrome(g, f.w, f.h, vw, vh, growth);\n}\n\n/** Full-height side panel flush against its edge. */\nexport function dockBox(g: EmbedGeometry, vw: number, _vh: number): BoxStyle {\n const w = Math.min(\n Math.max(g.dockW, MIN_DOCK_W),\n Math.max(0, vw - 2 * MARGIN),\n );\n const left = g.dockSide === 'left';\n return {\n top: '0px',\n bottom: '0px',\n height: 'auto',\n left: left ? '0px' : 'auto',\n right: left ? 'auto' : '0px',\n width: px(w),\n };\n}\n","import {\n CHANNEL,\n PROTOCOL_VERSION,\n envelope,\n isEnvelope,\n type HostToWidget,\n type MatterfactEvent,\n type WidgetToHost,\n} from './protocol';\n// Type-only: erased at build, so it does NOT pull the lazy ./context chunk eagerly.\nimport type { PageContextProvider } from './context';\nimport {\n applyDockResizeDelta,\n applyResizeDelta,\n clampSize,\n defaultGeometry,\n dockBox,\n floatBox,\n growthCorner,\n tabBox,\n dockChrome,\n floatChrome,\n parseGeometry,\n serializeGeometry,\n dragAnchor,\n visibleBox,\n edgeDock,\n placeDrop,\n LAUNCHER,\n MARGIN,\n MIN_DOCK_W,\n MIN_FLOAT_H,\n MIN_FLOAT_W,\n DEFAULT_DOCK_W,\n type BoxStyle,\n type Corner,\n type EmbedGeometry,\n} from './geometry';\n\n/**\n * The matterfact embed loader.\n *\n * <script type=\"module\" src=\"https://app.matterfact.com/embed/embed.js\"\n * data-key=\"pk_live_acme_...\"\n * data-origin=\"https://app.matterfact.com\"></script>\n *\n * This file runs on EVERY page load of a customer's site, so it is deliberately\n * tiny and deliberately dumb:\n *\n * - zero dependencies\n * - it does NOT read the DOM. The snapshot/activity code is a separate chunk,\n * fetched only when the user actually opens the chat. A customer should pay\n * nothing for a widget nobody clicked.\n * - it does NOT bundle React, or a CSS framework, or an RPC library.\n *\n * `iframe-resizer` is the thing you will be tempted to reach for here. It is\n * GPL-3.0 and cannot ship in this file. The ResizeObserver bridge below is the\n * fifteen lines it would have cost you anyway.\n */\n\n/** Returns a token this matterfact deployment's auth provider trusts (Firebase idToken,\n * Entra token, …). May be async; return null when there's no signed-in user. */\nexport type AuthTokenProvider = () => string | null | Promise<string | null>;\n\nexport interface LoaderConfig {\n publishableKey: string;\n /** Origin of the widget. Overridable for dev/self-hosted; defaults to production. */\n origin: string;\n theme: 'light' | 'dark' | 'auto';\n /** Optional label identifying THIS embedding, when one app embeds the agent in more\n * than one place (e.g. \"orders\" vs \"support\"). Stamped on runs/threads so usage and\n * history can be told apart per surface. Free-form; the app_id (from the session)\n * is the trusted half. */\n surface: string;\n /**\n * OPTIONAL host-auth passthrough, for TRUSTED first-party embeds (the admin portal,\n * EMC). When set, the host page already holds a token this deployment's auth provider\n * trusts (its Firebase idToken, an Entra token, …); the loader hands it to the widget\n * on `widget.needsAuth` instead of opening a sign-in popup. The backend still verifies\n * the token, so identity can't be forged — this only skips a redundant second sign-in.\n * Called on demand (so tokens can refresh). Absent ⇒ the popup/inline sign-in flow.\n * The `<script>` loader has no config here; it reads window.matterfact.getEmbedAuthToken\n * instead (see provideAuth).\n */\n authTokenProvider?: AuthTokenProvider;\n /**\n * OPTIONAL pull callback for DECLARED page context, for a host whose context changes\n * without a URL navigation (a virtualized SPA: team switch, filter edit, selection). The\n * widget calls it at turn-assembly time (via `widget.requestContext`), so every turn\n * carries current context instead of context as of the last route change. Symmetric with\n * `authTokenProvider`. The `<script>` loader has no config here; it reads\n * `window.matterfact.getPageContext` instead (see resolveDeclaredContext in context.ts).\n * Absent ⇒ falls back to the static `window.matterfact.context`.\n */\n pageContextProvider?: PageContextProvider;\n /**\n * Render INTO this element instead of floating in the corner — for a host that has its\n * own side panel, tool drawer or tab and wants the agent to live there.\n *\n * This inverts who owns the chrome. In corner mode the widget owns everything: it draws\n * its own launcher and it tells us how big to be (setOpen/setDocked/resize). Inside\n * someone else's panel, both are theirs — a widget that resized its host's drawer, or\n * drew a second floating bubble inside it, is just broken. So here we fill the\n * container, ignore the size messages, and the widget skips the launcher and renders\n * the chat directly.\n *\n * The host also owns visibility: showing and hiding their own panel IS the open/close\n * control, so there is nothing for us to add.\n */\n container?: HTMLElement | null;\n /**\n * Turn off ALL host-page observation — no `host.context`, no `host.focus`, no\n * `host.snapshot`, no `host.activity`, no `host.artifactGrants`. Not a filter on what\n * gets sent: when this is false the loader never installs the DOM/nav/focus/activity\n * observers in the first place, and an inbound `widget.requestSnapshot` is ignored\n * rather than answered. Default `true` — seeing the page is the widget's whole value\n * proposition; this is the escape hatch for a host that wants agent chat with nothing\n * about the page ever reaching it.\n */\n pageContext?: boolean;\n /**\n * Force dev mode (see `devRequested()` below) without needing `?mfdev=1` on the host\n * URL. This is the programmatic equivalent of that trigger, not a replacement for it —\n * the URL param still works untouched; `mount()` ORs the two together.\n */\n dev?: boolean;\n}\n\nconst DEFAULT_ORIGIN = 'https://app.matterfact.com';\n\n/**\n * Has someone asked to see what the widget is doing? `?mfdev=1` on the HOST page.\n *\n * Driven by the host's own URL rather than a `data-` attribute on purpose: an engineer\n * debugging a page they didn't write can add a query param, but they cannot redeploy the\n * customer's site to change a script tag. It's also ephemeral — it lasts exactly as long\n * as that URL, so nobody can leave it on by accident.\n *\n * This only surfaces what the widget already collects FROM THE PAGE IT'S ON, to the\n * person whose page it is. It grants no access: the session, the origin allowlist and\n * the route scope are all enforced server-side and none of them consult this.\n */\nfunction devRequested(): boolean {\n try {\n return new URLSearchParams(location.search).get('mfdev') === '1';\n } catch {\n return false;\n }\n}\n\nfunction readConfig(): LoaderConfig | null {\n // `document.currentScript` is null inside a module or after async execution, so\n // fall back to finding our own tag by src.\n const el =\n (document.currentScript as HTMLScriptElement | null) ??\n document.querySelector<HTMLScriptElement>('script[data-key][src*=\"embed\"]');\n\n const publishableKey = el?.dataset.key;\n if (!publishableKey) {\n console.error('[matterfact] missing data-key on the embed script tag');\n return null;\n }\n // `data-container=\"#panel\"` renders into the host's own element instead of the\n // corner. A selector rather than an element, because a script tag can't hand us a\n // reference — and if it doesn't resolve we fall back to the corner rather than\n // vanish: a widget nobody can find looks identical to a broken install.\n const sel = el?.dataset.container;\n const container = sel ? document.querySelector<HTMLElement>(sel) : null;\n if (sel && !container) {\n console.error(\n `[matterfact] data-container=\"${sel}\" matched nothing; falling back to the corner`,\n );\n }\n\n // `data-page-context=\"off\"` (also \"false\" / \"0\") disables all page observation.\n // Anything else — including the attribute being absent — leaves it on. Lowercased\n // once before comparing: a privacy toggle that silently stays ON for \"Off\" or\n // \"FALSE\" (a customer's templating/CMS can easily produce either, unintentionally)\n // is exactly the wrong direction for this to fail in.\n const pageContextAttr = el?.dataset.pageContext?.toLowerCase();\n\n return {\n publishableKey,\n origin: el?.dataset.origin || DEFAULT_ORIGIN,\n theme: (el?.dataset.theme as LoaderConfig['theme']) || 'auto',\n surface: el?.dataset.surface || '',\n container,\n pageContext:\n pageContextAttr !== 'off' &&\n pageContextAttr !== 'false' &&\n pageContextAttr !== '0',\n // No `data-dev` — see the `dev` field's doc comment: the URL trigger is the\n // point for the script-tag path, so there is deliberately no script-tag knob here.\n // No `data-actions` either: the action policy lives entirely in the lazy chunk,\n // read straight off `window.matterfact.hoist.actions` by hoist-runtime.ts's\n // readActionsConfig() — see LoaderConfig's class doc and MatterfactAgentProps.actions\n // (react.tsx) for the one remaining way to SET that global programmatically.\n };\n}\n\nconst POS_KEY = 'mf.embed.pos';\n\nclass EmbedHost {\n private iframe: HTMLIFrameElement | null = null;\n private shadow: ShadowRoot | null = null;\n /** Buffered until the widget says it's listening — postMessage before load is dropped silently. */\n private queue: HostToWidget[] = [];\n private ready = false;\n private open = false;\n /** The persisted box: launcher corner, float size, dock state/side/width. */\n private geo: EmbedGeometry = defaultGeometry();\n /** Float size at resizeStart; resizeMove deltas apply against it (they're cumulative). */\n private resizeBase: { w: number; h: number } | null = null;\n /** Docked width at resizeStart — the docked panel resizes in one axis only. */\n private dockBase = DEFAULT_DOCK_W;\n /** The widget's logical anchor when the drag began, and where it is now. Deltas arrive\n * cumulative from the press, so the current spot is simply origin + delta — no need to\n * read the box back, which stops being the thing we're moving the moment it docks. */\n private dragFrom: { x: number; y: number } | null = null;\n private dragAt = { x: 0, y: 0 };\n /** The painted box when the drag began — the edge test measures what you can SEE\n * touching the screen edge, which is not the anchor once the panel is open. */\n private dragBox = { x: 0, w: 0 };\n /** Growth direction frozen for the drag — see floatChrome's `growth` param. */\n private dragGrowth: Corner | null = null;\n /**\n * Has this drag been clear of the dock band yet?\n *\n * The resting position is INSIDE the band — a corner-anchored widget sits MARGIN\n * (20px) from the edge, well within EDGE_DOCK (64px) — so without this, picking one\n * up docked it instantly, before it had moved anywhere. Docking now requires\n * ENTERING the band rather than merely starting in it.\n */\n private dragLeftBand = false;\n /** Loaded on first open. Holds everything that touches the customer's DOM. */\n private context: Promise<typeof import('./context')> | null = null;\n /** The host element; kept so `destroy()` can remove it (React lifecycle). */\n private hostEl: HTMLDivElement | null = null;\n /** Rendering into the host's own element: they own the box, the chrome and visibility. */\n private readonly inline: boolean;\n /** Host-auth storm guard (see provideAuth). Counts getAuthToken calls; past a cap we stop\n * calling the provider, rather than joining the storm. This host instance OUTLIVES iframe\n * reloads, so — unlike anything in the widget — the counter survives the very reload loop\n * that drives the storm. (Kept tiny on purpose: this file has a hard per-page size budget;\n * the widget side carries the windowed/retry-after-settle half.) Terse name = fewer bytes\n * in the stub; it is the host-auth request count. */\n private ac = 0;\n\n constructor(private config: LoaderConfig) {\n this.inline = !!config.container;\n }\n\n mount() {\n // A CLOSED shadow root, on a container that resets every inherited property.\n //\n // We are a guest on someone else's page. Their CSS must not reach into us, our\n // CSS must not leak out, and their JS should not be able to walk into our tree\n // by accident (closed mode: `host.shadowRoot` is null). `contain` stops our\n // layout/paint from invalidating theirs.\n const host = document.createElement('div');\n this.hostEl = host;\n host.id = 'matterfact-embed';\n\n if (this.inline) {\n // The container's box IS the widget's box. No fixed positioning, no z-index\n // scramble, no drag: where this sits is the host's layout problem, which is the\n // entire point of asking for it.\n host.style.cssText = [\n 'all: initial',\n 'position: relative',\n 'display: block',\n 'width: 100%',\n 'height: 100%',\n 'contain: layout style',\n ].join(';');\n this.config.container!.appendChild(host);\n } else {\n this.geo = this.readGeometry();\n host.style.cssText = [\n 'all: initial',\n 'position: fixed',\n // Below the max so a host that genuinely needs to cover us (a modal, a cookie\n // banner they are legally obliged to show) still can.\n 'z-index: 2147483000',\n 'contain: layout style',\n // The host element owns the BOX now (position AND size); the iframe fills it.\n // Transitioning the box is what makes the corner snap and the open/dock read as\n // motion rather than a jump. Suppressed during drag/resize (see those handlers).\n 'transition: width .18s ease, height .18s ease, top .18s ease,' +\n ' right .18s ease, bottom .18s ease, left .18s ease',\n ].join(';');\n document.body.appendChild(host);\n }\n\n this.shadow = host.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n // Shared prefix, then only what differs. This ships on every page load and the stub\n // has ~no headroom, so the two modes must not each carry a whole stylesheet.\n //\n // Inline fills the host's box and adds nothing: no radius, no shadow. Their panel\n // already has whatever chrome they chose; ours would sit inside it looking like a\n // mistake.\n // The iframe simply FILLS the host element, in both modes. The host owns every\n // dimension, so all the geometry lives in one place (and stays observable in the\n // light DOM — this shadow root is closed, so nothing in here can be inspected).\n // Only the corner treatment differs, switched off the host's data-mode: a circle\n // while it's the launcher, a card once it's a pill, menu or panel.\n //\n // Hairline ring + soft ambient: the widget must read as a crisp shape on ANY host\n // background, including pure white where a shadow alone bleeds.\n // Only the OPEN panel is a surface of ours. While collapsed the widget draws its\n // own shapes — the tab, the circle, the menu — onto the host's page, so the iframe\n // must not paint a card behind them: the host box grows to make room for the menu,\n // and a background there shows up as a slab hanging off the launcher.\n style.textContent =\n ':host{all:initial}' +\n 'iframe{border:0;display:block;width:100%;height:100%;background:transparent}' +\n (this.inline\n ? ''\n : // color-scheme only on the OPEN panel — on a collapsed launcher it makes the\n // UA paint an opaque canvas base behind our shapes.\n ':host([data-mode=\"float\"]) iframe,:host([data-mode=\"dock\"]) iframe' +\n '{color-scheme:light dark}' +\n ':host([data-mode=\"float\"]) iframe{border-radius:12px;' +\n 'box-shadow:0 0 0 1px #00000014,0 8px 40px #00000029}' +\n ':host([data-mode=\"dock\"]) iframe{box-shadow:0 0 0 1px #00000014,' +\n '0 8px 40px #00000029}' +\n ':host([data-mode=\"dock\"][data-flush=\"right\"]) iframe' +\n '{border-radius:12px 0 0 12px}' +\n ':host([data-mode=\"dock\"][data-flush=\"left\"]) iframe' +\n '{border-radius:0 12px 12px 0}');\n this.shadow.appendChild(style);\n\n const iframe = document.createElement('iframe');\n iframe.title = 'matterfact assistant';\n //\n // `allow-same-origin` is REQUIRED, and leaving it out is the trap.\n //\n // Without it the framed document gets an OPAQUE origin: its postMessage arrives\n // as `event.origin === \"null\"`, so our own origin check rejects the handshake and\n // the bridge silently never connects. It also denies the widget any storage at\n // all — no session, no auth, ever.\n //\n // The familiar warning — \"allow-scripts + allow-same-origin lets the frame escape\n // its sandbox\" — is about a frame that is SAME-ORIGIN WITH THE FRAMER, which can\n // then reach up and delete its own sandbox attribute. Ours is cross-origin to the\n // host by construction (that is the entire security model), so it cannot touch\n // this element. What the sandbox still buys us is real: no top-level navigation,\n // no downloads, no pointer lock.\n // `allow-downloads` lets the chat save a file in place. Every download path\n // is an in-place `<a download>`.click(); WITHOUT this flag a sandboxed frame\n // blocks that and the browser falls back to opening the file in a new tab.\n // It is a sandbox flag, not a permissions-policy `allow` token.\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads',\n );\n // Powerful features need an explicit permissions-policy grant: a cross-origin\n // frame is granted NONE by default, so without `allow` they are hard-blocked\n // no matter what the user approves.\n // - microphone: dictation's getUserMedia.\n // - clipboard-write: the \"Copy\" button on a chat message calls\n // navigator.clipboard.writeText, which throws NotAllowedError without it.\n // The bare tokens scope each grant to the iframe's own origin (the app), not\n // the host page. A host page can still deny either via its own\n // Permissions-Policy response header — outside our control, which is why the\n // in-app copy path also degrades gracefully rather than throwing.\n iframe.setAttribute('allow', 'microphone; clipboard-write');\n iframe.src =\n `${this.config.origin}/embed/chat?k=${encodeURIComponent(\n this.config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}` +\n (this.config.surface\n ? `&s=${encodeURIComponent(this.config.surface)}`\n : '') +\n // Either trigger works: the URL param (no redeploy needed) OR the config's\n // programmatic `dev` (the React prop). See both doc comments above.\n (devRequested() || this.config.dev ? '&dev=1' : '') +\n (this.inline ? '&inline=1' : '');\n this.iframe = iframe;\n this.shadow.appendChild(iframe);\n\n window.addEventListener('message', this.onMessage);\n if (!this.inline) {\n // A viewport change can strand a saved box off-page (a laptop undocked from an\n // external monitor is the common one), so re-clamp and re-anchor on resize.\n window.addEventListener('resize', this.onViewportResize);\n this.place();\n }\n }\n\n /**\n * Every message is checked twice, on every single message — not once at setup.\n *\n * `channel` is a namespace, not a boundary. The origin and source checks are the\n * boundary: any frame on the page can postMessage us, and a page with an ad iframe\n * on it has plenty of frames.\n */\n private onMessage = (event: MessageEvent) => {\n if (event.origin !== this.config.origin) return;\n if (event.source !== this.iframe?.contentWindow) return;\n if (!isEnvelope(event.data)) return;\n\n this.handle(event.data.payload as WidgetToHost);\n };\n\n /**\n * Test seam. The shadow root is CLOSED, so a test cannot reach the iframe to forge a\n * source-valid MessageEvent — this routes a message through the identical logic\n * without weakening the origin/source checks above, which stay the only real door.\n */\n __testHandle(msg: WidgetToHost) {\n this.handle(msg);\n }\n\n /**\n * The eager stub's own emit-and-swallow for the host's `onEvent` telemetry hook.\n * Deliberately does NOT import the registry's `emitEvent`: pulling the lazy ./context\n * chunk (where the registry lives) into the size-budgeted stub would blow it, so this\n * ~5-line duplication across the bundle boundary is intentional. Host telemetry is\n * host code — a throw here must never break the widget.\n */\n private emit(e: MatterfactEvent) {\n const cb = (\n globalThis as { matterfact?: { onEvent?: (e: MatterfactEvent) => void } }\n ).matterfact?.onEvent;\n if (typeof cb !== 'function') return;\n try {\n cb(e);\n } catch {\n /* host telemetry must never break the widget */\n }\n }\n\n private handle(msg: WidgetToHost) {\n switch (msg.type) {\n case 'widget.ready':\n this.ready = true;\n this.send({\n type: 'host.ready',\n protocol: PROTOCOL_VERSION,\n origin: location.origin,\n });\n // Theme NOW, not on first open. It used to ride in with the lazy context\n // chunk, which is only fetched when the chat is opened — so a collapsed\n // launcher sat in the wrong colours until you interacted with it.\n this.send({ type: 'host.theme', mode: this.themeMode() });\n this.flush();\n // Inline has no \"open\" event to hang this off — the chat is visible the moment\n // the host renders their panel, so the eye has to load now or the agent is\n // blind to the page for the whole session. The corner keeps its lazy load: a\n // page whose visitors never click still pays nothing.\n if (this.inline) void this.loadContext();\n this.emit({ type: 'ready' });\n break;\n\n case 'widget.setOpen':\n // Host telemetry sees the open/close moment regardless of placement (the inline\n // guard below only skips the popup SIZING, which is meaningless inline).\n this.emit({ type: msg.open ? 'open' : 'close' });\n // Inline: the host's panel IS the open/close control. There's no popup to size.\n if (this.inline) break;\n this.open = msg.open;\n this.place();\n // The DOM code is fetched HERE — the first time someone actually opens the\n // chat — and never on a page where they don't.\n if (msg.open) void this.loadContext();\n break;\n\n case 'widget.setMode':\n // Inline: the host owns the box; float/dock is not ours to choose.\n if (this.inline) break;\n this.geo.mode = msg.mode;\n this.writeGeometry(this.geo);\n this.place();\n break;\n\n case 'widget.setDockSide':\n if (this.inline) break;\n this.geo.dockSide = msg.side;\n this.writeGeometry(this.geo);\n this.place();\n break;\n\n case 'widget.snapCorner':\n if (this.inline) break;\n // Snapping is a FLOAT affordance; the picker only shows in float mode.\n this.geo.corner = msg.corner;\n this.writeGeometry(this.geo);\n this.place();\n break;\n\n case 'widget.setLauncherRegion': {\n // Only meaningful while collapsed — open, the panel is already bigger than any\n // pill or menu, and growing the box would fight the panel's own size.\n if (this.inline || this.open) break;\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n if (msg.w <= LAUNCHER && msg.h <= LAUNCHER) {\n // Back to the bare launcher — place() already knows how to draw it.\n this.place();\n } else {\n const region =\n this.geo.mode === 'dock'\n ? dockChrome(this.geo, msg.w, msg.h, vw, vh)\n : floatChrome(this.geo, msg.w, msg.h, vw, vh);\n this.applyBox(region, msg.h > LAUNCHER ? 'menu' : 'pill');\n }\n break;\n }\n\n case 'widget.resize':\n // Inline: the container's height is the host's business, and an auto-grow here\n // would fight their layout every time the transcript got longer.\n if (this.inline) break;\n // Content height auto-grow, for the FLOATING panel only. Docked, the edges own\n // the height; and a manual resize has already written floatH, which place()\n // would restore on the next call anyway.\n if (this.hostEl && this.open && this.geo.mode === 'float') {\n this.hostEl.style.height = `${Math.min(\n msg.height,\n Math.max(0, window.innerHeight - 2 * MARGIN),\n )}px`;\n }\n break;\n\n case 'widget.resizeStart':\n if (this.inline) break;\n this.resizeBase = { w: this.geo.floatW, h: this.geo.floatH };\n this.dockBase = this.geo.dockW;\n // The box must track the pointer exactly; an eased transition lags behind it.\n if (this.hostEl) this.hostEl.style.transition = 'none';\n break;\n\n case 'widget.resizeMove': {\n if (this.inline || !this.resizeBase) break;\n if (this.geo.mode === 'dock') {\n // Docked, only the WIDTH is the user's — the edges own the height.\n const w = applyDockResizeDelta(\n this.geo.dockSide,\n this.dockBase,\n msg.dx,\n );\n this.geo.dockW = Math.min(\n Math.max(w, MIN_DOCK_W),\n Math.max(0, window.innerWidth - 2 * MARGIN),\n );\n } else {\n const next = applyResizeDelta(\n growthCorner(this.geo, window.innerWidth, window.innerHeight),\n this.resizeBase.w,\n this.resizeBase.h,\n msg.dx,\n msg.dy,\n );\n const fit = clampSize(\n next.w,\n next.h,\n window.innerWidth,\n window.innerHeight,\n MIN_FLOAT_W,\n MIN_FLOAT_H,\n );\n this.geo.floatW = fit.w;\n this.geo.floatH = fit.h;\n }\n this.place();\n break;\n }\n\n case 'widget.resizeEnd':\n if (this.inline) break;\n this.resizeBase = null;\n if (this.hostEl) this.hostEl.style.transition = '';\n this.writeGeometry(this.geo);\n break;\n\n case 'widget.requestContext':\n // The pull path for declared context — re-read it now (via getPageContext if the\n // host supplied one) and re-publish `host.context`. No-op if pageContext is off.\n void this.loadContext().then((m) => m.provideContext());\n break;\n\n case 'widget.requestSnapshot':\n // pageContext: false ⇒ `sendSnapshot` itself no-ops (see context.ts) rather\n // than gating here — this file is the size-budgeted stub, and the check\n // costs nothing extra in the lazy chunk that already owns the DOM read.\n void this.loadContext().then((m) => m.sendSnapshot(this.send));\n break;\n\n case 'widget.readRegion':\n void this.loadContext().then((m) => m.sendRegion(msg.ref, this.send));\n break;\n\n case 'widget.callTool':\n void this.loadContext().then((m) => m.callTool(msg.call, this.send));\n break;\n\n // Everything below is LAUNCHER chrome: there is no launcher inline (the widget\n // doesn't draw one), and moving or hiding the host's own panel from inside it\n // would be us redecorating their app. An older cached loader could still be told\n // any of these by a newer widget, so they're guarded rather than assumed absent.\n case 'widget.dragStart':\n if (this.inline) break;\n this.dragFrom = dragAnchor(\n this.geo,\n window.innerWidth,\n window.innerHeight,\n );\n this.dragAt = { ...this.dragFrom };\n this.dragLeftBand = false;\n this.dragGrowth = growthCorner(\n this.geo,\n window.innerWidth,\n window.innerHeight,\n );\n this.dragBox = visibleBox(\n this.geo,\n this.open,\n window.innerWidth,\n window.innerHeight,\n );\n // Follow the pointer 1:1 while dragging; the ease is for the snap on release.\n if (this.hostEl) this.hostEl.style.transition = 'none';\n break;\n\n case 'widget.dragMove': {\n if (this.inline || !this.dragFrom) break;\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n this.dragAt = {\n x: this.dragFrom.x + msg.dx,\n y: this.dragFrom.y + msg.dy,\n };\n // Switch placement DURING the drag, not on release: drag toward a side and it\n // becomes the tab under your cursor, drag away and it pops back to the circle.\n // Deliberately only the EDGE test here — running the full drop resolver would\n // also snap corners mid-gesture, yanking the widget away while you're still\n // holding it. Corners are resolved on release, where a jump reads as a snap.\n const side = edgeDock(this.dragBox.x + msg.dx, this.dragBox.w, vw);\n if (!side) this.dragLeftBand = true;\n // A tab is already docked, so it may stay docked without having left first;\n // anything else must have been clear of the band at some point in this drag.\n if (side && (this.dragLeftBand || this.geo.mode === 'dock')) {\n this.geo.mode = 'dock';\n this.geo.dockSide = side;\n this.geo.tabY = Math.max(0, this.dragAt.y);\n } else {\n this.geo.mode = 'float';\n this.geo.corner = null;\n this.geo.x = this.dragAt.x;\n this.geo.y = this.dragAt.y;\n }\n this.place();\n break;\n }\n\n case 'widget.dragEnd': {\n if (this.inline || !this.dragFrom) break;\n // The drop resolves the FULL placement — including the corner snap the live\n // pass deliberately skipped. Restoring the transition first is what makes that\n // final snap animate rather than teleport.\n const at = placeDrop(\n this.dragAt.x,\n this.dragAt.y,\n this.dragBox.x + (this.dragAt.x - this.dragFrom.x),\n this.dragBox.w,\n window.innerWidth,\n window.innerHeight,\n );\n this.geo.mode = at.mode;\n if (at.mode === 'dock') {\n this.geo.dockSide = at.dockSide;\n this.geo.tabY = at.tabY;\n } else {\n this.geo.corner = at.corner;\n this.geo.x = at.x;\n this.geo.y = at.y;\n }\n this.dragFrom = null;\n this.dragGrowth = null;\n if (this.hostEl) this.hostEl.style.transition = '';\n this.place();\n this.writeGeometry(this.geo);\n break;\n }\n\n case 'widget.resetPos':\n if (this.inline) break;\n this.geo = defaultGeometry();\n this.writeGeometry(this.geo);\n this.place();\n break;\n\n case 'widget.hide':\n // Inline: hiding is the host's panel to hide. Blanking their drawer from in\n // here would leave them with an empty box and no way to get it back.\n if (this.inline) break;\n if (this.hostEl) this.hostEl.style.display = 'none';\n break;\n\n case 'widget.needsAuth':\n this.emit({ type: 'auth', phase: 'required' });\n void this.provideAuth();\n break;\n\n case 'widget.navigate':\n this.emit({ type: 'navigate', href: msg.href });\n // Delegated to the lazy context chunk (kept out of the every-page stub —\n // the eager budget is tight). By the time a document deeplink is clicked the\n // chat is open, so context is already loaded.\n void this.loadContext().then((m) => m.navigateHost(msg.href));\n break;\n\n case 'widget.chat':\n // Content-free chat-turn telemetry (phase + opaque chatId), relayed straight\n // to the host's onEvent. Never carries message text.\n this.emit({ type: 'chat', phase: msg.phase, chatId: msg.chatId });\n break;\n }\n }\n\n /**\n * Own a drag for its lifetime.\n *\n * The widget reports the press and then goes quiet: a cross-origin iframe only gets\n * pointer events while the pointer is over it, and a drag leaves that box immediately.\n * So we lay a transparent layer over the whole viewport and track the gesture in the\n * host document, where it can't be lost. The layer also stops the pointer landing on\n * the customer's own UI mid-drag (text selection, hover states, stray clicks).\n *\n * We are the dumb half on purpose — see `widget.dragMove` in the protocol for why the\n * widget has to own the gesture. All we do is take a delta and place the element.\n */\n /** Write a box onto the host element and stamp the mode the shadow CSS keys off. */\n private applyBox(\n box: BoxStyle,\n mode: 'launcher' | 'tab' | 'pill' | 'menu' | 'float' | 'dock',\n ) {\n if (!this.hostEl || this.inline) return;\n const s = this.hostEl.style;\n s.top = box.top;\n s.right = box.right;\n s.bottom = box.bottom;\n s.left = box.left;\n s.width = box.width;\n s.height = box.height;\n this.hostEl.dataset.mode = mode;\n // The flush shapes (tab, docked panel) round only on the side facing the page.\n if (mode === 'tab' || mode === 'dock')\n this.hostEl.dataset.flush = this.geo.dockSide;\n else delete this.hostEl.dataset.flush;\n }\n\n /** Re-apply the box for whatever state we're in: collapsed launcher, float, or dock. */\n /**\n * The growth direction to use RIGHT NOW — frozen while a drag is in flight.\n *\n * Every consumer has to agree on this, which is the bug that made the widget\n * flip-flop under small movements near the viewport centre: the box was frozen but\n * `host.geometry` still published a freshly-derived growth, so the WIDGET kept\n * swapping which corner it drew against (and it animates that), twitching back and\n * forth while the loader held perfectly still.\n */\n private growthNow(): Corner {\n return (\n this.dragGrowth ??\n growthCorner(this.geo, window.innerWidth, window.innerHeight)\n );\n }\n\n private place() {\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n if (!this.open) {\n const dock = this.geo.mode === 'dock';\n this.applyBox(\n dock\n ? tabBox(this.geo, vw, vh)\n : floatChrome(this.geo, LAUNCHER, LAUNCHER, vw, vh, this.growthNow()),\n dock ? 'tab' : 'launcher',\n );\n } else if (this.geo.mode === 'dock') {\n this.applyBox(dockBox(this.geo, vw, vh), 'dock');\n } else {\n this.applyBox(floatBox(this.geo, vw, vh, this.growthNow()), 'float');\n }\n this.publishGeometry();\n }\n\n /**\n * Tell the widget where it is. It can't see the viewport and doesn't own the box, so\n * without this it draws its launcher against a stale guess — which is what made the\n * circle jump when the launcher sat on the left (see `host.geometry` in the protocol).\n */\n private publishGeometry() {\n this.send({\n type: 'host.geometry',\n mode: this.geo.mode,\n dockSide: this.geo.dockSide,\n growth: this.growthNow(),\n });\n }\n\n /** The theme to publish: an explicit data-theme wins, else the OS preference. */\n private themeMode(): 'light' | 'dark' {\n return this.config.theme === 'auto'\n ? matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light'\n : this.config.theme;\n }\n\n private onViewportResize = () => {\n // Re-clamp and re-anchor: a saved box must never be left hanging off a smaller page.\n this.place();\n };\n\n private readGeometry(): EmbedGeometry {\n // First-party storage on the CUSTOMER's origin, so each site remembers its own spot.\n // Never throws: storage is unavailable in some embedding contexts, and a widget that\n // can't remember where it was put is fine — one that fails to mount is not.\n try {\n return parseGeometry(localStorage.getItem(POS_KEY)) ?? defaultGeometry();\n } catch {\n return defaultGeometry();\n }\n }\n\n private writeGeometry(g: EmbedGeometry) {\n try {\n localStorage.setItem(POS_KEY, serializeGeometry(g));\n } catch {\n /* storage denied — the box just won't survive the reload */\n }\n }\n\n /**\n * Answer `widget.needsAuth`. If a trusted first-party host has an auth-token provider,\n * call it and hand the token straight to the widget via `host.auth` — no popup. The\n * provider comes from EITHER the programmatic config (the React `<MatterfactAgent\n * getAuthToken>` prop) OR a global the host page sets for the `<script>` loader:\n *\n * window.matterfact = { getEmbedAuthToken: () => getIdToken(user) };\n *\n * Read fresh at call time (not at readConfig), so a global set after the loader booted\n * — e.g. once the host's auth is ready — is still picked up. `expiresAt: 0`: the widget\n * doesn't cache it, it exchanges the token for a rotating embed session anyway.\n *\n * No provider ⇒ this does nothing. The loader never opens a sign-in popup — the widget\n * owns interactive sign-in (inline Firebase/email, and Microsoft's own MSAL login popup\n * for Entra, then the PKCE token exchange), so the loader must not also fire its stale\n * `/embed/authorize?k=&o=` popup, which the deployed authorize page no longer accepts.\n */\n private async provideAuth() {\n const provider =\n this.config.authTokenProvider ??\n (globalThis as { matterfact?: { getEmbedAuthToken?: AuthTokenProvider } })\n .matterfact?.getEmbedAuthToken;\n if (!provider) return; // the widget owns interactive sign-in; the loader never opens it\n\n // Storm guard. A healthy host-auth flow asks ONCE — the widget exchanges the token for a\n // rotating session and never asks again. A flood of `widget.needsAuth` means the token\n // keeps being rejected (wrong audience/scope) and something is remounting the widget in a\n // loop; calling getAuthToken on every one hammers the host's identity provider (MSAL →\n // login.microsoftonline.com), which can get the app RATE-LIMITED. Past the cap we simply\n // stop calling the provider. Silent + minimal by necessity (hard per-page size budget);\n // the widget-side guard is what surfaces the reason to the user and logs the rejection.\n if (++this.ac > 5) return;\n try {\n const token = await provider();\n if (token) this.send({ type: 'host.auth', token, expiresAt: 0 });\n // One emit either way — a null token is a failure to provide, same as a throw.\n this.emit({ type: 'auth', phase: token ? 'granted' : 'failed' });\n } catch {\n this.emit({ type: 'auth', phase: 'failed' });\n /* no token this time; the widget falls back to its own inline / popup sign-in */\n }\n }\n\n private loadContext() {\n // One chunk, one fetch, cached. Everything that can see the customer's page\n // lives behind this boundary.\n this.context ??= import('./context').then((m) => {\n // The single place the eye actually starts: when pageContext is off, `start()`\n // skips installing every DOM/nav/focus/activity observer — not a filter over\n // what gets sent afterward, nothing is collected in the first place. Passed\n // through raw: `start`'s default parameter is what turns `undefined` (the\n // option omitted) into \"on\".\n m.start(\n this.send,\n this.config.origin,\n this.config.pageContext,\n this.config.pageContextProvider,\n );\n // start() emits the OS-preference theme. An explicit data-theme on the\n // script tag is the host's choice — resend it so it wins over auto-detect\n // (a light-branded site must be able to force a light widget on a dark-OS\n // visitor, and vice versa).\n if (this.config.theme !== 'auto') {\n this.send({ type: 'host.theme', mode: this.config.theme });\n }\n return m;\n });\n return this.context;\n }\n\n private send = (msg: HostToWidget) => {\n if (!this.ready) {\n this.queue.push(msg);\n return;\n }\n // targetOrigin is the widget's exact origin — never '*'. A '*' here would\n // broadcast the customer's page content to whatever happens to be listening.\n this.iframe?.contentWindow?.postMessage(envelope(msg), this.config.origin);\n };\n\n private flush() {\n const pending = this.queue;\n this.queue = [];\n for (const m of pending) this.send(m);\n }\n\n /** Tear down: stop listening and remove the host element. For the React wrapper's\n * unmount — the vanilla `<script>` loader lives for the page's lifetime and never\n * calls this. */\n destroy() {\n window.removeEventListener('message', this.onMessage);\n window.removeEventListener('resize', this.onViewportResize);\n this.hostEl?.remove();\n this.hostEl = null;\n this.iframe = null;\n this.shadow = null;\n this.ready = false;\n // context.ts's listeners/history-patch/ref-registry are module-global and\n // outlive this instance — stop() undoes exactly what start() installed. A no-op\n // if the eye was never loaded (chat never opened, so nothing was ever started).\n // This is the unmount-with-no-remount case; start()'s own stop()-first call\n // (see context.ts) is what protects a REMOUNT, which is why both exist.\n void this.context?.then((m) => m.stop());\n }\n}\n\n/**\n * Programmatic entry — mount the widget from a config object instead of the DOM\n * `<script data-*>`. This is what the React wrapper (`@matterfact/embed/react`) drives;\n * the vanilla loader below reads the script tag and calls this same class.\n */\nexport function mount(config: LoaderConfig): EmbedHost {\n const host = new EmbedHost(config);\n host.mount();\n return host;\n}\n\nexport { EmbedHost, CHANNEL, readConfig };\n"]}