testchimp-runner-core 0.0.21 → 0.0.23

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 (146) hide show
  1. package/VISION_DIAGNOSTICS_IMPROVEMENTS.md +336 -0
  2. package/dist/credit-usage-service.d.ts +9 -0
  3. package/dist/credit-usage-service.d.ts.map +1 -1
  4. package/dist/credit-usage-service.js +20 -5
  5. package/dist/credit-usage-service.js.map +1 -1
  6. package/dist/execution-service.d.ts +7 -2
  7. package/dist/execution-service.d.ts.map +1 -1
  8. package/dist/execution-service.js +91 -36
  9. package/dist/execution-service.js.map +1 -1
  10. package/dist/index.d.ts +30 -2
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +91 -26
  13. package/dist/index.js.map +1 -1
  14. package/dist/llm-facade.d.ts +64 -8
  15. package/dist/llm-facade.d.ts.map +1 -1
  16. package/dist/llm-facade.js +361 -109
  17. package/dist/llm-facade.js.map +1 -1
  18. package/dist/llm-provider.d.ts +39 -0
  19. package/dist/llm-provider.d.ts.map +1 -0
  20. package/dist/llm-provider.js +7 -0
  21. package/dist/llm-provider.js.map +1 -0
  22. package/dist/model-constants.d.ts +21 -0
  23. package/dist/model-constants.d.ts.map +1 -0
  24. package/dist/model-constants.js +24 -0
  25. package/dist/model-constants.js.map +1 -0
  26. package/dist/orchestrator/index.d.ts +8 -0
  27. package/dist/orchestrator/index.d.ts.map +1 -0
  28. package/dist/orchestrator/index.js +23 -0
  29. package/dist/orchestrator/index.js.map +1 -0
  30. package/dist/orchestrator/orchestrator-agent.d.ts +66 -0
  31. package/dist/orchestrator/orchestrator-agent.d.ts.map +1 -0
  32. package/dist/orchestrator/orchestrator-agent.js +855 -0
  33. package/dist/orchestrator/orchestrator-agent.js.map +1 -0
  34. package/dist/orchestrator/tool-registry.d.ts +74 -0
  35. package/dist/orchestrator/tool-registry.d.ts.map +1 -0
  36. package/dist/orchestrator/tool-registry.js +131 -0
  37. package/dist/orchestrator/tool-registry.js.map +1 -0
  38. package/dist/orchestrator/tools/check-page-ready.d.ts +13 -0
  39. package/dist/orchestrator/tools/check-page-ready.d.ts.map +1 -0
  40. package/dist/orchestrator/tools/check-page-ready.js +72 -0
  41. package/dist/orchestrator/tools/check-page-ready.js.map +1 -0
  42. package/dist/orchestrator/tools/extract-data.d.ts +13 -0
  43. package/dist/orchestrator/tools/extract-data.d.ts.map +1 -0
  44. package/dist/orchestrator/tools/extract-data.js +84 -0
  45. package/dist/orchestrator/tools/extract-data.js.map +1 -0
  46. package/dist/orchestrator/tools/index.d.ts +10 -0
  47. package/dist/orchestrator/tools/index.d.ts.map +1 -0
  48. package/dist/orchestrator/tools/index.js +18 -0
  49. package/dist/orchestrator/tools/index.js.map +1 -0
  50. package/dist/orchestrator/tools/inspect-page.d.ts +13 -0
  51. package/dist/orchestrator/tools/inspect-page.d.ts.map +1 -0
  52. package/dist/orchestrator/tools/inspect-page.js +39 -0
  53. package/dist/orchestrator/tools/inspect-page.js.map +1 -0
  54. package/dist/orchestrator/tools/recall-history.d.ts +13 -0
  55. package/dist/orchestrator/tools/recall-history.d.ts.map +1 -0
  56. package/dist/orchestrator/tools/recall-history.js +64 -0
  57. package/dist/orchestrator/tools/recall-history.js.map +1 -0
  58. package/dist/orchestrator/tools/take-screenshot.d.ts +15 -0
  59. package/dist/orchestrator/tools/take-screenshot.d.ts.map +1 -0
  60. package/dist/orchestrator/tools/take-screenshot.js +112 -0
  61. package/dist/orchestrator/tools/take-screenshot.js.map +1 -0
  62. package/dist/orchestrator/types.d.ts +133 -0
  63. package/dist/orchestrator/types.d.ts.map +1 -0
  64. package/dist/orchestrator/types.js +28 -0
  65. package/dist/orchestrator/types.js.map +1 -0
  66. package/dist/playwright-mcp-service.d.ts +9 -0
  67. package/dist/playwright-mcp-service.d.ts.map +1 -1
  68. package/dist/playwright-mcp-service.js +20 -5
  69. package/dist/playwright-mcp-service.js.map +1 -1
  70. package/dist/progress-reporter.d.ts +97 -0
  71. package/dist/progress-reporter.d.ts.map +1 -0
  72. package/dist/progress-reporter.js +18 -0
  73. package/dist/progress-reporter.js.map +1 -0
  74. package/dist/prompts.d.ts +24 -0
  75. package/dist/prompts.d.ts.map +1 -1
  76. package/dist/prompts.js +593 -68
  77. package/dist/prompts.js.map +1 -1
  78. package/dist/providers/backend-proxy-llm-provider.d.ts +25 -0
  79. package/dist/providers/backend-proxy-llm-provider.d.ts.map +1 -0
  80. package/dist/providers/backend-proxy-llm-provider.js +76 -0
  81. package/dist/providers/backend-proxy-llm-provider.js.map +1 -0
  82. package/dist/providers/local-llm-provider.d.ts +21 -0
  83. package/dist/providers/local-llm-provider.d.ts.map +1 -0
  84. package/dist/providers/local-llm-provider.js +35 -0
  85. package/dist/providers/local-llm-provider.js.map +1 -0
  86. package/dist/scenario-service.d.ts +27 -1
  87. package/dist/scenario-service.d.ts.map +1 -1
  88. package/dist/scenario-service.js +48 -12
  89. package/dist/scenario-service.js.map +1 -1
  90. package/dist/scenario-worker-class.d.ts +39 -2
  91. package/dist/scenario-worker-class.d.ts.map +1 -1
  92. package/dist/scenario-worker-class.js +614 -86
  93. package/dist/scenario-worker-class.js.map +1 -1
  94. package/dist/script-utils.d.ts +2 -0
  95. package/dist/script-utils.d.ts.map +1 -1
  96. package/dist/script-utils.js +44 -4
  97. package/dist/script-utils.js.map +1 -1
  98. package/dist/types.d.ts +11 -0
  99. package/dist/types.d.ts.map +1 -1
  100. package/dist/types.js.map +1 -1
  101. package/dist/utils/browser-utils.d.ts +20 -1
  102. package/dist/utils/browser-utils.d.ts.map +1 -1
  103. package/dist/utils/browser-utils.js +102 -51
  104. package/dist/utils/browser-utils.js.map +1 -1
  105. package/dist/utils/page-info-utils.d.ts +23 -4
  106. package/dist/utils/page-info-utils.d.ts.map +1 -1
  107. package/dist/utils/page-info-utils.js +174 -43
  108. package/dist/utils/page-info-utils.js.map +1 -1
  109. package/package.json +1 -2
  110. package/plandocs/HUMAN_LIKE_IMPROVEMENTS.md +642 -0
  111. package/plandocs/MULTI_AGENT_ARCHITECTURE_REVIEW.md +844 -0
  112. package/plandocs/ORCHESTRATOR_MVP_SUMMARY.md +539 -0
  113. package/plandocs/PHASE1_ABSTRACTION_COMPLETE.md +241 -0
  114. package/plandocs/PHASE1_FINAL_STATUS.md +210 -0
  115. package/plandocs/PLANNING_SESSION_SUMMARY.md +372 -0
  116. package/plandocs/SCRIPT_CLEANUP_FEATURE.md +201 -0
  117. package/plandocs/SCRIPT_GENERATION_ARCHITECTURE.md +364 -0
  118. package/plandocs/SELECTOR_IMPROVEMENTS.md +139 -0
  119. package/src/credit-usage-service.ts +23 -5
  120. package/src/execution-service.ts +152 -42
  121. package/src/index.ts +169 -26
  122. package/src/llm-facade.ts +500 -126
  123. package/src/llm-provider.ts +43 -0
  124. package/src/model-constants.ts +23 -0
  125. package/src/orchestrator/index.ts +33 -0
  126. package/src/orchestrator/orchestrator-agent.ts +1037 -0
  127. package/src/orchestrator/tool-registry.ts +182 -0
  128. package/src/orchestrator/tools/check-page-ready.ts +75 -0
  129. package/src/orchestrator/tools/extract-data.ts +92 -0
  130. package/src/orchestrator/tools/index.ts +11 -0
  131. package/src/orchestrator/tools/inspect-page.ts +42 -0
  132. package/src/orchestrator/tools/recall-history.ts +72 -0
  133. package/src/orchestrator/tools/take-screenshot.ts +128 -0
  134. package/src/orchestrator/types.ts +200 -0
  135. package/src/playwright-mcp-service.ts +23 -5
  136. package/src/progress-reporter.ts +109 -0
  137. package/src/prompts.ts +606 -69
  138. package/src/providers/backend-proxy-llm-provider.ts +91 -0
  139. package/src/providers/local-llm-provider.ts +38 -0
  140. package/src/scenario-service.ts +83 -13
  141. package/src/scenario-worker-class.ts +740 -72
  142. package/src/script-utils.ts +50 -5
  143. package/src/types.ts +13 -1
  144. package/src/utils/browser-utils.ts +123 -51
  145. package/src/utils/page-info-utils.ts +210 -53
  146. package/testchimp-runner-core-0.0.22.tgz +0 -0
