-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathindex.ts
More file actions
1650 lines (1532 loc) · 49.5 KB
/
index.ts
File metadata and controls
1650 lines (1532 loc) · 49.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Browser, BrowserContext, Page } from "playwright-core";
import { v4 as uuidv4 } from "uuid";
import {
BrowserProviders,
HyperAgentConfig,
MCPConfig,
MCPServerConfig,
} from "@/types/config";
import { HyperAgentLLM, createLLMClient } from "@/llm/providers";
import {
ActionContext,
ActionType,
AgentActionDefinition,
ActionCacheOutput,
ActionCacheReplayResult,
RunFromActionCacheParams,
endTaskStatuses,
Task,
TaskOutput,
TaskParams,
TaskState,
TaskStatus,
} from "@/types";
import fs from "fs";
import {
CompleteActionDefinition,
DEFAULT_ACTIONS,
generateCompleteActionWithOutputDefinition,
} from "./actions";
import {
HyperbrowserProvider,
LocalBrowserProvider,
} from "../browser-providers";
import { HyperagentError } from "./error";
import { findElementWithInstruction } from "./shared/find-element";
import {
A11yDOMState,
AccessibilityNode,
isEncodedId,
} from "../context-providers/a11y-dom/types";
import { MCPClient } from "./mcp/client";
import { runAgentTask } from "./tools/agent";
import type {
HyperPage,
HyperVariable,
ActionCacheEntry,
AgentTaskOutput,
PerformOptions,
} from "../types/agent/types";
import { z } from "zod";
import { ErrorEmitter } from "../utils";
import { waitForSettledDOM } from "@/utils/waitForSettledDOM";
import { performance } from "perf_hooks";
import { ExamineDomResult } from "./examine-dom/types";
import { disposeAllCDPClients, resolveElement, dispatchCDPAction } from "@/cdp";
import { markDomSnapshotDirty } from "@/context-providers/a11y-dom/dom-cache";
import { setDebugOptions } from "@/debug/options";
import { initializeRuntimeContext } from "./shared/runtime-context";
import { performAction } from "./actions/shared/perform-action";
import { createScriptFromActionCache } from "./shared/action-cache-script";
import { attachCachedActionHelpers } from "./shared/action-cache-exec";
import { AgentDeps } from "@/types/agent/types";
export class HyperAgent<T extends BrowserProviders = "Local"> {
// aiAction configuration constants
private static readonly AIACTION_CONFIG = {
MAX_RETRIES: 10,
RETRY_DELAY_MS: 1000,
CLICK_TIMEOUT: 3500,
MAX_DEBUG_ELEMENTS_TO_DISPLAY: 20,
MAX_DEBUG_ELEMENTS_TO_STORE: 50,
MAX_LABEL_LENGTH: 60,
};
private llm: HyperAgentLLM;
private tasks: Record<string, TaskState> = {};
private tokenLimit = 128000;
private debug = false;
private mcpClient: MCPClient | undefined;
private browserProvider: T extends "Hyperbrowser"
? HyperbrowserProvider
: LocalBrowserProvider;
private browserProviderType: T;
private actions: Array<AgentActionDefinition> = [...DEFAULT_ACTIONS];
private cdpActionsEnabled: boolean;
private actionCacheByTaskId: Record<string, ActionCacheOutput> = {};
public browser: Browser | null = null;
public context: BrowserContext | null = null;
private _currentPage: Page | null = null;
private _variables: Record<string, HyperVariable> = {};
private errorEmitter: ErrorEmitter;
public get currentPage(): HyperPage | null {
if (this._currentPage) {
return this.setupHyperPage(this._currentPage);
}
return null;
}
public set currentPage(page: Page) {
this._currentPage = page;
}
constructor(params: HyperAgentConfig<T> = {}) {
if (!params.llm) {
if (process.env.OPENAI_API_KEY) {
this.llm = createLLMClient({
provider: "openai",
model: "gpt-4o",
temperature: 0,
});
} else {
throw new HyperagentError("No LLM provider provided", 400);
}
} else if (typeof params.llm === "object" && "provider" in params.llm) {
// It's an LLMConfig
this.llm = createLLMClient(params.llm);
} else {
// It's already a HyperAgentLLM instance
this.llm = params.llm;
}
this.browserProviderType = (params.browserProvider ?? "Local") as T;
setDebugOptions(params.debugOptions, this.debug);
// TODO(Phase4): This legacy provider branch will be replaced by connector configs.
this.browserProvider = (
this.browserProviderType === "Hyperbrowser"
? new HyperbrowserProvider({
...(params.hyperbrowserConfig ?? {}),
debug: params.debug,
})
: new LocalBrowserProvider(params.localConfig)
) as T extends "Hyperbrowser" ? HyperbrowserProvider : LocalBrowserProvider;
if (params.customActions) {
params.customActions.forEach(this.registerAction, this);
}
this.debug = params.debug ?? false;
this.cdpActionsEnabled = params.cdpActions ?? true;
this.errorEmitter = new ErrorEmitter();
}
/**
* This is just exposed as a utility function. You don't need to call it explicitly.
* @returns A reference to the current rebrowser-playwright browser instance.
*/
public async initBrowser(): Promise<Browser> {
if (!this.browser) {
this.browser = await this.browserProvider.start();
if (
this.browserProviderType === "Hyperbrowser" &&
this.browser.contexts().length > 0
) {
this.context = this.browser.contexts()[0];
} else {
this.context = await this.browser.newContext({
viewport: null,
});
}
// Listen for new pages (tabs/popups)
this.context.on("page", () => {
if (this.debug) {
console.log("New tab/popup detected");
}
// Note: We used to auto-switch this._currentPage here, but that breaks
// scoped page interactions. If a user is awaiting pageA.ai(), and a new
// tab opens, we don't want pageA to suddenly become pageB.
// The user or the specific task logic should handle tab switching if desired.
});
return this.browser;
}
return this.browser;
}
/**
* Use this function instead of accessing this.actions directly.
* This function configures if there is a need for an output schema as a part of the complete action.
* @param outputSchema
* @returns
*/
private getActions(
outputSchema?: z.ZodType<any>
): Array<AgentActionDefinition> {
if (outputSchema) {
return [
...this.actions,
generateCompleteActionWithOutputDefinition(outputSchema),
];
} else {
return [...this.actions, CompleteActionDefinition];
}
}
/**
* Get all variables
* @returns Record of variables
*/
public getVariables(): Record<string, HyperVariable> {
return this._variables;
}
/**
* Set a variable
* @param key Key of the variable
* @param value Value of the variable
*/
public addVariable(variable: HyperVariable): void {
this._variables[variable.key] = variable;
}
/**
* Get a variable
* @param key Key of the variable
* @returns Value of the variable
*/
public getVariable(key: string): HyperVariable | undefined {
return this._variables[key];
}
/**
* Delete a variable
* @param key Key of the variable
*/
public deleteVariable(key: string): void {
delete this._variables[key];
}
public getActionCache(taskId: string): ActionCacheOutput | null {
const cache = this.actionCacheByTaskId[taskId];
if (!cache) return null;
return {
...cache,
steps: [...cache.steps],
};
}
/**
* Get all pages in the context
* @returns Array of HyperPage objects
*/
public async getPages(): Promise<HyperPage[]> {
if (!this.browser) {
await this.initBrowser();
}
if (!this.context) {
throw new HyperagentError("No context found");
}
return this.context.pages().map(this.setupHyperPage.bind(this), this);
}
/**
* Create a new page in the context
* @returns HyperPage object
*/
public async newPage(): Promise<HyperPage> {
if (!this.browser) {
await this.initBrowser();
}
if (!this.context) {
throw new HyperagentError("No context found");
}
const page = await this.context.newPage();
return this.setupHyperPage(page);
}
/**
* Close the agent and all associated resources
*/
public async closeAgent(): Promise<void> {
await disposeAllCDPClients().catch((error) => {
console.warn("[HyperAgent] Failed to dispose CDP clients:", error);
});
for (const taskId in this.tasks) {
const task = this.tasks[taskId];
if (!endTaskStatuses.has(task.status)) {
task.status = TaskStatus.CANCELLED;
}
}
if (this.mcpClient) {
await this.mcpClient.disconnect();
this.mcpClient = undefined;
}
if (this.browser) {
await this.browserProvider.close();
this.browser = null;
this.context = null;
}
}
/**
* Get the current page or create a new one if none exists
* @returns The current page
*/
public async getCurrentPage(): Promise<Page> {
if (!this.browser) {
await this.initBrowser();
}
if (!this.context) {
throw new HyperagentError("No context found");
}
// Poll context for new pages to catch any that opened since the last check
// This handles race conditions where the 'page' event might not have fired yet
// or where we missed it during a heavy operation.
const pages = this.context.pages();
if (pages.length > 0) {
const lastPage = pages[pages.length - 1];
// If the last page is different and not closed, switch to it
// We prefer the newest page as it's likely the result of the user's last action
if (lastPage && !lastPage.isClosed() && lastPage !== this._currentPage) {
if (this.debug) {
console.log(
`[HyperAgent] Polling detected new page, switching focus: ${lastPage.url()}`
);
}
this._currentPage = lastPage;
}
}
if (!this.currentPage || this.currentPage.isClosed()) {
this._currentPage = await this.context.newPage();
return this.setupHyperPage(this._currentPage);
}
return this.currentPage;
}
/**
* Get task control object for a specific task
* @param taskId ID of the task
* @returns Task control object
*/
private getTaskControl(taskId: string): Task {
const taskState = this.tasks[taskId];
if (!taskState) {
throw new HyperagentError(`Task ${taskId} not found`);
}
return {
id: taskId,
getStatus: () => taskState.status,
pause: () => {
if (taskState.status === TaskStatus.RUNNING) {
taskState.status = TaskStatus.PAUSED;
}
return taskState.status;
},
resume: () => {
if (taskState.status === TaskStatus.PAUSED) {
taskState.status = TaskStatus.RUNNING;
}
return taskState.status;
},
cancel: () => {
if (taskState.status !== TaskStatus.COMPLETED) {
taskState.status = TaskStatus.CANCELLED;
}
return taskState.status;
},
emitter: this.errorEmitter,
};
}
/**
* Execute a task asynchronously and return a Task control object
* @param task The task to execute
* @param params Optional parameters for the task
* @param initPage Optional page to use for the task
* @returns A promise that resolves to a Task control object for managing the running task
*/
public async executeTaskAsync(
task: string,
params?: TaskParams,
initPage?: Page
): Promise<Task> {
const taskId = uuidv4();
let activeTaskPage = initPage || (await this.getCurrentPage());
// Follow new tabs opened by the current active page
const onPage = async (newPage: Page) => {
try {
const opener = await newPage.opener();
if (opener === activeTaskPage) {
if (this.debug) {
console.log(
`[HyperAgent] Task following new tab: ${newPage.url()}`
);
}
activeTaskPage = newPage;
}
} catch {
// Ignore
}
};
this.context?.on("page", onPage);
const cleanup = () => this.context?.off("page", onPage);
const taskState: TaskState = {
id: taskId,
task: task,
status: TaskStatus.PENDING,
startingPage: activeTaskPage,
steps: [],
};
this.tasks[taskId] = taskState;
const mergedParams = params ?? {};
runAgentTask(
{
llm: this.llm,
actions: this.getActions(mergedParams.outputSchema),
tokenLimit: this.tokenLimit,
debug: this.debug,
mcpClient: this.mcpClient,
variables: this._variables,
cdpActions: this.cdpActionsEnabled,
activePage: async () => activeTaskPage,
},
taskState,
mergedParams
)
.then((result) => {
this.actionCacheByTaskId[taskId] = result.actionCache;
cleanup();
})
.catch((error: Error) => {
cleanup();
// Retrieve the correct state to update
const failedTaskState = this.tasks[taskId];
if (failedTaskState) {
failedTaskState.status = TaskStatus.FAILED;
failedTaskState.error = error.message;
// Emit error on the central emitter, including the taskId
this.errorEmitter.emit("error", error);
} else {
// Fallback if task state somehow doesn't exist
console.error(
`Task state ${taskId} not found during error handling.`
);
}
});
return this.getTaskControl(taskId);
}
/**
* Execute a task and wait for completion
* @param task The task to execute
* @param params Optional parameters for the task
* @param initPage Optional page to use for the task
* @returns A promise that resolves to the task output
*/
public async executeTask(
task: string,
params?: TaskParams,
initPage?: Page
): Promise<AgentTaskOutput> {
const taskId = uuidv4();
let activeTaskPage = initPage || (await this.getCurrentPage());
// Follow new tabs opened by the current active page
const onPage = async (newPage: Page) => {
try {
const opener = await newPage.opener();
if (opener === activeTaskPage) {
if (this.debug) {
console.log(
`[HyperAgent] Task following new tab: ${newPage.url()}`
);
}
activeTaskPage = newPage;
}
} catch {
// Ignore
}
};
this.context?.on("page", onPage);
const taskState: TaskState = {
id: taskId,
task: task,
status: TaskStatus.PENDING,
startingPage: activeTaskPage,
steps: [],
};
this.tasks[taskId] = taskState;
try {
const mergedParams = params ?? {};
const result = await runAgentTask(
{
llm: this.llm,
actions: this.getActions(mergedParams?.outputSchema),
tokenLimit: this.tokenLimit,
debug: this.debug,
mcpClient: this.mcpClient,
variables: this._variables,
cdpActions: this.cdpActionsEnabled,
activePage: async () => activeTaskPage,
},
taskState,
mergedParams
);
this.context?.off("page", onPage);
this.actionCacheByTaskId[taskId] = result.actionCache;
return result;
} catch (error) {
this.context?.off("page", onPage);
taskState.status = TaskStatus.FAILED;
throw error;
}
}
public async runFromActionCache(
cache: ActionCacheOutput,
pageOrGetter: Page | (() => Page),
params?: RunFromActionCacheParams
): Promise<ActionCacheReplayResult> {
const replayId = uuidv4();
const maxXPathRetries = params?.maxXPathRetries ?? 3;
const debug = params?.debug ?? this.debug;
const getPage = () =>
typeof pageOrGetter === "function" ? pageOrGetter() : pageOrGetter;
const stepsResult: ActionCacheReplayResult["steps"] = [];
let replayStatus: TaskStatus.COMPLETED | TaskStatus.FAILED =
TaskStatus.COMPLETED;
/**
* Type-safe dispatch for HyperPage perform* methods.
* Explicitly routes to the correct method with proper typing.
*
* Methods that require a value argument (second param): type, fill, press, selectOptionFromDropdown, scrollToPercentage
* Methods with only xpath and options: click, hover, check, uncheck, scrollToElement, nextChunk, prevChunk
*/
const dispatchPerformHelper = (
hp: HyperPage,
method: string,
xpath: string,
value: string | undefined,
options: PerformOptions
): Promise<TaskOutput> => {
switch (method) {
case "click":
return hp.performClick(xpath, options);
case "hover":
return hp.performHover(xpath, options);
case "type":
return hp.performType(xpath, value ?? "", options);
case "fill":
return hp.performFill(xpath, value ?? "", options);
case "press":
return hp.performPress(xpath, value ?? "", options);
case "selectOptionFromDropdown":
return hp.performSelectOption(xpath, value ?? "", options);
case "check":
return hp.performCheck(xpath, options);
case "uncheck":
return hp.performUncheck(xpath, options);
case "scrollToElement":
return hp.performScrollToElement(xpath, options);
case "scrollToPercentage":
return hp.performScrollToPercentage(xpath, value ?? "", options);
case "nextChunk":
return hp.performNextChunk(xpath, options);
case "prevChunk":
return hp.performPrevChunk(xpath, options);
default:
throw new Error(`Unknown perform helper method: ${method}`);
}
};
/** Set of valid method names that can be dispatched */
const validHelperMethods = new Set([
"click",
"fill",
"type",
"press",
"selectOptionFromDropdown",
"check",
"uncheck",
"hover",
"scrollToElement",
"scrollToPercentage",
"nextChunk",
"prevChunk",
]);
for (const step of [...cache.steps].sort(
(a, b) => a.stepIndex - b.stepIndex
)) {
const page = getPage();
const hyperPage = page as HyperPage;
let result: TaskOutput;
if (step.actionType === "goToUrl") {
const url =
(step.arguments && step.arguments[0]) ||
(step.actionParams as any)?.url ||
"";
if (!url || typeof url !== "string") {
result = {
taskId: cache.taskId,
status: TaskStatus.FAILED,
steps: [],
output: "Missing URL for goToUrl",
};
} else {
await hyperPage.goto(url, { waitUntil: "domcontentloaded" });
await waitForSettledDOM(hyperPage);
markDomSnapshotDirty(hyperPage);
result = {
taskId: cache.taskId,
status: TaskStatus.COMPLETED,
steps: [],
output: `Navigated to ${url}`,
replayStepMeta: {
usedCachedAction: true,
fallbackUsed: false,
retries: 0,
cachedXPath: null,
fallbackXPath: null,
fallbackElementId: null,
},
};
}
} else if (step.actionType === "complete") {
result = {
taskId: cache.taskId,
status: TaskStatus.COMPLETED,
steps: [],
output: "Task Complete",
replayStepMeta: {
usedCachedAction: true,
fallbackUsed: false,
retries: 0,
cachedXPath: null,
fallbackXPath: null,
fallbackElementId: null,
},
};
} else if (step.actionType === "refreshPage") {
await hyperPage.reload({ waitUntil: "domcontentloaded" });
await waitForSettledDOM(hyperPage);
markDomSnapshotDirty(hyperPage);
result = {
taskId: cache.taskId,
status: TaskStatus.COMPLETED,
steps: [],
output: "Page refreshed",
actionCache: {
taskId: cache.taskId,
createdAt: cache.createdAt,
status: TaskStatus.COMPLETED,
steps: [],
},
replayStepMeta: {
usedCachedAction: true,
fallbackUsed: false,
retries: 0,
cachedXPath: null,
fallbackXPath: null,
fallbackElementId: null,
},
};
} else if (step.actionType === "wait") {
const durationRaw =
(step.arguments && step.arguments[0]) ||
(step.actionParams as any)?.duration;
const durationMs =
typeof durationRaw === "number"
? durationRaw
: Number.parseInt(String(durationRaw ?? ""), 10);
const waitMs = Number.isFinite(durationMs) ? durationMs : 1000;
await hyperPage.waitForTimeout(waitMs);
result = {
taskId: cache.taskId,
status: TaskStatus.COMPLETED,
steps: [],
output: `Waited ${waitMs}ms`,
actionCache: {
taskId: cache.taskId,
createdAt: cache.createdAt,
status: TaskStatus.COMPLETED,
steps: [],
},
replayStepMeta: {
usedCachedAction: true,
fallbackUsed: false,
retries: 0,
cachedXPath: null,
fallbackXPath: null,
fallbackElementId: null,
},
};
} else if (step.actionType === "extract") {
try {
if (!step.instruction) {
throw new Error("Missing objective/instruction for extract action");
}
const extractResult = await hyperPage.extract(step.instruction);
result = {
taskId: cache.taskId,
status: TaskStatus.COMPLETED,
steps: [],
output:
typeof extractResult === "string"
? extractResult
: JSON.stringify(extractResult),
replayStepMeta: {
usedCachedAction: true,
fallbackUsed: false,
retries: 0,
cachedXPath: null,
fallbackXPath: null,
fallbackElementId: null,
},
};
} catch (err: any) {
result = {
taskId: cache.taskId,
status: TaskStatus.FAILED,
steps: [],
output: `Extract failed: ${err?.message || String(err)}`,
replayStepMeta: {
usedCachedAction: true,
fallbackUsed: false,
retries: 0,
cachedXPath: null,
fallbackXPath: null,
fallbackElementId: null,
},
};
}
} else if (step.actionType === "analyzePdf") {
result = {
taskId: cache.taskId,
status: TaskStatus.FAILED,
steps: [],
output: "analyzePdf replay is not supported in runFromActionCache.",
replayStepMeta: {
usedCachedAction: true,
fallbackUsed: false,
retries: 0,
cachedXPath: null,
fallbackXPath: null,
fallbackElementId: null,
},
};
} else {
const method = step.method;
if (method && validHelperMethods.has(method)) {
const options: PerformOptions = {
performInstruction: step.instruction ?? null,
maxSteps: maxXPathRetries,
};
if (step.frameIndex !== null && step.frameIndex !== undefined) {
options.frameIndex = step.frameIndex;
}
const valueArg = step.arguments?.[0];
result = await dispatchPerformHelper(
hyperPage,
method,
step.xpath ?? "",
valueArg,
options
);
} else if (step.instruction) {
result = await hyperPage.perform(step.instruction);
} else {
result = {
taskId: cache.taskId,
status: TaskStatus.FAILED,
steps: [],
output: `Cannot replay action type "${step.actionType}" without instruction`,
replayStepMeta: {
usedCachedAction: false,
fallbackUsed: false,
retries: 0,
cachedXPath: null,
fallbackXPath: null,
fallbackElementId: null,
},
};
}
}
const finalMeta = result.replayStepMeta;
const finalSuccess = result.status === TaskStatus.COMPLETED;
stepsResult.push({
stepIndex: step.stepIndex,
actionType: step.actionType,
usedXPath: finalMeta?.usedCachedAction ?? false,
fallbackUsed: finalMeta?.fallbackUsed ?? false,
cachedXPath: finalMeta?.cachedXPath ?? null,
fallbackXPath: finalMeta?.fallbackXPath ?? null,
fallbackElementId: finalMeta?.fallbackElementId ?? null,
retries: finalMeta?.retries ?? 0,
success: finalSuccess,
message:
result.output ||
(finalSuccess ? "Completed" : "Failed to execute cached action"),
});
if (!finalSuccess) {
replayStatus = TaskStatus.FAILED;
break;
}
}
const replayResult: ActionCacheReplayResult = {
replayId,
sourceTaskId: cache.taskId,
steps: stepsResult,
status: replayStatus,
};
if (debug) {
const debugDir = "debug/action-cache";
fs.mkdirSync(debugDir, { recursive: true });
fs.writeFileSync(
`${debugDir}/replay-${replayId}.json`,
JSON.stringify(replayResult, null, 2)
);
}
return replayResult;
}
/**
* Find element with retry logic
* Retries element finding with DOM refetch until element is found or max retries reached
*
* @param instruction Natural language instruction for the action
* @param page The page to search on
* @param maxRetries Maximum number of retry attempts
* @param retryDelayMs Delay between retries in milliseconds
* @returns Object containing the found element, DOM state, and element map
* @throws Error if element is not found after all retries
*/
private async findElementWithRetry(
instruction: string,
page: Page,
maxRetries: number,
retryDelayMs: number,
startTime: string
): Promise<{
element: ExamineDomResult;
domState: A11yDOMState;
elementMap: Map<string, AccessibilityNode>;
llmResponse: { rawText: string; parsed: unknown };
}> {
// Delegate to shared utility
const result = await findElementWithInstruction(
instruction,
page,
this.llm,
{
maxRetries,
retryDelayMs,
debug: this.debug,
}
);
// Check if element was found
if (result.success && result.element) {
// Success - return the result
return {
element: result.element,
domState: result.domState,
elementMap: result.elementMap,
llmResponse: result.llmResponse!,
};
}
// Element not found after all retries - handle error case
if (this.debug) {
console.error(
`[aiAction] No elements found for instruction: "${instruction}" after ${maxRetries} attempts`
);
console.error(`[aiAction] Current URL: ${page.url()}`);
console.error(
`[aiAction] Total elements in final a11y tree: ${result.domState.elements.size}`
);
// Write debug data to files before throwing error
await this.writeDebugData({
instruction,
page,
startTime,
domState: result.domState,
elementMap: result.elementMap,
llmResponse: result.llmResponse,
error: new HyperagentError(
`No elements found for instruction: "${instruction}" after ${maxRetries} retry attempts.`,
404
),
success: false,
});
}
throw new HyperagentError(
`No elements found for instruction: "${instruction}" after ${maxRetries} retry attempts. The instruction may be too vague, the element may not exist, or the page may not have fully loaded.`,
404
);
}
private async writeDebugData(params: {
instruction: string;
page: Page;
startTime: string;
domState: Awaited<
ReturnType<typeof import("../context-providers/a11y-dom").getA11yDOM>
> | null;
elementMap: Map<string, AccessibilityNode> | null;
element?: {
elementId: string;
method: string;
arguments: unknown[];
xpath?: string;
};
llmResponse?: {
rawText: string;
parsed: unknown;
};
error?: unknown;
success: boolean;
}): Promise<void> {
if (!this.debug || !params.domState || !params.elementMap) {
return;
}
const { writeAiActionDebug } = await import("../utils/debugWriter");
try {
const screenshot = await params.page
.screenshot({ type: "png" })
.catch(() => null);
if (params.success && params.element) {
// Success case - write found element data
await writeAiActionDebug({
instruction: params.instruction,
url: params.page.url(),
timestamp: params.startTime,
domElementCount: params.domState.elements.size,
domTree: params.domState.domState,
screenshot: screenshot || undefined,
foundElement: {
elementId: params.element.elementId,
method: params.element.method,
arguments: params.element.arguments,
xpath: params.element.xpath,
},
llmResponse: params.llmResponse,
success: true,
frameDebugInfo: params.domState.frameDebugInfo,
});
} else {
// Error case - write available elements
const availableElements = this.collectInteractiveElements(
params.elementMap,
HyperAgent.AIACTION_CONFIG.MAX_DEBUG_ELEMENTS_TO_STORE
);
await writeAiActionDebug({
instruction: params.instruction,
url: params.page.url(),
timestamp: params.startTime,
domElementCount: params.domState.elements.size,
domTree: params.domState.domState,
screenshot: screenshot || undefined,
availableElements,
llmResponse: params.llmResponse,
error: {
message:
params.error instanceof Error
? params.error.message
: String(params.error),
stack:
params.error instanceof Error ? params.error.stack : undefined,
},
success: false,
frameDebugInfo: params.domState.frameDebugInfo,
});
}
} catch (debugError) {
console.error(`[aiAction] Failed to write debug data:`, debugError);
}
}
/**
* Collect interactive elements from element map for debugging
* Extracts elements with interactive roles (button, link, textbox, etc.)