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