@@ -0,0 +1,855 @@
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 types_1 = require("./types");
13
+ /**
14
+ * Orchestrator Agent - manages step execution with tool use and memory
15
+ */
16
+ class OrchestratorAgent {
17
+ constructor(llmFacade, toolRegistry, config, progressReporter, logger, debugMode) {
18
+ this.debugMode = false;
19
+ this.llmFacade = llmFacade;
20
+ this.toolRegistry = toolRegistry;
21
+ this.config = { ...types_1.DEFAULT_AGENT_CONFIG, ...config };
22
+ this.progressReporter = progressReporter;
23
+ this.logger = logger;
24
+ this.debugMode = debugMode || false;
25
+ }
26
+ setDebugMode(enabled) {
27
+ this.debugMode = enabled;
28
+ }
29
+ /**
30
+ * Execute a single step of the scenario
31
+ */
32
+ async executeStep(page, stepDescription, stepNumber, totalSteps, scenarioSteps, memory, jobId) {
33
+ this.logger?.(`\n[Orchestrator] ========== STEP ${stepNumber}/${totalSteps} ==========`);
34
+ this.logger?.(`[Orchestrator] 🎯 Goal: ${stepDescription}`);
35
+ let iteration = 0;
36
+ let previousReflection = undefined;
37
+ const commandsExecuted = [];
38
+ let consecutiveFailures = 0; // Track consecutive iterations with failed commands
39
+ while (iteration < this.config.maxIterationsPerStep) {
40
+ iteration++;
41
+ this.logger?.(`\n[Orchestrator] === Iteration ${iteration}/${this.config.maxIterationsPerStep} ===`);
42
+ // Build context for agent
43
+ const context = await this.buildAgentContext(page, stepDescription, stepNumber, totalSteps, scenarioSteps, memory, previousReflection, consecutiveFailures);
44
+ // Call agent to make decision
45
+ const decision = await this.callAgent(context, jobId, stepNumber, iteration, consecutiveFailures);
46
+ // Log agent's reasoning
47
+ this.logAgentDecision(decision, iteration);
48
+ // Report progress
49
+ await this.reportStepProgress(jobId, stepNumber, stepDescription, decision, iteration);
50
+ // Execute tools if requested (tools are READ-ONLY, they don't change state)
51
+ let toolResults = {};
52
+ if (decision.toolCalls && decision.toolCalls.length > 0) {
53
+ toolResults = await this.executeTools(decision.toolCalls, page, memory, stepNumber);
54
+ // If agent wants to wait for tool results before proceeding, call agent again
55
+ if (decision.needsToolResults) {
56
+ const updatedContext = { ...context, toolResults };
57
+ const continuedDecision = await this.callAgent(updatedContext, jobId, stepNumber, iteration, consecutiveFailures);
58
+ // Merge continued decision
59
+ decision.commands = continuedDecision.commands || decision.commands;
60
+ decision.commandReasoning = continuedDecision.commandReasoning || decision.commandReasoning;
61
+ decision.status = continuedDecision.status;
62
+ decision.statusReasoning = continuedDecision.statusReasoning;
63
+ decision.reasoning = continuedDecision.reasoning;
64
+ }
65
+ }
66
+ // Execute commands sequentially
67
+ let iterationHadFailure = false;
68
+ // Handle blocker if detected (clear blocker FIRST, then proceed with main commands)
69
+ if (decision.blockerDetected && decision.blockerDetected.clearingCommands && decision.blockerDetected.clearingCommands.length > 0) {
70
+ this.logger?.(`[Orchestrator] 🚧 BLOCKER DETECTED: ${decision.blockerDetected.description}`);
71
+ this.logger?.(`[Orchestrator] 🧹 Clearing blocker with ${decision.blockerDetected.clearingCommands.length} command(s)...`);
72
+ const blockerResult = await this.executeCommandsSequentially(decision.blockerDetected.clearingCommands, page, memory, stepNumber, iteration, jobId);
73
+ // Add blocker commands with comment to output
74
+ if (blockerResult.executed.length > 0) {
75
+ commandsExecuted.push(`// Blocker: ${decision.blockerDetected.description}`);
76
+ commandsExecuted.push(...blockerResult.executed);
77
+ }
78
+ // If blocker clearing failed, track it
79
+ if (!blockerResult.allSucceeded) {
80
+ this.logger?.(`[Orchestrator] ❌ Failed to clear blocker - continuing anyway`);
81
+ consecutiveFailures++;
82
+ iterationHadFailure = true;
83
+ }
84
+ }
85
+ // Execute main commands (only if no blocker failure or continueOnFailure is true)
86
+ if (decision.commands && decision.commands.length > 0 && !iterationHadFailure) {
87
+ const executeResult = await this.executeCommandsSequentially(decision.commands, page, memory, stepNumber, iteration, jobId);
88
+ commandsExecuted.push(...executeResult.executed);
89
+ // Track failures
90
+ if (!executeResult.allSucceeded) {
91
+ this.logger?.(`[Orchestrator] ⚠ Command execution stopped at failure`);
92
+ consecutiveFailures++;
93
+ iterationHadFailure = true;
94
+ }
95
+ else {
96
+ consecutiveFailures = 0; // Reset on success
97
+ }
98
+ }
99
+ // System-enforced stuck detection (agent might not detect it)
100
+ if (consecutiveFailures >= 3) {
101
+ this.logger?.(`[Orchestrator] 🛑 SYSTEM: ${consecutiveFailures} consecutive failures detected - forcing stuck`, 'warn');
102
+ return {
103
+ success: false,
104
+ commands: commandsExecuted,
105
+ iterations: iteration,
106
+ terminationReason: 'agent_stuck',
107
+ memory,
108
+ error: `Failed ${consecutiveFailures} iterations in a row - unable to proceed`
109
+ };
110
+ }
111
+ // Update memory with experiences
112
+ if (decision.experiences && decision.experiences.length > 0) {
113
+ for (const exp of decision.experiences) {
114
+ // Deduplicate - don't add if very similar experience exists
115
+ const exists = memory.experiences.some(existing => existing.toLowerCase().includes(exp.toLowerCase()) ||
116
+ exp.toLowerCase().includes(existing.toLowerCase()));
117
+ if (!exists) {
118
+ memory.experiences.push(exp);
119
+ this.logger?.(`[Orchestrator] 📚 Experience: ${exp}`);
120
+ }
121
+ }
122
+ // Cap experiences
123
+ if (memory.experiences.length > this.config.maxExperiences) {
124
+ memory.experiences = memory.experiences.slice(-this.config.maxExperiences);
125
+ }
126
+ }
127
+ // Store self-reflection for next iteration
128
+ previousReflection = decision.selfReflection;
129
+ // Check termination
130
+ if (decision.status !== 'continue') {
131
+ this.logger?.(`[Orchestrator] 🎯 Status: ${decision.status}`);
132
+ 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
+ };
142
+ }
143
+ }
144
+ // Hit iteration limit
145
+ this.logger?.(`[Orchestrator] ⚠ Maximum iterations reached (${this.config.maxIterationsPerStep})`);
146
+ return {
147
+ success: false,
148
+ commands: commandsExecuted,
149
+ iterations: iteration,
150
+ terminationReason: 'system_limit',
151
+ memory,
152
+ error: 'Maximum iterations reached'
153
+ };
154
+ }
155
+ /**
156
+ * Build context for agent
157
+ */
158
+ async buildAgentContext(page, currentStepGoal, stepNumber, totalSteps, scenarioSteps, memory, previousReflection, consecutiveFailures) {
159
+ // Get fresh DOM
160
+ const currentPageInfo = await (0, page_info_utils_1.getEnhancedPageInfo)(page);
161
+ const currentURL = page.url();
162
+ // Get recent steps
163
+ const recentSteps = memory.history.slice(-this.config.recentStepsCount);
164
+ // Build context
165
+ return {
166
+ overallGoal: scenarioSteps.join('\n'),
167
+ currentStepGoal,
168
+ stepNumber,
169
+ totalSteps,
170
+ completedSteps: scenarioSteps.slice(0, stepNumber - 1),
171
+ remainingSteps: scenarioSteps.slice(stepNumber),
172
+ currentPageInfo,
173
+ currentURL,
174
+ recentSteps,
175
+ experiences: memory.experiences,
176
+ extractedData: memory.extractedData,
177
+ previousIterationGuidance: previousReflection
178
+ };
179
+ }
180
+ /**
181
+ * Call agent to make decision
182
+ */
183
+ async callAgent(context, jobId, stepNumber, iteration, consecutiveFailures) {
184
+ // Build prompt
185
+ const systemPrompt = this.buildSystemPrompt();
186
+ const userPrompt = this.buildUserPrompt(context, consecutiveFailures);
187
+ try {
188
+ // Call LLM directly via provider
189
+ const llmRequest = {
190
+ model: model_constants_1.DEFAULT_MODEL,
191
+ systemPrompt,
192
+ userPrompt
193
+ };
194
+ const response = await this.llmFacade.llmProvider.callLLM(llmRequest);
195
+ // Report token usage
196
+ if (response.usage && this.progressReporter?.onTokensUsed) {
197
+ const tokenUsage = {
198
+ jobId,
199
+ stepNumber,
200
+ iteration,
201
+ inputTokens: response.usage.inputTokens,
202
+ outputTokens: response.usage.outputTokens,
203
+ includesImage: false,
204
+ model: model_constants_1.DEFAULT_MODEL,
205
+ timestamp: Date.now()
206
+ };
207
+ this.logger?.(`[Orchestrator] 💰 Reporting token usage: ${tokenUsage.inputTokens} + ${tokenUsage.outputTokens}`, 'log');
208
+ await this.progressReporter.onTokensUsed(tokenUsage);
209
+ }
210
+ else if (!response.usage) {
211
+ this.logger?.(`[Orchestrator] ⚠ No usage data in LLM response`, 'warn');
212
+ }
213
+ // Parse response
214
+ return this.parseAgentDecision(response.answer);
215
+ }
216
+ catch (error) {
217
+ this.logger?.(`[Orchestrator] ✗ Agent call failed: ${error.message}`, 'error');
218
+ // Return fallback decision
219
+ return {
220
+ status: 'stuck',
221
+ statusReasoning: `Agent call failed: ${error.message}`,
222
+ reasoning: 'LLM call failed'
223
+ };
224
+ }
225
+ }
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
+ /**
612
+ * Parse agent decision from LLM response
613
+ */
614
+ parseAgentDecision(response) {
615
+ try {
616
+ // Extract JSON from response
617
+ const jsonMatch = response.match(/\{[\s\S]*\}/);
618
+ if (!jsonMatch) {
619
+ throw new Error('No JSON found in response');
620
+ }
621
+ const parsed = JSON.parse(jsonMatch[0]);
622
+ // Validate required fields
623
+ if (!parsed.status || !parsed.reasoning) {
624
+ throw new Error('Missing required fields: status and reasoning');
625
+ }
626
+ return parsed;
627
+ }
628
+ catch (error) {
629
+ this.logger?.(`[Orchestrator] ✗ Failed to parse agent decision: ${error.message}`, 'error');
630
+ this.logger?.(`[Orchestrator] Raw response: ${response.substring(0, 200)}...`, 'log');
631
+ // Return fallback
632
+ return {
633
+ status: 'stuck',
634
+ statusReasoning: 'Failed to parse agent response',
635
+ reasoning: `Parse error: ${error.message}`
636
+ };
637
+ }
638
+ }
639
+ /**
640
+ * Execute tools
641
+ */
642
+ async executeTools(toolCalls, page, memory, stepNumber) {
643
+ this.logger?.(`[Orchestrator] 🔧 Executing ${toolCalls.length} tool(s)`);
644
+ const results = {};
645
+ const toolContext = {
646
+ page,
647
+ memory,
648
+ stepNumber,
649
+ logger: this.logger
650
+ };
651
+ for (const toolCall of toolCalls.slice(0, this.config.maxToolCallsPerIteration)) {
652
+ this.logger?.(`[Orchestrator] ▶ ${toolCall.name}(${JSON.stringify(toolCall.params).substring(0, 50)}...)`);
653
+ const result = await this.toolRegistry.execute(toolCall, toolContext);
654
+ results[toolCall.name] = result;
655
+ if (result.success) {
656
+ this.logger?.(`[Orchestrator] ✓ ${toolCall.name} succeeded`);
657
+ }
658
+ else {
659
+ this.logger?.(`[Orchestrator] ✗ ${toolCall.name} failed: ${result.error}`, 'error');
660
+ }
661
+ }
662
+ return results;
663
+ }
664
+ /**
665
+ * Execute commands sequentially with SHARED context (variables persist across commands)
666
+ */
667
+ async executeCommandsSequentially(commands, page, memory, stepNumber, iteration, jobId) {
668
+ this.logger?.(`[Orchestrator] 📝 Executing ${commands.length} command(s) in shared context`);
669
+ const executed = [];
670
+ const limitedCommands = commands.slice(0, this.config.maxCommandsPerIteration);
671
+ // Build execution with shared context (all commands share scope - variables persist)
672
+ const commandsWithTracking = limitedCommands.map((cmd, i) => {
673
+ return `
674
+ // Command ${i + 1}/${limitedCommands.length}
675
+ try {
676
+ ${cmd}
677
+ __results.push({ index: ${i}, success: true });
678
+ } catch (error) {
679
+ __results.push({ index: ${i}, success: false, error: error.message });
680
+ throw error; // Stop on first failure
681
+ }`;
682
+ }).join('\n');
683
+ const wrappedCode = `
684
+ const __results = [];
685
+ ${commandsWithTracking}
686
+ return __results;
687
+ `;
688
+ try {
689
+ // Execute in shared context - variables declared here persist for entire scenario
690
+ // Pass both page and expect to make Playwright assertions available
691
+ const func = new Function('page', 'expect', 'return (async () => { ' + wrappedCode + ' })()');
692
+ const results = await func(page, test_1.expect);
693
+ // Record results for each command
694
+ for (let i = 0; i < limitedCommands.length; i++) {
695
+ const cmd = limitedCommands[i];
696
+ const result = results[i];
697
+ if (result && result.success) {
698
+ this.logger?.(`[Orchestrator] ✓ [${i + 1}/${limitedCommands.length}] Success`);
699
+ // Record in history
700
+ memory.history.push({
701
+ stepNumber,
702
+ iteration,
703
+ action: `Command ${i + 1}/${limitedCommands.length}`,
704
+ code: cmd,
705
+ result: 'success',
706
+ observation: 'Executed successfully',
707
+ url: page.url(),
708
+ timestamp: Date.now()
709
+ });
710
+ executed.push(cmd);
711
+ }
712
+ }
713
+ // Cap history
714
+ if (memory.history.length > this.config.maxHistorySize) {
715
+ memory.history = memory.history.slice(-this.config.maxHistorySize);
716
+ }
717
+ return { executed, allSucceeded: true };
718
+ }
719
+ catch (error) {
720
+ // One of the commands failed - find which one
721
+ const errorMessage = error.message || String(error);
722
+ // Capture page state for debug logging
723
+ let pageStateDebug = '';
724
+ if (this.debugMode) {
725
+ try {
726
+ const pageInfo = await (0, page_info_utils_1.getEnhancedPageInfo)(page);
727
+ pageStateDebug = `
728
+ === DEBUG: PAGE STATE AT FAILURE ===
729
+ URL: ${page.url()}
730
+ Title: ${pageInfo.title}
731
+
732
+ INTERACTIVE ELEMENTS:
733
+ ${pageInfo.formattedElements}
734
+
735
+ ARIA SNAPSHOT:
736
+ ${JSON.stringify(pageInfo.ariaSnapshot, null, 2)}
737
+
738
+ ====================================`;
739
+ }
740
+ catch (debugError) {
741
+ pageStateDebug = `Failed to capture page state: ${debugError.message}`;
742
+ }
743
+ }
744
+ // Record all that succeeded, then the failure
745
+ for (let i = 0; i < limitedCommands.length; i++) {
746
+ const cmd = limitedCommands[i];
747
+ // This is a failed command (error happened here or earlier)
748
+ if (executed.length <= i) {
749
+ this.logger?.(`[Orchestrator] ✗ [${i + 1}/${limitedCommands.length}] Failed: ${errorMessage}`, 'error');
750
+ // Log detailed debug info
751
+ if (this.debugMode && pageStateDebug) {
752
+ this.logger?.(pageStateDebug, 'debug');
753
+ }
754
+ memory.history.push({
755
+ stepNumber,
756
+ iteration,
757
+ action: `Command ${i + 1}/${limitedCommands.length} - FAILED`,
758
+ code: cmd,
759
+ result: 'failure',
760
+ observation: `Failed with error: ${errorMessage}. This selector likely doesn't exist or is incorrect.`,
761
+ error: errorMessage,
762
+ url: page.url(),
763
+ timestamp: Date.now()
764
+ });
765
+ if (i < limitedCommands.length - 1) {
766
+ this.logger?.(`[Orchestrator] ⚠ Skipping remaining ${limitedCommands.length - i - 1} command(s)`, 'warn');
767
+ }
768
+ break;
769
+ }
770
+ }
771
+ return { executed, allSucceeded: false };
772
+ }
773
+ }
774
+ /**
775
+ * Execute a single command
776
+ */
777
+ async executeCommand(cmd, page) {
778
+ // Wrap in async function and execute
779
+ const wrapped = `(async () => { ${cmd} })()`;
780
+ try {
781
+ await eval(wrapped);
782
+ }
783
+ catch (error) {
784
+ // If eval fails, try direct execution with page context
785
+ // Pass both page and expect to make Playwright assertions available
786
+ const func = new Function('page', 'expect', `return (async () => { ${cmd} })()`);
787
+ await func(page, test_1.expect);
788
+ }
789
+ }
790
+ /**
791
+ * Log agent decision
792
+ */
793
+ logAgentDecision(decision, iteration) {
794
+ this.logger?.(`[Orchestrator] 💭 REASONING: ${decision.reasoning}`);
795
+ if (decision.selfReflection) {
796
+ this.logger?.(`[Orchestrator] 🧠 SELF-REFLECTION:`);
797
+ this.logger?.(`[Orchestrator] Next: ${decision.selfReflection.guidanceForNext}`);
798
+ if (decision.selfReflection.detectingLoop) {
799
+ this.logger?.(`[Orchestrator] 🔄 LOOP DETECTED: ${decision.selfReflection.loopReasoning}`, 'warn');
800
+ }
801
+ }
802
+ if (decision.toolCalls && decision.toolCalls.length > 0) {
803
+ this.logger?.(`[Orchestrator] 🔧 TOOLS: ${decision.toolCalls.map(t => t.name).join(', ')}`);
804
+ if (decision.toolReasoning) {
805
+ this.logger?.(`[Orchestrator] 📋 Why: ${decision.toolReasoning}`);
806
+ }
807
+ }
808
+ if (decision.blockerDetected) {
809
+ this.logger?.(`[Orchestrator] 🚧 BLOCKER: ${decision.blockerDetected.description}`, 'warn');
810
+ this.logger?.(`[Orchestrator] 🧹 Clearing with ${decision.blockerDetected.clearingCommands.length} command(s)`);
811
+ }
812
+ if (decision.stepReEvaluation?.detected) {
813
+ this.logger?.(`[Orchestrator] 🔍 STEP RE-EVALUATION: ${decision.stepReEvaluation.issue}`, 'warn');
814
+ this.logger?.(`[Orchestrator] 📝 Explanation: ${decision.stepReEvaluation.explanation}`);
815
+ }
816
+ if (decision.commands && decision.commands.length > 0) {
817
+ this.logger?.(`[Orchestrator] 📝 COMMANDS (${decision.commands.length}):`);
818
+ decision.commands.slice(0, 3).forEach((cmd, i) => {
819
+ this.logger?.(`[Orchestrator] ${i + 1}. ${cmd.substring(0, 80)}...`);
820
+ });
821
+ if (decision.commands.length > 3) {
822
+ this.logger?.(`[Orchestrator] ... and ${decision.commands.length - 3} more`);
823
+ }
824
+ if (decision.commandReasoning) {
825
+ this.logger?.(`[Orchestrator] 💡 Why: ${decision.commandReasoning}`);
826
+ }
827
+ }
828
+ // Experiences will be logged when added to memory, no need to log here
829
+ }
830
+ /**
831
+ * Report step progress
832
+ */
833
+ async reportStepProgress(jobId, stepNumber, description, decision, iteration) {
834
+ if (!this.progressReporter?.onStepProgress)
835
+ return;
836
+ await this.progressReporter.onStepProgress({
837
+ jobId,
838
+ stepNumber,
839
+ description,
840
+ status: decision.status === 'complete' ? progress_reporter_1.StepExecutionStatus.SUCCESS :
841
+ decision.status === 'stuck' || decision.status === 'infeasible' ? progress_reporter_1.StepExecutionStatus.FAILURE :
842
+ progress_reporter_1.StepExecutionStatus.IN_PROGRESS,
843
+ code: decision.commands?.join('\n'),
844
+ // Include agent metadata for transparency
845
+ agentIteration: iteration,
846
+ agentReasoning: decision.reasoning,
847
+ agentSelfReflection: decision.selfReflection,
848
+ agentExperiences: decision.experiences,
849
+ agentToolsUsed: decision.toolCalls?.map(t => t.name),
850
+ agentStatus: decision.status
851
+ });
852
+ }
853
+ }
854
+ exports.OrchestratorAgent = OrchestratorAgent;
855
+ //# sourceMappingURL=orchestrator-agent.js.map