@dudko.dev/agent-web-ui 0.0.6 → 0.0.8

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 (170) hide show
  1. package/README.md +52 -0
  2. package/dist/{chunk-NHU6WQM5.js → chunk-ETYLHTPK.js} +435 -1
  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 +452 -16
  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 +458 -4
  14. package/dist/index.d.cts +4 -3
  15. package/dist/index.d.ts +4 -3
  16. package/dist/index.js +37 -1
  17. package/dist/{labels-CCPL7t17.d.ts → labels-CeJMN8NU.d.ts} +9 -1
  18. package/dist/{labels-ipy-ydkp.d.cts → labels-D-NI4hKW.d.cts} +9 -1
  19. package/dist/locales/be.cjs +9 -0
  20. package/dist/locales/be.d.cts +2 -2
  21. package/dist/locales/be.d.ts +2 -2
  22. package/dist/locales/be.js +5 -1
  23. package/dist/locales/bg.cjs +9 -0
  24. package/dist/locales/bg.d.cts +2 -2
  25. package/dist/locales/bg.d.ts +2 -2
  26. package/dist/locales/bg.js +5 -1
  27. package/dist/locales/ca.cjs +9 -0
  28. package/dist/locales/ca.d.cts +2 -2
  29. package/dist/locales/ca.d.ts +2 -2
  30. package/dist/locales/ca.js +5 -1
  31. package/dist/locales/cs.cjs +9 -0
  32. package/dist/locales/cs.d.cts +2 -2
  33. package/dist/locales/cs.d.ts +2 -2
  34. package/dist/locales/cs.js +5 -1
  35. package/dist/locales/da.cjs +9 -0
  36. package/dist/locales/da.d.cts +2 -2
  37. package/dist/locales/da.d.ts +2 -2
  38. package/dist/locales/da.js +5 -1
  39. package/dist/locales/de.cjs +9 -0
  40. package/dist/locales/de.d.cts +2 -2
  41. package/dist/locales/de.d.ts +2 -2
  42. package/dist/locales/de.js +5 -1
  43. package/dist/locales/el.cjs +9 -0
  44. package/dist/locales/el.d.cts +2 -2
  45. package/dist/locales/el.d.ts +2 -2
  46. package/dist/locales/el.js +5 -1
  47. package/dist/locales/en.cjs +9 -0
  48. package/dist/locales/en.d.cts +2 -2
  49. package/dist/locales/en.d.ts +2 -2
  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 +2 -2
  53. package/dist/locales/es-419.d.ts +2 -2
  54. package/dist/locales/es-419.js +2 -2
  55. package/dist/locales/es.cjs +9 -0
  56. package/dist/locales/es.d.cts +2 -2
  57. package/dist/locales/es.d.ts +2 -2
  58. package/dist/locales/es.js +2 -2
  59. package/dist/locales/fi.cjs +9 -0
  60. package/dist/locales/fi.d.cts +2 -2
  61. package/dist/locales/fi.d.ts +2 -2
  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 +2 -2
  65. package/dist/locales/fr-CA.d.ts +2 -2
  66. package/dist/locales/fr-CA.js +2 -2
  67. package/dist/locales/fr.cjs +9 -0
  68. package/dist/locales/fr.d.cts +2 -2
  69. package/dist/locales/fr.d.ts +2 -2
  70. package/dist/locales/fr.js +2 -2
  71. package/dist/locales/gn.cjs +9 -0
  72. package/dist/locales/gn.d.cts +2 -2
  73. package/dist/locales/gn.d.ts +2 -2
  74. package/dist/locales/gn.js +5 -1
  75. package/dist/locales/hr.cjs +9 -0
  76. package/dist/locales/hr.d.cts +2 -2
  77. package/dist/locales/hr.d.ts +2 -2
  78. package/dist/locales/hr.js +5 -1
  79. package/dist/locales/ht.cjs +9 -0
  80. package/dist/locales/ht.d.cts +2 -2
  81. package/dist/locales/ht.d.ts +2 -2
  82. package/dist/locales/ht.js +5 -1
  83. package/dist/locales/hu.cjs +9 -0
  84. package/dist/locales/hu.d.cts +2 -2
  85. package/dist/locales/hu.d.ts +2 -2
  86. package/dist/locales/hu.js +5 -1
  87. package/dist/locales/index.cjs +5 -0
  88. package/dist/locales/index.d.cts +4 -4
  89. package/dist/locales/index.d.ts +4 -4
  90. package/dist/locales/index.js +1 -1
  91. package/dist/locales/it.cjs +9 -0
  92. package/dist/locales/it.d.cts +2 -2
  93. package/dist/locales/it.d.ts +2 -2
  94. package/dist/locales/it.js +5 -1
  95. package/dist/locales/nb.cjs +9 -0
  96. package/dist/locales/nb.d.cts +2 -2
  97. package/dist/locales/nb.d.ts +2 -2
  98. package/dist/locales/nb.js +5 -1
  99. package/dist/locales/nl.cjs +9 -0
  100. package/dist/locales/nl.d.cts +2 -2
  101. package/dist/locales/nl.d.ts +2 -2
  102. package/dist/locales/nl.js +5 -1
  103. package/dist/locales/pl.cjs +9 -0
  104. package/dist/locales/pl.d.cts +2 -2
  105. package/dist/locales/pl.d.ts +2 -2
  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 +2 -2
  109. package/dist/locales/pt-BR.d.ts +2 -2
  110. package/dist/locales/pt-BR.js +5 -1
  111. package/dist/locales/pt.cjs +9 -0
  112. package/dist/locales/pt.d.cts +2 -2
  113. package/dist/locales/pt.d.ts +2 -2
  114. package/dist/locales/pt.js +5 -1
  115. package/dist/locales/qu.cjs +9 -0
  116. package/dist/locales/qu.d.cts +2 -2
  117. package/dist/locales/qu.d.ts +2 -2
  118. package/dist/locales/qu.js +5 -1
  119. package/dist/locales/ro.cjs +9 -0
  120. package/dist/locales/ro.d.cts +2 -2
  121. package/dist/locales/ro.d.ts +2 -2
  122. package/dist/locales/ro.js +5 -1
  123. package/dist/locales/ru.cjs +9 -0
  124. package/dist/locales/ru.d.cts +2 -2
  125. package/dist/locales/ru.d.ts +2 -2
  126. package/dist/locales/ru.js +5 -1
  127. package/dist/locales/sk.cjs +9 -0
  128. package/dist/locales/sk.d.cts +2 -2
  129. package/dist/locales/sk.d.ts +2 -2
  130. package/dist/locales/sk.js +5 -1
  131. package/dist/locales/sq.cjs +9 -0
  132. package/dist/locales/sq.d.cts +2 -2
  133. package/dist/locales/sq.d.ts +2 -2
  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 +2 -2
  137. package/dist/locales/sr-Latn.d.ts +2 -2
  138. package/dist/locales/sr-Latn.js +2 -2
  139. package/dist/locales/sr.cjs +9 -0
  140. package/dist/locales/sr.d.cts +2 -2
  141. package/dist/locales/sr.d.ts +2 -2
  142. package/dist/locales/sr.js +2 -2
  143. package/dist/locales/sv.cjs +9 -0
  144. package/dist/locales/sv.d.cts +2 -2
  145. package/dist/locales/sv.d.ts +2 -2
  146. package/dist/locales/sv.js +5 -1
  147. package/dist/locales/tr.cjs +9 -0
  148. package/dist/locales/tr.d.cts +2 -2
  149. package/dist/locales/tr.d.ts +2 -2
  150. package/dist/locales/tr.js +5 -1
  151. package/dist/locales/uk.cjs +9 -0
  152. package/dist/locales/uk.d.cts +2 -2
  153. package/dist/locales/uk.d.ts +2 -2
  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/pipeline.cjs +1 -0
  162. package/dist/pipeline.d.cts +2 -0
  163. package/dist/pipeline.d.ts +2 -0
  164. package/dist/pipeline.js +1 -0
  165. package/dist/styles.css +59 -0
  166. package/dist/{types-CQquuZpl.d.cts → types-B5cyqkWY.d.cts} +1 -1
  167. package/dist/{types-CXZfZVP5.d.ts → types-BgNjWN5Z.d.ts} +1 -1
  168. package/dist/{types-DnBCok3z.d.ts → types-CHFtTZjl.d.cts} +6 -0
  169. package/dist/{types-DnBCok3z.d.cts → types-CHFtTZjl.d.ts} +6 -0
  170. 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();
