@dudko.dev/agent-web-ui 0.0.6 → 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 +52 -0
  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 +441 -15
  8. package/dist/controller.d.cts +39 -3
  9. package/dist/controller.d.ts +39 -3
  10. package/dist/controller.js +39 -16
  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);
@@ -1859,7 +2266,8 @@ var createRemoteAgentController = (options) => {
1859
2266
  sentHere.add(id);
1860
2267
  const ended = new Promise((resolve) => runs.set(id, resolve));
1861
2268
  try {
1862
- 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);
1863
2271
  } catch (err) {
1864
2272
  runs.delete(id);
1865
2273
  waiting = waiting.filter((w) => w.id !== id);
@@ -1871,11 +2279,12 @@ var createRemoteAgentController = (options) => {
1871
2279
  }
1872
2280
  return ended;
1873
2281
  };
1874
- const sendMessage = async (id, text) => {
2282
+ const sendMessage = async (id, text, context) => {
1875
2283
  const sid = sessionId;
2284
+ const withContext = context && Object.keys(context).length ? { context } : {};
1876
2285
  if (sid) {
1877
2286
  try {
1878
- await post(`/sessions/${encodeURIComponent(sid)}/messages`, { text, id });
2287
+ await post(`/sessions/${encodeURIComponent(sid)}/messages`, { text, id, ...withContext });
1879
2288
  return;
1880
2289
  } catch (err) {
1881
2290
  const gone = err instanceof GatewayError && (err.status === 404 || err.status === 409 && err.code === "session_ended");
@@ -1883,7 +2292,7 @@ var createRemoteAgentController = (options) => {
1883
2292
  forgetSession();
1884
2293
  }
1885
2294
  }
1886
- const made = await post("/sessions", { message: text, id });
2295
+ const made = await post("/sessions", { message: text, id, ...withContext });
1887
2296
  if (disposed) return;
1888
2297
  if (typeof made?.sessionId !== "string")
1889
2298
  throw new Error("the agent’s server started no session");
@@ -1894,20 +2303,23 @@ var createRemoteAgentController = (options) => {
1894
2303
  setSession(made.sessionId);
1895
2304
  void openStream();
1896
2305
  };
1897
- const send = (text) => {
2306
+ const send = (text, sendOptions) => {
1898
2307
  const clean = typeof text === "string" ? text.trim() : "";
1899
2308
  if (disposed || state.status !== "running" || !clean || !sessionId) return false;
1900
2309
  const id = newMessageId();
1901
2310
  waiting.push({ id, text: clean });
1902
2311
  sentHere.add(id);
1903
2312
  fold(event({ type: "message.queued", id, text: clean }));
1904
- void post(`/sessions/${encodeURIComponent(sessionId)}/messages`, { text: clean, id }).catch(
1905
- (err) => {
1906
- waiting = waiting.filter((w) => w.id !== id);
1907
- fold({ type: "undelivered", texts: [...state.undelivered, clean], keepQueued: true });
1908
- sayError(err);
1909
- }
1910
- );
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
+ });
1911
2323
  return true;
1912
2324
  };
1913
2325
  const stop = () => {
@@ -1996,6 +2408,8 @@ var createRemoteAgentController = (options) => {
1996
2408
  stopRemote: () => {
1997
2409
  },
1998
2410
  send,
2411
+ previewPageContext: () => pageContexts.preview(),
2412
+ pageContextCollector: () => pageContexts,
1999
2413
  sendRemote: () => false,
2000
2414
  stopSubagent: () => false,
2001
2415
  forgetSkill: async () => false,
@@ -2057,6 +2471,7 @@ var createInitialAgentSnapshot = (config) => snapshotOf2(createInitialAgentState
2057
2471
  var createAgentController = (initialConfig, initialOptions = {}) => {
2058
2472
  let config = initialConfig;
2059
2473
  let options = initialOptions;
2474
+ const pageContexts = createPageContextCollector(() => options.pageContext);
2060
2475
  let disposed = false;
2061
2476
  let state = createInitialAgentState();
2062
2477
  let pendingQuestions = [];
@@ -2240,10 +2655,12 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2240
2655
  });
2241
2656
  }
2242
2657
  try {
2658
+ const context = runOptions?.context === false ? void 0 : runOptions?.context ?? await pageContexts.collect({ ask: true });
2243
2659
  const result = await current.run(goal, {
2244
2660
  signal: controller.signal,
2245
2661
  control: runControl,
2246
2662
  sessionId,
2663
+ ...context && Object.keys(context).length ? { context } : {},
2247
2664
  ...runOptions?.images?.length ? { images: runOptions.images } : {},
2248
2665
  ...runOptions?.files?.length ? { files: runOptions.files } : {},
2249
2666
  onEvent: (event) => {
@@ -2301,7 +2718,12 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2301
2718
  }
2302
2719
  }
2303
2720
  };
2304
- 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();
2305
2727
  let remoteSends = 0;
2306
2728
  const sendRemote = (text) => {
2307
2729
  const current = watch;
@@ -2479,6 +2901,8 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2479
2901
  stop,
2480
2902
  stopRemote,
2481
2903
  send,
2904
+ previewPageContext,
2905
+ pageContextCollector: () => pageContexts,
2482
2906
  sendRemote,
2483
2907
  stopSubagent,
2484
2908
  forgetSkill,
@@ -2501,9 +2925,11 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2501
2925
  createAgentController,
2502
2926
  createInitialAgentSnapshot,
2503
2927
  createInitialRemoteSnapshot,
2928
+ createPageContextCollector,
2504
2929
  createRemoteAgentController,
2505
2930
  createSseParser,
2506
2931
  parseRemoteCursor,
2507
2932
  remoteEventOf,
2508
- remoteEventScope
2933
+ remoteEventScope,
2934
+ trackPageFocus
2509
2935
  });
@@ -1,3 +1,5 @@
1
+ import { P as PageContextOptions, a as PageContext, b as PageContextCollector } from './page-context-BAmw4p6d.cjs';
2
+ export { c as createPageContextCollector, t as trackPageFocus } from './page-context-BAmw4p6d.cjs';
1
3
  import { AgentEvent, RunFile, RunResult, AskUserAnswer, ToolApprovalMode, AppToolCallRequest, AppSamplingRequest, AppSamplingView, AppSamplingResult, CompactResult, IUsage, BrowserAgentConfig, AgentEventHandler, Agent } from '@dudko.dev/agent-web';
2
4
  import { PendingQuestion } from './index.cjs';
3
5
  import { ChatAttachment, ChatMessage, AgentUiState, ApprovalView } from './index.cjs';
@@ -49,6 +51,12 @@ interface RemoteAgentOptions {
49
51
  minMs?: number;
50
52
  maxMs?: number;
51
53
  };
54
+ /**
55
+ * What the person is looking at, read at send time and POSTed with each message as `context`
56
+ * (ALL collectors off by default: nothing is sent without them). The gateway keeps only the
57
+ * keys its operator allows (`contextKeys`) and checks them; see `page-context.ts`.
58
+ */
59
+ pageContext?: PageContextOptions;
52
60
  }
53
61
  /**
54
62
  * What `onEvent` is told with an event. `live`: the event belongs to a turn that a message sent
@@ -169,6 +177,13 @@ interface AgentControllerOptions {
169
177
  * stopping it is explicit: `sendRemote` / `stopRemote`. Consent requests stay in that tab.
170
178
  */
171
179
  watch?: boolean;
180
+ /**
181
+ * What the person is looking at, read at SEND time and passed with each message (the core's
182
+ * `run(goal, { context })` / `control.send(text, { context })`): which collectors (ALL off by
183
+ * default), the host's `extra`, `include` / `exclude`, `maxChars`. See `page-context.ts` and the
184
+ * React package's docs/chat.md, "Page context". Untrusted data for the agent, never policy.
185
+ */
186
+ pageContext?: PageContextOptions;
172
187
  }
173
188
  interface ApproveOptions {
174
189
  /** Also allow this tool for the rest of the agent's life ("always allow"). */
@@ -187,6 +202,16 @@ interface RunGoalOptions {
187
202
  files?: RunFile[];
188
203
  /** What the transcript shows as attached to this turn (thumbnails, chips). */
189
204
  attachments?: ChatAttachment[];
205
+ /**
206
+ * The page context for this message: given (the composer collected it), `false` (the person
207
+ * turned sharing off for this message), or absent - collected now from `options.pageContext`.
208
+ */
209
+ context?: PageContext | false;
210
+ }
211
+ /** `send`'s options. */
212
+ interface SendOptions {
213
+ /** As `RunGoalOptions.context`; absent = collected now (the location only if already known). */
214
+ context?: PageContext | false;
190
215
  }
191
216
  /**
192
217
  * A tool call an MCP App asks for, as `approveAppToolCall` takes it: the core's request, plus
@@ -262,7 +287,18 @@ interface AgentControllerActions {
262
287
  * flight or the text is empty — then use `run`. Watch `queued` / `notes`. Only this tab's run:
263
288
  * for the conversation's run in another tab, `sendRemote`.
264
289
  */
265
- send: (text: string) => boolean;
290
+ send: (text: string, options?: SendOptions) => boolean;
291
+ /**
292
+ * What the next message would share (`options.pageContext`), read now without asking anything:
293
+ * for the composer's chip. A location not known yet is `PAGE_CONTEXT_ASK_ON_SEND`. `undefined`
294
+ * when the host shares nothing.
295
+ */
296
+ previewPageContext: () => PageContext | undefined;
297
+ /**
298
+ * The controller's page-context collector (`options.pageContext`): a chat gives it a focus
299
+ * tracker (`setTracker(trackPageFocus(...))`) so the focus and selection are read outside it.
300
+ */
301
+ pageContextCollector: () => PageContextCollector;
266
302
  /** Stop ONE running subagent (`SubagentView.id`); the run and its siblings go on. */
267
303
  stopSubagent: (id: string) => boolean;
268
304
  /**
@@ -368,5 +404,5 @@ declare const createInitialAgentSnapshot: (config: BrowserAgentConfig) => AgentC
368
404
  */
369
405
  declare const createAgentController: (initialConfig: BrowserAgentConfig, initialOptions?: AgentControllerOptions) => AgentController;
370
406
 
371
- export { createAgentController, createInitialAgentSnapshot, createInitialRemoteSnapshot, createRemoteAgentController, createSseParser, parseRemoteCursor, remoteEventOf, remoteEventScope };
372
- export type { AgentController, AgentControllerActions, AgentControllerOptions, AgentControllerSnapshot, AgentControllerUpdate, AppToolCall, ApproveOptions, RemoteAgentHeaders, RemoteAgentOptions, RemoteEventInfo, RemoteFrame, RunGoalOptions };
407
+ export { PageContext, PageContextCollector, PageContextOptions, createAgentController, createInitialAgentSnapshot, createInitialRemoteSnapshot, createRemoteAgentController, createSseParser, parseRemoteCursor, remoteEventOf, remoteEventScope };
408
+ export type { AgentController, AgentControllerActions, AgentControllerOptions, AgentControllerSnapshot, AgentControllerUpdate, AppToolCall, ApproveOptions, RemoteAgentHeaders, RemoteAgentOptions, RemoteEventInfo, RemoteFrame, RunGoalOptions, SendOptions };