@inbrowser/driver 0.0.0-stage → 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.
Files changed (39) hide show
  1. package/AGENTS.md +20 -0
  2. package/LICENSE +21 -0
  3. package/README.md +112 -2
  4. package/THIRD_PARTY_NOTICES.txt +216 -0
  5. package/dist/LICENSE +21 -0
  6. package/dist/THIRD_PARTY_NOTICES.txt +216 -0
  7. package/dist/index.js +1631 -0
  8. package/dist/index.js.map +7 -0
  9. package/dist/preload.iife.js +5 -0
  10. package/dist/preload.js +2 -0
  11. package/dist/puppeteer.js +2569 -0
  12. package/dist/puppeteer.js.map +7 -0
  13. package/dist/tools.js +1283 -0
  14. package/dist/tools.js.map +7 -0
  15. package/dist/types/host/capture-seam.d.ts +17 -0
  16. package/dist/types/host/preview-backend.d.ts +9 -0
  17. package/dist/types/host/sandbox-connect.d.ts +38 -0
  18. package/dist/types/host/viewport-capture.d.ts +2 -0
  19. package/dist/types/index.d.ts +5 -0
  20. package/dist/types/preload/act.d.ts +4 -0
  21. package/dist/types/preload/capture-seam.d.ts +1 -0
  22. package/dist/types/preload/cursor-overlay.d.ts +5 -0
  23. package/dist/types/preload/diagnostics.d.ts +13 -0
  24. package/dist/types/preload/diff.d.ts +3 -0
  25. package/dist/types/preload/entry.d.ts +1 -0
  26. package/dist/types/preload/eval.d.ts +7 -0
  27. package/dist/types/preload/export.d.ts +11 -0
  28. package/dist/types/preload/intrinsics.d.ts +255 -0
  29. package/dist/types/preload/observe.d.ts +27 -0
  30. package/dist/types/preload/ref-registry.d.ts +44 -0
  31. package/dist/types/preload/silent-capture.d.ts +3 -0
  32. package/dist/types/protocol.d.ts +103 -0
  33. package/dist/types/puppeteer/cdp-driver.d.ts +11 -0
  34. package/dist/types/puppeteer/index.d.ts +2 -0
  35. package/dist/types/tools/format.d.ts +7 -0
  36. package/dist/types/tools/index.d.ts +9 -0
  37. package/dist/types/tools/schemas.d.ts +36 -0
  38. package/dist/types/types.d.ts +268 -0
  39. package/package.json +70 -4
