@mgamadeus/ddd-agents 0.4.1 → 0.5.0

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
@@ -1,5 +1,6 @@
1
1
  "use client";
2
2
  import { useRef } from "react";
3
+ import { C, a, r, b } from "./chunks/realtime-arrival-DUJjwt2M.js";
3
4
  const MIN_SECONDS_LEFT_TO_START = 3;
4
5
  const MAX_ANSWER_TEXT_CHARS = 24e3;
5
6
  const CLIENT_TOOL_OUTCOMES = {
@@ -14,7 +15,9 @@ const CLIENT_TOOL_OUTCOMES = {
14
15
  notOnScreen: "NOT_ON_SCREEN",
15
16
  expiredBeforeStart: "EXPIRED_BEFORE_START",
16
17
  readFailed: "READ_FAILED",
17
- unknownRequest: "UNKNOWN_REQUEST"
18
+ unknownRequest: "UNKNOWN_REQUEST",
19
+ unknownMode: "UNKNOWN_MODE",
20
+ pictureUnavailable: "PICTURE_UNAVAILABLE"
18
21
  };
19
22
  const parseClientToolArguments = (argumentsJson) => {
20
23
  try {
@@ -74,6 +77,10 @@ const createAgentUIClientId = () => {
74
77
  const randomPart = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
75
78
  return `ui-${randomPart}`.slice(0, 64);
76
79
  };
80
+ const PACKAGE_REQUEST_TYPES = ["READ_SCREEN", "LIST_TARGETS", "OPEN_TARGET", "HIGHLIGHT", "SET_WINDOW_MODE"];
81
+ const STEP_ASIDE_REQUEST_TYPES = ["OPEN_TARGET", "HIGHLIGHT", "READ_SCREEN"];
82
+ const PICTURE_SIZES = ["small", "medium", "large"];
83
+ const RENDER_MODES = ["colour", "greyscale", "machine"];
77
84
  const MAX_SCREEN_CHARS = 6e3;
78
85
  const REMEMBERED_REQUEST_IDS = 50;
79
86
  class ClientToolRequestRunner {
@@ -112,20 +119,77 @@ class ClientToolRequestRunner {
112
119
  try {
113
120
  switch (delivery.requestType) {
114
121
  case "READ_SCREEN":
122
+ if (parameters.format === "picture") {
123
+ await this.stepAgentWindowAside("READ_SCREEN");
124
+ try {
125
+ return await this.readScreenPicture(parameters);
126
+ } finally {
127
+ await this.adapters.agentWindow?.restore();
128
+ }
129
+ }
115
130
  return this.readScreen(parameters);
116
131
  case "LIST_TARGETS":
117
132
  return this.listTargets(parameters);
118
133
  case "OPEN_TARGET":
119
134
  return await this.openTarget(parameters);
120
135
  case "HIGHLIGHT":
136
+ await this.stepAgentWindowAside("HIGHLIGHT");
121
137
  return this.highlight(parameters);
138
+ case "SET_WINDOW_MODE":
139
+ return await this.setWindowMode(parameters);
122
140
  default:
123
- return refusal(CLIENT_TOOL_OUTCOMES.unknownRequest);
141
+ return await this.runRequestOfApplication(delivery, parameters);
124
142
  }
125
143
  } catch {
126
144
  return refusal(CLIENT_TOOL_OUTCOMES.readFailed);
127
145
  }
128
146
  }
147
+ /** A request type the application registered: its handler, else `UNKNOWN_REQUEST`. */
148
+ async runRequestOfApplication(delivery, parameters) {
149
+ const handler = PACKAGE_REQUEST_TYPES.includes(delivery.requestType) ? void 0 : this.adapters.requestHandlers?.[delivery.requestType];
150
+ if (!handler) return refusal(CLIENT_TOOL_OUTCOMES.unknownRequest);
151
+ return handler(parameters, delivery);
152
+ }
153
+ /** Lets the agent window make room before the agent works on the screen (the default for the screen requests). */
154
+ async stepAgentWindowAside(requestType) {
155
+ const agentWindow = this.adapters.agentWindow;
156
+ if (!agentWindow) return;
157
+ const shouldStepAside = agentWindow.shouldStepAsideBefore ? agentWindow.shouldStepAsideBefore(requestType) : STEP_ASIDE_REQUEST_TYPES.includes(requestType);
158
+ if (shouldStepAside) await agentWindow.stepAside(requestType);
159
+ }
160
+ async setWindowMode(parameters) {
161
+ const agentWindow = this.adapters.agentWindow;
162
+ if (!agentWindow || !isClientToolToken(parameters.mode)) return refusal(CLIENT_TOOL_OUTCOMES.unknownMode);
163
+ if (parameters.mode === "restore") {
164
+ await agentWindow.restore();
165
+ return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: "", details: { mode: "restore" } };
166
+ }
167
+ const accepted = await agentWindow.setMode(parameters.mode);
168
+ if (!accepted) return refusal(CLIENT_TOOL_OUTCOMES.unknownMode);
169
+ return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: "", details: { mode: parameters.mode } };
170
+ }
171
+ async readScreenPicture(parameters) {
172
+ const capturer = this.adapters.picture;
173
+ if (!capturer) return refusal(CLIENT_TOOL_OUTCOMES.pictureUnavailable);
174
+ const pictureSize = PICTURE_SIZES.find((size) => size === parameters.pictureSize) ?? "medium";
175
+ const renderMode = RENDER_MODES.find((mode) => mode === parameters.renderMode) ?? "colour";
176
+ const picture = await capturer.capture({ pictureSize, renderMode });
177
+ if (!picture) return refusal(CLIENT_TOOL_OUTCOMES.pictureUnavailable);
178
+ const location = this.adapters.navigator.currentLocation();
179
+ return {
180
+ outcome: CLIENT_TOOL_OUTCOMES.ok,
181
+ text: "",
182
+ details: {
183
+ route: location.route,
184
+ visible: this.adapters.isVisible(),
185
+ width: picture.width,
186
+ height: picture.height,
187
+ bytes: picture.byteSize,
188
+ renderMode
189
+ },
190
+ pictureBase64: picture.base64
191
+ };
192
+ }
129
193
  readScreen(parameters) {
130
194
  const focus = isClientToolToken(parameters.focus) ? parameters.focus : void 0;
131
195
  const snapshot = this.adapters.reader.read({ focus, maxChars: MAX_SCREEN_CHARS });
@@ -160,7 +224,13 @@ class ClientToolRequestRunner {
160
224
  if (buildTargetRoute(target, recordIds, tab) === null) return refusal(CLIENT_TOOL_OUTCOMES.missingParameter);
161
225
  const blocker = this.adapters.navigator.describeBlockers();
162
226
  if (blocker) return { outcome: blocker.outcome, text: blocker.reason, details: {} };
163
- const location = await this.adapters.navigator.open(target, { recordIds, tab, filters });
227
+ await this.stepAgentWindowAside("OPEN_TARGET");
228
+ const openRequest = { recordIds, tab, filters };
229
+ try {
230
+ this.adapters.pathGuide?.guide(target, openRequest);
231
+ } catch {
232
+ }
233
+ const location = await this.adapters.navigator.open(target, openRequest);
164
234
  const details = { route: location.route, title: location.title };
165
235
  if (parameters.includeScreen !== true) return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: "", details };
166
236
  const snapshot = this.adapters.reader.read({ maxChars: MAX_SCREEN_CHARS });
@@ -227,6 +297,12 @@ const useAgentUIClient = (adapters, uiStateSource = null) => {
227
297
  },
228
298
  isVisible: () => adaptersRef.current.isVisible()
229
299
  };
300
+ Object.defineProperties(latestAdapters, {
301
+ picture: { enumerable: true, get: () => adaptersRef.current.picture },
302
+ agentWindow: { enumerable: true, get: () => adaptersRef.current.agentWindow },
303
+ pathGuide: { enumerable: true, get: () => adaptersRef.current.pathGuide },
304
+ requestHandlers: { enumerable: true, get: () => adaptersRef.current.requestHandlers }
305
+ });
230
306
  clientRef.current = new AgentUIClient(latestAdapters, { readUIState: () => uiStateSourceRef.current?.readUIState() ?? null });
231
307
  }
232
308
  return clientRef.current;
@@ -719,29 +795,429 @@ class DomScreenHighlighter {
719
795
  }, 50);
