agents
Version:
A home for your AI agents
70 lines (69 loc) • 2.27 kB
JavaScript
import { createBrowserRuntime } from "./ai.js";
import { z } from "zod";
import { toolDefinition } from "@tanstack/ai";
//#region src/browser/tanstack-ai.ts
/**
* Create TanStack AI tools for browser automation via CDP code mode.
*
* Returns an array with a single durable `browser_execute` `ServerTool`
* backed by the same codemode runtime as `agents/browser/ai` — the model
* writes TypeScript against the `cdp` connector and browser sessions
* survive pauses.
*
* The stateless Quick Action tools are not surfaced through this TanStack
* wrapper (it exposes only `browser_execute`); use `createQuickActionTools`
* from `agents/browser/ai` if you want them.
*
* @example
* ```ts
* import { createBrowserTools } from "agents/browser/tanstack-ai";
* import { chat } from "@tanstack/ai";
*
* // inside a Durable Object / Agent:
* const browserTools = createBrowserTools({
* ctx: this.ctx,
* browser: this.env.BROWSER,
* loader: this.env.LOADER,
* });
*
* const stream = chat({
* adapter: openaiText("gpt-4o"),
* tools: [...browserTools, ...otherTools],
* messages,
* });
* ```
*/
function createBrowserTools(options) {
const { tools } = createBrowserRuntime({
...options,
quickActions: false
});
const executeTool = tools.browser_execute;
return [toolDefinition({
name: "browser_execute",
description: typeof executeTool.description === "function" ? "" : executeTool.description ?? "",
inputSchema: z.object({ code: z.string().meta({ description: "TypeScript async arrow function that uses the cdp connector" }) })
}).server(async ({ code }) => {
if (!executeTool.execute) throw new Error("browser_execute tool is not executable");
const result = await executeTool.execute({ code }, {
toolCallId: crypto.randomUUID(),
messages: [],
context: {}
});
const modelOutput = await executeTool.toModelOutput?.({
toolCallId: crypto.randomUUID(),
input: { code },
output: result
});
if (modelOutput?.type === "error-text") throw new Error(modelOutput.value);
if (modelOutput?.type === "text") return {
...result,
result: modelOutput.value
};
if (modelOutput?.type === "json") return modelOutput.value;
return result;
})];
}
//#endregion
export { createBrowserTools };
//# sourceMappingURL=tanstack-ai.js.map