explorbot 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/bin/explorbot-cli.ts +19 -7
  2. package/boat/api-tester/src/cli.ts +17 -0
  3. package/boat/doc-collector/src/cli.ts +14 -1
  4. package/boat/prima/README.md +96 -0
  5. package/boat/prima/package.json +14 -10
  6. package/boat/prima/src/cli.ts +29 -12
  7. package/boat/prima/src/envelope.ts +35 -13
  8. package/boat/prima/src/prima.ts +78 -45
  9. package/dist/bin/explorbot-cli.js +19 -7
  10. package/dist/boat/api-tester/src/cli.js +17 -0
  11. package/dist/boat/doc-collector/src/cli.js +14 -1
  12. package/dist/boat/prima/src/cli.js +26 -7
  13. package/dist/boat/prima/src/envelope.js +32 -8
  14. package/dist/boat/prima/src/prima.js +75 -43
  15. package/dist/models.json +4 -4
  16. package/dist/package.json +6 -2
  17. package/dist/src/action-result.d.ts +13 -0
  18. package/dist/src/action-result.js +46 -15
  19. package/dist/src/action.d.ts +5 -2
  20. package/dist/src/action.js +53 -18
  21. package/dist/src/ai/captain/web-mode.js +1 -2
  22. package/dist/src/ai/captain.d.ts +20 -0
  23. package/dist/src/ai/captain.js +10 -1
  24. package/dist/src/ai/driller.js +6 -2
  25. package/dist/src/ai/fisherman-tools.d.ts +40 -1
  26. package/dist/src/ai/fisherman-tools.js +39 -0
  27. package/dist/src/ai/fisherman.js +2 -1
  28. package/dist/src/ai/navigator.d.ts +28 -0
  29. package/dist/src/ai/navigator.js +223 -175
  30. package/dist/src/ai/pilot.d.ts +7 -4
  31. package/dist/src/ai/pilot.js +89 -30
  32. package/dist/src/ai/planner/subpages.js +2 -16
  33. package/dist/src/ai/planner.js +1 -1
  34. package/dist/src/ai/provider.d.ts +2 -2
  35. package/dist/src/ai/provider.js +28 -22
  36. package/dist/src/ai/researcher/cache.d.ts +10 -3
  37. package/dist/src/ai/researcher/cache.js +23 -10
  38. package/dist/src/ai/researcher/deep-analysis.js +1 -1
  39. package/dist/src/ai/researcher/fingerprint-worker.js +21 -4
  40. package/dist/src/ai/researcher.js +6 -4
  41. package/dist/src/ai/rules.js +1 -5
  42. package/dist/src/ai/session-analyst.js +2 -0
  43. package/dist/src/ai/tester.d.ts +6 -3
  44. package/dist/src/ai/tester.js +30 -35
  45. package/dist/src/ai/tools.d.ts +8 -5
  46. package/dist/src/ai/tools.js +83 -57
  47. package/dist/src/commands/config-command.d.ts +51 -0
  48. package/dist/src/commands/config-command.js +117 -0
  49. package/dist/src/commands/index.js +2 -0
  50. package/dist/src/commands/init-command.js +13 -20
  51. package/dist/src/config.d.ts +8 -1
  52. package/dist/src/config.js +43 -1
  53. package/dist/src/experience-tracker.d.ts +2 -0
  54. package/dist/src/experience-tracker.js +12 -0
  55. package/dist/src/explorbot.js +5 -2
  56. package/dist/src/playwright-recorder.js +6 -12
  57. package/dist/src/remote.d.ts +3 -2
  58. package/dist/src/remote.js +8 -2
  59. package/dist/src/state-manager.d.ts +1 -1
  60. package/dist/src/state-manager.js +3 -1
  61. package/dist/src/test-plan.d.ts +9 -0
  62. package/dist/src/test-plan.js +30 -0
  63. package/dist/src/utils/html-diff.d.ts +5 -0
  64. package/dist/src/utils/html-diff.js +65 -6
  65. package/dist/src/utils/logger.d.ts +1 -1
  66. package/dist/src/utils/logger.js +8 -0
  67. package/dist/src/utils/strings.d.ts +2 -0
  68. package/dist/src/utils/strings.js +32 -0
  69. package/dist/src/utils/url-matcher.d.ts +1 -0
  70. package/dist/src/utils/url-matcher.js +31 -2
  71. package/docs/basics/getting-started.md +33 -10
  72. package/docs/basics/providers.md +6 -4
  73. package/docs/contributing/npm-package.md +73 -4
  74. package/docs/index.json +2 -1
  75. package/docs/reference/commands.md +3 -0
  76. package/docs/reference/websocket.md +50 -0
  77. package/docs/superpowers/specs/2026-08-18-prima-false-verdicts.md +159 -0
  78. package/models.json +4 -4
  79. package/package.json +6 -2
  80. package/src/action-result.ts +61 -16
  81. package/src/action.ts +56 -18
  82. package/src/ai/captain/web-mode.ts +1 -2
  83. package/src/ai/captain.ts +9 -1
  84. package/src/ai/driller.ts +6 -2
  85. package/src/ai/fisherman-tools.ts +35 -0
  86. package/src/ai/fisherman.ts +2 -1
  87. package/src/ai/navigator.ts +238 -179
  88. package/src/ai/pilot.ts +104 -36
  89. package/src/ai/planner/subpages.ts +2 -13
  90. package/src/ai/planner.ts +1 -1
  91. package/src/ai/provider.ts +29 -21
  92. package/src/ai/researcher/cache.ts +29 -11
  93. package/src/ai/researcher/deep-analysis.ts +1 -1
  94. package/src/ai/researcher/fingerprint-worker.ts +23 -5
  95. package/src/ai/researcher.ts +6 -4
  96. package/src/ai/rules.ts +1 -5
  97. package/src/ai/session-analyst.ts +2 -0
  98. package/src/ai/tester.ts +33 -34
  99. package/src/ai/tools.ts +88 -61
  100. package/src/commands/config-command.ts +146 -0
  101. package/src/commands/index.ts +2 -0
  102. package/src/commands/init-command.ts +14 -20
  103. package/src/config.ts +47 -2
  104. package/src/experience-tracker.ts +13 -0
  105. package/src/explorbot.ts +4 -2
  106. package/src/playwright-recorder.ts +6 -11
  107. package/src/remote.ts +8 -2
  108. package/src/state-manager.ts +5 -2
  109. package/src/test-plan.ts +38 -0
  110. package/src/utils/html-diff.ts +72 -7
  111. package/src/utils/logger.ts +9 -1
  112. package/src/utils/strings.ts +36 -0
  113. package/src/utils/url-matcher.ts +27 -2
