@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
package/README.md CHANGED
@@ -76,6 +76,7 @@ not install this package itself: `@dudko.dev/agent-web-react` depends on it.
76
76
  | `@dudko.dev/agent-web-ui/mcp-app` | MCP Apps on the page's side: the frame's policy and shell, the bridge, the link to a sandbox page, an app's requests | nothing |
77
77
  | `@dudko.dev/agent-web-ui/mcp-app-sandbox` | the MCP Apps sandbox page for a SERVER (a Worker, Node, Deno, Bun): the page, its headers, a `Request` → `Response` handler | nothing |
78
78
  | `@dudko.dev/agent-web-ui/pipeline` | the pipeline editor's logic: the reducer of a pipeline run, the editing helpers, the code generator, the editor's strings | the core |
79
+ | `@dudko.dev/agent-web-ui/pipeline-format` | the pipeline DEFINITION format an editor writes and an executor reads: its types, the validator (refuses secret values), references by name, the JSON Schema, the converters to and from the engine's definition (see [The pipeline definition format](#the-pipeline-definition-format)) | nothing |
79
80
  | `@dudko.dev/agent-web-ui/canvas` | the generic canvas's maths (viewport, curves, hit tests, layout order) and its strings | nothing |
80
81
  | `@dudko.dev/agent-web-ui/controller` | the agent as a store any front end wraps: `createAgentController`, and `createRemoteAgentController` for an agent on a server (see [Controller](#controller)) | the core, dynamically, when an agent is built in the page |
81
82
  | `@dudko.dev/agent-web-ui/markdown` | the answers' Markdown as a tree any front end draws: the parser, the parser of an answer still being written, `safeHref`, the link allowlist, the renderer's helpers (see [Markdown](#markdown)) | nothing |
@@ -108,7 +109,7 @@ the core's own by the tests. The rest goes through
108
109
  controller when it builds an agent (`createAgent`, the run's control, another tab's run), the
109
110
  chat history when it announces a write, `followOtherTabs` / `listenToOtherTabs` when there is a
110
111
  database to follow (pass `loadAgentCore` instead of the core's module: the follow starts once it
111
- resolves). `agentCoreIfLoaded()` answers without importing.
112
+ resolves). `agentCoreIfLoaded()` answers without importing; `AgentCoreModule` is the module's type.
112
113
 
113
114
  So a chat whose agent is on a server (`createRemoteAgentController`, the element's `backend`)
114
115
  never loads the core: the support chat of agent.dudko.dev went from 1.35 MB (399 KB gzip) to
@@ -228,6 +229,20 @@ const chat = createRemoteAgentController({
228
229
  })
229
230
  ```
230
231
 
232
+ The options (`RemoteAgentOptions`):
233
+
234
+ | Option | What |
235
+ | --- | --- |
236
+ | `baseUrl` | The gateway's base URL (required) |
237
+ | `sessionId` | A session to continue (below) |
238
+ | `headers` | Headers for every request: an object, or a function called before each one, async allowed (`RemoteAgentHeaders`) - a visitor token, a captcha token while there is no session yet |
239
+ | `credentials` | `fetch`'s `credentials` (default `'same-origin'`; `'include'` sends a cookie cross-site - the gateway's anonymous visitor cookie) |
240
+ | `fetch` | The `fetch` to use (default the global one) |
241
+ | `onSessionId` | Told every change of the session (started, forgotten, `reset()`) |
242
+ | `onEvent` | Every event folded, the swarm's `turn.started` / `turn.ended` markers as they came (a `tool.approval-resolved` that only says the turn parked is not told) |
243
+ | `maxEvents` | The raw event log kept in the snapshot (default 200; 0 = unbounded) |
244
+ | `reconnect` | `{ minMs, maxMs }`: the stream's reconnect backoff (default 1 s, doubled up to 30 s) |
245
+
231
246
  - `run(text)` - the first message `POST /sessions`, the next ones `POST /sessions/:id/messages`
232
247
  (each with an id: a retried POST is harmless); shown at once, its turn takes its place. Resolves
233
248
  with the turn's result, `undefined` when it failed (the error said, the words back in
@@ -251,12 +266,75 @@ const chat = createRemoteAgentController({
251
266
  `approveAppToolCall` / `sampleForApp` (throw), `setApprovalMode`, `stopRemote`, `update` (do
252
267
  nothing). `reset()` forgets the session; `loadChat({ sessionId })` opens another; `reload()` opens
253
268
  the stream again now. `dispose()` closes the stream and clears the reconnect timer.
254
- - `createInitialRemoteSnapshot({ sessionId })` is its snapshot before one exists. `createSseParser`,
255
- `parseRemoteCursor`, `remoteEventScope` and `remoteEventOf` are its pure parts.
269
+ - `onEvent(event, { live, id })` - every event as the reducer took it. `live` is true only for a
270
+ turn that a message sent through THIS controller started, as it happens: never for the replay of
271
+ a session's log (a reload, `loadChat`, a `sessionId` given) nor for a turn another tab or client
272
+ started on the same session - so a host can act on what its own message caused (open a page the
273
+ agent named, say) without acting again on every reload. `id` is the event's cursor on the
274
+ stream (`<turn>:<attempt>:<seq>`); the controller's own events (a request that failed) are live,
275
+ without an id.
276
+ - `createInitialRemoteSnapshot({ sessionId })` is its snapshot before one exists. `createSseParser`
277
+ (SSE text, fed chunk by chunk, to `RemoteFrame`s - `id`, `data` - and `retry:`), `parseRemoteCursor`
278
+ (`<turn>:<attempt>:<seq>`), `remoteEventScope` and `remoteEventOf` (a Node core event to the
279
+ shape the reducer folds) are its pure parts.
280
+ - **Nothing of the core is loaded** for it: the `./controller` entry takes the core only through
281
+ `loadAgentCore()`, which this controller never calls - see
282
+ [The core, loaded when needed](#the-core-loaded-when-needed).
256
283
 
257
284
  The React package's `useRemoteAgent` / `<RemoteAgentProvider>` and the element's `backend`
258
285
  attribute are this controller.
259
286
 
287
+ ## The pipeline definition format
288
+
289
+ `@dudko.dev/agent-web-ui/pipeline-format` is the JSON a pipeline is STORED and SHARED as: what an
290
+ editor saves and an executor (a server that runs pipelines, such as
291
+ [`examples/pipelines`](https://github.com/dudko-dev/agents/tree/main/examples/pipelines)) reads. It
292
+ wraps the engine's definition - the `PipelineDefinition` of both cores, which stays the source of
293
+ truth for execution, and what the React package's `PipelineEditor` edits - with what a stored
294
+ document needs: a format and a schema version, a stable `name`, required edge ids, and the names of
295
+ the secrets a node may use. It imports nothing, so the same module runs in a page, a Worker and
296
+ Node.
297
+
298
+ ```ts
299
+ import {
300
+ validatePipelineDocument,
301
+ documentToDefinition,
302
+ definitionToDocument,
303
+ unresolvedReferences,
304
+ pipelineDocumentJsonSchema,
305
+ } from '@dudko.dev/agent-web-ui/pipeline-format'
306
+
307
+ const v = validatePipelineDocument(json) // every issue at once: { path: '/nodes/0/id', code, message }
308
+ if (v.ok) {
309
+ const definition = documentToDefinition(v.document) // what the engine runs / the editor edits
310
+ const missing = unresolvedReferences(v.document, { tools: ['word_count'], models: () => true })
311
+ }
312
+ const doc = definitionToDocument(editedDefinition, { base: loadedDocument }) // an editor's save
313
+ ```
314
+
315
+ - `format: "agent-pipeline"`, `schemaVersion: 1` - a newer version is refused, never guessed at.
316
+ - **Conditions are data** (`always`, `contains`, `matches`, `route`, `otherwise`), as the engine's.
317
+ - **References by name only**: `model`, `tools`, `mcpServers`, `skills`, `secrets` per node, and
318
+ `{ "$secret": "NAME" }` anywhere in a node's `settings`. `pipelineReferences` lists them with
319
+ their paths; `unresolvedReferences(doc, resolvers)` says which an executor cannot resolve (a
320
+ kind the resolvers do not mention resolves nothing).
321
+ - **No secret values**: a string that looks like a key or a token (`secretKindOf`: provider key
322
+ shapes, private keys, JWTs, bearer and basic credentials, `password=...`, long random runs) and
323
+ any value under a secret-sounding settings key (`apiKey`, `token`, `password`, ...) is an issue
324
+ (`secret_value`) - which names the kind, never the value. The scan is linear and bounded.
325
+ - `pipelineDocumentJsonSchema` (draft 2020-12, `$id` `urn:dudko-dev:agent-pipeline:1`) describes
326
+ the shape for other tools; the validator is the full check. The engine's own rules (the
327
+ `otherwise` rule, a pattern's size, ...) are the core's `validatePipeline`, run on
328
+ `documentToDefinition(doc)`.
329
+ - `definitionToDocument(def, { base })` keeps from the loaded document what the engine has no field
330
+ for (the name, the description, each node's secrets); `documentToDefinition` copies only what the
331
+ engine reads. A document round-trips through both unchanged.
332
+ - `pipelineDocumentsEqual(a, b)` is an editor's "unsaved changes" check: the same pipeline whatever
333
+ the order of keys, a `title` equal to the `name` or an edge's default id
334
+ (`canonicalPipelineDocument(doc)` is the document as an editor would save it back). Compare with
335
+ it, not with `JSON.stringify` - a version stored by hand or by another tool would always look
336
+ changed.
337
+
260
338
  ## Labels
261
339
 
262
340
  `defaultLabels` is every string the chat shows; counted phrases are functions so that languages
@@ -1362,6 +1362,414 @@ var agentStateReducer = (state, action) => {
1362
1362
  }
1363
1363
  };
1364
1364
 
1365
+ // src/page-context.ts
1366
+ var PAGE_CONTEXT_VALUE_MAX = 500;
1367
+ var PAGE_CONTEXT_SELECTION_MAX = 500;
1368
+ var PAGE_CONTEXT_MAX_CHARS = 2e3;
1369
+ var HEADINGS_MAX = 8;
1370
+ var CLIP = "…";
1371
+ var clip = (text, max) => text.length > max ? `${text.slice(0, Math.max(0, max - 1))}${CLIP}` : text;
1372
+ var oneLine = (text) => text.replace(/\s+/g, " ").trim();
1373
+ var pageEnv = () => {
1374
+ const g = globalThis;
1375
+ if (typeof g.window === "undefined") return {};
1376
+ const w = g;
1377
+ return {
1378
+ location: w.location,
1379
+ document: w.document,
1380
+ getSelection: () => w.getSelection?.() ?? null,
1381
+ innerWidth: w.innerWidth,
1382
+ innerHeight: w.innerHeight,
1383
+ scrollY: w.scrollY,
1384
+ matchMedia: (q) => w.matchMedia(q),
1385
+ ...g.navigator?.geolocation ? { geolocation: g.navigator.geolocation } : {},
1386
+ now: () => Date.now(),
1387
+ timeZone: () => Intl.DateTimeFormat().resolvedOptions().timeZone,
1388
+ screenWidth: g.screen?.width ?? w.innerWidth
1389
+ };
1390
+ };
1391
+ var pageContextOff = (options) => !options || !options.extra && !Object.values(options.collect ?? {}).some((v) => v !== false && v != null);
1392
+ var addressWithoutQuery = (href) => {
1393
+ try {
1394
+ const u = new URL(href);
1395
+ if (u.protocol !== "http:" && u.protocol !== "https:") return void 0;
1396
+ return `${u.origin}${u.pathname}`;
1397
+ } catch {
1398
+ return void 0;
1399
+ }
1400
+ };
1401
+ var autocompleteTokens = (el) => (el.getAttribute("autocomplete") ?? "").toLowerCase().split(/\s+/).filter(Boolean);
1402
+ var isSecretField = (el) => {
1403
+ const type = (el.type ?? el.getAttribute("type") ?? "").toLowerCase();
1404
+ if (type === "password" || type === "hidden") return true;
1405
+ return autocompleteTokens(el).some(
1406
+ (t) => t.startsWith("cc-") || t === "one-time-code" || t === "current-password" || t === "new-password"
1407
+ );
1408
+ };
1409
+ var IMPLICIT_ROLE = {
1410
+ a: "link",
1411
+ button: "button",
1412
+ textarea: "textbox",
1413
+ select: "combobox",
1414
+ h1: "heading",
1415
+ h2: "heading",
1416
+ h3: "heading",
1417
+ summary: "button"
1418
+ };
1419
+ var roleOf = (el) => {
1420
+ const explicit = el.getAttribute("role");
1421
+ if (explicit) return explicit.split(/\s+/)[0];
1422
+ const tag = el.tagName.toLowerCase();
1423
+ if (tag === "input") {
1424
+ const type = (el.type ?? el.getAttribute("type") ?? "text").toLowerCase();
1425
+ if (type === "checkbox") return "checkbox";
1426
+ if (type === "radio") return "radio";
1427
+ if (type === "button" || type === "submit" || type === "reset") return "button";
1428
+ if (type === "range") return "slider";
1429
+ if (type === "search") return "searchbox";
1430
+ return "textbox";
1431
+ }
1432
+ if (tag !== "textarea" && tag !== "select" && isEditableElement(el)) return "textbox";
1433
+ return IMPLICIT_ROLE[tag] ?? tag;
1434
+ };
1435
+ var EDITABLE_ROLES = /* @__PURE__ */ new Set(["textbox", "searchbox", "combobox", "spinbutton"]);
1436
+ var isEditableElement = (el) => {
1437
+ const tag = el.tagName.toLowerCase();
1438
+ if (tag === "input" || tag === "textarea" || tag === "select") return true;
1439
+ if (el.isContentEditable === true) return true;
1440
+ const ce = el.getAttribute("contenteditable");
1441
+ if (ce !== null && ce.toLowerCase() !== "false") return true;
1442
+ const role = (el.getAttribute("role") ?? "").toLowerCase().split(/\s+/)[0] ?? "";
1443
+ return EDITABLE_ROLES.has(role);
1444
+ };
1445
+ var nameOf = (el, env) => {
1446
+ const aria = el.getAttribute("aria-label");
1447
+ if (aria) return aria;
1448
+ const by = el.getAttribute("aria-labelledby");
1449
+ if (by) {
1450
+ const text = by.split(/\s+/).map((id) => env.document?.getElementById?.(id)?.textContent ?? "").join(" ");
1451
+ if (text.trim()) return text;
1452
+ }
1453
+ const label = el.labels && el.labels.length ? el.labels[0]?.textContent ?? "" : "";
1454
+ if (label.trim()) return label;
1455
+ const placeholder = el.getAttribute("placeholder") ?? el.getAttribute("title");
1456
+ if (placeholder) return placeholder;
1457
+ return isEditableElement(el) ? "" : el.textContent ?? "";
1458
+ };
1459
+ var focusEntries = (env, includeValues) => {
1460
+ const el = env.document?.activeElement;
1461
+ if (!el) return {};
1462
+ const tag = el.tagName.toLowerCase();
1463
+ if (tag === "body" || tag === "html") return {};
1464
+ const out = { "focus.role": roleOf(el) };
1465
+ const name = clip(oneLine(nameOf(el, env)), 120);
1466
+ if (name) out["focus.label"] = name;
1467
+ out["focus.type"] = tag === "input" ? `input:${(el.type ?? "text").toLowerCase()}` : tag;
1468
+ if (includeValues && isEditableElement(el) && !isSecretField(el)) {
1469
+ const isControl = tag === "input" || tag === "textarea" || tag === "select";
1470
+ const raw = isControl ? el.value : el.textContent;
1471
+ const value = typeof raw === "string" ? raw.trim() : "";
1472
+ if (value) out["focus.value"] = clip(value, PAGE_CONTEXT_VALUE_MAX);
1473
+ }
1474
+ return out;
1475
+ };
1476
+ var headingsInView = (env) => {
1477
+ const all = env.document?.querySelectorAll?.("h1, h2, h3");
1478
+ if (!all) return void 0;
1479
+ const height = env.innerHeight ?? Infinity;
1480
+ const shown = [];
1481
+ for (let i = 0; i < all.length && shown.length < HEADINGS_MAX; i++) {
1482
+ const h = all[i];
1483
+ const box = h.getBoundingClientRect?.();
1484
+ if (box && (box.bottom < 0 || box.top > height)) continue;
1485
+ const text = clip(oneLine(h.textContent ?? ""), 120);
1486
+ if (text) shown.push(text);
1487
+ }
1488
+ return shown.length ? clip(shown.join(" / "), PAGE_CONTEXT_VALUE_MAX) : void 0;
1489
+ };
1490
+ var roundCoordinate = (value, precision) => {
1491
+ const p = Math.min(6, Math.max(0, Math.floor(precision)));
1492
+ const f = 10 ** p;
1493
+ return Math.round(value * f) / f;
1494
+ };
1495
+ var localIso = (ms) => {
1496
+ const d = new Date(ms);
1497
+ const pad = (n) => String(Math.abs(n)).padStart(2, "0");
1498
+ const off = -d.getTimezoneOffset();
1499
+ const sign = off >= 0 ? "+" : "-";
1500
+ 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)}`;
1501
+ };
1502
+ var capPageContext = (context, max) => {
1503
+ let left = max;
1504
+ const out = {};
1505
+ for (const [k, v] of Object.entries(context)) {
1506
+ const text = v === null ? "" : String(v);
1507
+ const room = left - k.length - 2;
1508
+ if (room <= 0) break;
1509
+ if (typeof v === "string" && text.length > room) {
1510
+ if (room < 8) break;
1511
+ out[k] = clip(text, room);
1512
+ left = 0;
1513
+ break;
1514
+ }
1515
+ if (typeof v !== "string" && text.length > room) break;
1516
+ out[k] = v;
1517
+ left -= k.length + 2 + text.length;
1518
+ }
1519
+ return out;
1520
+ };
1521
+ var trackPageFocus = (doc, isInside) => {
1522
+ let lastElement;
1523
+ let lastSelection;
1524
+ const deepActive = () => {
1525
+ let el = doc.activeElement;
1526
+ while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;
1527
+ return el;
1528
+ };
1529
+ const isPageElement = (el) => {
1530
+ const tag = el?.tagName?.toLowerCase();
1531
+ return Boolean(tag) && tag !== "body" && tag !== "html";
1532
+ };
1533
+ const onFocus = (e) => {
1534
+ const target = e.composedPath?.()[0] ?? e.target;
1535
+ if (isPageElement(target) && !isInside(target)) lastElement = target;
1536
+ };
1537
+ const onSelection = () => {
1538
+ const sel = doc.getSelection();
1539
+ if (!sel || isInside(sel.anchorNode)) return;
1540
+ const text = sel.toString().trim();
1541
+ lastSelection = text || void 0;
1542
+ };
1543
+ doc.addEventListener("focusin", onFocus, true);
1544
+ doc.addEventListener("selectionchange", onSelection);
1545
+ return {
1546
+ element() {
1547
+ const now = deepActive();
1548
+ if (isPageElement(now) && !isInside(now)) return now;
1549
+ const last = lastElement;
1550
+ return last && last.isConnected !== false ? lastElement : void 0;
1551
+ },
1552
+ selection() {
1553
+ const sel = doc.getSelection();
1554
+ if (sel && !isInside(sel.anchorNode)) {
1555
+ const text = sel.toString().trim();
1556
+ if (text) return text;
1557
+ }
1558
+ return lastSelection;
1559
+ },
1560
+ stop() {
1561
+ doc.removeEventListener("focusin", onFocus, true);
1562
+ doc.removeEventListener("selectionchange", onSelection);
1563
+ lastElement = void 0;
1564
+ lastSelection = void 0;
1565
+ }
1566
+ };
1567
+ };
1568
+ var PAGE_CONTEXT_ASK_ON_SEND = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web-ui:page-context-ask");
1569
+ var createPageContextCollector = (options, env = pageEnv) => {
1570
+ let position;
1571
+ let denied = false;
1572
+ let tracker;
1573
+ let asking;
1574
+ const geoSettings = (raw) => {
1575
+ const o = typeof raw === "object" && raw ? raw : {};
1576
+ return {
1577
+ precision: typeof o.precision === "number" ? o.precision : 2,
1578
+ maxAgeMs: typeof o.maxAgeMs === "number" ? o.maxAgeMs : 10 * 6e4,
1579
+ timeoutMs: typeof o.timeoutMs === "number" ? o.timeoutMs : 1e4
1580
+ };
1581
+ };
1582
+ const askPosition = (e, s) => {
1583
+ if (asking) return asking;
1584
+ const geo = e.geolocation;
1585
+ if (!geo) return Promise.resolve(void 0);
1586
+ asking = new Promise((resolve) => {
1587
+ let done = false;
1588
+ const finish = (p) => {
1589
+ if (done) return;
1590
+ done = true;
1591
+ asking = void 0;
1592
+ resolve(p);
1593
+ };
1594
+ const timer = setTimeout(() => finish(void 0), s.timeoutMs + 1e3);
1595
+ try {
1596
+ geo.getCurrentPosition(
1597
+ (p) => {
1598
+ clearTimeout(timer);
1599
+ const now = e.now?.() ?? Date.now();
1600
+ position = {
1601
+ latitude: p.coords.latitude,
1602
+ longitude: p.coords.longitude,
1603
+ accuracy: p.coords.accuracy,
1604
+ at: now
1605
+ };
1606
+ finish(position);
1607
+ },
1608
+ (err) => {
1609
+ clearTimeout(timer);
1610
+ if (err?.code === 1) denied = true;
1611
+ finish(void 0);
1612
+ },
1613
+ { timeout: s.timeoutMs, maximumAge: s.maxAgeMs, enableHighAccuracy: false }
1614
+ );
1615
+ } catch {
1616
+ clearTimeout(timer);
1617
+ finish(void 0);
1618
+ }
1619
+ });
1620
+ return asking;
1621
+ };
1622
+ const fresh = (e, maxAgeMs) => position && (e.now?.() ?? Date.now()) - position.at <= maxAgeMs ? position : void 0;
1623
+ const geoEntries = (p, precision) => ({
1624
+ "geo.latitude": roundCoordinate(p.latitude, precision),
1625
+ "geo.longitude": roundCoordinate(p.longitude, precision),
1626
+ // The accuracy is never better than the rounding: at 2 decimals, about a kilometre.
1627
+ "geo.accuracy": Math.max(
1628
+ Math.round(p.accuracy),
1629
+ Math.round(111e3 / 10 ** Math.min(6, precision))
1630
+ )
1631
+ });
1632
+ const read = (base, o) => {
1633
+ const t = tracker;
1634
+ const e = t ? {
1635
+ ...base,
1636
+ // Delegated one by one: a real Document's getters and methods live on its prototype.
1637
+ document: {
1638
+ ...base.document?.title !== void 0 ? { title: base.document.title } : {},
1639
+ ...base.document?.referrer !== void 0 ? { referrer: base.document.referrer } : {},
1640
+ ...base.document?.documentElement ? { documentElement: base.document.documentElement } : {},
1641
+ activeElement: t.element() ?? null,
1642
+ querySelectorAll: (q) => base.document?.querySelectorAll?.(q) ?? [],
1643
+ getElementById: (id) => base.document?.getElementById?.(id) ?? null
1644
+ },
1645
+ getSelection: () => {
1646
+ const text = t.selection();
1647
+ return text ? { toString: () => text } : null;
1648
+ }
1649
+ } : base;
1650
+ const c = o.collect ?? {};
1651
+ const out = {};
1652
+ if (c.url && e.location) {
1653
+ const url = addressWithoutQuery(e.location.href);
1654
+ if (url) out.url = clip(url, PAGE_CONTEXT_VALUE_MAX);
1655
+ }
1656
+ if (c.path && e.location) out.path = clip(e.location.pathname, PAGE_CONTEXT_VALUE_MAX);
1657
+ if (c.title && e.document?.title)
1658
+ out.title = clip(oneLine(e.document.title), PAGE_CONTEXT_VALUE_MAX);
1659
+ if (c.language && e.document?.documentElement?.lang)
1660
+ out.language = e.document.documentElement.lang.slice(0, 35);
1661
+ if (c.referrer && e.document?.referrer) {
1662
+ const ref = addressWithoutQuery(e.document.referrer);
1663
+ if (ref) out.referrer = clip(ref, PAGE_CONTEXT_VALUE_MAX);
1664
+ }
1665
+ if (c.focus) {
1666
+ const includeValues = typeof c.focus === "object" && c.focus.includeValues === true;
1667
+ Object.assign(out, focusEntries(e, includeValues));
1668
+ }
1669
+ if (c.selection) {
1670
+ 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;
1671
+ const text = (e.getSelection?.()?.toString() ?? "").trim();
1672
+ if (text) out.selection = clip(text, max);
1673
+ }
1674
+ if (c.viewport && e.innerWidth && e.innerHeight)
1675
+ out.viewport = `${e.innerWidth}x${e.innerHeight}`;
1676
+ if (c.scroll && typeof e.scrollY === "number") {
1677
+ const total = (e.document?.documentElement?.scrollHeight ?? 0) - (e.innerHeight ?? 0);
1678
+ out.scroll = total > 0 ? `${Math.round(Math.min(100, e.scrollY / total * 100))}% (${Math.round(e.scrollY)}px)` : `0% (${Math.round(e.scrollY)}px)`;
1679
+ }
1680
+ if (c.headings) {
1681
+ const h = headingsInView(e);
1682
+ if (h) out.headings = h;
1683
+ }
1684
+ if (c.time) {
1685
+ const tz = e.timeZone?.();
1686
+ if (tz) out.timeZone = tz;
1687
+ out.localTime = localIso(e.now?.() ?? Date.now());
1688
+ }
1689
+ if (c.colorScheme && e.matchMedia) {
1690
+ out.colorScheme = e.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
1691
+ }
1692
+ if (c.device && e.matchMedia) {
1693
+ const coarse = e.matchMedia("(pointer: coarse)").matches;
1694
+ const w = e.screenWidth ?? e.innerWidth ?? 0;
1695
+ out.device = coarse ? w && w < 768 ? "phone" : "tablet" : "desktop";
1696
+ }
1697
+ return out;
1698
+ };
1699
+ const finishContext = (o, out) => {
1700
+ let extra;
1701
+ try {
1702
+ extra = o.extra?.();
1703
+ } catch {
1704
+ extra = void 0;
1705
+ }
1706
+ if (extra && typeof extra === "object") {
1707
+ for (const [k, v] of Object.entries(extra)) {
1708
+ if (v === void 0) continue;
1709
+ if (v === null || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v))
1710
+ out[k] = v;
1711
+ else if (typeof v === "string") out[k] = clip(v, PAGE_CONTEXT_VALUE_MAX * 4);
1712
+ }
1713
+ }
1714
+ const include = o.include ? new Set(o.include) : void 0;
1715
+ const exclude = new Set(o.exclude ?? []);
1716
+ const kept = {};
1717
+ for (const [k, v] of Object.entries(out)) {
1718
+ if (include && !include.has(k) || exclude.has(k)) continue;
1719
+ kept[k] = v;
1720
+ }
1721
+ const capped = capPageContext(kept, o.maxChars ?? PAGE_CONTEXT_MAX_CHARS);
1722
+ return Object.keys(capped).length ? capped : void 0;
1723
+ };
1724
+ return {
1725
+ get geolocationDenied() {
1726
+ return denied;
1727
+ },
1728
+ setTracker(next) {
1729
+ tracker = next;
1730
+ },
1731
+ preview() {
1732
+ const o = options();
1733
+ if (pageContextOff(o)) return void 0;
1734
+ const e = env();
1735
+ const out = read(e, o);
1736
+ const g = o.collect?.geolocation;
1737
+ if (g && !denied && e.geolocation) {
1738
+ const s = geoSettings(g);
1739
+ const p = fresh(e, s.maxAgeMs);
1740
+ if (p) Object.assign(out, geoEntries(p, s.precision));
1741
+ else out["geo.latitude"] = PAGE_CONTEXT_ASK_ON_SEND;
1742
+ }
1743
+ return finishContext(o, out);
1744
+ },
1745
+ async collect(opts = {}) {
1746
+ const o = options();
1747
+ if (pageContextOff(o)) return void 0;
1748
+ const e = env();
1749
+ const out = read(e, o);
1750
+ const g = o.collect?.geolocation;
1751
+ if (g && !denied) {
1752
+ const s = geoSettings(g);
1753
+ const p = fresh(e, s.maxAgeMs) ?? (opts.ask ? await askPosition(e, s) : void 0);
1754
+ if (p) Object.assign(out, geoEntries(p, s.precision));
1755
+ }
1756
+ return finishContext(o, out);
1757
+ }
1758
+ };
1759
+ };
1760
+ var pageContextRows = (context, askedOnSend) => Object.entries(context ?? {}).map(([key, v]) => ({
1761
+ key: v === PAGE_CONTEXT_ASK_ON_SEND ? "geo" : key,
1762
+ value: v === PAGE_CONTEXT_ASK_ON_SEND ? askedOnSend : v === null ? "" : String(v)
1763
+ }));
1764
+ var withoutAskOnSend = (context) => {
1765
+ if (!context) return void 0;
1766
+ const out = {};
1767
+ for (const [k, v] of Object.entries(context)) {
1768
+ if (v !== PAGE_CONTEXT_ASK_ON_SEND) out[k] = v;
1769
+ }
1770
+ return Object.keys(out).length ? out : void 0;
1771
+ };
1772
+
1365
1773
  // src/approval-queue.ts
1366
1774
  var createApprovalQueue = () => {
1367
1775
  const waiting = /* @__PURE__ */ new Map();
@@ -1483,6 +1891,22 @@ export {
1483
1891
  pendingApprovalsOf,
1484
1892
  agentStatusOf,
1485
1893
  agentStateReducer,
1894
+ PAGE_CONTEXT_VALUE_MAX,
1895
+ PAGE_CONTEXT_SELECTION_MAX,
1896
+ PAGE_CONTEXT_MAX_CHARS,
1897
+ pageContextOff,
1898
+ addressWithoutQuery,
1899
+ isSecretField,
1900
+ isEditableElement,
1901
+ focusEntries,
1902
+ headingsInView,
1903
+ roundCoordinate,
1904
+ capPageContext,
1905
+ trackPageFocus,
1906
+ PAGE_CONTEXT_ASK_ON_SEND,
1907
+ createPageContextCollector,
1908
+ pageContextRows,
1909
+ withoutAskOnSend,
1486
1910
  createApprovalQueue,
1487
1911
  loadAgentCore,
1488
1912
  agentCoreIfLoaded,
@@ -261,6 +261,11 @@ var labelsFromCatalog = (tag, catalog) => {
261
261
  questionOther: t("questionOther"),
262
262
  questionOtherLabel: t("questionOtherLabel"),
263
263
  questionSkip: t("questionSkip"),
264
+ // ── the page context the composer shares (its chip) ──
265
+ pageContextSharing: t("pageContextSharing"),
266
+ pageContextNotSharing: t("pageContextNotSharing"),
267
+ pageContextDontShare: t("pageContextDontShare"),
268
+ pageContextAskedOnSend: t("pageContextAskedOnSend"),
264
269
  questionExpiresIn: (time) => t("questionExpiresIn", { time }),
265
270
  questionRemote: t("questionRemote"),
266
271
  questionAutomatic: (reason) => t("questionAutomatic", { reason }),
@@ -157,6 +157,10 @@ var catalog = {
157
157
  questionOther: "Otra…",
158
158
  questionOtherLabel: "Tu respuesta",
159
159
  questionSkip: "Omitir",
160
+ pageContextSharing: "Se comparte",
161
+ pageContextNotSharing: "No se comparte con este mensaje",
162
+ pageContextDontShare: "No compartir con este mensaje",
163
+ pageContextAskedOnSend: "se pedirá al enviar",
160
164
  questionExpiresIn: "Si no respondes, el asistente decidirá por su cuenta en {time}",
161
165
  questionRemote: "Se responde en la otra pestaña, donde trabaja el asistente.",
162
166
  questionAutomatic: "El asistente siguió sin tu respuesta: {reason}.",
@@ -157,6 +157,10 @@ var catalog = {
157
157
  questionOther: "Autre…",
158
158
  questionOtherLabel: "Votre réponse",
159
159
  questionSkip: "Passer",
160
+ pageContextSharing: "Partagé",
161
+ pageContextNotSharing: "Non partagé avec ce message",
162
+ pageContextDontShare: "Ne pas partager avec ce message",
163
+ pageContextAskedOnSend: "demandé à l’envoi",
160
164
  questionExpiresIn: "Sans réponse de votre part, l’assistant décidera seul dans {time}",
161
165
  questionRemote: "La réponse se donne dans l’autre onglet, où l’assistant travaille.",
162
166
  questionAutomatic: "L’assistant a continué sans votre réponse : {reason}.",
@@ -157,6 +157,10 @@ var catalog = {
157
157
  questionOther: "Друго…",
158
158
  questionOtherLabel: "Ваш одговор",
159
159
  questionSkip: "Прескочи",
160
+ pageContextSharing: "Дели се",
161
+ pageContextNotSharing: "Не дели се са овом поруком",
162
+ pageContextDontShare: "Не дели са овом поруком",
163
+ pageContextAskedOnSend: "тражиће се при слању",
160
164
  questionExpiresIn: "Ако не одговорите, асистент ће сам одлучити за {time}",
161
165
  questionRemote: "Одговара се у другој картици, где асистент ради.",
162
166
  questionAutomatic: "Асистент је наставио без вашег одговора: {reason}.",