@phi-code-admin/phi-code 0.83.0 → 0.84.0

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/extensions/phi/btw/LICENSE +21 -0
  3. package/extensions/phi/btw/btw-ui.ts +238 -0
  4. package/extensions/phi/btw/btw.ts +363 -0
  5. package/extensions/phi/btw/index.ts +17 -0
  6. package/extensions/phi/btw/prompts/btw-system.txt +9 -0
  7. package/extensions/phi/chrome/LICENSE +21 -0
  8. package/extensions/phi/chrome/browser-extension/manifest.json +26 -0
  9. package/extensions/phi/chrome/browser-extension/service_worker.js +2388 -0
  10. package/extensions/phi/chrome/browser-extension/snapshot_injected.js +677 -0
  11. package/extensions/phi/chrome/index.ts +1799 -0
  12. package/extensions/phi/goal/LICENSE +21 -0
  13. package/extensions/phi/goal/index.ts +784 -0
  14. package/extensions/phi/todo/LICENSE +21 -0
  15. package/extensions/phi/todo/config.ts +14 -0
  16. package/extensions/phi/todo/index.ts +113 -0
  17. package/extensions/phi/todo/locales/de.json +17 -0
  18. package/extensions/phi/todo/locales/en.json +15 -0
  19. package/extensions/phi/todo/locales/es.json +17 -0
  20. package/extensions/phi/todo/locales/fr.json +17 -0
  21. package/extensions/phi/todo/locales/pt-BR.json +17 -0
  22. package/extensions/phi/todo/locales/pt.json +17 -0
  23. package/extensions/phi/todo/locales/ru.json +17 -0
  24. package/extensions/phi/todo/locales/uk.json +17 -0
  25. package/extensions/phi/todo/rpiv-config/config.ts +223 -0
  26. package/extensions/phi/todo/rpiv-config/index.ts +12 -0
  27. package/extensions/phi/todo/state/i18n-bridge.ts +65 -0
  28. package/extensions/phi/todo/state/invariants.ts +20 -0
  29. package/extensions/phi/todo/state/replay.ts +38 -0
  30. package/extensions/phi/todo/state/selectors.ts +107 -0
  31. package/extensions/phi/todo/state/state-reducer.ts +187 -0
  32. package/extensions/phi/todo/state/state.ts +18 -0
  33. package/extensions/phi/todo/state/store.ts +54 -0
  34. package/extensions/phi/todo/state/task-graph.ts +57 -0
  35. package/extensions/phi/todo/todo-overlay.ts +194 -0
  36. package/extensions/phi/todo/todo.ts +146 -0
  37. package/extensions/phi/todo/tool/response-envelope.ts +94 -0
  38. package/extensions/phi/todo/tool/types.ts +128 -0
  39. package/extensions/phi/todo/view/format.ts +162 -0
  40. package/package.json +1 -1
