ft-scout 9.5.4 → 9.5.6

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 (105) hide show
  1. package/README.md +1 -1
  2. package/bin/src/commands/agent.d.ts +5 -0
  3. package/bin/src/commands/agent.js +45 -3
  4. package/bin/src/commands/support.d.ts +9 -0
  5. package/bin/src/commands/support.js +227 -0
  6. package/bin/src/engine/agent/computerUseLoop.d.ts +107 -0
  7. package/bin/src/engine/agent/computerUseLoop.js +413 -0
  8. package/bin/src/engine/agent/index.d.ts +2 -0
  9. package/bin/src/engine/agent/index.js +2 -0
  10. package/bin/src/engine/agent/recovery/index.d.ts +4 -0
  11. package/bin/src/engine/agent/recovery/index.js +4 -0
  12. package/bin/src/engine/agent/recovery/loopDetector.d.ts +26 -0
  13. package/bin/src/engine/agent/recovery/loopDetector.js +126 -0
  14. package/bin/src/engine/agent/recovery/recoveryManager.d.ts +43 -0
  15. package/bin/src/engine/agent/recovery/recoveryManager.js +271 -0
  16. package/bin/src/engine/agent/recovery/types.d.ts +48 -0
  17. package/bin/src/engine/agent/recovery/types.js +4 -0
  18. package/bin/src/engine/agent/verification/index.d.ts +3 -0
  19. package/bin/src/engine/agent/verification/index.js +3 -0
  20. package/bin/src/engine/agent/verification/stateChangeVerifier.d.ts +22 -0
  21. package/bin/src/engine/agent/verification/stateChangeVerifier.js +282 -0
  22. package/bin/src/engine/agent/verification/types.d.ts +28 -0
  23. package/bin/src/engine/agent/verification/types.js +4 -0
  24. package/bin/src/engine/agentEngine.d.ts +2 -1
  25. package/bin/src/engine/agentEngine.js +98 -7
  26. package/bin/src/engine/agentState.d.ts +41 -1
  27. package/bin/src/engine/agentState.js +45 -0
  28. package/bin/src/engine/browser/actions/actionEngine.d.ts +41 -0
  29. package/bin/src/engine/browser/actions/actionEngine.js +707 -0
  30. package/bin/src/engine/browser/actions/index.d.ts +4 -0
  31. package/bin/src/engine/browser/actions/index.js +4 -0
  32. package/bin/src/engine/browser/actions/reliability.d.ts +41 -0
  33. package/bin/src/engine/browser/actions/reliability.js +170 -0
  34. package/bin/src/engine/browser/actions/types.d.ts +50 -0
  35. package/bin/src/engine/browser/actions/types.js +2 -0
  36. package/bin/src/engine/browser/browserController.d.ts +18 -0
  37. package/bin/src/engine/browser/browserController.js +44 -12
  38. package/bin/src/engine/browser/index.d.ts +2 -0
  39. package/bin/src/engine/browser/index.js +2 -0
  40. package/bin/src/engine/browser/observer/accessibilityTree.d.ts +14 -0
  41. package/bin/src/engine/browser/observer/accessibilityTree.js +214 -0
  42. package/bin/src/engine/browser/observer/browserObserver.d.ts +29 -0
  43. package/bin/src/engine/browser/observer/browserObserver.js +204 -0
  44. package/bin/src/engine/browser/observer/domExtractor.d.ts +30 -0
  45. package/bin/src/engine/browser/observer/domExtractor.js +407 -0
  46. package/bin/src/engine/browser/observer/index.d.ts +5 -0
  47. package/bin/src/engine/browser/observer/index.js +5 -0
  48. package/bin/src/engine/browser/observer/types.d.ts +163 -0
  49. package/bin/src/engine/browser/observer/types.js +8 -0
  50. package/bin/src/engine/computer/computerController.d.ts +49 -0
  51. package/bin/src/engine/computer/computerController.js +249 -104
  52. package/bin/src/engine/computer/mockComputer.d.ts +6 -1
  53. package/bin/src/engine/computer/mockComputer.js +58 -0
  54. package/bin/src/engine/computer/scoutDriver.cs +84 -2
  55. package/bin/src/engine/llm.js +16 -0
  56. package/bin/src/engine/models/harpProvider.d.ts +32 -0
  57. package/bin/src/engine/models/harpProvider.js +124 -0
  58. package/bin/src/engine/models/index.d.ts +6 -0
  59. package/bin/src/engine/models/index.js +6 -0
  60. package/bin/src/engine/models/localModelProvider.d.ts +11 -0
  61. package/bin/src/engine/models/localModelProvider.js +48 -0
  62. package/bin/src/engine/models/openaiProvider.d.ts +11 -0
  63. package/bin/src/engine/models/openaiProvider.js +50 -0
  64. package/bin/src/engine/models/reasoningOrchestrator.d.ts +17 -0
  65. package/bin/src/engine/models/reasoningOrchestrator.js +75 -0
  66. package/bin/src/engine/models/types.d.ts +63 -0
  67. package/bin/src/engine/models/types.js +2 -0
  68. package/bin/src/engine/planner.js +64 -34
  69. package/bin/src/engine/production/index.d.ts +3 -0
  70. package/bin/src/engine/production/index.js +3 -0
  71. package/bin/src/engine/production/taskReplay.d.ts +37 -0
  72. package/bin/src/engine/production/taskReplay.js +81 -0
  73. package/bin/src/engine/production/telemetry.d.ts +43 -0
  74. package/bin/src/engine/production/telemetry.js +68 -0
  75. package/bin/src/engine/runtime/agentRuntime.d.ts +1 -1
  76. package/bin/src/engine/runtime/agentRuntime.js +99 -0
  77. package/bin/src/engine/safety/index.d.ts +3 -0
  78. package/bin/src/engine/safety/index.js +3 -0
  79. package/bin/src/engine/safety/policyEngine.d.ts +40 -0
  80. package/bin/src/engine/safety/policyEngine.js +282 -0
  81. package/bin/src/engine/safety/types.d.ts +24 -0
  82. package/bin/src/engine/safety/types.js +2 -0
  83. package/bin/src/engine/safety.d.ts +1 -0
  84. package/bin/src/engine/safety.js +1 -0
  85. package/bin/src/engine/subagents/subagentManager.js +2 -2
  86. package/bin/src/engine/toolRegistry.d.ts +4 -0
  87. package/bin/src/engine/toolRegistry.js +9 -0
  88. package/bin/src/engine/tools/domainHandlers.d.ts +61 -0
  89. package/bin/src/engine/tools/domainHandlers.js +458 -0
  90. package/bin/src/engine/tools/index.d.ts +4 -0
  91. package/bin/src/engine/tools/index.js +4 -0
  92. package/bin/src/engine/tools/types.d.ts +56 -0
  93. package/bin/src/engine/tools/types.js +2 -0
  94. package/bin/src/engine/tools/unifiedRouter.d.ts +29 -0
  95. package/bin/src/engine/tools/unifiedRouter.js +426 -0
  96. package/bin/src/index.js +26 -6
  97. package/bin/src/mcp/client.js +1 -1
  98. package/bin/src/server/server.js +136 -0
  99. package/bin/src/utils/branding.js +1 -1
  100. package/bin/src/utils/qrBridge.js +1 -1
  101. package/bin/src/utils/session.d.ts +5 -1
  102. package/bin/src/utils/session.js +36 -3
  103. package/bin/src/utils/support.d.ts +63 -0
  104. package/bin/src/utils/support.js +182 -0
  105. package/package.json +2 -2
