@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
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 |
@@ -283,6 +284,57 @@ The options (`RemoteAgentOptions`):
283
284
  The React package's `useRemoteAgent` / `<RemoteAgentProvider>` and the element's `backend`
284
285
  attribute are this controller.
285
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
+
286
338
  ## Labels
287
339
 
288
340
  `defaultLabels` is every string the chat shows; counted phrases are functions so that languages
@@ -238,6 +238,7 @@ var sentEntryOf = (queued, text) => queued.findIndex(
238
238
  (q) => q.sentTo === "another-tab" && (q.text === text || text.endsWith("…") && q.text.length > text.length && q.text.startsWith(text.slice(0, -1)))
239
239
  );
240
240
  var patchStep = (steps, id, fn) => steps.map((s) => s.id === id ? fn(s) : s);
241
+ var summaryOf = (summary) => typeof summary === "string" && summary.trim() ? { summary: summary.slice(0, 4e3) } : {};
241
242
  var withoutSkillBody = (a) => {
242
243
  if (!a.skill || a.skill.body === void 0) return a;
243
244
  const { body: _body, ...skill } = a.skill;
@@ -323,13 +324,20 @@ var answerQuestion = (state, event) => state.questions?.some((q) => q.id === eve
323
324
  } : state;
324
325
  var patchSubagent = (subagents, id, fn) => subagents.map((s) => s.id === id ? fn(s) : s);
325
326
  var runningStepId = (steps) => [...steps].reverse().find((s) => s.status === "running")?.id;
327
+ var stepPlace = (index, total) => {
328
+ const whole = (n) => typeof n === "number" && Number.isInteger(n);
329
+ if (whole(index) && whole(total) && index >= 1 && total >= index) return `${index}/${total}`;
330
+ if (whole(index) && index >= 0 && total === void 0) return String(index + 1);
331
+ if (whole(index) && index >= 1) return String(index);
332
+ return "?";
333
+ };
326
334
  var applySubagentEvent = (view, event) => {
327
335
  switch (event.type) {
328
336
  case "step.start":
329
337
  return {
330
338
  ...view,
331
339
  steps: view.steps + 1,
332
- activity: `step ${event.index}/${event.total}: ${event.step.description}`,
340
+ activity: `step ${stepPlace(event.index, event.total)}: ${event.step.description}`,
333
341
  // Known only when the child runs with model tiers.
334
342
  ...event.model !== void 0 ? { model: event.model } : {},
335
343
  ...event.tier !== void 0 ? { tier: event.tier } : {}
@@ -517,6 +525,7 @@ var applySubagent = (state, event, ancestors, ctx) => {
517
525
  },
518
526
  ...inner.skill ? { skill: inner.skill } : {},
519
527
  ...inner.rule ? { rule: inner.rule } : {},
528
+ ...summaryOf(inner.summary),
520
529
  ...ctx.remote ? { remote: true } : {},
521
530
  status: "pending"
522
531
  }
@@ -1071,6 +1080,7 @@ var applyEvent = (state, event, ctx) => {
1071
1080
  ...event.app ? { app: event.app } : {},
1072
1081
  ...event.skill ? { skill: event.skill } : {},
1073
1082
  ...event.rule ? { rule: event.rule } : {},
1083
+ ...summaryOf(event.summary),
1074
1084
  // Asked in the tab that runs the tool: shown here, answered there.
1075
1085
  ...ctx.remote ? { remote: true } : {},
1076
1086
  status: "pending"
@@ -1362,6 +1372,414 @@ var agentStateReducer = (state, action) => {
1362
1372
  }
1363
1373
  };
1364
1374
 
1375
+ // src/page-context.ts
1376
+ var PAGE_CONTEXT_VALUE_MAX = 500;
1377
+ var PAGE_CONTEXT_SELECTION_MAX = 500;
1378
+ var PAGE_CONTEXT_MAX_CHARS = 2e3;
1379
+ var HEADINGS_MAX = 8;
1380
+ var CLIP = "…";
1381
+ var clip = (text, max) => text.length > max ? `${text.slice(0, Math.max(0, max - 1))}${CLIP}` : text;
1382
+ var oneLine = (text) => text.replace(/\s+/g, " ").trim();
1383
+ var pageEnv = () => {
1384
+ const g = globalThis;
1385
+ if (typeof g.window === "undefined") return {};
1386
+ const w = g;
1387
+ return {
1388
+ location: w.location,
1389
+ document: w.document,
1390
+ getSelection: () => w.getSelection?.() ?? null,
1391
+ innerWidth: w.innerWidth,
1392
+ innerHeight: w.innerHeight,
1393
+ scrollY: w.scrollY,
1394
+ matchMedia: (q) => w.matchMedia(q),
1395
+ ...g.navigator?.geolocation ? { geolocation: g.navigator.geolocation } : {},
1396
+ now: () => Date.now(),
1397
+ timeZone: () => Intl.DateTimeFormat().resolvedOptions().timeZone,
1398
+ screenWidth: g.screen?.width ?? w.innerWidth
1399
+ };
1400
+ };
1401
+ var pageContextOff = (options) => !options || !options.extra && !Object.values(options.collect ?? {}).some((v) => v !== false && v != null);
1402
+ var addressWithoutQuery = (href) => {
1403
+ try {
1404
+ const u = new URL(href);
1405
+ if (u.protocol !== "http:" && u.protocol !== "https:") return void 0;
1406
+ return `${u.origin}${u.pathname}`;
1407
+ } catch {
1408
+ return void 0;
1409
+ }
1410
+ };
1411
+ var autocompleteTokens = (el) => (el.getAttribute("autocomplete") ?? "").toLowerCase().split(/\s+/).filter(Boolean);
1412
+ var isSecretField = (el) => {
1413
+ const type = (el.type ?? el.getAttribute("type") ?? "").toLowerCase();
1414
+ if (type === "password" || type === "hidden") return true;
1415
+ return autocompleteTokens(el).some(
1416
+ (t) => t.startsWith("cc-") || t === "one-time-code" || t === "current-password" || t === "new-password"
1417
+ );
1418
+ };
1419
+ var IMPLICIT_ROLE = {
1420
+ a: "link",
1421
+ button: "button",
1422
+ textarea: "textbox",
1423
+ select: "combobox",
1424
+ h1: "heading",
1425
+ h2: "heading",
1426
+ h3: "heading",
1427
+ summary: "button"
1428
+ };
1429
+ var roleOf = (el) => {
1430
+ const explicit = el.getAttribute("role");
1431
+ if (explicit) return explicit.split(/\s+/)[0];
1432
+ const tag = el.tagName.toLowerCase();
1433
+ if (tag === "input") {
1434
+ const type = (el.type ?? el.getAttribute("type") ?? "text").toLowerCase();
1435
+ if (type === "checkbox") return "checkbox";
1436
+ if (type === "radio") return "radio";
1437
+ if (type === "button" || type === "submit" || type === "reset") return "button";
1438
+ if (type === "range") return "slider";
1439
+ if (type === "search") return "searchbox";
1440
+ return "textbox";
1441
+ }
1442
+ if (tag !== "textarea" && tag !== "select" && isEditableElement(el)) return "textbox";
1443
+ return IMPLICIT_ROLE[tag] ?? tag;
1444
+ };
1445
+ var EDITABLE_ROLES = /* @__PURE__ */ new Set(["textbox", "searchbox", "combobox", "spinbutton"]);
1446
+ var isEditableElement = (el) => {
1447
+ const tag = el.tagName.toLowerCase();
1448
+ if (tag === "input" || tag === "textarea" || tag === "select") return true;
1449
+ if (el.isContentEditable === true) return true;
1450
+ const ce = el.getAttribute("contenteditable");
1451
+ if (ce !== null && ce.toLowerCase() !== "false") return true;
1452
+ const role = (el.getAttribute("role") ?? "").toLowerCase().split(/\s+/)[0] ?? "";
1453
+ return EDITABLE_ROLES.has(role);
1454
+ };
1455
+ var nameOf = (el, env) => {
1456
+ const aria = el.getAttribute("aria-label");
1457
+ if (aria) return aria;
1458
+ const by = el.getAttribute("aria-labelledby");
1459
+ if (by) {
1460
+ const text = by.split(/\s+/).map((id) => env.document?.getElementById?.(id)?.textContent ?? "").join(" ");
1461
+ if (text.trim()) return text;
1462
+ }
1463
+ const label = el.labels && el.labels.length ? el.labels[0]?.textContent ?? "" : "";
1464
+ if (label.trim()) return label;
1465
+ const placeholder = el.getAttribute("placeholder") ?? el.getAttribute("title");
1466
+ if (placeholder) return placeholder;
1467
+ return isEditableElement(el) ? "" : el.textContent ?? "";
1468
+ };
1469
+ var focusEntries = (env, includeValues) => {
1470
+ const el = env.document?.activeElement;
1471
+ if (!el) return {};
1472
+ const tag = el.tagName.toLowerCase();
1473
+ if (tag === "body" || tag === "html") return {};
1474
+ const out = { "focus.role": roleOf(el) };
1475
+ const name = clip(oneLine(nameOf(el, env)), 120);
1476
+ if (name) out["focus.label"] = name;
1477
+ out["focus.type"] = tag === "input" ? `input:${(el.type ?? "text").toLowerCase()}` : tag;
1478
+ if (includeValues && isEditableElement(el) && !isSecretField(el)) {
1479
+ const isControl = tag === "input" || tag === "textarea" || tag === "select";
1480
+ const raw = isControl ? el.value : el.textContent;
1481
+ const value = typeof raw === "string" ? raw.trim() : "";
1482
+ if (value) out["focus.value"] = clip(value, PAGE_CONTEXT_VALUE_MAX);
1483
+ }
1484
+ return out;
1485
+ };
1486
+ var headingsInView = (env) => {
1487
+ const all = env.document?.querySelectorAll?.("h1, h2, h3");
1488
+ if (!all) return void 0;
1489
+ const height = env.innerHeight ?? Infinity;
1490
+ const shown = [];
1491
+ for (let i = 0; i < all.length && shown.length < HEADINGS_MAX; i++) {
1492
+ const h = all[i];
1493
+ const box = h.getBoundingClientRect?.();
1494
+ if (box && (box.bottom < 0 || box.top > height)) continue;
1495
+ const text = clip(oneLine(h.textContent ?? ""), 120);
1496
+ if (text) shown.push(text);
1497
+ }
1498
+ return shown.length ? clip(shown.join(" / "), PAGE_CONTEXT_VALUE_MAX) : void 0;
1499
+ };
1500
+ var roundCoordinate = (value, precision) => {
1501
+ const p = Math.min(6, Math.max(0, Math.floor(precision)));
1502
+ const f = 10 ** p;
1503
+ return Math.round(value * f) / f;
1504
+ };
1505
+ var localIso = (ms) => {
1506
+ const d = new Date(ms);
1507
+ const pad = (n) => String(Math.abs(n)).padStart(2, "0");
1508
+ const off = -d.getTimezoneOffset();
1509
+ const sign = off >= 0 ? "+" : "-";
1510
+ 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)}`;
1511
+ };
1512
+ var capPageContext = (context, max) => {
1513
+ let left = max;
1514
+ const out = {};
1515
+ for (const [k, v] of Object.entries(context)) {
1516
+ const text = v === null ? "" : String(v);
1517
+ const room = left - k.length - 2;
1518
+ if (room <= 0) break;
1519
+ if (typeof v === "string" && text.length > room) {
1520
+ if (room < 8) break;
1521
+ out[k] = clip(text, room);
1522
+ left = 0;
1523
+ break;
1524
+ }
1525
+ if (typeof v !== "string" && text.length > room) break;
1526
+ out[k] = v;
1527
+ left -= k.length + 2 + text.length;
1528
+ }
1529
+ return out;
1530
+ };
1531
+ var trackPageFocus = (doc, isInside) => {
1532
+ let lastElement;
1533
+ let lastSelection;
1534
+ const deepActive = () => {
1535
+ let el = doc.activeElement;
1536
+ while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;
1537
+ return el;
1538
+ };
1539
+ const isPageElement = (el) => {
1540
+ const tag = el?.tagName?.toLowerCase();
1541
+ return Boolean(tag) && tag !== "body" && tag !== "html";
1542
+ };
1543
+ const onFocus = (e) => {
1544
+ const target = e.composedPath?.()[0] ?? e.target;
1545
+ if (isPageElement(target) && !isInside(target)) lastElement = target;
1546
+ };
1547
+ const onSelection = () => {
1548
+ const sel = doc.getSelection();
1549
+ if (!sel || isInside(sel.anchorNode)) return;
1550
+ const text = sel.toString().trim();
1551
+ lastSelection = text || void 0;
1552
+ };
1553
+ doc.addEventListener("focusin", onFocus, true);
1554
+ doc.addEventListener("selectionchange", onSelection);
1555
+ return {
1556
+ element() {
1557
+ const now = deepActive();
1558
+ if (isPageElement(now) && !isInside(now)) return now;
1559
+ const last = lastElement;
1560
+ return last && last.isConnected !== false ? lastElement : void 0;
1561
+ },
1562
+ selection() {
1563
+ const sel = doc.getSelection();
1564
+ if (sel && !isInside(sel.anchorNode)) {
1565
+ const text = sel.toString().trim();
1566
+ if (text) return text;
1567
+ }
1568
+ return lastSelection;
1569
+ },
1570
+ stop() {
1571
+ doc.removeEventListener("focusin", onFocus, true);
1572
+ doc.removeEventListener("selectionchange", onSelection);
1573
+ lastElement = void 0;
1574
+ lastSelection = void 0;
1575
+ }
1576
+ };
1577
+ };
1578
+ var PAGE_CONTEXT_ASK_ON_SEND = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web-ui:page-context-ask");
1579
+ var createPageContextCollector = (options, env = pageEnv) => {
1580
+ let position;
1581
+ let denied = false;
1582
+ let tracker;
1583
+ let asking;
1584
+ const geoSettings = (raw) => {
1585
+ const o = typeof raw === "object" && raw ? raw : {};
1586
+ return {
1587
+ precision: typeof o.precision === "number" ? o.precision : 2,
1588
+ maxAgeMs: typeof o.maxAgeMs === "number" ? o.maxAgeMs : 10 * 6e4,
1589
+ timeoutMs: typeof o.timeoutMs === "number" ? o.timeoutMs : 1e4
1590
+ };
1591
+ };
1592
+ const askPosition = (e, s) => {
1593
+ if (asking) return asking;
1594
+ const geo = e.geolocation;
1595
+ if (!geo) return Promise.resolve(void 0);
1596
+ asking = new Promise((resolve) => {
1597
+ let done = false;
1598
+ const finish = (p) => {
1599
+ if (done) return;
1600
+ done = true;
1601
+ asking = void 0;
1602
+ resolve(p);
1603
+ };
1604
+ const timer = setTimeout(() => finish(void 0), s.timeoutMs + 1e3);
1605
+ try {
1606
+ geo.getCurrentPosition(
1607
+ (p) => {
1608
+ clearTimeout(timer);
1609
+ const now = e.now?.() ?? Date.now();
1610
+ position = {
1611
+ latitude: p.coords.latitude,
1612
+ longitude: p.coords.longitude,
1613
+ accuracy: p.coords.accuracy,
1614
+ at: now
1615
+ };
1616
+ finish(position);
1617
+ },
1618
+ (err) => {
1619
+ clearTimeout(timer);
1620
+ if (err?.code === 1) denied = true;
1621
+ finish(void 0);
1622
+ },
1623
+ { timeout: s.timeoutMs, maximumAge: s.maxAgeMs, enableHighAccuracy: false }
1624
+ );
1625
+ } catch {
1626
+ clearTimeout(timer);
1627
+ finish(void 0);
1628
+ }
1629
+ });
1630
+ return asking;
1631
+ };
1632
+ const fresh = (e, maxAgeMs) => position && (e.now?.() ?? Date.now()) - position.at <= maxAgeMs ? position : void 0;
1633
+ const geoEntries = (p, precision) => ({
1634
+ "geo.latitude": roundCoordinate(p.latitude, precision),
1635
+ "geo.longitude": roundCoordinate(p.longitude, precision),
1636
+ // The accuracy is never better than the rounding: at 2 decimals, about a kilometre.
1637
+ "geo.accuracy": Math.max(
1638
+ Math.round(p.accuracy),
1639
+ Math.round(111e3 / 10 ** Math.min(6, precision))
1640
+ )
1641
+ });
1642
+ const read = (base, o) => {
1643
+ const t = tracker;
1644
+ const e = t ? {
1645
+ ...base,
1646
+ // Delegated one by one: a real Document's getters and methods live on its prototype.
1647
+ document: {
1648
+ ...base.document?.title !== void 0 ? { title: base.document.title } : {},
1649
+ ...base.document?.referrer !== void 0 ? { referrer: base.document.referrer } : {},
1650
+ ...base.document?.documentElement ? { documentElement: base.document.documentElement } : {},
1651
+ activeElement: t.element() ?? null,
1652
+ querySelectorAll: (q) => base.document?.querySelectorAll?.(q) ?? [],
1653
+ getElementById: (id) => base.document?.getElementById?.(id) ?? null
1654
+ },
1655
+ getSelection: () => {
1656
+ const text = t.selection();
1657
+ return text ? { toString: () => text } : null;
1658
+ }
1659
+ } : base;
1660
+ const c = o.collect ?? {};
1661
+ const out = {};
1662
+ if (c.url && e.location) {
1663
+ const url = addressWithoutQuery(e.location.href);
1664
+ if (url) out.url = clip(url, PAGE_CONTEXT_VALUE_MAX);
1665
+ }
1666
+ if (c.path && e.location) out.path = clip(e.location.pathname, PAGE_CONTEXT_VALUE_MAX);
1667
+ if (c.title && e.document?.title)
1668
+ out.title = clip(oneLine(e.document.title), PAGE_CONTEXT_VALUE_MAX);
1669
+ if (c.language && e.document?.documentElement?.lang)
1670
+ out.language = e.document.documentElement.lang.slice(0, 35);
1671
+ if (c.referrer && e.document?.referrer) {
1672
+ const ref = addressWithoutQuery(e.document.referrer);
1673
+ if (ref) out.referrer = clip(ref, PAGE_CONTEXT_VALUE_MAX);
1674
+ }
1675
+ if (c.focus) {
1676
+ const includeValues = typeof c.focus === "object" && c.focus.includeValues === true;
1677
+ Object.assign(out, focusEntries(e, includeValues));
1678
+ }
1679
+ if (c.selection) {
1680
+ 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;
1681
+ const text = (e.getSelection?.()?.toString() ?? "").trim();
1682
+ if (text) out.selection = clip(text, max);
1683
+ }
1684
+ if (c.viewport && e.innerWidth && e.innerHeight)
1685
+ out.viewport = `${e.innerWidth}x${e.innerHeight}`;
1686
+ if (c.scroll && typeof e.scrollY === "number") {
1687
+ const total = (e.document?.documentElement?.scrollHeight ?? 0) - (e.innerHeight ?? 0);
1688
+ out.scroll = total > 0 ? `${Math.round(Math.min(100, e.scrollY / total * 100))}% (${Math.round(e.scrollY)}px)` : `0% (${Math.round(e.scrollY)}px)`;
1689
+ }
1690
+ if (c.headings) {
1691
+ const h = headingsInView(e);
1692
+ if (h) out.headings = h;
1693
+ }
1694
+ if (c.time) {
1695
+ const tz = e.timeZone?.();
1696
+ if (tz) out.timeZone = tz;
1697
+ out.localTime = localIso(e.now?.() ?? Date.now());
1698
+ }
1699
+ if (c.colorScheme && e.matchMedia) {
1700
+ out.colorScheme = e.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
1701
+ }
1702
+ if (c.device && e.matchMedia) {
1703
+ const coarse = e.matchMedia("(pointer: coarse)").matches;
1704
+ const w = e.screenWidth ?? e.innerWidth ?? 0;
1705
+ out.device = coarse ? w && w < 768 ? "phone" : "tablet" : "desktop";
1706
+ }
1707
+ return out;
1708
+ };
1709
+ const finishContext = (o, out) => {
1710
+ let extra;
1711
+ try {
1712
+ extra = o.extra?.();
1713
+ } catch {
1714
+ extra = void 0;
1715
+ }
1716
+ if (extra && typeof extra === "object") {
1717
+ for (const [k, v] of Object.entries(extra)) {
1718
+ if (v === void 0) continue;
1719
+ if (v === null || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v))
1720
+ out[k] = v;
1721
+ else if (typeof v === "string") out[k] = clip(v, PAGE_CONTEXT_VALUE_MAX * 4);
1722
+ }
1723
+ }
1724
+ const include = o.include ? new Set(o.include) : void 0;
1725
+ const exclude = new Set(o.exclude ?? []);
1726
+ const kept = {};
1727
+ for (const [k, v] of Object.entries(out)) {
1728
+ if (include && !include.has(k) || exclude.has(k)) continue;
1729
+ kept[k] = v;
1730
+ }
1731
+ const capped = capPageContext(kept, o.maxChars ?? PAGE_CONTEXT_MAX_CHARS);
1732
+ return Object.keys(capped).length ? capped : void 0;
1733
+ };
1734
+ return {
1735
+ get geolocationDenied() {
1736
+ return denied;
1737
+ },
1738
+ setTracker(next) {
1739
+ tracker = next;
1740
+ },
1741
+ preview() {
1742
+ const o = options();
1743
+ if (pageContextOff(o)) return void 0;
1744
+ const e = env();
1745
+ const out = read(e, o);
1746
+ const g = o.collect?.geolocation;
1747
+ if (g && !denied && e.geolocation) {
1748
+ const s = geoSettings(g);
1749
+ const p = fresh(e, s.maxAgeMs);
1750
+ if (p) Object.assign(out, geoEntries(p, s.precision));
1751
+ else out["geo.latitude"] = PAGE_CONTEXT_ASK_ON_SEND;
1752
+ }
1753
+ return finishContext(o, out);
1754
+ },
1755
+ async collect(opts = {}) {
1756
+ const o = options();
1757
+ if (pageContextOff(o)) return void 0;
1758
+ const e = env();
1759
+ const out = read(e, o);
1760
+ const g = o.collect?.geolocation;
1761
+ if (g && !denied) {
1762
+ const s = geoSettings(g);
1763
+ const p = fresh(e, s.maxAgeMs) ?? (opts.ask ? await askPosition(e, s) : void 0);
1764
+ if (p) Object.assign(out, geoEntries(p, s.precision));
1765
+ }
1766
+ return finishContext(o, out);
1767
+ }
1768
+ };
1769
+ };
1770
+ var pageContextRows = (context, askedOnSend) => Object.entries(context ?? {}).map(([key, v]) => ({
1771
+ key: v === PAGE_CONTEXT_ASK_ON_SEND ? "geo" : key,
1772
+ value: v === PAGE_CONTEXT_ASK_ON_SEND ? askedOnSend : v === null ? "" : String(v)
1773
+ }));
1774
+ var withoutAskOnSend = (context) => {
1775
+ if (!context) return void 0;
1776
+ const out = {};
1777
+ for (const [k, v] of Object.entries(context)) {
1778
+ if (v !== PAGE_CONTEXT_ASK_ON_SEND) out[k] = v;
1779
+ }
1780
+ return Object.keys(out).length ? out : void 0;
1781
+ };
1782
+
1365
1783
  // src/approval-queue.ts
1366
1784
  var createApprovalQueue = () => {
1367
1785
  const waiting = /* @__PURE__ */ new Map();
@@ -1483,6 +1901,22 @@ export {
1483
1901
  pendingApprovalsOf,
1484
1902
  agentStatusOf,
1485
1903
  agentStateReducer,
1904
+ PAGE_CONTEXT_VALUE_MAX,
1905
+ PAGE_CONTEXT_SELECTION_MAX,
1906
+ PAGE_CONTEXT_MAX_CHARS,
1907
+ pageContextOff,
1908
+ addressWithoutQuery,
1909
+ isSecretField,
1910
+ isEditableElement,
1911
+ focusEntries,
1912
+ headingsInView,
1913
+ roundCoordinate,
1914
+ capPageContext,
1915
+ trackPageFocus,
1916
+ PAGE_CONTEXT_ASK_ON_SEND,
1917
+ createPageContextCollector,
1918
+ pageContextRows,
1919
+ withoutAskOnSend,
1486
1920
  createApprovalQueue,
1487
1921
  loadAgentCore,
1488
1922
  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}.",