@@ -0,0 +1,677 @@
1
+ // Static MAIN-world snapshot implementation injected by the MV3 service worker.
2
+ // Keep this file free of eval/new Function so `chrome_snapshot` works on strict-CSP pages.
3
+ (() => {
4
+ function getPiChromeState() {
5
+ const state = window.__PI_CHROME_STATE__ || {
6
+ nextElementUid: 1,
7
+ elements: {},
8
+ console: [],
9
+ network: [],
10
+ nextRequestId: 1,
11
+ instrumentationInstalled: false,
12
+ lastSnapshotDigest: null,
13
+ };
14
+ window.__PI_CHROME_STATE__ = state;
15
+ return state;
16
+ }
17
+
18
+ function rememberElement(element) {
19
+ const state = getPiChromeState();
20
+ if (!element.__piChromeUid) element.__piChromeUid = "el-" + state.nextElementUid++;
21
+ state.elements[element.__piChromeUid] = element;
22
+ return element.__piChromeUid;
23
+ }
24
+
25
+ function isElementVisible(element) {
26
+ if (!element || !element.getBoundingClientRect) return false;
27
+ const style = getComputedStyle(element);
28
+ if (style.visibility === "hidden" || style.display === "none") return false;
29
+ const rect = element.getBoundingClientRect();
30
+ if (rect.width === 0 || rect.height === 0) return false;
31
+ if (rect.bottom < 0 || rect.right < 0) return false;
32
+ if (rect.top > innerHeight || rect.left > innerWidth) return false;
33
+ return true;
34
+ }
35
+
36
+ function occluderAt(x, y, expected) {
37
+ const top = document.elementFromPoint(x, y);
38
+ if (!top || top === expected) return null;
39
+ if (expected && expected.contains(top)) return null;
40
+ if (top.contains(expected)) return null;
41
+ return {
42
+ tag: top.tagName.toLowerCase(),
43
+ id: top.id || undefined,
44
+ className: typeof top.className === "string" ? top.className : undefined,
45
+ };
46
+ }
47
+
48
+ function textOf(element, max) {
49
+ return (element?.innerText || element?.textContent || "").replace(/\s+/g, " ").trim().slice(0, max || 500);
50
+ }
51
+
52
+ function accessibleLabel(element) {
53
+ if (!element) return "";
54
+ const labelledBy = element.getAttribute("aria-labelledby");
55
+ if (labelledBy) {
56
+ const text = labelledBy.split(/\s+/).map((id) => document.getElementById(id)?.innerText || "").join(" ").trim();
57
+ if (text) return text;
58
+ }
59
+ const id = element.id;
60
+ if (id) {
61
+ try {
62
+ const label = document.querySelector(`label[for="${cssEscape(id)}"]`);
63
+ if (label?.innerText) return label.innerText;
64
+ } catch {}
65
+ }
66
+ const wrappingLabel = element.closest?.("label");
67
+ return (
68
+ element.getAttribute("aria-label") ||
69
+ element.getAttribute("title") ||
70
+ element.getAttribute("placeholder") ||
71
+ wrappingLabel?.innerText ||
72
+ element.innerText ||
73
+ element.textContent ||
74
+ ""
75
+ ).trim().replace(/\s+/g, " ").slice(0, 180);
76
+ }
77
+
78
+ function cssEscape(value) {
79
+ return (window.CSS && CSS.escape) ? CSS.escape(value) : String(value).replace(/[^a-zA-Z0-9_-]/g, "\\$&");
80
+ }
81
+
82
+ function roleOf(element) {
83
+ const explicit = element.getAttribute("role");
84
+ if (explicit) return explicit.toLowerCase();
85
+ const tag = element.tagName.toLowerCase();
86
+ const type = (element.getAttribute("type") || "").toLowerCase();
87
+ if (tag === "a" && element.href) return "link";
88
+ if (tag === "button" || type === "button" || type === "submit" || type === "reset") return "button";
89
+ if (tag === "textarea") return "textbox";
90
+ if (tag === "select") return "combobox";
91
+ if (tag === "input") {
92
+ if (["checkbox", "radio", "range", "search", "email", "password", "tel", "url", "number"].includes(type)) return type === "checkbox" || type === "radio" || type === "range" ? type : "textbox";
93
+ return "textbox";
94
+ }
95
+ if (element.isContentEditable) return "textbox";
96
+ if (tag.match(/^h[1-6]$/)) return "heading";
97
+ return tag;
98
+ }
99
+
100
+ function isSensitiveField(element) {
101
+ if (!element) return false;
102
+ const tag = element.tagName?.toLowerCase?.() || "";
103
+ if (!/^(input|textarea|select)$/.test(tag) && !element.isContentEditable) return false;
104
+ const type = (element.getAttribute("type") || "").toLowerCase();
105
+ if (["password"].includes(type)) return true;
106
+ const haystack = [
107
+ type,
108
+ element.getAttribute("name"),
109
+ element.id,
110
+ element.getAttribute("autocomplete"),
111
+ element.getAttribute("aria-label"),
112
+ element.getAttribute("placeholder"),
113
+ element.getAttribute("data-testid"),
114
+ ].filter(Boolean).join(" ").toLowerCase();
115
+ return /password|passwd|\bpwd\b|secret|token|bearer|api[-_ ]?key|access[-_ ]?key|auth[-_ ]?code|one[-_ ]?time|otp|2fa|mfa|verification[-_ ]?code|recovery[-_ ]?code|credit[-_ ]?card|card[-_ ]?number|cc-number|cc-csc|cvc|cvv|security[-_ ]?code|ssn|social[-_ ]?security/.test(haystack);
116
+ }
117
+
118
+ function installPiChromeInstrumentation() {
119
+ const state = getPiChromeState();
120
+ if (state.instrumentationInstalled) return;
121
+ state.instrumentationInstalled = true;
122
+ const pushConsole = (level, args) => {
123
+ state.console.push({
124
+ id: state.console.length + 1,
125
+ level,
126
+ timestamp: Date.now(),
127
+ url: location.href,
128
+ args: Array.from(args).map((arg) => {
129
+ try {
130
+ if (typeof arg === "string") return arg;
131
+ if (arg instanceof Error) return { name: arg.name, message: arg.message, stack: arg.stack };
132
+ return JSON.parse(JSON.stringify(arg));
133
+ } catch {
134
+ return String(arg);
135
+ }
136
+ }),
137
+ });
138
+ if (state.console.length > 500) state.console.splice(0, state.console.length - 500);
139
+ };
140
+ for (const level of ["debug", "log", "info", "warn", "error"]) {
141
+ const original = console[level];
142
+ if (typeof original !== "function" || original.__piChromeWrapped) continue;
143
+ const wrapped = function(...args) {
144
+ pushConsole(level, args);
145
+ return original.apply(this, args);
146
+ };
147
+ wrapped.__piChromeWrapped = true;
148
+ console[level] = wrapped;
149
+ }
150
+ window.addEventListener("error", (event) => pushConsole("pageerror", [event.message, event.filename + ":" + event.lineno + ":" + event.colno]));
151
+ window.addEventListener("unhandledrejection", (event) => pushConsole("unhandledrejection", [event.reason]));
152
+
153
+ const record = (entry) => {
154
+ state.network.push(entry);
155
+ if (state.network.length > 1000) state.network.splice(0, state.network.length - 1000);
156
+ return entry;
157
+ };
158
+ if (window.fetch && !window.fetch.__piChromeWrapped) {
159
+ const originalFetch = window.fetch.bind(window);
160
+ const wrappedFetch = async (...args) => {
161
+ const id = "req-" + state.nextRequestId++;
162
+ const startedAt = Date.now();
163
+ const input = args[0];
164
+ const init = args[1] || {};
165
+ const url = typeof input === "string" ? input : input?.url;
166
+ const method = (init.method || input?.method || "GET").toUpperCase();
167
+ const entry = record({ id, type: "fetch", method, url: String(url || ""), startedAt, pageUrl: location.href, status: "pending" });
168
+ try {
169
+ const response = await originalFetch(...args);
170
+ entry.status = response.status;
171
+ entry.statusText = response.statusText;
172
+ entry.ok = response.ok;
173
+ entry.responseUrl = response.url;
174
+ entry.durationMs = Date.now() - startedAt;
175
+ entry.responseHeaders = Array.from(response.headers.entries());
176
+ entry.responseBodyOmitted = "response body capture is disabled by default";
177
+ return response;
178
+ } catch (error) {
179
+ entry.error = error?.message || String(error);
180
+ entry.durationMs = Date.now() - startedAt;
181
+ throw error;
182
+ }
183
+ };
184
+ wrappedFetch.__piChromeWrapped = true;
185
+ window.fetch = wrappedFetch;
186
+ }
187
+ if (window.XMLHttpRequest && !XMLHttpRequest.prototype.open.__piChromeWrapped) {
188
+ const originalOpen = XMLHttpRequest.prototype.open;
189
+ const originalSend = XMLHttpRequest.prototype.send;
190
+ XMLHttpRequest.prototype.open = function(method, url, ...rest) {
191
+ this.__piChromeRequest = { method: String(method || "GET").toUpperCase(), url: String(url || "") };
192
+ return originalOpen.call(this, method, url, ...rest);
193
+ };
194
+ XMLHttpRequest.prototype.open.__piChromeWrapped = true;
195
+ XMLHttpRequest.prototype.send = function(body) {
196
+ const id = "req-" + state.nextRequestId++;
197
+ const startedAt = Date.now();
198
+ const info = this.__piChromeRequest || {};
199
+ const entry = record({ id, type: "xhr", method: info.method || "GET", url: info.url || "", startedAt, pageUrl: location.href, status: "pending" });
200
+ this.addEventListener("loadend", () => {
201
+ entry.status = this.status;
202
+ entry.statusText = this.statusText;
203
+ entry.responseUrl = this.responseURL;
204
+ entry.durationMs = Date.now() - startedAt;
205
+ try { entry.responseHeadersText = this.getAllResponseHeaders(); } catch {}
206
+ entry.responseBodyOmitted = "response body capture is disabled by default";
207
+ });
208
+ this.addEventListener("error", () => { entry.error = "XMLHttpRequest error"; entry.durationMs = Date.now() - startedAt; });
209
+ return originalSend.call(this, body);
210
+ };
211
+ }
212
+ }
213
+
214
+ function hashString(text) {
215
+ let h = 0;
216
+ for (let i = 0; i < text.length; i++) h = (h * 31 + text.charCodeAt(i)) | 0;
217
+ return h;
218
+ }
219
+
220
+ function selectorFor(element) {
221
+ const unique = (selector) => {
222
+ try { return document.querySelectorAll(selector).length === 1; } catch { return false; }
223
+ };
224
+ if (element.id && unique("#" + cssEscape(element.id))) return "#" + cssEscape(element.id);
225
+ const attr = ["aria-label", "name", "placeholder", "data-testid", "role"].find((name) => element.getAttribute(name));
226
+ if (attr) {
227
+ const candidate = element.tagName.toLowerCase() + "[" + attr + "=" + JSON.stringify(element.getAttribute(attr)) + "]";
228
+ if (unique(candidate)) return candidate;
229
+ }
230
+ const parts = [];
231
+ let current = element;
232
+ while (current && current.nodeType === Node.ELEMENT_NODE && parts.length < 5) {
233
+ let part = current.tagName.toLowerCase();
234
+ if (current.classList.length > 0) part += "." + Array.from(current.classList).slice(0, 2).map(cssEscape).join(".");
235
+ const siblings = Array.from(current.parentElement?.children ?? []).filter((sibling) => sibling.tagName === current.tagName);
236
+ if (siblings.length > 1) part += ":nth-of-type(" + (siblings.indexOf(current) + 1) + ")";
237
+ parts.unshift(part);
238
+ const candidate = parts.join(" > ");
239
+ if (unique(candidate)) return candidate;
240
+ current = current.parentElement;
241
+ }
242
+ return parts.join(" > ");
243
+ }
244
+
245
+ function directHeadingText(element) {
246
+ const labelledBy = element.getAttribute?.("aria-labelledby");
247
+ if (labelledBy) {
248
+ const text = labelledBy.split(/\s+/).map((id) => document.getElementById(id)?.innerText || "").join(" ").replace(/\s+/g, " ").trim();
249
+ if (text) return text.slice(0, 180);
250
+ }
251
+ const aria = element.getAttribute?.("aria-label");
252
+ if (aria) return aria.trim().slice(0, 180);
253
+ const heading = Array.from(element.querySelectorAll?.("h1,h2,h3,h4,[role='heading']") || []).find(isElementVisible);
254
+ if (heading) return textOf(heading, 180);
255
+ return "";
256
+ }
257
+
258
+ function meaningfulContainerFor(element) {
259
+ let current = element.parentElement;
260
+ let fallback = current;
261
+ let depth = 0;
262
+ while (current && current !== document.body && depth++ < 8) {
263
+ if (!isElementVisible(current)) { current = current.parentElement; continue; }
264
+ const tag = current.tagName.toLowerCase();
265
+ const role = (current.getAttribute("role") || "").toLowerCase();
266
+ const cls = typeof current.className === "string" ? current.className : "";
267
+ const id = current.id || "";
268
+ const named = Boolean(current.getAttribute("aria-label") || current.getAttribute("aria-labelledby") || directHeadingText(current));
269
+ const semantic = /^(form|dialog|section|article|nav|header|main|aside|footer|li|tr|td|fieldset)$/.test(tag) ||
270
+ /^(dialog|alertdialog|region|group|listitem|row|cell|tabpanel|menu|toolbar|navigation|main|banner|contentinfo|complementary)$/.test(role);
271
+ const classHint = /card|panel|pane|modal|dialog|section|content|container|toolbar|menu|list|item|row|cell|header|footer|sidebar|drawer|popover|dropdown/i.test(`${id} ${cls}`);
272
+ const rect = current.getBoundingClientRect();
273
+ const childActions = current.querySelectorAll?.('a, button, input, textarea, select, [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])').length || 0;
274
+ if ((semantic || classHint || named) && rect.width > 20 && rect.height > 20 && childActions <= 80) return current;
275
+ if (!fallback && rect.width > 20 && rect.height > 20) fallback = current;
276
+ current = current.parentElement;
277
+ }
278
+ return fallback || document.body;
279
+ }
280
+
281
+ function contextForElement(element) {
282
+ const container = meaningfulContainerFor(element);
283
+ if (!container || container === document.body || container === element) return undefined;
284
+ return {
285
+ uid: rememberElement(container),
286
+ tag: container.tagName.toLowerCase(),
287
+ role: roleOf(container),
288
+ label: directHeadingText(container) || accessibleLabel(container) || textOf(container, 140),
289
+ rect: rectSummary(container),
290
+ };
291
+ }
292
+
293
+ function summarizeElement(element, index) {
294
+ const rect = element.getBoundingClientRect();
295
+ const style = getComputedStyle(element);
296
+ const cx = rect.left + rect.width / 2;
297
+ const cy = rect.top + rect.height / 2;
298
+ const occluded = occluderAt(cx, cy, element);
299
+ const role = roleOf(element);
300
+ const disabled = Boolean(element.disabled || element.getAttribute("aria-disabled") === "true");
301
+ const rawValue = "value" in element && typeof element.value === "string" ? element.value : undefined;
302
+ const sensitive = isSensitiveField(element);
303
+ const value = rawValue && !sensitive ? rawValue.slice(0, 120) : undefined;
304
+ const checked = "checked" in element ? Boolean(element.checked) : undefined;
305
+ return {
306
+ index,
307
+ uid: rememberElement(element),
308
+ tag: element.tagName.toLowerCase(),
309
+ role,
310
+ selector: selectorFor(element),
311
+ label: accessibleLabel(element),
312
+ href: element.href || undefined,
313
+ type: element.getAttribute("type") || undefined,
314
+ value: value || undefined,
315
+ hasValue: rawValue ? rawValue.length > 0 : undefined,
316
+ valueLength: rawValue && sensitive ? rawValue.length : undefined,
317
+ valueRedacted: sensitive && rawValue ? true : undefined,
318
+ checked,
319
+ disabled,
320
+ inert: Boolean(element.closest?.("[inert]")),
321
+ pointerEvents: style.pointerEvents,
322
+ occluded: occluded || undefined,
323
+ context: contextForElement(element),
324
+ rect: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) },
325
+ };
326
+ }
327
+
328
+ function isInViewport(element) {
329
+ const rect = element.getBoundingClientRect();
330
+ return rect.bottom >= 0 && rect.right >= 0 && rect.top <= innerHeight && rect.left <= innerWidth;
331
+ }
332
+
333
+ function formSummaries() {
334
+ const fields = Array.from(document.querySelectorAll('input, textarea, select, [contenteditable="true"]'))
335
+ .filter(isElementVisible)
336
+ .slice(0, 80)
337
+ .map((element, index) => ({
338
+ ...summarizeElement(element, index),
339
+ required: Boolean(element.required || element.getAttribute("aria-required") === "true"),
340
+ invalid: Boolean(element.matches?.(":invalid") || element.getAttribute("aria-invalid") === "true"),
341
+ autocomplete: element.getAttribute("autocomplete") || undefined,
342
+ }));
343
+ const submits = Array.from(document.querySelectorAll('button, input[type="submit"], [role="button"]'))
344
+ .filter(isElementVisible)
345
+ .filter((element) => /submit|save|continue|next|send|sign in|log in|create|update|done/i.test(accessibleLabel(element) + " " + (element.getAttribute("type") || "")))
346
+ .slice(0, 30)
347
+ .map((element, index) => summarizeElement(element, index));
348
+ return { fields, submits };
349
+ }
350
+
351
+ function pageMap() {
352
+ const landmarkSelectors = [
353
+ ["header", 'header, [role="banner"]'],
354
+ ["nav", 'nav, [role="navigation"]'],
355
+ ["main", 'main, [role="main"]'],
356
+ ["aside", 'aside, [role="complementary"]'],
357
+ ["footer", 'footer, [role="contentinfo"]'],
358
+ ["dialog", 'dialog, [role="dialog"], [aria-modal="true"]'],
359
+ ["form", "form"],
360
+ ];
361
+ const regions = [];
362
+ for (const [kind, selector] of landmarkSelectors) {
363
+ for (const element of Array.from(document.querySelectorAll(selector)).filter(isElementVisible).slice(0, 12)) {
364
+ const headings = Array.from(element.querySelectorAll("h1,h2,h3,[role='heading']")).filter(isElementVisible).slice(0, 6).map((h) => textOf(h, 120));
365
+ const actions = Array.from(element.querySelectorAll('a, button, input, textarea, select, [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])')).filter(isElementVisible).slice(0, 8).map((a) => {
366
+ const summary = summarizeElement(a, 0);
367
+ return { uid: summary.uid, role: summary.role, label: summary.label || summary.selector, disabled: summary.disabled || undefined };
368
+ });
369
+ regions.push({ kind, uid: rememberElement(element), label: accessibleLabel(element) || headings[0] || textOf(element, 100), headings, actions });
370
+ }
371
+ }
372
+ const headings = Array.from(document.querySelectorAll("h1,h2,h3,[role='heading']")).filter(isElementVisible).slice(0, 30).map((element) => ({
373
+ uid: rememberElement(element),
374
+ level: Number(element.tagName?.slice(1)) || Number(element.getAttribute("aria-level")) || undefined,
375
+ text: textOf(element, 180),
376
+ }));
377
+ return { regions, headings };
378
+ }
379
+
380
+ function layoutSections(elements, forms) {
381
+ const byUid = new Map();
382
+ const addToSection = (summary, kind) => {
383
+ const source = getPiChromeState().elements[summary.uid];
384
+ const container = source ? meaningfulContainerFor(source) : null;
385
+ if (!container || container === document.body) return;
386
+ const uid = rememberElement(container);
387
+ let section = byUid.get(uid);
388
+ if (!section) {
389
+ const rect = rectSummary(container);
390
+ section = {
391
+ uid,
392
+ tag: container.tagName.toLowerCase(),
393
+ role: roleOf(container),
394
+ label: directHeadingText(container) || accessibleLabel(container) || textOf(container, 160),
395
+ text: textOf(container, 260),
396
+ rect,
397
+ actions: [],
398
+ fields: [],
399
+ };
400
+ byUid.set(uid, section);
401
+ }
402
+ const item = { uid: summary.uid, role: summary.role, label: summary.label || summary.selector, disabled: summary.disabled || undefined };
403
+ if (kind === "field") section.fields.push(item);
404
+ else section.actions.push(item);
405
+ };
406
+ for (const el of (elements || []).slice(0, 80)) addToSection(el, ["textbox", "checkbox", "radio", "combobox"].includes(el.role) ? "field" : "action");
407
+ for (const field of (forms?.fields || []).slice(0, 80)) addToSection(field, "field");
408
+ const sections = Array.from(byUid.values())
409
+ .filter((section) => section.actions.length || section.fields.length)
410
+ .sort((a, b) => a.rect.y - b.rect.y || a.rect.x - b.rect.x)
411
+ .slice(0, 18);
412
+ for (const section of sections) {
413
+ section.actions = section.actions.slice(0, 10);
414
+ section.fields = section.fields.slice(0, 10);
415
+ }
416
+ return sections;
417
+ }
418
+
419
+ function tokenScore(haystack, query) {
420
+ if (!query) return 0;
421
+ const hay = String(haystack || "").toLowerCase();
422
+ const tokens = String(query).toLowerCase().split(/\W+/).filter(Boolean);
423
+ if (!tokens.length) return 0;
424
+ let score = 0;
425
+ for (const token of tokens) {
426
+ if (hay.includes(token)) score += token.length <= 2 ? 1 : 3;
427
+ }
428
+ if (hay.includes(String(query).toLowerCase())) score += 8;
429
+ return score;
430
+ }
431
+
432
+ function queryMatches(query, elements, map) {
433
+ if (!query) return [];
434
+ const candidates = [];
435
+ for (const element of elements) {
436
+ const hay = [element.role, element.label, element.selector, element.type, element.href].filter(Boolean).join(" ");
437
+ const score = tokenScore(hay, query);
438
+ if (score > 0) candidates.push({ score, kind: "element", ...element });
439
+ }
440
+ const textNodes = [];
441
+ for (const block of Array.from(document.querySelectorAll("h1,h2,h3,h4,p,li,td,th,label,summary,[role='alert']")).filter(isElementVisible).slice(0, 300)) {
442
+ const text = textOf(block, 300);
443
+ const score = tokenScore(text, query);
444
+ if (score > 0) textNodes.push({ score, kind: "text", uid: rememberElement(block), tag: block.tagName.toLowerCase(), role: roleOf(block), text, rect: rectSummary(block) });
445
+ }
446
+ for (const region of map.regions || []) {
447
+ const score = tokenScore([region.kind, region.label, ...(region.headings || [])].join(" "), query);
448
+ if (score > 0) candidates.push({ score, kind: "region", ...region });
449
+ }
450
+ return candidates.concat(textNodes).sort((a, b) => b.score - a.score).slice(0, 20);
451
+ }
452
+
453
+ function rectSummary(element) {
454
+ const rect = element.getBoundingClientRect();
455
+ return { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) };
456
+ }
457
+
458
+ function activeElementSummary() {
459
+ const el = document.activeElement;
460
+ if (!el || el === document.body || el === document.documentElement) return null;
461
+ return summarizeElement(el, 0);
462
+ }
463
+
464
+ function modalSummary() {
465
+ const selectors = 'dialog[open], [role="dialog"], [aria-modal="true"], [role="alertdialog"]';
466
+ const modal = Array.from(document.querySelectorAll(selectors)).find(isElementVisible);
467
+ if (!modal) return null;
468
+ return { uid: rememberElement(modal), tag: modal.tagName.toLowerCase(), role: roleOf(modal), label: accessibleLabel(modal) || textOf(modal, 180), rect: rectSummary(modal) };
469
+ }
470
+
471
+ function digestFor(snapshot) {
472
+ return {
473
+ url: snapshot.url,
474
+ title: snapshot.title,
475
+ textHash: hashString(snapshot.text || ""),
476
+ focusedUid: snapshot.focused?.uid || null,
477
+ modalUid: snapshot.modal?.uid || null,
478
+ labels: (snapshot.elements || []).slice(0, 50).map((el) => ({ uid: el.uid, role: el.role, label: el.label, disabled: el.disabled, value: el.value, checked: el.checked })),
479
+ };
480
+ }
481
+
482
+ function diffSnapshot(previous, current) {
483
+ if (!previous) return { firstSnapshot: true };
484
+ const changes = [];
485
+ if (previous.url !== current.url) changes.push({ kind: "url", before: previous.url, after: current.url });
486
+ if (previous.title !== current.title) changes.push({ kind: "title", before: previous.title, after: current.title });
487
+ if (previous.textHash !== current.textHash) changes.push({ kind: "textChanged" });
488
+ if (previous.focusedUid !== current.focusedUid) changes.push({ kind: "focus", before: previous.focusedUid, after: current.focusedUid });
489
+ if (previous.modalUid !== current.modalUid) changes.push({ kind: "modal", before: previous.modalUid, after: current.modalUid });
490
+ const prevByUid = new Map((previous.labels || []).map((x) => [x.uid, x]));
491
+ const curByUid = new Map((current.labels || []).map((x) => [x.uid, x]));
492
+ const added = [];
493
+ const removed = [];
494
+ const updated = [];
495
+ for (const cur of current.labels || []) {
496
+ const prev = prevByUid.get(cur.uid);
497
+ if (!prev) added.push(cur);
498
+ else if (prev.label !== cur.label || prev.disabled !== cur.disabled || prev.value !== cur.value || prev.checked !== cur.checked) updated.push({ uid: cur.uid, before: prev, after: cur });
499
+ }
500
+ for (const prev of previous.labels || []) {
501
+ if (!curByUid.has(prev.uid)) removed.push(prev);
502
+ }
503
+ return { changes, added: added.slice(0, 12), removed: removed.slice(0, 12), updated: updated.slice(0, 12) };
504
+ }
505
+
506
+ function visibleTextSnippets(maxChars) {
507
+ const snippets = [];
508
+ const blocks = Array.from(document.querySelectorAll("h1,h2,h3,h4,p,li,td,th,label,summary,[role='alert']")).filter(isElementVisible);
509
+ let used = 0;
510
+ for (const block of blocks) {
511
+ if (!isInViewport(block) && snippets.length > 12) continue;
512
+ const text = textOf(block, 500);
513
+ if (!text || snippets.some((s) => s.text === text)) continue;
514
+ const next = { uid: rememberElement(block), tag: block.tagName.toLowerCase(), text, rect: rectSummary(block) };
515
+ snippets.push(next);
516
+ used += text.length;
517
+ if (used >= maxChars || snippets.length >= 40) break;
518
+ }
519
+ return snippets;
520
+ }
521
+
522
+ function snapshotPage(maxElements, containingText, roleFilter, nearUid, mode, query, maxTextChars) {
523
+ installPiChromeInstrumentation();
524
+ mode = ["auto", "interactive", "forms", "pageMap", "text", "changes", "full"].includes(mode) ? mode : "auto";
525
+ const fullTextLimit = Number(maxTextChars || (mode === "full" ? 30000 : mode === "text" ? 18000 : 6000));
526
+ let candidates = Array.from(document.querySelectorAll('a, button, input, textarea, select, summary, [role="button"], [role="link"], [role="menuitem"], [role="tab"], [role="checkbox"], [contenteditable="true"], [tabindex]:not([tabindex="-1"])'));
527
+ if (containingText) {
528
+ const needle = String(containingText).toLowerCase();
529
+ candidates = candidates.filter((element) => accessibleLabel(element).toLowerCase().includes(needle));
530
+ }
531
+ if (roleFilter) {
532
+ const wanted = String(roleFilter).toLowerCase();
533
+ candidates = candidates.filter((element) => roleOf(element) === wanted || element.tagName.toLowerCase() === wanted);
534
+ }
535
+ let near;
536
+ if (nearUid) near = getPiChromeState().elements[nearUid];
537
+ if (near) {
538
+ const nearRect = near.getBoundingClientRect();
539
+ const cx = nearRect.left + nearRect.width / 2;
540
+ const cy = nearRect.top + nearRect.height / 2;
541
+ candidates.sort((a, b) => {
542
+ const ra = a.getBoundingClientRect();
543
+ const rb = b.getBoundingClientRect();
544
+ const da = Math.hypot(ra.left + ra.width / 2 - cx, ra.top + ra.height / 2 - cy);
545
+ const db = Math.hypot(rb.left + rb.width / 2 - cx, rb.top + rb.height / 2 - cy);
546
+ return da - db;
547
+ });
548
+ } else {
549
+ candidates.sort((a, b) => {
550
+ const ar = a.getBoundingClientRect();
551
+ const br = b.getBoundingClientRect();
552
+ const avis = isInViewport(a) ? 0 : 1;
553
+ const bvis = isInViewport(b) ? 0 : 1;
554
+ return avis - bvis || ar.top - br.top || ar.left - br.left;
555
+ });
556
+ }
557
+ const visibleCandidates = candidates.filter(isElementVisible);
558
+ const elements = visibleCandidates.slice(0, maxElements).map((element, index) => summarizeElement(element, index));
559
+ const queryElements = query
560
+ ? visibleCandidates.slice(0, Math.max(maxElements, 500)).map((element, index) => summarizeElement(element, index))
561
+ : elements;
562
+ const map = pageMap();
563
+ const forms = formSummaries();
564
+ const layout = layoutSections(elements, forms);
565
+ const focused = activeElementSummary();
566
+ const modal = modalSummary();
567
+ const bodyText = document.body ? document.body.innerText.replace(/\s+\n/g, "\n").trim() : "";
568
+ const text = bodyText.slice(0, fullTextLimit);
569
+ const snapshot = {
570
+ title: document.title,
571
+ url: location.href,
572
+ mode,
573
+ query: query || undefined,
574
+ viewport: { width: innerWidth, height: innerHeight, scrollX, scrollY },
575
+ summary: {
576
+ visibleText: textOf(document.body, 500),
577
+ visibleInteractiveCount: elements.filter((el) => el.rect.y >= 0 && el.rect.y <= innerHeight).length,
578
+ totalInteractiveSampled: elements.length,
579
+ totalInteractiveVisible: visibleCandidates.length,
580
+ focused: focused ? { uid: focused.uid, role: focused.role, label: focused.label } : undefined,
581
+ modal: modal ? { uid: modal.uid, label: modal.label } : undefined,
582
+ hints: [],
583
+ },
584
+ focused: focused || undefined,
585
+ modal: modal || undefined,
586
+ text,
587
+ textTruncated: bodyText.length > text.length,
588
+ textSnippets: visibleTextSnippets(mode === "text" ? 12000 : 3000),
589
+ elements,
590
+ forms,
591
+ layout,
592
+ pageMap: map,
593
+ matches: queryMatches(query, queryElements, map),
594
+ filter: { containingText: containingText || undefined, roleFilter: roleFilter || undefined, nearUid: nearUid || undefined },
595
+ };
596
+ if (snapshot.modal) snapshot.summary.hints.push("A modal/dialog is visible; interact with it before the underlying page.");
597
+ const disabledImportant = elements.find((el) => el.disabled && /submit|save|merge|continue|next|send|approve|login|sign in/i.test(el.label || ""));
598
+ if (disabledImportant) snapshot.summary.hints.push(`${disabledImportant.uid} '${disabledImportant.label}' is disabled.`);
599
+ const occluded = elements.find((el) => el.occluded);
600
+ if (occluded) snapshot.summary.hints.push(`${occluded.uid} '${occluded.label || occluded.role}' appears occluded by ${occluded.occluded.tag}.`);
601
+
602
+ const state = getPiChromeState();
603
+ const currentDigest = digestFor(snapshot);
604
+ snapshot.diff = diffSnapshot(state.lastSnapshotDigest, currentDigest);
605
+ state.lastSnapshotDigest = currentDigest;
606
+
607
+ if (mode === "interactive") {
608
+ delete snapshot.text;
609
+ delete snapshot.textSnippets;
610
+ delete snapshot.pageMap;
611
+ } else if (mode === "forms") {
612
+ delete snapshot.text;
613
+ delete snapshot.textSnippets;
614
+ snapshot.elements = elements.filter((el) => ["textbox", "checkbox", "radio", "combobox", "button"].includes(el.role));
615
+ } else if (mode === "pageMap") {
616
+ delete snapshot.text;
617
+ delete snapshot.textSnippets;
618
+ snapshot.elements = elements.slice(0, 20);
619
+ } else if (mode === "changes") {
620
+ delete snapshot.text;
621
+ delete snapshot.textSnippets;
622
+ delete snapshot.elements;
623
+ delete snapshot.forms;
624
+ delete snapshot.layout;
625
+ delete snapshot.pageMap;
626
+ } else if (mode === "text") {
627
+ snapshot.elements = elements.slice(0, 20);
628
+ } else if (mode !== "full") {
629
+ snapshot.elements = elements.slice(0, Math.min(maxElements, 40));
630
+ snapshot.text = text.slice(0, Math.min(text.length, 6000));
631
+ }
632
+ return snapshot;
633
+ }
634
+
635
+ function inspectTarget(uid, selector, shouldScrollIntoView) {
636
+ installPiChromeInstrumentation();
637
+ const state = getPiChromeState();
638
+ let element = null;
639
+ if (uid) element = state.elements[uid];
640
+ if (!element && selector) element = document.querySelector(selector);
641
+ if (!element || !element.isConnected) throw new Error(uid ? `No live element for uid: ${uid}. Take a fresh chrome_snapshot.` : `No element matches selector: ${selector}`);
642
+ if (shouldScrollIntoView) element.scrollIntoView?.({ block: "center", inline: "center", behavior: "instant" });
643
+ const summary = summarizeElement(element, 0);
644
+ const ancestors = [];
645
+ let current = element.parentElement;
646
+ while (current && current !== document.body && ancestors.length < 6) {
647
+ ancestors.push({ uid: rememberElement(current), tag: current.tagName.toLowerCase(), role: roleOf(current), label: accessibleLabel(current) || textOf(current, 100), selector: selectorFor(current) });
648
+ current = current.parentElement;
649
+ }
650
+ const container = element.closest?.('form, dialog, [role="dialog"], [aria-modal="true"], section, article, main, aside') || element.parentElement || document.body;
651
+ const nearbyText = Array.from(container.querySelectorAll("h1,h2,h3,h4,p,li,label,[role='alert']"))
652
+ .filter(isElementVisible)
653
+ .slice(0, 24)
654
+ .map((node) => ({ uid: rememberElement(node), tag: node.tagName.toLowerCase(), text: textOf(node, 240), rect: rectSummary(node) }))
655
+ .filter((entry) => entry.text);
656
+ const nearbyActions = Array.from(container.querySelectorAll('a, button, input, textarea, select, [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])'))
657
+ .filter(isElementVisible)
658
+ .slice(0, 30)
659
+ .map((node, index) => summarizeElement(node, index));
660
+ const form = element.closest?.("form");
661
+ const formContext = form ? {
662
+ uid: rememberElement(form),
663
+ label: accessibleLabel(form) || textOf(form, 160),
664
+ fields: Array.from(form.querySelectorAll('input, textarea, select, [contenteditable="true"]')).filter(isElementVisible).slice(0, 30).map((node, index) => summarizeElement(node, index)),
665
+ actions: Array.from(form.querySelectorAll('button, input[type="submit"], [role="button"]')).filter(isElementVisible).slice(0, 12).map((node, index) => summarizeElement(node, index)),
666
+ } : undefined;
667
+ const rect = element.getBoundingClientRect();
668
+ const center = { x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2) };
669
+ const clickSuggestion = summary.disabled || summary.inert || summary.pointerEvents === "none"
670
+ ? undefined
671
+ : { uid: summary.uid, x: center.x, y: center.y };
672
+ return { target: summary, ancestors, nearbyText, nearbyActions, formContext, clickSuggestion };
673
+ }
674
+
675
+ globalThis.__piChromeSnapshotPage = snapshotPage;
676
+ globalThis.__piChromeInspectTarget = inspectTarget;
677
+ })();