testchimp-runner-core 0.0.33 → 0.0.34

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 (71) hide show
  1. package/dist/llm-facade.d.ts.map +1 -1
  2. package/dist/llm-facade.js +7 -7
  3. package/dist/llm-facade.js.map +1 -1
  4. package/dist/llm-provider.d.ts +9 -0
  5. package/dist/llm-provider.d.ts.map +1 -1
  6. package/dist/model-constants.d.ts +16 -5
  7. package/dist/model-constants.d.ts.map +1 -1
  8. package/dist/model-constants.js +17 -6
  9. package/dist/model-constants.js.map +1 -1
  10. package/dist/orchestrator/index.d.ts +1 -1
  11. package/dist/orchestrator/index.d.ts.map +1 -1
  12. package/dist/orchestrator/index.js +3 -2
  13. package/dist/orchestrator/index.js.map +1 -1
  14. package/dist/orchestrator/orchestrator-agent.d.ts +0 -8
  15. package/dist/orchestrator/orchestrator-agent.d.ts.map +1 -1
  16. package/dist/orchestrator/orchestrator-agent.js +206 -405
  17. package/dist/orchestrator/orchestrator-agent.js.map +1 -1
  18. package/dist/orchestrator/orchestrator-prompts.d.ts +20 -0
  19. package/dist/orchestrator/orchestrator-prompts.d.ts.map +1 -0
  20. package/dist/orchestrator/orchestrator-prompts.js +455 -0
  21. package/dist/orchestrator/orchestrator-prompts.js.map +1 -0
  22. package/dist/orchestrator/tools/index.d.ts +2 -1
  23. package/dist/orchestrator/tools/index.d.ts.map +1 -1
  24. package/dist/orchestrator/tools/index.js +4 -2
  25. package/dist/orchestrator/tools/index.js.map +1 -1
  26. package/dist/orchestrator/tools/verify-action-result.d.ts +17 -0
  27. package/dist/orchestrator/tools/verify-action-result.d.ts.map +1 -0
  28. package/dist/orchestrator/tools/verify-action-result.js +140 -0
  29. package/dist/orchestrator/tools/verify-action-result.js.map +1 -0
  30. package/dist/orchestrator/types.d.ts +26 -0
  31. package/dist/orchestrator/types.d.ts.map +1 -1
  32. package/dist/orchestrator/types.js.map +1 -1
  33. package/dist/prompts.d.ts.map +1 -1
  34. package/dist/prompts.js +40 -34
  35. package/dist/prompts.js.map +1 -1
  36. package/dist/scenario-worker-class.d.ts.map +1 -1
  37. package/dist/scenario-worker-class.js +4 -1
  38. package/dist/scenario-worker-class.js.map +1 -1
  39. package/dist/utils/coordinate-converter.d.ts +32 -0
  40. package/dist/utils/coordinate-converter.d.ts.map +1 -0
  41. package/dist/utils/coordinate-converter.js +130 -0
  42. package/dist/utils/coordinate-converter.js.map +1 -0
  43. package/package.json +1 -1
  44. package/plandocs/BEFORE_AFTER_VERIFICATION.md +148 -0
  45. package/plandocs/COORDINATE_MODE_DIAGNOSIS.md +144 -0
  46. package/plandocs/IMPLEMENTATION_STATUS.md +108 -0
  47. package/plandocs/PHASE_1_COMPLETE.md +165 -0
  48. package/plandocs/PHASE_1_SUMMARY.md +184 -0
  49. package/plandocs/PROMPT_OPTIMIZATION_ANALYSIS.md +120 -0
  50. package/plandocs/PROMPT_SANITY_CHECK.md +120 -0
  51. package/plandocs/SESSION_SUMMARY_v0.0.33.md +151 -0
  52. package/plandocs/TROUBLESHOOTING_SESSION.md +72 -0
  53. package/plandocs/VISUAL_AGENT_EVOLUTION_PLAN.md +396 -0
  54. package/plandocs/WHATS_NEW_v0.0.33.md +183 -0
  55. package/src/llm-facade.ts +8 -8
  56. package/src/llm-provider.ts +11 -1
  57. package/src/model-constants.ts +17 -5
  58. package/src/orchestrator/index.ts +3 -2
  59. package/src/orchestrator/orchestrator-agent.ts +249 -424
  60. package/src/orchestrator/orchestrator-agent.ts.backup +1386 -0
  61. package/src/orchestrator/orchestrator-prompts.ts +474 -0
  62. package/src/orchestrator/tools/index.ts +2 -1
  63. package/src/orchestrator/tools/verify-action-result.ts +159 -0
  64. package/src/orchestrator/types.ts +48 -0
  65. package/src/prompts.ts +40 -34
  66. package/src/scenario-worker-class.ts +7 -2
  67. package/src/utils/coordinate-converter.ts +162 -0
  68. package/testchimp-runner-core-0.0.33.tgz +0 -0
  69. /package/{CREDIT_CALLBACK_ARCHITECTURE.md → plandocs/CREDIT_CALLBACK_ARCHITECTURE.md} +0 -0
  70. /package/{INTEGRATION_COMPLETE.md → plandocs/INTEGRATION_COMPLETE.md} +0 -0
  71. /package/{VISION_DIAGNOSTICS_IMPROVEMENTS.md → plandocs/VISION_DIAGNOSTICS_IMPROVEMENTS.md} +0 -0
@@ -8,8 +8,10 @@ exports.OrchestratorAgent = void 0;
8
8
  const test_1 = require("@playwright/test");
9
9
  const progress_reporter_1 = require("../progress-reporter");
10
10
  const page_info_utils_1 = require("../utils/page-info-utils");
11
+ const coordinate_converter_1 = require("../utils/coordinate-converter");
11
12
  const model_constants_1 = require("../model-constants");
12
13
  const types_1 = require("./types");