package/dist/tools.js ADDED
@@ -0,0 +1,1283 @@
1
+ // src/types.ts
2
+ var DriverError = class extends Error {
3
+ code;
4
+ candidates;
5
+ constructor(code, message, options) {
6
+ super(message, options?.cause !== void 0 ? { cause: options.cause } : void 0);
7
+ this.name = "DriverError";
8
+ this.code = code;
9
+ if (options?.candidates !== void 0) {
10
+ this.candidates = options.candidates;
11
+ }
12
+ }
13
+ };
14
+
15
+ // src/tools/format.ts
16
+ var DEFAULT_OBSERVE_MAX_YAML_CHARS = 16e3;
17
+ var DEFAULT_ACT_MAX_YAML_CHARS = 12e3;
18
+ var DEFAULT_EVAL_MAX_YAML_CHARS = 12e3;
19
+ function quoteYamlString(value) {
20
+ return JSON.stringify(value).replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
21
+ }
22
+ function formatRoleToken(role) {
23
+ return /^[A-Za-z0-9_-]+$/.test(role) ? role : quoteYamlString(role);
24
+ }
25
+ function formatDriverToken(driverId) {
26
+ return /^[A-Za-z0-9_.:/-]+$/.test(driverId) ? driverId : quoteYamlString(driverId);
27
+ }
28
+ function isDiagnosticsClean(diagnostics) {
29
+ return diagnostics.compileOverlay === null && diagnostics.consoleErrors.length === 0 && diagnostics.pageErrors.length === 0 && diagnostics.networkFailures.length === 0;
30
+ }
31
+ function appendDiagnosticsLines(lines, diagnostics) {
32
+ if (isDiagnosticsClean(diagnostics)) {
33
+ return;
34
+ }
35
+ lines.push("diagnostics:");
36
+ if (diagnostics.compileOverlay !== null) {
37
+ lines.push(` compileOverlay: ${quoteYamlString(diagnostics.compileOverlay)}`);
38
+ }
39
+ if (diagnostics.consoleErrors.length > 0) {
40
+ lines.push(" consoleErrors:");
41
+ for (const msg of diagnostics.consoleErrors) {
42
+ lines.push(` - ${quoteYamlString(msg)}`);
43
+ }
44
+ }
45
+ if (diagnostics.pageErrors.length > 0) {
46
+ lines.push(" pageErrors:");
47
+ for (const msg of diagnostics.pageErrors) {
48
+ lines.push(` - ${quoteYamlString(msg)}`);
49
+ }
50
+ }
51
+ if (diagnostics.networkFailures.length > 0) {
52
+ lines.push(" networkFailures:");
53
+ for (const nf of diagnostics.networkFailures) {
54
+ lines.push(
55
+ ` - ${String(nf.status)} ${formatRoleToken(nf.method)} ${quoteYamlString(nf.url)} ${quoteYamlString(nf.statusText)}`
56
+ );
57
+ }
58
+ }
59
+ }
60
+ function formatMediaAttrs(media) {
61
+ const parts = [
62
+ media.paused ? "paused" : "playing",
63
+ `time=${String(media.currentTime)}/${media.duration === null ? "?" : String(media.duration)}`
64
+ ];
65
+ if (media.kind === "video" || media.width > 0 || media.height > 0) {
66
+ parts.push(`size=${String(media.width)}x${String(media.height)}`);
67
+ }
68
+ parts.push(media.ready ? "ready" : "ready=false");
69
+ if (media.error !== null) {
70
+ parts.push(`error=${quoteYamlString(media.error)}`);
71
+ }
72
+ return parts.join(" ");
73
+ }
74
+ function formatCanvasAttrs(canvas) {
75
+ return `size=${String(canvas.width)}x${String(canvas.height)} nonBlank=${String(canvas.nonBlank)}`;
76
+ }
77
+ function formatSingleNodeLine(node, indentSpaces, includeChildrenColon) {
78
+ const indent = " ".repeat(indentSpaces);
79
+ const tokens = [`${indent}- ${formatRoleToken(node.role)}`];
80
+ if (node.name.length > 0) {
81
+ tokens.push(quoteYamlString(node.name));
82
+ }
83
+ if (node.ref !== void 0) {
84
+ tokens.push(`[ref=${node.ref}]`);
85
+ }
86
+ if (node.driverId !== void 0 && node.driverId.length > 0) {
87
+ tokens.push(`[driver=${formatDriverToken(node.driverId)}]`);
88
+ }
89
+ if (node.intent !== void 0 && node.intent.length > 0) {
90
+ tokens.push(`intent=${quoteYamlString(node.intent)}`);
91
+ }
92
+ if (node.value !== void 0) {
93
+ tokens.push(`value=${quoteYamlString(node.value)}`);
94
+ }
95
+ if (node.checked !== void 0) {
96
+ tokens.push(`checked=${String(node.checked)}`);
97
+ }
98
+ if (node.disabled === true) {
99
+ tokens.push("disabled");
100
+ }
101
+ if (node.expanded !== void 0) {
102
+ tokens.push(`expanded=${String(node.expanded)}`);
103
+ }
104
+ if (node.min !== void 0) {
105
+ tokens.push(`min=${String(node.min)}`);
106
+ }
107
+ if (node.max !== void 0) {
108
+ tokens.push(`max=${String(node.max)}`);
109
+ }
110
+ if (node.media !== void 0) {
111
+ tokens.push(formatMediaAttrs(node.media));
112
+ }
113
+ if (node.canvas !== void 0) {
114
+ tokens.push(formatCanvasAttrs(node.canvas));
115
+ }
116
+ const hasChildren = includeChildrenColon && node.children !== void 0 && node.children.length > 0;
117
+ return `${tokens.join(" ")}${hasChildren ? ":" : ""}`;
118
+ }
119
+ function appendNodeTreeLines(lines, nodes, indentSpaces, recurseChildren = true) {
120
+ for (const node of nodes) {
121
+ const hasChildren = recurseChildren && node.children !== void 0 && node.children.length > 0;
122
+ lines.push(formatSingleNodeLine(node, indentSpaces, recurseChildren));
123
+ if (hasChildren && node.children !== void 0) {
124
+ appendNodeTreeLines(lines, node.children, indentSpaces + 2, true);
125
+ }
126
+ }
127
+ }
128
+ function truncateYaml(yaml, maxChars, defaultMaxChars) {
129
+ if (maxChars === Number.POSITIVE_INFINITY) {
130
+ return yaml;
131
+ }
132
+ const effective = Number.isFinite(maxChars) ? maxChars : defaultMaxChars;
133
+ const budget = Math.max(0, Math.floor(effective));
134
+ if (yaml.length <= budget) {
135
+ return yaml;
136
+ }
137
+ const maxDigits = String(yaml.length).length;
138
+ const maxTrailerLength = `
139
+ ... (truncated ${"9".repeat(maxDigits)} chars; pass scope to narrow)`.length;
140
+ if (budget <= maxTrailerLength) {
141
+ const fallback = `... (truncated ${String(yaml.length)} chars; pass scope to narrow)`;
142
+ return fallback.slice(0, budget);
143
+ }
144
+ const prefixLimit = budget - maxTrailerLength;
145
+ const rawPrefix = yaml.slice(0, prefixLimit);
146
+ const lastNewline = rawPrefix.lastIndexOf("\n");
147
+ const kept = lastNewline > 0 ? rawPrefix.slice(0, lastNewline) : rawPrefix;
148
+ const omittedChars = yaml.length - kept.length;
149
+ return `${kept}
150
+ ... (truncated ${String(omittedChars)} chars; pass scope to narrow)`;
151
+ }
152
+ function hintForDriverErrorCode(code) {
153
+ switch (code) {
154
+ case "DRIVER_TARGET_NOT_FOUND":
155
+ return "Call ui_observe to refresh refs or select one of the listed candidates.";
156
+ case "DRIVER_TARGET_AMBIGUOUS":
157
+ return 'Disambiguate the target using an exact ref (e.g. "e3") or pass nth in { role, name, nth }.';
158
+ case "DRIVER_EVAL_DISABLED":
159
+ return "JavaScript evaluation requires allowEval: true on both the PageDriver and createDriverTools.";
160
+ case "DRIVER_UNSUPPORTED":
161
+ return "This operation is unsupported by the active PageDriver backend.";
162
+ case "DRIVER_TIMEOUT":
163
+ return "Operation timed out or was cancelled; call ui_observe to inspect current UI state before retrying.";
164
+ case "DRIVER_DISPOSED":
165
+ return "The PageDriver instance has been disposed and can no longer execute commands.";
166
+ case "DRIVER_PROTOCOL":
167
+ return "Protocol transport failed communicating with the guest frame; call ui_observe to verify connectivity.";
168
+ }
169
+ }
170
+ function formatCandidateLine(candidate) {
171
+ const parts = [
172
+ `role=${quoteYamlString(candidate.role)}`,
173
+ `name=${quoteYamlString(candidate.name)}`,
174
+ `nth=${String(candidate.nth)}`
175
+ ];
176
+ if (candidate.driverId !== void 0) {
177
+ parts.push(`driver=${quoteYamlString(candidate.driverId)}`);
178
+ }
179
+ if (candidate.landmark !== void 0) {
180
+ parts.push(`landmark=${quoteYamlString(candidate.landmark)}`);
181
+ }
182
+ return ` - ${parts.join(" ")}`;
183
+ }
184
+ function formatValidationErrorYaml(message) {
185
+ return [
186
+ "status: error",
187
+ "code: INVALID_ARGUMENTS",
188
+ `message: ${quoteYamlString(message)}`,
189
+ 'hint: "Check the tool schema parameters and retry."'
190
+ ].join("\n");
191
+ }
192
+ function isDriverErrorCode(value) {
193
+ switch (value) {
194
+ case "DRIVER_TIMEOUT":
195
+ case "DRIVER_DISPOSED":
196
+ case "DRIVER_PROTOCOL":
197
+ case "DRIVER_UNSUPPORTED":
198
+ case "DRIVER_TARGET_NOT_FOUND":
199
+ case "DRIVER_TARGET_AMBIGUOUS":
200
+ case "DRIVER_EVAL_DISABLED":
201
+ return true;
202
+ default:
203
+ return false;
204
+ }
205
+ }
206
+ function isSemanticFingerprintLike(value) {
207
+ return typeof value === "object" && value !== null && "role" in value && typeof value.role === "string" && "name" in value && typeof value.name === "string" && "nth" in value && typeof value.nth === "number" && (!("landmark" in value) || value.landmark === void 0 || typeof value.landmark === "string") && (!("driverId" in value) || value.driverId === void 0 || typeof value.driverId === "string");
208
+ }
209
+ function extractDriverErrorShape(err) {
210
+ if (err instanceof DriverError) {
211
+ return err;
212
+ }
213
+ if (typeof err === "object" && err !== null && "code" in err && isDriverErrorCode(err.code) && "message" in err && typeof err.message === "string") {
214
+ const rawCandidates = "candidates" in err ? err.candidates : void 0;
215
+ const candidates = Array.isArray(rawCandidates) && rawCandidates.every(isSemanticFingerprintLike) ? rawCandidates : void 0;
216
+ return {
217
+ code: err.code,
218
+ message: err.message,
219
+ ...candidates !== void 0 ? { candidates } : {}
220
+ };
221
+ }
222
+ return null;
223
+ }
224
+ function formatToolErrorYaml(err) {
225
+ const driverErr = extractDriverErrorShape(err);
226
+ if (driverErr !== null) {
227
+ const lines = [
228
+ "status: error",
229
+ `code: ${driverErr.code}`,
230
+ `message: ${quoteYamlString(driverErr.message)}`
231
+ ];
232
+ if (driverErr.candidates !== void 0 && driverErr.candidates.length > 0) {
233
+ lines.push("candidates:");
234
+ for (const candidate of driverErr.candidates) {
235
+ lines.push(formatCandidateLine(candidate));
236
+ }
237
+ }
238
+ lines.push(`hint: ${quoteYamlString(hintForDriverErrorCode(driverErr.code))}`);
239
+ return lines.join("\n");
240
+ }
241
+ return [
242
+ "status: error",
243
+ "code: UNEXPECTED_ERROR",
244
+ `message: ${quoteYamlString(err instanceof Error ? err.message : String(err))}`
245
+ ].join("\n");
246
+ }
247
+ function formatObservationYaml(snapshot, maxChars = DEFAULT_OBSERVE_MAX_YAML_CHARS) {
248
+ const lines = [
249
+ `rev: ${String(snapshot.rev)}`,
250
+ `url: ${quoteYamlString(snapshot.url)}`,
251
+ `title: ${quoteYamlString(snapshot.title)}`,
252
+ `viewport: ${String(snapshot.viewport.width)}x${String(snapshot.viewport.height)}`
253
+ ];
254
+ appendDiagnosticsLines(lines, snapshot.diagnostics);
255
+ if (snapshot.elements.length === 0) {
256
+ lines.push("elements: []");
257
+ } else {
258
+ lines.push("elements:");
259
+ appendNodeTreeLines(lines, snapshot.elements, 2, true);
260
+ }
261
+ return truncateYaml(lines.join("\n"), maxChars, DEFAULT_OBSERVE_MAX_YAML_CHARS);
262
+ }
263
+ function formatActResultYaml(result, maxChars = DEFAULT_ACT_MAX_YAML_CHARS) {
264
+ const lines = [
265
+ result.interruptedReason === void 0 ? "status: ok" : `interrupted: ${result.interruptedReason}`,
266
+ `steps: ${String(result.completedSteps)}/${String(result.totalSteps)}`,
267
+ `rev: ${String(result.rev)}`,
268
+ `url: ${quoteYamlString(result.url)}`,
269
+ `title: ${quoteYamlString(result.title)}`
270
+ ];
271
+ if (result.error !== void 0) {
272
+ lines.push(`error: ${quoteYamlString(result.error)}`);
273
+ }
274
+ appendDiagnosticsLines(lines, result.diagnostics);
275
+ const { diff } = result;
276
+ if (diff.fullReset) {
277
+ lines.push("diff:");
278
+ lines.push(" fullReset: true");
279
+ const resetElements = diff.elements ?? [];
280
+ if (resetElements.length === 0) {
281
+ lines.push(" elements: []");
282
+ } else {
283
+ lines.push(" elements:");
284
+ appendNodeTreeLines(lines, resetElements, 4, true);
285
+ }
286
+ } else if (diff.added.length === 0 && diff.changed.length === 0 && diff.removed.length === 0) {
287
+ lines.push("diff: none");
288
+ } else {
289
+ lines.push("diff:");
290
+ if (diff.added.length > 0) {
291
+ lines.push(" added:");
292
+ appendNodeTreeLines(lines, diff.added, 4, true);
293
+ }
294
+ if (diff.changed.length > 0) {
295
+ lines.push(" changed:");
296
+ appendNodeTreeLines(lines, diff.changed, 4, false);
297
+ }
298
+ if (diff.removed.length > 0) {
299
+ lines.push(` removed: [${diff.removed.join(", ")}]`);
300
+ }
301
+ }
302
+ return truncateYaml(lines.join("\n"), maxChars, DEFAULT_ACT_MAX_YAML_CHARS);
303
+ }
304
+ function formatCaptureResultYaml(result) {
305
+ const lines = [
306
+ "status: ok",
307
+ `mimeType: ${quoteYamlString(result.mimeType)}`,
308
+ `width: ${String(result.width)}`,
309
+ `height: ${String(result.height)}`,
310
+ `byteLength: ${String(result.bytes.byteLength)}`,
311
+ `modeUsed: ${result.modeUsed}`
312
+ ];
313
+ if (result.durationMs !== void 0) {
314
+ lines.push(`durationMs: ${String(result.durationMs)}`);
315
+ }
316
+ return lines.join("\n");
317
+ }
318
+ function toSafeJsonValue(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
319
+ if (value === null || value === void 0) return null;
320
+ if (typeof value === "boolean" || typeof value === "string") return value;
321
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
322
+ if (typeof value === "bigint") return `${String(value)}n`;
323
+ if (typeof value === "symbol") return String(value);
324
+ if (typeof value === "function") return `[Function: ${value.name || "anonymous"}]`;
325
+ if (typeof value !== "object") return String(value);
326
+ if (value instanceof Date) {
327
+ return Number.isFinite(value.getTime()) ? value.toISOString() : null;
328
+ }
329
+ if (value instanceof RegExp) {
330
+ return String(value);
331
+ }
332
+ if (value instanceof Error) {
333
+ return {
334
+ name: value.name,
335
+ message: value.message,
336
+ ...value.stack !== void 0 ? { stack: value.stack } : {}
337
+ };
338
+ }
339
+ if (seen.has(value)) return "[Circular]";
340
+ if (depth >= 12) return "[MaxDepth]";
341
+ seen.add(value);
342
+ try {
343
+ if (Array.isArray(value)) {
344
+ return value.map((item) => toSafeJsonValue(item, seen, depth + 1));
345
+ }
346
+ if (value instanceof Set) {
347
+ return [...value].map((item) => toSafeJsonValue(item, seen, depth + 1));
348
+ }
349
+ if (value instanceof Map) {
350
+ return [...value.entries()].map(([k, v]) => [
351
+ toSafeJsonValue(k, seen, depth + 1),
352
+ toSafeJsonValue(v, seen, depth + 1)
353
+ ]);
354
+ }
355
+ const out = {};
356
+ for (const k of Object.keys(value)) {
357
+ try {
358
+ out[k] = toSafeJsonValue(Reflect.get(value, k), seen, depth + 1);
359
+ } catch (err) {
360
+ out[k] = `[GetterError: ${err instanceof Error ? err.message : String(err)}]`;
361
+ }
362
+ }
363
+ return out;
364
+ } finally {
365
+ seen.delete(value);
366
+ }
367
+ }
368
+ function formatEvalResultYaml(result, maxChars = DEFAULT_EVAL_MAX_YAML_CHARS) {
369
+ const safeVal = toSafeJsonValue(result.value);
370
+ const serializedValue = JSON.stringify(safeVal).replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
371
+ const lines = ["status: ok", `value: ${serializedValue}`];
372
+ appendDiagnosticsLines(lines, result.diagnostics);
373
+ return truncateYaml(lines.join("\n"), maxChars, DEFAULT_EVAL_MAX_YAML_CHARS);
374
+ }
375
+
376
+ // src/protocol.ts
377
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
378
+ var isPosSafeInt = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 1;
379
+
380
+ // src/tools/schemas.ts
381
+ var TARGET_SPEC_SCHEMA = {
382
+ description: 'Element ref from ui_observe (e.g. "e3"), data-driver query ({ driver, nth? } or "driver:editor.source"), role query ({ role, name?, nth? }), or text query ({ text, exact? }).',
383
+ anyOf: [
384
+ {
385
+ type: "string",
386
+ description: 'Element ref ID from ui_observe (e.g. "e1") or "driver:<id>" shorthand.'
387
+ },
388
+ {
389
+ type: "object",
390
+ properties: {
391
+ driver: {
392
+ type: "string",
393
+ description: 'Namespaced data-driver attribute value (e.g. "editor.source").'
394
+ },
395
+ nth: { type: "integer", description: "Zero-based index among matching elements." }
396
+ },
397
+ required: ["driver"]
398
+ },
399
+ {
400
+ type: "object",
401
+ properties: {
402
+ role: {
403
+ type: "string",
404
+ description: 'ARIA role such as "button", "textbox", or "slider".'
405
+ },
406
+ name: { type: "string", description: "Accessible name to match." },
407
+ nth: { type: "integer", description: "Zero-based index among matching elements." }
408
+ },
409
+ required: ["role"]
410
+ },
411
+ {
412
+ type: "object",
413
+ properties: {
414
+ text: { type: "string", description: "Visible text content to match." },
415
+ exact: { type: "boolean", description: "Require exact full-text match when true." }
416
+ },
417
+ required: ["text"]
418
+ }
419
+ ]
420
+ };
421
+ var DRAG_DESTINATION_SCHEMA = {
422
+ description: "Drop destination: { target }, relative offset { deltaX, deltaY }, or viewport point { clientX, clientY }.",
423
+ type: "object",
424
+ properties: {
425
+ target: TARGET_SPEC_SCHEMA,
426
+ deltaX: { type: "number" },
427
+ deltaY: { type: "number" },
428
+ clientX: { type: "number" },
429
+ clientY: { type: "number" }
430
+ }
431
+ };
432
+ var DRIVER_STEP_SCHEMA = {
433
+ type: "object",
434
+ description: "Single UI action step: click, fill, setValue, select, press, drag, navigate, or waitFor.",
435
+ properties: {
436
+ kind: {
437
+ type: "string",
438
+ enum: ["click", "fill", "setValue", "select", "press", "drag", "navigate", "waitFor"],
439
+ description: "Action step discriminant."
440
+ },
441
+ target: TARGET_SPEC_SCHEMA,
442
+ button: {
443
+ type: "string",
444
+ enum: ["left", "middle", "right"],
445
+ description: "Mouse button for click steps."
446
+ },
447
+ clickCount: {
448
+ type: "integer",
449
+ description: "Click count (e.g. 2 for double-click)."
450
+ },
451
+ value: {
452
+ description: "Text string (fill), string/number (setValue), or option string/string[] (select)."
453
+ },
454
+ submit: {
455
+ type: "boolean",
456
+ description: "Submit enclosing form after fill when true."
457
+ },
458
+ key: {
459
+ type: "string",
460
+ description: 'Key or chord for press steps (e.g. "Enter", "Control+a").'
461
+ },
462
+ from: TARGET_SPEC_SCHEMA,
463
+ to: DRAG_DESTINATION_SCHEMA,
464
+ steps: {
465
+ type: "integer",
466
+ description: "Intermediate pointer move steps for drag."
467
+ },
468
+ url: {
469
+ type: "string",
470
+ description: "Destination URL for navigate steps (mutually exclusive with action)."
471
+ },
472
+ action: {
473
+ type: "string",
474
+ enum: ["reload", "back", "forward"],
475
+ description: "History navigation action (mutually exclusive with url)."
476
+ },
477
+ text: {
478
+ type: "string",
479
+ description: "Substring text to await in waitFor steps."
480
+ },
481
+ state: {
482
+ type: "string",
483
+ enum: ["attached", "visible", "hidden", "detached"],
484
+ description: "Target element state to await in waitFor steps."
485
+ },
486
+ idleMs: {
487
+ type: "number",
488
+ description: "Network and DOM quiet window in milliseconds for waitFor steps."
489
+ },
490
+ timeoutMs: {
491
+ type: "number",
492
+ description: "Per-step waitFor timeout in milliseconds."
493
+ }
494
+ },
495
+ required: ["kind"]
496
+ };
497
+ var UI_OBSERVE_SCHEMA = {
498
+ type: "object",
499
+ description: "Observe the live UI semantic tree, element refs, media/canvas state, and drained console/page/network/compile diagnostics.",
500
+ properties: {
501
+ scope: {
502
+ type: "string",
503
+ description: 'Optional ref ID (e.g. "e2"), driver prefix ("driver:composer"), role/landmark ("main" or "region:inspector"), or CSS selector ("#inspector") to narrow observation.'
504
+ },
505
+ includeAllText: {
506
+ type: "boolean",
507
+ description: "Include non-interactive static text nodes when true."
508
+ }
509
+ }
510
+ };
511
+ var UI_ACT_SCHEMA = {
512
+ type: "object",
513
+ description: "Execute an ordered transactional batch of UI steps in 1 RTT against a snapshot revision and return the compact UI diff plus diagnostics.",
514
+ properties: {
515
+ rev: {
516
+ type: "integer",
517
+ description: "Snapshot revision from the latest ui_observe or ui_act result (pass 0 if unobserved)."
518
+ },
519
+ steps: {
520
+ type: "array",
521
+ description: "Ordered transactional UI steps to execute sequentially until completion or guard halt.",
522
+ items: DRIVER_STEP_SCHEMA
523
+ },
524
+ timeoutMs: {
525
+ type: "number",
526
+ description: "Optional actionability and batch timeout in milliseconds."
527
+ }
528
+ },
529
+ required: ["rev", "steps"]
530
+ };
531
+ var UI_CAPTURE_SCHEMA = {
532
+ type: "object",
533
+ description: "Capture a visual screenshot (viewport or element target) or start/stop viewport video recording.",
534
+ properties: {
535
+ mode: {
536
+ type: "string",
537
+ enum: ["screenshot", "start_recording", "stop_recording"],
538
+ description: "Capture operation mode."
539
+ },
540
+ target: TARGET_SPEC_SCHEMA,
541
+ format: {
542
+ type: "string",
543
+ enum: ["webp", "png"],
544
+ description: 'Screenshot image format when mode is "screenshot" (default "webp").'
545
+ },
546
+ quality: {
547
+ type: "number",
548
+ description: 'Encoding quality between 0 and 1 when format is "webp".'
549
+ }
550
+ },
551
+ required: ["mode"]
552
+ };
553
+ var UI_EVAL_SCHEMA = {
554
+ type: "object",
555
+ description: "Evaluate a JavaScript expression inside the live guest page and return its sanitized value plus drained diagnostics.",
556
+ properties: {
557
+ expression: {
558
+ type: "string",
559
+ description: "JavaScript expression or async IIFE to evaluate in the page context."
560
+ },
561
+ timeoutMs: {
562
+ type: "number",
563
+ description: "Optional evaluation timeout in milliseconds."
564
+ }
565
+ },
566
+ required: ["expression"]
567
+ };
568
+ function isCanonicalRefId(value) {
569
+ return /^e\d+$/.test(value);
570
+ }
571
+ function isNonNegSafeInt(value) {
572
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
573
+ }
574
+ function isFiniteNum(value) {
575
+ return typeof value === "number" && Number.isFinite(value);
576
+ }
577
+ function isNonNegFinite(value) {
578
+ return isFiniteNum(value) && value >= 0;
579
+ }
580
+ function parseRefIdLike(raw) {
581
+ const trimmed = raw.trim();
582
+ const match = /^(?:\[?\s*ref\s*=\s*(e\d+)\s*\]?|@?(e\d+))$/i.exec(trimmed);
583
+ if (!match) return null;
584
+ const candidate = (match[1] ?? match[2] ?? "").toLowerCase();
585
+ return isCanonicalRefId(candidate) ? candidate : null;
586
+ }
587
+ function parseDriverIdLike(raw) {
588
+ const trimmed = raw.trim();
589
+ const match = /^(?:driver\s*:\s*(.+)|\[\s*driver\s*=\s*([^\]]+)\s*\])$/i.exec(trimmed);
590
+ if (!match) return null;
591
+ const val = (match[1] ?? match[2] ?? "").trim().replace(/^["']|["']$/g, "");
592
+ return val.length > 0 ? val : null;
593
+ }
594
+ function parseTargetSpec(raw, pathLabel) {
595
+ if (typeof raw === "string") {
596
+ const refId = parseRefIdLike(raw);
597
+ if (refId !== null) {
598
+ return { ok: true, value: refId };
599
+ }
600
+ const driverId = parseDriverIdLike(raw);
601
+ if (driverId !== null) {
602
+ return { ok: true, value: { driver: driverId } };
603
+ }
604
+ return {
605
+ ok: false,
606
+ error: `Invalid ${pathLabel}: string target "${raw}" is not a ref ID (expected e.g. "e1", "driver:<id>", { driver, nth? }, { role, name? }, or { text }).`
607
+ };
608
+ }
609
+ if (!isRecord(raw)) {
610
+ return {
611
+ ok: false,
612
+ error: `Invalid ${pathLabel}: expected ref string (e.g. "e1"), { driver, nth? }, { role, name?, nth? }, or { text, exact? }.`
613
+ };
614
+ }
615
+ if (typeof raw["ref"] === "string" && raw["role"] === void 0 && raw["driver"] === void 0 && raw["text"] === void 0) {
616
+ const refId = parseRefIdLike(raw["ref"]);
617
+ if (refId !== null) {
618
+ return { ok: true, value: refId };
619
+ }
620
+ return {
621
+ ok: false,
622
+ error: `Invalid ${pathLabel}.ref: expected ref ID such as "e1".`
623
+ };
624
+ }
625
+ if (raw["driver"] !== void 0) {
626
+ if (typeof raw["driver"] !== "string" || raw["driver"].trim().length === 0) {
627
+ return {
628
+ ok: false,
629
+ error: `Invalid ${pathLabel}.driver: expected a non-empty data-driver string.`
630
+ };
631
+ }
632
+ if (raw["nth"] !== void 0 && !isNonNegSafeInt(raw["nth"])) {
633
+ return {
634
+ ok: false,
635
+ error: `Invalid ${pathLabel}.nth: expected a non-negative integer.`
636
+ };
637
+ }
638
+ return {
639
+ ok: true,
640
+ value: {
641
+ driver: raw["driver"].trim(),
642
+ ...raw["nth"] !== void 0 ? { nth: raw["nth"] } : {}
643
+ }
644
+ };
645
+ }
646
+ if (raw["role"] !== void 0) {
647
+ if (typeof raw["role"] !== "string" || raw["role"].trim().length === 0) {
648
+ return {
649
+ ok: false,
650
+ error: `Invalid ${pathLabel}.role: expected a non-empty ARIA role string.`
651
+ };
652
+ }
653
+ if (raw["name"] !== void 0 && typeof raw["name"] !== "string") {
654
+ return {
655
+ ok: false,
656
+ error: `Invalid ${pathLabel}.name: expected a string.`
657
+ };
658
+ }
659
+ if (raw["nth"] !== void 0 && !isNonNegSafeInt(raw["nth"])) {
660
+ return {
661
+ ok: false,
662
+ error: `Invalid ${pathLabel}.nth: expected a non-negative integer.`
663
+ };
664
+ }
665
+ return {
666
+ ok: true,
667
+ value: {
668
+ role: raw["role"].trim(),
669
+ ...raw["name"] !== void 0 ? { name: raw["name"] } : {},
670
+ ...raw["nth"] !== void 0 ? { nth: raw["nth"] } : {}
671
+ }
672
+ };
673
+ }
674
+ if (raw["text"] !== void 0) {
675
+ if (typeof raw["text"] !== "string" || raw["text"].length === 0) {
676
+ return {
677
+ ok: false,
678
+ error: `Invalid ${pathLabel}.text: expected a non-empty string.`
679
+ };
680
+ }
681
+ if (raw["exact"] !== void 0 && typeof raw["exact"] !== "boolean") {
682
+ return {
683
+ ok: false,
684
+ error: `Invalid ${pathLabel}.exact: expected a boolean.`
685
+ };
686
+ }
687
+ return {
688
+ ok: true,
689
+ value: {
690
+ text: raw["text"],
691
+ ...raw["exact"] !== void 0 ? { exact: raw["exact"] } : {}
692
+ }
693
+ };
694
+ }
695
+ return {
696
+ ok: false,
697
+ error: `Invalid ${pathLabel}: target object must specify "role" or "text" (or pass a ref string like "e1").`
698
+ };
699
+ }
700
+ function parseDragDestination(raw, pathLabel) {
701
+ if (!isRecord(raw)) {
702
+ return {
703
+ ok: false,
704
+ error: `Invalid ${pathLabel}: expected { target }, { deltaX, deltaY }, or { clientX, clientY }.`
705
+ };
706
+ }
707
+ if (raw["target"] !== void 0) {
708
+ const parsedTarget = parseTargetSpec(raw["target"], `${pathLabel}.target`);
709
+ if (!parsedTarget.ok) return parsedTarget;
710
+ return { ok: true, value: { target: parsedTarget.value } };
711
+ }
712
+ if (raw["deltaX"] !== void 0 || raw["deltaY"] !== void 0) {
713
+ if (!isFiniteNum(raw["deltaX"]) || !isFiniteNum(raw["deltaY"])) {
714
+ return {
715
+ ok: false,
716
+ error: `Invalid ${pathLabel}: deltaX and deltaY must both be finite numbers.`
717
+ };
718
+ }
719
+ return { ok: true, value: { deltaX: raw["deltaX"], deltaY: raw["deltaY"] } };
720
+ }
721
+ if (raw["clientX"] !== void 0 || raw["clientY"] !== void 0) {
722
+ if (!isFiniteNum(raw["clientX"]) || !isFiniteNum(raw["clientY"])) {
723
+ return {
724
+ ok: false,
725
+ error: `Invalid ${pathLabel}: clientX and clientY must both be finite numbers.`
726
+ };
727
+ }
728
+ return { ok: true, value: { clientX: raw["clientX"], clientY: raw["clientY"] } };
729
+ }
730
+ return {
731
+ ok: false,
732
+ error: `Invalid ${pathLabel}: expected { target }, { deltaX, deltaY }, or { clientX, clientY }.`
733
+ };
734
+ }
735
+ function parseDriverStep(raw, index) {
736
+ const stepLabel = `ui_act steps[${String(index)}]`;
737
+ if (!isRecord(raw) || typeof raw["kind"] !== "string") {
738
+ return {
739
+ ok: false,
740
+ error: `Invalid ${stepLabel}: expected an object with a string "kind" discriminant.`
741
+ };
742
+ }
743
+ switch (raw["kind"]) {
744
+ case "click": {
745
+ const target = parseTargetSpec(raw["target"], `${stepLabel}.target`);
746
+ if (!target.ok) return target;
747
+ const button = raw["button"];
748
+ if (button !== void 0 && button !== "left" && button !== "middle" && button !== "right") {
749
+ return {
750
+ ok: false,
751
+ error: `Invalid ${stepLabel}.button: expected "left", "middle", or "right".`
752
+ };
753
+ }
754
+ const clickCount = raw["clickCount"];
755
+ if (clickCount !== void 0 && !isPosSafeInt(clickCount)) {
756
+ return {
757
+ ok: false,
758
+ error: `Invalid ${stepLabel}.clickCount: expected a positive integer.`
759
+ };
760
+ }
761
+ return {
762
+ ok: true,
763
+ value: {
764
+ kind: "click",
765
+ target: target.value,
766
+ ...button !== void 0 ? { button } : {},
767
+ ...clickCount !== void 0 ? { clickCount } : {}
768
+ }
769
+ };
770
+ }
771
+ case "fill": {
772
+ const target = parseTargetSpec(raw["target"], `${stepLabel}.target`);
773
+ if (!target.ok) return target;
774
+ if (typeof raw["value"] !== "string") {
775
+ return {
776
+ ok: false,
777
+ error: `Invalid ${stepLabel}.value: expected a string for fill.`
778
+ };
779
+ }
780
+ if (raw["submit"] !== void 0 && typeof raw["submit"] !== "boolean") {
781
+ return {
782
+ ok: false,
783
+ error: `Invalid ${stepLabel}.submit: expected a boolean.`
784
+ };
785
+ }
786
+ return {
787
+ ok: true,
788
+ value: {
789
+ kind: "fill",
790
+ target: target.value,
791
+ value: raw["value"],
792
+ ...raw["submit"] !== void 0 ? { submit: raw["submit"] } : {}
793
+ }
794
+ };
795
+ }
796
+ case "setValue": {
797
+ const target = parseTargetSpec(raw["target"], `${stepLabel}.target`);
798
+ if (!target.ok) return target;
799
+ const val = raw["value"];
800
+ if (typeof val !== "string" && !isFiniteNum(val)) {
801
+ return {
802
+ ok: false,
803
+ error: `Invalid ${stepLabel}.value: expected a string or finite number for setValue.`
804
+ };
805
+ }
806
+ return {
807
+ ok: true,
808
+ value: {
809
+ kind: "setValue",
810
+ target: target.value,
811
+ value: val
812
+ }
813
+ };
814
+ }
815
+ case "select": {
816
+ const target = parseTargetSpec(raw["target"], `${stepLabel}.target`);
817
+ if (!target.ok) return target;
818
+ const val = raw["value"];
819
+ if (typeof val === "string") {
820
+ return { ok: true, value: { kind: "select", target: target.value, value: val } };
821
+ }
822
+ if (Array.isArray(val) && val.every((item) => typeof item === "string")) {
823
+ return { ok: true, value: { kind: "select", target: target.value, value: [...val] } };
824
+ }
825
+ return {
826
+ ok: false,
827
+ error: `Invalid ${stepLabel}.value: expected a string or array of strings for select.`
828
+ };
829
+ }
830
+ case "press": {
831
+ if (typeof raw["key"] !== "string" || raw["key"].trim().length === 0) {
832
+ return {
833
+ ok: false,
834
+ error: `Invalid ${stepLabel}.key: expected a non-empty key string (e.g. "Enter" or "Control+a").`
835
+ };
836
+ }
837
+ let targetSpec;
838
+ if (raw["target"] !== void 0) {
839
+ const parsedTarget = parseTargetSpec(raw["target"], `${stepLabel}.target`);
840
+ if (!parsedTarget.ok) return parsedTarget;
841
+ targetSpec = parsedTarget.value;
842
+ }
843
+ return {
844
+ ok: true,
845
+ value: {
846
+ kind: "press",
847
+ key: raw["key"],
848
+ ...targetSpec !== void 0 ? { target: targetSpec } : {}
849
+ }
850
+ };
851
+ }
852
+ case "drag": {
853
+ const from = parseTargetSpec(raw["from"], `${stepLabel}.from`);
854
+ if (!from.ok) return from;
855
+ const to = parseDragDestination(raw["to"], `${stepLabel}.to`);
856
+ if (!to.ok) return to;
857
+ const steps = raw["steps"];
858
+ if (steps !== void 0 && !isPosSafeInt(steps)) {
859
+ return {
860
+ ok: false,
861
+ error: `Invalid ${stepLabel}.steps: expected a positive integer.`
862
+ };
863
+ }
864
+ return {
865
+ ok: true,
866
+ value: {
867
+ kind: "drag",
868
+ from: from.value,
869
+ to: to.value,
870
+ ...steps !== void 0 ? { steps } : {}
871
+ }
872
+ };
873
+ }
874
+ case "navigate": {
875
+ const hasUrl = raw["url"] !== void 0;
876
+ const hasAction = raw["action"] !== void 0;
877
+ if (hasUrl === hasAction) {
878
+ return {
879
+ ok: false,
880
+ error: `Invalid ${stepLabel}: navigate requires exactly one of "url" or "action".`
881
+ };
882
+ }
883
+ if (hasUrl) {
884
+ if (typeof raw["url"] !== "string" || raw["url"].trim().length === 0) {
885
+ return {
886
+ ok: false,
887
+ error: `Invalid ${stepLabel}.url: expected a non-empty URL string.`
888
+ };
889
+ }
890
+ return { ok: true, value: { kind: "navigate", url: raw["url"] } };
891
+ }
892
+ const action = raw["action"];
893
+ if (action !== "reload" && action !== "back" && action !== "forward") {
894
+ return {
895
+ ok: false,
896
+ error: `Invalid ${stepLabel}.action: expected "reload", "back", or "forward".`
897
+ };
898
+ }
899
+ return { ok: true, value: { kind: "navigate", action } };
900
+ }
901
+ case "waitFor": {
902
+ let targetSpec;
903
+ if (raw["target"] !== void 0) {
904
+ const parsedTarget = parseTargetSpec(raw["target"], `${stepLabel}.target`);
905
+ if (!parsedTarget.ok) return parsedTarget;
906
+ targetSpec = parsedTarget.value;
907
+ }
908
+ const text = raw["text"];
909
+ if (text !== void 0 && typeof text !== "string") {
910
+ return {
911
+ ok: false,
912
+ error: `Invalid ${stepLabel}.text: expected a string.`
913
+ };
914
+ }
915
+ const state = raw["state"];
916
+ if (state !== void 0 && state !== "attached" && state !== "visible" && state !== "hidden" && state !== "detached") {
917
+ return {
918
+ ok: false,
919
+ error: `Invalid ${stepLabel}.state: expected "attached", "visible", "hidden", or "detached".`
920
+ };
921
+ }
922
+ const idleMs = raw["idleMs"];
923
+ if (idleMs !== void 0 && !isNonNegFinite(idleMs)) {
924
+ return {
925
+ ok: false,
926
+ error: `Invalid ${stepLabel}.idleMs: expected a non-negative finite number.`
927
+ };
928
+ }
929
+ const timeoutMs = raw["timeoutMs"];
930
+ if (timeoutMs !== void 0 && !isNonNegFinite(timeoutMs)) {
931
+ return {
932
+ ok: false,
933
+ error: `Invalid ${stepLabel}.timeoutMs: expected a non-negative finite number.`
934
+ };
935
+ }
936
+ if (targetSpec === void 0 && text === void 0 && idleMs === void 0) {
937
+ return {
938
+ ok: false,
939
+ error: `Invalid ${stepLabel} ("waitFor"): specify at least one of "target", "text", or "idleMs".`
940
+ };
941
+ }
942
+ return {
943
+ ok: true,
944
+ value: {
945
+ kind: "waitFor",
946
+ ...targetSpec !== void 0 ? { target: targetSpec } : {},
947
+ ...text !== void 0 ? { text } : {},
948
+ ...state !== void 0 ? { state } : {},
949
+ ...idleMs !== void 0 ? { idleMs } : {},
950
+ ...timeoutMs !== void 0 ? { timeoutMs } : {}
951
+ }
952
+ };
953
+ }
954
+ default:
955
+ return {
956
+ ok: false,
957
+ error: `Invalid ${stepLabel}.kind "${raw["kind"]}": expected click, fill, setValue, select, press, drag, navigate, or waitFor.`
958
+ };
959
+ }
960
+ }
961
+ function normalizeScopeString(raw) {
962
+ const trimmed = raw.trim();
963
+ if (trimmed.length === 0) {
964
+ return void 0;
965
+ }
966
+ const directRef = parseRefIdLike(trimmed);
967
+ if (directRef !== null) {
968
+ return directRef;
969
+ }
970
+ const directDriver = parseDriverIdLike(trimmed);
971
+ if (directDriver !== null) {
972
+ return `driver:${directDriver}`;
973
+ }
974
+ const ariaLineMatch = /^(?:-\s+)?([a-z]+)\s+"([^"]+)"(?:\s*\[ref=(e\d+)\])?:?$/i.exec(trimmed);
975
+ if (ariaLineMatch) {
976
+ if (ariaLineMatch[3] !== void 0) {
977
+ const lineRef = parseRefIdLike(ariaLineMatch[3]);
978
+ if (lineRef !== null) return lineRef;
979
+ }
980
+ const role = (ariaLineMatch[1] ?? "").toLowerCase();
981
+ const name = ariaLineMatch[2] ?? "";
982
+ return `${role}:${name}`;
983
+ }
984
+ return trimmed;
985
+ }
986
+ function parseUiObserveArgs(raw) {
987
+ if (raw === void 0) {
988
+ return { ok: true, value: {} };
989
+ }
990
+ if (!isRecord(raw)) {
991
+ return {
992
+ ok: false,
993
+ error: "Invalid ui_observe arguments: expected an object or undefined."
994
+ };
995
+ }
996
+ let normalizedScope;
997
+ if (raw["scope"] !== void 0) {
998
+ if (typeof raw["scope"] !== "string") {
999
+ return {
1000
+ ok: false,
1001
+ error: 'Invalid ui_observe "scope": expected a string.'
1002
+ };
1003
+ }
1004
+ normalizedScope = normalizeScopeString(raw["scope"]);
1005
+ }
1006
+ if (raw["includeAllText"] !== void 0 && typeof raw["includeAllText"] !== "boolean") {
1007
+ return {
1008
+ ok: false,
1009
+ error: 'Invalid ui_observe "includeAllText": expected a boolean.'
1010
+ };
1011
+ }
1012
+ return {
1013
+ ok: true,
1014
+ value: {
1015
+ ...normalizedScope !== void 0 ? { scope: normalizedScope } : {},
1016
+ ...raw["includeAllText"] !== void 0 ? { includeAllText: raw["includeAllText"] } : {}
1017
+ }
1018
+ };
1019
+ }
1020
+ function parseUiActArgs(raw) {
1021
+ if (!isRecord(raw)) {
1022
+ return {
1023
+ ok: false,
1024
+ error: 'Invalid ui_act arguments: expected an object with "rev" and "steps".'
1025
+ };
1026
+ }
1027
+ if (!isNonNegSafeInt(raw["rev"])) {
1028
+ return {
1029
+ ok: false,
1030
+ error: 'Invalid ui_act "rev": expected a non-negative integer snapshot revision (pass 0 if unobserved).'
1031
+ };
1032
+ }
1033
+ if (!Array.isArray(raw["steps"])) {
1034
+ return {
1035
+ ok: false,
1036
+ error: 'Invalid ui_act "steps": expected an array of DriverStep objects.'
1037
+ };
1038
+ }
1039
+ if (raw["timeoutMs"] !== void 0 && !isNonNegFinite(raw["timeoutMs"])) {
1040
+ return {
1041
+ ok: false,
1042
+ error: 'Invalid ui_act "timeoutMs": expected a non-negative finite number.'
1043
+ };
1044
+ }
1045
+ const normalizedSteps = [];
1046
+ for (let i = 0; i < raw["steps"].length; i += 1) {
1047
+ const parsedStep = parseDriverStep(raw["steps"][i], i);
1048
+ if (!parsedStep.ok) return parsedStep;
1049
+ normalizedSteps.push(parsedStep.value);
1050
+ }
1051
+ return {
1052
+ ok: true,
1053
+ value: {
1054
+ rev: raw["rev"],
1055
+ steps: normalizedSteps,
1056
+ ...raw["timeoutMs"] !== void 0 ? { timeoutMs: raw["timeoutMs"] } : {}
1057
+ }
1058
+ };
1059
+ }
1060
+ function parseUiCaptureArgs(raw) {
1061
+ if (!isRecord(raw)) {
1062
+ return {
1063
+ ok: false,
1064
+ error: 'Invalid ui_capture arguments: expected an object with "mode".'
1065
+ };
1066
+ }
1067
+ const mode = raw["mode"];
1068
+ if (mode === "start_recording" || mode === "stop_recording") {
1069
+ if (raw["target"] !== void 0) {
1070
+ return {
1071
+ ok: false,
1072
+ error: `Invalid ui_capture "target": target is only supported when mode is "screenshot".`
1073
+ };
1074
+ }
1075
+ return { ok: true, value: { mode } };
1076
+ }
1077
+ if (mode !== "screenshot") {
1078
+ return {
1079
+ ok: false,
1080
+ error: 'Invalid ui_capture "mode": expected "screenshot", "start_recording", or "stop_recording".'
1081
+ };
1082
+ }
1083
+ let targetSpec;
1084
+ if (raw["target"] !== void 0) {
1085
+ const parsedTarget = parseTargetSpec(raw["target"], "ui_capture.target");
1086
+ if (!parsedTarget.ok) return parsedTarget;
1087
+ targetSpec = parsedTarget.value;
1088
+ }
1089
+ const format = raw["format"];
1090
+ if (format !== void 0 && format !== "webp" && format !== "png") {
1091
+ return {
1092
+ ok: false,
1093
+ error: 'Invalid ui_capture "format": expected "webp" or "png".'
1094
+ };
1095
+ }
1096
+ const quality = raw["quality"];
1097
+ if (quality !== void 0 && (!isFiniteNum(quality) || quality < 0 || quality > 1)) {
1098
+ return {
1099
+ ok: false,
1100
+ error: 'Invalid ui_capture "quality": expected a finite number between 0 and 1.'
1101
+ };
1102
+ }
1103
+ return {
1104
+ ok: true,
1105
+ value: {
1106
+ mode: "screenshot",
1107
+ ...targetSpec !== void 0 ? { target: targetSpec } : {},
1108
+ ...format !== void 0 ? { format } : {},
1109
+ ...quality !== void 0 ? { quality } : {}
1110
+ }
1111
+ };
1112
+ }
1113
+ function parseUiEvalArgs(raw) {
1114
+ if (!isRecord(raw)) {
1115
+ return {
1116
+ ok: false,
1117
+ error: 'Invalid ui_eval arguments: expected an object with "expression".'
1118
+ };
1119
+ }
1120
+ if (typeof raw["expression"] !== "string" || raw["expression"].trim().length === 0) {
1121
+ return {
1122
+ ok: false,
1123
+ error: 'Invalid ui_eval "expression": expected a non-empty JavaScript expression string.'
1124
+ };
1125
+ }
1126
+ if (raw["timeoutMs"] !== void 0 && !isNonNegFinite(raw["timeoutMs"])) {
1127
+ return {
1128
+ ok: false,
1129
+ error: 'Invalid ui_eval "timeoutMs": expected a non-negative finite number.'
1130
+ };
1131
+ }
1132
+ return {
1133
+ ok: true,
1134
+ value: {
1135
+ expression: raw["expression"],
1136
+ ...raw["timeoutMs"] !== void 0 ? { timeoutMs: raw["timeoutMs"] } : {}
1137
+ }
1138
+ };
1139
+ }
1140
+
1141
+ // src/tools/index.ts
1142
+ function createDriverTools(driver, options) {
1143
+ const maxYamlChars = options?.maxYamlChars;
1144
+ const allowEval = options?.allowEval === true;
1145
+ const observeTool = {
1146
+ name: "ui_observe",
1147
+ description: "Observe the live UI semantic tree, element refs, media/canvas state, and drained console/page/network/compile diagnostics.",
1148
+ parameters: UI_OBSERVE_SCHEMA,
1149
+ parallelSafe: false,
1150
+ pure: false,
1151
+ async execute(rawArgs, ctx) {
1152
+ const parsed = parseUiObserveArgs(rawArgs);
1153
+ if (!parsed.ok) {
1154
+ return { ok: false, summary: formatValidationErrorYaml(parsed.error) };
1155
+ }
1156
+ try {
1157
+ const hasOptions = parsed.value.scope !== void 0 || parsed.value.includeAllText !== void 0 || ctx?.signal !== void 0;
1158
+ const snapshot = await driver.observe(
1159
+ hasOptions ? {
1160
+ ...parsed.value.scope !== void 0 ? { scope: parsed.value.scope } : {},
1161
+ ...parsed.value.includeAllText !== void 0 ? { includeAllText: parsed.value.includeAllText } : {},
1162
+ ...ctx?.signal !== void 0 ? { signal: ctx.signal } : {}
1163
+ } : void 0
1164
+ );
1165
+ return {
1166
+ ok: true,
1167
+ summary: formatObservationYaml(snapshot, maxYamlChars),
1168
+ data: snapshot
1169
+ };
1170
+ } catch (err) {
1171
+ return { ok: false, summary: formatToolErrorYaml(err) };
1172
+ }
1173
+ }
1174
+ };
1175
+ const actTool = {
1176
+ name: "ui_act",
1177
+ description: "Execute a transactional batch of UI steps in 1 RTT against a snapshot revision and return the compact diff plus diagnostics.",
1178
+ parameters: UI_ACT_SCHEMA,
1179
+ parallelSafe: false,
1180
+ pure: false,
1181
+ async execute(rawArgs, ctx) {
1182
+ const parsed = parseUiActArgs(rawArgs);
1183
+ if (!parsed.ok) {
1184
+ return { ok: false, summary: formatValidationErrorYaml(parsed.error) };
1185
+ }
1186
+ try {
1187
+ const result = await driver.act({
1188
+ rev: parsed.value.rev,
1189
+ steps: parsed.value.steps,
1190
+ ...parsed.value.timeoutMs !== void 0 ? { timeoutMs: parsed.value.timeoutMs } : {},
1191
+ ...ctx?.signal !== void 0 ? { signal: ctx.signal } : {}
1192
+ });
1193
+ return {
1194
+ ok: result.interruptedReason === void 0,
1195
+ summary: formatActResultYaml(result, maxYamlChars),
1196
+ data: result
1197
+ };
1198
+ } catch (err) {
1199
+ return { ok: false, summary: formatToolErrorYaml(err) };
1200
+ }
1201
+ }
1202
+ };
1203
+ const captureTool = {
1204
+ name: "ui_capture",
1205
+ description: "Capture a visual screenshot (viewport or element target) or start/stop viewport video recording.",
1206
+ parameters: UI_CAPTURE_SCHEMA,
1207
+ parallelSafe: false,
1208
+ pure: false,
1209
+ async execute(rawArgs, ctx) {
1210
+ const parsed = parseUiCaptureArgs(rawArgs);
1211
+ if (!parsed.ok) {
1212
+ return { ok: false, summary: formatValidationErrorYaml(parsed.error) };
1213
+ }
1214
+ try {
1215
+ const captureResult = await driver.capture({
1216
+ ...parsed.value,
1217
+ ...ctx?.signal !== void 0 ? { signal: ctx.signal } : {}
1218
+ });
1219
+ return {
1220
+ ok: true,
1221
+ summary: formatCaptureResultYaml(captureResult),
1222
+ data: captureResult
1223
+ };
1224
+ } catch (err) {
1225
+ return { ok: false, summary: formatToolErrorYaml(err) };
1226
+ }
1227
+ }
1228
+ };
1229
+ if (!allowEval) {
1230
+ return [observeTool, actTool, captureTool];
1231
+ }
1232
+ const evalTool = {
1233
+ name: "ui_eval",
1234
+ description: "Evaluate a JavaScript expression inside the live guest page and return its sanitized value plus drained diagnostics.",
1235
+ parameters: UI_EVAL_SCHEMA,
1236
+ parallelSafe: false,
1237
+ pure: false,
1238
+ async execute(rawArgs, ctx) {
1239
+ if (!driver.capabilities.allowEval) {
1240
+ return {
1241
+ ok: false,
1242
+ summary: formatToolErrorYaml(
1243
+ new DriverError(
1244
+ "DRIVER_EVAL_DISABLED",
1245
+ "JavaScript evaluation is disabled on this PageDriver (capabilities.allowEval is false)."
1246
+ )
1247
+ )
1248
+ };
1249
+ }
1250
+ const parsed = parseUiEvalArgs(rawArgs);
1251
+ if (!parsed.ok) {
1252
+ return { ok: false, summary: formatValidationErrorYaml(parsed.error) };
1253
+ }
1254
+ try {
1255
+ const evalResult = await driver.eval({
1256
+ expression: parsed.value.expression,
1257
+ ...parsed.value.timeoutMs !== void 0 ? { timeoutMs: parsed.value.timeoutMs } : {},
1258
+ ...ctx?.signal !== void 0 ? { signal: ctx.signal } : {}
1259
+ });
1260
+ return {
1261
+ ok: true,
1262
+ summary: formatEvalResultYaml(evalResult, maxYamlChars),
1263
+ data: evalResult
1264
+ };
1265
+ } catch (err) {
1266
+ return { ok: false, summary: formatToolErrorYaml(err) };
1267
+ }
1268
+ }
1269
+ };
1270
+ return [observeTool, actTool, captureTool, evalTool];
1271
+ }
1272
+ export {
1273
+ UI_ACT_SCHEMA,
1274
+ UI_CAPTURE_SCHEMA,
1275
+ UI_EVAL_SCHEMA,
1276
+ UI_OBSERVE_SCHEMA,
1277
+ createDriverTools,
1278
+ formatActResultYaml,
1279
+ formatCaptureResultYaml,
1280
+ formatEvalResultYaml,
1281
+ formatObservationYaml
1282
+ };
1283
+ //# sourceMappingURL=tools.js.map