import "dotenv/config"; import axios from "axios"; import prompts from "prompts"; (async () => { const agentid = process.env.AGENT_ID ?? ( await prompts({ type: "text", name: "agentId", message: "enter your agent id", }) ).agentId; const requester = axios.create({ headers: { ["X-Phantombuster-Key"]: process.env.API_KEY ?? ( await prompts({ type: "text", name: "API_KEY", message: "enter your API key", }) ).API_KEY, ["Content-Type"]: "application/json", }, }); const MAX_TIME_TO_RUN = 10000; type FetchOutputResult = { containerId: string; status: string; output: string; outputPos: number; mostRecentEndedAt: number; isAgentRunning: boolean; canSoftAbort: boolean; }; async function getUntilRunStop( url: string, startTime: number ): Promise { const timeRunning = Date.now() - startTime; if (timeRunning > MAX_TIME_TO_RUN) { throw new Error("TIMEOUT: phantom run for too long"); } return await requester .get(url) .then((res) => res.data.status !== "finished" ? getUntilRunStop(url, startTime) : res.data ); } await requester .post<{ containerId: string }>( "https://api.phantombuster.com/api/v2/agents/launch", { id: agentid } ) .then((res) => res.data.containerId) .then(async () => { try { await getUntilRunStop( `https://api.phantombuster.com/api/v2/agents/fetch-output?id=${agentid}`, Date.now() ) .then((res) => res.output) .then(console.log); } catch (err) { console.error(err); console.log("stopping agent"); await requester.post( "https://api.phantombuster.com/api/v2/agents/stop", { id: agentid, } ); } }) .catch((err) => console.error(err.data, agentid)); })();