@dudko.dev/agent-web-ui 0.0.5 → 0.0.7

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 (164) hide show
  1. package/README.md +81 -3
  2. package/dist/{chunk-NHU6WQM5.js → chunk-3TMUUU3O.js} +424 -0
  3. package/dist/{chunk-627OXMFG.js → chunk-HIHUK7YA.js} +5 -0
  4. package/dist/{chunk-S5AHUAFG.js → chunk-JEW2ZWYX.js} +4 -0
  5. package/dist/{chunk-VZCQXE3P.js → chunk-UO2Q7AIV.js} +4 -0
  6. package/dist/{chunk-V33T6VX3.js → chunk-VG5NLFI5.js} +4 -0
  7. package/dist/controller.cjs +460 -16
  8. package/dist/controller.d.cts +53 -5
  9. package/dist/controller.d.ts +53 -5
  10. package/dist/controller.js +58 -17
  11. package/dist/{en-Dg2MtzcJ.d.cts → en-CPCAidve.d.cts} +4 -0
  12. package/dist/{en-Dg2MtzcJ.d.ts → en-CPCAidve.d.ts} +4 -0
  13. package/dist/index.cjs +447 -3
  14. package/dist/index.d.cts +2 -1
  15. package/dist/index.d.ts +2 -1
  16. package/dist/index.js +37 -1
  17. package/dist/{labels-ipy-ydkp.d.cts → labels-Dnh2tn8S.d.cts} +8 -0
  18. package/dist/{labels-CCPL7t17.d.ts → labels-h-grbo5N.d.ts} +8 -0
  19. package/dist/locales/be.cjs +9 -0
  20. package/dist/locales/be.d.cts +1 -1
  21. package/dist/locales/be.d.ts +1 -1
  22. package/dist/locales/be.js +5 -1
  23. package/dist/locales/bg.cjs +9 -0
  24. package/dist/locales/bg.d.cts +1 -1
  25. package/dist/locales/bg.d.ts +1 -1
  26. package/dist/locales/bg.js +5 -1
  27. package/dist/locales/ca.cjs +9 -0
  28. package/dist/locales/ca.d.cts +1 -1
  29. package/dist/locales/ca.d.ts +1 -1
  30. package/dist/locales/ca.js +5 -1
  31. package/dist/locales/cs.cjs +9 -0
  32. package/dist/locales/cs.d.cts +1 -1
  33. package/dist/locales/cs.d.ts +1 -1
  34. package/dist/locales/cs.js +5 -1
  35. package/dist/locales/da.cjs +9 -0
  36. package/dist/locales/da.d.cts +1 -1
  37. package/dist/locales/da.d.ts +1 -1
  38. package/dist/locales/da.js +5 -1
  39. package/dist/locales/de.cjs +9 -0
  40. package/dist/locales/de.d.cts +1 -1
  41. package/dist/locales/de.d.ts +1 -1
  42. package/dist/locales/de.js +5 -1
  43. package/dist/locales/el.cjs +9 -0
  44. package/dist/locales/el.d.cts +1 -1
  45. package/dist/locales/el.d.ts +1 -1
  46. package/dist/locales/el.js +5 -1
  47. package/dist/locales/en.cjs +9 -0
  48. package/dist/locales/en.d.cts +1 -1
  49. package/dist/locales/en.d.ts +1 -1
  50. package/dist/locales/en.js +5 -1
  51. package/dist/locales/es-419.cjs +9 -0
  52. package/dist/locales/es-419.d.cts +1 -1
  53. package/dist/locales/es-419.d.ts +1 -1
  54. package/dist/locales/es-419.js +2 -2
  55. package/dist/locales/es.cjs +9 -0
  56. package/dist/locales/es.d.cts +1 -1
  57. package/dist/locales/es.d.ts +1 -1
  58. package/dist/locales/es.js +2 -2
  59. package/dist/locales/fi.cjs +9 -0
  60. package/dist/locales/fi.d.cts +1 -1
  61. package/dist/locales/fi.d.ts +1 -1
  62. package/dist/locales/fi.js +5 -1
  63. package/dist/locales/fr-CA.cjs +9 -0
  64. package/dist/locales/fr-CA.d.cts +1 -1
  65. package/dist/locales/fr-CA.d.ts +1 -1
  66. package/dist/locales/fr-CA.js +2 -2
  67. package/dist/locales/fr.cjs +9 -0
  68. package/dist/locales/fr.d.cts +1 -1
  69. package/dist/locales/fr.d.ts +1 -1
  70. package/dist/locales/fr.js +2 -2
  71. package/dist/locales/gn.cjs +9 -0
  72. package/dist/locales/gn.d.cts +1 -1
  73. package/dist/locales/gn.d.ts +1 -1
  74. package/dist/locales/gn.js +5 -1
  75. package/dist/locales/hr.cjs +9 -0
  76. package/dist/locales/hr.d.cts +1 -1
  77. package/dist/locales/hr.d.ts +1 -1
  78. package/dist/locales/hr.js +5 -1
  79. package/dist/locales/ht.cjs +9 -0
  80. package/dist/locales/ht.d.cts +1 -1
  81. package/dist/locales/ht.d.ts +1 -1
  82. package/dist/locales/ht.js +5 -1
  83. package/dist/locales/hu.cjs +9 -0
  84. package/dist/locales/hu.d.cts +1 -1
  85. package/dist/locales/hu.d.ts +1 -1
  86. package/dist/locales/hu.js +5 -1
  87. package/dist/locales/index.cjs +5 -0
  88. package/dist/locales/index.d.cts +3 -3
  89. package/dist/locales/index.d.ts +3 -3
  90. package/dist/locales/index.js +1 -1
  91. package/dist/locales/it.cjs +9 -0
  92. package/dist/locales/it.d.cts +1 -1
  93. package/dist/locales/it.d.ts +1 -1
  94. package/dist/locales/it.js +5 -1
  95. package/dist/locales/nb.cjs +9 -0
  96. package/dist/locales/nb.d.cts +1 -1
  97. package/dist/locales/nb.d.ts +1 -1
  98. package/dist/locales/nb.js +5 -1
  99. package/dist/locales/nl.cjs +9 -0
  100. package/dist/locales/nl.d.cts +1 -1
  101. package/dist/locales/nl.d.ts +1 -1
  102. package/dist/locales/nl.js +5 -1
  103. package/dist/locales/pl.cjs +9 -0
  104. package/dist/locales/pl.d.cts +1 -1
  105. package/dist/locales/pl.d.ts +1 -1
  106. package/dist/locales/pl.js +5 -1
  107. package/dist/locales/pt-BR.cjs +9 -0
  108. package/dist/locales/pt-BR.d.cts +1 -1
  109. package/dist/locales/pt-BR.d.ts +1 -1
  110. package/dist/locales/pt-BR.js +5 -1
  111. package/dist/locales/pt.cjs +9 -0
  112. package/dist/locales/pt.d.cts +1 -1
  113. package/dist/locales/pt.d.ts +1 -1
  114. package/dist/locales/pt.js +5 -1
  115. package/dist/locales/qu.cjs +9 -0
  116. package/dist/locales/qu.d.cts +1 -1
  117. package/dist/locales/qu.d.ts +1 -1
  118. package/dist/locales/qu.js +5 -1
  119. package/dist/locales/ro.cjs +9 -0
  120. package/dist/locales/ro.d.cts +1 -1
  121. package/dist/locales/ro.d.ts +1 -1
  122. package/dist/locales/ro.js +5 -1
  123. package/dist/locales/ru.cjs +9 -0
  124. package/dist/locales/ru.d.cts +1 -1
  125. package/dist/locales/ru.d.ts +1 -1
  126. package/dist/locales/ru.js +5 -1
  127. package/dist/locales/sk.cjs +9 -0
  128. package/dist/locales/sk.d.cts +1 -1
  129. package/dist/locales/sk.d.ts +1 -1
  130. package/dist/locales/sk.js +5 -1
  131. package/dist/locales/sq.cjs +9 -0
  132. package/dist/locales/sq.d.cts +1 -1
  133. package/dist/locales/sq.d.ts +1 -1
  134. package/dist/locales/sq.js +5 -1
  135. package/dist/locales/sr-Latn.cjs +9 -0
  136. package/dist/locales/sr-Latn.d.cts +1 -1
  137. package/dist/locales/sr-Latn.d.ts +1 -1
  138. package/dist/locales/sr-Latn.js +2 -2
  139. package/dist/locales/sr.cjs +9 -0
  140. package/dist/locales/sr.d.cts +1 -1
  141. package/dist/locales/sr.d.ts +1 -1
  142. package/dist/locales/sr.js +2 -2
  143. package/dist/locales/sv.cjs +9 -0
  144. package/dist/locales/sv.d.cts +1 -1
  145. package/dist/locales/sv.d.ts +1 -1
  146. package/dist/locales/sv.js +5 -1
  147. package/dist/locales/tr.cjs +9 -0
  148. package/dist/locales/tr.d.cts +1 -1
  149. package/dist/locales/tr.d.ts +1 -1
  150. package/dist/locales/tr.js +5 -1
  151. package/dist/locales/uk.cjs +9 -0
  152. package/dist/locales/uk.d.cts +1 -1
  153. package/dist/locales/uk.d.ts +1 -1
  154. package/dist/locales/uk.js +5 -1
  155. package/dist/page-context-BAmw4p6d.d.cts +244 -0
  156. package/dist/page-context-BAmw4p6d.d.ts +244 -0
  157. package/dist/pipeline-format.cjs +842 -0
  158. package/dist/pipeline-format.d.cts +512 -0
  159. package/dist/pipeline-format.d.ts +512 -0
  160. package/dist/pipeline-format.js +788 -0
  161. package/dist/styles.css +55 -0
  162. package/dist/{types-CQquuZpl.d.cts → types-B5cyqkWY.d.cts} +1 -1
  163. package/dist/{types-CXZfZVP5.d.ts → types-BgNjWN5Z.d.ts} +1 -1
  164. package/package.json +12 -2
