@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,675 @@
1
+ /**
2
+ * Explorer phase
3
+ *
4
+ * Drives Playwright through the site, capturing the structural skeleton of
5
+ * each page (title, headings, forms, buttons, links). The LLM is used per
6
+ * page to:
7
+ * - write a one-sentence summary of what the page is for
8
+ * - call out the salient interactive elements
9
+ * - guess whether the page is auth-gated
10
+ *
11
+ * After all pages are visited (or the budget is exhausted) the LLM does one
12
+ * final whole-site summary that names the site type ("ecommerce",
13
+ * "saas dashboard", etc.).
14
+ *
15
+ * Link order is still breadth-first, but a few slots are reserved for
16
+ * form / help / contact / support / about pages the crawl actually saw.
17
+ * A shop homepage full of product links cannot spend the whole `maxPages`
18
+ * budget before `/help` is visited. URLs that were never linked are not
19
+ * invented.
20
+ *
21
+ * Crawl scope is the site, not a single `URL.origin`. `http://shop.example/`
22
+ * and `https://www.shop.example/help` are the same site. Another host,
23
+ * another subdomain, or another explicit port is not. A redirect that stays
24
+ * on the site is recorded as the URL the browser landed on.
25
+ *
26
+ * What the explorer is NOT:
27
+ * - It does not log in. Auth-gated flows are surfaced to the planner so
28
+ * they can be flagged as `auth_required` later.
29
+ * - It does not click destructive buttons. The visit is read-only.
30
+ */
31
+ import { chromium } from 'playwright';
32
+ import { basename } from 'node:path';
33
+ import { mkdirSync } from 'node:fs';
34
+ import { join, resolve } from 'node:path';
35
+ import { z } from 'zod';
36
+ import { clipText, coerceBoolean, coerceEnum, coerceProse, coerceStringList, coerceToString, logModelDetail, unwrapModelObject, } from '../llm/coerce.js';
37
+ import { noopBus } from '../events.js';
38
+ import { canonicalPageUrl, crawledPageUrl, enqueueLinks, FORM_SURFACE_PATH_SOURCE, FORM_SURFACE_TEXT_SOURCE, isFormSurfaceLink, linksOnCrawlSite, looksLikeAuthUrl, pickNextCrawlUrl, rememberVisited, selectOutboundLinks, wasVisited, } from './queue.js';
39
+ export async function explore(startUrl, llm, opts = {}) {
40
+ const maxPages = opts.maxPages ?? 8;
41
+ const timeout = opts.pageTimeoutMs ?? 20_000;
42
+ const headless = opts.headless ?? true;
43
+ const events = opts.events ?? noopBus();
44
+ const visited = new Set();
45
+ const start = canonicalPageUrl(startUrl);
46
+ const queue = [{ url: start, surface: isFormSurfaceLink({ url: start }) }];
47
+ const pages = [];
48
+ const failures = [];
49
+ const warnings = [];
50
+ let authUrlsQueued = 0;
51
+ let surfaceVisited = 0;
52
+ const screenshotsDir = opts.screenshotsDir ? resolve(opts.screenshotsDir) : null;
53
+ if (screenshotsDir) {
54
+ mkdirSync(screenshotsDir, { recursive: true });
55
+ }
56
+ events.emit({
57
+ phase: 'explorer', type: 'explore.start',
58
+ message: `Crawling ${startUrl}…`,
59
+ data: { startUrl, maxPages },
60
+ });
61
+ const browser = await chromium.launch({ headless });
62
+ try {
63
+ const context = await browser.newContext({
64
+ userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 13_0) AppleWebKit/537.36 '
65
+ + '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 monkeytest.ai',
66
+ viewport: { width: 1280, height: 800 },
67
+ });
68
+ while (queue.length > 0 && pages.length < maxPages) {
69
+ const index = pickNextCrawlUrl(queue, {
70
+ pagesVisited: pages.length,
71
+ maxPages,
72
+ surfaceVisited,
73
+ });
74
+ if (index < 0)
75
+ break;
76
+ const next = queue.splice(index, 1)[0];
77
+ if (!next || wasVisited(visited, next.url))
78
+ continue;
79
+ const requestedUrl = next.url;
80
+ rememberVisited(visited, requestedUrl);
81
+ const page = await context.newPage();
82
+ try {
83
+ await page.goto(requestedUrl, { waitUntil: 'domcontentloaded', timeout });
84
+ const url = crawledPageUrl(requestedUrl, page.url(), startUrl);
85
+ rememberVisited(visited, url);
86
+ // SPAs (CRA, Next dev, Vite) often keep a websocket open for HMR so
87
+ // networkidle never settles. We give it a brief shot, then fall back
88
+ // to a `waitForFunction` that polls for actual rendered content.
89
+ await page.waitForLoadState('networkidle', { timeout: 5_000 }).catch(() => { });
90
+ await page.waitForFunction(() => (document.body?.innerText || '').replace(/\s+/g, '').length > 30, undefined, { timeout: 8_000 }).catch(() => { });
91
+ const skeleton = await scrapePageSkeleton(page);
92
+ // Screenshot each visited page if a directory was provided. Filename
93
+ // is a deterministic, filesystem-safe hash of the URL so subsequent
94
+ // runs can reference the same path.
95
+ let screenshotPath;
96
+ if (screenshotsDir) {
97
+ const filename = `page-${pages.length + 1}-${slugifyUrl(url)}.png`;
98
+ const fullPath = join(screenshotsDir, filename);
99
+ try {
100
+ await page.screenshot({ path: fullPath, fullPage: false });
101
+ screenshotPath = fullPath;
102
+ events.emit({
103
+ phase: 'explorer', type: 'explore.screenshot',
104
+ message: `Captured screenshot of ${url}`,
105
+ data: { url, screenshot: basename(fullPath) },
106
+ });
107
+ }
108
+ catch (err) {
109
+ // Don't fail the crawl just because a screenshot didn't save.
110
+ }
111
+ }
112
+ // The LLM summarisation is best-effort. If it fails (404 model id,
113
+ // 503, schema mismatch, …) we still want the page recorded with the
114
+ // skeleton we already scraped — losing a screenshot + the entire page
115
+ // because the LLM returned malformed JSON is overkill.
116
+ let summary;
117
+ try {
118
+ summary = await summarisePageWithLLM(llm, url, skeleton);
119
+ }
120
+ catch (err) {
121
+ const detail = err instanceof Error ? err.message : String(err);
122
+ logModelDetail(`explorer.summarisePage ${url}`, detail);
123
+ const message = `Page summary from the model was incomplete for ${url}; continuing with the page title.`;
124
+ warnings.push(message);
125
+ events.emit({
126
+ phase: 'explorer', type: 'explore.warning',
127
+ message,
128
+ data: { url, detail },
129
+ });
130
+ summary = {
131
+ summary: skeleton.title || `Page at ${url}`,
132
+ interactive: [],
133
+ authGated: false,
134
+ };
135
+ }
136
+ const forms = skeleton.forms.filter(form => form.action || form.fields.length > 0 || form.submitLabel);
137
+ const controls = skeleton.controls.filter(control => control.label);
138
+ const outbound = selectOutboundLinks(linksOnCrawlSite(skeleton.links, startUrl));
139
+ const sm = {
140
+ url,
141
+ title: skeleton.title,
142
+ summary: summary.summary,
143
+ interactive: withScrapedForm(summary.interactive, forms),
144
+ outboundLinks: outbound.map(link => link.url),
145
+ ...(forms.length ? { forms } : {}),
146
+ ...(controls.length ? { controls } : {}),
147
+ authGated: summary.authGated,
148
+ ...(screenshotPath ? { screenshotPath } : {}),
149
+ };
150
+ pages.push(sm);
151
+ if (isFormSurfaceLink({ url: sm.url, text: sm.title }))
152
+ surfaceVisited += 1;
153
+ opts.onPage?.(sm);
154
+ events.emit({
155
+ phase: 'explorer', type: 'explore.page_visited',
156
+ message: `Explored ${url}`,
157
+ data: {
158
+ url,
159
+ title: sm.title,
160
+ summary: sm.summary,
161
+ screenshot: screenshotPath ? basename(screenshotPath) : undefined,
162
+ authGated: sm.authGated,
163
+ },
164
+ });
165
+ // Auth walls eat crawl budget and produce login-only test plans.
166
+ // Cap obvious auth URLs at one visit so the planner still knows a
167
+ // login surface exists. Form/help links stay in the queue and are
168
+ // pulled forward while the surface reserve is unfilled.
169
+ if (!sm.authGated) {
170
+ authUrlsQueued = enqueueLinks(queue, visited, outbound, authUrlsQueued);
171
+ }
172
+ }
173
+ catch (err) {
174
+ const reason = err instanceof Error ? err.message : String(err);
175
+ failures.push({ url: requestedUrl, reason });
176
+ events.emit({
177
+ phase: 'explorer', type: 'explore.page_failed',
178
+ message: `Failed to load ${requestedUrl}`,
179
+ data: { url: requestedUrl, reason },
180
+ });
181
+ }
182
+ finally {
183
+ await page.close().catch(() => { });
184
+ }
185
+ }
186
+ const overall = await summariseSiteBestEffort(llm, startUrl, pages, (message, detail) => {
187
+ warnings.push(message);
188
+ events.emit({
189
+ phase: 'explorer', type: 'explore.warning',
190
+ message,
191
+ data: { detail },
192
+ });
193
+ });
194
+ events.emit({
195
+ phase: 'explorer', type: 'explore.complete',
196
+ message: `Crawl complete: ${pages.length} page${pages.length === 1 ? '' : 's'} visited`
197
+ + (failures.length ? `, ${failures.length} failed.` : '.'),
198
+ data: {
199
+ siteType: overall.siteType,
200
+ pagesVisited: pages.length,
201
+ pagesFailed: failures.length,
202
+ ...(warnings.length ? { warnings } : {}),
203
+ },
204
+ });
205
+ return {
206
+ startUrl,
207
+ siteType: overall.siteType,
208
+ summary: overall.summary,
209
+ productName: overall.productName ?? undefined,
210
+ publicJourneys: overall.publicJourneys ?? undefined,
211
+ authSurfaces: overall.authSurfaces ?? undefined,
212
+ pages,
213
+ pendingUrls: queue.map(item => item.url),
214
+ failedUrls: failures,
215
+ ...(warnings.length ? { warnings } : {}),
216
+ };
217
+ }
218
+ finally {
219
+ await browser.close().catch(() => { });
220
+ }
221
+ }
222
+ async function scrapePageSkeleton(page) {
223
+ const url = page.url();
224
+ const title = await page.title().catch(() => '');
225
+ // Use page.evaluate for one cheap round-trip to collect everything we need.
226
+ // Keep every form/help-style anchor, plus the first 80 ordinary ones, so a
227
+ // long product grid cannot drop a footer "Help" link before it leaves the page.
228
+ const collected = await page.evaluate(({ pathSource, textSource }) => {
229
+ function txt(el) {
230
+ return (el.textContent || '').trim().replace(/\s+/g, ' ');
231
+ }
232
+ const headings = Array.from(document.querySelectorAll('h1, h2, h3'))
233
+ .map(txt)
234
+ .filter(Boolean)
235
+ .slice(0, 20);
236
+ const pathRe = new RegExp(pathSource, 'i');
237
+ const textRe = new RegExp(textSource, 'i');
238
+ const anchors = Array.from(document.querySelectorAll('a[href]'))
239
+ .map(a => ({
240
+ url: a.href,
241
+ text: txt(a).slice(0, 80),
242
+ }))
243
+ .filter(link => link.url);
244
+ const surfaceUrls = new Set();
245
+ const ordinaryUrls = new Set();
246
+ for (const link of anchors) {
247
+ let path = link.url;
248
+ try {
249
+ const parsed = new URL(link.url);
250
+ path = `${parsed.pathname}${parsed.search}`;
251
+ }
252
+ catch { /* keep the raw href */ }
253
+ const surface = pathRe.test(path) || (link.text ? textRe.test(link.text) : false);
254
+ if (surface)
255
+ surfaceUrls.add(link.url);
256
+ else if (ordinaryUrls.size < 80)
257
+ ordinaryUrls.add(link.url);
258
+ }
259
+ const seen = new Set();
260
+ const links = anchors.filter(link => {
261
+ if (seen.has(link.url))
262
+ return false;
263
+ if (!surfaceUrls.has(link.url) && !ordinaryUrls.has(link.url))
264
+ return false;
265
+ seen.add(link.url);
266
+ return true;
267
+ });
268
+ function fieldLabel(el) {
269
+ const control = el;
270
+ if (control.id) {
271
+ const byFor = document.querySelector(`label[for="${CSS.escape(control.id)}"]`);
272
+ if (byFor) {
273
+ const text = txt(byFor);
274
+ if (text)
275
+ return text.slice(0, 80);
276
+ }
277
+ }
278
+ const aria = control.getAttribute('aria-label');
279
+ if (aria && aria.trim())
280
+ return aria.trim().replace(/\s+/g, ' ').slice(0, 80);
281
+ const labelledBy = control.getAttribute('aria-labelledby');
282
+ if (labelledBy) {
283
+ const text = labelledBy.split(/\s+/).map(id => {
284
+ const node = document.getElementById(id);
285
+ return node ? txt(node) : '';
286
+ }).filter(Boolean).join(' ').trim();
287
+ if (text)
288
+ return text.slice(0, 80);
289
+ }
290
+ const parent = control.closest('label');
291
+ if (parent) {
292
+ const clone = parent.cloneNode(true);
293
+ clone.querySelectorAll('input, textarea, select').forEach(node => node.remove());
294
+ const text = txt(clone);
295
+ if (text)
296
+ return text.slice(0, 80);
297
+ }
298
+ return '';
299
+ }
300
+ const forms = Array.from(document.querySelectorAll('form')).slice(0, 10).map(f => {
301
+ const form = f;
302
+ const controls = Array.from(form.querySelectorAll('input, textarea, select')).flatMap(i => {
303
+ const el = i;
304
+ const type = (el.type || el.tagName || '').toLowerCase();
305
+ if (type === 'hidden' || type === 'submit' || type === 'button' || type === 'image' || type === 'reset')
306
+ return [];
307
+ const name = el.name || '';
308
+ const placeholder = el.placeholder || '';
309
+ const label = fieldLabel(el);
310
+ const token = name || placeholder || type;
311
+ if (!token)
312
+ return [];
313
+ return [{
314
+ token,
315
+ ...(name ? { name } : {}),
316
+ ...(label ? { label } : {}),
317
+ ...(placeholder ? { placeholder } : {}),
318
+ ...(type ? { type } : {}),
319
+ }];
320
+ });
321
+ const submit = form.querySelector('button[type="submit"], input[type="submit"], button:not([type])');
322
+ const submitLabel = submit ? (txt(submit) || submit.value || '') : '';
323
+ return {
324
+ action: form.action || '',
325
+ method: (form.method || 'get').toLowerCase(),
326
+ fields: controls.map(control => control.token),
327
+ ...(controls.length ? {
328
+ inputs: controls.map(control => ({
329
+ ...(control.name ? { name: control.name } : {}),
330
+ ...(control.label ? { label: control.label } : {}),
331
+ ...(control.placeholder ? { placeholder: control.placeholder } : {}),
332
+ ...(control.type ? { type: control.type } : {}),
333
+ })),
334
+ } : {}),
335
+ ...(submitLabel ? { submitLabel: submitLabel.slice(0, 80) } : {}),
336
+ };
337
+ });
338
+ const buttonControls = Array.from(document.querySelectorAll('button, [role="button"], input[type="submit"], input[type="button"]'))
339
+ .map(b => {
340
+ const label = (txt(b) || b.value || '').slice(0, 80);
341
+ const disabled = Boolean(b.disabled) || b.getAttribute('aria-disabled') === 'true';
342
+ return { kind: 'button', label, ...(disabled ? { disabled: true } : {}) };
343
+ })
344
+ .filter(control => control.label);
345
+ const buttons = [
346
+ ...buttonControls.filter(control => control.disabled),
347
+ ...buttonControls.filter(control => !control.disabled),
348
+ ].slice(0, 40);
349
+ const linkControls = links
350
+ .filter(link => link.text)
351
+ .slice(0, 40)
352
+ .map(link => ({ kind: 'link', label: link.text.slice(0, 80), href: link.url }));
353
+ const visibleText = (document.body?.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 2200);
354
+ return { headings, links, forms, buttons: buttons.map(control => control.label), controls: [...buttons, ...linkControls], visibleText };
355
+ }, {
356
+ pathSource: FORM_SURFACE_PATH_SOURCE,
357
+ textSource: FORM_SURFACE_TEXT_SOURCE,
358
+ });
359
+ return {
360
+ url,
361
+ title,
362
+ headings: collected.headings,
363
+ visibleText: collected.visibleText,
364
+ links: collected.links,
365
+ forms: collected.forms,
366
+ buttons: collected.buttons,
367
+ controls: collected.controls,
368
+ };
369
+ }
370
+ /* ── LLM: per-page summary ────────────────────────────────────────────── */
371
+ const INTERACTIVE_KINDS = ['form', 'button', 'link', 'input', 'menu'];
372
+ const INTERACTIVE_KIND_ALIASES = {
373
+ cta: 'button',
374
+ submit: 'button',
375
+ anchor: 'link',
376
+ hyperlink: 'link',
377
+ textbox: 'input',
378
+ field: 'input',
379
+ textarea: 'input',
380
+ dropdown: 'menu',
381
+ nav: 'menu',
382
+ navigation: 'menu',
383
+ };
384
+ const InteractiveItemSchema = z.object({
385
+ kind: z.enum(INTERACTIVE_KINDS),
386
+ label: z.string().min(1).max(80),
387
+ selector: z.string().min(1).max(200).optional(),
388
+ });
389
+ function coerceInteractiveItem(value) {
390
+ if (!value || typeof value !== 'object' || Array.isArray(value))
391
+ return value;
392
+ const record = value;
393
+ const kind = coerceEnum(record.kind ?? record.type ?? record.role, INTERACTIVE_KINDS, INTERACTIVE_KIND_ALIASES);
394
+ const label = coerceProse(record.label ?? record.name ?? record.text ?? record.title);
395
+ const selector = coerceToString(record.selector ?? record.css);
396
+ return {
397
+ ...(kind ? { kind } : {}),
398
+ ...(label ? { label: clipText(label, 80) } : {}),
399
+ ...(selector ? { selector: clipText(selector, 200) } : {}),
400
+ };
401
+ }
402
+ function coerceInteractiveList(value) {
403
+ if (value == null)
404
+ return undefined;
405
+ const rawList = Array.isArray(value) ? value.flat(2) : [value];
406
+ const items = [];
407
+ for (const item of rawList) {
408
+ const parsed = InteractiveItemSchema.safeParse(coerceInteractiveItem(item));
409
+ if (!parsed.success)
410
+ continue;
411
+ items.push(parsed.data.selector
412
+ ? parsed.data
413
+ : { kind: parsed.data.kind, label: parsed.data.label });
414
+ if (items.length >= 10)
415
+ break;
416
+ }
417
+ return items;
418
+ }
419
+ export const PageSummarySchema = z.preprocess((value) => unwrapModelObject(value, ['summary', 'authGated', 'interactive']), z.object({
420
+ summary: z.preprocess((value) => {
421
+ const text = coerceProse(value);
422
+ return text ? clipText(text, 400) : value;
423
+ }, z.string().min(3).max(400)),
424
+ // Unrecognised values become false. The previous failure path stored false
425
+ // anyway and dropped the sentence; keeping the sentence is more useful.
426
+ authGated: z.preprocess((value) => coerceBoolean(value) ?? false, z.boolean()),
427
+ interactive: z.preprocess((value) => coerceInteractiveList(value) ?? [], z.array(InteractiveItemSchema).max(10)),
428
+ }));
429
+ async function summarisePageWithLLM(llm, url, skeleton) {
430
+ const prompt = `
431
+ You are a QA analyst inspecting a single web page during an exploratory crawl.
432
+ Based on the page metadata below, return JSON with three fields:
433
+
434
+ - "summary": one sentence (max 30 words) naming the page's job for a visitor (e.g. "CRED marketing homepage promoting credit-card rewards"). A string, not an object.
435
+ - "authGated": boolean true or false — true only if the page is a login/OTP wall, or clearly requires an existing session. A marketing page that merely links to Sign in is NOT auth-gated. Do not send "yes"/"no" strings; use JSON booleans.
436
+ - "interactive": an array of up to 10 important elements (primary CTAs first). Each item is an object, never a bare string:
437
+ kind — exactly one of "form" | "button" | "link" | "input" | "menu" (lowercase)
438
+ label — a short string (max 60 chars)
439
+ selector — optional CSS selector string. Omit the key if you are not sure. Do not send null.
440
+
441
+ URL: ${url}
442
+ Title: ${skeleton.title}
443
+
444
+ Headings:
445
+ ${skeleton.headings.map(h => ` - ${h}`).join('\n') || ' (none)'}
446
+
447
+ Buttons:
448
+ ${skeleton.buttons.map(b => ` - ${b}`).join('\n') || ' (none)'}
449
+
450
+ Forms:
451
+ ${skeleton.forms.map((f, i) => ` ${i + 1}. method=${f.method || 'get'} action=${f.action || '(none)'} submit=${f.submitLabel || '(none)'} fields=[${f.fields.join(', ')}]`).join('\n') || ' (none)'}
452
+
453
+ Visible text (excerpt):
454
+ ${skeleton.visibleText || '(empty)'}
455
+
456
+ Reply with JSON only.
457
+ `;
458
+ const raw = await llm.generateJSON({
459
+ label: 'explorer.summarisePage',
460
+ prompt,
461
+ schema: PageSummarySchema,
462
+ });
463
+ const parsed = PageSummarySchema.parse(raw);
464
+ return {
465
+ summary: parsed.summary,
466
+ authGated: parsed.authGated,
467
+ interactive: parsed.interactive ?? [],
468
+ };
469
+ }
470
+ /* ── LLM: whole-site summary ──────────────────────────────────────────── */
471
+ const SITE_SUMMARY_FALLBACK_WARNING = 'Site summary from the model was incomplete; continuing with a basic map of the site.';
472
+ function llmProseField(min, max) {
473
+ return z.preprocess((value) => {
474
+ const text = coerceProse(value);
475
+ return text ? clipText(text, max) : value;
476
+ }, z.string().min(min).max(max));
477
+ }
478
+ function llmOptionalProse(max) {
479
+ return z.preprocess((value) => {
480
+ if (value == null || value === '')
481
+ return undefined;
482
+ const text = coerceProse(value);
483
+ return text ? clipText(text, max) : undefined;
484
+ }, z.string().min(1).max(max).optional());
485
+ }
486
+ function llmStringListField(minLength, maxItems) {
487
+ return z.preprocess((value) => {
488
+ if (value == null)
489
+ return undefined;
490
+ const list = coerceStringList(value, { minLength, maxItems });
491
+ return list ?? undefined;
492
+ }, z.array(z.string().min(minLength)).max(maxItems).optional());
493
+ }
494
+ export const SiteSummarySchema = z.preprocess((value) => unwrapModelObject(value, ['siteType', 'summary', 'authSurfaces', 'publicJourneys', 'productName']), z.object({
495
+ siteType: llmProseField(2, 80),
496
+ summary: llmProseField(3, 1200),
497
+ productName: llmOptionalProse(120),
498
+ publicJourneys: llmStringListField(3, 6),
499
+ authSurfaces: llmStringListField(2, 6),
500
+ }));
501
+ async function summariseSiteWithLLM(llm, startUrl, pages) {
502
+ if (pages.length === 0) {
503
+ return { siteType: 'unknown', summary: 'No pages were successfully visited.' };
504
+ }
505
+ const prompt = `
506
+ You just finished exploring a website as an anonymous visitor (you never logged in).
507
+ Understand the product, then describe it so a QA architect can design real user tests.
508
+
509
+ Return JSON:
510
+ - "siteType": short category string, e.g. "ecommerce", "fintech consumer app", "saas marketing site",
511
+ "blog", "documentation", "marketplace", "internal tool", "other".
512
+ - "productName": brand or product name string if obvious, else omit the key.
513
+ - "summary": a string of 2–3 sentences (max 90 words): what the product does, who the visitor is,
514
+ and which jobs they can complete WITHOUT an account.
515
+ - "publicJourneys": an array of up to 5 short strings. Each item is one sentence
516
+ (e.g. "Read credit-card benefits and open Apply"), never an object. Do not invent pages.
517
+ - "authSurfaces": an array of short strings only, one per login / signup / OTP wall
518
+ (e.g. "Login (/login)"). Never objects with url/label keys. Empty array if none.
519
+
520
+ Start URL: ${startUrl}
521
+
522
+ Pages visited:
523
+ ${pages.map(p => ` - ${p.url}\n title: ${p.title}\n auth-gated: ${p.authGated}\n summary: ${p.summary}\n interactive: ${p.interactive.map(i => i.label).join(', ') || '(none)'}`).join('\n')}
524
+
525
+ Reply with JSON only.
526
+ `;
527
+ const raw = await llm.generateJSON({
528
+ label: 'explorer.summariseSite',
529
+ prompt,
530
+ schema: SiteSummarySchema,
531
+ });
532
+ return normaliseSiteSummary(SiteSummarySchema.parse(raw));
533
+ }
534
+ /**
535
+ * Whole-site summary is best-effort. A schema miss used to abort the crawl
536
+ * after every page had already been visited. Keep the pages and substitute a
537
+ * map built from titles and URLs.
538
+ */
539
+ async function summariseSiteBestEffort(llm, startUrl, pages, onFallback) {
540
+ try {
541
+ return await summariseSiteWithLLM(llm, startUrl, pages);
542
+ }
543
+ catch (err) {
544
+ const detail = err instanceof Error ? err.message : String(err);
545
+ logModelDetail('explorer.summariseSite', detail);
546
+ onFallback(SITE_SUMMARY_FALLBACK_WARNING, detail);
547
+ return fallbackSiteSummary(startUrl, pages);
548
+ }
549
+ }
550
+ function normaliseSiteSummary(parsed) {
551
+ return {
552
+ siteType: parsed.siteType,
553
+ summary: parsed.summary,
554
+ productName: parsed.productName ?? undefined,
555
+ publicJourneys: parsed.publicJourneys ?? undefined,
556
+ authSurfaces: parsed.authSurfaces ?? undefined,
557
+ };
558
+ }
559
+ /** Crawl metadata when the model summary cannot be used. No page is invented. */
560
+ export function fallbackSiteSummary(startUrl, pages) {
561
+ if (pages.length === 0) {
562
+ return { siteType: 'unknown', summary: 'No pages were successfully visited.' };
563
+ }
564
+ const host = hostOf(startUrl);
565
+ const titles = uniqueStrings(pages.map(page => page.title.trim()).filter(title => title.length >= 2)).slice(0, 4);
566
+ const blurbs = pages.map(pageBlurb).filter((line) => Boolean(line)).slice(0, 3);
567
+ const lead = `Explored ${pages.length} page${pages.length === 1 ? '' : 's'} on ${host}.`;
568
+ const summary = clipText(blurbs.length
569
+ ? `${lead} ${blurbs.join(' ')}`
570
+ : `${lead}${titles.length ? ` Pages include ${titles.join(', ')}.` : ''}`, 600);
571
+ const publicJourneys = uniqueStrings(pages.filter(page => !page.authGated).map(page => {
572
+ const label = page.title.trim() || pathLabel(page.url);
573
+ return label.length >= 3 ? `Visit ${label}` : '';
574
+ })).slice(0, 5);
575
+ const authSurfaces = uniqueStrings(pages.filter(page => page.authGated || looksLikeAuthUrl(page.url)).map(page => {
576
+ const label = page.title.trim();
577
+ if (label.length >= 2)
578
+ return `${label} (${page.url})`;
579
+ return page.url.length >= 2 ? page.url : '';
580
+ })).slice(0, 6);
581
+ return {
582
+ siteType: inferSiteType(startUrl, pages),
583
+ summary,
584
+ ...(publicJourneys.length ? { publicJourneys } : {}),
585
+ ...(authSurfaces.length ? { authSurfaces } : {}),
586
+ };
587
+ }
588
+ function pageBlurb(page) {
589
+ const summary = page.summary.trim();
590
+ if (summary.length < 3)
591
+ return undefined;
592
+ if (/schema|LLM summary unavailable|did not match/i.test(summary))
593
+ return undefined;
594
+ if (summary === page.title.trim())
595
+ return undefined;
596
+ return summary;
597
+ }
598
+ function inferSiteType(startUrl, pages) {
599
+ const blob = [startUrl, ...pages.map(page => `${page.url} ${page.title} ${page.summary}`)].join(' ').toLowerCase();
600
+ if (/\b(cart|checkout|product|shop|store)\b/.test(blob))
601
+ return 'ecommerce';
602
+ if (/\b(docs|documentation|api reference)\b/.test(blob))
603
+ return 'documentation';
604
+ if (/\bblog\b/.test(blob))
605
+ return 'blog';
606
+ if (/\b(pricing|dashboard|sign in|log in)\b/.test(blob))
607
+ return 'saas marketing site';
608
+ return 'website';
609
+ }
610
+ function hostOf(startUrl) {
611
+ try {
612
+ return new URL(startUrl).hostname.replace(/^www\./, '');
613
+ }
614
+ catch {
615
+ return startUrl;
616
+ }
617
+ }
618
+ function pathLabel(value) {
619
+ try {
620
+ const path = new URL(value).pathname.replace(/\/+$/, '');
621
+ const last = path.split('/').filter(Boolean).pop();
622
+ return last || '';
623
+ }
624
+ catch {
625
+ return '';
626
+ }
627
+ }
628
+ function uniqueStrings(values) {
629
+ const seen = new Set();
630
+ const out = [];
631
+ for (const value of values) {
632
+ if (!value || seen.has(value))
633
+ continue;
634
+ seen.add(value);
635
+ out.push(value);
636
+ }
637
+ return out;
638
+ }
639
+ /* ── Helpers ──────────────────────────────────────────────────────────── */
640
+ /**
641
+ * Filesystem-safe filename slug derived from a URL. Caps length so we don't
642
+ * blow past OS path limits on deep URLs.
643
+ */
644
+ function slugifyUrl(u) {
645
+ try {
646
+ const url = new URL(u);
647
+ const raw = (url.hostname + url.pathname + url.search)
648
+ .toLowerCase()
649
+ .replace(/[^a-z0-9]+/g, '-')
650
+ .replace(/^-+|-+$/g, '');
651
+ return raw.slice(0, 80) || 'page';
652
+ }
653
+ catch {
654
+ return 'page';
655
+ }
656
+ }
657
+ function withScrapedForm(interactive, forms) {
658
+ if (forms.length === 0 || interactive.some(item => item.kind === 'form'))
659
+ return interactive;
660
+ const form = [...forms].sort((a, b) => scrapedFormRank(b) - scrapedFormRank(a))[0];
661
+ const label = (form.submitLabel || form.fields.slice(0, 3).join(', ') || 'form').slice(0, 60);
662
+ return [...interactive, { kind: 'form', label }];
663
+ }
664
+ /** Header search boxes sort below a POST form so the planner sees the contact control. */
665
+ function scrapedFormRank(form) {
666
+ let score = 0;
667
+ if ((form.method || 'get').toLowerCase() === 'post')
668
+ score += 2;
669
+ if (form.submitLabel)
670
+ score += 1;
671
+ if (/\/search(?:\/|$|\?)/i.test(form.action || ''))
672
+ score -= 2;
673
+ return score;
674
+ }
675
+ //# sourceMappingURL=index.js.map