explorbot 0.2.4 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/explorbot-cli.ts +19 -7
- package/boat/api-tester/src/cli.ts +17 -0
- package/boat/doc-collector/src/cli.ts +14 -1
- package/boat/prima/src/cli.ts +24 -12
- package/boat/prima/src/envelope.ts +35 -13
- package/boat/prima/src/prima.ts +61 -41
- package/dist/bin/explorbot-cli.js +19 -7
- package/dist/boat/api-tester/src/cli.js +17 -0
- package/dist/boat/doc-collector/src/cli.js +14 -1
- package/dist/boat/prima/src/cli.js +19 -7
- package/dist/boat/prima/src/envelope.js +32 -8
- package/dist/boat/prima/src/prima.js +57 -39
- package/dist/package.json +1 -1
- package/dist/src/action.js +5 -1
- package/dist/src/ai/navigator.d.ts +27 -0
- package/dist/src/ai/navigator.js +227 -175
- package/dist/src/ai/pilot.d.ts +7 -4
- package/dist/src/ai/pilot.js +50 -8
- package/dist/src/ai/provider.d.ts +2 -2
- package/dist/src/ai/provider.js +12 -21
- package/dist/src/ai/researcher/cache.d.ts +2 -0
- package/dist/src/ai/researcher/cache.js +10 -2
- package/dist/src/ai/researcher.js +2 -1
- package/dist/src/ai/session-analyst.js +2 -0
- package/dist/src/ai/tester.d.ts +5 -2
- package/dist/src/ai/tester.js +17 -13
- package/dist/src/ai/tools.js +4 -1
- package/dist/src/commands/config-command.d.ts +51 -0
- package/dist/src/commands/config-command.js +117 -0
- package/dist/src/commands/index.js +2 -0
- package/dist/src/config.d.ts +8 -1
- package/dist/src/config.js +40 -0
- package/dist/src/explorbot.js +4 -1
- package/dist/src/remote.d.ts +3 -2
- package/dist/src/remote.js +8 -2
- package/dist/src/state-manager.d.ts +1 -1
- package/dist/src/state-manager.js +3 -1
- package/dist/src/test-plan.d.ts +1 -0
- package/dist/src/test-plan.js +19 -0
- package/dist/src/utils/logger.d.ts +1 -1
- package/dist/src/utils/logger.js +8 -0
- package/docs/index.json +2 -1
- package/docs/reference/commands.md +3 -0
- package/docs/reference/websocket.md +50 -0
- package/docs/superpowers/specs/2026-08-18-prima-false-verdicts.md +159 -0
- package/package.json +1 -1
- package/src/action.ts +5 -1
- package/src/ai/navigator.ts +241 -178
- package/src/ai/pilot.ts +63 -12
- package/src/ai/provider.ts +12 -20
- package/src/ai/researcher/cache.ts +12 -2
- package/src/ai/researcher.ts +2 -1
- package/src/ai/session-analyst.ts +2 -0
- package/src/ai/tester.ts +20 -12
- package/src/ai/tools.ts +4 -1
- package/src/commands/config-command.ts +146 -0
- package/src/commands/index.ts +2 -0
- package/src/config.ts +45 -1
- package/src/explorbot.ts +3 -1
- package/src/remote.ts +8 -2
- package/src/state-manager.ts +5 -2
- package/src/test-plan.ts +20 -0
- package/src/utils/logger.ts +9 -1
package/src/ai/navigator.ts
CHANGED
|
@@ -9,11 +9,14 @@ import Explorer from '../explorer.ts';
|
|
|
9
9
|
import type { KnowledgeTracker } from '../knowledge-tracker.js';
|
|
10
10
|
import { type StateManager, normalizeUrl } from '../state-manager.js';
|
|
11
11
|
import { renderAssertion } from '../playwright-recorder.ts';
|
|
12
|
+
import { isFatalBrowserError } from '../utils/browser-errors.ts';
|
|
13
|
+
import { getCliName } from '../utils/cli-name.ts';
|
|
12
14
|
import { extractCodeBlocks } from '../utils/code-extractor.js';
|
|
13
15
|
import { HooksRunner } from '../utils/hooks-runner.ts';
|
|
14
16
|
import { createDebug, pluralize, tag } from '../utils/logger.js';
|
|
15
17
|
import { loop, pause } from '../utils/loop.js';
|
|
16
18
|
import { RulesLoader } from '../utils/rules-loader.ts';
|
|
19
|
+
import { normalizeInlineText } from '../utils/strings.ts';
|
|
17
20
|
import { extractStatePath, matchesNavigationUrl } from '../utils/url-matcher.js';
|
|
18
21
|
import type { Agent, AgentDeps } from './agent.js';
|
|
19
22
|
import type { Conversation } from './conversation.js';
|
|
@@ -33,6 +36,7 @@ class Navigator implements Agent {
|
|
|
33
36
|
private hooksRunner: HooksRunner;
|
|
34
37
|
|
|
35
38
|
private MAX_ATTEMPTS = Number.parseInt(process.env.MAX_ATTEMPTS || '5');
|
|
39
|
+
lastFailureReason: string | null = null;
|
|
36
40
|
|
|
37
41
|
private systemPrompt = dedent`
|
|
38
42
|
<role>
|
|
@@ -105,8 +109,12 @@ class Navigator implements Agent {
|
|
|
105
109
|
private getComparableCurrentUrl(stateManager: any, expectedUrl: string): string {
|
|
106
110
|
const currentState = stateManager.getCurrentState();
|
|
107
111
|
if (!currentState) return '';
|
|
108
|
-
|
|
109
|
-
|
|
112
|
+
return this.comparableUrl(currentState, expectedUrl);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private comparableUrl(state: { url?: string; fullUrl?: string }, expectedUrl: string): string {
|
|
116
|
+
if (/^https?:\/\//i.test(expectedUrl)) return state.fullUrl || state.url || '';
|
|
117
|
+
return state.url || '';
|
|
110
118
|
}
|
|
111
119
|
|
|
112
120
|
private isSameExpectedOrigin(expectedUrl: string, stateManager: any): boolean {
|
|
@@ -162,7 +170,7 @@ class Navigator implements Agent {
|
|
|
162
170
|
|
|
163
171
|
const resolved = await this.resolveState(originalMessage, actionResult, { action, expectedUrl: url });
|
|
164
172
|
if (!resolved) {
|
|
165
|
-
throw
|
|
173
|
+
throw this.navigationError(url, `redirected to ${actualPath} and could not resolve`);
|
|
166
174
|
}
|
|
167
175
|
} else if (action.lastError) {
|
|
168
176
|
const actionResult = action.actionResult || ActionResult.fromState(action.stateManager.getCurrentState()!);
|
|
@@ -174,7 +182,7 @@ class Navigator implements Agent {
|
|
|
174
182
|
|
|
175
183
|
const resolved = await this.resolveState(originalMessage, actionResult, { action, expectedUrl: url });
|
|
176
184
|
if (!resolved) {
|
|
177
|
-
throw
|
|
185
|
+
throw this.navigationError(url, action.lastError?.message || 'Navigation failed');
|
|
178
186
|
}
|
|
179
187
|
}
|
|
180
188
|
await this.explorer.capture({ screenshot: true });
|
|
@@ -190,9 +198,25 @@ class Navigator implements Agent {
|
|
|
190
198
|
}
|
|
191
199
|
}
|
|
192
200
|
|
|
201
|
+
private navigationError(url: string, fallback: string): Error {
|
|
202
|
+
if (this.lastFailureReason) return new Error(`Navigation to ${url} failed: ${this.lastFailureReason}`);
|
|
203
|
+
return new Error(`Navigation to ${url} failed: ${fallback}`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private failureReason(stopReason: string | null, knowledge: string, url: string): string | null {
|
|
207
|
+
const reasons: string[] = [];
|
|
208
|
+
if (stopReason) reasons.push(stopReason);
|
|
209
|
+
if (!knowledge) {
|
|
210
|
+
const path = extractStatePath(url).split('?')[0].split('#')[0];
|
|
211
|
+
reasons.push(`no knowledge is set for ${path} — teach it what this page needs (credentials, hints) with: ${getCliName()} learn "${path}" "<facts>"`);
|
|
212
|
+
}
|
|
213
|
+
return reasons.join('; ') || null;
|
|
214
|
+
}
|
|
215
|
+
|
|
193
216
|
async resolveState(message: string, actionResult: ActionResult, opts?: { action?: Action; expectedUrl?: string; onAttempt?: (attempt: { code: string; error?: string }) => void }): Promise<boolean> {
|
|
194
217
|
if (!this.provider) throw new Error('AI-assisted recovery is unavailable: no AI model is configured.');
|
|
195
218
|
|
|
219
|
+
this.lastFailureReason = null;
|
|
196
220
|
tag('info').log('AI Navigator resolving state at', actionResult.url);
|
|
197
221
|
debugLog('Resolution message:', message);
|
|
198
222
|
|
|
@@ -200,52 +224,9 @@ class Navigator implements Agent {
|
|
|
200
224
|
const expectedUrl = opts?.expectedUrl;
|
|
201
225
|
|
|
202
226
|
const knowledge = this.knowledgeTracker.renderRelevantContext(actionResult);
|
|
203
|
-
let experience = '';
|
|
204
|
-
|
|
205
|
-
if (!actionResult.isInsideIframe) {
|
|
206
|
-
const successful = this.experienceTracker.getSuccessfulExperience(actionResult);
|
|
207
|
-
if (successful.length > 0) {
|
|
208
|
-
tag('operation').log(`Found ${successful.length} experience ${pluralize(successful.length, 'file')} for: ${actionResult.url}`);
|
|
209
|
-
experience = `<experience>\nPast successful recipes recorded from prior runs for this page. Prefer these solutions first if they match the goal.\n\n${successful.join('\n\n')}\n</experience>`;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
const prompt = dedent`
|
|
214
|
-
<message>
|
|
215
|
-
${message}
|
|
216
|
-
</message>
|
|
217
|
-
|
|
218
|
-
<page>
|
|
219
|
-
${actionResult.toAiContext()}
|
|
220
|
-
|
|
221
|
-
<page_html>
|
|
222
|
-
${await actionResult.combinedHtml()}
|
|
223
|
-
</page_html>
|
|
224
|
-
</page>
|
|
225
|
-
|
|
226
|
-
<task>
|
|
227
|
-
Identify the actual request of the user.
|
|
228
|
-
Identify what is expected by user.
|
|
229
|
-
Identify what might have caused the error.
|
|
230
|
-
Propose different solutions to achieve the result.
|
|
231
|
-
Solution should be valid CodeceptJS code.
|
|
232
|
-
Use only data from the <page> context to plan the solution.
|
|
233
|
-
Try various ways to achieve the result
|
|
234
|
-
</task>
|
|
235
|
-
|
|
236
|
-
${actionRule}
|
|
237
|
-
|
|
238
|
-
${unexpectedPopupRule}
|
|
239
|
-
|
|
240
|
-
${RulesLoader.loadRules('navigator', ['multiple-locator', 'output'], actionResult.url || '').replace('{{maxAttempts}}', String(this.MAX_ATTEMPTS))}
|
|
241
|
-
|
|
242
|
-
${experience}
|
|
243
|
-
|
|
244
|
-
${knowledge}
|
|
245
|
-
`;
|
|
246
227
|
|
|
247
228
|
const conversation = this.provider.startConversation(this.systemPrompt, 'navigator');
|
|
248
|
-
conversation.addUserText(
|
|
229
|
+
conversation.addUserText(await this.buildResolutionPrompt(message, actionResult));
|
|
249
230
|
|
|
250
231
|
let stopReason: string | null = null;
|
|
251
232
|
const tools = {
|
|
@@ -273,8 +254,9 @@ class Navigator implements Agent {
|
|
|
273
254
|
let htmlContextAdded = false;
|
|
274
255
|
let codeBlockIndex = 0;
|
|
275
256
|
let totalAttempts = 0;
|
|
257
|
+
let lastFailure: string | null = null;
|
|
276
258
|
const progressBlocks: string[] = [];
|
|
277
|
-
const batchFailures:
|
|
259
|
+
const batchFailures: BatchFailure[] = [];
|
|
278
260
|
|
|
279
261
|
let resolved = false;
|
|
280
262
|
await loop(
|
|
@@ -283,7 +265,6 @@ class Navigator implements Agent {
|
|
|
283
265
|
const result = await this.provider.invokeConversation(conversation, tools);
|
|
284
266
|
if (!result) return;
|
|
285
267
|
if (stopReason) {
|
|
286
|
-
tag('error').log(`Navigator stopped: ${stopReason}`);
|
|
287
268
|
resolved = false;
|
|
288
269
|
stop();
|
|
289
270
|
return;
|
|
@@ -307,41 +288,8 @@ class Navigator implements Agent {
|
|
|
307
288
|
return;
|
|
308
289
|
}
|
|
309
290
|
tag('operation').log('Feeding failures back to AI for a new batch...');
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
const lines = batchFailures
|
|
313
|
-
.map((f) => {
|
|
314
|
-
const head = `- \`${f.code.split('\n')[0]}\` → ${f.error}`;
|
|
315
|
-
if (!f.ariaChanges) return head;
|
|
316
|
-
const trimmed = f.ariaChanges.split('\n').slice(0, 12).join('\n ');
|
|
317
|
-
return `${head}\n • ARIA changes after the action:\n ${trimmed}`;
|
|
318
|
-
})
|
|
319
|
-
.join('\n');
|
|
320
|
-
contextMsg += `<previous_failures>\n${lines}\n</previous_failures>\n\n`;
|
|
321
|
-
}
|
|
322
|
-
if (!htmlContextAdded) {
|
|
323
|
-
htmlContextAdded = true;
|
|
324
|
-
contextMsg += `Full HTML context:\n\n<page_html>\n${await actionResult.combinedHtml()}\n</page_html>\n\n`;
|
|
325
|
-
}
|
|
326
|
-
const pageReacted = batchFailures.some((f) => f.ariaChanges);
|
|
327
|
-
if (pageReacted) {
|
|
328
|
-
contextMsg += dedent`
|
|
329
|
-
Some steps in the previous batch did not throw, but the URL did not change to the expected target and the page changed in other ways — the ARIA diff for each such step is listed in <previous_failures> above.
|
|
330
|
-
|
|
331
|
-
Read those diffs and judge what each step actually triggered. Different action types produce different reactions; the diff is your only evidence of what happened. A diff might show, for example: a new alert / alertdialog / status / validation message appearing near a field or at page level; a modal, dialog, or wizard step opening; a banner, toast, or notification region appearing; a section expanding or collapsing; a tab or accordion switching content. A diff might also be empty or unrelated to the step — that is also a signal.
|
|
332
|
-
|
|
333
|
-
Choose exactly ONE path based on what the diffs actually show — do not assume the previous step submitted any particular kind of data:
|
|
334
|
-
|
|
335
|
-
A. The diff indicates the application requires something only the user can supply — for example: an authentication failure you cannot guess past, a captcha, a permission the test cannot satisfy, or knowledge that is not present in the provided context. Call the stop() tool and quote what you saw in the diff and what is needed.
|
|
336
|
-
|
|
337
|
-
B. The diff indicates the next step is something you can perform from the existing knowledge / hint context — for example: re-emit a step with a value that exists in the knowledge but was used incorrectly; dismiss an unexpected modal; accept a confirmation; take a follow-up step the page now requires. Emit code blocks for that next step. Do NOT change the locator of a step that already produced a reaction.
|
|
338
|
-
|
|
339
|
-
C. The diff is empty or unrelated to your step — the action likely missed its target. Propose a different locator strategy.
|
|
340
|
-
`;
|
|
341
|
-
} else {
|
|
342
|
-
contextMsg += 'Propose new solutions. If errors mention "intercepts pointer events" or timeouts on visible elements, an overlay is blocking — dismiss it first (Escape, click outside, Close button) before retrying the original action.';
|
|
343
|
-
}
|
|
344
|
-
conversation.addUserText(contextMsg);
|
|
291
|
+
conversation.addUserText(await this.buildRetryFeedback(batchFailures, !htmlContextAdded, actionResult));
|
|
292
|
+
htmlContextAdded = true;
|
|
345
293
|
codeBlocks = [];
|
|
346
294
|
batchFailures.length = 0;
|
|
347
295
|
return;
|
|
@@ -349,114 +297,59 @@ class Navigator implements Agent {
|
|
|
349
297
|
codeBlockIndex++;
|
|
350
298
|
totalAttempts++;
|
|
351
299
|
|
|
352
|
-
await action.exitIframe();
|
|
353
|
-
|
|
354
300
|
const prevActionResult = action.actionResult ?? actionResult;
|
|
355
301
|
const prevHash = prevActionResult.getStateHash();
|
|
356
302
|
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
try {
|
|
363
|
-
await page.waitForLoadState('load', { timeout: 5000 });
|
|
364
|
-
} catch {
|
|
365
|
-
// Navigation did not reach 'load' state within timeout; continue and verify URL
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
if (attemptOk) opts?.onAttempt?.({ code: codeBlock });
|
|
370
|
-
|
|
371
|
-
if (!attemptOk) {
|
|
372
|
-
const raw = action.lastError?.message || 'attempt failed';
|
|
373
|
-
const firstMeaningful = raw.split('\n').find((l) => l.trim() && !l.trim().startsWith('at ')) || raw;
|
|
374
|
-
const shortErr = firstMeaningful.replace(/\s+/g, ' ').trim().slice(0, 220);
|
|
375
|
-
batchFailures.push({ code: codeBlock, error: shortErr });
|
|
376
|
-
opts?.onAttempt?.({ code: codeBlock, error: shortErr });
|
|
303
|
+
const attempt = await this.executeAttempt(action, codeBlock, message);
|
|
304
|
+
opts?.onAttempt?.({ code: codeBlock, error: attempt.error });
|
|
305
|
+
if (attempt.error) {
|
|
306
|
+
batchFailures.push({ code: codeBlock, error: attempt.error });
|
|
307
|
+
lastFailure = attempt.error;
|
|
377
308
|
}
|
|
378
309
|
|
|
379
310
|
if (expectedUrl) {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
const freshState = await this.explorer.capture();
|
|
388
|
-
const currentUrl = /^https?:\/\//i.test(expectedUrl) ? freshState.fullUrl || freshState.url || '' : freshState.url || '';
|
|
389
|
-
const urlMatches = this.isSameExpectedOrigin(expectedUrl, action.stateManager) && matchesNavigationUrl(expectedUrl, currentUrl);
|
|
390
|
-
const stateChanged = freshState.getStateHash() !== actionResult.getStateHash();
|
|
391
|
-
resolved = urlMatches && stateChanged;
|
|
392
|
-
|
|
393
|
-
if (!resolved && attemptOk) {
|
|
394
|
-
let ariaChanges: string | null = null;
|
|
395
|
-
if (freshState.getStateHash() !== prevHash) {
|
|
396
|
-
try {
|
|
397
|
-
const diff = await freshState.diff(prevActionResult);
|
|
398
|
-
ariaChanges = diff.ariaChanged;
|
|
399
|
-
} catch (err) {
|
|
400
|
-
debugLog('Failed to compute pageDiff for failed URL verification:', err);
|
|
401
|
-
}
|
|
402
|
-
}
|
|
311
|
+
const check = await this.verifyNavigation(action, expectedUrl);
|
|
312
|
+
const freshHash = check.freshState.getStateHash();
|
|
313
|
+
resolved = check.urlMatches && freshHash !== actionResult.getStateHash();
|
|
314
|
+
|
|
315
|
+
if (!resolved && attempt.ok) {
|
|
316
|
+
lastFailure = `URL did not change (still ${check.freshState.url})`;
|
|
403
317
|
batchFailures.push({
|
|
404
318
|
code: codeBlock,
|
|
405
|
-
error:
|
|
406
|
-
ariaChanges,
|
|
407
|
-
urlAfter: freshState.url,
|
|
319
|
+
error: lastFailure,
|
|
320
|
+
ariaChanges: await this.ariaDiff(check.freshState, prevActionResult),
|
|
321
|
+
urlAfter: check.freshState.url,
|
|
408
322
|
});
|
|
409
|
-
tag('warning').log(`URL verification failed: expected ${expectedUrl}, got ${freshState.url}`);
|
|
323
|
+
tag('warning').log(`URL verification failed: expected ${expectedUrl}, got ${check.freshState.url}`);
|
|
410
324
|
}
|
|
411
|
-
if (
|
|
325
|
+
if (freshHash !== prevHash && (attempt.ok || check.urlMatches)) {
|
|
412
326
|
progressBlocks.push(codeBlock);
|
|
413
327
|
}
|
|
414
328
|
} else {
|
|
415
|
-
resolved =
|
|
416
|
-
if (
|
|
329
|
+
resolved = attempt.ok;
|
|
330
|
+
if (attempt.ok) progressBlocks.push(codeBlock);
|
|
417
331
|
}
|
|
418
332
|
|
|
419
|
-
if (resolved)
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
const toPath = extractStatePath(expectedUrl);
|
|
425
|
-
scenario = `reach ${toPath} from ${fromPath}`;
|
|
426
|
-
}
|
|
427
|
-
const recipe = progressBlocks
|
|
428
|
-
.join('\n')
|
|
429
|
-
.split('\n')
|
|
430
|
-
.filter((line) => !/^\s*I\.amOnPage\s*\(/.test(line))
|
|
431
|
-
.join('\n')
|
|
432
|
-
.trim();
|
|
433
|
-
if (recipe) {
|
|
434
|
-
const body = `## FLOW: ${scenario}\n\n* ${scenario}\n\n\`\`\`js\n${recipe}\n\`\`\`\n\n---\n`;
|
|
435
|
-
this.experienceTracker.writeFlow(actionResult, body);
|
|
436
|
-
}
|
|
437
|
-
stop();
|
|
438
|
-
return;
|
|
439
|
-
}
|
|
333
|
+
if (!resolved) return;
|
|
334
|
+
|
|
335
|
+
tag('success').log('Navigation resolved successfully');
|
|
336
|
+
this.saveFlow(message, expectedUrl, actionResult, progressBlocks);
|
|
337
|
+
stop();
|
|
440
338
|
},
|
|
441
339
|
{
|
|
442
340
|
maxAttempts: this.MAX_ATTEMPTS * 2,
|
|
443
341
|
observability: {
|
|
444
342
|
agent: 'navigator',
|
|
445
343
|
},
|
|
446
|
-
catch: async (error) => {
|
|
344
|
+
catch: async ({ error }) => {
|
|
345
|
+
if (isFatalBrowserError(error)) throw error;
|
|
447
346
|
debugLog(error);
|
|
448
347
|
resolved = false;
|
|
449
348
|
},
|
|
450
349
|
}
|
|
451
350
|
);
|
|
452
351
|
|
|
453
|
-
if (!resolved && expectedUrl)
|
|
454
|
-
await (action.getActor() as any).wait(1);
|
|
455
|
-
if (this.isOnExpectedPage(expectedUrl, action.stateManager)) {
|
|
456
|
-
resolved = true;
|
|
457
|
-
tag('success').log('Navigation resolved after delayed redirect');
|
|
458
|
-
}
|
|
459
|
-
}
|
|
352
|
+
if (!resolved && expectedUrl) resolved = await this.rescueDelayedRedirect(action, expectedUrl);
|
|
460
353
|
|
|
461
354
|
if (!resolved && stopReason) {
|
|
462
355
|
tag('error').log(`Navigator stopped: ${stopReason}`);
|
|
@@ -464,24 +357,192 @@ class Navigator implements Agent {
|
|
|
464
357
|
tag('error').log(`Navigation failed after ${totalAttempts} attempts`);
|
|
465
358
|
}
|
|
466
359
|
|
|
467
|
-
if (!resolved && isInteractive())
|
|
468
|
-
const stopLine = stopReason ? `Navigator stopped: ${stopReason}\n` : '';
|
|
469
|
-
const userInput = await pause(`${stopLine}Navigator failed to resolve. Current: ${action.stateManager.getCurrentState()?.url}\n` + `Target: ${expectedUrl ?? '(none)'}\nEnter CodeceptJS commands (or press Enter to skip):`);
|
|
360
|
+
if (!resolved && isInteractive()) resolved = await this.askUserToResolve(action, message, expectedUrl, stopReason);
|
|
470
361
|
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
resolved = false;
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
}
|
|
362
|
+
if (!resolved) {
|
|
363
|
+
let cause = 'the AI proposed no working solution for this page';
|
|
364
|
+
if (lastFailure) cause = `${totalAttempts} ${pluralize(totalAttempts, 'attempt')} failed, last: ${lastFailure}`;
|
|
365
|
+
if (stopReason) cause = stopReason;
|
|
366
|
+
this.lastFailureReason = this.failureReason(cause, knowledge, actionResult.url || '');
|
|
480
367
|
}
|
|
481
368
|
|
|
482
369
|
return resolved;
|
|
483
370
|
}
|
|
484
371
|
|
|
372
|
+
private async buildResolutionPrompt(message: string, actionResult: ActionResult): Promise<string> {
|
|
373
|
+
let experience = '';
|
|
374
|
+
if (!actionResult.isInsideIframe) {
|
|
375
|
+
const successful = this.experienceTracker.getSuccessfulExperience(actionResult);
|
|
376
|
+
if (successful.length > 0) {
|
|
377
|
+
tag('operation').log(`Found ${successful.length} experience ${pluralize(successful.length, 'file')} for: ${actionResult.url}`);
|
|
378
|
+
experience = `<experience>\nPast successful recipes recorded from prior runs for this page. Prefer these solutions first if they match the goal.\n\n${successful.join('\n\n')}\n</experience>`;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
return dedent`
|
|
383
|
+
<message>
|
|
384
|
+
${message}
|
|
385
|
+
</message>
|
|
386
|
+
|
|
387
|
+
<page>
|
|
388
|
+
${actionResult.toAiContext()}
|
|
389
|
+
|
|
390
|
+
<page_html>
|
|
391
|
+
${await actionResult.combinedHtml()}
|
|
392
|
+
</page_html>
|
|
393
|
+
</page>
|
|
394
|
+
|
|
395
|
+
<task>
|
|
396
|
+
Identify the actual request of the user.
|
|
397
|
+
Identify what is expected by user.
|
|
398
|
+
Identify what might have caused the error.
|
|
399
|
+
Propose different solutions to achieve the result.
|
|
400
|
+
Solution should be valid CodeceptJS code.
|
|
401
|
+
Use only data from the <page> context to plan the solution.
|
|
402
|
+
Try various ways to achieve the result
|
|
403
|
+
</task>
|
|
404
|
+
|
|
405
|
+
${actionRule}
|
|
406
|
+
|
|
407
|
+
${unexpectedPopupRule}
|
|
408
|
+
|
|
409
|
+
${RulesLoader.loadRules('navigator', ['multiple-locator', 'output'], actionResult.url || '').replace('{{maxAttempts}}', String(this.MAX_ATTEMPTS))}
|
|
410
|
+
|
|
411
|
+
${experience}
|
|
412
|
+
|
|
413
|
+
${this.knowledgeTracker.renderRelevantContext(actionResult)}
|
|
414
|
+
`;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
private async buildRetryFeedback(failures: BatchFailure[], includeHtml: boolean, actionResult: ActionResult): Promise<string> {
|
|
418
|
+
let contextMsg = 'Previous solutions did not work. Analyze the failures and try DIFFERENT strategies (not syntactic variants of the same locator).\n\n';
|
|
419
|
+
|
|
420
|
+
if (failures.length > 0) {
|
|
421
|
+
const lines = failures
|
|
422
|
+
.map((f) => {
|
|
423
|
+
const head = `- \`${f.code.split('\n')[0]}\` → ${f.error}`;
|
|
424
|
+
if (!f.ariaChanges) return head;
|
|
425
|
+
const trimmed = f.ariaChanges.split('\n').slice(0, 12).join('\n ');
|
|
426
|
+
return `${head}\n • ARIA changes after the action:\n ${trimmed}`;
|
|
427
|
+
})
|
|
428
|
+
.join('\n');
|
|
429
|
+
contextMsg += `<previous_failures>\n${lines}\n</previous_failures>\n\n`;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
if (includeHtml) {
|
|
433
|
+
contextMsg += `Full HTML context:\n\n<page_html>\n${await actionResult.combinedHtml()}\n</page_html>\n\n`;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (!failures.some((f) => f.ariaChanges)) {
|
|
437
|
+
return `${contextMsg}Propose new solutions. If errors mention "intercepts pointer events" or timeouts on visible elements, an overlay is blocking — dismiss it first (Escape, click outside, Close button) before retrying the original action.`;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
return (
|
|
441
|
+
contextMsg +
|
|
442
|
+
dedent`
|
|
443
|
+
Some steps in the previous batch did not throw, but the URL did not change to the expected target and the page changed in other ways — the ARIA diff for each such step is listed in <previous_failures> above.
|
|
444
|
+
|
|
445
|
+
Read those diffs and judge what each step actually triggered. Different action types produce different reactions; the diff is your only evidence of what happened. A diff might show, for example: a new alert / alertdialog / status / validation message appearing near a field or at page level; a modal, dialog, or wizard step opening; a banner, toast, or notification region appearing; a section expanding or collapsing; a tab or accordion switching content. A diff might also be empty or unrelated to the step — that is also a signal.
|
|
446
|
+
|
|
447
|
+
Choose exactly ONE path based on what the diffs actually show — do not assume the previous step submitted any particular kind of data:
|
|
448
|
+
|
|
449
|
+
A. The diff indicates the application requires something only the user can supply — for example: an authentication failure you cannot guess past, a captcha, a permission the test cannot satisfy, or knowledge that is not present in the provided context. Call the stop() tool and quote what you saw in the diff and what is needed.
|
|
450
|
+
|
|
451
|
+
B. The diff indicates the next step is something you can perform from the existing knowledge / hint context — for example: re-emit a step with a value that exists in the knowledge but was used incorrectly; dismiss an unexpected modal; accept a confirmation; take a follow-up step the page now requires. Emit code blocks for that next step. Do NOT change the locator of a step that already produced a reaction.
|
|
452
|
+
|
|
453
|
+
C. The diff is empty or unrelated to your step — the action likely missed its target. Propose a different locator strategy.
|
|
454
|
+
`
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
private async executeAttempt(action: Action, codeBlock: string, message: string): Promise<{ ok: boolean; error?: string }> {
|
|
459
|
+
await action.exitIframe();
|
|
460
|
+
|
|
461
|
+
debugLog(`Attempting resolution: ${codeBlock}`);
|
|
462
|
+
const ok = await action.attempt(codeBlock, message);
|
|
463
|
+
|
|
464
|
+
const page = action.playwrightHelper?.page;
|
|
465
|
+
if (page) {
|
|
466
|
+
try {
|
|
467
|
+
await page.waitForLoadState('load', { timeout: 5000 });
|
|
468
|
+
} catch {
|
|
469
|
+
// Navigation did not reach 'load' state within timeout; continue and verify URL
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
if (ok) return { ok };
|
|
474
|
+
|
|
475
|
+
const raw = action.lastError?.message || 'attempt failed';
|
|
476
|
+
const firstMeaningful = raw.split('\n').find((l) => l.trim() && !l.trim().startsWith('at ')) || raw;
|
|
477
|
+
return { ok, error: normalizeInlineText(firstMeaningful).slice(0, 220) || 'attempt failed' };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
private async verifyNavigation(action: Action, expectedUrl: string): Promise<{ freshState: ActionResult; urlMatches: boolean }> {
|
|
481
|
+
const page = action.playwrightHelper?.page;
|
|
482
|
+
if (page) {
|
|
483
|
+
try {
|
|
484
|
+
await page.waitForURL((url: URL) => matchesNavigationUrl(expectedUrl, `${url.pathname}${url.search}${url.hash}`), { timeout: 5000 });
|
|
485
|
+
} catch {
|
|
486
|
+
// URL did not transition to expectedUrl within timeout
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
const freshState = await this.explorer.capture();
|
|
491
|
+
const urlMatches = this.isSameExpectedOrigin(expectedUrl, action.stateManager) && matchesNavigationUrl(expectedUrl, this.comparableUrl(freshState, expectedUrl));
|
|
492
|
+
|
|
493
|
+
return { freshState, urlMatches };
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
private async ariaDiff(freshState: ActionResult, previous: ActionResult): Promise<string | null> {
|
|
497
|
+
if (freshState.getStateHash() === previous.getStateHash()) return null;
|
|
498
|
+
try {
|
|
499
|
+
const diff = await freshState.diff(previous);
|
|
500
|
+
return diff.ariaChanged;
|
|
501
|
+
} catch (err) {
|
|
502
|
+
debugLog('Failed to compute pageDiff for failed URL verification:', err);
|
|
503
|
+
return null;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
private saveFlow(message: string, expectedUrl: string | undefined, actionResult: ActionResult, progressBlocks: string[]): void {
|
|
508
|
+
let scenario = message.split('\n')[0];
|
|
509
|
+
if (expectedUrl) {
|
|
510
|
+
scenario = `reach ${extractStatePath(expectedUrl)} from ${extractStatePath(actionResult.url || '')}`;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const recipe = progressBlocks
|
|
514
|
+
.join('\n')
|
|
515
|
+
.split('\n')
|
|
516
|
+
.filter((line) => !/^\s*I\.amOnPage\s*\(/.test(line))
|
|
517
|
+
.join('\n')
|
|
518
|
+
.trim();
|
|
519
|
+
if (!recipe) return;
|
|
520
|
+
|
|
521
|
+
this.experienceTracker.writeFlow(actionResult, `## FLOW: ${scenario}\n\n* ${scenario}\n\n\`\`\`js\n${recipe}\n\`\`\`\n\n---\n`);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
private async rescueDelayedRedirect(action: Action, expectedUrl: string): Promise<boolean> {
|
|
525
|
+
await (action.getActor() as any).wait(1);
|
|
526
|
+
if (!this.isOnExpectedPage(expectedUrl, action.stateManager)) return false;
|
|
527
|
+
tag('success').log('Navigation resolved after delayed redirect');
|
|
528
|
+
return true;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
private async askUserToResolve(action: Action, message: string, expectedUrl: string | undefined, stopReason: string | null): Promise<boolean> {
|
|
532
|
+
let stopLine = '';
|
|
533
|
+
if (stopReason) stopLine = `Navigator stopped: ${stopReason}\n`;
|
|
534
|
+
|
|
535
|
+
const userInput = await pause(`${stopLine}Navigator failed to resolve. Current: ${action.stateManager.getCurrentState()?.url}\nTarget: ${expectedUrl ?? '(none)'}\nEnter CodeceptJS commands (or press Enter to skip):`);
|
|
536
|
+
if (!userInput?.trim()) return false;
|
|
537
|
+
|
|
538
|
+
const resolved = await action.attempt(userInput, message);
|
|
539
|
+
if (!resolved) return false;
|
|
540
|
+
if (!expectedUrl) return true;
|
|
541
|
+
|
|
542
|
+
await (action.getActor() as any).wait(1);
|
|
543
|
+
return this.isOnExpectedPage(expectedUrl, action.stateManager);
|
|
544
|
+
}
|
|
545
|
+
|
|
485
546
|
private buildExperienceTools(): { learnExperience: unknown } | undefined {
|
|
486
547
|
if (!this.experienceTracker) return undefined;
|
|
487
548
|
const stateManager = this.stateManager;
|
|
@@ -791,6 +852,8 @@ class Navigator implements Agent {
|
|
|
791
852
|
}
|
|
792
853
|
}
|
|
793
854
|
|
|
855
|
+
type BatchFailure = { code: string; error: string; ariaChanges?: string | null; urlAfter?: string };
|
|
856
|
+
|
|
794
857
|
export type AssertionResult = { code: string; passed: boolean; proof: string[] };
|
|
795
858
|
|
|
796
859
|
export { Navigator };
|