testchimp-runner-core 0.0.22 → 0.0.24

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 (151) hide show
  1. package/RELEASE_0.0.23.md +120 -0
  2. package/VISION_DIAGNOSTICS_IMPROVEMENTS.md +336 -0
  3. package/dist/credit-usage-service.d.ts +9 -0
  4. package/dist/credit-usage-service.d.ts.map +1 -1
  5. package/dist/credit-usage-service.js +20 -5
  6. package/dist/credit-usage-service.js.map +1 -1
  7. package/dist/env-loader.d.ts +5 -0
  8. package/dist/env-loader.d.ts.map +1 -1
  9. package/dist/env-loader.js +21 -0
  10. package/dist/env-loader.js.map +1 -1
  11. package/dist/execution-service.d.ts +7 -2
  12. package/dist/execution-service.d.ts.map +1 -1
  13. package/dist/execution-service.js +91 -36
  14. package/dist/execution-service.js.map +1 -1
  15. package/dist/index.d.ts +30 -2
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +91 -26
  18. package/dist/index.js.map +1 -1
  19. package/dist/llm-facade.d.ts +64 -8
  20. package/dist/llm-facade.d.ts.map +1 -1
  21. package/dist/llm-facade.js +361 -109
  22. package/dist/llm-facade.js.map +1 -1
  23. package/dist/llm-provider.d.ts +39 -0
  24. package/dist/llm-provider.d.ts.map +1 -0
  25. package/dist/llm-provider.js +7 -0
  26. package/dist/llm-provider.js.map +1 -0
  27. package/dist/model-constants.d.ts +21 -0
  28. package/dist/model-constants.d.ts.map +1 -0
  29. package/dist/model-constants.js +24 -0
  30. package/dist/model-constants.js.map +1 -0
  31. package/dist/orchestrator/index.d.ts +8 -0
  32. package/dist/orchestrator/index.d.ts.map +1 -0
  33. package/dist/orchestrator/index.js +23 -0
  34. package/dist/orchestrator/index.js.map +1 -0
  35. package/dist/orchestrator/orchestrator-agent.d.ts +66 -0
  36. package/dist/orchestrator/orchestrator-agent.d.ts.map +1 -0
  37. package/dist/orchestrator/orchestrator-agent.js +860 -0
  38. package/dist/orchestrator/orchestrator-agent.js.map +1 -0
  39. package/dist/orchestrator/tool-registry.d.ts +74 -0
  40. package/dist/orchestrator/tool-registry.d.ts.map +1 -0
  41. package/dist/orchestrator/tool-registry.js +131 -0
  42. package/dist/orchestrator/tool-registry.js.map +1 -0
  43. package/dist/orchestrator/tools/check-page-ready.d.ts +13 -0
  44. package/dist/orchestrator/tools/check-page-ready.d.ts.map +1 -0
  45. package/dist/orchestrator/tools/check-page-ready.js +72 -0
  46. package/dist/orchestrator/tools/check-page-ready.js.map +1 -0
  47. package/dist/orchestrator/tools/extract-data.d.ts +13 -0
  48. package/dist/orchestrator/tools/extract-data.d.ts.map +1 -0
  49. package/dist/orchestrator/tools/extract-data.js +84 -0
  50. package/dist/orchestrator/tools/extract-data.js.map +1 -0
  51. package/dist/orchestrator/tools/index.d.ts +10 -0
  52. package/dist/orchestrator/tools/index.d.ts.map +1 -0
  53. package/dist/orchestrator/tools/index.js +18 -0
  54. package/dist/orchestrator/tools/index.js.map +1 -0
  55. package/dist/orchestrator/tools/inspect-page.d.ts +13 -0
  56. package/dist/orchestrator/tools/inspect-page.d.ts.map +1 -0
  57. package/dist/orchestrator/tools/inspect-page.js +39 -0
  58. package/dist/orchestrator/tools/inspect-page.js.map +1 -0
  59. package/dist/orchestrator/tools/recall-history.d.ts +13 -0
  60. package/dist/orchestrator/tools/recall-history.d.ts.map +1 -0
  61. package/dist/orchestrator/tools/recall-history.js +64 -0
  62. package/dist/orchestrator/tools/recall-history.js.map +1 -0
  63. package/dist/orchestrator/tools/take-screenshot.d.ts +15 -0
  64. package/dist/orchestrator/tools/take-screenshot.d.ts.map +1 -0
  65. package/dist/orchestrator/tools/take-screenshot.js +112 -0
  66. package/dist/orchestrator/tools/take-screenshot.js.map +1 -0
  67. package/dist/orchestrator/types.d.ts +133 -0
  68. package/dist/orchestrator/types.d.ts.map +1 -0
  69. package/dist/orchestrator/types.js +28 -0
  70. package/dist/orchestrator/types.js.map +1 -0
  71. package/dist/playwright-mcp-service.d.ts +9 -0
  72. package/dist/playwright-mcp-service.d.ts.map +1 -1
  73. package/dist/playwright-mcp-service.js +20 -5
  74. package/dist/playwright-mcp-service.js.map +1 -1
  75. package/dist/progress-reporter.d.ts +97 -0
  76. package/dist/progress-reporter.d.ts.map +1 -0
  77. package/dist/progress-reporter.js +18 -0
  78. package/dist/progress-reporter.js.map +1 -0
  79. package/dist/prompts.d.ts +24 -0
  80. package/dist/prompts.d.ts.map +1 -1
  81. package/dist/prompts.js +593 -68
  82. package/dist/prompts.js.map +1 -1
  83. package/dist/providers/backend-proxy-llm-provider.d.ts +25 -0
  84. package/dist/providers/backend-proxy-llm-provider.d.ts.map +1 -0
  85. package/dist/providers/backend-proxy-llm-provider.js +76 -0
  86. package/dist/providers/backend-proxy-llm-provider.js.map +1 -0
  87. package/dist/providers/local-llm-provider.d.ts +21 -0
  88. package/dist/providers/local-llm-provider.d.ts.map +1 -0
  89. package/dist/providers/local-llm-provider.js +35 -0
  90. package/dist/providers/local-llm-provider.js.map +1 -0
  91. package/dist/scenario-service.d.ts +27 -1
  92. package/dist/scenario-service.d.ts.map +1 -1
  93. package/dist/scenario-service.js +48 -12
  94. package/dist/scenario-service.js.map +1 -1
  95. package/dist/scenario-worker-class.d.ts +39 -2
  96. package/dist/scenario-worker-class.d.ts.map +1 -1
  97. package/dist/scenario-worker-class.js +614 -86
  98. package/dist/scenario-worker-class.js.map +1 -1
  99. package/dist/script-utils.d.ts +2 -0
  100. package/dist/script-utils.d.ts.map +1 -1
  101. package/dist/script-utils.js +44 -4
  102. package/dist/script-utils.js.map +1 -1
  103. package/dist/types.d.ts +11 -0
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js.map +1 -1
  106. package/dist/utils/browser-utils.d.ts +20 -1
  107. package/dist/utils/browser-utils.d.ts.map +1 -1
  108. package/dist/utils/browser-utils.js +102 -51
  109. package/dist/utils/browser-utils.js.map +1 -1
  110. package/dist/utils/page-info-utils.d.ts +23 -4
  111. package/dist/utils/page-info-utils.d.ts.map +1 -1
  112. package/dist/utils/page-info-utils.js +174 -43
  113. package/dist/utils/page-info-utils.js.map +1 -1
  114. package/package.json +1 -2
  115. package/plandocs/HUMAN_LIKE_IMPROVEMENTS.md +642 -0
  116. package/plandocs/MULTI_AGENT_ARCHITECTURE_REVIEW.md +844 -0
  117. package/plandocs/ORCHESTRATOR_MVP_SUMMARY.md +539 -0
  118. package/plandocs/PHASE1_ABSTRACTION_COMPLETE.md +241 -0
  119. package/plandocs/PHASE1_FINAL_STATUS.md +210 -0
  120. package/plandocs/PLANNING_SESSION_SUMMARY.md +372 -0
  121. package/plandocs/SCRIPT_CLEANUP_FEATURE.md +201 -0
  122. package/plandocs/SCRIPT_GENERATION_ARCHITECTURE.md +364 -0
  123. package/plandocs/SELECTOR_IMPROVEMENTS.md +139 -0
  124. package/src/credit-usage-service.ts +23 -5
  125. package/src/env-loader.ts +22 -0
  126. package/src/execution-service.ts +152 -42
  127. package/src/index.ts +169 -26
  128. package/src/llm-facade.ts +500 -126
  129. package/src/llm-provider.ts +43 -0
  130. package/src/model-constants.ts +23 -0
  131. package/src/orchestrator/index.ts +33 -0
  132. package/src/orchestrator/orchestrator-agent.ts +1042 -0
  133. package/src/orchestrator/tool-registry.ts +182 -0
  134. package/src/orchestrator/tools/check-page-ready.ts +75 -0
  135. package/src/orchestrator/tools/extract-data.ts +92 -0
  136. package/src/orchestrator/tools/index.ts +11 -0
  137. package/src/orchestrator/tools/inspect-page.ts +42 -0
  138. package/src/orchestrator/tools/recall-history.ts +72 -0
  139. package/src/orchestrator/tools/take-screenshot.ts +128 -0
  140. package/src/orchestrator/types.ts +200 -0
  141. package/src/playwright-mcp-service.ts +23 -5
  142. package/src/progress-reporter.ts +109 -0
  143. package/src/prompts.ts +606 -69
  144. package/src/providers/backend-proxy-llm-provider.ts +91 -0
  145. package/src/providers/local-llm-provider.ts +38 -0
  146. package/src/scenario-service.ts +83 -13
  147. package/src/scenario-worker-class.ts +740 -72
  148. package/src/script-utils.ts +50 -5
  149. package/src/types.ts +13 -1
  150. package/src/utils/browser-utils.ts +123 -51
  151. package/src/utils/page-info-utils.ts +210 -53
