-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathaction.ts
More file actions
90 lines (77 loc) · 2.44 KB
/
action.ts
File metadata and controls
90 lines (77 loc) · 2.44 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
import fs from "fs";
import prettier from "prettier";
import { HyperAgentConfig } from "@/types";
export function initActionScript(
actionLogFile: string,
task: string,
agentConfig?: HyperAgentConfig<"Local" | "Hyperbrowser">,
) {
let agentConfigString: string;
let llmComment = "";
if (agentConfig) {
const configCopy = { ...agentConfig }; // Create a shallow copy to modify
if (configCopy.llm) {
const llm = configCopy.llm as any;
const llmClassName = llm.constructor?.name || "LLM";
const llmParams = JSON.stringify(llm, null, 2);
llmComment = `
// The agent's LLM configuration has been omitted as it cannot be reliably stringified.
// It was an instance of '${llmClassName}'.
// You may need to manually instantiate it. The original parameters were:
// Note: The following parameters are from JSON.stringify and may be an incomplete representation of the class instance.
// ${llmParams.replace(/\n/g, "\n // ")}
`;
delete configCopy.llm;
}
agentConfigString = JSON.stringify(configCopy, null, 2);
} else {
agentConfigString = "";
}
fs.writeFileSync(
actionLogFile,
`
/*
This script is generated by Hyperagent.
It is used to execute the task and log the actions.
Task: ${task}
*/
import { HyperAgent } from "@hyperbrowser/agent";
import { waitForElementToBeEnabled, waitForElementToBeStable } from "@hyperbrowser/agent/actions";
import { parseMarkdown, sleep } from "@hyperbrowser/agent/utils";
import { VariableExtractionOutput, HyperVariable } from "@hyperbrowser/agent/types";
(async () => {
${llmComment}
const agent = new HyperAgent(${agentConfigString});
const page = await agent.newPage();
if (!page) {
throw new Error("No page found");
}
const ctx = {
page,
llm: agent.llm,
variables: {} as Record<string, HyperVariable>,
};
`,
);
// Add main execution function
fs.appendFileSync(
actionLogFile,
`
` + `\n\n`,
);
}
export async function wrapUpActionScript(actionLogFile: string) {
fs.appendFileSync(
actionLogFile,
`
await agent.closeAgent();
console.log("Action script complete");
`,
);
fs.appendFileSync(actionLogFile, `})();`);
const formatted = await prettier.format(
fs.readFileSync(actionLogFile, "utf-8"),
{ filepath: actionLogFile },
);
fs.writeFileSync(actionLogFile, formatted);
}