@inflatable-cookie/longhorn 0.1.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.
Files changed (178) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +38 -0
  3. package/package.json +205 -0
  4. package/src/agent-control/index.ts +20 -0
  5. package/src/agent-control/inject.ts +4 -0
  6. package/src/agent-control/shim.ts +722 -0
  7. package/src/bridge/direct.ts +22 -0
  8. package/src/bridge/generated/fields.ts +32 -0
  9. package/src/bridge/generated/protocol.ts +218 -0
  10. package/src/bridge/generated/variant-fields.ts +10 -0
  11. package/src/bridge/index.ts +15 -0
  12. package/src/bridge/job.ts +51 -0
  13. package/src/bridge/loopback.ts +84 -0
  14. package/src/bridge/operation.ts +166 -0
  15. package/src/bridge/router.ts +71 -0
  16. package/src/bridge/runtime/connection.ts +318 -0
  17. package/src/bridge/runtime/policy.ts +89 -0
  18. package/src/bridge/runtime/retry.ts +60 -0
  19. package/src/bridge/runtime.ts +3 -0
  20. package/src/bridge/session.ts +67 -0
  21. package/src/bridge/stream/connection.ts +146 -0
  22. package/src/bridge/stream/source.ts +61 -0
  23. package/src/bridge/stream/tracker.ts +109 -0
  24. package/src/bridge/stream.ts +6 -0
  25. package/src/bridge/supervision.ts +204 -0
  26. package/src/bridge/validation/base.ts +164 -0
  27. package/src/bridge/validation/jobs.ts +105 -0
  28. package/src/bridge/validation/negotiation.ts +242 -0
  29. package/src/bridge/validation/operations.ts +213 -0
  30. package/src/bridge/validation/streams.ts +47 -0
  31. package/src/bridge/validation.ts +5 -0
  32. package/src/commands/client.ts +124 -0
  33. package/src/commands/controller.ts +411 -0
  34. package/src/commands/generated/fields.ts +43 -0
  35. package/src/commands/generated/protocol.ts +876 -0
  36. package/src/commands/generated/variant-fields.ts +88 -0
  37. package/src/commands/index.ts +13 -0
  38. package/src/commands/keyboard.ts +361 -0
  39. package/src/commands/ports.ts +82 -0
  40. package/src/commands/projectors.ts +306 -0
  41. package/src/commands/validation.ts +444 -0
  42. package/src/config/client.ts +215 -0
  43. package/src/config/generated/base.ts +714 -0
  44. package/src/config/generated/fields.ts +54 -0
  45. package/src/config/generated/label-template.ts +14 -0
  46. package/src/config/generated/labels.ts +30 -0
  47. package/src/config/generated/protocol.ts +3 -0
  48. package/src/config/generated/restore.ts +658 -0
  49. package/src/config/generated/variant-fields.ts +129 -0
  50. package/src/config/index.ts +12 -0
  51. package/src/config/names.ts +19 -0
  52. package/src/config/validation/commands.ts +155 -0
  53. package/src/config/validation/outcomes.ts +243 -0
  54. package/src/config/validation/primitives.ts +174 -0
  55. package/src/config/validation/projection.ts +351 -0
  56. package/src/config/validation.ts +7 -0
  57. package/src/core/connection.ts +252 -0
  58. package/src/core/index.ts +2 -0
  59. package/src/core/transport.ts +24 -0
  60. package/src/history/client.ts +65 -0
  61. package/src/history/controller.ts +385 -0
  62. package/src/history/direct.ts +21 -0
  63. package/src/history/generated/fields.ts +18 -0
  64. package/src/history/generated/protocol.ts +389 -0
  65. package/src/history/generated/variant-fields.ts +27 -0
  66. package/src/history/index.ts +13 -0
  67. package/src/history/ports.ts +31 -0
  68. package/src/history/serialized.ts +38 -0
  69. package/src/history/validation.ts +334 -0
  70. package/src/history-tree/client.ts +16 -0
  71. package/src/history-tree/controller.ts +199 -0
  72. package/src/history-tree/direct.ts +3 -0
  73. package/src/history-tree/generated/fields.ts +26 -0
  74. package/src/history-tree/generated/protocol.ts +711 -0
  75. package/src/history-tree/generated/variant-fields.ts +39 -0
  76. package/src/history-tree/index.ts +13 -0
  77. package/src/history-tree/ports.ts +43 -0
  78. package/src/history-tree/serialized.ts +15 -0
  79. package/src/history-tree/validation.ts +269 -0
  80. package/src/layout/generated/protocol.ts +289 -0
  81. package/src/layout/index.ts +4 -0
  82. package/src/layout/ratio.ts +22 -0
  83. package/src/layout/validation.ts +110 -0
  84. package/src/layout/visibility.ts +30 -0
  85. package/src/licence/client.ts +32 -0
  86. package/src/licence/controller.ts +301 -0
  87. package/src/licence/direct.ts +3 -0
  88. package/src/licence/generated/fields.ts +17 -0
  89. package/src/licence/generated/key-conformance.json +42 -0
  90. package/src/licence/generated/protocol.ts +249 -0
  91. package/src/licence/generated/variant-fields.ts +34 -0
  92. package/src/licence/index.ts +14 -0
  93. package/src/licence/key.ts +125 -0
  94. package/src/licence/ports.ts +39 -0
  95. package/src/licence/serialized.ts +13 -0
  96. package/src/licence/validation.ts +226 -0
  97. package/src/native-content/client.ts +474 -0
  98. package/src/native-content/direct.ts +16 -0
  99. package/src/native-content/generated/fields.ts +32 -0
  100. package/src/native-content/generated/protocol.ts +498 -0
  101. package/src/native-content/generated/variant-fields.ts +77 -0
  102. package/src/native-content/index.ts +12 -0
  103. package/src/native-content/ports.ts +46 -0
  104. package/src/native-content/serialized.ts +50 -0
  105. package/src/native-content/validation/base.ts +194 -0
  106. package/src/native-content/validation/messages.ts +192 -0
  107. package/src/native-content/validation/state.ts +404 -0
  108. package/src/native-content/validation.ts +7 -0
  109. package/src/notifications/client.ts +106 -0
  110. package/src/notifications/controller.ts +240 -0
  111. package/src/notifications/direct.ts +12 -0
  112. package/src/notifications/generated/fields.ts +19 -0
  113. package/src/notifications/generated/labels.ts +20 -0
  114. package/src/notifications/generated/protocol.ts +522 -0
  115. package/src/notifications/generated/variant-fields.ts +37 -0
  116. package/src/notifications/index.ts +16 -0
  117. package/src/notifications/ports.ts +22 -0
  118. package/src/notifications/serialized.ts +27 -0
  119. package/src/notifications/toast.ts +41 -0
  120. package/src/notifications/tone.ts +27 -0
  121. package/src/notifications/validation.ts +246 -0
  122. package/src/operation/bridge.ts +168 -0
  123. package/src/operation/client.ts +167 -0
  124. package/src/operation/controller.ts +321 -0
  125. package/src/operation/direct.ts +15 -0
  126. package/src/operation/generated/fields.ts +20 -0
  127. package/src/operation/generated/labels.ts +15 -0
  128. package/src/operation/generated/protocol.ts +762 -0
  129. package/src/operation/generated/variant-fields.ts +60 -0
  130. package/src/operation/index.ts +14 -0
  131. package/src/operation/ports.ts +29 -0
  132. package/src/operation/serialized.ts +39 -0
  133. package/src/operation/validation.ts +479 -0
  134. package/src/settings/client.ts +142 -0
  135. package/src/settings/connection.ts +246 -0
  136. package/src/settings/generated/fields.ts +34 -0
  137. package/src/settings/generated/protocol.ts +668 -0
  138. package/src/settings/generated/variant-fields.ts +26 -0
  139. package/src/settings/index.ts +12 -0
  140. package/src/settings/names.ts +8 -0
  141. package/src/settings/registry.ts +141 -0
  142. package/src/settings/validation/authority.ts +66 -0
  143. package/src/settings/validation/command.ts +165 -0
  144. package/src/settings/validation/error.ts +33 -0
  145. package/src/settings/validation/primitives.ts +203 -0
  146. package/src/settings/validation/projection.ts +50 -0
  147. package/src/settings/validation/registry.ts +170 -0
  148. package/src/settings/validation.ts +4 -0
  149. package/src/surface-transfer/client.ts +54 -0
  150. package/src/surface-transfer/generated/fields.ts +12 -0
  151. package/src/surface-transfer/generated/protocol.ts +61 -0
  152. package/src/surface-transfer/generated/variant-fields.ts +30 -0
  153. package/src/surface-transfer/index.ts +9 -0
  154. package/src/surface-transfer/validation.ts +209 -0
  155. package/src/surfaces/client.ts +140 -0
  156. package/src/surfaces/generated/fields.ts +19 -0
  157. package/src/surfaces/generated/protocol.ts +217 -0
  158. package/src/surfaces/generated/variant-fields.ts +42 -0
  159. package/src/surfaces/index.ts +9 -0
  160. package/src/surfaces/validation.ts +199 -0
  161. package/src/transfer/client.ts +133 -0
  162. package/src/transfer/connection.ts +87 -0
  163. package/src/transfer/generated/fields.ts +23 -0
  164. package/src/transfer/generated/protocol.ts +171 -0
  165. package/src/transfer/generated/variant-fields.ts +45 -0
  166. package/src/transfer/index.ts +11 -0
  167. package/src/transfer/payload.ts +71 -0
  168. package/src/transfer/validation.ts +282 -0
  169. package/src/update/client.ts +29 -0
  170. package/src/update/controller.ts +255 -0
  171. package/src/update/direct.ts +3 -0
  172. package/src/update/generated/fields.ts +14 -0
  173. package/src/update/generated/protocol.ts +238 -0
  174. package/src/update/generated/variant-fields.ts +44 -0
  175. package/src/update/index.ts +14 -0
  176. package/src/update/ports.ts +36 -0
  177. package/src/update/serialized.ts +12 -0
  178. package/src/update/validation.ts +191 -0