@@ -0,0 +1,860 @@
1
+ "use strict";
2
+ /**
3
+ * Orchestrator Agent
4
+ * Single agent with tool-use capabilities that maintains journey memory and executes scenarios
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.OrchestratorAgent = void 0;
8
+ const test_1 = require("@playwright/test");
9
+ const progress_reporter_1 = require("../progress-reporter");
10
+ const page_info_utils_1 = require("../utils/page-info-utils");
11
+ const model_constants_1 = require("../model-constants");
12
+ const env_loader_1 = require("../env-loader");
13
+ const types_1 = require("./types");
14
+ /**
15
+ * Orchestrator Agent - manages step execution with tool use and memory
16
+ */
17
+ class OrchestratorAgent {
18
+ constructor(llmFacade, toolRegistry, config, progressReporter, logger, debugMode) {
19
+ this.debugMode = false;
20
+ this.llmFacade = llmFacade;
21
+ this.toolRegistry = toolRegistry;
22
+ this.config = { ...types_1.DEFAULT_AGENT_CONFIG, ...config };
23
+ this.progressReporter = progressReporter;
24
+ this.logger = logger;
25
+ this.debugMode = debugMode || false;
26
+ }
27
+ setDebugMode(enabled) {
28
+ this.debugMode = enabled;
29
+ }
30
+ /**
31
+ * Execute a single step of the scenario
32
+ */
33
+ async executeStep(page, stepDescription, stepNumber, totalSteps, scenarioSteps, memory, jobId) {
34
+ this.logger?.(`\n[Orchestrator] ========== STEP ${stepNumber}/${totalSteps} ==========`);
35
+ this.logger?.(`[Orchestrator] 🎯 Goal: ${stepDescription}`);
36
+ let iteration = 0;
37
+ let previousReflection = undefined;
38
+ const commandsExecuted = [];
39
+ let consecutiveFailures = 0; // Track consecutive iterations with failed commands
40
+ while (iteration < this.config.maxIterationsPerStep) {
41
+ iteration++;
42
+ this.logger?.(`\n[Orchestrator] === Iteration ${iteration}/${this.config.maxIterationsPerStep} ===`);
43
+ // Build context for agent
44
+ const context = await this.buildAgentContext(page, stepDescription, stepNumber, totalSteps, scenarioSteps, memory, previousReflection, consecutiveFailures);
45
+ // Call agent to make decision
46
+ const decision = await this.callAgent(context, jobId, stepNumber, iteration, consecutiveFailures);
47
+ // Log agent's reasoning
48
+ this.logAgentDecision(decision, iteration);
49
+ // Report progress
50
+ await this.reportStepProgress(jobId, stepNumber, stepDescription, decision, iteration);
51
+ // Execute tools if requested (tools are READ-ONLY, they don't change state)
52
+ let toolResults = {};
53
+ if (decision.toolCalls && decision.toolCalls.length > 0) {
54
+ toolResults = await this.executeTools(decision.toolCalls, page, memory, stepNumber);
55
+ // If agent wants to wait for tool results before proceeding, call agent again
56
+ if (decision.needsToolResults) {
57
+ const updatedContext = { ...context, toolResults };
58
+ const continuedDecision = await this.callAgent(updatedContext, jobId, stepNumber, iteration, consecutiveFailures);
59
+ // Merge continued decision
60
+ decision.commands = continuedDecision.commands || decision.commands;
61
+ decision.commandReasoning = continuedDecision.commandReasoning || decision.commandReasoning;
62
+ decision.status = continuedDecision.status;
63
+ decision.statusReasoning = continuedDecision.statusReasoning;
64
+ decision.reasoning = continuedDecision.reasoning;
65
+ }
66
+ }
67
+ // Execute commands sequentially
68
+ let iterationHadFailure = false;
69
+ // Handle blocker if detected (clear blocker FIRST, then proceed with main commands)
70
+ if (decision.blockerDetected && decision.blockerDetected.clearingCommands && decision.blockerDetected.clearingCommands.length > 0) {
71
+ this.logger?.(`[Orchestrator] 🚧 BLOCKER DETECTED: ${decision.blockerDetected.description}`);
72
+ this.logger?.(`[Orchestrator] 🧹 Clearing blocker with ${decision.blockerDetected.clearingCommands.length} command(s)...`);
73
+ const blockerResult = await this.executeCommandsSequentially(decision.blockerDetected.clearingCommands, page, memory, stepNumber, iteration, jobId);
74
+ // Add blocker commands with comment to output
75
+ if (blockerResult.executed.length > 0) {
76
+ commandsExecuted.push(`// Blocker: ${decision.blockerDetected.description}`);
77
+ commandsExecuted.push(...blockerResult.executed);
78
+ }
79
+ // If blocker clearing failed, track it
80
+ if (!blockerResult.allSucceeded) {
81
+ this.logger?.(`[Orchestrator] ❌ Failed to clear blocker - continuing anyway`);
82
+ consecutiveFailures++;
83
+ iterationHadFailure = true;
84
+ }
85
+ }
86
+ // Execute main commands (only if no blocker failure or continueOnFailure is true)
87
+ if (decision.commands && decision.commands.length > 0 && !iterationHadFailure) {
88
+ const executeResult = await this.executeCommandsSequentially(decision.commands, page, memory, stepNumber, iteration, jobId);
89
+ commandsExecuted.push(...executeResult.executed);
90
+ // Track failures
91
+ if (!executeResult.allSucceeded) {
92
+ this.logger?.(`[Orchestrator] ⚠ Command execution stopped at failure`);
93
+ consecutiveFailures++;
94
+ iterationHadFailure = true;
95
+ }
96
+ else {
97
+ consecutiveFailures = 0; // Reset on success
98
+ }
99
+ }
100
+ // System-enforced stuck detection (agent might not detect it)
101
+ if (consecutiveFailures >= 3) {
102
+ this.logger?.(`[Orchestrator] 🛑 SYSTEM: ${consecutiveFailures} consecutive failures detected - forcing stuck`, 'warn');
103
+ return {
104
+ success: false,
105
+ commands: commandsExecuted,
106
+ iterations: iteration,
107
+ terminationReason: 'agent_stuck',
108
+ memory,
109
+ error: `Failed ${consecutiveFailures} iterations in a row - unable to proceed`
110
+ };
111
+ }
112
+ // Update memory with experiences
113
+ if (decision.experiences && decision.experiences.length > 0) {
114
+ for (const exp of decision.experiences) {
115
+ // Deduplicate - don't add if very similar experience exists
116
+ const exists = memory.experiences.some(existing => existing.toLowerCase().includes(exp.toLowerCase()) ||
117
+ exp.toLowerCase().includes(existing.toLowerCase()));
118
+ if (!exists) {
119
+ memory.experiences.push(exp);
120
+ this.logger?.(`[Orchestrator] 📚 Experience: ${exp}`);
121
+ }
122
+ }
123
+ // Cap experiences
124
+ if (memory.experiences.length > this.config.maxExperiences) {
125
+ memory.experiences = memory.experiences.slice(-this.config.maxExperiences);
126
+ }
127
+ }
128
+ // Store self-reflection for next iteration
129
+ previousReflection = decision.selfReflection;
130
+ // Check termination
131
+ if (decision.status !== 'continue') {
132
+ this.logger?.(`[Orchestrator] 🎯 Status: ${decision.status}`);
133
+ this.logger?.(`[Orchestrator] 💭 Reason: ${decision.statusReasoning}`);
134
+ return {
135
+ success: decision.status === 'complete',
136
+ commands: commandsExecuted,
137
+ iterations: iteration,
138
+ terminationReason: decision.status === 'complete' ? 'complete' :
139
+ decision.status === 'stuck' ? 'agent_stuck' :
140
+ 'infeasible',
141
+ memory
142
+ };
143
+ }
144
+ }
145
+ // Hit iteration limit
146
+ this.logger?.(`[Orchestrator] ⚠ Maximum iterations reached (${this.config.maxIterationsPerStep})`);
147
+ return {
148
+ success: false,
149
+ commands: commandsExecuted,
150
+ iterations: iteration,
151
+ terminationReason: 'system_limit',
152
+ memory,
153
+ error: 'Maximum iterations reached'
154
+ };
155
+ }
156
+ /**
157
+ * Build context for agent
158
+ */
159
+ async buildAgentContext(page, currentStepGoal, stepNumber, totalSteps, scenarioSteps, memory, previousReflection, consecutiveFailures) {
160
+ // Get fresh DOM
161
+ const currentPageInfo = await (0, page_info_utils_1.getEnhancedPageInfo)(page);
162
+ const currentURL = page.url();
163
+ // Get recent steps
164
+ const recentSteps = memory.history.slice(-this.config.recentStepsCount);
165
+ // Build context
166
+ return {
167
+ overallGoal: scenarioSteps.join('\n'),
168
+ currentStepGoal,
169
+ stepNumber,
170
+ totalSteps,
171
+ completedSteps: scenarioSteps.slice(0, stepNumber - 1),
172
+ remainingSteps: scenarioSteps.slice(stepNumber),
173
+ currentPageInfo,
174
+ currentURL,
175
+ recentSteps,
176
+ experiences: memory.experiences,
177
+ extractedData: memory.extractedData,
178
+ previousIterationGuidance: previousReflection
179
+ };
180
+ }
181
+ /**
182
+ * Call agent to make decision
183
+ */
184
+ async callAgent(context, jobId, stepNumber, iteration, consecutiveFailures) {
185
+ // Build prompt
186
+ const systemPrompt = this.buildSystemPrompt();
187
+ const userPrompt = this.buildUserPrompt(context, consecutiveFailures);
188
+ try {
189
+ // Call LLM directly via provider
190
+ const llmRequest = {
191
+ model: model_constants_1.DEFAULT_MODEL,
192
+ systemPrompt,
193
+ userPrompt
194
+ };
195
+ const response = await this.llmFacade.llmProvider.callLLM(llmRequest);
196
+ // Report token usage
197
+ if (response.usage && this.progressReporter?.onTokensUsed) {
198
+ const tokenUsage = {
199
+ jobId,
200
+ stepNumber,
201
+ iteration,
202
+ inputTokens: response.usage.inputTokens,
203
+ outputTokens: response.usage.outputTokens,
204
+ includesImage: false,
205
+ model: model_constants_1.DEFAULT_MODEL,
206
+ timestamp: Date.now()
207
+ };
208
+ // Only log token usage in development mode (not in staging/prod)
209
+ if ((0, env_loader_1.isDevelopmentMode)()) {
210
+ this.logger?.(`[Orchestrator] 💰 Reporting token usage: ${tokenUsage.inputTokens} + ${tokenUsage.outputTokens}`, 'log');
211
+ }
212
+ await this.progressReporter.onTokensUsed(tokenUsage);
213
+ }
214
+ else if (!response.usage && (0, env_loader_1.isDevelopmentMode)()) {
215
+ // Only log missing usage data in development mode
216
+ this.logger?.(`[Orchestrator] ⚠ No usage data in LLM response`, 'warn');
217
+ }
218
+ // Parse response
219
+ return this.parseAgentDecision(response.answer);
220
+ }
221
+ catch (error) {
222
+ this.logger?.(`[Orchestrator] ✗ Agent call failed: ${error.message}`, 'error');
223
+ // Return fallback decision
224
+ return {
225
+ status: 'stuck',
226
+ statusReasoning: `Agent call failed: ${error.message}`,
227
+ reasoning: 'LLM call failed'
228
+ };
229
+ }
230
+ }
231
+ /**
232
+ * Build system prompt with tool descriptions
233
+ */
234
+ buildSystemPrompt() {
235
+ const toolDescriptions = this.toolRegistry.generateToolDescriptions();
236
+ return `You are an intelligent test automation agent that executes web scenarios using Playwright.
237
+
238
+ ${toolDescriptions}
239
+
240
+ YOUR RESPONSE FORMAT (JSON):
241
+ {
242
+ "toolCalls": [{"name": "tool_name", "params": {...}}], // Optional: Tools to use
243
+ "toolReasoning": "Why I need these tools", // If using tools
244
+ "needsToolResults": true/false, // Wait for tool results before commands?
245
+ "commands": ["await page.click(...)", ...], // Playwright commands to execute
246
+ "commandReasoning": "Why these commands", // If executing commands
247
+ "selfReflection": { // Guidance for your next iteration
248
+ "guidanceForNext": "What to focus on next",
249
+ "detectingLoop": false, // Set true if repeating same approach
250
+ "loopReasoning": "Why I think I'm looping" // If detecting loop
251
+ },
252
+ "experiences": ["App-specific learning"], // APP-SPECIFIC patterns (see rules below)
253
+ "status": "continue|complete|stuck|infeasible", // Your decision
254
+ "statusReasoning": "Why this status",
255
+ "reasoning": "Overall reasoning for this iteration",
256
+ "blockerDetected": { // OPTIONAL: If something blocks the current goal
257
+ "description": "What's blocking", // E.g., "Cookie consent modal"
258
+ "clearingCommands": ["await page.click(...)"] // Commands to clear blocker FIRST
259
+ },
260
+ "stepReEvaluation": { // OPTIONAL: If questioning step order (last resort)
261
+ "detected": true, // Set true if you think step order is wrong
262
+ "issue": "prior_incomplete|already_done|wrong_order", // What's the issue?
263
+ "explanation": "Why step order seems wrong" // Your reasoning
264
+ }
265
+ }
266
+
267
+ STATUS DECISION RULES (CRITICAL!):
268
+
269
+ - "complete": ALL commands succeeded AND step goal achieved
270
+ ❌ NEVER mark complete if ANY command failed!
271
+
272
+ - "continue": Command failed OR need more actions
273
+ Use when: Need to retry with different selector, wait for something, or continue execution
274
+
275
+ - "stuck": Tried 3+ iterations, all failed
276
+
277
+ - "infeasible": Goal truly impossible (element doesn't exist anywhere)
278
+
279
+ IF COMMAND FAILED → status must be "continue" (to retry) or "stuck" (if tried many times)
280
+ IF COMMAND SUCCEEDED → status can be "complete" (if goal done) or "continue" (if more needed)
281
+
282
+ STEP RE-EVALUATION (LAST RESORT - After 2+ Failures):
283
+
284
+ When you've failed multiple times on current step, QUESTION YOUR ASSUMPTIONS:
285
+
286
+ 1. **LOOK BACK**: Did prior steps really complete?
287
+ - Check COMPLETED steps list vs current page state
288
+ - Example: Says "Login complete" but you see login form → PRIOR STEP FAILED
289
+ - If prior step incomplete: Execute commands to complete it, explain in reasoning
290
+
291
+ 2. **LOOK FORWARD**: Is current step already done or no longer relevant?
292
+ - Check if current step goal already achieved (element exists, state correct)
293
+ - Example: Step says "Click Submit" but form already submitted → STEP ALREADY DONE
294
+ - If already done: Mark "complete" and explain why
295
+
296
+ 3. **LOOK AHEAD**: Is next step more feasible?
297
+ - Sometimes UI flows differently than expected
298
+ - Example: Current step "Click Edit" fails, but next step "Fill Name" elements are visible
299
+ - If can do future step: Note in reasoning, but PREFER sticking to order
300
+
301
+ STICK TO ORIGINAL PLAN unless clear evidence suggests otherwise.
302
+ Only re-evaluate after repeated failures on same step.
303
+
304
+ BLOCKER DETECTION (IMPORTANT!):
305
+
306
+ Use "blockerDetected" when the CURRENT STEP GOAL is not immediately feasible because something unexpected is in the way:
307
+
308
+ Examples of BLOCKERS:
309
+ - Cookie consent modal appears before login
310
+ - "What's New" tour overlay prevents clicking navigation
311
+ - Email verification prompt blocks form submission
312
+ - Session timeout modal requires re-login before continuing
313
+
314
+ When you detect a blocker:
315
+ 1. Set "blockerDetected.description" to describe what's blocking
316
+ 2. Provide "clearingCommands" to dismiss/handle the blocker
317
+ 3. Set your main "commands" to execute AFTER blocker is cleared
318
+ 4. Agent will execute: clearingCommands FIRST, then your commands
319
+
320
+ Example:
321
+ {
322
+ "blockerDetected": {
323
+ "description": "Cookie consent modal blocking page interaction",
324
+ "clearingCommands": ["await page.getByRole('button', {name: 'Accept'}).click()"]
325
+ },
326
+ "commands": ["await page.getByRole('textbox', {name: 'Email'}).fill('user@example.com')"],
327
+ ...
328
+ }
329
+
330
+ DON'T use blockerDetected for:
331
+ - Normal step execution (just use commands)
332
+ - Wrong selectors (that's not a blocker, just fix the selector)
333
+ - Missing elements (that's infeasible, not blocked)
334
+
335
+ EXPERIENCES - APP-SPECIFIC PATTERNS ONLY:
336
+
337
+ Guidelines:
338
+ - Concise - combine related info into single learning
339
+ - Focus on app quirks, not obvious practices
340
+ - Max 1-2 experiences per iteration
341
+ - Capture SEMANTIC SELECTOR patterns when discovered
342
+
343
+ ✅ GOOD - App-specific patterns:
344
+ - "Login form fields accessible via getByLabel: 'Email' and 'Password'"
345
+ - "Submit buttons consistently use role=button with text matching action"
346
+ - "Form uses custom dropdowns (role=combobox) instead of native selects"
347
+ - "Navigation items accessible via getByRole('link') with visible text"
348
+ - "Site uses data-testid attributes consistently (pattern: action-element-name)"
349
+ - "Input fields have clear placeholders - prefer getByPlaceholder over IDs"
350
+
351
+ ❌ BAD - Too specific or obvious:
352
+ - Listing individual field selectors (combine them)
353
+ - "Button exists with role=button" (obvious)
354
+ - Generic automation advice
355
+ - Noting auto-generated IDs like #«r3»-form-item (these are unreliable)
356
+
357
+ COMBINE related learnings instead of listing each element separately.
358
+ PRIORITIZE learning about semantic selector availability over CSS selectors.
359
+
360
+ CRITICAL RULES FOR DECISION MAKING:
361
+
362
+ 1. **BE FOCUSED AND CONCISE** (CRITICAL!):
363
+ - Read the CURRENT STEP GOAL carefully - ONLY do what's explicitly asked for in THAT step
364
+ - DON'T add extra actions, verifications, or defensive checks not mentioned in the step goal
365
+ - If step says "Send a message" → ONLY send the message, DON'T verify it appeared
366
+ - If step says "Click Submit" → ONLY click, DON'T wait or verify submission success
367
+ - ONLY add expect() assertions if the step explicitly mentions "verify", "check", "ensure", or "confirm"
368
+ - Keep commands minimal - no unnecessary preparatory or validation actions
369
+
370
+ 2. **COMMAND EFFICIENCY**:
371
+ - DON'T click on input field before filling it - just use .fill() directly
372
+ - DON'T do preparatory actions unless necessary
373
+ - Example: page.fill works without clicking the input first
374
+
375
+ 2b. **VARIABLE SCOPE & AVAILABLE FUNCTIONS** (CRITICAL!):
376
+ - Commands in SAME BATCH share scope - variables persist within iteration
377
+ - To save data for later steps: Use extract_data tool, then access via extractedData in context
378
+ - Within same batch: Variables work across commands
379
+ - AVAILABLE IN CONTEXT: page (Playwright Page object) and expect (Playwright assertions)
380
+ - You can use expect() directly - it is already imported and available
381
+
382
+ 3. **WHEN COMMAND FAILS** (most important!):
383
+ - DON'T repeat the same command/selector
384
+ - DO analyze the error message
385
+ - DO look at DOM snapshot for SEMANTIC selectors (getByRole, getByLabel, getByText)
386
+ - AVOID falling back to auto-generated IDs with unicode characters (e.g., #«r3»-form-item)
387
+ - DO take screenshot if DOM doesn't help
388
+ - "Element is not a <select>" → It's a custom dropdown, use .click() then select from menu
389
+ - "Timeout waiting for locator" → Try semantic selectors from ARIA tree instead of CSS IDs
390
+
391
+ 4. **CHECK YOUR RECENT STEPS FOR PATTERNS**:
392
+ - If you see same selector failed 2+ times → YOU ARE LOOPING!
393
+ - Set detectingLoop: true and explain why
394
+ - Take screenshot to see what's actually on the page
395
+ - Use different SEMANTIC selector from DOM/ARIA tree (getByRole, getByLabel, getByText, data-testid)
396
+ - AVOID repeating with similar auto-generated ID patterns (e.g., #«r3»-form-item → #«r4»-form-item)
397
+
398
+ 5. **USE DOM SNAPSHOT** - ONLY USE WHAT'S ACTUALLY THERE (CRITICAL!):
399
+ - You get INTERACTIVE ELEMENTS list showing: position, tag, id, text, SUGGESTED SELECTORS
400
+ - ONLY use selectors from this list - DO NOT invent selectors with text/names not in the list!
401
+ - ❌ WRONG: List shows button "Submit" but you use getByRole('button', {name: 'SomeOtherText'})
402
+ - ✅ RIGHT: Use EXACT selector from the provided list
403
+ - ✅ RIGHT: If list shows "#submit-btn" → use that
404
+ - ✅ RIGHT: If list shows "getByRole('button', {name: 'X'})" → use exactly that
405
+ - If element you need is NOT in list → take_screenshot to find it
406
+ - ARIA tree shows roles/names that exist - inventing roles/names not in tree will fail!
407
+
408
+ 5b. **SELECTOR PREFERENCE** (CRITICAL - Playwright Best Practices):
409
+ ALWAYS prefer user-friendly, semantic selectors in this order:
410
+
411
+ 🏆 BEST (use these first):
412
+ 1. page.getByRole('role', {name: 'text'}) → ✅ Accessible, semantic, resilient
413
+ 2. page.getByLabel('label text') → ✅ Great for form inputs
414
+ 3. page.getByPlaceholder('placeholder') → ✅ Good for inputs without labels
415
+ 4. page.getByText('visible text') → ✅ Clear and readable
416
+ 5. page.getByTestId('test-id') → ✅ Stable if available
417
+
418
+ ⚠️ AVOID (last resort only):
419
+ - CSS selectors with auto-generated IDs: #r3-form-item, #«r3»-form-item
420
+ - CSS selectors with unicode: #«r4»-form-item
421
+ - Complex CSS paths: div.ant-form > div:nth-child(2)
422
+
423
+ Examples:
424
+ ❌ BAD: await page.fill('#«r3»-form-item', 'alice@example.com')
425
+ ✅ GOOD: await page.getByLabel('Email').fill('alice@example.com')
426
+ ✅ GOOD: await page.getByRole('textbox', {name: 'Email'}).fill('alice@example.com')
427
+ ✅ GOOD: await page.getByPlaceholder('Enter your email').fill('alice@example.com')
428
+
429
+ ❌ BAD: await page.click('#submit-btn-23847')
430
+ ✅ GOOD: await page.getByRole('button', {name: 'Submit'}).click()
431
+ ✅ GOOD: await page.getByText('Submit').click()
432
+
433
+ WHY: Semantic selectors are more maintainable, self-documenting, and resilient to UI changes.
434
+ Auto-generated IDs (especially with unicode like «r3») break when component instances change.
435
+
436
+ 5c. **ASSERTIONS AND VERIFICATION** (CRITICAL - Use expect):
437
+ Use expect() for verification ONLY when the step explicitly asks for verification.
438
+
439
+ 🏆 WHEN TO USE expect():
440
+ - Step says "Verify message appears" → await expect(locator).toBeVisible()
441
+ - Step says "Check field is empty" → await expect(locator).toBeEmpty()
442
+ - Step says "Confirm URL changed" → await expect(page).toHaveURL('...')
443
+ - Step explicitly mentions: "verify", "check", "ensure", "confirm", "validate"
444
+
445
+ ❌ WHEN NOT TO USE expect():
446
+ - Step says "Send a message" → DON'T add expect() for message visibility
447
+ - Step says "Click Submit" → DON'T add expect() for button state or result
448
+ - Step says "Fill Email field" → DON'T add expect() to verify it's filled
449
+ - Step says "Navigate to Dashboard" → DON'T add expect() for URL (unless step asks)
450
+
451
+ 🏆 expect() syntax (when needed):
452
+ - await expect(locator).toBeVisible()
453
+ - await expect(locator).toHaveText('expected text')
454
+ - await expect(locator).toHaveValue('expected value')
455
+ - await expect(locator).toBeEmpty()
456
+ - await expect(page).toHaveURL('expected-url')
457
+
458
+ ❌ BAD - Manual checks:
459
+ const value = await page.getByPlaceholder('Message...').inputValue();
460
+ if (value !== '') throw new Error(\`Expected empty but found: '\${value}'\`);
461
+
462
+ ✅ GOOD - Use expect (but ONLY if step asks to verify):
463
+ await expect(page.getByPlaceholder('Message...')).toBeEmpty();
464
+
465
+ WHY: expect() has built-in retries and better error messages.
466
+ BUT: Only use it when verification is explicitly requested in the step goal.
467
+
468
+ 6. **TOOLS ARE READ-ONLY (Information Gathering)**:
469
+ AVAILABLE TOOLS (for information only):
470
+ - take_screenshot: Get visual context when DOM isn't enough or stuck 2+ times
471
+ * DEFAULT: Captures FULL PAGE (elements below fold included)
472
+ * Set isFullPage=false ONLY if you need just viewport
473
+ * Use for: Planning, finding hidden elements, verifying layout
474
+ - recall_history: Remember earlier steps in journey
475
+ - inspect_page: Force fresh DOM snapshot (rarely needed, already in context)
476
+ - check_page_ready: Verify page loaded (use sparingly!)
477
+ - extract_data: Save data from page to memory for later steps
478
+
479
+ ALL STATE CHANGES USE PLAYWRIGHT COMMANDS:
480
+ - Navigation: await page.goto('url')
481
+ - Go back: await page.goBack()
482
+ - Refresh: await page.reload()
483
+ - Fill inputs: await page.fill() or page.getByRole().fill()
484
+ - Click buttons: await page.click() or page.getByRole().click()
485
+ - Wait: await page.waitForURL(), page.waitForLoadState()
486
+
487
+ Tools gather info → Commands change state
488
+
489
+ 7. **ERROR-SPECIFIC RESPONSES**:
490
+ - "Timeout waiting for locator" → Selector doesn't exist, try different one from DOM
491
+ - "Element is not a <select>" → It's a custom dropdown (button with role=combobox), use .click()
492
+ - "Multiple elements" → Add more specific selector from DOM (use #id)
493
+
494
+ 8. **WHEN TO RUN COMMANDS vs TOOLS**:
495
+ - Confident about selectors from DOM → Run commands directly
496
+ - Unsure or failed 2+ times → Take screenshot first
497
+ - First iteration of a step → Usually can run commands from DOM`;
498
+ }
499
+ /**
500
+ * Build user prompt with context
501
+ */
502
+ buildUserPrompt(context, consecutiveFailures) {
503
+ const parts = [];
504
+ parts.push('=== YOUR CURRENT CONTEXT ===\n');
505
+ // System warnings for accumulated failures
506
+ if (consecutiveFailures && consecutiveFailures >= 2) {
507
+ parts.push(`⚠️⚠️⚠️ SYSTEM WARNING ⚠️⚠️⚠️`);
508
+ parts.push(`You've failed ${consecutiveFailures} iterations in a row!`);
509
+ parts.push(`Next failure will force STUCK. You MUST:`);
510
+ parts.push(`1. Take screenshot if you haven't already`);
511
+ parts.push(`2. Try completely different selector strategy`);
512
+ parts.push(`3. QUESTION ASSUMPTIONS: Am I at the right step?`);
513
+ parts.push(` - LOOK BACK: Did prior steps really complete? Check page state vs COMPLETED list`);
514
+ parts.push(` - LOOK FORWARD: Is current step already done? Check if goal already achieved`);
515
+ parts.push(`4. OR mark status="stuck" if truly can't proceed`);
516
+ parts.push(`⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️\n`);
517
+ }
518
+ // Goals - make current step very prominent
519
+ parts.push(`🎯 CURRENT STEP GOAL (${context.stepNumber}/${context.totalSteps}):`);
520
+ parts.push(`${context.currentStepGoal}`);
521
+ parts.push(`^^ DO ONLY WHAT THIS STEP ASKS - NO EXTRA ACTIONS OR VERIFICATIONS ^^`);
522
+ parts.push(`^^ If step doesn't say "verify/check/confirm" → DON'T add expect() assertions ^^`);
523
+ parts.push(`^^ Mark "complete" ONLY if commands succeeded ^^`);
524
+ parts.push(``);
525
+ parts.push(`OVERALL SCENARIO: ${context.overallGoal}\n`);
526
+ if (context.completedSteps.length > 0) {
527
+ parts.push(`COMPLETED: ${context.completedSteps.join(', ')}`);
528
+ }
529
+ if (context.remainingSteps.length > 0) {
530
+ parts.push(`REMAINING: ${context.remainingSteps.join(', ')}\n`);
531
+ }
532
+ // Current page state
533
+ parts.push(`\nCURRENT PAGE:`);
534
+ parts.push(`URL: ${context.currentURL}`);
535
+ parts.push(`Title: ${context.currentPageInfo.title}`);
536
+ parts.push(`\nINTERACTIVE ELEMENTS (with positions and selectors):`);
537
+ parts.push(context.currentPageInfo.formattedElements);
538
+ parts.push(`\nARIA TREE (hierarchical structure):`);
539
+ parts.push(JSON.stringify(context.currentPageInfo.ariaSnapshot, null, 2).substring(0, 5000));
540
+ if (JSON.stringify(context.currentPageInfo.ariaSnapshot).length > 5000) {
541
+ parts.push('... (truncated)');
542
+ }
543
+ parts.push('');
544
+ // Recent steps
545
+ if (context.recentSteps.length > 0) {
546
+ parts.push(`\nRECENT STEPS (last ${context.recentSteps.length}):`);
547
+ for (const step of context.recentSteps) {
548
+ const status = step.result === 'success' ? '✓' : '✗';
549
+ parts.push(` ${status} ${step.stepNumber}.${step.iteration || ''} ${step.action}`);
550
+ parts.push(` Code: ${step.code}`);
551
+ if (step.result === 'failure' && step.error) {
552
+ parts.push(` ❌ ERROR: ${step.error}`);
553
+ parts.push(` ^^ THIS SELECTOR FAILED - TRY DIFFERENT APPROACH ^^`);
554
+ }
555
+ else {
556
+ parts.push(` Result: ${step.observation}`);
557
+ }
558
+ }
559
+ parts.push('');
560
+ // Detect repeated failures
561
+ const recentFailures = context.recentSteps.filter(s => s.result === 'failure');
562
+ if (recentFailures.length >= 2) {
563
+ const sameSelector = recentFailures.slice(-2).every((s, i, arr) => i === 0 || s.code === arr[i - 1].code);
564
+ if (sameSelector) {
565
+ parts.push(`⚠️ WARNING: You've tried the same selector multiple times and it failed!`);
566
+ parts.push(` Last failed selector: ${recentFailures[recentFailures.length - 1].code}`);
567
+ parts.push(` YOU MUST try a completely different selector this time!\n`);
568
+ }
569
+ }
570
+ }
571
+ // Experiences
572
+ if (context.experiences.length > 0) {
573
+ parts.push(`\nLEARNINGS (${context.experiences.length}):`);
574
+ for (const exp of context.experiences) {
575
+ parts.push(` - ${exp}`);
576
+ }
577
+ parts.push('');
578
+ }
579
+ // Extracted data
580
+ if (Object.keys(context.extractedData).length > 0) {
581
+ parts.push(`\nEXTRACTED DATA:`);
582
+ for (const [key, value] of Object.entries(context.extractedData)) {
583
+ parts.push(` ${key}: ${value}`);
584
+ }
585
+ parts.push('');
586
+ }
587
+ // Previous reflection
588
+ if (context.previousIterationGuidance) {
589
+ parts.push(`\nYOUR PREVIOUS GUIDANCE TO YOURSELF:`);
590
+ parts.push(`Focus: ${context.previousIterationGuidance.guidanceForNext}`);
591
+ if (context.previousIterationGuidance.detectingLoop) {
592
+ parts.push(`⚠ YOU DETECTED A LOOP: ${context.previousIterationGuidance.loopReasoning}`);
593
+ }
594
+ parts.push('');
595
+ }
596
+ // Tool results (if any)
597
+ if (context.toolResults) {
598
+ parts.push(`\n========== TOOL RESULTS ==========`);
599
+ for (const [toolName, result] of Object.entries(context.toolResults)) {
600
+ parts.push(`\n${toolName}: ${result.success ? '✓ SUCCESS' : '✗ FAILED'}`);
601
+ if (result.learning) {
602
+ parts.push(`\n📊 ANALYSIS FROM ${toolName.toUpperCase()}:`);
603
+ parts.push(result.learning);
604
+ parts.push(`^^ USE THIS INFORMATION TO DECIDE YOUR NEXT COMMANDS ^^`);
605
+ }
606
+ if (result.error) {
607
+ parts.push(` Error: ${result.error}`);
608
+ }
609
+ }
610
+ parts.push(`\n===================================\n`);
611
+ }
612
+ parts.push('=== WHAT DO YOU WANT TO DO? ===');
613
+ parts.push('Respond with JSON following the format specified in the system prompt.');
614
+ return parts.join('\n');
615
+ }
616
+ /**
617
+ * Parse agent decision from LLM response
618
+ */
619
+ parseAgentDecision(response) {
620
+ try {
621
+ // Extract JSON from response
622
+ const jsonMatch = response.match(/\{[\s\S]*\}/);
623
+ if (!jsonMatch) {
624
+ throw new Error('No JSON found in response');
625
+ }
626
+ const parsed = JSON.parse(jsonMatch[0]);
627
+ // Validate required fields
628
+ if (!parsed.status || !parsed.reasoning) {
629
+ throw new Error('Missing required fields: status and reasoning');
630
+ }
631
+ return parsed;
632
+ }
633
+ catch (error) {
634
+ this.logger?.(`[Orchestrator] ✗ Failed to parse agent decision: ${error.message}`, 'error');
635
+ this.logger?.(`[Orchestrator] Raw response: ${response.substring(0, 200)}...`, 'log');
636
+ // Return fallback
637
+ return {
638
+ status: 'stuck',
639
+ statusReasoning: 'Failed to parse agent response',
640
+ reasoning: `Parse error: ${error.message}`
641
+ };
642
+ }
643
+ }
644
+ /**
645
+ * Execute tools
646
+ */
647
+ async executeTools(toolCalls, page, memory, stepNumber) {
648
+ this.logger?.(`[Orchestrator] 🔧 Executing ${toolCalls.length} tool(s)`);
649
+ const results = {};
650
+ const toolContext = {
651
+ page,
652
+ memory,
653
+ stepNumber,
654
+ logger: this.logger
655
+ };
656
+ for (const toolCall of toolCalls.slice(0, this.config.maxToolCallsPerIteration)) {
657
+ this.logger?.(`[Orchestrator] ▶ ${toolCall.name}(${JSON.stringify(toolCall.params).substring(0, 50)}...)`);
658
+ const result = await this.toolRegistry.execute(toolCall, toolContext);
659
+ results[toolCall.name] = result;
660
+ if (result.success) {
661
+ this.logger?.(`[Orchestrator] ✓ ${toolCall.name} succeeded`);
662
+ }
663
+ else {
664
+ this.logger?.(`[Orchestrator] ✗ ${toolCall.name} failed: ${result.error}`, 'error');
665
+ }
666
+ }
667
+ return results;
668
+ }
669
+ /**
670
+ * Execute commands sequentially with SHARED context (variables persist across commands)
671
+ */
672
+ async executeCommandsSequentially(commands, page, memory, stepNumber, iteration, jobId) {
673
+ this.logger?.(`[Orchestrator] 📝 Executing ${commands.length} command(s) in shared context`);
674
+ const executed = [];
675
+ const limitedCommands = commands.slice(0, this.config.maxCommandsPerIteration);
676
+ // Build execution with shared context (all commands share scope - variables persist)
677
+ const commandsWithTracking = limitedCommands.map((cmd, i) => {
678
+ return `
679
+ // Command ${i + 1}/${limitedCommands.length}
680
+ try {
681
+ ${cmd}
682
+ __results.push({ index: ${i}, success: true });
683
+ } catch (error) {
684
+ __results.push({ index: ${i}, success: false, error: error.message });
685
+ throw error; // Stop on first failure
686
+ }`;
687
+ }).join('\n');
688
+ const wrappedCode = `
689
+ const __results = [];
690
+ ${commandsWithTracking}
691
+ return __results;
692
+ `;
693
+ try {
694
+ // Execute in shared context - variables declared here persist for entire scenario
695
+ // Pass both page and expect to make Playwright assertions available
696
+ const func = new Function('page', 'expect', 'return (async () => { ' + wrappedCode + ' })()');
697
+ const results = await func(page, test_1.expect);
698
+ // Record results for each command
699
+ for (let i = 0; i < limitedCommands.length; i++) {
700
+ const cmd = limitedCommands[i];
701
+ const result = results[i];
702
+ if (result && result.success) {
703
+ this.logger?.(`[Orchestrator] ✓ [${i + 1}/${limitedCommands.length}] Success`);
704
+ // Record in history
705
+ memory.history.push({
706
+ stepNumber,
707
+ iteration,
708
+ action: `Command ${i + 1}/${limitedCommands.length}`,
709
+ code: cmd,
710
+ result: 'success',
711
+ observation: 'Executed successfully',
712
+ url: page.url(),
713
+ timestamp: Date.now()
714
+ });
715
+ executed.push(cmd);
716
+ }
717
+ }
718
+ // Cap history
719
+ if (memory.history.length > this.config.maxHistorySize) {
720
+ memory.history = memory.history.slice(-this.config.maxHistorySize);
721
+ }
722
+ return { executed, allSucceeded: true };
723
+ }
724
+ catch (error) {
725
+ // One of the commands failed - find which one
726
+ const errorMessage = error.message || String(error);
727
+ // Capture page state for debug logging
728
+ let pageStateDebug = '';
729
+ if (this.debugMode) {
730
+ try {
731
+ const pageInfo = await (0, page_info_utils_1.getEnhancedPageInfo)(page);
732
+ pageStateDebug = `
733
+ === DEBUG: PAGE STATE AT FAILURE ===
734
+ URL: ${page.url()}
735
+ Title: ${pageInfo.title}
736
+
737
+ INTERACTIVE ELEMENTS:
738
+ ${pageInfo.formattedElements}
739
+
740
+ ARIA SNAPSHOT:
741
+ ${JSON.stringify(pageInfo.ariaSnapshot, null, 2)}
742
+
743
+ ====================================`;
744
+ }
745
+ catch (debugError) {
746
+ pageStateDebug = `Failed to capture page state: ${debugError.message}`;
747
+ }
748
+ }
749
+ // Record all that succeeded, then the failure
750
+ for (let i = 0; i < limitedCommands.length; i++) {
751
+ const cmd = limitedCommands[i];
752
+ // This is a failed command (error happened here or earlier)
753
+ if (executed.length <= i) {
754
+ this.logger?.(`[Orchestrator] ✗ [${i + 1}/${limitedCommands.length}] Failed: ${errorMessage}`, 'error');
755
+ // Log detailed debug info
756
+ if (this.debugMode && pageStateDebug) {
757
+ this.logger?.(pageStateDebug, 'debug');
758
+ }
759
+ memory.history.push({
760
+ stepNumber,
761
+ iteration,
762
+ action: `Command ${i + 1}/${limitedCommands.length} - FAILED`,
763
+ code: cmd,
764
+ result: 'failure',
765
+ observation: `Failed with error: ${errorMessage}. This selector likely doesn't exist or is incorrect.`,
766
+ error: errorMessage,
767
+ url: page.url(),
768
+ timestamp: Date.now()
769
+ });
770
+ if (i < limitedCommands.length - 1) {
771
+ this.logger?.(`[Orchestrator] ⚠ Skipping remaining ${limitedCommands.length - i - 1} command(s)`, 'warn');
772
+ }
773
+ break;
774
+ }
775
+ }
776
+ return { executed, allSucceeded: false };
777
+ }
778
+ }
779
+ /**
780
+ * Execute a single command
781
+ */
782
+ async executeCommand(cmd, page) {
783
+ // Wrap in async function and execute
784
+ const wrapped = `(async () => { ${cmd} })()`;
785
+ try {
786
+ await eval(wrapped);
787
+ }
788
+ catch (error) {
789
+ // If eval fails, try direct execution with page context
790
+ // Pass both page and expect to make Playwright assertions available
791
+ const func = new Function('page', 'expect', `return (async () => { ${cmd} })()`);
792
+ await func(page, test_1.expect);
793
+ }
794
+ }
795
+ /**
796
+ * Log agent decision
797
+ */
798
+ logAgentDecision(decision, iteration) {
799
+ this.logger?.(`[Orchestrator] 💭 REASONING: ${decision.reasoning}`);
800
+ if (decision.selfReflection) {
801
+ this.logger?.(`[Orchestrator] 🧠 SELF-REFLECTION:`);
802
+ this.logger?.(`[Orchestrator] Next: ${decision.selfReflection.guidanceForNext}`);
803
+ if (decision.selfReflection.detectingLoop) {
804
+ this.logger?.(`[Orchestrator] 🔄 LOOP DETECTED: ${decision.selfReflection.loopReasoning}`, 'warn');
805
+ }
806
+ }
807
+ if (decision.toolCalls && decision.toolCalls.length > 0) {
808
+ this.logger?.(`[Orchestrator] 🔧 TOOLS: ${decision.toolCalls.map(t => t.name).join(', ')}`);
809
+ if (decision.toolReasoning) {
810
+ this.logger?.(`[Orchestrator] 📋 Why: ${decision.toolReasoning}`);
811
+ }
812
+ }
813
+ if (decision.blockerDetected) {
814
+ this.logger?.(`[Orchestrator] 🚧 BLOCKER: ${decision.blockerDetected.description}`, 'warn');
815
+ this.logger?.(`[Orchestrator] 🧹 Clearing with ${decision.blockerDetected.clearingCommands.length} command(s)`);
816
+ }
817
+ if (decision.stepReEvaluation?.detected) {
818
+ this.logger?.(`[Orchestrator] 🔍 STEP RE-EVALUATION: ${decision.stepReEvaluation.issue}`, 'warn');
819
+ this.logger?.(`[Orchestrator] 📝 Explanation: ${decision.stepReEvaluation.explanation}`);
820
+ }
821
+ if (decision.commands && decision.commands.length > 0) {
822
+ this.logger?.(`[Orchestrator] 📝 COMMANDS (${decision.commands.length}):`);
823
+ decision.commands.slice(0, 3).forEach((cmd, i) => {
824
+ this.logger?.(`[Orchestrator] ${i + 1}. ${cmd.substring(0, 80)}...`);
825
+ });
826
+ if (decision.commands.length > 3) {
827
+ this.logger?.(`[Orchestrator] ... and ${decision.commands.length - 3} more`);
828
+ }
829
+ if (decision.commandReasoning) {
830
+ this.logger?.(`[Orchestrator] 💡 Why: ${decision.commandReasoning}`);
831
+ }
832
+ }
833
+ // Experiences will be logged when added to memory, no need to log here
834
+ }
835
+ /**
836
+ * Report step progress
837
+ */
838
+ async reportStepProgress(jobId, stepNumber, description, decision, iteration) {
839
+ if (!this.progressReporter?.onStepProgress)
840
+ return;
841
+ await this.progressReporter.onStepProgress({
842
+ jobId,
843
+ stepNumber,
844
+ description,
845
+ status: decision.status === 'complete' ? progress_reporter_1.StepExecutionStatus.SUCCESS :
846
+ decision.status === 'stuck' || decision.status === 'infeasible' ? progress_reporter_1.StepExecutionStatus.FAILURE :
847
+ progress_reporter_1.StepExecutionStatus.IN_PROGRESS,
848
+ code: decision.commands?.join('\n'),
849
+ // Include agent metadata for transparency
850
+ agentIteration: iteration,
851
+ agentReasoning: decision.reasoning,
852
+ agentSelfReflection: decision.selfReflection,
853
+ agentExperiences: decision.experiences,
854
+ agentToolsUsed: decision.toolCalls?.map(t => t.name),
855
+ agentStatus: decision.status
856
+ });
857
+ }
858
+ }
859
+ exports.OrchestratorAgent = OrchestratorAgent;
860
+ //# sourceMappingURL=orchestrator-agent.js.map