@@ -297,6 +703,7 @@ var sentEntryOf = (queued, text) => queued.findIndex(
297
703
  (q) => q.sentTo === "another-tab" && (q.text === text || text.endsWith("…") && q.text.length > text.length && q.text.startsWith(text.slice(0, -1)))
298
704
  );
299
705
  var patchStep = (steps, id, fn) => steps.map((s) => s.id === id ? fn(s) : s);
706
+ var summaryOf = (summary) => typeof summary === "string" && summary.trim() ? { summary: summary.slice(0, 4e3) } : {};
300
707
  var withoutSkillBody = (a) => {
301
708
  if (!a.skill || a.skill.body === void 0) return a;
302
709
  const { body: _body, ...skill } = a.skill;
@@ -382,13 +789,20 @@ var answerQuestion = (state, event) => state.questions?.some((q) => q.id === eve
382
789
  } : state;
383
790
  var patchSubagent = (subagents, id, fn) => subagents.map((s) => s.id === id ? fn(s) : s);
384
791
  var runningStepId = (steps) => [...steps].reverse().find((s) => s.status === "running")?.id;
792
+ var stepPlace = (index, total) => {
793
+ const whole = (n) => typeof n === "number" && Number.isInteger(n);
794
+ if (whole(index) && whole(total) && index >= 1 && total >= index) return `${index}/${total}`;
795
+ if (whole(index) && index >= 0 && total === void 0) return String(index + 1);
796
+ if (whole(index) && index >= 1) return String(index);
797
+ return "?";
798
+ };
385
799
  var applySubagentEvent = (view, event) => {
386
800
  switch (event.type) {
387
801
  case "step.start":
388
802
  return {
389
803
  ...view,
390
804
  steps: view.steps + 1,
391
- activity: `step ${event.index}/${event.total}: ${event.step.description}`,
805
+ activity: `step ${stepPlace(event.index, event.total)}: ${event.step.description}`,
392
806
  // Known only when the child runs with model tiers.
393
807
  ...event.model !== void 0 ? { model: event.model } : {},
394
808
  ...event.tier !== void 0 ? { tier: event.tier } : {}
@@ -576,6 +990,7 @@ var applySubagent = (state, event, ancestors, ctx) => {
576
990
  },
577
991
  ...inner.skill ? { skill: inner.skill } : {},
578
992
  ...inner.rule ? { rule: inner.rule } : {},
993
+ ...summaryOf(inner.summary),
579
994
  ...ctx.remote ? { remote: true } : {},
580
995
  status: "pending"
581
996
  }
@@ -1111,6 +1526,7 @@ var applyEvent = (state, event, ctx) => {
1111
1526
  ...event.app ? { app: event.app } : {},
1112
1527
  ...event.skill ? { skill: event.skill } : {},
1113
1528
  ...event.rule ? { rule: event.rule } : {},
1529
+ ...summaryOf(event.summary),
1114
1530
  // Asked in the tab that runs the tool: shown here, answered there.
1115
1531
  ...ctx.remote ? { remote: true } : {},
1116
1532
  status: "pending"
@@ -1559,6 +1975,7 @@ var snapshotOf = (state, sessionId, answering) => Object.freeze({
1559
1975
  });
1560
1976
  var createRemoteAgentController = (options) => {
1561
1977
  const base = options.baseUrl.replace(/\/+$/, "");
1978
+ const pageContexts = createPageContextCollector(() => options.pageContext);
1562
1979
  const doFetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
1563
1980
  const minWait = Math.max(0, options.reconnect?.minMs ?? 1e3);
1564
1981
  const maxWait = Math.max(minWait, options.reconnect?.maxMs ?? 3e4);
@@ -1859,7 +2276,8 @@ var createRemoteAgentController = (options) => {
1859
2276
  sentHere.add(id);
1860
2277
  const ended = new Promise((resolve) => runs.set(id, resolve));
1861
2278
  try {
1862
- await sendMessage(id, text);
2279
+ const context = runOptions?.context === false ? void 0 : runOptions?.context ?? await pageContexts.collect({ ask: true });
2280
+ await sendMessage(id, text, context);
1863
2281
  } catch (err) {
1864
2282
  runs.delete(id);
1865
2283
  waiting = waiting.filter((w) => w.id !== id);
@@ -1871,11 +2289,12 @@ var createRemoteAgentController = (options) => {
1871
2289
  }
1872
2290
  return ended;
1873
2291
  };
1874
- const sendMessage = async (id, text) => {
2292
+ const sendMessage = async (id, text, context) => {
1875
2293
  const sid = sessionId;
2294
+ const withContext = context && Object.keys(context).length ? { context } : {};
1876
2295
  if (sid) {
1877
2296
  try {
1878
- await post(`/sessions/${encodeURIComponent(sid)}/messages`, { text, id });
2297
+ await post(`/sessions/${encodeURIComponent(sid)}/messages`, { text, id, ...withContext });
1879
2298
  return;
1880
2299
  } catch (err) {
1881
2300
  const gone = err instanceof GatewayError && (err.status === 404 || err.status === 409 && err.code === "session_ended");
@@ -1883,7 +2302,7 @@ var createRemoteAgentController = (options) => {
1883
2302
  forgetSession();
1884
2303
  }
1885
2304
  }
1886
- const made = await post("/sessions", { message: text, id });
2305
+ const made = await post("/sessions", { message: text, id, ...withContext });
1887
2306
  if (disposed) return;
1888
2307
  if (typeof made?.sessionId !== "string")
1889
2308
  throw new Error("the agent’s server started no session");
@@ -1894,20 +2313,23 @@ var createRemoteAgentController = (options) => {
1894
2313
  setSession(made.sessionId);
1895
2314
  void openStream();
1896
2315
  };
1897
- const send = (text) => {
2316
+ const send = (text, sendOptions) => {
1898
2317
  const clean = typeof text === "string" ? text.trim() : "";
1899
2318
  if (disposed || state.status !== "running" || !clean || !sessionId) return false;
1900
2319
  const id = newMessageId();
1901
2320
  waiting.push({ id, text: clean });
1902
2321
  sentHere.add(id);
1903
2322
  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
- );
2323
+ const context = sendOptions?.context === false ? void 0 : sendOptions?.context ?? withoutAskOnSend(pageContexts.preview());
2324
+ void post(`/sessions/${encodeURIComponent(sessionId)}/messages`, {
2325
+ text: clean,
2326
+ id,
2327
+ ...context && Object.keys(context).length ? { context } : {}
2328
+ }).catch((err) => {
2329
+ waiting = waiting.filter((w) => w.id !== id);
2330
+ fold({ type: "undelivered", texts: [...state.undelivered, clean], keepQueued: true });
2331
+ sayError(err);
2332
+ });
1911
2333
  return true;
1912
2334
  };
1913
2335
  const stop = () => {
@@ -1996,6 +2418,8 @@ var createRemoteAgentController = (options) => {
1996
2418
  stopRemote: () => {
1997
2419
  },
1998
2420
  send,
2421
+ previewPageContext: () => pageContexts.preview(),
2422
+ pageContextCollector: () => pageContexts,
1999
2423
  sendRemote: () => false,
2000
2424
  stopSubagent: () => false,
2001
2425
  forgetSkill: async () => false,
@@ -2057,6 +2481,7 @@ var createInitialAgentSnapshot = (config) => snapshotOf2(createInitialAgentState
2057
2481
  var createAgentController = (initialConfig, initialOptions = {}) => {
2058
2482
  let config = initialConfig;
2059
2483
  let options = initialOptions;
2484
+ const pageContexts = createPageContextCollector(() => options.pageContext);
2060
2485
  let disposed = false;
2061
2486
  let state = createInitialAgentState();
2062
2487
  let pendingQuestions = [];
@@ -2240,10 +2665,12 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2240
2665
  });
2241
2666
  }
2242
2667
  try {
2668
+ const context = runOptions?.context === false ? void 0 : runOptions?.context ?? await pageContexts.collect({ ask: true });
2243
2669
  const result = await current.run(goal, {
2244
2670
  signal: controller.signal,
2245
2671
  control: runControl,
2246
2672
  sessionId,
2673
+ ...context && Object.keys(context).length ? { context } : {},
2247
2674
  ...runOptions?.images?.length ? { images: runOptions.images } : {},
2248
2675
  ...runOptions?.files?.length ? { files: runOptions.files } : {},
2249
2676
  onEvent: (event) => {
@@ -2301,7 +2728,12 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2301
2728
  }
2302
2729
  }
2303
2730
  };
2304
- const send = (text) => control?.send(text) ?? false;
2731
+ const send = (text, sendOptions) => {
2732
+ if (!control) return false;
2733
+ const context = sendOptions?.context === false ? void 0 : sendOptions?.context ?? withoutAskOnSend(pageContexts.preview());
2734
+ return context && Object.keys(context).length ? control.send(text, { context }) : control.send(text);
2735
+ };
2736
+ const previewPageContext = () => pageContexts.preview();
2305
2737
  let remoteSends = 0;
2306
2738
  const sendRemote = (text) => {
2307
2739
  const current = watch;
@@ -2479,6 +2911,8 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2479
2911
  stop,
2480
2912
  stopRemote,
2481
2913
  send,
2914
+ previewPageContext,
2915
+ pageContextCollector: () => pageContexts,
2482
2916
  sendRemote,
2483
2917
  stopSubagent,
2484
2918
  forgetSkill,
@@ -2501,9 +2935,11 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2501
2935
  createAgentController,
2502
2936
  createInitialAgentSnapshot,
2503
2937
  createInitialRemoteSnapshot,
2938
+ createPageContextCollector,
2504
2939
  createRemoteAgentController,
2505
2940
  createSseParser,
2506
2941
  parseRemoteCursor,
2507
2942
  remoteEventOf,
2508
- remoteEventScope
2943
+ remoteEventScope,
2944
+ trackPageFocus
2509
2945
  });
@@ -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 };