@@ -0,0 +1,722 @@
1
+ //! In-page semantic surface for contract 022: tree, live-DOM refs, synthetic
2
+ //! input, wait_for predicates, and a bounded page-event ring.
3
+ //!
4
+ //! Pure page mechanics. No transport, no timers, no animation-frame waits.
5
+ //! Refs live as attributes on the elements they name — there is no shim-side
6
+ //! table that outlives the DOM. Truncation is a sentinel child with role
7
+ //! `truncated` (the core vocabulary has no truncation field; a silent cap
8
+ //! is forbidden). Synthetic events are untrusted: `isTrusted` stays false.
9
+
10
+ export const REF_ATTR = "data-longhorn-agent-ref";
11
+ export const REF_SEQ_ATTR = "data-longhorn-agent-ref-seq";
12
+ export const REF_PREFIX_GLOBAL = "__longhornAgentRefPrefix";
13
+ export const TRUNCATED_ROLE = "truncated";
14
+ export const TRUNCATED_REF = "truncated";
15
+ export const MAX_DEPTH = 24;
16
+ export const MAX_NODES = 200;
17
+ export const EVENT_BUFFER_LIMIT = 64;
18
+ export const SHIM_GLOBAL = "__longhornAgentControl";
19
+
20
+ const SKIP_TAGS = new Set([
21
+ "SCRIPT",
22
+ "STYLE",
23
+ "NOSCRIPT",
24
+ "TEMPLATE",
25
+ "HEAD",
26
+ "META",
27
+ "LINK",
28
+ "TITLE",
29
+ "IFRAME",
30
+ ]);
31
+
32
+ type FormControl = Element & {
33
+ value: string;
34
+ disabled?: boolean;
35
+ checked?: boolean;
36
+ readOnly?: boolean;
37
+ type?: string;
38
+ selectionStart?: number | null;
39
+ selectionEnd?: number | null;
40
+ setSelectionRange?: (start: number, end: number) => void;
41
+ selectedOptions?: ArrayLike<Element>;
42
+ selected?: boolean;
43
+ };
44
+
45
+ function isFormControl(element: Element): element is FormControl {
46
+ const tag = element.tagName;
47
+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || tag === "OPTION";
48
+ }
49
+
50
+ function prop<T>(element: Element, name: string): T | undefined {
51
+ return (element as unknown as Record<string, T | undefined>)[name];
52
+ }
53
+
54
+ export type ToolErrorBody =
55
+ | { error: "unresolvedRef"; element: string }
56
+ | { error: "unsupported"; message: string };
57
+
58
+ export type ShimOk<T> = { ok: true } & T;
59
+ export type ShimErr = { ok: false; error: ToolErrorBody };
60
+ export type ShimResult<T> = ShimOk<T> | ShimErr;
61
+ export type ActionOk = ShimOk<Record<string, never>>;
62
+
63
+ export type SemanticNode = {
64
+ elementRef: string;
65
+ role: string;
66
+ name?: string;
67
+ value?: string;
68
+ states: string[];
69
+ children: SemanticNode[];
70
+ };
71
+
72
+ export type PageState = { url: string; title: string };
73
+
74
+ export type PageEvent =
75
+ | { seq: number; kind: "console"; level: string; text: string }
76
+ | { seq: number; kind: "error"; message: string }
77
+ | { seq: number; kind: "navigation"; url: string };
78
+
79
+ export type WaitPredicate =
80
+ | { predicate: "refResolve"; element: string }
81
+ | { predicate: "refAbsent"; element: string }
82
+ | { predicate: "pageUrlContains"; needle: string }
83
+ | { predicate: "pageTitleContains"; needle: string };
84
+
85
+ export type AgentControlApi = {
86
+ snapshot: () => ShimResult<{ page: PageState; root: SemanticNode }>;
87
+ click: (element: string) => ShimResult<Record<string, never>>;
88
+ type: (element: string, text: string) => ShimResult<Record<string, never>>;
89
+ press: (
90
+ key: string,
91
+ modifiers?: string[],
92
+ element?: string | null,
93
+ ) => ShimResult<Record<string, never>>;
94
+ scroll: (
95
+ deltaX: number,
96
+ deltaY: number,
97
+ element?: string | null,
98
+ ) => ShimResult<Record<string, never>>;
99
+ drag: (source: string, target: string) => ShimResult<Record<string, never>>;
100
+ waitFor: (predicate: WaitPredicate) => ShimResult<{ holds: boolean }>;
101
+ readEvents: (sinceSeq?: number) => {
102
+ events: PageEvent[];
103
+ nextSeq: number;
104
+ dropped: number;
105
+ };
106
+ };
107
+
108
+ export type ShimWorld = {
109
+ document: Document;
110
+ location: { href: string };
111
+ console: Pick<Console, "log" | "info" | "warn" | "error" | "debug">;
112
+ history: History;
113
+ MouseEvent: typeof MouseEvent;
114
+ KeyboardEvent: typeof KeyboardEvent;
115
+ Event: typeof Event;
116
+ InputEvent?: typeof InputEvent;
117
+ addEventListener: (type: string, listener: (event: Event) => void) => void;
118
+ onunhandledrejection?: ((event: Event) => void) | null;
119
+ } & Record<string, unknown>;
120
+
121
+ type Budget = { nodes: number; truncated: boolean };
122
+
123
+ function unresolved(element: string): ShimResult<never> {
124
+ return { ok: false, error: { error: "unresolvedRef", element } };
125
+ }
126
+
127
+ function ok(): ActionOk {
128
+ return { ok: true } as ActionOk;
129
+ }
130
+
131
+ function resolveRef(document: Document, element: string): Element | null {
132
+ if (element === TRUNCATED_REF || element.length === 0) return null;
133
+ return document.querySelector(`[${REF_ATTR}="${element}"]`);
134
+ }
135
+
136
+ function refPrefix(document: Document): string {
137
+ const view = document.defaultView as unknown as Record<string, unknown> | null;
138
+ const value = view?.[REF_PREFIX_GLOBAL];
139
+ return typeof value === "string" ? value : "";
140
+ }
141
+
142
+ function allocRef(document: Document): string {
143
+ const root = document.documentElement;
144
+ const current = Number(root.getAttribute(REF_SEQ_ATTR) ?? "0");
145
+ const next = Number.isFinite(current) ? current + 1 : 1;
146
+ root.setAttribute(REF_SEQ_ATTR, String(next));
147
+ const id = `e${next}`;
148
+ const prefix = refPrefix(document);
149
+ return prefix.length > 0 ? `${prefix}:${id}` : id;
150
+ }
151
+
152
+ function stamp(element: Element, document: Document): string {
153
+ const existing = element.getAttribute(REF_ATTR);
154
+ if (existing) return existing;
155
+ const id = allocRef(document);
156
+ element.setAttribute(REF_ATTR, id);
157
+ return id;
158
+ }
159
+
160
+ function computedStyle(element: Element): CSSStyleDeclaration | null {
161
+ const view = element.ownerDocument.defaultView;
162
+ return view ? view.getComputedStyle(element) : null;
163
+ }
164
+
165
+ function isVisible(element: Element): boolean {
166
+ if (element.hasAttribute("hidden")) return false;
167
+ if (element.getAttribute("aria-hidden") === "true") return false;
168
+ const style = computedStyle(element);
169
+ if (!style) return true;
170
+ return style.display !== "none" && style.visibility !== "hidden";
171
+ }
172
+
173
+ function implicitRole(element: Element): string | null {
174
+ const tag = element.tagName;
175
+ if (tag === "A") return element.hasAttribute("href") ? "link" : null;
176
+ if (tag === "BUTTON") return "button";
177
+ if (tag === "TEXTAREA") return "textbox";
178
+ if (tag === "SELECT") return "combobox";
179
+ if (tag === "OPTION") return "option";
180
+ if (tag === "SUMMARY") return "button";
181
+ if (tag === "DETAILS") return "group";
182
+ if (tag === "NAV") return "navigation";
183
+ if (tag === "MAIN") return "main";
184
+ if (tag === "HEADER") return "banner";
185
+ if (tag === "FOOTER") return "contentinfo";
186
+ if (tag === "FORM") return "form";
187
+ if (tag === "UL" || tag === "OL") return "list";
188
+ if (tag === "LI") return "listitem";
189
+ if (tag === "TABLE") return "table";
190
+ if (tag === "DIALOG") return "dialog";
191
+ if (tag === "IMG") return "image";
192
+ if (tag === "H1" || tag === "H2" || tag === "H3" || tag === "H4" || tag === "H5" || tag === "H6") {
193
+ return "heading";
194
+ }
195
+ if (tag === "INPUT") {
196
+ const type = (element.getAttribute("type") ?? "text").toLowerCase();
197
+ if (type === "checkbox") return "checkbox";
198
+ if (type === "radio") return "radio";
199
+ if (type === "number") return "spinbutton";
200
+ if (type === "range") return "slider";
201
+ if (type === "button" || type === "submit" || type === "reset" || type === "file") {
202
+ return "button";
203
+ }
204
+ if (type === "hidden") return null;
205
+ return "textbox";
206
+ }
207
+ if (element.hasAttribute("contenteditable")) return "textbox";
208
+ return null;
209
+ }
210
+
211
+ function roleOf(element: Element): string | null {
212
+ const explicit = element.getAttribute("role");
213
+ if (explicit === "none" || explicit === "presentation") return null;
214
+ if (explicit) return explicit;
215
+ return implicitRole(element);
216
+ }
217
+
218
+ function labelledByText(element: Element): string | undefined {
219
+ const ids = element.getAttribute("aria-labelledby");
220
+ if (!ids) return undefined;
221
+ const document = element.ownerDocument;
222
+ const text = ids
223
+ .split(/\s+/)
224
+ .map((id) => document.getElementById(id)?.textContent ?? "")
225
+ .join(" ")
226
+ .replace(/\s+/g, " ")
227
+ .trim();
228
+ return text.length > 0 ? text : undefined;
229
+ }
230
+
231
+ function associatedLabel(element: Element): string | undefined {
232
+ const id = element.id;
233
+ const document = element.ownerDocument;
234
+ if (id) {
235
+ const label = document.querySelector(`label[for="${id}"]`);
236
+ const text = label?.textContent?.replace(/\s+/g, " ").trim();
237
+ if (text) return text;
238
+ }
239
+ const parent = element.closest("label");
240
+ if (parent) {
241
+ const text = parent.textContent?.replace(/\s+/g, " ").trim();
242
+ if (text) return text;
243
+ }
244
+ return undefined;
245
+ }
246
+
247
+ function accessibleName(element: Element): string | undefined {
248
+ const labelled = labelledByText(element);
249
+ if (labelled) return labelled;
250
+ const aria = element.getAttribute("aria-label")?.trim();
251
+ if (aria) return aria;
252
+ const label = associatedLabel(element);
253
+ if (label) return label;
254
+ if (element.tagName === "IMG") {
255
+ const alt = element.getAttribute("alt")?.trim();
256
+ if (alt) return alt;
257
+ }
258
+ const role = roleOf(element);
259
+ if (
260
+ role === "button" ||
261
+ role === "link" ||
262
+ role === "heading" ||
263
+ role === "option" ||
264
+ role === "tab" ||
265
+ role === "listitem"
266
+ ) {
267
+ const text = element.textContent?.replace(/\s+/g, " ").trim();
268
+ if (text) return text;
269
+ }
270
+ const title = element.getAttribute("title")?.trim();
271
+ if (title) return title;
272
+ const placeholder = element.getAttribute("placeholder")?.trim();
273
+ if (placeholder) return placeholder;
274
+ return undefined;
275
+ }
276
+
277
+ function valueOf(element: Element): string | undefined {
278
+ const now = element.getAttribute("aria-valuenow");
279
+ if (now) return now;
280
+ if (element.tagName === "INPUT") {
281
+ const type = (prop<string>(element, "type") ?? "text").toLowerCase();
282
+ if (type === "checkbox" || type === "radio") return undefined;
283
+ return prop<string>(element, "value");
284
+ }
285
+ if (element.tagName === "TEXTAREA") return prop<string>(element, "value");
286
+ if (element.tagName === "SELECT") {
287
+ const selected = prop<ArrayLike<Element>>(element, "selectedOptions");
288
+ const first = selected && selected.length > 0 ? selected[0] : undefined;
289
+ return first?.textContent?.trim() ?? prop<string>(element, "value");
290
+ }
291
+ if (element.hasAttribute("contenteditable")) {
292
+ return element.textContent ?? undefined;
293
+ }
294
+ return undefined;
295
+ }
296
+
297
+ function statesOf(element: Element, document: Document): string[] {
298
+ const states: string[] = [];
299
+ if (isVisible(element)) states.push("visible");
300
+ if (
301
+ element.hasAttribute("disabled") ||
302
+ element.getAttribute("aria-disabled") === "true" ||
303
+ prop<boolean>(element, "disabled") === true
304
+ ) {
305
+ states.push("disabled");
306
+ }
307
+ if (prop<boolean>(element, "checked") === true || element.getAttribute("aria-checked") === "true") {
308
+ states.push("checked");
309
+ }
310
+ if (document.activeElement === element) states.push("focused");
311
+ if (element.getAttribute("aria-expanded") === "true") states.push("expanded");
312
+ if (element.getAttribute("aria-pressed") === "true") states.push("pressed");
313
+ if (
314
+ element.getAttribute("aria-selected") === "true" ||
315
+ prop<boolean>(element, "selected") === true
316
+ ) {
317
+ states.push("selected");
318
+ }
319
+ if (
320
+ element.getAttribute("aria-readonly") === "true" ||
321
+ prop<boolean>(element, "readOnly") === true
322
+ ) {
323
+ states.push("readonly");
324
+ }
325
+ return states;
326
+ }
327
+
328
+ function isInteresting(element: Element): boolean {
329
+ if (SKIP_TAGS.has(element.tagName)) return false;
330
+ // Labels contribute their text to the control's name; they are not nodes.
331
+ if (element.tagName === "LABEL") return false;
332
+ if (roleOf(element)) return true;
333
+ if (accessibleName(element)) return true;
334
+ if (element.tagName === "INPUT") return true;
335
+ if (element.hasAttribute("tabindex")) return true;
336
+ return false;
337
+ }
338
+
339
+ function truncatedNode(): SemanticNode {
340
+ return {
341
+ elementRef: TRUNCATED_REF,
342
+ role: TRUNCATED_ROLE,
343
+ states: [],
344
+ children: [],
345
+ };
346
+ }
347
+
348
+ function walk(
349
+ element: Element,
350
+ document: Document,
351
+ depth: number,
352
+ budget: Budget,
353
+ ): SemanticNode[] {
354
+ if (SKIP_TAGS.has(element.tagName) || !isVisible(element)) return [];
355
+ const interesting = isInteresting(element) || depth === 0;
356
+ if (!interesting) {
357
+ const promoted: SemanticNode[] = [];
358
+ for (const child of Array.from(element.children)) {
359
+ promoted.push(...walk(child, document, depth, budget));
360
+ if (budget.truncated) break;
361
+ }
362
+ return promoted;
363
+ }
364
+ if (budget.nodes >= MAX_NODES) {
365
+ budget.truncated = true;
366
+ return [truncatedNode()];
367
+ }
368
+ budget.nodes += 1;
369
+ const node: SemanticNode = {
370
+ elementRef: stamp(element, document),
371
+ role: roleOf(element) ?? element.tagName.toLowerCase(),
372
+ states: statesOf(element, document),
373
+ children: [],
374
+ };
375
+ const name = accessibleName(element);
376
+ if (name) node.name = name;
377
+ const value = valueOf(element);
378
+ if (value !== undefined && value.length > 0) node.value = value;
379
+ if (depth >= MAX_DEPTH) {
380
+ if (element.children.length > 0) {
381
+ budget.truncated = true;
382
+ node.children.push(truncatedNode());
383
+ }
384
+ return [node];
385
+ }
386
+ for (const child of Array.from(element.children)) {
387
+ if (budget.nodes >= MAX_NODES) {
388
+ budget.truncated = true;
389
+ node.children.push(truncatedNode());
390
+ break;
391
+ }
392
+ node.children.push(...walk(child, document, depth + 1, budget));
393
+ }
394
+ return [node];
395
+ }
396
+
397
+ function snapshot(world: ShimWorld): ShimResult<{ page: PageState; root: SemanticNode }> {
398
+ const document = world.document;
399
+ const rootElement = document.body ?? document.documentElement;
400
+ const budget: Budget = { nodes: 0, truncated: false };
401
+ const [root] = walk(rootElement, document, 0, budget);
402
+ return {
403
+ ok: true,
404
+ page: { url: world.location.href, title: document.title },
405
+ root: root ?? truncatedNode(),
406
+ };
407
+ }
408
+
409
+ function centerOf(element: Element): { x: number; y: number } {
410
+ const rect = element.getBoundingClientRect();
411
+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
412
+ }
413
+
414
+ function dispatchMouse(
415
+ world: ShimWorld,
416
+ element: Element,
417
+ type: string,
418
+ point?: { x: number; y: number },
419
+ ): void {
420
+ const coords = point ?? centerOf(element);
421
+ element.dispatchEvent(
422
+ new world.MouseEvent(type, {
423
+ bubbles: true,
424
+ cancelable: true,
425
+ composed: true,
426
+ button: 0,
427
+ clientX: coords.x,
428
+ clientY: coords.y,
429
+ screenX: coords.x,
430
+ screenY: coords.y,
431
+ }),
432
+ );
433
+ }
434
+
435
+ function dispatchKey(
436
+ world: ShimWorld,
437
+ element: Element,
438
+ type: string,
439
+ key: string,
440
+ modifiers: string[],
441
+ ): boolean {
442
+ const event = new world.KeyboardEvent(type, {
443
+ bubbles: true,
444
+ cancelable: true,
445
+ composed: true,
446
+ key,
447
+ altKey: modifiers.includes("alt"),
448
+ ctrlKey: modifiers.includes("control"),
449
+ metaKey: modifiers.includes("meta"),
450
+ shiftKey: modifiers.includes("shift"),
451
+ });
452
+ return element.dispatchEvent(event);
453
+ }
454
+
455
+ function dispatchInput(world: ShimWorld, element: Element, data: string): void {
456
+ const InputEvent = world.InputEvent;
457
+ if (InputEvent) {
458
+ element.dispatchEvent(
459
+ new InputEvent("input", {
460
+ bubbles: true,
461
+ cancelable: true,
462
+ data,
463
+ inputType: "insertText",
464
+ }),
465
+ );
466
+ return;
467
+ }
468
+ element.dispatchEvent(new world.Event("input", { bubbles: true }));
469
+ }
470
+
471
+ function focus(element: Element): void {
472
+ const focusFn = prop<(this: Element) => void>(element, "focus");
473
+ focusFn?.call(element);
474
+ }
475
+
476
+ function click(world: ShimWorld, element: string): ShimResult<Record<string, never>> {
477
+ const node = resolveRef(world.document, element);
478
+ if (!node) return unresolved(element);
479
+ focus(node);
480
+ dispatchMouse(world, node, "pointerdown");
481
+ dispatchMouse(world, node, "mousedown");
482
+ dispatchMouse(world, node, "pointerup");
483
+ dispatchMouse(world, node, "mouseup");
484
+ // Native click() fires the click event and runs default actions
485
+ // (submit, checkbox toggle, link navigation) that a synthetic MouseEvent
486
+ // does not. isTrusted stays false.
487
+ const nativeClick = prop<(this: Element) => void>(node, "click");
488
+ if (nativeClick) nativeClick.call(node);
489
+ else dispatchMouse(world, node, "click");
490
+ return ok();
491
+ }
492
+
493
+ function insertText(element: Element, text: string): void {
494
+ if (element.tagName === "INPUT" || element.tagName === "TEXTAREA") {
495
+ const current = prop<string>(element, "value") ?? "";
496
+ const start = prop<number | null>(element, "selectionStart") ?? current.length;
497
+ const end = prop<number | null>(element, "selectionEnd") ?? start;
498
+ const next = `${current.slice(0, start)}${text}${current.slice(end)}`;
499
+ (element as FormControl).value = next;
500
+ const cursor = start + text.length;
501
+ prop<(this: Element, start: number, end: number) => void>(
502
+ element,
503
+ "setSelectionRange",
504
+ )?.call(element, cursor, cursor);
505
+ return;
506
+ }
507
+ if (element.hasAttribute("contenteditable") || prop<boolean>(element, "isContentEditable")) {
508
+ element.textContent = `${element.textContent ?? ""}${text}`;
509
+ }
510
+ }
511
+
512
+ function typeInto(
513
+ world: ShimWorld,
514
+ element: string,
515
+ text: string,
516
+ ): ShimResult<Record<string, never>> {
517
+ const node = resolveRef(world.document, element);
518
+ if (!node) return unresolved(element);
519
+ focus(node);
520
+ for (const char of text) {
521
+ dispatchKey(world, node, "keydown", char, []);
522
+ insertText(node, char);
523
+ dispatchInput(world, node, char);
524
+ dispatchKey(world, node, "keyup", char, []);
525
+ }
526
+ node.dispatchEvent(new world.Event("change", { bubbles: true }));
527
+ return ok();
528
+ }
529
+
530
+ function press(
531
+ world: ShimWorld,
532
+ key: string,
533
+ modifiers: string[] = [],
534
+ element?: string | null,
535
+ ): ShimResult<Record<string, never>> {
536
+ let node: Element | null;
537
+ if (element) {
538
+ node = resolveRef(world.document, element);
539
+ if (!node) return unresolved(element);
540
+ } else {
541
+ node = world.document.activeElement ?? world.document.body ?? world.document.documentElement;
542
+ }
543
+ focus(node);
544
+ dispatchKey(world, node, "keydown", key, modifiers);
545
+ dispatchKey(world, node, "keyup", key, modifiers);
546
+ return ok();
547
+ }
548
+
549
+ function scroll(
550
+ world: ShimWorld,
551
+ deltaX: number,
552
+ deltaY: number,
553
+ element?: string | null,
554
+ ): ShimResult<Record<string, never>> {
555
+ if (element) {
556
+ const node = resolveRef(world.document, element);
557
+ if (!node) return unresolved(element);
558
+ node.scrollTop += deltaY;
559
+ node.scrollLeft += deltaX;
560
+ node.dispatchEvent(new world.Event("scroll", { bubbles: true }));
561
+ return ok();
562
+ }
563
+ const scrolling = world.document.scrollingElement ?? world.document.documentElement;
564
+ scrolling.scrollTop += deltaY;
565
+ scrolling.scrollLeft += deltaX;
566
+ world.document.dispatchEvent(new world.Event("scroll", { bubbles: true }));
567
+ return ok();
568
+ }
569
+
570
+ function drag(
571
+ world: ShimWorld,
572
+ sourceRef: string,
573
+ targetRef: string,
574
+ ): ShimResult<Record<string, never>> {
575
+ const source = resolveRef(world.document, sourceRef);
576
+ if (!source) return unresolved(sourceRef);
577
+ const target = resolveRef(world.document, targetRef);
578
+ if (!target) return unresolved(targetRef);
579
+ const from = centerOf(source);
580
+ const to = centerOf(target);
581
+ // Two-point untrusted path: pointer/mouse at the source center, then the
582
+ // target center. There is no interpolated pixel trail — drag is ref-to-ref.
583
+ dispatchMouse(world, source, "pointerdown", from);
584
+ dispatchMouse(world, source, "mousedown", from);
585
+ dispatchMouse(world, target, "pointermove", to);
586
+ dispatchMouse(world, target, "mousemove", to);
587
+ const transfer: DataTransfer =
588
+ typeof DataTransfer === "function"
589
+ ? new DataTransfer()
590
+ : ({ setData() {}, getData() { return ""; } } as unknown as DataTransfer);
591
+ const dragEvent = (type: string, current: Element, point: { x: number; y: number }) => {
592
+ const event = new world.MouseEvent(type, {
593
+ bubbles: true,
594
+ cancelable: true,
595
+ composed: true,
596
+ clientX: point.x,
597
+ clientY: point.y,
598
+ });
599
+ Object.defineProperty(event, "dataTransfer", { value: transfer });
600
+ current.dispatchEvent(event);
601
+ };
602
+ dragEvent("dragstart", source, from);
603
+ dragEvent("dragenter", target, to);
604
+ dragEvent("dragover", target, to);
605
+ dragEvent("drop", target, to);
606
+ dragEvent("dragend", source, from);
607
+ dispatchMouse(world, target, "pointerup", to);
608
+ dispatchMouse(world, target, "mouseup", to);
609
+ return ok();
610
+ }
611
+
612
+ function waitFor(world: ShimWorld, predicate: WaitPredicate): ShimResult<{ holds: boolean }> {
613
+ switch (predicate.predicate) {
614
+ case "refResolve":
615
+ return { ok: true, holds: resolveRef(world.document, predicate.element) !== null };
616
+ case "refAbsent":
617
+ return { ok: true, holds: resolveRef(world.document, predicate.element) === null };
618
+ case "pageUrlContains":
619
+ return { ok: true, holds: world.location.href.includes(predicate.needle) };
620
+ case "pageTitleContains":
621
+ return { ok: true, holds: world.document.title.includes(predicate.needle) };
622
+ default:
623
+ return {
624
+ ok: false,
625
+ error: {
626
+ error: "unsupported",
627
+ message: "wait_for admits only the four DOM-relative predicates",
628
+ },
629
+ };
630
+ }
631
+ }
632
+
633
+ function installEventRing(world: ShimWorld): AgentControlApi["readEvents"] {
634
+ const existing = world[SHIM_GLOBAL] as AgentControlApi | undefined;
635
+ if (existing) return existing.readEvents.bind(existing);
636
+
637
+ const ring: PageEvent[] = [];
638
+ let nextSeq = 1;
639
+ let dropped = 0;
640
+
641
+ const push = (event: PageEvent) => {
642
+ const recorded = event;
643
+ nextSeq += 1;
644
+ if (ring.length >= EVENT_BUFFER_LIMIT) {
645
+ ring.shift();
646
+ dropped += 1;
647
+ }
648
+ ring.push(recorded);
649
+ };
650
+
651
+ const wrap = (level: "log" | "info" | "warn" | "error" | "debug") => {
652
+ const original = world.console[level]?.bind(world.console);
653
+ world.console[level] = (...args: unknown[]) => {
654
+ push({
655
+ seq: nextSeq,
656
+ kind: "console",
657
+ level,
658
+ text: args.map((value) => String(value)).join(" "),
659
+ });
660
+ original?.(...args);
661
+ };
662
+ };
663
+ wrap("log");
664
+ wrap("info");
665
+ wrap("warn");
666
+ wrap("error");
667
+ wrap("debug");
668
+
669
+ world.addEventListener("error", (event) => {
670
+ const message =
671
+ "message" in event && typeof event.message === "string"
672
+ ? event.message
673
+ : String(event);
674
+ push({ seq: nextSeq, kind: "error", message });
675
+ });
676
+ world.addEventListener("unhandledrejection", (event) => {
677
+ const reason =
678
+ "reason" in event ? String((event as PromiseRejectionEvent).reason) : "unhandledrejection";
679
+ push({ seq: nextSeq, kind: "error", message: reason });
680
+ });
681
+
682
+ const notifyNavigation = () => {
683
+ push({ seq: nextSeq, kind: "navigation", url: world.location.href });
684
+ };
685
+ world.addEventListener("hashchange", notifyNavigation);
686
+ world.addEventListener("popstate", notifyNavigation);
687
+ const history = world.history;
688
+ const pushState = history.pushState.bind(history);
689
+ const replaceState = history.replaceState.bind(history);
690
+ history.pushState = ((...args: Parameters<History["pushState"]>) => {
691
+ pushState(...args);
692
+ notifyNavigation();
693
+ }) as History["pushState"];
694
+ history.replaceState = ((...args: Parameters<History["replaceState"]>) => {
695
+ replaceState(...args);
696
+ notifyNavigation();
697
+ }) as History["replaceState"];
698
+
699
+ return (sinceSeq = 0) => ({
700
+ events: ring.filter((event) => event.seq > sinceSeq),
701
+ nextSeq,
702
+ dropped,
703
+ });
704
+ }
705
+
706
+ export function installAgentControlShim(world: ShimWorld): AgentControlApi {
707
+ const existing = world[SHIM_GLOBAL] as AgentControlApi | undefined;
708
+ if (existing) return existing;
709
+ const readEvents = installEventRing(world);
710
+ const api: AgentControlApi = {
711
+ snapshot: () => snapshot(world),
712
+ click: (element) => click(world, element),
713
+ type: (element, text) => typeInto(world, element, text),
714
+ press: (key, modifiers, element) => press(world, key, modifiers, element),
715
+ scroll: (deltaX, deltaY, element) => scroll(world, deltaX, deltaY, element),
716
+ drag: (source, target) => drag(world, source, target),
717
+ waitFor: (predicate) => waitFor(world, predicate),
718
+ readEvents,
719
+ };
720
+ world[SHIM_GLOBAL] = api;
721
+ return api;
722
+ }