@monkeytestai/monkeytester 0.0.0-stage → 0.5.1

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 (113) hide show
  1. package/CHANGELOG.md +179 -0
  2. package/LICENSE +661 -0
  3. package/NOTICE +12 -0
  4. package/README.md +196 -2
  5. package/dist/cli.d.ts +43 -0
  6. package/dist/cli.d.ts.map +1 -0
  7. package/dist/cli.js +774 -0
  8. package/dist/cli.js.map +1 -0
  9. package/dist/diff/index.d.ts +78 -0
  10. package/dist/diff/index.d.ts.map +1 -0
  11. package/dist/diff/index.js +119 -0
  12. package/dist/diff/index.js.map +1 -0
  13. package/dist/events.d.ts +66 -0
  14. package/dist/events.d.ts.map +1 -0
  15. package/dist/events.js +77 -0
  16. package/dist/events.js.map +1 -0
  17. package/dist/explorer/index.d.ts +131 -0
  18. package/dist/explorer/index.d.ts.map +1 -0
  19. package/dist/explorer/index.js +675 -0
  20. package/dist/explorer/index.js.map +1 -0
  21. package/dist/explorer/queue.d.ts +94 -0
  22. package/dist/explorer/queue.d.ts.map +1 -0
  23. package/dist/explorer/queue.js +277 -0
  24. package/dist/explorer/queue.js.map +1 -0
  25. package/dist/index.d.ts +36 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +22 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/llm/coerce.d.ts +59 -0
  30. package/dist/llm/coerce.d.ts.map +1 -0
  31. package/dist/llm/coerce.js +246 -0
  32. package/dist/llm/coerce.js.map +1 -0
  33. package/dist/llm/index.d.ts +79 -0
  34. package/dist/llm/index.d.ts.map +1 -0
  35. package/dist/llm/index.js +392 -0
  36. package/dist/llm/index.js.map +1 -0
  37. package/dist/llm/presets.d.ts +61 -0
  38. package/dist/llm/presets.d.ts.map +1 -0
  39. package/dist/llm/presets.js +101 -0
  40. package/dist/llm/presets.js.map +1 -0
  41. package/dist/monkey.d.ts +151 -0
  42. package/dist/monkey.d.ts.map +1 -0
  43. package/dist/monkey.js +323 -0
  44. package/dist/monkey.js.map +1 -0
  45. package/dist/persistence/index.d.ts +118 -0
  46. package/dist/persistence/index.d.ts.map +1 -0
  47. package/dist/persistence/index.js +196 -0
  48. package/dist/persistence/index.js.map +1 -0
  49. package/dist/planner/faults.d.ts +24 -0
  50. package/dist/planner/faults.d.ts.map +1 -0
  51. package/dist/planner/faults.js +128 -0
  52. package/dist/planner/faults.js.map +1 -0
  53. package/dist/planner/forms.d.ts +33 -0
  54. package/dist/planner/forms.d.ts.map +1 -0
  55. package/dist/planner/forms.js +163 -0
  56. package/dist/planner/forms.js.map +1 -0
  57. package/dist/planner/index.d.ts +31 -0
  58. package/dist/planner/index.d.ts.map +1 -0
  59. package/dist/planner/index.js +252 -0
  60. package/dist/planner/index.js.map +1 -0
  61. package/dist/planner/salvage.d.ts +16 -0
  62. package/dist/planner/salvage.d.ts.map +1 -0
  63. package/dist/planner/salvage.js +107 -0
  64. package/dist/planner/salvage.js.map +1 -0
  65. package/dist/runner/actions.d.ts +91 -0
  66. package/dist/runner/actions.d.ts.map +1 -0
  67. package/dist/runner/actions.js +659 -0
  68. package/dist/runner/actions.js.map +1 -0
  69. package/dist/runner/evidence.d.ts +37 -0
  70. package/dist/runner/evidence.d.ts.map +1 -0
  71. package/dist/runner/evidence.js +122 -0
  72. package/dist/runner/evidence.js.map +1 -0
  73. package/dist/runner/http5xx.d.ts +40 -0
  74. package/dist/runner/http5xx.d.ts.map +1 -0
  75. package/dist/runner/http5xx.js +189 -0
  76. package/dist/runner/http5xx.js.map +1 -0
  77. package/dist/runner/index.d.ts +88 -0
  78. package/dist/runner/index.d.ts.map +1 -0
  79. package/dist/runner/index.js +600 -0
  80. package/dist/runner/index.js.map +1 -0
  81. package/dist/runner/replay.d.ts +42 -0
  82. package/dist/runner/replay.d.ts.map +1 -0
  83. package/dist/runner/replay.js +458 -0
  84. package/dist/runner/replay.js.map +1 -0
  85. package/dist/runner/timeout.d.ts +16 -0
  86. package/dist/runner/timeout.d.ts.map +1 -0
  87. package/dist/runner/timeout.js +38 -0
  88. package/dist/runner/timeout.js.map +1 -0
  89. package/dist/trace/fingerprint.d.ts +78 -0
  90. package/dist/trace/fingerprint.d.ts.map +1 -0
  91. package/dist/trace/fingerprint.js +273 -0
  92. package/dist/trace/fingerprint.js.map +1 -0
  93. package/dist/trace/serialize.d.ts +15 -0
  94. package/dist/trace/serialize.d.ts.map +1 -0
  95. package/dist/trace/serialize.js +86 -0
  96. package/dist/trace/serialize.js.map +1 -0
  97. package/dist/triager/index.d.ts +86 -0
  98. package/dist/triager/index.d.ts.map +1 -0
  99. package/dist/triager/index.js +322 -0
  100. package/dist/triager/index.js.map +1 -0
  101. package/dist/types.d.ts +497 -0
  102. package/dist/types.d.ts.map +1 -0
  103. package/dist/types.js +10 -0
  104. package/dist/types.js.map +1 -0
  105. package/dist/verify/index.d.ts +52 -0
  106. package/dist/verify/index.d.ts.map +1 -0
  107. package/dist/verify/index.js +140 -0
  108. package/dist/verify/index.js.map +1 -0
  109. package/dist/verify/verdict.d.ts +34 -0
  110. package/dist/verify/verdict.d.ts.map +1 -0
  111. package/dist/verify/verdict.js +89 -0
  112. package/dist/verify/verdict.js.map +1 -0
  113. package/package.json +90 -4