@@ -19,7 +19,7 @@ import { annotatePageElements } from '../utils/web-annotate.ts';
19
19
  import type { Agent, AgentDeps } from './agent.js';
20
20
  import type { Navigator } from './navigator.ts';
21
21
  import { ContextLengthError, type Provider } from './provider.js';
22
- import { findSimilarResearch, getCachedResearch, saveResearch } from './researcher/cache.ts';
22
+ import { findSimilarResearch, getCachedResearch, reportResearch, saveResearch } from './researcher/cache.ts';
23
23
  import { type CoordinateMethods, WithCoordinates } from './researcher/coordinates.ts';
24
24
  import { type DeepAnalysisMethods, WithDeepAnalysis } from './researcher/deep-analysis.ts';
25
25
  import { detectFocusedSection, hasFocusedSection, markSectionAsFocused, pickDefaultFocusedSection } from './researcher/focus.ts';
@@ -97,11 +97,13 @@ export class Researcher extends ResearcherBase implements Agent {
97
97
  let retriesLeft = opts._retriesLeft ?? maxRetries;
98
98
  this.actionResult = ActionResult.fromState(state);
99
99
  const stateHash = state.hash || this.actionResult.getStateHash();
100
+ const researchState = { ...state, hash: stateHash };
100
101
 
101
102
  if (!force && stateHash) {
102
103
  const cached = getCachedResearch(stateHash);
103
104
  if (cached) {
104
105
  debugLog('Previous research result found');
106
+ reportResearch(stateHash, cached);
105
107
  return cached;
106
108
  }
107
109
  }
@@ -138,10 +140,10 @@ export class Researcher extends ResearcherBase implements Agent {
138
140
  const combinedHtml = await this.actionResult!.combinedHtml();
139
141
 
140
142
  if (!deep && !force) {
141
- const similar = await findSimilarResearch(combinedHtml);
143
+ const similar = await findSimilarResearch(combinedHtml, state.url);
142
144
  if (similar) {
143
145
  tag('operation').log('Similar research found, reusing cached result');
144
- if (stateHash) saveResearch(stateHash, similar, combinedHtml);
146
+ if (stateHash) saveResearch(researchState, similar, combinedHtml);
145
147
  tag('multiline').log(formatResearchSummary(similar));
146
148
  tag('success').log('Research complete (reused)');
147
149
  await this.hooksRunner.runAfterHook('researcher', state.url);
@@ -285,7 +287,7 @@ export class Researcher extends ResearcherBase implements Agent {
285
287
 
286
288
  let researchFile: string | null = null;
287
289
  if (stateHash) {
288
- researchFile = saveResearch(stateHash, result.text, combinedHtml);
290
+ researchFile = saveResearch(researchState, result.text, combinedHtml);
289
291
  }
290
292
 
291
293
  const summaryText = mdq(result.text).query('section2(/^summary/)').query('paragraph[0]').text().trim();
package/src/ai/rules.ts CHANGED
@@ -4,10 +4,6 @@ export const recommendedCodeceptCommands = ['I.click', 'I.type', 'I.fillField',
4
4
 
5
5
  const locatorPriorityRule = dedent`
6
6
  <locator_priority>
7
- When the page context shows the element a ref, such as [ref=e14], there is no locator to select: click it with clickRef
8
- and that ref. A ref names one exact element, so it never matches the wrong one and never has to be narrowed. Everything
9
- below is for elements the context gives no ref for.
10
-
11
7
  Use the following priority when selecting locators:
12
8
 
13
9
  1. ARIA locators (first choice) - target browser's accessibility tree, most reliable
@@ -80,7 +76,7 @@ const locatorStrategyRule = dedent`
80
76
 
81
77
  NEVER include \`eidx\` attribute in any locator (ARIA, CSS, XPath). It is an internal annotation.
82
78
 
83
- If <aria> section is not present or element is not found there, fall back to CSS/XPath locators from <html> section.
79
+ If the element is not found in the ARIA snapshot, fall back to CSS/XPath locators from page HTML.
84
80
 
85
81
  Stick to semantic attributes like role, aria-*, id, class, name, data-id, etc.
86
82
  Avoid IDs that follow framework auto-generation patterns (these change on every page load):
@@ -4,6 +4,7 @@ import dedent from 'dedent';
4
4
  import { outputPath } from '../config.ts';
5
5
  import { Stats } from '../stats.ts';
6
6
  import type { Test } from '../test-plan.ts';
7
+ import { tag } from '../utils/logger.ts';
7
8
  import type { Agent } from './agent.ts';
8
9
  import type { Provider } from './provider.ts';
9
10
 
@@ -117,6 +118,7 @@ export class SessionAnalyst implements Agent {
117
118
  const dir = path.dirname(filePath);
118
119
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
119
120
  writeFileSync(filePath, markdown);
121
+ tag('data').log('report', { path: filePath, content: markdown });
120
122
  return filePath;
121
123
  }
122
124
 
package/src/ai/tester.ts CHANGED
@@ -11,10 +11,11 @@ import { Observability } from '../observability.ts';
11
11
  import type { StateTransition } from '../state-manager.ts';
12
12
  import { Stats } from '../stats.ts';
13
13
  import { type Test, TestResult, type TestResultType } from '../test-plan.ts';
14
- import { compactAriaSnapshot, detectFocusArea } from '../utils/aria.ts';
14
+ import { detectFocusArea } from '../utils/aria.ts';
15
15
  import { ErrorPageError, isErrorPage } from '../utils/error-page.ts';
16
16
  import { createDebug, tag } from '../utils/logger.ts';
17
17
  import { loop } from '../utils/loop.ts';
18
+ import { compactErrorMessage } from '../utils/strings.ts';
18
19
  import type { Agent, AgentDeps } from './agent.ts';
19
20
  import type { Captain } from './captain.ts';
20
21
  import type { Conversation } from './conversation.ts';
@@ -41,6 +42,7 @@ const SAMPLE_FILES: Record<string, string> = {
41
42
 
42
43
  export class Tester extends TaskAgent implements Agent {
43
44
  protected readonly ACTION_TOOLS = ['click', 'hover', 'pressKey', 'form'];
45
+ protected readonly DELEGATED_ACTION_TOOLS = ['interact'];
44
46
  protected readonly SPECIAL_CONTEXT_ACTION_TOOLS = ['exitIframe'];
45
47
  emoji = '🧪';
46
48
  private requestStore: RequestStore;
@@ -96,7 +98,7 @@ export class Tester extends TaskAgent implements Agent {
96
98
  return this.currentConversation;
97
99
  }
98
100
 
99
- async test(task: Test): Promise<{ success: boolean }> {
101
+ async test(task: Test, opts: TestOptions = {}): Promise<{ success: boolean }> {
100
102
  Stats.tests++;
101
103
  const state = this.stateManager.getCurrentState();
102
104
  if (!state) throw new Error('No state found');
@@ -151,11 +153,11 @@ export class Tester extends TaskAgent implements Agent {
151
153
  expected: task.expected,
152
154
  },
153
155
  },
154
- async () => this.runTestSession(task, initialState, conversation, { offFailedRequest })
156
+ async () => this.runTestSession(task, initialState, conversation, { offFailedRequest }, opts)
155
157
  );
156
158
  }
157
159
 
158
- private async runTestSession(task: Test, initialState: ActionResult, conversation: Conversation, handlers: TestSessionHandlers): Promise<{ success: boolean }> {
160
+ private async runTestSession(task: Test, initialState: ActionResult, conversation: Conversation, handlers: TestSessionHandlers, opts: TestOptions): Promise<{ success: boolean }> {
159
161
  const { offFailedRequest } = handlers;
160
162
 
161
163
  if (this.pilot) {
@@ -187,15 +189,19 @@ export class Tester extends TaskAgent implements Agent {
187
189
  return { success: task.isSuccessful };
188
190
  }
189
191
 
190
- debugLog(`Navigating to ${task.startUrl}`);
191
- try {
192
- await this.explorer.visit(task.startUrl!);
193
- } catch (error) {
194
- const result = await this.handleLoopError(task, error);
195
- if (result === 'stop') {
196
- offFailedRequest?.();
197
- await this.cleanupStartedTest(task);
198
- return { success: task.isSuccessful };
192
+ if (opts.startOnCurrentPage) debugLog(`Starting on the page already open at ${task.startUrl}`);
193
+
194
+ if (!opts.startOnCurrentPage) {
195
+ debugLog(`Navigating to ${task.startUrl}`);
196
+ try {
197
+ await this.explorer.visit(task.startUrl!);
198
+ } catch (error) {
199
+ const result = await this.handleLoopError(task, error);
200
+ if (result === 'stop') {
201
+ offFailedRequest?.();
202
+ await this.cleanupStartedTest(task);
203
+ return { success: task.isSuccessful };
204
+ }
199
205
  }
200
206
  }
201
207
 
@@ -271,8 +277,6 @@ export class Tester extends TaskAgent implements Agent {
271
277
  }
272
278
 
273
279
  conversation.cleanupTag('page_aria', '...cleaned aria snapshot...', 1);
274
- conversation.cleanupTag('page_html', '...cleaned HTML snapshot...', 1);
275
- conversation.cleanupTag('experience', '...cleaned experience...', 1);
276
280
  conversation.cleanupTag('applied_experience', '...cleaned past experience...', 1);
277
281
  conversation.cleanupTag('page_ui_map', '...cleaned UI map...', 1);
278
282
  conversation.cleanupTag('page_ui_map_overlay', '...cleaned UI overlay...', 1);
@@ -410,8 +414,6 @@ export class Tester extends TaskAgent implements Agent {
410
414
  this.stalledIterations = 0;
411
415
  tag('info').log(`Pilot extending test (${extensions}/${this.MAX_EXTENSIONS})`);
412
416
  conversation.cleanupTag('page_aria', '...trimmed...', 1);
413
- conversation.cleanupTag('page_html', '...trimmed...', 0);
414
- conversation.cleanupTag('experience', '...trimmed...', 0);
415
417
  conversation.cleanupTag('page_ui_map', '...trimmed...', 0);
416
418
  conversation.cleanupTag('page_ui_map_overlay', '...trimmed...', 0);
417
419
  conversation.compactToolResults(1);
@@ -451,7 +453,7 @@ export class Tester extends TaskAgent implements Agent {
451
453
 
452
454
  const currentState = this.getCurrentState();
453
455
  const stateChanged = previousState.url !== currentState.url || previousState.hash !== currentState.hash;
454
- const actionTools = [...this.ACTION_TOOLS, ...this.SPECIAL_CONTEXT_ACTION_TOOLS];
456
+ const actionTools = [...this.ACTION_TOOLS, ...this.DELEGATED_ACTION_TOOLS, ...this.SPECIAL_CONTEXT_ACTION_TOOLS];
455
457
  const hasSuccessfulAction = toolExecutions.some((execution) => execution.wasSuccessful && actionTools.includes(execution.toolName));
456
458
  const hasSuccessfulAssertion = toolExecutions.some((execution) => execution.wasSuccessful && this.ASSERTION_TOOLS.includes(execution.toolName));
457
459
 
@@ -478,6 +480,7 @@ export class Tester extends TaskAgent implements Agent {
478
480
 
479
481
  <rules>
480
482
  Use tools ${this.ACTION_TOOLS.join(', ')} to interact with the page.
483
+ Fall back to interact() when those fail, when the step needs a sequence of actions, or when your context is not enough to locate the element.
481
484
  Use tool names exactly as listed in this prompt. Do not invent combined tool names, aliases, or names with channel markers such as "commentary".
482
485
  Match each tool input schema exactly. Do not invent parameter names or pass extra fields.
483
486
  Do not do unsuccesful clicks again.
@@ -598,13 +601,13 @@ export class Tester extends TaskAgent implements Agent {
598
601
  </page>
599
602
 
600
603
  <page_aria>
601
- ${await this.interactiveAriaWithRefs(currentState)}
604
+ ${currentState.getInteractiveARIA()}
602
605
  </page_aria>
603
606
  ${uiMapSection}
604
607
 
605
608
  Use <page_ui_map> to understand the page structure and its main elements.
606
- However, <page_ui_map> is not always up to date, use <page_aria> and <page_html> to understand the ACTUAL state of the page
607
- Do not interact with elements that are not listed in <page_aria> and <page_html>
609
+ However, <page_ui_map> is not always up to date, use <page_aria> to understand the ACTUAL state of the page
610
+ Do not interact with elements that are not listed in <page_aria> or in HTML returned by tools
608
611
  Refer to information on page sections in <page_ui_map> and use container CSS locators to interact with elements inside sections
609
612
  `;
610
613
  return context;
@@ -635,17 +638,11 @@ export class Tester extends TaskAgent implements Agent {
635
638
  </page>
636
639
 
637
640
  <page_aria>
638
- ${await this.interactiveAriaWithRefs(currentState)}
641
+ ${currentState.getInteractiveARIA()}
639
642
  </page_aria>
640
643
  `;
641
644
  }
642
645
 
643
- private async interactiveAriaWithRefs(state: ActionResult): Promise<string> {
644
- const withRefs = await Promise.resolve(this.explorer?.withPage?.((page: any) => page.locator('body').ariaSnapshot({ mode: 'ai' }))).catch(() => null);
645
- if (!withRefs) return state.getInteractiveARIA();
646
- return compactAriaSnapshot(withRefs, false);
647
- }
648
-
649
646
  private finishTest(task: Test): void {
650
647
  if (!task.result) {
651
648
  if (task.hasAchievedAll()) task.finish(TestResult.PASSED);
@@ -715,7 +712,7 @@ export class Tester extends TaskAgent implements Agent {
715
712
 
716
713
  <rules>
717
714
  - Refer to UI Map from <page_ui_map> to understand the page structure and its main elements
718
- - Use only elements that exist in the provided ARIA tree or HTML, <page_aria> and <page_html>
715
+ - Use only elements that exist in <page_aria> or in HTML returned by tools
719
716
  - Use tool input schemas exactly as documented. Do not invent parameter names or add fields not listed by the tool schema.
720
717
  - Use click() for buttons, links, and clickable elements ONLY - do NOT include I.fillField() or I.type() commands in click() tool
721
718
  - click() commands array is for FALLBACK LOCATORS of the SAME element, NOT for clicking different elements in sequence. If you need to click two different elements, make two separate click() calls.
@@ -738,7 +735,8 @@ export class Tester extends TaskAgent implements Agent {
738
735
  - Check for error messages to understand if there are issues
739
736
  - Verify if data was correctly saved and changes are reflected on the page
740
737
  - By default, you receive accessibility tree data which shows interactive elements and page structure
741
- - Understand current context by following <page_html>, <page_aria>, and <page_ui_map>
738
+ - Full page HTML is never injected automatically. When ARIA is not enough, delegate to the tools that read it: verify() to assert, interact() to act
739
+ - Understand current context by following <page_aria> and <page_ui_map>
742
740
  - Before submitting form, check all inputs were filled in correctly using see() tool
743
741
  - When you interact with form with inputs, ensure that you click corresponding button to save its data
744
742
  - Follow <locator_priority> rules when selecting locators for all tools
@@ -790,7 +788,6 @@ export class Tester extends TaskAgent implements Agent {
790
788
 
791
789
  private buildScenarioBlock(task: Test, actionResult: ActionResult): string {
792
790
  const knowledge = this.getKnowledge(actionResult);
793
- const experience = this.getExperience(actionResult);
794
791
 
795
792
  return dedent`
796
793
  <task>
@@ -820,8 +817,6 @@ export class Tester extends TaskAgent implements Agent {
820
817
  ${this.buildAvailableFiles()}
821
818
 
822
819
  ${knowledge}
823
-
824
- ${experience}
825
820
  `;
826
821
  }
827
822
 
@@ -943,7 +938,7 @@ export class Tester extends TaskAgent implements Agent {
943
938
  };
944
939
 
945
940
  if (resetAction.lastError) {
946
- result.error = resetAction.lastError.toString();
941
+ result.error = compactErrorMessage(resetAction.lastError);
947
942
  }
948
943
 
949
944
  return result;
@@ -1160,3 +1155,7 @@ export class Tester extends TaskAgent implements Agent {
1160
1155
  interface TestSessionHandlers {
1161
1156
  offFailedRequest?: () => void;
1162
1157
  }
1158
+
1159
+ export interface TestOptions {
1160
+ startOnCurrentPage?: boolean;
1161
+ }
package/src/ai/tools.ts CHANGED
@@ -2,12 +2,13 @@ import { tool } from 'ai';
2
2
  import dedent from 'dedent';
3
3
  import { z } from 'zod';
4
4
  import { ActionResult, type PageDiff, type ToolResultMetadata } from '../action-result.ts';
5
- import type { ExperienceTracker } from '../experience-tracker.ts';
5
+ import { type ExperienceTracker, renderExperienceRecipes } from '../experience-tracker.ts';
6
6
  import { Stats } from '../stats.ts';
7
7
  import { type Task, TestResult } from '../test-plan.js';
8
8
  import { LARGE_ARIA_CHANGE_THRESHOLD } from '../utils/aria.ts';
9
9
  import { isFatalBrowserError } from '../utils/browser-errors.ts';
10
10
  import { createDebug, tag } from '../utils/logger.js';
11
+ import { compactErrorMessage } from '../utils/strings.ts';
11
12
  import { pause } from '../utils/loop.js';
12
13
  import { WebElement } from '../utils/web-element.ts';
13
14
  import type { ToolDeps } from './agent.ts';
@@ -34,10 +35,6 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
34
35
  description: dedent`
35
36
  Click an element by trying multiple CodeceptJS commands in order until one succeeds.
36
37
 
37
- Use this only for elements the page context gives you no ref for. When the element shows a ref such as [ref=e14],
38
- call clickRef with that ref instead — composing a locator for an element that already has a ref is wasted work,
39
- and a locator can match several elements where a ref cannot.
40
-
41
38
  Follow <locator_priority> from system prompt for locator selection.
42
39
 
43
40
  I.click(locator) - click element matching locator
@@ -98,7 +95,7 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
98
95
  const success = await action.attempt(command, explanation);
99
96
 
100
97
  const attempt: { command: string; success: boolean; error?: string } = { command, success };
101
- if (action.lastError) attempt.error = action.lastError.toString();
98
+ if (action.lastError) attempt.error = errorText(action.lastError);
102
99
  attempts.push(attempt);
103
100
 
104
101
  if (success) {
@@ -124,7 +121,7 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
124
121
 
125
122
  for (const retryCmd of retryCommands) {
126
123
  if (!(await action.attempt(retryCmd, explanation))) {
127
- attempts.push({ command: retryCmd, success: false, error: action.lastError?.toString() });
124
+ attempts.push({ command: retryCmd, success: false, error: errorText(action.lastError) });
128
125
  continue;
129
126
  }
130
127
  const toolResult = await ActionResult.fromState(stateManager.getCurrentState()!).toToolResult(previousState, retryCmd);
@@ -151,41 +148,6 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
151
148
  },
152
149
  }),
153
150
 
154
- clickRef: tool({
155
- description: dedent`
156
- Click an element by the ref the page context gave it, e.g. [ref=e14].
157
-
158
- Prefer this over click() whenever the element you want carries a ref. A ref names one exact element, so it
159
- cannot match several by mistake and never needs disambiguating — it is the fastest way to click.
160
- Only pass a ref that appears in the page context you were given. Never invent or guess one.
161
- If it reports the ref is gone, the page has been rebuilt: get fresh context and use the new ref.
162
- `,
163
- inputSchema: z.object({
164
- ref: z.string().describe('The ref exactly as it appears in the page context, e.g. "e14"'),
165
- element: z.string().describe('Role and name of the element you are clicking, for the record'),
166
- }),
167
- execute: async ({ ref, element }) => {
168
- const activeNote = task.startNote(`Click ${element}`);
169
- const previousState = ActionResult.fromState(stateManager.getCurrentState()!);
170
- const action = explorer.action();
171
- const named = await describeRef(explorer, ref);
172
- const run = `I.usePlaywrightTo(${JSON.stringify(`click ${element}`)}, async ({ page }) => page.locator(${JSON.stringify(`aria-ref=${ref}`)}).click())`;
173
-
174
- if (!(await action.attempt(run, `Click ${element}`))) {
175
- activeNote.commit(TestResult.FAILED);
176
- return failedToolResult('clickRef', `Ref ${ref} could not be clicked: ${errorText(action.lastError)}`, {
177
- suggestion: 'The ref may belong to an older version of the page. Get fresh context and use the ref it gives, or fall back to click() with a locator.',
178
- });
179
- }
180
-
181
- // a ref belongs to this session only, so the run is reported as the locator a later test can replay
182
- const code = named ? `I.click(${JSON.stringify(named)})` : run;
183
- const toolResult = await ActionResult.fromState(stateManager.getCurrentState()!).toToolResult(previousState, code);
184
- await commitNote(activeNote, TestResult.PASSED, toolResult, action);
185
- return successToolResult('clickRef', { ...toolResult, code }, action);
186
- },
187
- }),
188
-
189
151
  hover: tool({
190
152
  description: dedent`
191
153
  Move the mouse cursor to an element to reveal hover-only controls.
@@ -237,7 +199,7 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
237
199
  for (const command of commands) {
238
200
  const success = await action.attempt(command, explanation);
239
201
  const attempt: { command: string; success: boolean; error?: string } = { command, success };
240
- if (action.lastError) attempt.error = action.lastError.toString();
202
+ if (action.lastError) attempt.error = errorText(action.lastError);
241
203
  attempts.push(attempt);
242
204
 
243
205
  if (!success) continue;
@@ -320,7 +282,7 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
320
282
  );
321
283
  }
322
284
 
323
- const errorMsg = `pressKey fallback to type() failed: ${action.lastError?.toString()}`;
285
+ const errorMsg = `pressKey fallback to type() failed: ${errorText(action.lastError)}`;
324
286
  await commitNote(activeNote, TestResult.FAILED, toolResult, action);
325
287
  return failedToolResult('pressKey', errorMsg, {
326
288
  ...toolResult,
@@ -366,7 +328,7 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
366
328
  );
367
329
  }
368
330
 
369
- const errorMsg = `pressKey() failed: ${action.lastError?.toString()}`;
331
+ const errorMsg = `pressKey() failed: ${errorText(action.lastError)}`;
370
332
  await commitNote(activeNote, TestResult.FAILED, toolResult, action);
371
333
  return failedToolResult('pressKey', errorMsg, {
372
334
  ...toolResult,
@@ -387,8 +349,6 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
387
349
  Execute raw CodeceptJS code block with multiple commands.
388
350
  USE THIS TOOL for typing text into fields: I.fillField, I.type
389
351
 
390
- Do not put a click on a ref-bearing element in here — clickRef with its ref is cheaper and cannot mis-target.
391
-
392
352
  Follow <actions> from system prompt for available commands.
393
353
  Follow <locator_priority> from system prompt for locator selection.
394
354
 
@@ -448,7 +408,7 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
448
408
  const toolResult = await ActionResult.fromState(stateManager.getCurrentState()!).toToolResult(previousState, formLocator);
449
409
 
450
410
  if (action.lastError) {
451
- const message = action.lastError ? String(action.lastError) : 'Unknown error';
411
+ const message = errorText(action.lastError);
452
412
  await commitNote(activeNote, TestResult.FAILED, toolResult, action);
453
413
 
454
414
  let formSuggestion = 'Look into error message and identify which commands passed and which failed. Continue execution using step-by-step approach using click() and form() tools.';
@@ -502,6 +462,45 @@ export function createCodeceptJSTools({ explorer, stateManager, ai }: ToolDeps,
502
462
  };
503
463
  }
504
464
 
465
+ export function createRefTools({ explorer, stateManager }: ToolDeps, task: Task) {
466
+ return {
467
+ clickRef: tool({
468
+ description: dedent`
469
+ Click an element by the ref the page context gave it, e.g. [ref=e14].
470
+
471
+ Prefer this over click() whenever the element you want carries a ref. A ref names one exact element, so it
472
+ cannot match several by mistake and never needs disambiguating — it is the fastest way to click.
473
+ Only pass a ref that appears in the page context you were given. Never invent or guess one.
474
+ If it reports the ref is gone, the page has been rebuilt: get fresh context and use the new ref.
475
+ `,
476
+ inputSchema: z.object({
477
+ ref: z.string().describe('The ref exactly as it appears in the page context, e.g. "e14"'),
478
+ element: z.string().describe('Role and name of the element you are clicking, for the record'),
479
+ }),
480
+ execute: async ({ ref, element }) => {
481
+ const activeNote = task.startNote(`Click ${element}`);
482
+ const previousState = ActionResult.fromState(stateManager.getCurrentState()!);
483
+ const action = explorer.action();
484
+ const named = await describeRef(explorer, ref);
485
+ const run = `I.usePlaywrightTo(${JSON.stringify(`click ${element}`)}, async ({ page }) => page.locator(${JSON.stringify(`aria-ref=${ref}`)}).click())`;
486
+
487
+ if (!(await action.attempt(run, `Click ${element}`))) {
488
+ activeNote.commit(TestResult.FAILED);
489
+ return failedToolResult('clickRef', `Ref ${ref} could not be clicked: ${errorText(action.lastError)}`, {
490
+ suggestion: 'The ref may belong to an older version of the page. Get fresh context and use the ref it gives, or fall back to click() with a locator.',
491
+ });
492
+ }
493
+
494
+ // a ref belongs to this session only, so the run is reported as the locator a later test can replay
495
+ const code = named ? `I.click(${JSON.stringify(named)})` : run;
496
+ const toolResult = await ActionResult.fromState(stateManager.getCurrentState()!).toToolResult(previousState, code);
497
+ await commitNote(activeNote, TestResult.PASSED, toolResult, action);
498
+ return successToolResult('clickRef', { ...toolResult, code }, action);
499
+ },
500
+ }),
501
+ };
502
+ }
503
+
505
504
  export function createIframeTools({ explorer, stateManager }: ToolDeps) {
506
505
  return {
507
506
  exitIframe: tool({
@@ -627,7 +626,7 @@ export function createAgentTools({ explorer, stateManager, ai, researcher, navig
627
626
 
628
627
  DO NOT call this if:
629
628
  - You just performed an action (pageDiff already provided in response)
630
- - You already have recent <page_html>/<page_aria> in context
629
+ - You already have a recent <page_aria> snapshot in context
631
630
  - You're about to perform an action (you'll get pageDiff after)
632
631
 
633
632
  Call ONLY when:
@@ -782,12 +781,18 @@ export function createAgentTools({ explorer, stateManager, ai, researcher, navig
782
781
 
783
782
  interact: tool({
784
783
  description: dedent`
785
- Execute an action on the current page using AI-powered interaction.
786
- Use this to perform actions like clicking buttons, selecting options, filling forms, etc.
787
- The AI will generate and try multiple CodeceptJS code strategies to accomplish the instruction.
784
+ Delegate one step to the Navigator, which reads the full page HTML and tries multiple CodeceptJS strategies.
785
+ Slower than the direct action tools use it as a fallback, not as the default.
786
+
787
+ Use when:
788
+ - direct action tools failed and you have no better locator to try
789
+ - the step needs a sequence of actions to complete
790
+ - the element is not in the context you have
791
+
792
+ Describe the outcome to reach, not the locator to use.
788
793
  `,
789
794
  inputSchema: z.object({
790
- instruction: z.string().describe('What action to perform on the page, e.g. "select new suite option", "click the Submit button"'),
795
+ instruction: z.string().describe('The step to perform on the page, described by its intent'),
791
796
  }),
792
797
  execute: async ({ instruction }) => {
793
798
  try {
@@ -799,7 +804,8 @@ export function createAgentTools({ explorer, stateManager, ai, researcher, navig
799
804
 
800
805
  const previousState = ActionResult.fromState(currentState);
801
806
  const actionResult = ActionResult.fromState(currentState);
802
- const success = await navigator.resolveState(instruction, actionResult);
807
+ const experience = renderExperienceRecipes(explorer.activeTest?.getAppliedExperience(actionResult) ?? []);
808
+ const success = await navigator.resolveState(instruction, actionResult, { experience });
803
809
 
804
810
  const toolResult = await ActionResult.fromState(stateManager.getCurrentState()!).toToolResult(previousState, instruction);
805
811
 
@@ -810,7 +816,10 @@ export function createAgentTools({ explorer, stateManager, ai, researcher, navig
810
816
  });
811
817
  }
812
818
 
813
- return failedToolResult('interact', `Failed to execute: ${instruction}`, {
819
+ let reason = '';
820
+ if (navigator.lastFailureReason) reason = `: ${navigator.lastFailureReason}`;
821
+
822
+ return failedToolResult('interact', `Failed to execute: ${instruction}${reason}`, {
814
823
  ...toolResult,
815
824
  suggestion: 'The action could not be completed. Try a different instruction or use more specific element descriptions.',
816
825
  });
@@ -949,7 +958,7 @@ export function createAgentTools({ explorer, stateManager, ai, researcher, navig
949
958
  }
950
959
 
951
960
  const failData: Record<string, any> = { suggestion: 'Try reset() to return to the starting page.' };
952
- if (action.lastError) failData.error = action.lastError.toString();
961
+ if (action.lastError) failData.error = errorText(action.lastError);
953
962
  return failedToolResult('back', `Failed to navigate back to ${targetUrl}`, failData);
954
963
  },
955
964
  }),
@@ -1012,7 +1021,7 @@ export function createAgentTools({ explorer, stateManager, ai, researcher, navig
1012
1021
 
1013
1022
  if (result.totalFound === 0) {
1014
1023
  return failedToolResult('xpathCheck', `No elements matched XPath: ${xpath}`, {
1015
- suggestion: 'Try a broader expression. Examples: //*[contains(@class, "btn")], //button, //*[contains(text(), "keyword")]',
1024
+ suggestion: 'Do not guess another expression. Narrow down from what you know about the target: its role, its visible text, its nearest labelled ancestor. Add one constraint at a time.',
1016
1025
  });
1017
1026
  }
1018
1027
 
@@ -1109,7 +1118,12 @@ export function createAgentTools({ explorer, stateManager, ai, researcher, navig
1109
1118
  return tools;
1110
1119
  }
1111
1120
 
1112
- const PAGE_DIFF_SUGGESTION = 'Analyze page diff. htmlParts shows what changed and WHERE — each part has a container selector. Use the container as context when clicking elements from the diff.';
1121
+ const PAGE_DIFF_SUGGESTION =
1122
+ 'Analyze page diff. htmlParts shows what changed and WHERE — each part has a container selector. Use the container as context when clicking elements from the diff. messages holds text the app showed in response, requests the calls it made and consoleErrors what it logged.';
1123
+
1124
+ const FAILED_REQUEST_SUGGESTION = 'The server rejected a request made by this action (see requests). The UI accepted the interaction but the operation did not complete — read messages and consoleErrors for the reason and report it instead of repeating the action.';
1125
+
1126
+ const NAVIGATED_SUGGESTION = 'The action left the page. Elements are never compared across pages, so this diff carries the move itself and what the app announced in transit — an empty element diff does not mean nothing happened.';
1113
1127
 
1114
1128
  const ARIA_OUTPUT_CAP = 4000;
1115
1129
  const HTML_OUTPUT_CAP = 6000;
@@ -1151,7 +1165,7 @@ function transformContainsCommand(command: string): string {
1151
1165
  }
1152
1166
 
1153
1167
  function errorText(error: unknown): string {
1154
- if (error instanceof Error) return error.toString();
1168
+ if (error instanceof Error) return compactErrorMessage(error);
1155
1169
  return 'Unknown error occurred';
1156
1170
  }
1157
1171
 
@@ -1194,7 +1208,11 @@ export function successToolResult(action: string, data?: Record<string, any>, so
1194
1208
  const ariaChanges = data.pageDiff.ariaChanges || '';
1195
1209
  const urlChanged = data.pageDiff.urlChanged === true;
1196
1210
  const hasHtmlParts = Array.isArray(data.pageDiff.htmlParts) && data.pageDiff.htmlParts.length > 0;
1197
- if (isMajorPageChange(data.pageDiff)) {
1211
+ if (hasFailedRequest(data.pageDiff)) {
1212
+ suggestion = `${FAILED_REQUEST_SUGGESTION} ${suggestion}`;
1213
+ } else if (urlChanged) {
1214
+ suggestion = `${NAVIGATED_SUGGESTION} ${suggestion}`;
1215
+ } else if (isMajorPageChange(data.pageDiff)) {
1198
1216
  suggestion = `MAJOR PAGE CHANGE. Page entered a different mode. Check htmlParts and iframes in pageDiff before next action. ${suggestion}`;
1199
1217
  } else if (!urlChanged && !ariaChanges && !hasHtmlParts) {
1200
1218
  suggestion = 'Action ran without error but produced no observable change (URL, ARIA and HTML all unchanged). The locator likely matched a non-interactive ancestor or an element outside the intended control. Re-locate via xpathCheck() or verify with see() before treating this as success.';
@@ -1210,10 +1228,15 @@ export function isMajorPageChange(pageDiff: PageDiff): boolean {
1210
1228
  return pageDiff.urlChanged !== true && (pageDiff.ariaChangeCount ?? 0) >= LARGE_ARIA_CHANGE_THRESHOLD;
1211
1229
  }
1212
1230
 
1231
+ export function hasFailedRequest(pageDiff: PageDiff): boolean {
1232
+ return (pageDiff.requests ?? []).some((request) => request.status >= 400);
1233
+ }
1234
+
1213
1235
  function hasObservablePageChange(data?: Record<string, any>): boolean {
1214
1236
  if (!data?.pageDiff) return false;
1215
1237
  if (data.pageDiff.urlChanged === true) return true;
1216
1238
  if (data.pageDiff.ariaChanges) return true;
1239
+ if (data.pageDiff.messages?.length) return true;
1217
1240
  return Array.isArray(data.pageDiff.htmlParts) && data.pageDiff.htmlParts.length > 0;
1218
1241
  }
1219
1242
 
@@ -1275,6 +1298,10 @@ export function clickFailureSuggestion(attempts: Array<{ error?: string }>): str
1275
1298
  return 'Element is in the DOM but not visible. Reveal it first — scroll to it, expand its section, or open the panel holding it.';
1276
1299
  }
1277
1300
 
1301
+ if (errors.some((e) => e.includes('SyntaxError'))) {
1302
+ return 'The command string never parsed as JavaScript — quotes or brackets do not match. No element was looked up, so this tells you nothing about the page. Re-emit the same intent as valid CodeceptJS.';
1303
+ }
1304
+
1278
1305
  const notFound = errors.filter((e) => e.includes('was not found'));
1279
1306
 
1280
1307
  if (notFound.length && notFound.every((e) => e.includes('was not found inside element'))) {
@@ -1369,7 +1396,7 @@ function getNotFoundSuggestion(errorMessage: string): string | null {
1369
1396
  Element was not found. The locator does not exist on this page.
1370
1397
  1. Use see() to visually analyze what elements are actually on the page
1371
1398
  2. Use context() to get fresh HTML and ARIA snapshot
1372
- 3. Use ONLY locators from <page_aria> or <page_html>
1399
+ 3. Use ONLY locators from <page_aria> or from HTML returned by context()
1373
1400
  4. Prefer ARIA locators: { "role": "button", "text": "visible text" }
1374
1401
  `;
1375
1402
  }