@mgamadeus/ddd-agents 0.6.13 → 0.6.15

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.
package/dist/ui.js CHANGED
@@ -18,8 +18,17 @@ const CLIENT_TOOL_OUTCOMES = {
18
18
  readFailed: "READ_FAILED",
19
19
  unknownRequest: "UNKNOWN_REQUEST",
20
20
  unknownMode: "UNKNOWN_MODE",
21
- pictureUnavailable: "PICTURE_UNAVAILABLE"
21
+ pictureUnavailable: "PICTURE_UNAVAILABLE",
22
+ actionsUnavailable: "ACTIONS_UNAVAILABLE",
23
+ unknownAction: "UNKNOWN_ACTION",
24
+ noFilters: "NO_FILTERS",
25
+ notDeclared: "NOT_DECLARED",
26
+ writeAction: "WRITE_ACTION",
27
+ disabled: "DISABLED",
28
+ noEffect: "NO_EFFECT"
22
29
  };
30
+ const SCREEN_ACTION_KINDS = ["setFilters", "sort", "openRow", "switchTab", "press"];
31
+ const SCREEN_SORT_DIRECTIONS = ["asc", "desc", "none"];
23
32
  const parseClientToolArguments = (argumentsJson) => {
24
33
  try {
25
34
  const parsed = JSON.parse(argumentsJson);
@@ -74,8 +83,10 @@ const buildTargetRoute = (target, recordIds, tab) => {
74
83
  if (tab) segments.push(tab);
75
84
  return `/${segments.join("/")}`;
76
85
  };
77
- const PACKAGE_REQUEST_TYPES = ["READ_SCREEN", "LIST_TARGETS", "OPEN_TARGET", "HIGHLIGHT", "SET_WINDOW_MODE"];
78
- const STEP_ASIDE_REQUEST_TYPES = ["OPEN_TARGET", "HIGHLIGHT", "READ_SCREEN"];
86
+ const PACKAGE_REQUEST_TYPES = ["READ_SCREEN", "LIST_TARGETS", "OPEN_TARGET", "HIGHLIGHT", "SET_WINDOW_MODE", "ACT_ON_SCREEN"];
87
+ const STEP_ASIDE_REQUEST_TYPES = ["OPEN_TARGET", "HIGHLIGHT", "READ_SCREEN", "ACT_ON_SCREEN"];
88
+ const MAX_ACTION_FILTERS = 6;
89
+ const MAX_FILTER_VALUE_CHARS = 100;
79
90
  const PICTURE_SIZES = ["small", "medium", "large"];
80
91
  const RENDER_MODES = ["colour", "greyscale", "machine"];
81
92
  const MAX_SCREEN_CHARS = MAX_ANSWER_TEXT_CHARS / 2;
@@ -111,7 +122,7 @@ class ClientToolRequestRunner {
111
122
  /** The answer of one request. Exposed for the tests. */
112
123
  async run(delivery, receivedAt = Date.now()) {
113
124
  const secondsLeft = delivery.secondsLeft - (Date.now() - receivedAt) / 1e3;
114
- if (secondsLeft < MIN_SECONDS_LEFT_TO_START) return refusal(CLIENT_TOOL_OUTCOMES.expiredBeforeStart);
125
+ if (secondsLeft < MIN_SECONDS_LEFT_TO_START) return refusal$1(CLIENT_TOOL_OUTCOMES.expiredBeforeStart);
115
126
  const parameters = parseClientToolArguments(delivery.argumentsJson);
116
127
  try {
117
128
  switch (delivery.requestType) {
@@ -134,17 +145,19 @@ class ClientToolRequestRunner {
134
145
  return this.highlight(parameters);
135
146
  case "SET_WINDOW_MODE":
136
147
  return await this.setWindowMode(parameters);
148
+ case "ACT_ON_SCREEN":
149
+ return await this.actOnScreen(parameters);
137
150
  default:
138
151
  return await this.runRequestOfApplication(delivery, parameters);
139
152
  }
140
153
  } catch {
141
- return refusal(CLIENT_TOOL_OUTCOMES.readFailed);
154
+ return refusal$1(CLIENT_TOOL_OUTCOMES.readFailed);
142
155
  }
143
156
  }
144
157
  /** A request type the application registered: its handler, else `UNKNOWN_REQUEST`. */
145
158
  async runRequestOfApplication(delivery, parameters) {
146
159
  const handler = PACKAGE_REQUEST_TYPES.includes(delivery.requestType) ? void 0 : this.adapters.requestHandlers?.[delivery.requestType];
147
- if (!handler) return refusal(CLIENT_TOOL_OUTCOMES.unknownRequest);
160
+ if (!handler) return refusal$1(CLIENT_TOOL_OUTCOMES.unknownRequest);
148
161
  return handler(parameters, delivery);
149
162
  }
150
163
  /** Lets the agent window make room before the agent works on the screen (the default for the screen requests). */
@@ -156,22 +169,22 @@ class ClientToolRequestRunner {
156
169
  }
157
170
  async setWindowMode(parameters) {
158
171
  const agentWindow = this.adapters.agentWindow;
159
- if (!agentWindow || !isClientToolToken(parameters.mode)) return refusal(CLIENT_TOOL_OUTCOMES.unknownMode);
172
+ if (!agentWindow || !isClientToolToken(parameters.mode)) return refusal$1(CLIENT_TOOL_OUTCOMES.unknownMode);
160
173
  if (parameters.mode === "restore") {
161
174
  await agentWindow.restore();
162
175
  return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: "", details: { mode: "restore" } };
163
176
  }
164
177
  const accepted = await agentWindow.setMode(parameters.mode);
165
- if (!accepted) return refusal(CLIENT_TOOL_OUTCOMES.unknownMode);
178
+ if (!accepted) return refusal$1(CLIENT_TOOL_OUTCOMES.unknownMode);
166
179
  return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: "", details: { mode: parameters.mode } };
167
180
  }
168
181
  async readScreenPicture(parameters) {
169
182
  const capturer = this.adapters.picture;
170
- if (!capturer) return refusal(CLIENT_TOOL_OUTCOMES.pictureUnavailable);
183
+ if (!capturer) return refusal$1(CLIENT_TOOL_OUTCOMES.pictureUnavailable);
171
184
  const pictureSize = PICTURE_SIZES.find((size) => size === parameters.pictureSize) ?? "medium";
172
185
  const renderMode = RENDER_MODES.find((mode) => mode === parameters.renderMode) ?? "colour";
173
186
  const picture = await capturer.capture({ pictureSize, renderMode });
174
- if (!picture) return refusal(CLIENT_TOOL_OUTCOMES.pictureUnavailable);
187
+ if (!picture) return refusal$1(CLIENT_TOOL_OUTCOMES.pictureUnavailable);
175
188
  const location = this.adapters.navigator.currentLocation();
176
189
  return {
177
190
  outcome: CLIENT_TOOL_OUTCOMES.ok,
@@ -206,19 +219,19 @@ class ClientToolRequestRunner {
206
219
  }
207
220
  async openTarget(parameters) {
208
221
  const target = this.findTarget(parameters.target);
209
- if (!target) return refusal(CLIENT_TOOL_OUTCOMES.unknownTarget);
222
+ if (!target) return refusal$1(CLIENT_TOOL_OUTCOMES.unknownTarget);
210
223
  const tab = isClientToolToken(parameters.tab) ? parameters.tab : null;
211
- if (tab !== null && !target.tabs.includes(tab)) return refusal(CLIENT_TOOL_OUTCOMES.unknownTab);
224
+ if (tab !== null && !target.tabs.includes(tab)) return refusal$1(CLIENT_TOOL_OUTCOMES.unknownTab);
212
225
  const filters = {};
213
226
  for (const filter of Array.isArray(parameters.filters) ? parameters.filters : []) {
214
227
  const [key, ...valueParts] = String(filter).split("=");
215
228
  if (!target.filters.some((targetFilter) => targetFilter.key === key) || valueParts.length === 0) {
216
- return refusal(CLIENT_TOOL_OUTCOMES.unknownFilter);
229
+ return refusal$1(CLIENT_TOOL_OUTCOMES.unknownFilter);
217
230
  }
218
231
  filters[key] = valueParts.join("=");
219
232
  }
220
233
  const recordIds = typeof parameters.recordId === "number" ? [parameters.recordId] : [];
221
- if (buildTargetRoute(target, recordIds, tab) === null) return refusal(CLIENT_TOOL_OUTCOMES.missingParameter);
234
+ if (buildTargetRoute(target, recordIds, tab) === null) return refusal$1(CLIENT_TOOL_OUTCOMES.missingParameter);
222
235
  const blocker = this.adapters.navigator.describeBlockers();
223
236
  if (blocker) return { outcome: blocker.outcome, text: blocker.reason, details: {} };
224
237
  await this.stepAgentWindowAside("OPEN_TARGET");
@@ -233,6 +246,55 @@ class ClientToolRequestRunner {
233
246
  const snapshot = this.adapters.reader.read({ maxChars: MAX_SCREEN_CHARS });
234
247
  return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: snapshot.markdown, details };
235
248
  }
249
+ /**
250
+ * A typed action on the open screen: `setFilters` through the navigator (the filters the screen's target declares),
251
+ * every other kind through the actor on an element the screen declares for it. With `includeScreen` the answer
252
+ * carries the screen after the action.
253
+ */
254
+ async actOnScreen(parameters) {
255
+ const action = SCREEN_ACTION_KINDS.find((kind) => kind === parameters.action);
256
+ if (!action) return refusal$1(CLIENT_TOOL_OUTCOMES.unknownAction);
257
+ const answer = action === "setFilters" ? await this.setFilters(parameters) : await this.actOnElement(action, parameters);
258
+ if (answer.outcome !== CLIENT_TOOL_OUTCOMES.ok || parameters.includeScreen !== true) return answer;
259
+ const snapshot = this.adapters.reader.read({ maxChars: MAX_SCREEN_CHARS });
260
+ return { ...answer, text: `${answer.text}
261
+ ${snapshot.markdown}` };
262
+ }
263
+ async actOnElement(action, parameters) {
264
+ const actor = this.adapters.actions;
265
+ if (!actor) return refusal$1(CLIENT_TOOL_OUTCOMES.actionsUnavailable);
266
+ if (!isClientToolToken(parameters.reference)) return refusal$1(CLIENT_TOOL_OUTCOMES.missingParameter);
267
+ const direction = SCREEN_SORT_DIRECTIONS.find((candidate) => candidate === parameters.direction) ?? null;
268
+ await this.stepAgentWindowAside("ACT_ON_SCREEN");
269
+ return actor.act({ action, reference: parameters.reference, direction });
270
+ }
271
+ /** Sets and clears URL filters of the open screen: only keys its target declares, the rest of the URL stays. */
272
+ async setFilters(parameters) {
273
+ const navigator = this.adapters.navigator;
274
+ if (!navigator.currentTarget || !navigator.applyFilters) return refusal$1(CLIENT_TOOL_OUTCOMES.actionsUnavailable);
275
+ const target = navigator.currentTarget();
276
+ if (!target || target.filters.length === 0) return refusal$1(CLIENT_TOOL_OUTCOMES.noFilters);
277
+ const entries = (Array.isArray(parameters.filters) ? parameters.filters : []).slice(0, MAX_ACTION_FILTERS);
278
+ if (entries.length === 0) return refusal$1(CLIENT_TOOL_OUTCOMES.missingParameter);
279
+ const filters = {};
280
+ for (const entry of entries) {
281
+ const [key, ...valueParts] = String(entry).split("=");
282
+ if (!target.filters.some((targetFilter) => targetFilter.key === key) || valueParts.length === 0) {
283
+ return { outcome: CLIENT_TOOL_OUTCOMES.unknownFilter, text: `Filters of this screen: ${target.filters.map((filter) => filter.key).join(", ")}.`, details: {} };
284
+ }
285
+ filters[key] = valueParts.join("=").slice(0, MAX_FILTER_VALUE_CHARS);
286
+ }
287
+ const blocker = navigator.describeBlockers();
288
+ if (blocker) return { outcome: blocker.outcome, text: blocker.reason, details: {} };
289
+ await this.stepAgentWindowAside("ACT_ON_SCREEN");
290
+ const location = await navigator.applyFilters(target, filters);
291
+ const changes = Object.entries(filters).map(([key, value]) => value === "" ? `${key} cleared` : `${key}=${value}`);
292
+ return {
293
+ outcome: CLIENT_TOOL_OUTCOMES.ok,
294
+ text: `Filters of ${target.key}: ${changes.join(", ")}.`,
295
+ details: { route: location.route, title: location.title }
296
+ };
297
+ }
236
298
  highlight(parameters) {
237
299
  const references = (Array.isArray(parameters.references) ? parameters.references : []).filter(isClientToolToken);
238
300
  const note = typeof parameters.note === "string" && parameters.note.trim() !== "" ? parameters.note : null;
@@ -251,7 +313,7 @@ class ClientToolRequestRunner {
251
313
  return this.adapters.targets.listTargets().find((target) => target.key === key) ?? null;
252
314
  }
253
315
  }
254
- const refusal = (outcome) => ({ outcome, text: "", details: {} });
316
+ const refusal$1 = (outcome) => ({ outcome, text: "", details: {} });
255
317
  class AgentUIClient {
256
318
  constructor(adapters, uiStateSource = null, clientId = createAgentUIClientId()) {
257
319
  this.acceptedClientToolRequestCount = 0;
@@ -356,6 +418,12 @@ const formatFieldLine = (field) => {
356
418
  if (field.invalidMessage) flags.push(`error "${capValue(field.invalidMessage, 120)}"`);
357
419
  return `- ${capValue(field.label, 80) || field.reference} (${field.reference}, ${field.kind}): ${value}${flags.length > 0 ? ` · ${flags.join(" · ")}` : ""}`;
358
420
  };
421
+ const ROWS_OPEN_LINE = "Rows open with actOnScreen (action openRow, reference row.<key>).";
422
+ const formatSortColumns = (sortColumns) => {
423
+ if (sortColumns.length === 0) return null;
424
+ const shown = sortColumns.map((column) => `${column.reference} "${capValue(column.label, 40)}"${column.direction ? ` (${column.direction})` : ""}`);
425
+ return `Sort (actOnScreen, action sort): ${shown.join(" · ")}`;
426
+ };
359
427
  const formatTable = (table, maxRows = MAX_TABLE_ROWS) => {
360
428
  const lines = [];
361
429
  const shownRows = table.rows.slice(0, maxRows);
@@ -371,6 +439,9 @@ const formatTable = (table, maxRows = MAX_TABLE_ROWS) => {
371
439
  lines.push(`| ${row.reference}${row.selected ? " (selected)" : ""} | ${cells.join(" | ")} |`);
372
440
  }
373
441
  if (table.totalRows > shownRows.length) lines.push(`… ${table.totalRows - shownRows.length} more rows on screen`);
442
+ const sortLine = formatSortColumns(table.sortColumns ?? []);
443
+ if (sortLine) lines.push(sortLine);
444
+ if (table.rowsOpen && shownRows.length > 0) lines.push(ROWS_OPEN_LINE);
374
445
  return lines;
375
446
  };
376
447
  const formatButtons = (buttons) => {
@@ -379,6 +450,11 @@ const formatButtons = (buttons) => {
379
450
  const more = buttons.length > MAX_BUTTONS ? ` · … ${buttons.length - MAX_BUTTONS} more` : "";
380
451
  return `Buttons: ${shown.join(" · ")}${more}`;
381
452
  };
453
+ const formatActions = (actions) => {
454
+ if (actions.length === 0) return null;
455
+ const shown = actions.slice(0, MAX_BUTTONS).map((action) => `${action.reference} "${capValue(action.label, 40)}"${action.disabled ? " (disabled)" : ""}`);
456
+ return `Actions (actOnScreen, action press): ${shown.join(" · ")}`;
457
+ };
382
458
  const joinScreenParts = (parts, maxChars) => {
383
459
  const text = parts.filter((part) => part !== "").join("\n");
384
460
  if (text.length <= maxChars) return text;
@@ -399,8 +475,23 @@ const AGENT_ATTRIBUTES = {
399
475
  /** The key of a main menu entry (@mgamadeus/ddd-admin-ui): `nav.<value>` */
400
476
  navKey: "data-nav-key",
401
477
  /** The key of a main menu group (@mgamadeus/ddd-admin-ui): `nav.<value>`; its entries sit inside it */
402
- navGroup: "data-nav-group"
478
+ navGroup: "data-nav-group",
479
+ /**
480
+ * What the agent may do with the element (`actOnScreen`): `sort` (a column's sort control), `open` (a row or card
481
+ * that opens its record), `tab` (a tab), `press` (a button). Set by @mgamadeus/ddd-admin-ui on its tables, cards
482
+ * and tabs, by the application on its own buttons. An element without it is never acted on.
483
+ */
484
+ action: "data-agent-action",
485
+ /** The stable key of a declared element: the sort key (`col.<value>`), the tab id, the button (`act.<value>`) */
486
+ actionKey: "data-agent-action-key",
487
+ /** Only on `press`: `view` (changes what the screen shows, nothing stored). Anything else counts as a write and is refused. */
488
+ actionEffect: "data-agent-action-effect"
403
489
  };
490
+ const AGENT_ACTIONS = { sort: "sort", open: "open", tab: "tab", press: "press" };
491
+ const AGENT_ACTION_EFFECT_VIEW = "view";
492
+ const DECLARED_TAB_SELECTOR = `[${AGENT_ATTRIBUTES.action}="${AGENT_ACTIONS.tab}"]`;
493
+ const DECLARED_SORT_SELECTOR = `[${AGENT_ATTRIBUTES.action}="${AGENT_ACTIONS.sort}"]`;
494
+ const DECLARED_PRESS_SELECTOR = `[${AGENT_ATTRIBUTES.action}="${AGENT_ACTIONS.press}"]`;
404
495
  const SKIPPED_SELECTOR = `[${AGENT_ATTRIBUTES.skip}], script, style, noscript, template, svg, [aria-hidden="true"], [hidden]`;
405
496
  const SECRET_FIELD_SELECTOR = `[${AGENT_ATTRIBUTES.secret}] , input[type="password"], input[autocomplete="one-time-code"]`;
406
497
  const FIELD_SELECTOR = 'input:not([type="hidden"]):not([type="submit"]):not([type="button"]), textarea, select, [role="combobox"], [role="switch"], [role="checkbox"], [role="radiogroup"]';
@@ -432,6 +523,31 @@ class ScreenReferenceRegistry {
432
523
  const element = this.elements.get(reference);
433
524
  return element?.isConnected ? element : null;
434
525
  }
526
+ /** Adds one reference to the newest read (an element found without a read, so the highlighter can mark it). */
527
+ remember(reference, element) {
528
+ this.elements.set(reference, element);
529
+ }
530
+ /**
531
+ * A declared element found on the page even without a read: `col.<key>` (sort), `t.<key>` (tab), `act.<key>`
532
+ * (press) by its action key, `row.<key>` by its row key. Null for every other reference.
533
+ */
534
+ findDeclared(reference) {
535
+ const separator = reference.indexOf(".");
536
+ if (separator <= 0) return null;
537
+ const key = reference.slice(separator + 1);
538
+ const selector = {
539
+ col: `[${AGENT_ATTRIBUTES.action}="${AGENT_ACTIONS.sort}"][${AGENT_ATTRIBUTES.actionKey}]`,
540
+ t: `[${AGENT_ATTRIBUTES.action}="${AGENT_ACTIONS.tab}"][${AGENT_ATTRIBUTES.actionKey}]`,
541
+ act: `[${AGENT_ATTRIBUTES.action}="${AGENT_ACTIONS.press}"][${AGENT_ATTRIBUTES.actionKey}]`,
542
+ row: `[${AGENT_ATTRIBUTES.rowKey}]`
543
+ }[reference.slice(0, separator)];
544
+ if (!selector) return null;
545
+ const keyAttribute = reference.startsWith("row.") ? AGENT_ATTRIBUTES.rowKey : AGENT_ATTRIBUTES.actionKey;
546
+ for (const element of Array.from(document.querySelectorAll(selector))) {
547
+ if (slugOf(element.getAttribute(keyAttribute) ?? "") === slugOf(key) && !element.closest(`[${AGENT_ATTRIBUTES.skip}]`)) return element;
548
+ }
549
+ return null;
550
+ }
435
551
  /** An anchor is found on the page even without a read. */
436
552
  findAnchor(reference) {
437
553
  if (!reference.startsWith("a.")) return null;
@@ -453,6 +569,13 @@ const isRendered = (element) => {
453
569
  return true;
454
570
  };
455
571
  const isChecked = (checkbox) => checkbox instanceof HTMLInputElement ? checkbox.checked : checkbox.getAttribute("aria-checked") === "true";
572
+ const isOpenableByAgent = (row) => row.getAttribute(AGENT_ATTRIBUTES.action) === AGENT_ACTIONS.open;
573
+ const isPressableByAgent = (button) => button.getAttribute(AGENT_ATTRIBUTES.action) === AGENT_ACTIONS.press && button.getAttribute(AGENT_ATTRIBUTES.actionEffect) === AGENT_ACTION_EFFECT_VIEW;
574
+ const sortDirectionOf = (control) => {
575
+ const ariaSort = control.closest('th, [role="columnheader"]')?.getAttribute("aria-sort");
576
+ return ariaSort === "ascending" ? "asc" : ariaSort === "descending" ? "desc" : null;
577
+ };
578
+ const isOpenTab = (tab) => tab.getAttribute("aria-selected") === "true" || tab.getAttribute("aria-current") !== null || tab.getAttribute("aria-pressed") === "true";
456
579
  const textOf = (element) => {
457
580
  if (!element) return "";
458
581
  const htmlElement = element;
@@ -477,6 +600,7 @@ const labelOfElement = (element) => {
477
600
  if (placeholder) return oneLine(placeholder);
478
601
  return textOf(element).slice(0, 80);
479
602
  };
603
+ const labelOfTab = (tab) => tab.getAttribute("aria-label") ?? textOf(tab);
480
604
  const rowKeyOf = (row, idColumnIndex, rowIndex) => {
481
605
  const rowKey = row.getAttribute(AGENT_ATTRIBUTES.rowKey);
482
606
  if (rowKey) return slugOf(rowKey);
@@ -536,6 +660,8 @@ class DomScreenReader {
536
660
  const unsaved = this.options.describeUnsavedChanges();
537
661
  parts.push(`Unsaved changes: ${unsaved}`);
538
662
  parts.push(this.describeWindow());
663
+ const filters = this.options.describeFilters?.() ?? null;
664
+ if (filters) parts.push(`Filters (actOnScreen, action setFilters): ${oneLine(filters)}`);
539
665
  const root = this.options.findRoot();
540
666
  const dialogs = Array.from(document.querySelectorAll('[role="dialog"], [role="alertdialog"]')).filter(isRendered);
541
667
  for (const dialog of dialogs) {
@@ -543,14 +669,14 @@ class DomScreenReader {
543
669
  parts.push(...this.readContainer(dialog, register));
544
670
  }
545
671
  if (root) {
546
- const tabs = Array.from(root.querySelectorAll('[role="tab"], nav[aria-label] a[aria-current]')).filter((tab) => isRendered(tab) && tab.closest("form, fieldset") === null).slice(0, MAX_PAGE_TABS);
672
+ const tabs = Array.from(root.querySelectorAll(`[role="tab"], ${DECLARED_TAB_SELECTOR}, nav[aria-label] a[aria-current]`)).filter((tab) => isRendered(tab) && tab.closest("form, fieldset") === null).slice(0, MAX_PAGE_TABS);
547
673
  if (tabs.length > 0) {
548
674
  const tabNames = tabs.map((tab) => {
549
- const reference = register(`t.${slugOf(textOf(tab))}`, tab);
550
- const current = tab.getAttribute("aria-selected") === "true" || tab.getAttribute("aria-current") !== null;
551
- return `${reference} "${capValue(textOf(tab), 40)}"${current ? " (open)" : ""}`;
675
+ const reference = register(`t.${slugOf(tab.getAttribute(AGENT_ATTRIBUTES.actionKey) ?? textOf(tab))}`, tab);
676
+ return `${reference} "${capValue(labelOfTab(tab), 40)}"${isOpenTab(tab) ? " (open)" : ""}`;
552
677
  });
553
- parts.push(`Tabs: ${tabNames.join(" · ")}`);
678
+ const switchable = tabs.some((tab) => tab.matches(`[role="tab"], ${DECLARED_TAB_SELECTOR}`));
679
+ parts.push(`Tabs${switchable ? " (actOnScreen, action switchTab)" : ""}: ${tabNames.join(" · ")}`);
554
680
  }
555
681
  const messages = Array.from(root.querySelectorAll('[role="alert"], [role="status"]')).filter(isRendered);
556
682
  for (const message of messages) {
@@ -667,19 +793,25 @@ ${menu}`, route: location.route, title: location.title, references };
667
793
  lines.push(formatFieldLine(facts));
668
794
  }
669
795
  const buttons = [];
670
- for (const button of Array.from(container.querySelectorAll(BUTTON_SELECTOR))) {
796
+ const actions = [];
797
+ for (const button of Array.from(container.querySelectorAll(`${BUTTON_SELECTOR}, ${DECLARED_PRESS_SELECTOR}`))) {
671
798
  if (seen.has(button) || !isRendered(button) || button.closest('table, [role="grid"], [role="tablist"]')) continue;
799
+ if (button.matches(DECLARED_TAB_SELECTOR) && button.closest("form, fieldset") === null) continue;
672
800
  seen.add(button);
673
801
  const label = labelOfElement(button);
674
802
  if (label === "") continue;
675
- buttons.push({
676
- reference: register(`b.${slugOf(label)}`, button),
677
- label,
678
- disabled: button.hasAttribute("disabled") || button.getAttribute("aria-disabled") === "true"
679
- });
803
+ const disabled = button.hasAttribute("disabled") || button.getAttribute("aria-disabled") === "true";
804
+ const actionKey = isPressableByAgent(button) ? button.getAttribute(AGENT_ATTRIBUTES.actionKey) : null;
805
+ if (actionKey) {
806
+ actions.push({ reference: register(`act.${slugOf(actionKey)}`, button), label, disabled });
807
+ continue;
808
+ }
809
+ buttons.push({ reference: register(`b.${slugOf(label)}`, button), label, disabled });
680
810
  }
681
811
  const buttonLine = formatButtons(buttons);
682
812
  if (buttonLine) lines.push(buttonLine);
813
+ const actionLine = formatActions(actions);
814
+ if (actionLine) lines.push(actionLine);
683
815
  return lines;
684
816
  }
685
817
  /** The tables of a container and the cards of a card grid (`EntityListGrid` sets `data-row-key` on each). */
@@ -703,6 +835,7 @@ ${menu}`, route: location.route, title: location.title, references };
703
835
  lines.push(`- ${register(`row.${rowKeyOf(card, null, 0)}`, card)}${selected}: ${capValue(textOf(card), 160)}`);
704
836
  }
705
837
  if (cards.length > MAX_TABLE_ROWS) lines.push(`… ${cards.length - MAX_TABLE_ROWS} more cards on screen`);
838
+ if (cards.some(isOpenableByAgent)) lines.push(ROWS_OPEN_LINE);
706
839
  }
707
840
  return lines;
708
841
  }
@@ -757,7 +890,20 @@ ${menu}`, route: location.route, title: location.title, references };
757
890
  }),
758
891
  selected: row.getAttribute("aria-selected") === "true" || row.getAttribute("data-state") === "selected" || this.isRowChecked(row)
759
892
  }));
760
- return { caption: textOf(table.querySelector("caption")) || table.getAttribute("aria-label"), columns, rows, totalRows: bodyRows.length };
893
+ const sortColumns = [];
894
+ for (const control of Array.from(table.querySelectorAll(DECLARED_SORT_SELECTOR))) {
895
+ const sortKey = control.getAttribute(AGENT_ATTRIBUTES.actionKey);
896
+ if (!sortKey || !isRendered(control)) continue;
897
+ sortColumns.push({ reference: register(`col.${slugOf(sortKey)}`, control), label: labelOfElement(control), direction: sortDirectionOf(control) });
898
+ }
899
+ return {
900
+ caption: textOf(table.querySelector("caption")) || table.getAttribute("aria-label"),
901
+ columns,
902
+ rows,
903
+ totalRows: bodyRows.length,
904
+ sortColumns,
905
+ rowsOpen: bodyRows.some(isOpenableByAgent)
906
+ };
761
907
  }
762
908
  /** Whether the row's selection checkbox is checked. */
763
909
  isRowChecked(row) {
@@ -947,6 +1093,157 @@ class DomScreenHighlighter {
947
1093
  }, 50);
948
1094
  }
949
1095
  }
1096
+ const ACTION_MARK_BEAT_MS = 700;
1097
+ const MAX_SORT_CLICKS = 3;
1098
+ const SORT_CHANGE_WAIT_MS = 1500;
1099
+ const OPEN_DIALOG_SELECTOR = '[role="dialog"], [role="alertdialog"]';
1100
+ const DECLARATION_OF_ACTION = {
1101
+ sort: AGENT_ACTIONS.sort,
1102
+ openRow: AGENT_ACTIONS.open,
1103
+ switchTab: AGENT_ACTIONS.tab,
1104
+ press: AGENT_ACTIONS.press
1105
+ };
1106
+ const wait = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
1107
+ const nextFrame = () => new Promise((resolve) => {
1108
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(() => resolve());
1109
+ else setTimeout(resolve, 16);
1110
+ });
1111
+ const refusal = (outcome, text = "") => ({ outcome, text, details: {} });
1112
+ const isDisabled = (element) => element.hasAttribute("disabled") || element.getAttribute("aria-disabled") === "true";
1113
+ const activateElement = (element) => {
1114
+ const init = { bubbles: true, cancelable: true, composed: true, button: 0 };
1115
+ const PointerEventClass = typeof PointerEvent === "function" ? PointerEvent : MouseEvent;
1116
+ element.dispatchEvent(new PointerEventClass("pointerdown", init));
1117
+ element.dispatchEvent(new MouseEvent("mousedown", init));
1118
+ element.dispatchEvent(new PointerEventClass("pointerup", init));
1119
+ element.dispatchEvent(new MouseEvent("mouseup", init));
1120
+ if (typeof element.click === "function") element.click();
1121
+ else element.dispatchEvent(new MouseEvent("click", init));
1122
+ };
1123
+ class DomScreenActor {
1124
+ constructor(options) {
1125
+ this.options = options;
1126
+ }
1127
+ async act(request) {
1128
+ const element = this.options.registry.find(request.reference) ?? this.options.registry.findDeclared(request.reference);
1129
+ if (!element) return refusal(CLIENT_TOOL_OUTCOMES.notOnScreen);
1130
+ const declarationRefusal = this.checkDeclaration(request, element);
1131
+ if (declarationRefusal) return declarationRefusal;
1132
+ if (isDisabled(element)) return refusal(CLIENT_TOOL_OUTCOMES.disabled, this.name(request.reference, element));
1133
+ const blockerRefusal = this.checkBlockers(request, element);
1134
+ if (blockerRefusal) return blockerRefusal;
1135
+ const label = labelOfElement(element);
1136
+ const routeBefore = this.options.currentLocation().route;
1137
+ if (request.action === "switchTab" && isOpenTab(element)) {
1138
+ return this.done(`Tab ${this.name(request.reference, element)} is open already.`, routeBefore);
1139
+ }
1140
+ if (request.action === "sort" && this.sortOf(element) === request.direction) {
1141
+ return this.done(`${this.name(request.reference, element)} is sorted ${this.describeDirection(request.direction)} already.`, routeBefore);
1142
+ }
1143
+ await this.markBeforeActing(request, element, label);
1144
+ if (request.action === "sort") {
1145
+ const reached = await this.sort(request.reference, element, request.direction ?? "asc");
1146
+ if (!reached) return refusal(CLIENT_TOOL_OUTCOMES.noEffect, this.name(request.reference, element));
1147
+ await this.settle();
1148
+ return this.done(`Sorted by ${this.name(request.reference, element)} ${this.describeDirection(request.direction)}.`, routeBefore);
1149
+ }
1150
+ activateElement(element);
1151
+ await this.settle();
1152
+ const sentence = {
1153
+ openRow: `Opened ${this.nameOf(request.reference, label)}.`,
1154
+ switchTab: `Switched to tab ${this.nameOf(request.reference, label)}.`,
1155
+ press: `Pressed ${this.nameOf(request.reference, label)}.`
1156
+ }[request.action];
1157
+ return this.done(sentence, routeBefore);
1158
+ }
1159
+ /** The element must declare the action of the request; a button must declare the effect `view`. */
1160
+ checkDeclaration(request, element) {
1161
+ const declared = element.getAttribute(AGENT_ATTRIBUTES.action);
1162
+ if (request.action === "switchTab") {
1163
+ return declared === AGENT_ACTIONS.tab || element.getAttribute("role") === "tab" ? null : this.notDeclared(request, element);
1164
+ }
1165
+ if (request.action === "openRow") return isOpenableByAgent(element) ? null : this.notDeclared(request, element);
1166
+ if (request.action === "sort") {
1167
+ if (declared !== AGENT_ACTIONS.sort) return this.notDeclared(request, element);
1168
+ return request.direction === null ? refusal(CLIENT_TOOL_OUTCOMES.missingParameter) : null;
1169
+ }
1170
+ if (declared !== DECLARATION_OF_ACTION.press) return this.notDeclared(request, element);
1171
+ return isPressableByAgent(element) ? null : refusal(CLIENT_TOOL_OUTCOMES.writeAction, this.name(request.reference, element));
1172
+ }
1173
+ notDeclared(request, element) {
1174
+ return refusal(CLIENT_TOOL_OUTCOMES.notDeclared, this.name(request.reference, element));
1175
+ }
1176
+ /**
1177
+ * Unsaved changes refuse what leaves the screen; an open dialog refuses every element outside it and what leaves
1178
+ * the screen inside it.
1179
+ */
1180
+ checkBlockers(request, element) {
1181
+ const blocker = this.options.describeBlockers();
1182
+ if (!blocker) return null;
1183
+ const leavesScreen = request.action === "openRow" || request.action === "switchTab" && element.matches("a[href]");
1184
+ if (blocker.outcome === CLIENT_TOOL_OUTCOMES.dialogOpen) {
1185
+ return element.closest(OPEN_DIALOG_SELECTOR) === null || leavesScreen ? { outcome: blocker.outcome, text: blocker.reason, details: {} } : null;
1186
+ }
1187
+ return leavesScreen ? { outcome: blocker.outcome, text: blocker.reason, details: {} } : null;
1188
+ }
1189
+ /** Marks the element with the application's note and waits the beat; a failing highlighter never stops the action. */
1190
+ async markBeforeActing(request, element, label) {
1191
+ const highlighter = this.options.highlighter;
1192
+ if (!highlighter) return;
1193
+ try {
1194
+ this.options.registry.remember(request.reference, element);
1195
+ highlighter.mark([request.reference], this.options.describeAction?.(request.action, label) ?? null);
1196
+ } catch {
1197
+ return;
1198
+ }
1199
+ await wait(this.options.markBeatMs ?? ACTION_MARK_BEAT_MS);
1200
+ }
1201
+ /** Clicks the sort control until its column shows the wanted direction; false when it never does. */
1202
+ async sort(reference, control, direction) {
1203
+ let current = control;
1204
+ for (let click = 0; click < MAX_SORT_CLICKS; click += 1) {
1205
+ if (this.sortOf(current) === direction) return true;
1206
+ const before = this.sortOf(current);
1207
+ activateElement(current);
1208
+ const startedAt = Date.now();
1209
+ do {
1210
+ await nextFrame();
1211
+ current = current.isConnected ? current : this.options.registry.findDeclared(reference) ?? current;
1212
+ } while (this.sortOf(current) === before && Date.now() - startedAt < SORT_CHANGE_WAIT_MS);
1213
+ if (this.sortOf(current) === before) return false;
1214
+ }
1215
+ return this.sortOf(current) === direction;
1216
+ }
1217
+ /** The sort a control shows, in the words of the request (`none` when its column is not sorted). */
1218
+ sortOf(control) {
1219
+ return sortDirectionOf(control) ?? "none";
1220
+ }
1221
+ describeDirection(direction) {
1222
+ return direction === "asc" ? "ascending" : direction === "desc" ? "descending" : "in the list's own order";
1223
+ }
1224
+ async settle() {
1225
+ if (this.options.settle) {
1226
+ await this.options.settle();
1227
+ return;
1228
+ }
1229
+ await nextFrame();
1230
+ await nextFrame();
1231
+ }
1232
+ done(text, routeBefore) {
1233
+ const location = this.options.currentLocation();
1234
+ return {
1235
+ outcome: CLIENT_TOOL_OUTCOMES.ok,
1236
+ text,
1237
+ details: { route: location.route, title: location.title, routeChanged: location.route !== routeBefore }
1238
+ };
1239
+ }
1240
+ name(reference, element) {
1241
+ return this.nameOf(reference, labelOfElement(element));
1242
+ }
1243
+ nameOf(reference, label) {
1244
+ return label === "" ? reference : `${reference} "${capValue(label, 80)}"`;
1245
+ }
1246
+ }
950
1247
  const AGENT_ANCHOR_ATTRIBUTE = "data-agent-anchor";
951
1248
  const AGENT_ANCHOR_GROUP_ATTRIBUTE = "data-agent-anchor-group";
952
1249
  const listAttribute = (element, attributeName) => (element.getAttribute(attributeName) ?? "").split(",").map((part) => part.trim()).filter((part) => part !== "");
@@ -1382,7 +1679,7 @@ const createDomScreenPictureCapturer = (options = {}) => ({
1382
1679
  });
1383
1680
  const createAgentWindowAdapter = (options) => {
1384
1681
  const asideMode = options.asideMode ?? "aside";
1385
- const stepAsideFor = options.stepAsideFor ?? ["OPEN_TARGET", "HIGHLIGHT", "READ_SCREEN"];
1682
+ const stepAsideFor = options.stepAsideFor ?? ["OPEN_TARGET", "HIGHLIGHT", "READ_SCREEN", "ACT_ON_SCREEN"];
1386
1683
  let modeBeforeAside = null;
1387
1684
  return {
1388
1685
  stepAside: async () => {
@@ -1541,6 +1838,9 @@ const createAccountRealtimePoll = (options) => {
1541
1838
  export {
1542
1839
  ACCOUNT_REALTIME_PING_REREAD_DELAY_MS,
1543
1840
  ACCOUNT_REALTIME_POLL_INTERVAL_MS,
1841
+ ACTION_MARK_BEAT_MS,
1842
+ AGENT_ACTIONS,
1843
+ AGENT_ACTION_EFFECT_VIEW,
1544
1844
  AGENT_ANCHOR_ATTRIBUTE,
1545
1845
  AGENT_ANCHOR_GROUP_ATTRIBUTE,
1546
1846
  AGENT_ATTRIBUTES,
@@ -1552,6 +1852,7 @@ export {
1552
1852
  b as CLIENT_TOOL_REQUEST_PING_REREAD_DELAY_MS,
1553
1853
  ClientToolRequestRunner,
1554
1854
  DEFAULT_GUIDES_PER_TARGET,
1855
+ DomScreenActor,
1555
1856
  DomScreenHighlighter,
1556
1857
  DomScreenReader,
1557
1858
  HIDDEN_VALUE,
@@ -1575,11 +1876,15 @@ export {
1575
1876
  PATH_GUIDE_COUNT_KEY_PREFIX,
1576
1877
  PATH_GUIDE_STEP_MS,
1577
1878
  PICTURE_LIMITATIONS,
1879
+ ROWS_OPEN_LINE,
1578
1880
  ReferenceNames,
1881
+ SCREEN_ACTION_KINDS,
1579
1882
  SCREEN_PICTURE_PRESETS,
1883
+ SCREEN_SORT_DIRECTIONS,
1580
1884
  SIDE_PANEL_MIN_HEIGHT_SHARE,
1581
1885
  ScreenReferenceRegistry,
1582
1886
  a as acceptArrivedRealtimeMessage,
1887
+ activateElement,
1583
1888
  buildTargetRoute,
1584
1889
  capAnswerText,
1585
1890
  capValue,
@@ -1596,12 +1901,17 @@ export {
1596
1901
  createFrameDefaultStyleSource,
1597
1902
  createGuideCounter,
1598
1903
  fieldReferenceNameOf,
1904
+ formatActions,
1599
1905
  formatButtons,
1600
1906
  formatFieldLine,
1601
1907
  formatScreenTargetLine,
1602
1908
  formatScreenTargetList,
1909
+ formatSortColumns,
1603
1910
  formatTable,
1604
1911
  isClientToolToken,
1912
+ isOpenTab,
1913
+ isOpenableByAgent,
1914
+ isPressableByAgent,
1605
1915
  joinScreenParts,
1606
1916
  labelOfElement,
1607
1917
  oneLine,
@@ -1614,6 +1924,7 @@ export {
1614
1924
  rowKeyOf,
1615
1925
  e as runClientToolRequestForDevelopment,
1616
1926
  slugOf,
1927
+ sortDirectionOf,
1617
1928
  useAgentUIClient
1618
1929
  };
1619
1930
  //# sourceMappingURL=ui.js.map