@@ -33,14 +33,420 @@ __export(controller_exports, {
33
33
  createAgentController: () => createAgentController,
34
34
  createInitialAgentSnapshot: () => createInitialAgentSnapshot,
35
35
  createInitialRemoteSnapshot: () => createInitialRemoteSnapshot,
36
+ createPageContextCollector: () => createPageContextCollector,
36
37
  createRemoteAgentController: () => createRemoteAgentController,
37
38
  createSseParser: () => createSseParser,
38
39
  parseRemoteCursor: () => parseRemoteCursor,
39
40
  remoteEventOf: () => remoteEventOf,
40
- remoteEventScope: () => remoteEventScope
41
+ remoteEventScope: () => remoteEventScope,
42
+ trackPageFocus: () => trackPageFocus
41
43
  });
42
44
  module.exports = __toCommonJS(controller_exports);
43
45
 
46
+ // src/page-context.ts
47
+ var PAGE_CONTEXT_VALUE_MAX = 500;
48
+ var PAGE_CONTEXT_SELECTION_MAX = 500;
49
+ var PAGE_CONTEXT_MAX_CHARS = 2e3;
50
+ var HEADINGS_MAX = 8;
51
+ var CLIP = "…";
52
+ var clip = (text, max) => text.length > max ? `${text.slice(0, Math.max(0, max - 1))}${CLIP}` : text;
53
+ var oneLine = (text) => text.replace(/\s+/g, " ").trim();
54
+ var pageEnv = () => {
55
+ const g = globalThis;
56
+ if (typeof g.window === "undefined") return {};
57
+ const w = g;
58
+ return {
59
+ location: w.location,
60
+ document: w.document,
61
+ getSelection: () => w.getSelection?.() ?? null,
62
+ innerWidth: w.innerWidth,
63
+ innerHeight: w.innerHeight,
64
+ scrollY: w.scrollY,
65
+ matchMedia: (q) => w.matchMedia(q),
66
+ ...g.navigator?.geolocation ? { geolocation: g.navigator.geolocation } : {},
67
+ now: () => Date.now(),
68
+ timeZone: () => Intl.DateTimeFormat().resolvedOptions().timeZone,
69
+ screenWidth: g.screen?.width ?? w.innerWidth
70
+ };
71
+ };
72
+ var pageContextOff = (options) => !options || !options.extra && !Object.values(options.collect ?? {}).some((v) => v !== false && v != null);
73
+ var addressWithoutQuery = (href) => {
74
+ try {
75
+ const u = new URL(href);
76
+ if (u.protocol !== "http:" && u.protocol !== "https:") return void 0;
77
+ return `${u.origin}${u.pathname}`;
78
+ } catch {
79
+ return void 0;
80
+ }
81
+ };
82
+ var autocompleteTokens = (el) => (el.getAttribute("autocomplete") ?? "").toLowerCase().split(/\s+/).filter(Boolean);
83
+ var isSecretField = (el) => {
84
+ const type = (el.type ?? el.getAttribute("type") ?? "").toLowerCase();
85
+ if (type === "password" || type === "hidden") return true;
86
+ return autocompleteTokens(el).some(
87
+ (t) => t.startsWith("cc-") || t === "one-time-code" || t === "current-password" || t === "new-password"
88
+ );
89
+ };
90
+ var IMPLICIT_ROLE = {
91
+ a: "link",
92
+ button: "button",
93
+ textarea: "textbox",
94
+ select: "combobox",
95
+ h1: "heading",
96
+ h2: "heading",
97
+ h3: "heading",
98
+ summary: "button"
99
+ };
100
+ var roleOf = (el) => {
101
+ const explicit = el.getAttribute("role");
102
+ if (explicit) return explicit.split(/\s+/)[0];
103
+ const tag = el.tagName.toLowerCase();
104
+ if (tag === "input") {
105
+ const type = (el.type ?? el.getAttribute("type") ?? "text").toLowerCase();
106
+ if (type === "checkbox") return "checkbox";
107
+ if (type === "radio") return "radio";
108
+ if (type === "button" || type === "submit" || type === "reset") return "button";
109
+ if (type === "range") return "slider";
110
+ if (type === "search") return "searchbox";
111
+ return "textbox";
112
+ }
113
+ if (tag !== "textarea" && tag !== "select" && isEditableElement(el)) return "textbox";
114
+ return IMPLICIT_ROLE[tag] ?? tag;
115
+ };
116
+ var EDITABLE_ROLES = /* @__PURE__ */ new Set(["textbox", "searchbox", "combobox", "spinbutton"]);
117
+ var isEditableElement = (el) => {
118
+ const tag = el.tagName.toLowerCase();
119
+ if (tag === "input" || tag === "textarea" || tag === "select") return true;
120
+ if (el.isContentEditable === true) return true;
121
+ const ce = el.getAttribute("contenteditable");
122
+ if (ce !== null && ce.toLowerCase() !== "false") return true;
123
+ const role = (el.getAttribute("role") ?? "").toLowerCase().split(/\s+/)[0] ?? "";
124
+ return EDITABLE_ROLES.has(role);
125
+ };
126
+ var nameOf = (el, env) => {
127
+ const aria = el.getAttribute("aria-label");
128
+ if (aria) return aria;
129
+ const by = el.getAttribute("aria-labelledby");
130
+ if (by) {
131
+ const text = by.split(/\s+/).map((id) => env.document?.getElementById?.(id)?.textContent ?? "").join(" ");
132
+ if (text.trim()) return text;
133
+ }
134
+ const label = el.labels && el.labels.length ? el.labels[0]?.textContent ?? "" : "";
135
+ if (label.trim()) return label;
136
+ const placeholder = el.getAttribute("placeholder") ?? el.getAttribute("title");
137
+ if (placeholder) return placeholder;
138
+ return isEditableElement(el) ? "" : el.textContent ?? "";
139
+ };
140
+ var focusEntries = (env, includeValues) => {
141
+ const el = env.document?.activeElement;
142
+ if (!el) return {};
143
+ const tag = el.tagName.toLowerCase();
144
+ if (tag === "body" || tag === "html") return {};
145
+ const out = { "focus.role": roleOf(el) };
146
+ const name = clip(oneLine(nameOf(el, env)), 120);
147
+ if (name) out["focus.label"] = name;
148
+ out["focus.type"] = tag === "input" ? `input:${(el.type ?? "text").toLowerCase()}` : tag;
149
+ if (includeValues && isEditableElement(el) && !isSecretField(el)) {
150
+ const isControl = tag === "input" || tag === "textarea" || tag === "select";
151
+ const raw = isControl ? el.value : el.textContent;
152
+ const value = typeof raw === "string" ? raw.trim() : "";
153
+ if (value) out["focus.value"] = clip(value, PAGE_CONTEXT_VALUE_MAX);
154
+ }
155
+ return out;
156
+ };
157
+ var headingsInView = (env) => {
158
+ const all = env.document?.querySelectorAll?.("h1, h2, h3");
159
+ if (!all) return void 0;
160
+ const height = env.innerHeight ?? Infinity;
161
+ const shown = [];
162
+ for (let i = 0; i < all.length && shown.length < HEADINGS_MAX; i++) {
163
+ const h = all[i];
164
+ const box = h.getBoundingClientRect?.();
165
+ if (box && (box.bottom < 0 || box.top > height)) continue;
166
+ const text = clip(oneLine(h.textContent ?? ""), 120);
167
+ if (text) shown.push(text);
168
+ }
169
+ return shown.length ? clip(shown.join(" / "), PAGE_CONTEXT_VALUE_MAX) : void 0;
170
+ };
171
+ var roundCoordinate = (value, precision) => {
172
+ const p = Math.min(6, Math.max(0, Math.floor(precision)));
173
+ const f = 10 ** p;
174
+ return Math.round(value * f) / f;
175
+ };
176
+ var localIso = (ms) => {
177
+ const d = new Date(ms);
178
+ const pad = (n) => String(Math.abs(n)).padStart(2, "0");
179
+ const off = -d.getTimezoneOffset();
180
+ const sign = off >= 0 ? "+" : "-";
181
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}${sign}${pad(Math.floor(Math.abs(off) / 60))}:${pad(Math.abs(off) % 60)}`;
182
+ };
183
+ var capPageContext = (context, max) => {
184
+ let left = max;
185
+ const out = {};
186
+ for (const [k, v] of Object.entries(context)) {
187
+ const text = v === null ? "" : String(v);
188
+ const room = left - k.length - 2;
189
+ if (room <= 0) break;
190
+ if (typeof v === "string" && text.length > room) {
191
+ if (room < 8) break;
192
+ out[k] = clip(text, room);
193
+ left = 0;
194
+ break;
195
+ }
196
+ if (typeof v !== "string" && text.length > room) break;
197
+ out[k] = v;
198
+ left -= k.length + 2 + text.length;
199
+ }
200
+ return out;
201
+ };
202
+ var trackPageFocus = (doc, isInside) => {
203
+ let lastElement;
204
+ let lastSelection;
205
+ const deepActive = () => {
206
+ let el = doc.activeElement;
207
+ while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;
208
+ return el;
209
+ };
210
+ const isPageElement = (el) => {
211
+ const tag = el?.tagName?.toLowerCase();
212
+ return Boolean(tag) && tag !== "body" && tag !== "html";
213
+ };
214
+ const onFocus = (e) => {
215
+ const target = e.composedPath?.()[0] ?? e.target;
216
+ if (isPageElement(target) && !isInside(target)) lastElement = target;
217
+ };
218
+ const onSelection = () => {
219
+ const sel = doc.getSelection();
220
+ if (!sel || isInside(sel.anchorNode)) return;
221
+ const text = sel.toString().trim();
222
+ lastSelection = text || void 0;
223
+ };
224
+ doc.addEventListener("focusin", onFocus, true);
225
+ doc.addEventListener("selectionchange", onSelection);
226
+ return {
227
+ element() {
228
+ const now = deepActive();
229
+ if (isPageElement(now) && !isInside(now)) return now;
230
+ const last = lastElement;
231
+ return last && last.isConnected !== false ? lastElement : void 0;
232
+ },
233
+ selection() {
234
+ const sel = doc.getSelection();
235
+ if (sel && !isInside(sel.anchorNode)) {
236
+ const text = sel.toString().trim();
237
+ if (text) return text;
238
+ }
239
+ return lastSelection;
240
+ },
241
+ stop() {
242
+ doc.removeEventListener("focusin", onFocus, true);
243
+ doc.removeEventListener("selectionchange", onSelection);
244
+ lastElement = void 0;
245
+ lastSelection = void 0;
246
+ }
247
+ };
248
+ };
249
+ var PAGE_CONTEXT_ASK_ON_SEND = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web-ui:page-context-ask");
250
+ var createPageContextCollector = (options, env = pageEnv) => {
251
+ let position;
252
+ let denied = false;
253
+ let tracker;
254
+ let asking;
255
+ const geoSettings = (raw) => {
256
+ const o = typeof raw === "object" && raw ? raw : {};
257
+ return {
258
+ precision: typeof o.precision === "number" ? o.precision : 2,
259
+ maxAgeMs: typeof o.maxAgeMs === "number" ? o.maxAgeMs : 10 * 6e4,
260
+ timeoutMs: typeof o.timeoutMs === "number" ? o.timeoutMs : 1e4
261
+ };
262
+ };
263
+ const askPosition = (e, s) => {
264
+ if (asking) return asking;
265
+ const geo = e.geolocation;
266
+ if (!geo) return Promise.resolve(void 0);
267
+ asking = new Promise((resolve) => {
268
+ let done = false;
269
+ const finish = (p) => {
270
+ if (done) return;
271
+ done = true;
272
+ asking = void 0;
273
+ resolve(p);
274
+ };
275
+ const timer = setTimeout(() => finish(void 0), s.timeoutMs + 1e3);
276
+ try {
277
+ geo.getCurrentPosition(
278
+ (p) => {
279
+ clearTimeout(timer);
280
+ const now = e.now?.() ?? Date.now();
281
+ position = {
282
+ latitude: p.coords.latitude,
283
+ longitude: p.coords.longitude,
284
+ accuracy: p.coords.accuracy,
285
+ at: now
286
+ };
287
+ finish(position);
288
+ },
289
+ (err) => {
290
+ clearTimeout(timer);
291
+ if (err?.code === 1) denied = true;
292
+ finish(void 0);
293
+ },
294
+ { timeout: s.timeoutMs, maximumAge: s.maxAgeMs, enableHighAccuracy: false }
295
+ );
296
+ } catch {
297
+ clearTimeout(timer);
298
+ finish(void 0);
299
+ }
300
+ });
301
+ return asking;
302
+ };
303
+ const fresh = (e, maxAgeMs) => position && (e.now?.() ?? Date.now()) - position.at <= maxAgeMs ? position : void 0;
304
+ const geoEntries = (p, precision) => ({
305
+ "geo.latitude": roundCoordinate(p.latitude, precision),
306
+ "geo.longitude": roundCoordinate(p.longitude, precision),
307
+ // The accuracy is never better than the rounding: at 2 decimals, about a kilometre.
308
+ "geo.accuracy": Math.max(
309
+ Math.round(p.accuracy),
310
+ Math.round(111e3 / 10 ** Math.min(6, precision))
311
+ )
312
+ });
313
+ const read = (base, o) => {
314
+ const t = tracker;
315
+ const e = t ? {
316
+ ...base,
317
+ // Delegated one by one: a real Document's getters and methods live on its prototype.
318
+ document: {
319
+ ...base.document?.title !== void 0 ? { title: base.document.title } : {},
320
+ ...base.document?.referrer !== void 0 ? { referrer: base.document.referrer } : {},
321
+ ...base.document?.documentElement ? { documentElement: base.document.documentElement } : {},
322
+ activeElement: t.element() ?? null,
323
+ querySelectorAll: (q) => base.document?.querySelectorAll?.(q) ?? [],
324
+ getElementById: (id) => base.document?.getElementById?.(id) ?? null
325
+ },
326
+ getSelection: () => {
327
+ const text = t.selection();
328
+ return text ? { toString: () => text } : null;
329
+ }
330
+ } : base;
331
+ const c = o.collect ?? {};
332
+ const out = {};
333
+ if (c.url && e.location) {
334
+ const url = addressWithoutQuery(e.location.href);
335
+ if (url) out.url = clip(url, PAGE_CONTEXT_VALUE_MAX);
336
+ }
337
+ if (c.path && e.location) out.path = clip(e.location.pathname, PAGE_CONTEXT_VALUE_MAX);
338
+ if (c.title && e.document?.title)
339
+ out.title = clip(oneLine(e.document.title), PAGE_CONTEXT_VALUE_MAX);
340
+ if (c.language && e.document?.documentElement?.lang)
341
+ out.language = e.document.documentElement.lang.slice(0, 35);
342
+ if (c.referrer && e.document?.referrer) {
343
+ const ref = addressWithoutQuery(e.document.referrer);
344
+ if (ref) out.referrer = clip(ref, PAGE_CONTEXT_VALUE_MAX);
345
+ }
346
+ if (c.focus) {
347
+ const includeValues = typeof c.focus === "object" && c.focus.includeValues === true;
348
+ Object.assign(out, focusEntries(e, includeValues));
349
+ }
350
+ if (c.selection) {
351
+ const max = typeof c.selection === "object" && typeof c.selection.maxChars === "number" ? Math.max(1, Math.min(PAGE_CONTEXT_VALUE_MAX * 4, c.selection.maxChars)) : PAGE_CONTEXT_SELECTION_MAX;
352
+ const text = (e.getSelection?.()?.toString() ?? "").trim();
353
+ if (text) out.selection = clip(text, max);
354
+ }
355
+ if (c.viewport && e.innerWidth && e.innerHeight)
356
+ out.viewport = `${e.innerWidth}x${e.innerHeight}`;
357
+ if (c.scroll && typeof e.scrollY === "number") {
358
+ const total = (e.document?.documentElement?.scrollHeight ?? 0) - (e.innerHeight ?? 0);
359
+ out.scroll = total > 0 ? `${Math.round(Math.min(100, e.scrollY / total * 100))}% (${Math.round(e.scrollY)}px)` : `0% (${Math.round(e.scrollY)}px)`;
360
+ }
361
+ if (c.headings) {
362
+ const h = headingsInView(e);
363
+ if (h) out.headings = h;
364
+ }
365
+ if (c.time) {
366
+ const tz = e.timeZone?.();
367
+ if (tz) out.timeZone = tz;
368
+ out.localTime = localIso(e.now?.() ?? Date.now());
369
+ }
370
+ if (c.colorScheme && e.matchMedia) {
371
+ out.colorScheme = e.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
372
+ }
373
+ if (c.device && e.matchMedia) {
374
+ const coarse = e.matchMedia("(pointer: coarse)").matches;
375
+ const w = e.screenWidth ?? e.innerWidth ?? 0;
376
+ out.device = coarse ? w && w < 768 ? "phone" : "tablet" : "desktop";
377
+ }
378
+ return out;
379
+ };
380
+ const finishContext = (o, out) => {
381
+ let extra;
382
+ try {
383
+ extra = o.extra?.();
384
+ } catch {
385
+ extra = void 0;
386
+ }
387
+ if (extra && typeof extra === "object") {
388
+ for (const [k, v] of Object.entries(extra)) {
389
+ if (v === void 0) continue;
390
+ if (v === null || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v))
391
+ out[k] = v;
392
+ else if (typeof v === "string") out[k] = clip(v, PAGE_CONTEXT_VALUE_MAX * 4);
393
+ }
394
+ }
395
+ const include = o.include ? new Set(o.include) : void 0;
396
+ const exclude = new Set(o.exclude ?? []);
397
+ const kept = {};
398
+ for (const [k, v] of Object.entries(out)) {
399
+ if (include && !include.has(k) || exclude.has(k)) continue;
400
+ kept[k] = v;
401
+ }
402
+ const capped = capPageContext(kept, o.maxChars ?? PAGE_CONTEXT_MAX_CHARS);
403
+ return Object.keys(capped).length ? capped : void 0;
404
+ };
405
+ return {
406
+ get geolocationDenied() {
407
+ return denied;
408
+ },
409
+ setTracker(next) {
410
+ tracker = next;
411
+ },
412
+ preview() {
413
+ const o = options();
414
+ if (pageContextOff(o)) return void 0;
415
+ const e = env();
416
+ const out = read(e, o);
417
+ const g = o.collect?.geolocation;
418
+ if (g && !denied && e.geolocation) {
419
+ const s = geoSettings(g);
420
+ const p = fresh(e, s.maxAgeMs);
421
+ if (p) Object.assign(out, geoEntries(p, s.precision));
422
+ else out["geo.latitude"] = PAGE_CONTEXT_ASK_ON_SEND;
423
+ }
424
+ return finishContext(o, out);
425
+ },
426
+ async collect(opts = {}) {
427
+ const o = options();
428
+ if (pageContextOff(o)) return void 0;
429
+ const e = env();
430
+ const out = read(e, o);
431
+ const g = o.collect?.geolocation;
432
+ if (g && !denied) {
433
+ const s = geoSettings(g);
434
+ const p = fresh(e, s.maxAgeMs) ?? (opts.ask ? await askPosition(e, s) : void 0);
435
+ if (p) Object.assign(out, geoEntries(p, s.precision));
436
+ }
437
+ return finishContext(o, out);
438
+ }
439
+ };
440
+ };
441
+ var withoutAskOnSend = (context) => {
442
+ if (!context) return void 0;
443
+ const out = {};
444
+ for (const [k, v] of Object.entries(context)) {
445
+ if (v !== PAGE_CONTEXT_ASK_ON_SEND) out[k] = v;
446
+ }
447
+ return Object.keys(out).length ? out : void 0;
448
+ };
449
+
44
450
  // src/approval-queue.ts
45
451
  var createApprovalQueue = () => {
46
452
  const waiting = /* @__PURE__ */ new Map();
@@ -1559,6 +1965,7 @@ var snapshotOf = (state, sessionId, answering) => Object.freeze({
1559
1965
  });
1560
1966
  var createRemoteAgentController = (options) => {
1561
1967
  const base = options.baseUrl.replace(/\/+$/, "");
1968
+ const pageContexts = createPageContextCollector(() => options.pageContext);
1562
1969
  const doFetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
1563
1970
  const minWait = Math.max(0, options.reconnect?.minMs ?? 1e3);
1564
1971
  const maxWait = Math.max(minWait, options.reconnect?.maxMs ?? 3e4);
@@ -1592,6 +1999,9 @@ var createRemoteAgentController = (options) => {
1592
1999
  let turnIds = [];
1593
2000
  let turnFinal = false;
1594
2001
  let waiting = [];
2002
+ const sentHere = /* @__PURE__ */ new Set();
2003
+ let frameInfo;
2004
+ const turnIsOurs = () => turnIds.some((id) => sentHere.has(id));
1595
2005
  const runs = /* @__PURE__ */ new Map();
1596
2006
  const fold = (action, attempt = 0, scope) => {
1597
2007
  if (turn) {
@@ -1609,7 +2019,7 @@ var createRemoteAgentController = (options) => {
1609
2019
  };
1610
2020
  const tell = (e) => {
1611
2021
  try {
1612
- options.onEvent?.(e);
2022
+ options.onEvent?.(e, frameInfo ?? { live: true });
1613
2023
  } catch {
1614
2024
  }
1615
2025
  };
@@ -1665,13 +2075,26 @@ var createRemoteAgentController = (options) => {
1665
2075
  }
1666
2076
  const raw = parsed?.event;
1667
2077
  if (!raw || typeof raw !== "object" || typeof raw.type !== "string") return;
2078
+ try {
2079
+ foldFrame(frame, raw);
2080
+ } finally {
2081
+ frameInfo = void 0;
2082
+ }
2083
+ };
2084
+ const foldFrame = (frame, raw) => {
1668
2085
  const cursor2 = parseRemoteCursor(frame.id);
2086
+ const info = () => ({
2087
+ live: turnIsOurs(),
2088
+ ...frame.id !== void 0 ? { id: frame.id } : {}
2089
+ });
2090
+ frameInfo = info();
1669
2091
  const attempt = cursor2?.attempt ?? 0;
1670
2092
  const shown = remoteEventOf(raw);
1671
2093
  if (raw.type === "turn.started") {
1672
2094
  const ids = Array.isArray(raw.messageIds) ? raw.messageIds.filter((x) => typeof x === "string") : [];
1673
2095
  waiting = waiting.filter((w) => !ids.includes(w.id));
1674
2096
  turnIds = ids;
2097
+ frameInfo = info();
1675
2098
  turnFinal = false;
1676
2099
  apply({ type: "status", status: "running" });
1677
2100
  turn = { number: cursor2?.turn ?? 0, start: state, entries: [] };
@@ -1840,9 +2263,11 @@ var createRemoteAgentController = (options) => {
1840
2263
  apply({ type: "status", status: "running" });
1841
2264
  apply({ type: "submitted", goal: shown });
1842
2265
  waiting.push({ id, text });
2266
+ sentHere.add(id);
1843
2267
  const ended = new Promise((resolve) => runs.set(id, resolve));
1844
2268
  try {
1845
- await sendMessage(id, text);
2269
+ const context = runOptions?.context === false ? void 0 : runOptions?.context ?? await pageContexts.collect({ ask: true });
2270
+ await sendMessage(id, text, context);
1846
2271
  } catch (err) {
1847
2272
  runs.delete(id);
1848
2273
  waiting = waiting.filter((w) => w.id !== id);
@@ -1854,11 +2279,12 @@ var createRemoteAgentController = (options) => {
1854
2279
  }
1855
2280
  return ended;
1856
2281
  };
1857
- const sendMessage = async (id, text) => {
2282
+ const sendMessage = async (id, text, context) => {
1858
2283
  const sid = sessionId;
2284
+ const withContext = context && Object.keys(context).length ? { context } : {};
1859
2285
  if (sid) {
1860
2286
  try {
1861
- await post(`/sessions/${encodeURIComponent(sid)}/messages`, { text, id });
2287
+ await post(`/sessions/${encodeURIComponent(sid)}/messages`, { text, id, ...withContext });
1862
2288
  return;
1863
2289
  } catch (err) {
1864
2290
  const gone = err instanceof GatewayError && (err.status === 404 || err.status === 409 && err.code === "session_ended");
@@ -1866,7 +2292,7 @@ var createRemoteAgentController = (options) => {
1866
2292
  forgetSession();
1867
2293
  }
1868
2294
  }
1869
- const made = await post("/sessions", { message: text, id });
2295
+ const made = await post("/sessions", { message: text, id, ...withContext });
1870
2296
  if (disposed) return;
1871
2297
  if (typeof made?.sessionId !== "string")
1872
2298
  throw new Error("the agent’s server started no session");
@@ -1877,19 +2303,23 @@ var createRemoteAgentController = (options) => {
1877
2303
  setSession(made.sessionId);
1878
2304
  void openStream();
1879
2305
  };
1880
- const send = (text) => {
2306
+ const send = (text, sendOptions) => {
1881
2307
  const clean = typeof text === "string" ? text.trim() : "";
1882
2308
  if (disposed || state.status !== "running" || !clean || !sessionId) return false;
1883
2309
  const id = newMessageId();
1884
2310
  waiting.push({ id, text: clean });
2311
+ sentHere.add(id);
1885
2312
  fold(event({ type: "message.queued", id, text: clean }));
1886
- void post(`/sessions/${encodeURIComponent(sessionId)}/messages`, { text: clean, id }).catch(
1887
- (err) => {
1888
- waiting = waiting.filter((w) => w.id !== id);
1889
- fold({ type: "undelivered", texts: [...state.undelivered, clean], keepQueued: true });
1890
- sayError(err);
1891
- }
1892
- );
2313
+ const context = sendOptions?.context === false ? void 0 : sendOptions?.context ?? withoutAskOnSend(pageContexts.preview());
2314
+ void post(`/sessions/${encodeURIComponent(sessionId)}/messages`, {
2315
+ text: clean,
2316
+ id,
2317
+ ...context && Object.keys(context).length ? { context } : {}
2318
+ }).catch((err) => {
2319
+ waiting = waiting.filter((w) => w.id !== id);
2320
+ fold({ type: "undelivered", texts: [...state.undelivered, clean], keepQueued: true });
2321
+ sayError(err);
2322
+ });
1893
2323
  return true;
1894
2324
  };
1895
2325
  const stop = () => {
@@ -1978,6 +2408,8 @@ var createRemoteAgentController = (options) => {
1978
2408
  stopRemote: () => {
1979
2409
  },
1980
2410
  send,
2411
+ previewPageContext: () => pageContexts.preview(),
2412
+ pageContextCollector: () => pageContexts,
1981
2413
  sendRemote: () => false,
1982
2414
  stopSubagent: () => false,
1983
2415
  forgetSkill: async () => false,
@@ -2039,6 +2471,7 @@ var createInitialAgentSnapshot = (config) => snapshotOf2(createInitialAgentState
2039
2471
  var createAgentController = (initialConfig, initialOptions = {}) => {
2040
2472
  let config = initialConfig;
2041
2473
  let options = initialOptions;
2474
+ const pageContexts = createPageContextCollector(() => options.pageContext);
2042
2475
  let disposed = false;
2043
2476
  let state = createInitialAgentState();
2044
2477
  let pendingQuestions = [];
@@ -2222,10 +2655,12 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2222
2655
  });
2223
2656
  }
2224
2657
  try {
2658
+ const context = runOptions?.context === false ? void 0 : runOptions?.context ?? await pageContexts.collect({ ask: true });
2225
2659
  const result = await current.run(goal, {
2226
2660
  signal: controller.signal,
2227
2661
  control: runControl,
2228
2662
  sessionId,
2663
+ ...context && Object.keys(context).length ? { context } : {},
2229
2664
  ...runOptions?.images?.length ? { images: runOptions.images } : {},
2230
2665
  ...runOptions?.files?.length ? { files: runOptions.files } : {},
2231
2666
  onEvent: (event) => {
@@ -2283,7 +2718,12 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2283
2718
  }
2284
2719
  }
2285
2720
  };
2286
- const send = (text) => control?.send(text) ?? false;
2721
+ const send = (text, sendOptions) => {
2722
+ if (!control) return false;
2723
+ const context = sendOptions?.context === false ? void 0 : sendOptions?.context ?? withoutAskOnSend(pageContexts.preview());
2724
+ return context && Object.keys(context).length ? control.send(text, { context }) : control.send(text);
2725
+ };
2726
+ const previewPageContext = () => pageContexts.preview();
2287
2727
  let remoteSends = 0;
2288
2728
  const sendRemote = (text) => {
2289
2729
  const current = watch;
@@ -2461,6 +2901,8 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2461
2901
  stop,
2462
2902
  stopRemote,
2463
2903
  send,
2904
+ previewPageContext,
2905
+ pageContextCollector: () => pageContexts,
2464
2906
  sendRemote,
2465
2907
  stopSubagent,
2466
2908
  forgetSkill,
@@ -2483,9 +2925,11 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2483
2925
  createAgentController,
2484
2926
  createInitialAgentSnapshot,
2485
2927
  createInitialRemoteSnapshot,
2928
+ createPageContextCollector,
2486
2929
  createRemoteAgentController,
2487
2930
  createSseParser,
2488
2931
  parseRemoteCursor,
2489
2932
  remoteEventOf,
2490
- remoteEventScope
2933
+ remoteEventScope,
2934
+ trackPageFocus
2491
2935
  });