@@ -0,0 +1,659 @@
1
+ /**
2
+ * Translate a plan step into a Playwright action, execute it, and capture a
3
+ * stable locator (role, name, text, test id, CSS fallback) for later replay.
4
+ */
5
+ import { z } from 'zod';
6
+ import { clipText, coerceEnum, coerceToString, unwrapModelObject } from '../llm/coerce.js';
7
+ const ACTION_TOOLS = ['click', 'fill', 'goto', 'wait', 'assert_text', 'press', 'noop'];
8
+ const ACTION_LOCATORS = ['css', 'role', 'text', 'placeholder', 'label', 'testid'];
9
+ const TOOL_ALIASES = {
10
+ type: 'fill',
11
+ input: 'fill',
12
+ fill_in: 'fill',
13
+ navigate: 'goto',
14
+ open: 'goto',
15
+ visit: 'goto',
16
+ assert: 'assert_text',
17
+ asserttext: 'assert_text',
18
+ check_text: 'assert_text',
19
+ keypress: 'press',
20
+ key: 'press',
21
+ none: 'noop',
22
+ skip: 'noop',
23
+ tap: 'click',
24
+ wait_for: 'wait',
25
+ };
26
+ const LOCATOR_ALIASES = {
27
+ css_selector: 'css',
28
+ selector: 'css',
29
+ visible_text: 'text',
30
+ test_id: 'testid',
31
+ data_testid: 'testid',
32
+ aria_label: 'label',
33
+ };
34
+ function coerceActionInput(value) {
35
+ const unwrapped = unwrapModelObject(value, ['tool', 'action', 'target', 'selector']);
36
+ if (!unwrapped || typeof unwrapped !== 'object' || Array.isArray(unwrapped))
37
+ return unwrapped;
38
+ const record = unwrapped;
39
+ const tool = coerceEnum(record.tool ?? record.action, ACTION_TOOLS, TOOL_ALIASES);
40
+ const locator = coerceEnum(record.locator ?? record.strategy, ACTION_LOCATORS, LOCATOR_ALIASES);
41
+ const target = coerceToString(record.target ?? record.selector ?? record.url ?? record.element);
42
+ const filled = coerceToString(record.value ?? record.input ?? record.key);
43
+ const rationale = coerceToString(record.rationale ?? record.reason);
44
+ return {
45
+ ...(tool ? { tool } : {}),
46
+ ...(locator ? { locator } : {}),
47
+ ...(target ? { target } : {}),
48
+ ...(filled !== undefined ? { value: filled } : {}),
49
+ ...(rationale ? { rationale: clipText(rationale, 400) } : {}),
50
+ };
51
+ }
52
+ export const ActionSchema = z.preprocess(coerceActionInput, z.object({
53
+ tool: z.enum(ACTION_TOOLS),
54
+ /** CSS selector, URL (for goto), test id, or text snippet (for assert_text). */
55
+ target: z.string().optional(),
56
+ /** Value to type (for fill) or key chord (for press). */
57
+ value: z.string().optional(),
58
+ /**
59
+ * Locator strategy hint. Role / text / label / testid survive DOM reshuffles
60
+ * better than a raw CSS selector.
61
+ */
62
+ locator: z.enum(ACTION_LOCATORS).optional(),
63
+ /** One-sentence explanation, useful for the report timeline. */
64
+ rationale: z.string().optional(),
65
+ }));
66
+ /**
67
+ * Execute a step whose wording names a control that is already on screen.
68
+ *
69
+ * `Click "Save order"` and `Fill the "email" field` do not need a model.
70
+ * A step that does not quote a visible label returns null and the caller
71
+ * falls through to `resolveAction`.
72
+ */
73
+ export function directActionFromStep(action, skeleton) {
74
+ const fill = action.match(/\bfill(?:\s+in)?\s+the\s+["“]([^"”]+)["”]\s+field/i);
75
+ if (fill) {
76
+ const field = fill[1].trim();
77
+ const nameHint = action.match(/\bname\s*=\s*["“']([^"”']+)["”']/i)?.[1]?.trim();
78
+ const input = (nameHint && findInput(skeleton.inputs, nameHint)) || findInput(skeleton.inputs, field);
79
+ if (!input)
80
+ return null;
81
+ return fillActionForInput(input, undefined, `Field "${field}" is on the page.`);
82
+ }
83
+ const quoted = action.match(/(?:click|press|tap)(?:ing)?\s+(?:the\s+)?["“]([^"”]+)["”]/i);
84
+ const plain = action.match(/^(?:please\s+)?(?:click|press|tap)\s+(?:the\s+)?(.+?)(?:\s+(?:button|link))?[.!]?\s*$/i);
85
+ const label = (quoted?.[1] || (plain && matchesControl(skeleton, plain[1].trim()) ? plain[1].trim() : '')).trim();
86
+ if (!label)
87
+ return null;
88
+ const wantsLink = /\blink\b/i.test(action) && !/\bbutton\b/i.test(action);
89
+ const button = findText(skeleton.buttons, label);
90
+ const link = skeleton.links.find(item => item.text.trim().toLowerCase() === label.toLowerCase());
91
+ if (wantsLink && link) {
92
+ return clickAction('link', link.text);
93
+ }
94
+ if (button && !wantsLink)
95
+ return clickAction('button', button);
96
+ if (link)
97
+ return clickAction('link', link.text);
98
+ if (button)
99
+ return clickAction('button', button);
100
+ return null;
101
+ }
102
+ function clickAction(role, label) {
103
+ return {
104
+ tool: 'click',
105
+ locator: 'role',
106
+ target: `${role}:${label}`,
107
+ rationale: `${role} "${label}" is on the page.`,
108
+ };
109
+ }
110
+ function matchesControl(skeleton, label) {
111
+ return Boolean(findText(skeleton.buttons, label) || skeleton.links.some(link => link.text.trim().toLowerCase() === label.toLowerCase()));
112
+ }
113
+ function findText(values, label) {
114
+ const needle = label.trim().toLowerCase();
115
+ return values.find(value => value.trim().toLowerCase() === needle);
116
+ }
117
+ /**
118
+ * A model often answers `placeholder:Email` for a box whose only identity is
119
+ * its label or `name`. Prefer those. Placeholder remains when it is all the
120
+ * page exposed.
121
+ */
122
+ export function groundFillAction(action, skeleton) {
123
+ if (action.tool !== 'fill')
124
+ return action;
125
+ if (action.locator === 'role' || action.locator === 'testid')
126
+ return action;
127
+ const wanted = (action.target || '').trim();
128
+ if (!wanted)
129
+ return action;
130
+ if (action.locator === 'css' && (inputByNameSelector(skeleton.inputs, wanted) || /[[\]#.=]/.test(wanted))) {
131
+ return action;
132
+ }
133
+ const placeholderOnly = action.locator === 'placeholder'
134
+ ? findInput(skeleton.inputs, wanted, 'placeholder')
135
+ : undefined;
136
+ if (placeholderOnly && !placeholderOnly.label && !placeholderOnly.name)
137
+ return action;
138
+ const input = placeholderOnly || findInput(skeleton.inputs, wanted);
139
+ if (!input || (!input.label && !input.name))
140
+ return action;
141
+ const grounded = fillActionForInput(input, action.value, action.rationale);
142
+ if (action.locator === grounded.locator && action.target === grounded.target)
143
+ return action;
144
+ const inventedPlaceholder = action.locator === 'placeholder';
145
+ const labelMiss = action.locator === 'label' && !(input.label && sameField(input.label, wanted) && action.target === input.label);
146
+ const bareCss = !action.locator || (action.locator === 'css' && !/[[\]#.=]/.test(wanted));
147
+ if (!inventedPlaceholder && !labelMiss && !bareCss)
148
+ return action;
149
+ return {
150
+ ...action,
151
+ locator: grounded.locator,
152
+ target: grounded.target,
153
+ value: action.value ?? grounded.value,
154
+ rationale: grounded.rationale,
155
+ };
156
+ }
157
+ function fillActionForInput(input, value, rationale) {
158
+ const sample = value ?? sampleFieldValue(input);
159
+ if (input.label) {
160
+ return {
161
+ tool: 'fill',
162
+ locator: 'label',
163
+ target: input.label,
164
+ value: sample,
165
+ rationale: rationale || `Label "${input.label}" is on the page.`,
166
+ };
167
+ }
168
+ if (input.name) {
169
+ return {
170
+ tool: 'fill',
171
+ locator: 'css',
172
+ target: nameSelector(input.name),
173
+ value: sample,
174
+ rationale: rationale || `Input name "${input.name}" is on the page.`,
175
+ };
176
+ }
177
+ return {
178
+ tool: 'fill',
179
+ locator: 'placeholder',
180
+ target: input.placeholder || '',
181
+ value: sample,
182
+ rationale: rationale || `Placeholder "${input.placeholder}" is on the page.`,
183
+ };
184
+ }
185
+ function findInput(inputs, wanted, only) {
186
+ const keys = only ? [only] : ['name', 'label', 'placeholder'];
187
+ return inputs.find(input => keys.some(key => sameField(input[key], wanted)));
188
+ }
189
+ function inputByNameSelector(inputs, target) {
190
+ return inputs.find(input => input.name && nameSelector(input.name) === target);
191
+ }
192
+ function sameField(value, wanted) {
193
+ return Boolean(value && value.trim().toLowerCase() === wanted.trim().toLowerCase());
194
+ }
195
+ function nameSelector(name) {
196
+ return `[name="${name.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"]`;
197
+ }
198
+ function sampleFieldValue(input) {
199
+ const blob = `${input.type || ''} ${input.name || ''} ${input.label || ''} ${input.placeholder || ''}`.toLowerCase();
200
+ if (blob.includes('email'))
201
+ return 'qa@example.com';
202
+ if (blob.includes('phone') || blob.includes('tel'))
203
+ return '555-0100';
204
+ if (blob.includes('url') || blob.includes('website'))
205
+ return 'https://example.com';
206
+ if (/\bdate\b/.test(blob))
207
+ return '2026-01-15';
208
+ if (input.type === 'number' || blob.includes('qty') || blob.includes('quantity'))
209
+ return '1';
210
+ if (blob.includes('message') || blob.includes('comment') || input.type === 'textarea')
211
+ return 'Hello from monkeytest';
212
+ if (blob.includes('name'))
213
+ return 'Test User';
214
+ return 'test';
215
+ }
216
+ export async function resolveAction(llm, flow, step, skeleton) {
217
+ const prompt = `
218
+ You are translating a single natural-language test step into a concrete browser
219
+ action that a Playwright agent can execute.
220
+
221
+ You MUST reply with a JSON object, no prose, no markdown.
222
+
223
+ Schema:
224
+ tool: "click" | "fill" | "goto" | "wait" | "assert_text" | "press" | "noop"
225
+ target: string — CSS selector, role-like description, or URL/text (see examples)
226
+ value: string (optional) — value to type for "fill", or key for "press" (e.g. "Enter")
227
+ locator: "css" | "role" | "text" | "placeholder" | "label" | "testid" (optional, default "css")
228
+ rationale: string (optional) — one short sentence explaining your choice
229
+
230
+ Tool semantics:
231
+ click — click the element identified by target+locator
232
+ fill — type \`value\` into the element identified by target+locator
233
+ goto — navigate to URL in target
234
+ wait — wait for selector in target to appear (use sparingly)
235
+ assert_text — observe whether the page contains the text in target. Missing text is not a bug by itself.
236
+ press — press a key (target = optional selector, value = key like "Enter")
237
+ noop — only use this when the step is impossible (e.g. asks for real signup)
238
+
239
+ Locator guidance:
240
+ - Prefer "testid", "role", "label", "placeholder", or "text" when CSS selectors aren't obvious.
241
+ - For testid: target is the data-testid value.
242
+ - For role: target like "button:Sign in" or "link:Pricing" or "textbox:Email".
243
+ - For text: target is the visible text.
244
+ - For label: target is the form label text.
245
+ - For placeholder: target is the input placeholder text.
246
+ - If the control is not in the skeleton, use "noop" rather than guessing a selector.
247
+ - Never invent selectors, search boxes, or exact page titles. Use only elements visible in the skeleton.
248
+ - Do not turn page-title expectations into bugs; exploratory users observe what loaded.
249
+ - If the step asks to log in, enter OTP, or create an account, use "noop".
250
+ - "tool" and "locator" are exact lowercase strings from the lists above, not objects.
251
+ - "target" and "value" are strings. Omit a key instead of sending null.
252
+
253
+ Context:
254
+ Flow: ${flow.name} (${flow.kind})
255
+ Flow goal: ${flow.expectation}
256
+ Step: ${step.action}
257
+ Expectation: ${step.expectation || '(none stated)'}
258
+ Current URL: ${skeleton.url}
259
+ Page title: ${skeleton.title}
260
+
261
+ Visible page skeleton (top of body):
262
+ Headings: ${skeleton.headings.slice(0, 8).join(' | ') || '(none)'}
263
+ Buttons: ${skeleton.buttons.slice(0, 12).join(' | ') || '(none)'}
264
+ Links: ${skeleton.links.slice(0, 12).map(l => l.text).join(' | ') || '(none)'}
265
+ Inputs: ${skeleton.inputs.slice(0, 12).map(i => `${i.label || i.placeholder || i.name || i.type}`).join(' | ') || '(none)'}
266
+
267
+ Reply with JSON only.`;
268
+ const raw = await llm.generateJSON({
269
+ label: 'runner.resolveAction',
270
+ prompt,
271
+ schema: ActionSchema,
272
+ });
273
+ return ActionSchema.parse(raw);
274
+ }
275
+ export async function executeAction(page, action, timeoutMs, options) {
276
+ try {
277
+ switch (action.tool) {
278
+ case 'click': {
279
+ const locator = buildLocator(page, action);
280
+ if (options?.strictOracles) {
281
+ const disabled = await failIfDisabled(locator, action);
282
+ if (disabled)
283
+ return disabled;
284
+ }
285
+ await locator.first().click({ timeout: timeoutMs });
286
+ await settleSPA(page).catch(() => { });
287
+ return { status: 'passed', observation: `Clicked ${describeTarget(action)}.` };
288
+ }
289
+ case 'fill': {
290
+ const locator = buildLocator(page, action);
291
+ await locator.first().fill(action.value ?? '', { timeout: timeoutMs });
292
+ return { status: 'passed', observation: `Typed "${truncate(action.value ?? '', 40)}" into ${describeTarget(action)}.` };
293
+ }
294
+ case 'goto': {
295
+ const url = action.target || '';
296
+ if (!/^https?:\/\//.test(url)) {
297
+ return { status: 'failed', observation: `Refused to navigate to non-http URL "${url}".`, error: 'invalid_url' };
298
+ }
299
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: timeoutMs });
300
+ await settleSPA(page).catch(() => { });
301
+ return { status: 'passed', observation: `Navigated to ${url}.` };
302
+ }
303
+ case 'wait': {
304
+ const locator = buildLocator(page, action);
305
+ await locator.first().waitFor({ state: 'visible', timeout: timeoutMs });
306
+ return { status: 'passed', observation: `Confirmed ${describeTarget(action)} is visible.` };
307
+ }
308
+ case 'assert_text': {
309
+ const text = action.target || '';
310
+ if (!text)
311
+ return { status: 'skipped', observation: 'No text supplied for observation.' };
312
+ const found = await page.locator('body').filter({ hasText: text }).first().count();
313
+ if (found > 0) {
314
+ return { status: 'passed', observation: `Observed "${truncate(text, 60)}" on the page.` };
315
+ }
316
+ return {
317
+ status: 'skipped',
318
+ observation: `Did not observe "${truncate(text, 60)}" on the page. Treated as an exploratory observation, not a product bug.`,
319
+ };
320
+ }
321
+ case 'press': {
322
+ const key = action.value || 'Enter';
323
+ if (action.target) {
324
+ const locator = buildLocator(page, action);
325
+ if (options?.strictOracles) {
326
+ const disabled = await failIfDisabled(locator, action);
327
+ if (disabled)
328
+ return disabled;
329
+ }
330
+ await locator.first().press(key, { timeout: timeoutMs });
331
+ }
332
+ else {
333
+ await page.keyboard.press(key);
334
+ }
335
+ await settleSPA(page).catch(() => { });
336
+ return { status: 'passed', observation: `Pressed ${key}${action.target ? ` on ${describeTarget(action)}` : ''}.` };
337
+ }
338
+ case 'noop': {
339
+ return {
340
+ status: 'skipped',
341
+ observation: action.rationale || 'Step intentionally skipped — not safe to automate.',
342
+ };
343
+ }
344
+ }
345
+ }
346
+ catch (err) {
347
+ const msg = err instanceof Error ? err.message : String(err);
348
+ if (isSoftAutomationMiss(msg)) {
349
+ return {
350
+ status: 'skipped',
351
+ observation: `${capitalise(action.tool)} on ${describeTarget(action)} could not be completed by the agent (${truncate(msg, 140)}). Treated as inconclusive rather than a product bug.`,
352
+ };
353
+ }
354
+ return {
355
+ status: 'failed',
356
+ observation: `${capitalise(action.tool)} on ${describeTarget(action)} failed: ${truncate(msg, 160)}`,
357
+ error: msg,
358
+ };
359
+ }
360
+ return { status: 'skipped', observation: 'Unknown tool — skipped.' };
361
+ }
362
+ export function buildLocator(page, action) {
363
+ const target = action.target || '';
364
+ const strategy = action.locator || 'css';
365
+ switch (strategy) {
366
+ case 'role': {
367
+ // target is "role:label" e.g. "button:Sign in"
368
+ const m = target.match(/^([a-z]+)\s*:\s*(.+)$/i);
369
+ if (m) {
370
+ return page.getByRole(m[1], { name: new RegExp(escapeRegex(m[2]), 'i') });
371
+ }
372
+ return page.getByRole(target);
373
+ }
374
+ case 'text':
375
+ return page.getByText(target, { exact: false });
376
+ case 'placeholder':
377
+ return page.getByPlaceholder(target);
378
+ case 'label':
379
+ return page.getByLabel(target);
380
+ case 'testid':
381
+ return page.getByTestId(target);
382
+ case 'css':
383
+ default:
384
+ return page.locator(target);
385
+ }
386
+ }
387
+ /**
388
+ * Read role / accessible name / text / test id / CSS off the element the
389
+ * action is about to hit. Replay tries these in stability order and does not
390
+ * need the original LLM call.
391
+ */
392
+ export async function captureLocator(page, action) {
393
+ const strategy = (action.locator || 'css');
394
+ const base = {
395
+ strategy,
396
+ target: action.target || '',
397
+ };
398
+ if (strategy === 'role') {
399
+ const m = (action.target || '').match(/^([a-z]+)\s*:\s*(.+)$/i);
400
+ if (m) {
401
+ base.role = m[1].toLowerCase();
402
+ base.name = m[2].trim();
403
+ }
404
+ }
405
+ else if (strategy === 'text') {
406
+ base.text = action.target;
407
+ }
408
+ else if (strategy === 'label') {
409
+ base.label = action.target;
410
+ base.name = action.target;
411
+ }
412
+ else if (strategy === 'placeholder') {
413
+ base.placeholder = action.target;
414
+ base.name = action.target;
415
+ }
416
+ else if (strategy === 'testid') {
417
+ base.testId = action.target;
418
+ }
419
+ else if (strategy === 'css') {
420
+ base.css = action.target;
421
+ }
422
+ if (action.tool === 'goto' || action.tool === 'noop' || action.tool === 'assert_text') {
423
+ return base;
424
+ }
425
+ if (!action.target)
426
+ return base;
427
+ try {
428
+ const locator = buildLocator(page, action);
429
+ const count = await locator.count();
430
+ if (count === 0)
431
+ return base;
432
+ const info = await locator.first().evaluate(readElementIdentity);
433
+ return {
434
+ ...base,
435
+ ...(info.role ? { role: info.role } : {}),
436
+ ...(info.name ? { name: info.name } : {}),
437
+ ...(info.text ? { text: info.text } : {}),
438
+ ...(info.testId ? { testId: info.testId } : {}),
439
+ ...(info.css ? { css: info.css } : {}),
440
+ ...(info.placeholder ? { placeholder: info.placeholder } : {}),
441
+ ...(info.label ? { label: info.label } : {}),
442
+ };
443
+ }
444
+ catch {
445
+ return base;
446
+ }
447
+ }
448
+ export async function skeletonForLLM(page) {
449
+ const url = page.url();
450
+ const title = await page.title().catch(() => '');
451
+ const collected = await page.evaluate(() => {
452
+ function txt(el) {
453
+ return (el.textContent || '').trim().replace(/\s+/g, ' ');
454
+ }
455
+ const headings = Array.from(document.querySelectorAll('h1, h2, h3'))
456
+ .map(txt).filter(Boolean).slice(0, 12);
457
+ const buttons = Array.from(document.querySelectorAll('button, [role="button"], input[type="submit"]'))
458
+ .map(b => txt(b) || b.value || '')
459
+ .filter(Boolean).slice(0, 25);
460
+ const links = Array.from(document.querySelectorAll('a[href]'))
461
+ .slice(0, 25)
462
+ .map(a => ({
463
+ text: txt(a),
464
+ href: a.href,
465
+ }))
466
+ .filter(l => l.text);
467
+ function fieldLabel(el) {
468
+ const control = el;
469
+ if (control.id) {
470
+ const byFor = document.querySelector(`label[for="${CSS.escape(control.id)}"]`);
471
+ if (byFor) {
472
+ const text = txt(byFor);
473
+ if (text)
474
+ return text.slice(0, 80);
475
+ }
476
+ }
477
+ const aria = control.getAttribute('aria-label');
478
+ if (aria && aria.trim())
479
+ return aria.trim().replace(/\s+/g, ' ').slice(0, 80);
480
+ const labelledBy = control.getAttribute('aria-labelledby');
481
+ if (labelledBy) {
482
+ const text = labelledBy.split(/\s+/).map(id => {
483
+ const node = document.getElementById(id);
484
+ return node ? txt(node) : '';
485
+ }).filter(Boolean).join(' ').trim();
486
+ if (text)
487
+ return text.slice(0, 80);
488
+ }
489
+ const parent = control.closest('label');
490
+ if (parent) {
491
+ const clone = parent.cloneNode(true);
492
+ clone.querySelectorAll('input, textarea, select').forEach(node => node.remove());
493
+ const text = txt(clone);
494
+ if (text)
495
+ return text.slice(0, 80);
496
+ }
497
+ return '';
498
+ }
499
+ const inputs = Array.from(document.querySelectorAll('input, textarea, select'))
500
+ .slice(0, 25)
501
+ .map(el => {
502
+ const i = el;
503
+ const label = fieldLabel(i);
504
+ return {
505
+ label: label || undefined,
506
+ placeholder: i.placeholder || undefined,
507
+ name: i.name || undefined,
508
+ type: i.type || i.tagName.toLowerCase(),
509
+ };
510
+ });
511
+ return { headings, buttons, links, inputs };
512
+ });
513
+ return {
514
+ url,
515
+ title,
516
+ ...collected,
517
+ };
518
+ }
519
+ export async function settleSPA(page) {
520
+ await page.waitForLoadState('networkidle', { timeout: 4_000 }).catch(() => { });
521
+ await page.waitForFunction(() => (document.body?.innerText || '').replace(/\s+/g, '').length > 30, undefined, { timeout: 6_000 }).catch(() => { });
522
+ }
523
+ export function describeTarget(action) {
524
+ if (!action.target)
525
+ return '(no target)';
526
+ const prefix = action.locator && action.locator !== 'css' ? `${action.locator}:` : '';
527
+ return `${prefix}${truncate(action.target, 60)}`;
528
+ }
529
+ /**
530
+ * A disabled control is a product bug. Playwright would otherwise wait until
531
+ * the control becomes enabled and the runner would record a soft timeout skip.
532
+ * A missing element throws immediately (`isDisabled` defaults to no wait) and
533
+ * falls through to the real action.
534
+ */
535
+ async function failIfDisabled(locator, action) {
536
+ try {
537
+ if (await locator.first().isDisabled()) {
538
+ return {
539
+ status: 'failed',
540
+ observation: `${capitalise(action.tool)} on ${describeTarget(action)} failed: control is disabled.`,
541
+ error: 'element-disabled',
542
+ };
543
+ }
544
+ }
545
+ catch {
546
+ return undefined;
547
+ }
548
+ return undefined;
549
+ }
550
+ function isSoftAutomationMiss(msg) {
551
+ const lower = msg.toLowerCase();
552
+ return lower.includes('timeout') && (lower.includes('waiting for locator')
553
+ || lower.includes('locator.fill')
554
+ || lower.includes('locator.click')
555
+ || lower.includes('locator.press')
556
+ || lower.includes('locator.waitfor'));
557
+ }
558
+ function truncate(s, n) {
559
+ return s.length > n ? `${s.slice(0, n - 1)}…` : s;
560
+ }
561
+ function capitalise(s) {
562
+ return s.length === 0 ? s : s[0].toUpperCase() + s.slice(1);
563
+ }
564
+ function escapeRegex(s) {
565
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
566
+ }
567
+ /**
568
+ * Runs in the page. Kept as a function declaration so Playwright can serialize
569
+ * it into `locator.evaluate` without closing over Node state.
570
+ */
571
+ function readElementIdentity(el) {
572
+ function clean(value) {
573
+ const text = (value || '').replace(/\s+/g, ' ').trim();
574
+ return text ? text.slice(0, 160) : undefined;
575
+ }
576
+ function implicitRole(node) {
577
+ const explicit = node.getAttribute('role');
578
+ if (explicit)
579
+ return explicit.toLowerCase();
580
+ const tag = node.tagName.toLowerCase();
581
+ if (tag === 'a' && node.hasAttribute('href'))
582
+ return 'link';
583
+ if (tag === 'button')
584
+ return 'button';
585
+ if (tag === 'textarea')
586
+ return 'textbox';
587
+ if (tag === 'select')
588
+ return 'combobox';
589
+ if (/^h[1-6]$/.test(tag))
590
+ return 'heading';
591
+ if (tag === 'input') {
592
+ const type = (node.getAttribute('type') || 'text').toLowerCase();
593
+ if (type === 'checkbox')
594
+ return 'checkbox';
595
+ if (type === 'radio')
596
+ return 'radio';
597
+ if (type === 'button' || type === 'submit' || type === 'image')
598
+ return 'button';
599
+ if (['email', 'password', 'search', 'tel', 'url', 'text', 'number', ''].includes(type))
600
+ return 'textbox';
601
+ }
602
+ return undefined;
603
+ }
604
+ const html = el;
605
+ const testId = html.getAttribute('data-testid') || undefined;
606
+ const placeholder = html.getAttribute('placeholder') || undefined;
607
+ const text = clean(html.innerText || html.textContent);
608
+ let label;
609
+ const id = html.getAttribute('id');
610
+ if (id) {
611
+ const labelEl = document.querySelector(`label[for="${CSS.escape(id)}"]`);
612
+ label = clean(labelEl?.textContent);
613
+ }
614
+ if (!label) {
615
+ const wrapped = html.closest('label');
616
+ if (wrapped && wrapped !== html)
617
+ label = clean(wrapped.textContent);
618
+ }
619
+ let name = clean(html.getAttribute('aria-label')) || label || clean(placeholder) || text;
620
+ const labelledBy = html.getAttribute('aria-labelledby');
621
+ if (labelledBy) {
622
+ const combined = labelledBy.split(/\s+/)
623
+ .map(part => document.getElementById(part)?.textContent || '')
624
+ .join(' ');
625
+ name = clean(combined) || name;
626
+ }
627
+ let css;
628
+ if (testId)
629
+ css = `[data-testid="${CSS.escape(testId)}"]`;
630
+ else if (id)
631
+ css = `#${CSS.escape(id)}`;
632
+ else {
633
+ const parts = [];
634
+ let node = html;
635
+ let depth = 0;
636
+ while (node && node.tagName.toLowerCase() !== 'html' && depth < 4) {
637
+ const tag = node.tagName.toLowerCase();
638
+ const parentEl = node.parentElement;
639
+ if (!parentEl)
640
+ break;
641
+ const siblings = Array.from(parentEl.children).filter(child => child.tagName === node.tagName);
642
+ const index = siblings.indexOf(node) + 1;
643
+ parts.unshift(siblings.length > 1 ? `${tag}:nth-of-type(${index})` : tag);
644
+ node = parentEl;
645
+ depth++;
646
+ }
647
+ css = parts.join(' > ') || undefined;
648
+ }
649
+ return {
650
+ role: implicitRole(html),
651
+ name,
652
+ text,
653
+ testId,
654
+ css,
655
+ placeholder: placeholder || undefined,
656
+ label,
657
+ };
658
+ }
659
+ //# sourceMappingURL=actions.js.map