14
+ const orchestrator_prompts_1 = require("./orchestrator-prompts");
13
15
  /**
14
16
  * Orchestrator Agent - manages step execution with tool use and memory
15
17
  */
@@ -34,13 +36,16 @@ class OrchestratorAgent {
34
36
  this.logger?.(`[Orchestrator] 🎯 Goal: ${stepDescription}`);
35
37
  let iteration = 0;
36
38
  let previousReflection = undefined;
39
+ let noteToSelf = memory.latestNote; // Start with note from previous step
37
40
  const commandsExecuted = [];
38
41
  let consecutiveFailures = 0; // Track consecutive iterations with failed commands
42
+ let coordinateAttempts = 0; // Track coordinate mode attempts (max 2)
39
43
  while (iteration < this.config.maxIterationsPerStep) {
40
44
  iteration++;
41
45
  this.logger?.(`\n[Orchestrator] === Iteration ${iteration}/${this.config.maxIterationsPerStep} ===`);
42
46
  // Build context for agent
43
- const context = await this.buildAgentContext(page, stepDescription, stepNumber, totalSteps, scenarioSteps, memory, previousReflection, consecutiveFailures);
47
+ const context = await this.buildAgentContext(page, stepDescription, stepNumber, totalSteps, scenarioSteps, memory, previousReflection, consecutiveFailures, noteToSelf // NEW: Pass note from previous iteration
48
+ );
44
49
  // Call agent to make decision
45
50
  const decision = await this.callAgent(context, jobId, stepNumber, iteration, consecutiveFailures);
46
51
  // Log agent's reasoning
@@ -49,6 +54,12 @@ class OrchestratorAgent {
49
54
  await this.reportStepProgress(jobId, stepNumber, stepDescription, decision, iteration);
50
55
  // Execute tools if requested (tools are READ-ONLY, they don't change state)
51
56
  let toolResults = {};
57
+ // ANTI-LOOP: Detect if agent is taking screenshots repeatedly without acting
58
+ const recentScreenshots = memory.history.slice(-3).filter(s => s.code.includes('take_screenshot') || s.action.includes('Screenshot'));
59
+ if (recentScreenshots.length >= 2 && iteration >= 3) {
60
+ this.logger?.(`[Orchestrator] ⚠️ WARNING: ${recentScreenshots.length} screenshots in last 3 iterations - agent may be looping`, 'warn');
61
+ this.logger?.(`[Orchestrator] 💭 System: Stop gathering info, START ACTING with available selectors`);
62
+ }
52
63
  if (decision.toolCalls && decision.toolCalls.length > 0) {
53
64
  toolResults = await this.executeTools(decision.toolCalls, page, memory, stepNumber);
54
65
  // If agent wants to wait for tool results before proceeding, call agent again
@@ -82,7 +93,7 @@ class OrchestratorAgent {
82
93
  iterationHadFailure = true;
83
94
  }
84
95
  }
85
- // Execute main commands (only if no blocker failure or continueOnFailure is true)
96
+ // Execute main commands (only if no blocker failure)
86
97
  if (decision.commands && decision.commands.length > 0 && !iterationHadFailure) {
87
98
  const executeResult = await this.executeCommandsSequentially(decision.commands, page, memory, stepNumber, iteration, jobId);
88
99
  commandsExecuted.push(...executeResult.executed);
@@ -96,8 +107,136 @@ class OrchestratorAgent {
96
107
  consecutiveFailures = 0; // Reset on success
97
108
  }
98
109
  }
110
+ // Handle coordinate-based actions (NEW - fallback when selectors fail)
111
+ if (decision.coordinateAction && !iterationHadFailure) {
112
+ coordinateAttempts++;
113
+ this.logger?.(`[Orchestrator] 🎯 Coordinate Action (attempt ${coordinateAttempts}/2): ${decision.coordinateAction.action} at (${decision.coordinateAction.xPercent}%, ${decision.coordinateAction.yPercent}%)`);
114
+ try {
115
+ // BEFORE screenshot for visual verification
116
+ const beforeScreenshot = await page.screenshot({ encoding: 'base64', fullPage: false, type: 'jpeg', quality: 60 });
117
+ const beforeDataUrl = `data:image/jpeg;base64,${beforeScreenshot}`;
118
+ // Generate Playwright commands from coordinate action
119
+ const coordCommands = await coordinate_converter_1.CoordinateConverter.generateCommands(decision.coordinateAction, page);
120
+ this.logger?.(`[Orchestrator] Generated commands:`);
121
+ coordCommands.forEach(cmd => this.logger?.(` ${cmd}`));
122
+ // Execute coordinate commands
123
+ const coordResult = await this.executeCommandsSequentially(coordCommands, page, memory, stepNumber, iteration, jobId);
124
+ commandsExecuted.push(...coordResult.executed);
125
+ if (!coordResult.allSucceeded) {
126
+ this.logger?.(`[Orchestrator] ❌ Coordinate action failed (Playwright error)`);
127
+ consecutiveFailures++;
128
+ iterationHadFailure = true;
129
+ // Give up after 2 coordinate attempts
130
+ if (coordinateAttempts >= 2) {
131
+ this.logger?.(`[Orchestrator] 🛑 Coordinate mode exhausted (2 attempts) - marking stuck`);
132
+ return {
133
+ success: false,
134
+ commands: commandsExecuted,
135
+ iterations: iteration,
136
+ terminationReason: 'agent_stuck',
137
+ memory,
138
+ error: 'Coordinate fallback failed after 2 attempts - unable to proceed'
139
+ };
140
+ }
141
+ }
142
+ else {
143
+ this.logger?.(`[Orchestrator] ✅ Coordinate action succeeded (no Playwright error)`);
144
+ // CRITICAL: Verify visually if goal was achieved (coordinates might have clicked wrong place)
145
+ // Wait for network idle (smarter than fixed timeout - waits as needed, max 10s)
146
+ try {
147
+ await page.waitForLoadState('networkidle', { timeout: 10000 });
148
+ }
149
+ catch (e) {
150
+ // Network idle timeout - page may still be loading, but proceed with verification
151
+ this.logger?.(`[Orchestrator] ⚠️ Network idle timeout after 10s, proceeding with verification`, 'warn');
152
+ }
153
+ const afterScreenshot = await page.screenshot({ encoding: 'base64', fullPage: false, type: 'jpeg', quality: 60 });
154
+ const afterDataUrl = `data:image/jpeg;base64,${afterScreenshot}`;
155
+ this.logger?.(`[Orchestrator] 📸 Verifying coordinate action visually...`);
156
+ const verificationRequest = {
157
+ model: 'gpt-5-mini',
158
+ systemPrompt: 'You are a visual verification expert for web automation. Compare before/after screenshots to determine if an action achieved its goal.',
159
+ userPrompt: `Goal: ${scenarioSteps[stepNumber - 1]}\n\nA coordinate-based action was just executed. Compare the BEFORE and AFTER screenshots.\n\nDid the action achieve the goal? Respond with JSON:\n{\n "verified": boolean,\n "reasoning": "What changed (or didn't change) between screenshots",\n "visibleChanges": ["List of UI changes observed"],\n "clickedWrongPlace": boolean\n}\n\nBe strict: Only return verified=true if you clearly see the expected change matching the goal.`,
160
+ images: [
161
+ { label: 'BEFORE', dataUrl: beforeDataUrl },
162
+ { label: 'AFTER', dataUrl: afterDataUrl }
163
+ ]
164
+ };
165
+ const verificationResponse = await this.llmFacade.llmProvider.callLLM(verificationRequest);
166
+ const jsonMatch = verificationResponse.answer.match(/\{[\s\S]*\}/);
167
+ if (jsonMatch) {
168
+ const verificationResult = JSON.parse(jsonMatch[0]);
169
+ const verified = verificationResult.verified === true;
170
+ const reasoning = verificationResult.reasoning || 'No reasoning provided';
171
+ const clickedWrongPlace = verificationResult.clickedWrongPlace === true;
172
+ this.logger?.(`[Orchestrator] 📊 Visual verification: ${verified ? '✅ VERIFIED' : '❌ NOT VERIFIED'}`);
173
+ this.logger?.(`[Orchestrator] 💭 Reasoning: ${reasoning}`);
174
+ if (verified) {
175
+ // Goal achieved! Can mark complete
176
+ consecutiveFailures = 0;
177
+ // Store note for context
178
+ noteToSelf = {
179
+ fromIteration: iteration,
180
+ content: `Coordinate action verified successful: ${reasoning}`
181
+ };
182
+ memory.latestNote = noteToSelf;
183
+ }
184
+ else {
185
+ // Goal NOT achieved despite no error
186
+ this.logger?.(`[Orchestrator] ⚠️ Coordinate click succeeded but goal NOT achieved`, 'warn');
187
+ consecutiveFailures++;
188
+ iterationHadFailure = true;
189
+ // Store diagnostic note for next attempt
190
+ const diagnostic = clickedWrongPlace
191
+ ? `Clicked wrong place. ${reasoning}. Try different coordinates.`
192
+ : `Action executed but goal not achieved. ${reasoning}. May need different approach.`;
193
+ noteToSelf = {
194
+ fromIteration: iteration,
195
+ content: diagnostic
196
+ };
197
+ memory.latestNote = noteToSelf;
198
+ // Give up after 2 coordinate attempts
199
+ if (coordinateAttempts >= 2) {
200
+ this.logger?.(`[Orchestrator] 🛑 Coordinate mode exhausted (2 attempts, none achieved goal) - marking stuck`);
201
+ return {
202
+ success: false,
203
+ commands: commandsExecuted,
204
+ iterations: iteration,
205
+ terminationReason: 'agent_stuck',
206
+ memory,
207
+ error: `Coordinate actions clicked but didn't achieve goal: ${reasoning}`
208
+ };
209
+ }
210
+ }
211
+ }
212
+ else {
213
+ this.logger?.(`[Orchestrator] ⚠️ Could not parse verification response - treating as unverified`, 'warn');
214
+ consecutiveFailures++;
215
+ iterationHadFailure = true;
216
+ }
217
+ }
218
+ }
219
+ catch (error) {
220
+ this.logger?.(`[Orchestrator] ❌ Coordinate action error: ${error.message}`, 'error');
221
+ consecutiveFailures++;
222
+ iterationHadFailure = true;
223
+ // Give up after 2 coordinate attempts
224
+ if (coordinateAttempts >= 2) {
225
+ this.logger?.(`[Orchestrator] 🛑 Coordinate mode exhausted (2 attempts) - marking stuck`);
226
+ return {
227
+ success: false,
228
+ commands: commandsExecuted,
229
+ iterations: iteration,
230
+ terminationReason: 'agent_stuck',
231
+ memory,
232
+ error: 'Coordinate fallback failed after 2 attempts - unable to proceed'
233
+ };
234
+ }
235
+ }
236
+ }
99
237
  // System-enforced stuck detection (agent might not detect it)
100
- if (consecutiveFailures >= 3) {
238
+ // Allow 5 failures: 3 selector attempts + 2 coordinate attempts
239
+ if (consecutiveFailures >= 5) {
101
240
  this.logger?.(`[Orchestrator] 🛑 SYSTEM: ${consecutiveFailures} consecutive failures detected - forcing stuck`, 'warn');
102
241
  return {
103
242
  success: false,
@@ -126,19 +265,37 @@ class OrchestratorAgent {
126
265
  }
127
266
  // Store self-reflection for next iteration
128
267
  previousReflection = decision.selfReflection;
268
+ // Store note to future self (NEW - tactical memory across iterations AND steps)
269
+ if (decision.noteToFutureSelf) {
270
+ noteToSelf = {
271
+ fromIteration: iteration,
272
+ content: decision.noteToFutureSelf
273
+ };
274
+ memory.latestNote = noteToSelf; // Persist in journey memory across steps
275
+ this.logger?.(`[Orchestrator] 📝 Note to self: ${decision.noteToFutureSelf}`);
276
+ }
129
277
  // Check termination
130
278
  if (decision.status !== 'continue') {
131
279
  this.logger?.(`[Orchestrator] 🎯 Status: ${decision.status}`);
132
280
  this.logger?.(`[Orchestrator] 💭 Reason: ${decision.statusReasoning}`);
133
- return {
134
- success: decision.status === 'complete',
135
- commands: commandsExecuted,
136
- iterations: iteration,
137
- terminationReason: decision.status === 'complete' ? 'complete' :
138
- decision.status === 'stuck' ? 'agent_stuck' :
139
- 'infeasible',
140
- memory
141
- };
281
+ // SAFETY CHECK: Don't allow "complete" if commands failed this iteration
282
+ if (decision.status === 'complete' && iterationHadFailure) {
283
+ this.logger?.(`[Orchestrator] ⚠️ OVERRIDE: Agent said "complete" but commands FAILED - forcing "continue"`, 'warn');
284
+ this.logger?.(`[Orchestrator] 💭 System: Commands must succeed before marking complete`);
285
+ // Don't return - continue to next iteration
286
+ }
287
+ else {
288
+ // Valid termination
289
+ return {
290
+ success: decision.status === 'complete',
291
+ commands: commandsExecuted,
292
+ iterations: iteration,
293
+ terminationReason: decision.status === 'complete' ? 'complete' :
294
+ decision.status === 'stuck' ? 'agent_stuck' :
295
+ 'infeasible',
296
+ memory
297
+ };
298
+ }
142
299
  }
143
300
  }
144
301
  // Hit iteration limit
@@ -155,7 +312,8 @@ class OrchestratorAgent {
155
312
  /**
156
313
  * Build context for agent
157
314
  */
158
- async buildAgentContext(page, currentStepGoal, stepNumber, totalSteps, scenarioSteps, memory, previousReflection, consecutiveFailures) {
315
+ async buildAgentContext(page, currentStepGoal, stepNumber, totalSteps, scenarioSteps, memory, previousReflection, consecutiveFailures, noteFromPreviousIteration // NEW
316
+ ) {
159
317
  // Get fresh DOM
160
318
  const currentPageInfo = await (0, page_info_utils_1.getEnhancedPageInfo)(page);
161
319
  const currentURL = page.url();
@@ -174,16 +332,30 @@ class OrchestratorAgent {
174
332
  recentSteps,
175
333
  experiences: memory.experiences,
176
334
  extractedData: memory.extractedData,
177
- previousIterationGuidance: previousReflection
335
+ previousIterationGuidance: previousReflection,
336
+ noteFromPreviousIteration // NEW: Pass tactical note from previous iteration
178
337
  };
179
338
  }
180
339
  /**
181
340
  * Call agent to make decision
182
341
  */
183
342
  async callAgent(context, jobId, stepNumber, iteration, consecutiveFailures) {
184
- // Build prompt
185
- const systemPrompt = this.buildSystemPrompt();
186
- const userPrompt = this.buildUserPrompt(context, consecutiveFailures);
343
+ // Detect if coordinate mode should be activated
344
+ // Phase 1: Only 2 tiers (selectors → coordinates), so activate after 3 failures
345
+ // Phase 2: Will have 3 tiers (selectors → index → coordinates), threshold will be 5
346
+ const useCoordinateMode = consecutiveFailures !== undefined && consecutiveFailures >= 3;
347
+ // Build appropriate system prompt based on mode
348
+ const toolDescriptions = this.toolRegistry.generateToolDescriptions();
349
+ const systemPrompt = useCoordinateMode
350
+ ? orchestrator_prompts_1.OrchestratorPrompts.buildCoordinateSystemPrompt()
351
+ : orchestrator_prompts_1.OrchestratorPrompts.buildSystemPrompt(toolDescriptions);
352
+ const userPrompt = orchestrator_prompts_1.OrchestratorPrompts.buildUserPrompt(context, consecutiveFailures);
353
+ // Log prompt lengths for monitoring
354
+ const systemLength = systemPrompt.length;
355
+ const userLength = userPrompt.length;
356
+ const totalLength = systemLength + userLength;
357
+ const estimatedTokens = Math.ceil(totalLength / 4); // Rough estimate: 4 chars per token
358
+ this.logger?.(`[Orchestrator] 📊 Prompt lengths: system=${systemLength} chars, user=${userLength} chars, total=${totalLength} chars (~${estimatedTokens} tokens)`, 'log');
187
359
  try {
188
360
  // Call LLM directly via provider
189
361
  const llmRequest = {
@@ -223,391 +395,6 @@ class OrchestratorAgent {
223
395
  };
224
396
  }
225
397
  }
226
- /**
227
- * Build system prompt with tool descriptions
228
- */
229
- buildSystemPrompt() {
230
- const toolDescriptions = this.toolRegistry.generateToolDescriptions();
231
- return `You are an intelligent test automation agent that executes web scenarios using Playwright.
232
-
233
- ${toolDescriptions}
234
-
235
- YOUR RESPONSE FORMAT (JSON):
236
- {
237
- "toolCalls": [{"name": "tool_name", "params": {...}}], // Optional: Tools to use
238
- "toolReasoning": "Why I need these tools", // If using tools
239
- "needsToolResults": true/false, // Wait for tool results before commands?
240
- "commands": ["await page.click(...)", ...], // Playwright commands to execute
241
- "commandReasoning": "Why these commands", // If executing commands
242
- "selfReflection": { // Guidance for your next iteration
243
- "guidanceForNext": "What to focus on next",
244
- "detectingLoop": false, // Set true if repeating same approach
245
- "loopReasoning": "Why I think I'm looping" // If detecting loop
246
- },
247
- "experiences": ["App-specific learning"], // APP-SPECIFIC patterns (see rules below)
248
- "status": "continue|complete|stuck|infeasible", // Your decision
249
- "statusReasoning": "Why this status",
250
- "reasoning": "Overall reasoning for this iteration",
251
- "blockerDetected": { // OPTIONAL: If something blocks the current goal
252
- "description": "What's blocking", // E.g., "Cookie consent modal"
253
- "clearingCommands": ["await page.click(...)"] // Commands to clear blocker FIRST
254
- },
255
- "stepReEvaluation": { // OPTIONAL: If questioning step order (last resort)
256
- "detected": true, // Set true if you think step order is wrong
257
- "issue": "prior_incomplete|already_done|wrong_order", // What's the issue?
258
- "explanation": "Why step order seems wrong" // Your reasoning
259
- }
260
- }
261
-
262
- STATUS DECISION RULES (CRITICAL!):
263
-
264
- - "complete": ALL commands succeeded AND step goal achieved
265
- ❌ NEVER mark complete if ANY command failed!
266
-
267
- - "continue": Command failed OR need more actions
268
- Use when: Need to retry with different selector, wait for something, or continue execution
269
-
270
- - "stuck": Tried 3+ iterations, all failed
271
-
272
- - "infeasible": Goal truly impossible (element doesn't exist anywhere)
273
-
274
- IF COMMAND FAILED → status must be "continue" (to retry) or "stuck" (if tried many times)
275
- IF COMMAND SUCCEEDED → status can be "complete" (if goal done) or "continue" (if more needed)
276
-
277
- STEP RE-EVALUATION (LAST RESORT - After 2+ Failures):
278
-
279
- When you've failed multiple times on current step, QUESTION YOUR ASSUMPTIONS:
280
-
281
- 1. **LOOK BACK**: Did prior steps really complete?
282
- - Check COMPLETED steps list vs current page state
283
- - Example: Says "Login complete" but you see login form → PRIOR STEP FAILED
284
- - If prior step incomplete: Execute commands to complete it, explain in reasoning
285
-
286
- 2. **LOOK FORWARD**: Is current step already done or no longer relevant?
287
- - Check if current step goal already achieved (element exists, state correct)
288
- - Example: Step says "Click Submit" but form already submitted → STEP ALREADY DONE
289
- - If already done: Mark "complete" and explain why
290
-
291
- 3. **LOOK AHEAD**: Is next step more feasible?
292
- - Sometimes UI flows differently than expected
293
- - Example: Current step "Click Edit" fails, but next step "Fill Name" elements are visible
294
- - If can do future step: Note in reasoning, but PREFER sticking to order
295
-
296
- STICK TO ORIGINAL PLAN unless clear evidence suggests otherwise.
297
- Only re-evaluate after repeated failures on same step.
298
-
299
- BLOCKER DETECTION (IMPORTANT!):
300
-
301
- Use "blockerDetected" when the CURRENT STEP GOAL is not immediately feasible because something unexpected is in the way:
302
-
303
- Examples of BLOCKERS:
304
- - Cookie consent modal appears before login
305
- - "What's New" tour overlay prevents clicking navigation
306
- - Email verification prompt blocks form submission
307
- - Session timeout modal requires re-login before continuing
308
-
309
- When you detect a blocker:
310
- 1. Set "blockerDetected.description" to describe what's blocking
311
- 2. Provide "clearingCommands" to dismiss/handle the blocker
312
- 3. Set your main "commands" to execute AFTER blocker is cleared
313
- 4. Agent will execute: clearingCommands FIRST, then your commands
314
-
315
- Example:
316
- {
317
- "blockerDetected": {
318
- "description": "Cookie consent modal blocking page interaction",
319
- "clearingCommands": ["await page.getByRole('button', {name: 'Accept'}).click()"]
320
- },
321
- "commands": ["await page.getByRole('textbox', {name: 'Email'}).fill('user@example.com')"],
322
- ...
323
- }
324
-
325
- DON'T use blockerDetected for:
326
- - Normal step execution (just use commands)
327
- - Wrong selectors (that's not a blocker, just fix the selector)
328
- - Missing elements (that's infeasible, not blocked)
329
-
330
- EXPERIENCES - APP-SPECIFIC PATTERNS ONLY:
331
-
332
- Guidelines:
333
- - Concise - combine related info into single learning
334
- - Focus on app quirks, not obvious practices
335
- - Max 1-2 experiences per iteration
336
- - Capture SEMANTIC SELECTOR patterns when discovered
337
-
338
- ✅ GOOD - App-specific patterns:
339
- - "Login form fields accessible via getByLabel: 'Email' and 'Password'"
340
- - "Submit buttons consistently use role=button with text matching action"
341
- - "Form uses custom dropdowns (role=combobox) instead of native selects"
342
- - "Navigation items accessible via getByRole('link') with visible text"
343
- - "Site uses data-testid attributes consistently (pattern: action-element-name)"
344
- - "Input fields have clear placeholders - prefer getByPlaceholder over IDs"
345
-
346
- ❌ BAD - Too specific or obvious:
347
- - Listing individual field selectors (combine them)
348
- - "Button exists with role=button" (obvious)
349
- - Generic automation advice
350
- - Noting auto-generated IDs like #«r3»-form-item (these are unreliable)
351
-
352
- COMBINE related learnings instead of listing each element separately.
353
- PRIORITIZE learning about semantic selector availability over CSS selectors.
354
-
355
- CRITICAL RULES FOR DECISION MAKING:
356
-
357
- 1. **BE FOCUSED AND CONCISE** (CRITICAL!):
358
- - Read the CURRENT STEP GOAL carefully - ONLY do what's explicitly asked for in THAT step
359
- - DON'T add extra actions, verifications, or defensive checks not mentioned in the step goal
360
- - If step says "Send a message" → ONLY send the message, DON'T verify it appeared
361
- - If step says "Click Submit" → ONLY click, DON'T wait or verify submission success
362
- - ONLY add expect() assertions if the step explicitly mentions "verify", "check", "ensure", or "confirm"
363
- - Keep commands minimal - no unnecessary preparatory or validation actions
364
-
365
- 2. **COMMAND EFFICIENCY**:
366
- - DON'T click on input field before filling it - just use .fill() directly
367
- - DON'T do preparatory actions unless necessary
368
- - Example: page.fill works without clicking the input first
369
-
370
- 2b. **VARIABLE SCOPE & AVAILABLE FUNCTIONS** (CRITICAL!):
371
- - Commands in SAME BATCH share scope - variables persist within iteration
372
- - To save data for later steps: Use extract_data tool, then access via extractedData in context
373
- - Within same batch: Variables work across commands
374
- - AVAILABLE IN CONTEXT: page (Playwright Page object) and expect (Playwright assertions)
375
- - You can use expect() directly - it is already imported and available
376
-
377
- 3. **WHEN COMMAND FAILS** (most important!):
378
- - DON'T repeat the same command/selector
379
- - DO analyze the error message
380
- - DO look at DOM snapshot for SEMANTIC selectors (getByRole, getByLabel, getByText)
381
- - AVOID falling back to auto-generated IDs with unicode characters (e.g., #«r3»-form-item)
382
- - DO take screenshot if DOM doesn't help
383
- - "Element is not a <select>" → It's a custom dropdown, use .click() then select from menu
384
- - "Timeout waiting for locator" → Try semantic selectors from ARIA tree instead of CSS IDs
385
-
386
- 4. **CHECK YOUR RECENT STEPS FOR PATTERNS**:
387
- - If you see same selector failed 2+ times → YOU ARE LOOPING!
388
- - Set detectingLoop: true and explain why
389
- - Take screenshot to see what's actually on the page
390
- - Use different SEMANTIC selector from DOM/ARIA tree (getByRole, getByLabel, getByText, data-testid)
391
- - AVOID repeating with similar auto-generated ID patterns (e.g., #«r3»-form-item → #«r4»-form-item)
392
-
393
- 5. **USE DOM SNAPSHOT** - ONLY USE WHAT'S ACTUALLY THERE (CRITICAL!):
394
- - You get INTERACTIVE ELEMENTS list showing: position, tag, id, text, SUGGESTED SELECTORS
395
- - ONLY use selectors from this list - DO NOT invent selectors with text/names not in the list!
396
- - ❌ WRONG: List shows button "Submit" but you use getByRole('button', {name: 'SomeOtherText'})
397
- - ✅ RIGHT: Use EXACT selector from the provided list
398
- - ✅ RIGHT: If list shows "#submit-btn" → use that
399
- - ✅ RIGHT: If list shows "getByRole('button', {name: 'X'})" → use exactly that
400
- - If element you need is NOT in list → take_screenshot to find it
401
- - ARIA tree shows roles/names that exist - inventing roles/names not in tree will fail!
402
-
403
- 5b. **SELECTOR PREFERENCE** (CRITICAL - Playwright Best Practices):
404
- ALWAYS prefer user-friendly, semantic selectors in this order:
405
-
406
- 🏆 BEST (use these first):
407
- 1. page.getByRole('role', {name: 'text'}) → ✅ Accessible, semantic, resilient
408
- 2. page.getByLabel('label text') → ✅ Great for form inputs
409
- 3. page.getByPlaceholder('placeholder') → ✅ Good for inputs without labels
410
- 4. page.getByText('visible text') → ✅ Clear and readable
411
- 5. page.getByTestId('test-id') → ✅ Stable if available
412
-
413
- ⚠️ AVOID (last resort only):
414
- - CSS selectors with auto-generated IDs: #r3-form-item, #«r3»-form-item
415
- - CSS selectors with unicode: #«r4»-form-item
416
- - Complex CSS paths: div.ant-form > div:nth-child(2)
417
-
418
- Examples:
419
- ❌ BAD: await page.fill('#«r3»-form-item', 'alice@example.com')
420
- ✅ GOOD: await page.getByLabel('Email').fill('alice@example.com')
421
- ✅ GOOD: await page.getByRole('textbox', {name: 'Email'}).fill('alice@example.com')
422
- ✅ GOOD: await page.getByPlaceholder('Enter your email').fill('alice@example.com')
423
-
424
- ❌ BAD: await page.click('#submit-btn-23847')
425
- ✅ GOOD: await page.getByRole('button', {name: 'Submit'}).click()
426
- ✅ GOOD: await page.getByText('Submit').click()
427
-
428
- WHY: Semantic selectors are more maintainable, self-documenting, and resilient to UI changes.
429
- Auto-generated IDs (especially with unicode like «r3») break when component instances change.
430
-
431
- 5c. **ASSERTIONS AND VERIFICATION** (CRITICAL - Use expect):
432
- Use expect() for verification ONLY when the step explicitly asks for verification.
433
-
434
- 🏆 WHEN TO USE expect():
435
- - Step says "Verify message appears" → await expect(locator).toBeVisible()
436
- - Step says "Check field is empty" → await expect(locator).toBeEmpty()
437
- - Step says "Confirm URL changed" → await expect(page).toHaveURL('...')
438
- - Step explicitly mentions: "verify", "check", "ensure", "confirm", "validate"
439
-
440
- ❌ WHEN NOT TO USE expect():
441
- - Step says "Send a message" → DON'T add expect() for message visibility
442
- - Step says "Click Submit" → DON'T add expect() for button state or result
443
- - Step says "Fill Email field" → DON'T add expect() to verify it's filled
444
- - Step says "Navigate to Dashboard" → DON'T add expect() for URL (unless step asks)
445
-
446
- 🏆 expect() syntax (when needed):
447
- - await expect(locator).toBeVisible()
448
- - await expect(locator).toHaveText('expected text')
449
- - await expect(locator).toHaveValue('expected value')
450
- - await expect(locator).toBeEmpty()
451
- - await expect(page).toHaveURL('expected-url')
452
-
453
- ❌ BAD - Manual checks:
454
- const value = await page.getByPlaceholder('Message...').inputValue();
455
- if (value !== '') throw new Error(\`Expected empty but found: '\${value}'\`);
456
-
457
- ✅ GOOD - Use expect (but ONLY if step asks to verify):
458
- await expect(page.getByPlaceholder('Message...')).toBeEmpty();
459
-
460
- WHY: expect() has built-in retries and better error messages.
461
- BUT: Only use it when verification is explicitly requested in the step goal.
462
-
463
- 6. **TOOLS ARE READ-ONLY (Information Gathering)**:
464
- AVAILABLE TOOLS (for information only):
465
- - take_screenshot: Get visual context when DOM isn't enough or stuck 2+ times
466
- * DEFAULT: Captures FULL PAGE (elements below fold included)
467
- * Set isFullPage=false ONLY if you need just viewport
468
- * Use for: Planning, finding hidden elements, verifying layout
469
- - recall_history: Remember earlier steps in journey
470
- - inspect_page: Force fresh DOM snapshot (rarely needed, already in context)
471
- - check_page_ready: Verify page loaded (use sparingly!)
472
- - extract_data: Save data from page to memory for later steps
473
-
474
- ALL STATE CHANGES USE PLAYWRIGHT COMMANDS:
475
- - Navigation: await page.goto('url')
476
- - Go back: await page.goBack()
477
- - Refresh: await page.reload()
478
- - Fill inputs: await page.fill() or page.getByRole().fill()
479
- - Click buttons: await page.click() or page.getByRole().click()
480
- - Wait: await page.waitForURL(), page.waitForLoadState()
481
-
482
- Tools gather info → Commands change state
483
-
484
- 7. **ERROR-SPECIFIC RESPONSES**:
485
- - "Timeout waiting for locator" → Selector doesn't exist, try different one from DOM
486
- - "Element is not a <select>" → It's a custom dropdown (button with role=combobox), use .click()
487
- - "Multiple elements" → Add more specific selector from DOM (use #id)
488
-
489
- 8. **WHEN TO RUN COMMANDS vs TOOLS**:
490
- - Confident about selectors from DOM → Run commands directly
491
- - Unsure or failed 2+ times → Take screenshot first
492
- - First iteration of a step → Usually can run commands from DOM`;
493
- }
494
- /**
495
- * Build user prompt with context
496
- */
497
- buildUserPrompt(context, consecutiveFailures) {
498
- const parts = [];
499
- parts.push('=== YOUR CURRENT CONTEXT ===\n');
500
- // System warnings for accumulated failures
501
- if (consecutiveFailures && consecutiveFailures >= 2) {
502
- parts.push(`⚠️⚠️⚠️ SYSTEM WARNING ⚠️⚠️⚠️`);
503
- parts.push(`You've failed ${consecutiveFailures} iterations in a row!`);
504
- parts.push(`Next failure will force STUCK. You MUST:`);
505
- parts.push(`1. Take screenshot if you haven't already`);
506
- parts.push(`2. Try completely different selector strategy`);
507
- parts.push(`3. QUESTION ASSUMPTIONS: Am I at the right step?`);
508
- parts.push(` - LOOK BACK: Did prior steps really complete? Check page state vs COMPLETED list`);
509
- parts.push(` - LOOK FORWARD: Is current step already done? Check if goal already achieved`);
510
- parts.push(`4. OR mark status="stuck" if truly can't proceed`);
511
- parts.push(`⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️\n`);
512
- }
513
- // Goals - make current step very prominent
514
- parts.push(`🎯 CURRENT STEP GOAL (${context.stepNumber}/${context.totalSteps}):`);
515
- parts.push(`${context.currentStepGoal}`);
516
- parts.push(`^^ DO ONLY WHAT THIS STEP ASKS - NO EXTRA ACTIONS OR VERIFICATIONS ^^`);
517
- parts.push(`^^ If step doesn't say "verify/check/confirm" → DON'T add expect() assertions ^^`);
518
- parts.push(`^^ Mark "complete" ONLY if commands succeeded ^^`);
519
- parts.push(``);
520
- parts.push(`OVERALL SCENARIO: ${context.overallGoal}\n`);
521
- if (context.completedSteps.length > 0) {
522
- parts.push(`COMPLETED: ${context.completedSteps.join(', ')}`);
523
- }
524
- if (context.remainingSteps.length > 0) {
525
- parts.push(`REMAINING: ${context.remainingSteps.join(', ')}\n`);
526
- }
527
- // Current page state
528
- parts.push(`\nCURRENT PAGE:`);
529
- parts.push(`URL: ${context.currentURL}`);
530
- parts.push(`Title: ${context.currentPageInfo.title}`);
531
- parts.push(`\nINTERACTIVE ELEMENTS (with positions and selectors):`);
532
- parts.push(context.currentPageInfo.formattedElements);
533
- parts.push(`\nARIA TREE (hierarchical structure):`);
534
- parts.push(JSON.stringify(context.currentPageInfo.ariaSnapshot, null, 2).substring(0, 5000));
535
- if (JSON.stringify(context.currentPageInfo.ariaSnapshot).length > 5000) {
536
- parts.push('... (truncated)');
537
- }
538
- parts.push('');
539
- // Recent steps
540
- if (context.recentSteps.length > 0) {
541
- parts.push(`\nRECENT STEPS (last ${context.recentSteps.length}):`);
542
- for (const step of context.recentSteps) {
543
- const status = step.result === 'success' ? '✓' : '✗';
544
- parts.push(` ${status} ${step.stepNumber}.${step.iteration || ''} ${step.action}`);
545
- parts.push(` Code: ${step.code}`);
546
- if (step.result === 'failure' && step.error) {
547
- parts.push(` ❌ ERROR: ${step.error}`);
548
- parts.push(` ^^ THIS SELECTOR FAILED - TRY DIFFERENT APPROACH ^^`);
549
- }
550
- else {
551
- parts.push(` Result: ${step.observation}`);
552
- }
553
- }
554
- parts.push('');
555
- // Detect repeated failures
556
- const recentFailures = context.recentSteps.filter(s => s.result === 'failure');
557
- if (recentFailures.length >= 2) {
558
- const sameSelector = recentFailures.slice(-2).every((s, i, arr) => i === 0 || s.code === arr[i - 1].code);
559
- if (sameSelector) {
560
- parts.push(`⚠️ WARNING: You've tried the same selector multiple times and it failed!`);
561
- parts.push(` Last failed selector: ${recentFailures[recentFailures.length - 1].code}`);
562
- parts.push(` YOU MUST try a completely different selector this time!\n`);
563
- }
564
- }
565
- }
566
- // Experiences
567
- if (context.experiences.length > 0) {
568
- parts.push(`\nLEARNINGS (${context.experiences.length}):`);
569
- for (const exp of context.experiences) {
570
- parts.push(` - ${exp}`);
571
- }
572
- parts.push('');
573
- }
574
- // Extracted data
575
- if (Object.keys(context.extractedData).length > 0) {
576
- parts.push(`\nEXTRACTED DATA:`);
577
- for (const [key, value] of Object.entries(context.extractedData)) {
578
- parts.push(` ${key}: ${value}`);
579
- }
580
- parts.push('');
581
- }
582
- // Previous reflection
583
- if (context.previousIterationGuidance) {
584
- parts.push(`\nYOUR PREVIOUS GUIDANCE TO YOURSELF:`);
585
- parts.push(`Focus: ${context.previousIterationGuidance.guidanceForNext}`);
586
- if (context.previousIterationGuidance.detectingLoop) {
587
- parts.push(`⚠ YOU DETECTED A LOOP: ${context.previousIterationGuidance.loopReasoning}`);
588
- }
589
- parts.push('');
590
- }
591
- // Tool results (if any)
592
- if (context.toolResults) {
593
- parts.push(`\n========== TOOL RESULTS ==========`);
594
- for (const [toolName, result] of Object.entries(context.toolResults)) {
595
- parts.push(`\n${toolName}: ${result.success ? '✓ SUCCESS' : '✗ FAILED'}`);
596
- if (result.learning) {
597
- parts.push(`\n📊 ANALYSIS FROM ${toolName.toUpperCase()}:`);
598
- parts.push(result.learning);
599
- parts.push(`^^ USE THIS INFORMATION TO DECIDE YOUR NEXT COMMANDS ^^`);
600
- }
601
- if (result.error) {
602
- parts.push(` Error: ${result.error}`);
603
- }
604
- }
605
- parts.push(`\n===================================\n`);
606
- }
607
- parts.push('=== WHAT DO YOU WANT TO DO? ===');
608
- parts.push('Respond with JSON following the format specified in the system prompt.');
609
- return parts.join('\n');
610
- }
611
398
  /**
612
399
  * Parse agent decision from LLM response
613
400
  */
@@ -616,18 +403,32 @@ CRITICAL RULES FOR DECISION MAKING:
616
403
  // Extract JSON from response
617
404
  const jsonMatch = response.match(/\{[\s\S]*\}/);
618
405
  if (!jsonMatch) {
406
+ this.logger?.(`[Orchestrator] ✗ No JSON found in LLM response`, 'error');
407
+ this.logger?.(`[Orchestrator] 📄 FULL LLM RESPONSE:\n${response}`, 'error');
619
408
  throw new Error('No JSON found in response');
620
409
  }
621
410
  const parsed = JSON.parse(jsonMatch[0]);
622
411
  // Validate required fields
623
- if (!parsed.status || !parsed.reasoning) {
624
- throw new Error('Missing required fields: status and reasoning');
412
+ // Accept either "reasoning" or "statusReasoning" (LLMs sometimes only provide one)
413
+ if (!parsed.status || (!parsed.reasoning && !parsed.statusReasoning)) {
414
+ this.logger?.(`[Orchestrator] ✗ Missing required fields in parsed JSON`, 'error');
415
+ this.logger?.(`[Orchestrator] 📄 FULL LLM RESPONSE:\n${response}`, 'error');
416
+ this.logger?.(`[Orchestrator] 📄 PARSED JSON:\n${JSON.stringify(parsed, null, 2)}`, 'error');
417
+ this.logger?.(`[Orchestrator] ❌ Has status: ${!!parsed.status}, Has reasoning: ${!!parsed.reasoning}, Has statusReasoning: ${!!parsed.statusReasoning}`, 'error');
418
+ throw new Error('Missing required fields: status and (reasoning or statusReasoning)');
419
+ }
420
+ // Normalize: if reasoning is missing but statusReasoning exists, use statusReasoning as reasoning
421
+ if (!parsed.reasoning && parsed.statusReasoning) {
422
+ parsed.reasoning = parsed.statusReasoning;
625
423
  }
626
424
  return parsed;
627
425
  }
628
426
  catch (error) {
629
427
  this.logger?.(`[Orchestrator] ✗ Failed to parse agent decision: ${error.message}`, 'error');
630
- this.logger?.(`[Orchestrator] Raw response: ${response.substring(0, 200)}...`, 'log');
428
+ // Only log full response if not already logged above
429
+ if (!error.message.includes('Missing required fields') && !error.message.includes('No JSON found')) {
430
+ this.logger?.(`[Orchestrator] 📄 FULL LLM RESPONSE:\n${response}`, 'error');
431
+ }
631
432
  // Return fallback
632
433
  return {
633
434
  status: 'stuck',