@@ -0,0 +1,271 @@
1
+ import {} from '../../browser/observer/types.js';
2
+ import {} from '../../browser/actions/index.js';
3
+ import {} from './types.js';
4
+ export class RecoveryManager {
5
+ defaultMaxRetries;
6
+ baseBackoffMs;
7
+ maxBackoffMs;
8
+ constructor(options) {
9
+ this.defaultMaxRetries = options?.defaultMaxRetries || 3;
10
+ this.baseBackoffMs = options?.baseBackoffMs || 150;
11
+ this.maxBackoffMs = options?.maxBackoffMs || 2500;
12
+ }
13
+ /**
14
+ * Decides the next recovery step following the strict hierarchy:
15
+ * RETRY -> RE_OBSERVE -> RE_LOCATE -> SEMANTIC_ALTERNATIVE -> VISUAL_FALLBACK -> REPORT_FAILURE
16
+ */
17
+ decideRecovery(ctx) {
18
+ const maxRetries = ctx.maxRetries || this.defaultMaxRetries;
19
+ const errLower = (ctx.error || '').toLowerCase();
20
+ const backoffDelayMs = this.computeBackoff(ctx.attempt);
21
+ // 1. Loop Breaking: If a loop is detected, break out of RETRY/RE_LOCATE immediately
22
+ if (ctx.loopDetection?.isLoop) {
23
+ const alternative = ctx.currentState
24
+ ? this.findSemanticAlternative(ctx.target || ctx.tool, ctx.currentState)
25
+ : undefined;
26
+ if (alternative) {
27
+ return {
28
+ strategy: 'SEMANTIC_ALTERNATIVE',
29
+ attempt: ctx.attempt,
30
+ maxRetriesExceeded: false,
31
+ reason: `Loop detected (${ctx.loopDetection.message}). Breaking loop by switching to semantic alternative: "${alternative}".`,
32
+ backoffDelayMs,
33
+ suggestedAlternativeTarget: alternative,
34
+ shouldHalt: false,
35
+ };
36
+ }
37
+ return {
38
+ strategy: 'REPORT_FAILURE',
39
+ attempt: ctx.attempt,
40
+ maxRetriesExceeded: true,
41
+ reason: `Halted: Action loop detected (${ctx.loopDetection.message}) and no semantic alternatives remain.`,
42
+ backoffDelayMs: 0,
43
+ shouldHalt: true,
44
+ };
45
+ }
46
+ // 2. Max Retries Exceeded: Escalate to REPORT_FAILURE
47
+ if (ctx.attempt >= maxRetries) {
48
+ return {
49
+ strategy: 'REPORT_FAILURE',
50
+ attempt: ctx.attempt,
51
+ maxRetriesExceeded: true,
52
+ reason: `Exceeded maximum retry limit (${ctx.attempt}/${maxRetries}) for action "${ctx.tool}". Halting task step.`,
53
+ backoffDelayMs: 0,
54
+ shouldHalt: true,
55
+ };
56
+ }
57
+ // 3. Browser Disconnected / Crash Detected
58
+ if (errLower.includes('disconnected') || errLower.includes('crash') || errLower.includes('closed target')) {
59
+ return {
60
+ strategy: 'RE_OBSERVE',
61
+ attempt: ctx.attempt,
62
+ maxRetriesExceeded: false,
63
+ reason: 'Browser session disconnected or unresponsive. Attempting session recovery and fresh observation.',
64
+ backoffDelayMs: Math.max(backoffDelayMs, 500),
65
+ shouldHalt: false,
66
+ };
67
+ }
68
+ // 4. Verification signaled strategy recommendation
69
+ if (ctx.verificationResult?.recommendedStrategy) {
70
+ const recommended = ctx.verificationResult.recommendedStrategy;
71
+ if (recommended === 'SEMANTIC_ALTERNATIVE') {
72
+ const alt = ctx.currentState && ctx.target
73
+ ? this.findSemanticAlternative(ctx.target, ctx.currentState)
74
+ : undefined;
75
+ return {
76
+ strategy: 'SEMANTIC_ALTERNATIVE',
77
+ attempt: ctx.attempt,
78
+ maxRetriesExceeded: false,
79
+ reason: `Verification flagged: ${ctx.verificationResult.details}. Trying semantic alternative.`,
80
+ backoffDelayMs,
81
+ suggestedAlternativeTarget: alt,
82
+ shouldHalt: false,
83
+ };
84
+ }
85
+ if (recommended === 'RE_LOCATE') {
86
+ return {
87
+ strategy: 'RE_LOCATE',
88
+ attempt: ctx.attempt,
89
+ maxRetriesExceeded: false,
90
+ reason: `Verification indicated element not found or stale: ${ctx.verificationResult.details}.`,
91
+ backoffDelayMs,
92
+ shouldHalt: false,
93
+ };
94
+ }
95
+ }
96
+ // 5. Strict Hierarchy Escalation by Attempt Count
97
+ // Attempt 1: RETRY (if transient) or RE_OBSERVE
98
+ if (ctx.attempt === 1) {
99
+ const isTransient = /timeout|network|busy|loading|pending|econnreset/i.test(errLower);
100
+ if (isTransient) {
101
+ return {
102
+ strategy: 'RETRY',
103
+ attempt: ctx.attempt,
104
+ maxRetriesExceeded: false,
105
+ reason: `Transient error encountered: "${ctx.error || 'timeout'}". Retrying with backoff.`,
106
+ backoffDelayMs,
107
+ shouldHalt: false,
108
+ };
109
+ }
110
+ return {
111
+ strategy: 'RE_OBSERVE',
112
+ attempt: ctx.attempt,
113
+ maxRetriesExceeded: false,
114
+ reason: `Initial attempt failed (${ctx.error || 'unverified state'}). Re-observing current DOM/accessibility tree.`,
115
+ backoffDelayMs,
116
+ shouldHalt: false,
117
+ };
118
+ }
119
+ // Attempt 2: RE_LOCATE
120
+ if (ctx.attempt === 2) {
121
+ return {
122
+ strategy: 'RE_LOCATE',
123
+ attempt: ctx.attempt,
124
+ maxRetriesExceeded: false,
125
+ reason: `Target element "${ctx.target || ctx.tool}" stale or not found. Re-locating target using semantic attributes.`,
126
+ backoffDelayMs,
127
+ shouldHalt: false,
128
+ };
129
+ }
130
+ // Attempt 3: SEMANTIC_ALTERNATIVE
131
+ if (ctx.attempt === 3) {
132
+ const alt = ctx.currentState && ctx.target
133
+ ? this.findSemanticAlternative(ctx.target, ctx.currentState)
134
+ : undefined;
135
+ return {
136
+ strategy: 'SEMANTIC_ALTERNATIVE',
137
+ attempt: ctx.attempt,
138
+ maxRetriesExceeded: false,
139
+ reason: `Direct action failed. Seeking semantic alternative control on page.`,
140
+ backoffDelayMs,
141
+ suggestedAlternativeTarget: alt,
142
+ shouldHalt: false,
143
+ };
144
+ }
145
+ // Attempt 4: VISUAL_FALLBACK
146
+ if (ctx.attempt === 4) {
147
+ return {
148
+ strategy: 'VISUAL_FALLBACK',
149
+ attempt: ctx.attempt,
150
+ maxRetriesExceeded: false,
151
+ reason: `Semantic resolution unsuccessful. Falling back to visual bounding box coordinates.`,
152
+ backoffDelayMs,
153
+ shouldHalt: false,
154
+ };
155
+ }
156
+ // Fallback default
157
+ return {
158
+ strategy: 'REPORT_FAILURE',
159
+ attempt: ctx.attempt,
160
+ maxRetriesExceeded: true,
161
+ reason: `Recovery hierarchy exhausted without successful state change: "${ctx.error}".`,
162
+ backoffDelayMs: 0,
163
+ shouldHalt: true,
164
+ };
165
+ }
166
+ /**
167
+ * Calculates exponential backoff with randomized jitter to prevent thundering herds.
168
+ */
169
+ computeBackoff(attempt, baseMs = this.baseBackoffMs, maxMs = this.maxBackoffMs) {
170
+ const raw = Math.min(baseMs * Math.pow(2, Math.max(0, attempt - 1)), maxMs);
171
+ const jitterMultiplier = 0.85 + Math.random() * 0.3; // 85% to 115%
172
+ return Math.floor(raw * jitterMultiplier);
173
+ }
174
+ /**
175
+ * Checks if task has exceeded maximum allotted execution time.
176
+ */
177
+ isTaskTimedOut(startTime, timeoutMs = 60000) {
178
+ return (Date.now() - startTime) >= timeoutMs;
179
+ }
180
+ /**
181
+ * Returns remaining task execution time in milliseconds.
182
+ */
183
+ getRemainingTimeMs(startTime, timeoutMs = 60000) {
184
+ return Math.max(0, timeoutMs - (Date.now() - startTime));
185
+ }
186
+ /**
187
+ * Recovers from browser session crashes or lost connections.
188
+ */
189
+ async handleBrowserCrash(actionEngine, lastKnownUrl) {
190
+ try {
191
+ const fallbackUrl = lastKnownUrl || 'https://github.com';
192
+ const activeTab = actionEngine.getActiveTab();
193
+ const targetUrl = (activeTab && activeTab.url && activeTab.url !== 'about:blank')
194
+ ? activeTab.url
195
+ : fallbackUrl;
196
+ if (!activeTab) {
197
+ // Respawn tab
198
+ await actionEngine.open_tab(targetUrl, '<html><head><title>Restored</title></head><body><h1>Restored</h1></body></html>');
199
+ return {
200
+ recovered: true,
201
+ message: `Browser crash recovered: New active tab created and restored to "${targetUrl}".`,
202
+ recoveredUrl: targetUrl,
203
+ };
204
+ }
205
+ // Tab exists; reload and restore to target URL
206
+ await actionEngine.navigate(targetUrl, '<html><head><title>Restored</title></head><body><h1>Restored</h1></body></html>');
207
+ return {
208
+ recovered: true,
209
+ message: `Browser session re-established at "${targetUrl}".`,
210
+ recoveredUrl: targetUrl,
211
+ };
212
+ }
213
+ catch (err) {
214
+ return {
215
+ recovered: false,
216
+ message: `Failed to recover browser session: ${err.message}`,
217
+ recoveredUrl: 'about:blank',
218
+ };
219
+ }
220
+ }
221
+ /**
222
+ * Finds semantic alternative elements when a target element is missing or fails.
223
+ */
224
+ findSemanticAlternative(target, state) {
225
+ const targetLower = target.toLowerCase();
226
+ // Synonym mappings for common UI intentions
227
+ const synonymGroups = [
228
+ ['submit', 'save', 'confirm', 'continue', 'proceed', 'next', 'ok', 'apply'],
229
+ ['actions', 'ci', 'workflows', 'runs', 'checks', 'builds'],
230
+ ['login', 'sign in', 'authenticate', 'continue with', 'log in'],
231
+ ['close', 'dismiss', 'cancel', 'exit', 'x'],
232
+ ['logs', 'view logs', 'details', 'raw log', 'console'],
233
+ ['search', 'find', 'filter', 'query'],
234
+ ];
235
+ let matchedGroup;
236
+ for (const group of synonymGroups) {
237
+ if (group.some(word => targetLower.includes(word))) {
238
+ matchedGroup = group;
239
+ break;
240
+ }
241
+ }
242
+ if (matchedGroup) {
243
+ for (const synonym of matchedGroup) {
244
+ if (targetLower.includes(synonym))
245
+ continue; // skip identical
246
+ const found = state.elements.find(el => {
247
+ const text = (el.text || '').toLowerCase();
248
+ const aria = (el.attributes['aria-label'] || '').toLowerCase();
249
+ return text.includes(synonym) || aria.includes(synonym);
250
+ });
251
+ if (found) {
252
+ return found.selector;
253
+ }
254
+ }
255
+ }
256
+ // Generic fallback: Look for actionable element sharing token
257
+ const tokens = targetLower.replace(/[^a-z0-9]/g, ' ').split(/\s+/).filter(t => t.length > 3);
258
+ for (const token of tokens) {
259
+ const found = state.elements.find(el => {
260
+ const text = (el.text || '').toLowerCase();
261
+ const isActionable = !el.state.disabled && (el.role === 'button' || el.role === 'link' || el.tagName === 'a' || el.tagName === 'button');
262
+ return text.includes(token) && isActionable;
263
+ });
264
+ if (found) {
265
+ return found.selector;
266
+ }
267
+ }
268
+ return undefined;
269
+ }
270
+ }
271
+ //# sourceMappingURL=recoveryManager.js.map
@@ -0,0 +1,48 @@
1
+ import { type BrowserState } from '../../browser/observer/types.js';
2
+ import { type StateChangeVerificationResult } from '../verification/types.js';
3
+ export type RecoveryStrategyStep = 'RETRY' | 'RE_OBSERVE' | 'RE_LOCATE' | 'SEMANTIC_ALTERNATIVE' | 'VISUAL_FALLBACK' | 'REPORT_FAILURE';
4
+ export type LoopType = 'repeated_action' | 'ping_pong' | 'cycle';
5
+ export interface LoopDetectionResult {
6
+ isLoop: boolean;
7
+ loopType?: LoopType | undefined;
8
+ repeatedCount?: number | undefined;
9
+ cycleLength?: number | undefined;
10
+ patternSummary?: string | undefined;
11
+ message?: string | undefined;
12
+ }
13
+ export interface ActionHistoryRecord {
14
+ step: number;
15
+ tool: string;
16
+ actionType: string;
17
+ args: Record<string, any>;
18
+ target?: string | undefined;
19
+ success: boolean;
20
+ url: string;
21
+ pageFingerprint?: string | undefined;
22
+ timestamp: number;
23
+ }
24
+ export interface RecoveryDecision {
25
+ strategy: RecoveryStrategyStep;
26
+ attempt: number;
27
+ maxRetriesExceeded: boolean;
28
+ reason: string;
29
+ backoffDelayMs: number;
30
+ suggestedAlternativeTarget?: string | undefined;
31
+ suggestedActionOverride?: {
32
+ tool: string;
33
+ args: Record<string, any>;
34
+ } | undefined;
35
+ shouldHalt: boolean;
36
+ }
37
+ export interface RecoveryContext {
38
+ tool: string;
39
+ actionType?: string | undefined;
40
+ target?: string | undefined;
41
+ error?: string | undefined;
42
+ attempt: number;
43
+ maxRetries?: number | undefined;
44
+ loopDetection?: LoopDetectionResult | undefined;
45
+ verificationResult?: StateChangeVerificationResult | undefined;
46
+ currentState?: BrowserState | undefined;
47
+ }
48
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,4 @@
1
+ import {} from '../../browser/observer/types.js';
2
+ import {} from '../computerUseLoop.js';
3
+ import {} from '../verification/types.js';
4
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './stateChangeVerifier.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './stateChangeVerifier.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,22 @@
1
+ import { type BrowserState } from '../../browser/observer/types.js';
2
+ import { type ActionResult } from '../../browser/actions/types.js';
3
+ import { type PlannedAction } from '../computerUseLoop.js';
4
+ import { type StateChangeVerificationResult, type ExpectedStateChange } from './types.js';
5
+ export declare class StateChangeVerifier {
6
+ /**
7
+ * Verifies whether an expected state change occurred following an action.
8
+ * Core question: "Did the expected state change occur?"
9
+ */
10
+ verifyStateChange(params: {
11
+ actionResult: ActionResult;
12
+ plannedAction: PlannedAction;
13
+ beforeState?: BrowserState | Partial<BrowserState> | undefined;
14
+ afterState?: BrowserState | Partial<BrowserState> | undefined;
15
+ expected?: ExpectedStateChange | undefined;
16
+ }): StateChangeVerificationResult;
17
+ private extractErrorStrings;
18
+ private checkButtonActionOccurred;
19
+ private analyzeFormState;
20
+ private isSubmissionAction;
21
+ }
22
+ //# sourceMappingURL=stateChangeVerifier.d.ts.map
@@ -0,0 +1,282 @@
1
+ import {} from '../../browser/observer/types.js';
2
+ import {} from '../../browser/actions/types.js';
3
+ import {} from '../computerUseLoop.js';
4
+ import {} from './types.js';
5
+ export class StateChangeVerifier {
6
+ /**
7
+ * Verifies whether an expected state change occurred following an action.
8
+ * Core question: "Did the expected state change occur?"
9
+ */
10
+ verifyStateChange(params) {
11
+ const { actionResult, plannedAction, beforeState, afterState, expected } = params;
12
+ // 1. Primitive Execution Verification
13
+ if (!actionResult.success) {
14
+ return {
15
+ verified: false,
16
+ stateChanged: false,
17
+ navigationOccurred: false,
18
+ buttonActionOccurred: false,
19
+ formSubmitted: false,
20
+ formUnchanged: false,
21
+ errorAppeared: false,
22
+ modalDismissed: false,
23
+ modalAppeared: false,
24
+ contentChanged: false,
25
+ confidence: 1.0,
26
+ details: `Action execution primitive failed: ${actionResult.error || 'Unknown error'}`,
27
+ recoveryRecommended: true,
28
+ recommendedStrategy: 'RE_LOCATE',
29
+ };
30
+ }
31
+ const beforeUrl = beforeState?.url || actionResult.beforeState?.url || '';
32
+ const afterUrl = afterState?.url || actionResult.afterState?.url || '';
33
+ // 2. Navigation Verification
34
+ const urlChanged = Boolean(beforeUrl && afterUrl && beforeUrl !== afterUrl);
35
+ let navigationOccurred = urlChanged;
36
+ let navigationMatchesPattern = true;
37
+ if (expected?.expectedUrlPattern) {
38
+ navigationMatchesPattern = afterUrl.toLowerCase().includes(expected.expectedUrlPattern.toLowerCase());
39
+ if (!navigationMatchesPattern) {
40
+ navigationOccurred = false;
41
+ }
42
+ }
43
+ // 3. Error Detection (Did an error appear?)
44
+ const beforeErrors = this.extractErrorStrings(beforeState);
45
+ const afterErrors = this.extractErrorStrings(afterState);
46
+ const newErrors = afterErrors.filter(err => !beforeErrors.includes(err));
47
+ const errorAppeared = newErrors.length > 0;
48
+ const errorMessage = errorAppeared ? newErrors[0] : undefined;
49
+ // 4. Modal / Dialog Transition Detection
50
+ const beforeModalOpen = Boolean(beforeState?.modals?.some(m => m.isOpen));
51
+ const afterModalOpen = Boolean(afterState?.modals?.some(m => m.isOpen));
52
+ const modalDismissed = beforeModalOpen && !afterModalOpen;
53
+ const modalAppeared = !beforeModalOpen && afterModalOpen;
54
+ // 5. Button Action & Element Mutation Detection
55
+ const buttonActionOccurred = this.checkButtonActionOccurred({
56
+ plannedAction,
57
+ beforeState,
58
+ afterState,
59
+ urlChanged,
60
+ modalDismissed,
61
+ modalAppeared,
62
+ });
63
+ // 6. Form Submission vs Form Unchanged Detection
64
+ const formAnalysis = this.analyzeFormState({
65
+ plannedAction,
66
+ beforeState,
67
+ afterState,
68
+ urlChanged,
69
+ errorAppeared,
70
+ });
71
+ // 7. General Content Change Detection
72
+ const beforeTextLen = beforeState?.visibleText?.trim().length || 0;
73
+ const afterTextLen = afterState?.visibleText?.trim().length || 0;
74
+ const beforeElCount = beforeState?.elements?.length || 0;
75
+ const afterElCount = afterState?.elements?.length || 0;
76
+ const contentChanged = Math.abs(beforeTextLen - afterTextLen) > 10 || beforeElCount !== afterElCount;
77
+ const stateChanged = urlChanged || modalDismissed || modalAppeared || buttonActionOccurred || formAnalysis.formSubmitted || contentChanged;
78
+ // 8. Expected vs Actual Outcome Assessment
79
+ let verified = false;
80
+ let details = '';
81
+ let confidence = 0.9;
82
+ let recoveryRecommended = false;
83
+ let recommendedStrategy;
84
+ if (errorAppeared) {
85
+ // New error appeared on the page (e.g. form validation failure, invalid input, server error)
86
+ verified = false;
87
+ recoveryRecommended = true;
88
+ recommendedStrategy = 'SEMANTIC_ALTERNATIVE';
89
+ details = `Action triggered an error on page: "${errorMessage}"`;
90
+ }
91
+ else if (formAnalysis.formUnchanged && this.isSubmissionAction(plannedAction)) {
92
+ // Submit button clicked, but form remained identical with no feedback
93
+ verified = false;
94
+ recoveryRecommended = true;
95
+ recommendedStrategy = 'SEMANTIC_ALTERNATIVE';
96
+ details = 'Form unchanged: Submit action was clicked but form inputs were neither submitted nor cleared, and no navigation occurred.';
97
+ }
98
+ else if (plannedAction.tool === 'navigate') {
99
+ if (afterUrl === 'about:blank' || (expected?.expectedUrlPattern && !navigationMatchesPattern)) {
100
+ verified = false;
101
+ recoveryRecommended = true;
102
+ recommendedStrategy = 'RETRY';
103
+ details = `Navigation to expected target failed. Current URL: "${afterUrl}"`;
104
+ }
105
+ else {
106
+ verified = true;
107
+ details = `Navigation confirmed to: "${afterUrl}"`;
108
+ }
109
+ }
110
+ else if (plannedAction.args.key === 'Escape' || plannedAction.description.toLowerCase().includes('dismiss')) {
111
+ if (modalDismissed) {
112
+ verified = true;
113
+ details = 'Modal dialog dismissed successfully';
114
+ }
115
+ else if (!afterModalOpen) {
116
+ verified = true;
117
+ details = 'No blocking modal present';
118
+ }
119
+ else {
120
+ verified = false;
121
+ recoveryRecommended = true;
122
+ recommendedStrategy = 'RETRY';
123
+ details = 'Modal dialog remained open after dismiss attempt';
124
+ }
125
+ }
126
+ else if (plannedAction.tool === 'type') {
127
+ // Type action verification
128
+ const targetVal = plannedAction.args.text;
129
+ const hasTextNow = afterState?.visibleText?.includes(targetVal) ||
130
+ afterState?.forms?.some(f => f.fields.some(field => field.value?.includes(targetVal)));
131
+ verified = hasTextNow || stateChanged;
132
+ details = verified ? `Typed text successfully entered` : `Text input did not reflect in target element`;
133
+ if (!verified) {
134
+ recoveryRecommended = true;
135
+ recommendedStrategy = 'RE_LOCATE';
136
+ }
137
+ }
138
+ else if (plannedAction.tool === 'click') {
139
+ if (stateChanged) {
140
+ verified = true;
141
+ details = urlChanged
142
+ ? `Click resulted in navigation to ${afterUrl}`
143
+ : `Click triggered expected state change (mutation or modal)`;
144
+ }
145
+ else {
146
+ // Click occurred without any observable state change
147
+ verified = false;
148
+ recoveryRecommended = true;
149
+ recommendedStrategy = 'SEMANTIC_ALTERNATIVE';
150
+ details = 'Click had no observable effect on DOM or URL (potential inert element or missing handler)';
151
+ }
152
+ }
153
+ else {
154
+ // Default tool verification (wait, scroll, select)
155
+ verified = true;
156
+ details = `Action "${plannedAction.tool}" verified successfully`;
157
+ }
158
+ return {
159
+ verified,
160
+ stateChanged,
161
+ navigationOccurred,
162
+ buttonActionOccurred,
163
+ formSubmitted: formAnalysis.formSubmitted,
164
+ formUnchanged: formAnalysis.formUnchanged,
165
+ errorAppeared,
166
+ errorMessage: errorMessage || undefined,
167
+ modalDismissed,
168
+ modalAppeared,
169
+ contentChanged,
170
+ confidence,
171
+ details,
172
+ beforeUrl: beforeUrl || undefined,
173
+ afterUrl: afterUrl || undefined,
174
+ recoveryRecommended: recoveryRecommended || undefined,
175
+ recommendedStrategy: recommendedStrategy || undefined,
176
+ };
177
+ }
178
+ extractErrorStrings(state) {
179
+ if (!state)
180
+ return [];
181
+ const errors = [];
182
+ // 1. Accessibility & Role alerts
183
+ for (const el of (state.elements || [])) {
184
+ const role = (el.role || '').toLowerCase();
185
+ const text = (el.text || '').trim();
186
+ const cls = (el.attributes['class'] || '').toLowerCase();
187
+ if (role === 'alert' || role === 'alertdialog' || cls.includes('error') || cls.includes('alert-danger') || cls.includes('toast-error')) {
188
+ if (text && text.length < 300) {
189
+ errors.push(text);
190
+ }
191
+ }
192
+ }
193
+ // 2. Visible text matching
194
+ const lines = (state.visibleText || '').split('\n');
195
+ for (const line of lines) {
196
+ const trimmed = line.trim();
197
+ if (/^(?:error|failed|invalid|exception|warning)\b/i.test(trimmed) && trimmed.length < 200) {
198
+ if (!errors.includes(trimmed)) {
199
+ errors.push(trimmed);
200
+ }
201
+ }
202
+ }
203
+ return errors;
204
+ }
205
+ checkButtonActionOccurred(params) {
206
+ if (params.plannedAction.tool !== 'click') {
207
+ return false;
208
+ }
209
+ if (params.urlChanged || params.modalDismissed || params.modalAppeared) {
210
+ return true;
211
+ }
212
+ const target = (params.plannedAction.args.target || '').toLowerCase();
213
+ const beforeEl = params.beforeState?.elements?.find(e => (e.selector && target.includes(e.selector.toLowerCase())) ||
214
+ (e.text && target.includes(e.text.toLowerCase())) ||
215
+ (e.id && target.includes(e.id.toLowerCase())));
216
+ const afterEl = params.afterState?.elements?.find(e => (e.selector && target.includes(e.selector.toLowerCase())) ||
217
+ (e.text && target.includes(e.text.toLowerCase())) ||
218
+ (e.id && target.includes(e.id.toLowerCase())));
219
+ if (beforeEl && afterEl) {
220
+ // Check aria-expanded
221
+ if (beforeEl.attributes['aria-expanded'] !== afterEl.attributes['aria-expanded']) {
222
+ return true;
223
+ }
224
+ // Check disabled
225
+ if (beforeEl.state.disabled !== afterEl.state.disabled) {
226
+ return true;
227
+ }
228
+ // Check class change
229
+ if (beforeEl.attributes['class'] !== afterEl.attributes['class']) {
230
+ return true;
231
+ }
232
+ }
233
+ return false;
234
+ }
235
+ analyzeFormState(params) {
236
+ const isSubmit = this.isSubmissionAction(params.plannedAction);
237
+ if (!isSubmit) {
238
+ return { formSubmitted: false, formUnchanged: false };
239
+ }
240
+ // If URL changed on submit, navigation / submission succeeded
241
+ if (params.urlChanged) {
242
+ return { formSubmitted: true, formUnchanged: false };
243
+ }
244
+ const beforeForms = params.beforeState?.forms || [];
245
+ const afterForms = params.afterState?.forms || [];
246
+ // If form unmounted or disappeared, submission succeeded
247
+ if (beforeForms.length > 0 && afterForms.length === 0) {
248
+ return { formSubmitted: true, formUnchanged: false };
249
+ }
250
+ // Compare form values
251
+ if (beforeForms.length > 0 && afterForms.length > 0) {
252
+ const beforeF = beforeForms[0];
253
+ const afterF = afterForms[0];
254
+ let valuesIdentical = true;
255
+ for (let i = 0; i < beforeF.fields.length; i++) {
256
+ const bVal = beforeF.fields[i]?.value || '';
257
+ const aVal = afterF.fields[i]?.value || '';
258
+ if (bVal !== aVal) {
259
+ valuesIdentical = false;
260
+ break;
261
+ }
262
+ }
263
+ if (valuesIdentical && !params.errorAppeared) {
264
+ // Form remained completely unchanged with no feedback
265
+ return { formSubmitted: false, formUnchanged: true };
266
+ }
267
+ if (!valuesIdentical) {
268
+ return { formSubmitted: true, formUnchanged: false };
269
+ }
270
+ }
271
+ return { formSubmitted: false, formUnchanged: false };
272
+ }
273
+ isSubmissionAction(action) {
274
+ if (action.tool !== 'click')
275
+ return false;
276
+ const desc = (action.description || '').toLowerCase();
277
+ const target = (action.args.target || '').toLowerCase();
278
+ return /submit|register|sign\s*up|log\s*in|save|confirm|checkout/i.test(desc) ||
279
+ /submit|register|sign\s*up|log\s*in|save|confirm|checkout/i.test(target);
280
+ }
281
+ }
282
+ //# sourceMappingURL=stateChangeVerifier.js.map
@@ -0,0 +1,28 @@
1
+ export interface ExpectedStateChange {
2
+ type?: 'navigation' | 'button_action' | 'form_submission' | 'modal_dismiss' | 'text_present' | 'element_mutation' | 'any_state_change' | undefined;
3
+ target?: string | undefined;
4
+ expectedUrlPattern?: string | undefined;
5
+ expectedText?: string | undefined;
6
+ disallowedErrors?: string[] | undefined;
7
+ timeoutMs?: number | undefined;
8
+ }
9
+ export interface StateChangeVerificationResult {
10
+ verified: boolean;
11
+ stateChanged: boolean;
12
+ navigationOccurred: boolean;
13
+ buttonActionOccurred: boolean;
14
+ formSubmitted: boolean;
15
+ formUnchanged: boolean;
16
+ errorAppeared: boolean;
17
+ errorMessage?: string | undefined;
18
+ modalDismissed: boolean;
19
+ modalAppeared: boolean;
20
+ contentChanged: boolean;
21
+ confidence: number;
22
+ details: string;
23
+ beforeUrl?: string | undefined;
24
+ afterUrl?: string | undefined;
25
+ recoveryRecommended?: boolean | undefined;
26
+ recommendedStrategy?: 'RETRY' | 'RE_OBSERVE' | 'RE_LOCATE' | 'SEMANTIC_ALTERNATIVE' | 'VISUAL_FALLBACK' | 'REPORT_FAILURE' | undefined;
27
+ }
28
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,4 @@
1
+ import {} from '../../browser/observer/types.js';
2
+ import {} from '../../browser/actions/types.js';
3
+ import {} from '../computerUseLoop.js';
4
+ //# sourceMappingURL=types.js.map