720
796
  }
721
797
  }
798
+ const AGENT_ANCHOR_ATTRIBUTE = "data-agent-anchor";
799
+ const AGENT_ANCHOR_GROUP_ATTRIBUTE = "data-agent-anchor-group";
800
+ const listAttribute = (element, attributeName) => (element.getAttribute(attributeName) ?? "").split(",").map((part) => part.trim()).filter((part) => part !== "");
801
+ const routeOfMark = (element) => {
802
+ const route = element.getAttribute("data-agent-route");
803
+ if (route) return route;
804
+ const href = element.getAttribute("href");
805
+ if (!href) return null;
806
+ try {
807
+ const url = new URL(href, "http://screen.invalid");
808
+ return url.pathname;
809
+ } catch {
810
+ return null;
811
+ }
812
+ };
813
+ const readScreenTargetOfMark = (element) => {
814
+ const key = element.getAttribute(AGENT_ANCHOR_ATTRIBUTE)?.trim() ?? "";
815
+ if (!isClientToolToken(key)) return null;
816
+ const routePattern = routeOfMark(element);
817
+ if (!routePattern) return null;
818
+ const label = (element.getAttribute("data-agent-label") ?? element.textContent ?? "").replace(/\s+/g, " ").trim() || key;
819
+ return {
820
+ key,
821
+ label,
822
+ group: element.getAttribute("data-agent-group")?.trim() || null,
823
+ routePattern,
824
+ parameters: listAttribute(element, "data-agent-parameters"),
825
+ tabs: listAttribute(element, "data-agent-tabs"),
826
+ filters: listAttribute(element, "data-agent-filters").map((filterKey) => ({ key: filterKey })),
827
+ views: listAttribute(element, "data-agent-views")
828
+ };
829
+ };
830
+ const createDomScreenTargetSource = (options = {}) => ({
831
+ listTargets: () => {
832
+ const root = options.root?.() ?? (typeof document !== "undefined" ? document : null);
833
+ if (!root) return [];
834
+ const targets = [];
835
+ const seenKeys = /* @__PURE__ */ new Set();
836
+ for (const element of Array.from(root.querySelectorAll(`[${AGENT_ANCHOR_ATTRIBUTE}]`))) {
837
+ if (options.groupKey !== void 0 && element.getAttribute(AGENT_ANCHOR_GROUP_ATTRIBUTE) !== options.groupKey) continue;
838
+ const target = readScreenTargetOfMark(element);
839
+ if (!target || seenKeys.has(target.key)) continue;
840
+ seenKeys.add(target.key);
841
+ targets.push(target);
842
+ }
843
+ return targets;
844
+ }
845
+ });
846
+ const DEFAULT_GUIDES_PER_TARGET = 2;
847
+ const PATH_GUIDE_COUNT_KEY_PREFIX = "ddd-agents:pathGuide:";
848
+ const PATH_GUIDE_STEP_MS = 700;
849
+ const PATH_GUIDE_CLASS = "agents-path-guide-step";
850
+ const createGuideCounter = (limit = DEFAULT_GUIDES_PER_TARGET, readStorage = () => window.localStorage) => {
851
+ const counts = /* @__PURE__ */ new Map();
852
+ return (targetKey) => {
853
+ const storageKey = `${PATH_GUIDE_COUNT_KEY_PREFIX}${targetKey}`;
854
+ let count = counts.get(targetKey) ?? 0;
855
+ try {
856
+ count = Math.max(count, Number.parseInt(readStorage()?.getItem(storageKey) ?? "0", 10) || 0);
857
+ } catch {
858
+ }
859
+ if (count >= limit) return false;
860
+ counts.set(targetKey, count + 1);
861
+ try {
862
+ readStorage()?.setItem(storageKey, String(count + 1));
863
+ } catch {
864
+ }
865
+ return true;
866
+ };
867
+ };
868
+ const PATH_GUIDE_OUTLINE = "2px solid var(--ring, #2563eb)";
869
+ const markStep = (element, outlinesBefore) => {
870
+ element.classList.add(PATH_GUIDE_CLASS);
871
+ if (element instanceof HTMLElement) {
872
+ outlinesBefore.set(element, element.style.outline);
873
+ element.style.outline = PATH_GUIDE_OUTLINE;
874
+ }
875
+ };
876
+ const unmarkStep = (element, outlinesBefore) => {
877
+ element.classList.remove(PATH_GUIDE_CLASS);
878
+ if (element instanceof HTMLElement && outlinesBefore.has(element)) {
879
+ element.style.outline = outlinesBefore.get(element) ?? "";
880
+ outlinesBefore.delete(element);
881
+ }
882
+ };
883
+ const prefersReducedMotion = () => {
884
+ try {
885
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
886
+ } catch {
887
+ return false;
888
+ }
889
+ };
890
+ const createDomScreenPathGuide = (options) => {
891
+ const shouldGuide = options.shouldGuide ?? createGuideCounter();
892
+ const stepMs = options.stepMs ?? PATH_GUIDE_STEP_MS;
893
+ let timers = [];
894
+ let markedElements = [];
895
+ const outlinesBefore = /* @__PURE__ */ new Map();
896
+ let removeListeners = null;
897
+ const cancel = () => {
898
+ timers.forEach((timer) => clearTimeout(timer));
899
+ timers = [];
900
+ markedElements.forEach((element) => unmarkStep(element, outlinesBefore));
901
+ markedElements = [];
902
+ removeListeners?.();
903
+ removeListeners = null;
904
+ };
905
+ const guide = (target, request) => {
906
+ cancel();
907
+ if (prefersReducedMotion()) return false;
908
+ const targetRoute = buildTargetRoute(target, request.recordIds, request.tab);
909
+ const currentRoute = options.currentRoute().split("?")[0];
910
+ if (targetRoute !== null && currentRoute === targetRoute) return false;
911
+ const pathElements = options.findPathElements(target, request).filter((element) => element.isConnected);
912
+ if (pathElements.length === 0) return false;
913
+ if (!shouldGuide(target.key)) return false;
914
+ const onKeyDown = (event) => {
915
+ if (event.key === "Escape") cancel();
916
+ };
917
+ const onPointerDown = () => cancel();
918
+ document.addEventListener("keydown", onKeyDown, true);
919
+ document.addEventListener("pointerdown", onPointerDown, true);
920
+ removeListeners = () => {
921
+ document.removeEventListener("keydown", onKeyDown, true);
922
+ document.removeEventListener("pointerdown", onPointerDown, true);
923
+ };
924
+ pathElements.forEach((element, stepIndex) => {
925
+ timers.push(
926
+ setTimeout(() => {
927
+ markedElements.forEach((marked) => unmarkStep(marked, outlinesBefore));
928
+ markStep(element, outlinesBefore);
929
+ markedElements = [element];
930
+ }, stepIndex * stepMs)
931
+ );
932
+ });
933
+ timers.push(setTimeout(cancel, pathElements.length * stepMs));
934
+ return true;
935
+ };
936
+ return { guide, cancel };
937
+ };
938
+ const PICTURE_LIMITATIONS = [
939
+ "content of other origins (embedded frames, some images and fonts) can be blank or replaced",
940
+ "video, canvas and WebGL content can be blank",
941
+ "password fields show dots; fields the application marks secret or skipped are left out",
942
+ "scrolled-away parts of a scroll container are shown expanded, so the picture can be longer than the window"
943
+ ];
944
+ const SCREEN_PICTURE_PRESETS = {
945
+ small: { maxLongEdge: 1024, maxPixels: 786432, maxBytes: 15e4 },
946
+ medium: { maxLongEdge: 1600, maxPixels: 192e4, maxBytes: 35e4 },
947
+ large: { maxLongEdge: 2048, maxPixels: 375e4, maxBytes: 6e5 }
948
+ };
949
+ const MACHINE_MODE_GREY_LEVELS = 64;
950
+ const MACHINE_MODE_SIZE_FACTOR = 0.75;
951
+ const MACHINE_MODE_BYTE_FACTOR = 0.5;
952
+ const MAX_PICTURE_ENCODE_ATTEMPTS = 4;
953
+ const MAX_PICTURE_ELEMENTS = 8e3;
954
+ const AGENT_SKIP_ATTRIBUTE = "data-agent-skip";
955
+ const AGENT_SECRET_ATTRIBUTE = "data-agent-secret";
956
+ const computePictureByteBudget = (pictureSize, renderMode) => {
957
+ const preset = SCREEN_PICTURE_PRESETS[pictureSize];
958
+ return Math.floor(renderMode === "machine" ? preset.maxBytes * MACHINE_MODE_BYTE_FACTOR : preset.maxBytes);
959
+ };
960
+ const computePictureDimensions = (sourceWidth, sourceHeight, request, retryScale = 1) => {
961
+ const preset = SCREEN_PICTURE_PRESETS[request.pictureSize];
962
+ const safeWidth = Math.max(1, sourceWidth);
963
+ const safeHeight = Math.max(1, sourceHeight);
964
+ let scale = Math.min(1, preset.maxLongEdge / Math.max(safeWidth, safeHeight), Math.sqrt(preset.maxPixels / (safeWidth * safeHeight)));
965
+ if (request.renderMode === "machine") scale *= MACHINE_MODE_SIZE_FACTOR;
966
+ scale *= retryScale;
967
+ return {
968
+ width: Math.max(1, Math.floor(safeWidth * scale)),
969
+ height: Math.max(1, Math.floor(safeHeight * scale)),
970
+ scale
971
+ };
972
+ };
973
+ const computeRetryScale = (previousRetryScale, encodedBytes, byteBudget) => {
974
+ if (encodedBytes <= 0) return previousRetryScale;
975
+ return previousRetryScale * Math.min(0.9, Math.sqrt(byteBudget / encodedBytes) * 0.9);
976
+ };
977
+ const convertPixelsToGrey = (pixels, greyLevels = null) => {
978
+ const levelStep = greyLevels !== null && greyLevels > 1 ? 255 / (greyLevels - 1) : null;
979
+ for (let index = 0; index < pixels.length; index += 4) {
980
+ let grey = 0.2126 * pixels[index] + 0.7152 * pixels[index + 1] + 0.0722 * pixels[index + 2];
981
+ if (levelStep !== null) grey = Math.round(grey / levelStep) * levelStep;
982
+ pixels[index] = grey;
983
+ pixels[index + 1] = grey;
984
+ pixels[index + 2] = grey;
985
+ }
986
+ };
987
+ const isScrollContainer = (element, style) => element.scrollHeight > element.clientHeight + 1 && (style.overflowY === "auto" || style.overflowY === "scroll");
988
+ const copyComputedStyle = (style, clone) => {
989
+ const declarations = [];
990
+ for (let index = 0; index < style.length; index += 1) {
991
+ const property = style.item(index);
992
+ declarations.push(`${property}:${style.getPropertyValue(property)}`);
993
+ }
994
+ clone.setAttribute("style", declarations.join(";"));
995
+ };
996
+ const copyFieldValue = (original, clone) => {
997
+ if (original instanceof HTMLInputElement && clone instanceof HTMLInputElement) {
998
+ if (original.type === "password") {
999
+ clone.setAttribute("value", "•".repeat(Math.min(original.value.length, 24)));
1000
+ clone.type = "text";
1001
+ } else if (original.type === "checkbox" || original.type === "radio") {
1002
+ if (original.checked) clone.setAttribute("checked", "");
1003
+ else clone.removeAttribute("checked");
1004
+ } else {
1005
+ clone.setAttribute("value", original.value);
1006
+ }
1007
+ } else if (original instanceof HTMLTextAreaElement) {
1008
+ clone.textContent = original.value;
1009
+ } else if (original instanceof HTMLSelectElement && clone instanceof HTMLSelectElement) {
1010
+ Array.from(clone.options).forEach((option, optionIndex) => {
1011
+ if (optionIndex === original.selectedIndex) option.setAttribute("selected", "");
1012
+ else option.removeAttribute("selected");
1013
+ });
1014
+ }
1015
+ };
1016
+ const LEFT_OUT_TAGS = /* @__PURE__ */ new Set(["SCRIPT", "NOSCRIPT", "TEMPLATE", "LINK", "META"]);
1017
+ const prepareScreenCloneForPicture = (root, copyStyles = true) => {
1018
+ const clone = root.cloneNode(false);
1019
+ let copiedElements = 0;
1020
+ const copyInto = (original, target) => {
1021
+ const view = original.ownerDocument.defaultView;
1022
+ const style = copyStyles && view ? view.getComputedStyle(original) : null;
1023
+ if (style && (target instanceof HTMLElement || target instanceof SVGElement)) {
1024
+ copyComputedStyle(style, target);
1025
+ if (target instanceof HTMLElement && isScrollContainer(original, style)) {
1026
+ target.style.overflowY = "visible";
1027
+ target.style.height = "auto";
1028
+ target.style.maxHeight = "none";
1029
+ }
1030
+ } else if (!copyStyles && target instanceof HTMLElement && original.scrollHeight > original.clientHeight + 1) {
1031
+ target.style.overflowY = "visible";
1032
+ target.style.height = "auto";
1033
+ target.style.maxHeight = "none";
1034
+ }
1035
+ copyFieldValue(original, target);
1036
+ if (original.hasAttribute(AGENT_SECRET_ATTRIBUTE)) {
1037
+ target.textContent = "";
1038
+ if (target instanceof HTMLElement) target.style.background = "#9e9e9e";
1039
+ return;
1040
+ }
1041
+ if (original instanceof HTMLTextAreaElement) return;
1042
+ for (const childNode of Array.from(original.childNodes)) {
1043
+ if (childNode.nodeType === Node.TEXT_NODE) {
1044
+ target.appendChild(childNode.cloneNode(false));
1045
+ continue;
1046
+ }
1047
+ if (!(childNode instanceof Element)) continue;
1048
+ if (LEFT_OUT_TAGS.has(childNode.tagName) || childNode.hasAttribute(AGENT_SKIP_ATTRIBUTE)) continue;
1049
+ if (copiedElements >= MAX_PICTURE_ELEMENTS) return;
1050
+ copiedElements += 1;
1051
+ const childClone = childNode.cloneNode(false);
1052
+ target.appendChild(childClone);
1053
+ copyInto(childNode, childClone);
1054
+ }
1055
+ };
1056
+ copyInto(root, clone);
1057
+ return clone;
1058
+ };
1059
+ const measureCloneHeight = (clone, width, documentOfRoot) => {
1060
+ const holder = documentOfRoot.createElement("div");
1061
+ holder.setAttribute("aria-hidden", "true");
1062
+ holder.style.cssText = `position:fixed;left:-100000px;top:0;width:${width}px;visibility:hidden;pointer-events:none;`;
1063
+ const measured = clone.cloneNode(true);
1064
+ holder.appendChild(measured);
1065
+ documentOfRoot.body.appendChild(holder);
1066
+ try {
1067
+ return Math.ceil(Math.max(holder.scrollHeight, measured.scrollHeight ?? 0));
1068
+ } finally {
1069
+ holder.remove();
1070
+ }
1071
+ };
1072
+ const loadImage = (url) => new Promise((resolve, reject) => {
1073
+ const image = new Image();
1074
+ image.onload = () => resolve(image);
1075
+ image.onerror = () => reject(new Error("the screen could not be drawn"));
1076
+ image.src = url;
1077
+ });
1078
+ const encodeCanvas = (canvas, mimeType, quality) => new Promise((resolve) => {
1079
+ try {
1080
+ canvas.toBlob((blob) => resolve(blob), mimeType, quality);
1081
+ } catch {
1082
+ resolve(null);
1083
+ }
1084
+ });
1085
+ const encodeBase64 = async (blob) => {
1086
+ const bytes = new Uint8Array(await blob.arrayBuffer());
1087
+ let binary = "";
1088
+ const chunkSize = 32768;
1089
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
1090
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
1091
+ }
1092
+ return btoa(binary);
1093
+ };
1094
+ const createDomScreenPictureCapturer = (options = {}) => ({
1095
+ capture: async (request) => {
1096
+ if (typeof document === "undefined") return null;
1097
+ const root = options.root?.() ?? document.documentElement;
1098
+ if (!root) return null;
1099
+ try {
1100
+ const sourceWidth = Math.max(1, Math.ceil(window.innerWidth || root.clientWidth));
1101
+ const clone = prepareScreenCloneForPicture(root);
1102
+ const sourceHeight = Math.max(1, Math.min(measureCloneHeight(clone, sourceWidth, document), sourceWidth * 8));
1103
+ const serialized = new XMLSerializer().serializeToString(clone);
1104
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${sourceWidth}" height="${sourceHeight}"><foreignObject x="0" y="0" width="100%" height="100%">${serialized}</foreignObject></svg>`;
1105
+ const image = await loadImage(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`);
1106
+ const byteBudget = computePictureByteBudget(request.pictureSize, request.renderMode);
1107
+ let retryScale = 1;
1108
+ let quality = options.quality ?? 0.8;
1109
+ for (let attempt = 1; attempt <= MAX_PICTURE_ENCODE_ATTEMPTS; attempt += 1) {
1110
+ const dimensions = computePictureDimensions(sourceWidth, sourceHeight, request, retryScale);
1111
+ const canvas = document.createElement("canvas");
1112
+ canvas.width = dimensions.width;
1113
+ canvas.height = dimensions.height;
1114
+ const context = canvas.getContext("2d");
1115
+ if (!context) return null;
1116
+ context.fillStyle = "#ffffff";
1117
+ context.fillRect(0, 0, dimensions.width, dimensions.height);
1118
+ context.drawImage(image, 0, 0, dimensions.width, dimensions.height);
1119
+ if (request.renderMode !== "colour") {
1120
+ const imageData = context.getImageData(0, 0, dimensions.width, dimensions.height);
1121
+ convertPixelsToGrey(imageData.data, request.renderMode === "machine" ? MACHINE_MODE_GREY_LEVELS : null);
1122
+ context.putImageData(imageData, 0, 0);
1123
+ }
1124
+ let blob = await encodeCanvas(canvas, "image/webp", quality);
1125
+ if (blob && blob.type !== "image/webp") blob = await encodeCanvas(canvas, "image/jpeg", quality);
1126
+ if (!blob) return null;
1127
+ if (blob.size <= byteBudget || attempt === MAX_PICTURE_ENCODE_ATTEMPTS) {
1128
+ if (blob.size > byteBudget) return null;
1129
+ return {
1130
+ base64: await encodeBase64(blob),
1131
+ mimeType: blob.type === "image/webp" ? "image/webp" : "image/jpeg",
1132
+ width: dimensions.width,
1133
+ height: dimensions.height,
1134
+ byteSize: blob.size
1135
+ };
1136
+ }
1137
+ retryScale = computeRetryScale(retryScale, blob.size, byteBudget);
1138
+ quality = Math.min(quality, 0.65);
1139
+ }
1140
+ return null;
1141
+ } catch {
1142
+ return null;
1143
+ }
1144
+ }
1145
+ });
1146
+ const createAgentWindowAdapter = (options) => {
1147
+ const asideMode = options.asideMode ?? "aside";
1148
+ const stepAsideFor = options.stepAsideFor ?? ["OPEN_TARGET", "HIGHLIGHT", "READ_SCREEN"];
1149
+ let modeBeforeAside = null;
1150
+ return {
1151
+ stepAside: async () => {
1152
+ const currentMode = options.getMode();
1153
+ if (currentMode === asideMode) return;
1154
+ modeBeforeAside = currentMode;
1155
+ await options.applyMode(asideMode);
1156
+ },
1157
+ restore: async () => {
1158
+ if (modeBeforeAside === null) return;
1159
+ const mode = modeBeforeAside;
1160
+ modeBeforeAside = null;
1161
+ await options.applyMode(mode);
1162
+ },
1163
+ setMode: async (mode) => {
1164
+ if (!options.modes.includes(mode)) return false;
1165
+ modeBeforeAside = null;
1166
+ await options.applyMode(mode);
1167
+ return true;
1168
+ },
1169
+ shouldStepAsideBefore: (requestType) => stepAsideFor.includes(requestType)
1170
+ };
1171
+ };
722
1172
  export {
1173
+ AGENT_ANCHOR_ATTRIBUTE,
1174
+ AGENT_ANCHOR_GROUP_ATTRIBUTE,
723
1175
  AGENT_ATTRIBUTES,
1176
+ AGENT_SECRET_ATTRIBUTE,
1177
+ AGENT_SKIP_ATTRIBUTE,
724
1178
  AgentUIClient,
725
1179
  CLIENT_TOOL_OUTCOMES,
1180
+ C as CLIENT_TOOL_REQUEST_MESSAGE_TYPE,
726
1181
  ClientToolRequestRunner,
1182
+ DEFAULT_GUIDES_PER_TARGET,
727
1183
  DomScreenHighlighter,
728
1184
  DomScreenReader,
729
1185
  HIDDEN_VALUE,
1186
+ MACHINE_MODE_BYTE_FACTOR,
1187
+ MACHINE_MODE_GREY_LEVELS,
1188
+ MACHINE_MODE_SIZE_FACTOR,
730
1189
  MARK_VISIBLE_MS,
731
1190
  MAX_ANSWER_TEXT_CHARS,
732
1191
  MAX_BUTTONS,
1192
+ MAX_PICTURE_ELEMENTS,
1193
+ MAX_PICTURE_ENCODE_ATTEMPTS,
733
1194
  MAX_SCREEN_CHARS,
734
1195
  MAX_TABLE_ROWS,
735
1196
  MAX_TARGET_LIST_CHARS,
736
1197
  MAX_VALUE_CHARS,
737
1198
  MIN_SECONDS_LEFT_TO_START,
1199
+ PATH_GUIDE_CLASS,
1200
+ PATH_GUIDE_COUNT_KEY_PREFIX,
1201
+ PATH_GUIDE_STEP_MS,
1202
+ PICTURE_LIMITATIONS,
738
1203
  ReferenceNames,
1204
+ SCREEN_PICTURE_PRESETS,
739
1205
  SIDE_PANEL_MIN_HEIGHT_SHARE,
740
1206
  ScreenReferenceRegistry,
1207
+ a as acceptArrivedRealtimeMessage,
741
1208
  buildTargetRoute,
742
1209
  capAnswerText,
743
1210
  capValue,
1211
+ computePictureByteBudget,
1212
+ computePictureDimensions,
1213
+ computeRetryScale,
1214
+ convertPixelsToGrey,
744
1215
  createAgentUIClientId,
1216
+ createAgentWindowAdapter,
1217
+ createDomScreenPathGuide,
1218
+ createDomScreenPictureCapturer,
1219
+ createDomScreenTargetSource,
1220
+ createGuideCounter,
745
1221
  fieldReferenceNameOf,
746
1222
  formatButtons,
747
1223
  formatFieldLine,
@@ -754,7 +1230,11 @@ export {
754
1230
  oneLine,
755
1231
  parseClientToolArguments,
756
1232
  planHighlightScroll,
1233
+ prepareScreenCloneForPicture,
1234
+ r as readClientToolRequestOfRealtimeMessage,
1235
+ readScreenTargetOfMark,
757
1236
  rowKeyOf,
1237
+ b as runClientToolRequestForDevelopment,
758
1238
  slugOf,
759
1239
  useAgentUIClient
760
1240
  };