agents 0.15.0 → 0.16.1
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.
- package/dist/{agent-tool-types-VPsjVYL0.d.ts → agent-tool-types-NofdbL9X.d.ts} +57 -4
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-BGpgfpJT.d.ts → agent-tools-DLquv-dp.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/browser/ai.d.ts +211 -7
- package/dist/browser/ai.js +236 -25
- package/dist/browser/ai.js.map +1 -1
- package/dist/browser/index.d.ts +133 -69
- package/dist/browser/index.js +3 -2
- package/dist/browser/tanstack-ai.d.ts +17 -7
- package/dist/browser/tanstack-ai.js +25 -19
- package/dist/browser/tanstack-ai.js.map +1 -1
- package/dist/chat/index.d.ts +111 -5
- package/dist/chat/index.js +207 -35
- package/dist/chat/index.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +1 -1
- package/dist/{classPrivateFieldGet2-Beqsfu2Z.js → classPrivateFieldGet2-CZ7QjTXN.js} +5 -5
- package/dist/{classPrivateMethodInitSpec-B5ko1s2R.js → classPrivateMethodInitSpec-D-0__zd9.js} +2 -2
- package/dist/client.d.ts +19 -2
- package/dist/client.js +31 -11
- package/dist/client.js.map +1 -1
- package/dist/{compaction-helpers-BEUILPss.d.ts → compaction-helpers-DVcu5lPN.d.ts} +91 -12
- package/dist/connector-CrKhowfD.js +1291 -0
- package/dist/connector-CrKhowfD.js.map +1 -0
- package/dist/connector-v2M1zlZp.d.ts +659 -0
- package/dist/experimental/memory/session/index.d.ts +75 -12
- package/dist/experimental/memory/session/index.js +226 -21
- package/dist/experimental/memory/session/index.js.map +1 -1
- package/dist/experimental/memory/utils/index.d.ts +2 -2
- package/dist/{index-CPe1OtI0.d.ts → index-B7IbEeze.d.ts} +32 -1
- package/dist/index.d.ts +8 -2
- package/dist/index.js +119 -45
- package/dist/index.js.map +1 -1
- package/dist/mcp/client.d.ts +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +1 -1
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.d.ts +1 -1
- package/dist/react.d.ts +12 -1
- package/dist/react.js +101 -30
- package/dist/react.js.map +1 -1
- package/dist/{retries-CF_HKSlJ.d.ts → retries-CwlpAGet.d.ts} +35 -5
- package/dist/retries.d.ts +9 -5
- package/dist/retries.js +87 -1
- package/dist/retries.js.map +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/skills/index.js +2 -2
- package/dist/sub-routing.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/package.json +11 -11
- package/dist/shared-4CAYLCTO.d.ts +0 -34
- package/dist/shared-wyII629d.js +0 -432
- package/dist/shared-wyII629d.js.map +0 -1
package/dist/browser/ai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.js","names":[],"sources":["../../src/browser/ai.ts"],"sourcesContent":["import { tool } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport { z } from \"zod\";\nimport {\n createBrowserToolHandlers,\n SEARCH_DESCRIPTION,\n EXECUTE_DESCRIPTION,\n type BrowserToolsOptions\n} from \"./shared\";\n\nexport type { BrowserToolsOptions } from \"./shared\";\n\n/**\n * Create AI SDK tools for browser automation via CDP code mode.\n *\n * Returns a `ToolSet` with `search` (query the CDP spec) and\n * `execute` (run CDP commands against a live browser).\n *\n * @example\n * ```ts\n * import { createBrowserTools } from \"agents/browser/ai\";\n * import { generateText } from \"ai\";\n *\n * const browserTools = createBrowserTools({\n * browser: env.BROWSER,\n * loader: env.LOADER,\n * });\n *\n * const result = await generateText({\n * model,\n * tools: { ...browserTools, ...otherTools },\n * messages,\n * });\n * ```\n */\nexport function createBrowserTools(options: BrowserToolsOptions): ToolSet {\n const handlers = createBrowserToolHandlers(options);\n\n return {\n browser_search: tool({\n description: SEARCH_DESCRIPTION,\n inputSchema: z.object({\n code: z\n .string()\n .describe(\"JavaScript async arrow function that queries the CDP spec\")\n }),\n execute: async ({ code }) => {\n const result = await handlers.search(code);\n if (result.isError) {\n throw new Error(result.text);\n }\n return result.text;\n }\n }),\n\n browser_execute: tool({\n description: EXECUTE_DESCRIPTION,\n inputSchema: z.object({\n code: z\n .string()\n .describe(\"JavaScript async arrow function that uses the cdp helper\")\n }),\n execute: async ({ code }) => {\n const result = await handlers.execute(code);\n if (result.isError) {\n throw new Error(result.text);\n }\n return result.text;\n }\n })\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,mBAAmB,SAAuC;CACxE,MAAM,WAAW,0BAA0B,OAAO;CAElD,OAAO;EACL,gBAAgB,KAAK;GACnB,aAAa;GACb,aAAa,EAAE,OAAO,EACpB,MAAM,EACH,OAAO,CAAC,CACR,SAAS,2DAA2D,EACzE,CAAC;GACD,SAAS,OAAO,EAAE,WAAW;IAC3B,MAAM,SAAS,MAAM,SAAS,OAAO,IAAI;IACzC,IAAI,OAAO,SACT,MAAM,IAAI,MAAM,OAAO,IAAI;IAE7B,OAAO,OAAO;GAChB;EACF,CAAC;EAED,iBAAiB,KAAK;GACpB,aAAa;GACb,aAAa,EAAE,OAAO,EACpB,MAAM,EACH,OAAO,CAAC,CACR,SAAS,0DAA0D,EACxE,CAAC;GACD,SAAS,OAAO,EAAE,WAAW;IAC3B,MAAM,SAAS,MAAM,SAAS,QAAQ,IAAI;IAC1C,IAAI,OAAO,SACT,MAAM,IAAI,MAAM,OAAO,IAAI;IAE7B,OAAO,OAAO;GAChB;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"ai.js","names":["agentContext"],"sources":["../../src/browser/ai.ts"],"sourcesContent":["import { tool, type ToolSet } from \"ai\";\nimport { z } from \"zod\";\nimport {\n createCodemodeRuntime,\n DynamicWorkerExecutor,\n truncateResult,\n type CodemodeRuntimeHandle\n} from \"@cloudflare/codemode\";\nimport { __DO_NOT_USE_WILL_BREAK__agentContext as agentContext } from \"../internal_context\";\nimport type { BrowserBinding } from \"./browser-run\";\nimport {\n browserContent,\n browserExtract,\n browserLinks,\n browserMarkdown,\n browserScrape,\n type QuickActionBinding,\n type QuickActionCommonOptions,\n type QuickActionPage\n} from \"./quick-actions\";\nimport {\n BrowserConnector,\n type BrowserConnectorOptions,\n type BrowserConnectorSessionOptions\n} from \"./connector\";\nimport {\n DurableBrowserSessionStore,\n type BrowserSessionStore\n} from \"./session-manager\";\n\nexport interface CreateBrowserToolsOptions {\n /**\n * Durable Object state. The codemode runtime that backs the browser tool\n * lives in a facet of this DO, and browser session ids are stored in its\n * storage — so the tool must be created from inside a Durable Object\n * (e.g. an Agent).\n *\n * Optional: when omitted, it is resolved from the current Agent via\n * `getCurrentAgent()`, so inside an Agent method you can just pass `browser`\n * and `loader`. Pass it explicitly outside an Agent context.\n *\n * The worker must export the `CodemodeRuntime` class (the\n * `@cloudflare/codemode/vite` plugin does this automatically, or add\n * `export { CodemodeRuntime } from \"@cloudflare/codemode\"` to your entry).\n */\n ctx?: DurableObjectState;\n\n /**\n * WorkerLoader binding for sandboxed code execution.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader: WorkerLoader;\n\n /**\n * Browser Rendering binding (Fetcher).\n *\n * This is the primary way to connect — works both locally in\n * `wrangler dev` and when deployed to Cloudflare Workers.\n *\n * Requires `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc.\n */\n browser?: BrowserBinding;\n\n /**\n * Optional CDP base URL override (e.g. `http://localhost:9222`).\n *\n * Use when connecting to a manually managed Chrome instance or\n * a remote CDP endpoint behind a tunnel.\n */\n cdpUrl?: string;\n\n /**\n * Headers to send with CDP URL discovery requests.\n * Useful when the CDP endpoint requires authentication\n * (e.g. Cloudflare Access headers).\n */\n cdpHeaders?: Record<string, string>;\n\n /**\n * Browser session lifecycle (binding-backed only). Defaults to one fresh\n * session per codemode execution (`one-shot`).\n */\n session?: BrowserConnectorSessionOptions;\n\n /**\n * Durable store for Browser Run session ids. Defaults to a\n * {@link DurableBrowserSessionStore} over `ctx.storage`.\n */\n store?: BrowserSessionStore;\n\n /**\n * Sandbox execution timeout in milliseconds. Defaults to 30000 (30s).\n * Also used as the per-CDP-command timeout.\n */\n timeout?: number;\n\n /**\n * Codemode runtime name — the durable identity of the tool's executions\n * and snippets. Defaults to `\"browser\"`.\n */\n name?: string;\n\n /**\n * Also expose stateless {@link createQuickActionTools | Quick Action} tools\n * (`browser_markdown`, `browser_extract`, …) alongside the durable\n * `browser_execute` tool.\n *\n * Enabled by default whenever a Browser Run `browser` binding is available\n * (they share it). Pass an object to configure them, or `false` to disable.\n * The Quick Action binding defaults to `browser`; override it via\n * `quickActions.browser`. When only `cdpUrl` is set (no binding), the\n * defaults are skipped silently — pass `quickActions: { browser }` to force\n * them.\n */\n quickActions?:\n | boolean\n | {\n browser?: QuickActionBinding;\n actions?: QuickActionToolName[];\n maxChars?: number;\n options?: QuickActionCommonOptions;\n };\n}\n\n/**\n * The browser tool's moving parts, for hosts that need more than the tools:\n *\n * - `runtime` — the codemode runtime handle (approve/reject paused runs,\n * `expirePaused`, audit via `executions()`, snippets).\n * - `connector` — host-side session helpers: `sessionInfo()`,\n * `closeSession()`, and `sweep()` for a recurring cleanup task.\n * - `tools` — what `createBrowserTools` returns.\n */\nexport interface BrowserRuntime {\n runtime: CodemodeRuntimeHandle;\n connector: BrowserConnector;\n tools: ToolSet;\n}\n\nlet didWarnExperimental = false;\nlet didDebugQuickActionSkip = false;\n\n/**\n * The Durable Object state to build the runtime in: the explicit `ctx` if\n * given, otherwise the current Agent's `ctx` (via `getCurrentAgent()`), so\n * `createBrowserRuntime` can be called from an Agent method without threading\n * `this.ctx` through.\n */\nfunction resolveCtx(\n options: CreateBrowserToolsOptions\n): DurableObjectState | undefined {\n if (options.ctx) return options.ctx;\n const agent = agentContext.getStore()?.agent as\n | { ctx?: DurableObjectState }\n | undefined;\n return agent?.ctx;\n}\n\nfunction connectorOptions(\n options: CreateBrowserToolsOptions,\n ctx: DurableObjectState\n): BrowserConnectorOptions {\n if (options.cdpUrl) {\n return {\n cdpUrl: options.cdpUrl,\n cdpHeaders: options.cdpHeaders,\n timeout: options.timeout\n };\n }\n if (!options.browser) {\n throw new Error(\n \"Either 'browser' (Fetcher binding) or 'cdpUrl' must be provided\"\n );\n }\n return {\n browser: options.browser,\n store: options.store ?? new DurableBrowserSessionStore(ctx.storage),\n session: options.session,\n timeout: options.timeout\n };\n}\n\n/**\n * Create the browser codemode runtime: the `browser_execute` tool plus the\n * runtime handle and connector for host-side wiring (approvals, session info,\n * sweeps).\n *\n * @example\n * ```ts\n * export class MyAgent extends Agent<Env> {\n * get browser() {\n * return createBrowserRuntime({\n * ctx: this.ctx,\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * session: { mode: \"dynamic\" }\n * });\n * }\n *\n * @callable()\n * async closeBrowserSession() {\n * await this.browser.connector.closeSession();\n * }\n * }\n * ```\n */\nexport function createBrowserRuntime(\n options: CreateBrowserToolsOptions\n): BrowserRuntime {\n if (!didWarnExperimental) {\n didWarnExperimental = true;\n console.warn(\n \"[agents/browser] Browser tools are experimental and may change in a future release.\"\n );\n }\n\n const ctx = resolveCtx(options);\n if (!ctx) {\n throw new Error(\n \"createBrowserRuntime requires a Durable Object 'ctx' — pass it explicitly, or call from within an Agent so it can be resolved via getCurrentAgent()\"\n );\n }\n\n const connector = new BrowserConnector(ctx, connectorOptions(options, ctx));\n const runtime = createCodemodeRuntime({\n ctx,\n executor: new DynamicWorkerExecutor({\n loader: options.loader,\n timeout: options.timeout\n }),\n connectors: [connector],\n name: options.name ?? \"browser\",\n transformResult: truncateResult\n });\n\n const tools: ToolSet = { browser_execute: runtime.tool() };\n\n // Quick Actions ride the same `browser` binding, so they are on by default.\n // `env.BROWSER` satisfies both the CDP `BrowserBinding` (fetch) and the\n // `QuickActionBinding` (quickAction) surfaces; our narrower option type only\n // sees the former, so reuse it here unless an explicit binding wins.\n if (options.quickActions !== false) {\n const qa =\n options.quickActions == null || options.quickActions === true\n ? {}\n : options.quickActions;\n const quickActionBrowser =\n qa.browser ??\n (options.browser as unknown as QuickActionBinding | undefined);\n if (quickActionBrowser) {\n Object.assign(\n tools,\n createQuickActionTools({\n browser: quickActionBrowser,\n actions: qa.actions,\n maxChars: qa.maxChars,\n options: qa.options\n })\n );\n } else if (options.quickActions) {\n // Explicitly requested but no binding to back them.\n throw new Error(\n \"quickActions requires a Browser Run binding — set 'browser' (env.BROWSER) or 'quickActions.browser'\"\n );\n } else if (!didDebugQuickActionSkip) {\n // Defaulted on, but only `cdpUrl` is set: there is no binding to call\n // Quick Actions through, so they are skipped. Surface it once so a user\n // expecting `browser_markdown` et al. isn't left wondering.\n didDebugQuickActionSkip = true;\n console.debug(\n \"[agents/browser] Quick Action tools skipped — no Browser Run binding (only 'cdpUrl' is set). Pass 'browser' or 'quickActions.browser' to enable them.\"\n );\n }\n }\n\n return { runtime, connector, tools };\n}\n\n/**\n * Create AI SDK tools for browser automation via CDP code mode.\n *\n * Returns a `ToolSet` with a single durable `browser_execute` tool backed by\n * a codemode runtime: the model writes TypeScript against the `cdp` connector\n * (`cdp.send`, `cdp.attachToTarget`, `cdp.spec`, …), executions are recorded\n * for abort-and-replay, and browser sessions survive pauses.\n *\n * @example\n * ```ts\n * import { createBrowserTools } from \"agents/browser/ai\";\n * import { generateText } from \"ai\";\n *\n * // inside a Durable Object / Agent:\n * const browserTools = createBrowserTools({\n * ctx: this.ctx,\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * });\n *\n * const result = await generateText({\n * model,\n * tools: { ...browserTools, ...otherTools },\n * messages,\n * });\n * ```\n */\nexport function createBrowserTools(\n options: CreateBrowserToolsOptions\n): ToolSet {\n return createBrowserRuntime(options).tools;\n}\n\n/** A Quick Action exposed as an AI SDK tool. */\nexport type QuickActionToolName =\n | \"markdown\"\n | \"extract\"\n | \"links\"\n | \"scrape\"\n | \"content\";\n\nexport interface CreateQuickActionToolsOptions {\n /**\n * Browser Run binding with Quick Actions support (`env.BROWSER`). Requires a\n * Worker `compatibility_date` of `2026-03-24`+ and `remote: true` for local\n * `wrangler dev`.\n */\n browser: QuickActionBinding;\n\n /**\n * Which tools to expose. Defaults to the text-returning, model-friendly set\n * (`markdown`, `extract`, `links`, `scrape`). `content` (raw HTML) is opt-in\n * since it is large and rarely what a model wants.\n */\n actions?: QuickActionToolName[];\n\n /**\n * Bound every result to roughly this many characters before returning it to\n * the model, to protect the context window, preserving each result's shape:\n * text (markdown/content) is truncated to a string, oversized arrays\n * (links/scrape) are trimmed but stay arrays, and only an opaque oversized\n * object degrades to a truncated-preview summary. Set to `0` to disable.\n * Defaults to 50000.\n */\n maxChars?: number;\n\n /**\n * Common Browser Run options merged into every request — e.g. `cookies`,\n * `authenticate`, or `setExtraHTTPHeaders` for authenticated pages, and\n * `gotoOptions` / `viewport` for JavaScript-heavy pages. The model only ever\n * supplies the page (`url`/`html`) and action-specific fields; these\n * host-supplied options are never exposed to it.\n */\n options?: QuickActionCommonOptions;\n}\n\nconst DEFAULT_QUICK_ACTION_TOOLS: QuickActionToolName[] = [\n \"markdown\",\n \"extract\",\n \"links\",\n \"scrape\"\n];\n\nconst DEFAULT_QUICK_ACTION_MAX_CHARS = 50_000;\n\nconst pageInputSchema = z\n .object({\n url: z.string().url().optional().describe(\"URL of the page to load\"),\n html: z\n .string()\n .optional()\n .describe(\"Raw HTML to render instead of loading a URL\")\n })\n .refine((value) => Boolean(value.url) || Boolean(value.html), {\n message: \"Provide either 'url' or 'html'\"\n });\n\nfunction toPage(\n input: { url?: string; html?: string },\n options?: QuickActionCommonOptions\n): QuickActionPage {\n const page = input.url ? { url: input.url } : { html: input.html as string };\n return { ...options, ...page } as QuickActionPage;\n}\n\nfunction truncate(text: string, maxChars: number): string {\n if (maxChars <= 0 || text.length <= maxChars) return text;\n return `${text.slice(0, maxChars)}\\n\\n[truncated ${text.length - maxChars} characters]`;\n}\n\n/**\n * Keep a tool result within a rough character budget so a single browse cannot\n * blow the model's context window — while preserving the result's shape so the\n * model sees a consistent type across calls:\n *\n * - strings (markdown/content) are truncated to a string;\n * - arrays (links/scrape) are trimmed from the end but stay arrays;\n * - only an opaque oversized object (e.g. a sprawling `extract`) degrades to a\n * `{ truncated, note, preview }` summary, since it cannot be trimmed safely.\n */\nfunction boundResult(value: unknown, maxChars: number): unknown {\n if (maxChars <= 0) return value;\n if (typeof value === \"string\") return truncate(value, maxChars);\n let json: string;\n try {\n json = JSON.stringify(value);\n } catch {\n return value;\n }\n if (json.length <= maxChars) return value;\n if (Array.isArray(value)) {\n const trimmed = boundArray(value, maxChars);\n // If even the first element overflows the budget, `trimmed` is empty —\n // returning `[]` would read as \"no results\" rather than \"too large\", so\n // fall through to the explicit truncated-preview summary instead.\n if (trimmed.length > 0) return trimmed;\n }\n return {\n truncated: true,\n note: `Result is too large (${json.length} characters); narrow the request.`,\n preview: `${json.slice(0, maxChars)}…`\n };\n}\n\n/**\n * Take as many leading items as fit within `maxChars` (measured against their\n * JSON length), returning a trimmed array of the same element type. Silent by\n * design: the model gets fewer, valid items rather than a reshaped result.\n */\nfunction boundArray(value: unknown[], maxChars: number): unknown[] {\n const out: unknown[] = [];\n let size = 2; // the enclosing \"[]\"\n for (const item of value) {\n const itemSize = JSON.stringify(item).length + 1; // + a separating comma\n if (size + itemSize > maxChars) break;\n out.push(item);\n size += itemSize;\n }\n return out;\n}\n\n/**\n * Create AI SDK tools for Browser Run [Quick Actions](https://developers.cloudflare.com/browser-run/quick-actions/):\n * stateless one-shot browsing (read a page as Markdown, extract structured\n * data with AI, list links, scrape elements). Unlike `createBrowserTools`,\n * these need only the `browser` binding — no Durable Object, loader, or\n * sandbox — so they work from any Worker.\n *\n * @example\n * ```ts\n * import { createQuickActionTools } from \"agents/browser/ai\";\n *\n * const tools = createQuickActionTools({ browser: this.env.BROWSER });\n * const result = await generateText({ model, tools, messages });\n * ```\n */\nexport function createQuickActionTools(\n options: CreateQuickActionToolsOptions\n): ToolSet {\n const { browser } = options;\n const requestOptions = options.options;\n const enabled = new Set(options.actions ?? DEFAULT_QUICK_ACTION_TOOLS);\n const maxChars = options.maxChars ?? DEFAULT_QUICK_ACTION_MAX_CHARS;\n const tools: ToolSet = {};\n\n if (enabled.has(\"markdown\")) {\n tools.browser_markdown = tool({\n description:\n \"Load a web page (or render raw HTML) and return its content as Markdown. Best for reading articles, docs, or any page as text.\",\n inputSchema: pageInputSchema,\n execute: async (input) =>\n boundResult(\n await browserMarkdown(browser, toPage(input, requestOptions)),\n maxChars\n )\n });\n }\n\n if (enabled.has(\"extract\")) {\n tools.browser_extract = tool({\n description:\n \"Extract structured data from a web page using AI. Describe what you want in 'prompt'. Passing a JSON Schema in 'schema' is strongly recommended — without one the extractor often fails to produce JSON.\",\n inputSchema: z\n .object({\n url: z.string().url().optional().describe(\"URL of the page to load\"),\n html: z\n .string()\n .optional()\n .describe(\"Raw HTML to render instead of loading a URL\"),\n prompt: z\n .string()\n .optional()\n .describe(\"What to extract, in natural language\"),\n schema: z\n .unknown()\n .optional()\n .describe(\"Optional JSON Schema describing the desired output\")\n })\n .refine((value) => Boolean(value.url) || Boolean(value.html), {\n message: \"Provide either 'url' or 'html'\"\n })\n .refine((value) => Boolean(value.prompt) || Boolean(value.schema), {\n message: \"Provide either 'prompt' or 'schema'\"\n }),\n execute: async (input) =>\n boundResult(\n await browserExtract(browser, {\n ...toPage(input, requestOptions),\n prompt: input.prompt,\n response_format: input.schema\n ? { type: \"json_schema\", schema: input.schema }\n : undefined\n }),\n maxChars\n )\n });\n }\n\n if (enabled.has(\"links\")) {\n tools.browser_links = tool({\n description:\n \"Return every link found on a web page (including ones not visible). Useful for discovering pages to follow.\",\n inputSchema: pageInputSchema,\n execute: async (input) =>\n boundResult(\n await browserLinks(browser, toPage(input, requestOptions)),\n maxChars\n )\n });\n }\n\n if (enabled.has(\"scrape\")) {\n tools.browser_scrape = tool({\n description:\n \"Scrape specific elements from a web page by CSS selector. Returns the matched elements' text, HTML, and attributes.\",\n inputSchema: z\n .object({\n url: z.string().url().optional().describe(\"URL of the page to load\"),\n html: z\n .string()\n .optional()\n .describe(\"Raw HTML to render instead of loading a URL\"),\n selectors: z\n .array(z.string())\n .min(1)\n .describe(\"CSS selectors to extract\")\n })\n .refine((value) => Boolean(value.url) || Boolean(value.html), {\n message: \"Provide either 'url' or 'html'\"\n }),\n execute: async (input) =>\n boundResult(\n await browserScrape(browser, {\n ...toPage(input, requestOptions),\n elements: input.selectors.map((selector) => ({ selector }))\n }),\n maxChars\n )\n });\n }\n\n if (enabled.has(\"content\")) {\n tools.browser_content = tool({\n description:\n \"Load a web page and return its fully rendered HTML (after JavaScript runs). Prefer 'browser_markdown' unless you need the raw HTML.\",\n inputSchema: pageInputSchema,\n execute: async (input) =>\n boundResult(\n await browserContent(browser, toPage(input, requestOptions)),\n maxChars\n )\n });\n }\n\n return tools;\n}\n"],"mappings":";;;;;;AA4IA,IAAI,sBAAsB;AAC1B,IAAI,0BAA0B;;;;;;;AAQ9B,SAAS,WACP,SACgC;CAChC,IAAI,QAAQ,KAAK,OAAO,QAAQ;CAIhC,QAHcA,sCAAa,SAAS,CAAC,EAAE,MAAA,EAGzB;AAChB;AAEA,SAAS,iBACP,SACA,KACyB;CACzB,IAAI,QAAQ,QACV,OAAO;EACL,QAAQ,QAAQ;EAChB,YAAY,QAAQ;EACpB,SAAS,QAAQ;CACnB;CAEF,IAAI,CAAC,QAAQ,SACX,MAAM,IAAI,MACR,iEACF;CAEF,OAAO;EACL,SAAS,QAAQ;EACjB,OAAO,QAAQ,SAAS,IAAI,2BAA2B,IAAI,OAAO;EAClE,SAAS,QAAQ;EACjB,SAAS,QAAQ;CACnB;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,qBACd,SACgB;CAChB,IAAI,CAAC,qBAAqB;EACxB,sBAAsB;EACtB,QAAQ,KACN,qFACF;CACF;CAEA,MAAM,MAAM,WAAW,OAAO;CAC9B,IAAI,CAAC,KACH,MAAM,IA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ACF,aAAa,EACV,OAAO;GACN,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yBAAyB;GACnE,MAAM,EACH,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,6CAA6C;GACzD,WAAW,EACR,MAAM,EAAE,OAAO,CAAC,CAAC,CACjB,IAAI,CAAC,CAAC,CACN,SAAS,0BAA0B;EACxC,CAAC,CAAC,CACD,QAAQ,UAAU,QAAQ,MAAM,GAAG,KAAK,QAAQ,MAAM,IAAI,GAAG,EAC5D,SAAS,iCACX,CAAC;EACH,SAAS,OAAO,UACd,YACE,MAAM,cAAc,SAAS;GAC3B,GAAG,OAAO,OAAO,cAAc;GAC/B,UAAU,MAAM,UAAU,KAAK,cAAc,EAAE,SAAS,EAAE;EAC5D,CAAC,GACD,QACF;CACJ,CAAC;CAGH,IAAI,QAAQ,IAAI,SAAS,GACvB,MAAM,kBAAkB,KAAK;EAC3B,aACE;EACF,aAAa;EACb,SAAS,OAAO,UACd,YACE,MAAM,eAAe,SAAS,OAAO,OAAO,cAAc,CAAC,GAC3D,QACF;CACJ,CAAC;CAGH,OAAO;AACT"}
|
package/dist/browser/index.d.ts
CHANGED
|
@@ -1,82 +1,146 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
A as browserMarkdown,
|
|
3
|
+
B as BrowserTargetInfo,
|
|
4
|
+
C as QuickActionScrapeInput,
|
|
5
|
+
D as browserContent,
|
|
6
|
+
E as QuickActionSnapshot,
|
|
7
|
+
F as runQuickAction,
|
|
8
|
+
G as deleteBrowserSession,
|
|
9
|
+
H as connectBrowser,
|
|
10
|
+
I as BrowserBinding,
|
|
11
|
+
J as CdpAttachOptions,
|
|
12
|
+
K as getBrowserRecording,
|
|
13
|
+
L as BrowserRecording,
|
|
14
|
+
M as browserScrape,
|
|
15
|
+
N as browserScreenshot,
|
|
16
|
+
O as browserExtract,
|
|
17
|
+
P as browserSnapshot,
|
|
18
|
+
R as BrowserRenderingError,
|
|
19
|
+
S as QuickActionPage,
|
|
20
|
+
T as QuickActionScreenshotInput,
|
|
21
|
+
U as connectBrowserSession,
|
|
22
|
+
V as ConnectBrowserOptions,
|
|
23
|
+
W as createBrowserSession,
|
|
24
|
+
X as CdpSession,
|
|
25
|
+
Y as CdpSendOptions,
|
|
26
|
+
Z as connectUrl,
|
|
27
|
+
_ as QuickActionBinary,
|
|
28
|
+
a as BrowserConnectorSweepResult,
|
|
29
|
+
b as QuickActionExtractInput,
|
|
30
|
+
c as BrowserLiveViewUrl,
|
|
31
|
+
d as BrowserSessionLock,
|
|
32
|
+
f as BrowserSessionStore,
|
|
33
|
+
g as QuickAction,
|
|
34
|
+
h as StoredBrowserSession,
|
|
35
|
+
i as BrowserConnectorSweepOptions,
|
|
36
|
+
j as browserPdf,
|
|
37
|
+
k as browserLinks,
|
|
38
|
+
l as DEFAULT_EXEC_SWEEP_IDLE_MS,
|
|
39
|
+
m as DurableBrowserSessionStore,
|
|
40
|
+
n as BrowserConnectorOptions,
|
|
41
|
+
o as BrowserLiveView,
|
|
42
|
+
p as DEFAULT_SWEEP_IDLE_MS,
|
|
43
|
+
q as listBrowserTargets,
|
|
44
|
+
r as BrowserConnectorSessionOptions,
|
|
45
|
+
s as BrowserLiveViewTarget,
|
|
46
|
+
t as BrowserConnector,
|
|
47
|
+
u as LiveViewMode,
|
|
48
|
+
v as QuickActionBinding,
|
|
49
|
+
w as QuickActionScrapeResult,
|
|
50
|
+
x as QuickActionInput,
|
|
51
|
+
y as QuickActionCommonOptions,
|
|
52
|
+
z as BrowserSessionInfo
|
|
53
|
+
} from "../connector-v2M1zlZp.js";
|
|
54
|
+
import { CodemodeRuntime } from "@cloudflare/codemode";
|
|
8
55
|
|
|
9
|
-
//#region src/browser/
|
|
10
|
-
interface
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
56
|
+
//#region src/browser/spec.d.ts
|
|
57
|
+
interface SearchableCdpSpec {
|
|
58
|
+
domains: Array<{
|
|
59
|
+
name: string;
|
|
60
|
+
description?: string;
|
|
61
|
+
commands: Array<{
|
|
62
|
+
name: string;
|
|
63
|
+
method: string;
|
|
64
|
+
description?: string;
|
|
65
|
+
}>;
|
|
66
|
+
events: Array<{
|
|
67
|
+
name: string;
|
|
68
|
+
event: string;
|
|
69
|
+
description?: string;
|
|
70
|
+
}>;
|
|
71
|
+
types: Array<{
|
|
72
|
+
id: string;
|
|
73
|
+
name: string;
|
|
74
|
+
description?: string;
|
|
75
|
+
}>;
|
|
76
|
+
}>;
|
|
14
77
|
}
|
|
15
|
-
interface
|
|
16
|
-
|
|
17
|
-
|
|
78
|
+
interface CdpSpecSource {
|
|
79
|
+
/** Browser Rendering binding (Fetcher) — used in production */
|
|
80
|
+
browser?: BrowserBinding;
|
|
81
|
+
/** CDP base URL override (e.g. http://localhost:9222) */
|
|
82
|
+
cdpUrl?: string;
|
|
83
|
+
/** Headers to send with CDP URL discovery requests */
|
|
84
|
+
cdpHeaders?: Record<string, string>;
|
|
18
85
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* A CDP session over an open WebSocket. Manages command correlation,
|
|
24
|
-
* timeouts, target sessions, and a debug event ring buffer.
|
|
25
|
-
*
|
|
26
|
-
* Used host-side (not in the sandbox) — the sandbox calls into this
|
|
27
|
-
* via DynamicWorkerExecutor's ToolDispatcher RPC.
|
|
28
|
-
*/
|
|
29
|
-
declare class CdpSession {
|
|
30
|
-
#private;
|
|
31
|
-
constructor(
|
|
32
|
-
socket: WebSocket,
|
|
33
|
-
defaultTimeoutMs?: number,
|
|
34
|
-
dispose?: () => void
|
|
35
|
-
);
|
|
36
|
-
send(
|
|
37
|
-
method: string,
|
|
38
|
-
params?: unknown,
|
|
39
|
-
options?: CdpSendOptions
|
|
40
|
-
): Promise<unknown>;
|
|
41
|
-
attachToTarget(targetId: string, options?: CdpAttachOptions): Promise<string>;
|
|
42
|
-
getDebugLog(limit?: number): DebugEntry[];
|
|
43
|
-
clearDebugLog(): void;
|
|
44
|
-
close(): void;
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Connect to a browser via the Browser Rendering binding (Fetcher).
|
|
48
|
-
* Establishes a CDP WebSocket through the binding's fetch interface.
|
|
49
|
-
*/
|
|
50
|
-
declare function connectBrowser(
|
|
51
|
-
browser: Fetcher,
|
|
52
|
-
timeoutMs?: number
|
|
53
|
-
): Promise<CdpSession>;
|
|
54
|
-
/**
|
|
55
|
-
* Connect to a browser via a CDP base URL (e.g. http://localhost:9222).
|
|
56
|
-
* Discovers the WebSocket debugger URL via /json/version,
|
|
57
|
-
* rewrites localhost URLs to the base URL host, and opens the WebSocket.
|
|
58
|
-
*
|
|
59
|
-
* Useful for local development with `chrome --remote-debugging-port=9222`
|
|
60
|
-
* or when connecting through a tunnel.
|
|
61
|
-
*/
|
|
62
|
-
declare function connectUrl(
|
|
63
|
-
baseUrl: string,
|
|
64
|
-
options?: {
|
|
65
|
-
timeoutMs?: number;
|
|
66
|
-
headers?: Record<string, string>;
|
|
67
|
-
}
|
|
68
|
-
): Promise<CdpSession>;
|
|
86
|
+
/** Load the (cached) searchable CDP spec for a browser source. */
|
|
87
|
+
declare function loadCdpSpec(source: CdpSpecSource): Promise<SearchableCdpSpec>;
|
|
69
88
|
//#endregion
|
|
70
89
|
export {
|
|
71
|
-
type
|
|
90
|
+
type BrowserBinding,
|
|
91
|
+
BrowserConnector,
|
|
92
|
+
type BrowserConnectorOptions,
|
|
93
|
+
type BrowserConnectorSessionOptions,
|
|
94
|
+
type BrowserConnectorSweepOptions,
|
|
95
|
+
type BrowserConnectorSweepResult,
|
|
96
|
+
type BrowserLiveView,
|
|
97
|
+
type BrowserLiveViewTarget,
|
|
98
|
+
type BrowserLiveViewUrl,
|
|
99
|
+
type BrowserRecording,
|
|
100
|
+
BrowserRenderingError,
|
|
101
|
+
type BrowserSessionInfo,
|
|
102
|
+
type BrowserSessionLock,
|
|
103
|
+
type BrowserSessionStore,
|
|
104
|
+
type BrowserTargetInfo,
|
|
72
105
|
type CdpAttachOptions,
|
|
73
106
|
type CdpSendOptions,
|
|
74
107
|
CdpSession,
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
type
|
|
108
|
+
type CdpSpecSource,
|
|
109
|
+
CodemodeRuntime,
|
|
110
|
+
type ConnectBrowserOptions,
|
|
111
|
+
DEFAULT_EXEC_SWEEP_IDLE_MS,
|
|
112
|
+
DEFAULT_SWEEP_IDLE_MS,
|
|
113
|
+
DurableBrowserSessionStore,
|
|
114
|
+
type LiveViewMode,
|
|
115
|
+
type QuickAction,
|
|
116
|
+
type QuickActionBinary,
|
|
117
|
+
type QuickActionBinding,
|
|
118
|
+
type QuickActionCommonOptions,
|
|
119
|
+
type QuickActionExtractInput,
|
|
120
|
+
type QuickActionInput,
|
|
121
|
+
type QuickActionPage,
|
|
122
|
+
type QuickActionScrapeInput,
|
|
123
|
+
type QuickActionScrapeResult,
|
|
124
|
+
type QuickActionScreenshotInput,
|
|
125
|
+
type QuickActionSnapshot,
|
|
126
|
+
type SearchableCdpSpec,
|
|
127
|
+
type StoredBrowserSession,
|
|
128
|
+
browserContent,
|
|
129
|
+
browserExtract,
|
|
130
|
+
browserLinks,
|
|
131
|
+
browserMarkdown,
|
|
132
|
+
browserPdf,
|
|
133
|
+
browserScrape,
|
|
134
|
+
browserScreenshot,
|
|
135
|
+
browserSnapshot,
|
|
78
136
|
connectBrowser,
|
|
137
|
+
connectBrowserSession,
|
|
79
138
|
connectUrl,
|
|
80
|
-
|
|
139
|
+
createBrowserSession,
|
|
140
|
+
deleteBrowserSession,
|
|
141
|
+
getBrowserRecording,
|
|
142
|
+
listBrowserTargets,
|
|
143
|
+
loadCdpSpec,
|
|
144
|
+
runQuickAction
|
|
81
145
|
};
|
|
82
146
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/browser/index.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import { a as connectBrowser, i as
|
|
2
|
-
|
|
1
|
+
import { C as connectUrl, S as CdpSession, _ as connectBrowserSession, a as loadCdpSpec, b as getBrowserRecording, c as browserLinks, d as browserScrape, f as browserScreenshot, g as connectBrowser, h as BrowserRenderingError, i as DurableBrowserSessionStore, l as browserMarkdown, m as runQuickAction, n as DEFAULT_EXEC_SWEEP_IDLE_MS, o as browserContent, p as browserSnapshot, r as DEFAULT_SWEEP_IDLE_MS, s as browserExtract, t as BrowserConnector, u as browserPdf, v as createBrowserSession, x as listBrowserTargets, y as deleteBrowserSession } from "../connector-CrKhowfD.js";
|
|
2
|
+
import { CodemodeRuntime } from "@cloudflare/codemode";
|
|
3
|
+
export { BrowserConnector, BrowserRenderingError, CdpSession, CodemodeRuntime, DEFAULT_EXEC_SWEEP_IDLE_MS, DEFAULT_SWEEP_IDLE_MS, DurableBrowserSessionStore, browserContent, browserExtract, browserLinks, browserMarkdown, browserPdf, browserScrape, browserScreenshot, browserSnapshot, connectBrowser, connectBrowserSession, connectUrl, createBrowserSession, deleteBrowserSession, getBrowserRecording, listBrowserTargets, loadCdpSpec, runQuickAction };
|
|
@@ -1,21 +1,29 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CreateBrowserToolsOptions } from "./ai.js";
|
|
2
2
|
import { ServerTool } from "@tanstack/ai";
|
|
3
3
|
|
|
4
4
|
//#region src/browser/tanstack-ai.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Create TanStack AI tools for browser automation via CDP code mode.
|
|
7
7
|
*
|
|
8
|
-
* Returns an array
|
|
9
|
-
*
|
|
8
|
+
* Returns an array with a single durable `browser_execute` `ServerTool`
|
|
9
|
+
* backed by the same codemode runtime as `agents/browser/ai` — the model
|
|
10
|
+
* writes TypeScript against the `cdp` connector and browser sessions
|
|
11
|
+
* survive pauses.
|
|
12
|
+
*
|
|
13
|
+
* The stateless Quick Action tools are not surfaced through this TanStack
|
|
14
|
+
* wrapper (it exposes only `browser_execute`); use `createQuickActionTools`
|
|
15
|
+
* from `agents/browser/ai` if you want them.
|
|
10
16
|
*
|
|
11
17
|
* @example
|
|
12
18
|
* ```ts
|
|
13
19
|
* import { createBrowserTools } from "agents/browser/tanstack-ai";
|
|
14
20
|
* import { chat } from "@tanstack/ai";
|
|
15
21
|
*
|
|
22
|
+
* // inside a Durable Object / Agent:
|
|
16
23
|
* const browserTools = createBrowserTools({
|
|
17
|
-
*
|
|
18
|
-
*
|
|
24
|
+
* ctx: this.ctx,
|
|
25
|
+
* browser: this.env.BROWSER,
|
|
26
|
+
* loader: this.env.LOADER,
|
|
19
27
|
* });
|
|
20
28
|
*
|
|
21
29
|
* const stream = chat({
|
|
@@ -25,7 +33,9 @@ import { ServerTool } from "@tanstack/ai";
|
|
|
25
33
|
* });
|
|
26
34
|
* ```
|
|
27
35
|
*/
|
|
28
|
-
declare function createBrowserTools(
|
|
36
|
+
declare function createBrowserTools(
|
|
37
|
+
options: CreateBrowserToolsOptions
|
|
38
|
+
): ServerTool[];
|
|
29
39
|
//#endregion
|
|
30
|
-
export { type
|
|
40
|
+
export { type CreateBrowserToolsOptions, createBrowserTools };
|
|
31
41
|
//# sourceMappingURL=tanstack-ai.d.ts.map
|
|
@@ -1,21 +1,29 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createBrowserRuntime } from "./ai.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { toolDefinition } from "@tanstack/ai";
|
|
4
4
|
//#region src/browser/tanstack-ai.ts
|
|
5
5
|
/**
|
|
6
6
|
* Create TanStack AI tools for browser automation via CDP code mode.
|
|
7
7
|
*
|
|
8
|
-
* Returns an array
|
|
9
|
-
*
|
|
8
|
+
* Returns an array with a single durable `browser_execute` `ServerTool`
|
|
9
|
+
* backed by the same codemode runtime as `agents/browser/ai` — the model
|
|
10
|
+
* writes TypeScript against the `cdp` connector and browser sessions
|
|
11
|
+
* survive pauses.
|
|
12
|
+
*
|
|
13
|
+
* The stateless Quick Action tools are not surfaced through this TanStack
|
|
14
|
+
* wrapper (it exposes only `browser_execute`); use `createQuickActionTools`
|
|
15
|
+
* from `agents/browser/ai` if you want them.
|
|
10
16
|
*
|
|
11
17
|
* @example
|
|
12
18
|
* ```ts
|
|
13
19
|
* import { createBrowserTools } from "agents/browser/tanstack-ai";
|
|
14
20
|
* import { chat } from "@tanstack/ai";
|
|
15
21
|
*
|
|
22
|
+
* // inside a Durable Object / Agent:
|
|
16
23
|
* const browserTools = createBrowserTools({
|
|
17
|
-
*
|
|
18
|
-
*
|
|
24
|
+
* ctx: this.ctx,
|
|
25
|
+
* browser: this.env.BROWSER,
|
|
26
|
+
* loader: this.env.LOADER,
|
|
19
27
|
* });
|
|
20
28
|
*
|
|
21
29
|
* const stream = chat({
|
|
@@ -26,23 +34,21 @@ import { toolDefinition } from "@tanstack/ai";
|
|
|
26
34
|
* ```
|
|
27
35
|
*/
|
|
28
36
|
function createBrowserTools(options) {
|
|
29
|
-
const
|
|
37
|
+
const { tools } = createBrowserRuntime({
|
|
38
|
+
...options,
|
|
39
|
+
quickActions: false
|
|
40
|
+
});
|
|
41
|
+
const executeTool = tools.browser_execute;
|
|
30
42
|
return [toolDefinition({
|
|
31
|
-
name: "browser_search",
|
|
32
|
-
description: SEARCH_DESCRIPTION,
|
|
33
|
-
inputSchema: z.object({ code: z.string().meta({ description: "JavaScript async arrow function that queries the CDP spec" }) })
|
|
34
|
-
}).server(async ({ code }) => {
|
|
35
|
-
const result = await handlers.search(code);
|
|
36
|
-
if (result.isError) throw new Error(result.text);
|
|
37
|
-
return { text: result.text };
|
|
38
|
-
}), toolDefinition({
|
|
39
43
|
name: "browser_execute",
|
|
40
|
-
description:
|
|
41
|
-
inputSchema: z.object({ code: z.string().meta({ description: "
|
|
44
|
+
description: executeTool.description ?? "",
|
|
45
|
+
inputSchema: z.object({ code: z.string().meta({ description: "TypeScript async arrow function that uses the cdp connector" }) })
|
|
42
46
|
}).server(async ({ code }) => {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
47
|
+
if (!executeTool.execute) throw new Error("browser_execute tool is not executable");
|
|
48
|
+
return await executeTool.execute({ code }, {
|
|
49
|
+
toolCallId: crypto.randomUUID(),
|
|
50
|
+
messages: []
|
|
51
|
+
});
|
|
46
52
|
})];
|
|
47
53
|
}
|
|
48
54
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tanstack-ai.js","names":[],"sources":["../../src/browser/tanstack-ai.ts"],"sourcesContent":["import { toolDefinition } from \"@tanstack/ai\";\nimport type { ServerTool } from \"@tanstack/ai\";\nimport { z } from \"zod\";\nimport {
|
|
1
|
+
{"version":3,"file":"tanstack-ai.js","names":[],"sources":["../../src/browser/tanstack-ai.ts"],"sourcesContent":["import { toolDefinition } from \"@tanstack/ai\";\nimport type { ServerTool } from \"@tanstack/ai\";\nimport type { ProxyToolOutput } from \"@cloudflare/codemode\";\nimport { z } from \"zod\";\nimport { createBrowserRuntime, type CreateBrowserToolsOptions } from \"./ai\";\n\nexport type { CreateBrowserToolsOptions } from \"./ai\";\n\n/**\n * Create TanStack AI tools for browser automation via CDP code mode.\n *\n * Returns an array with a single durable `browser_execute` `ServerTool`\n * backed by the same codemode runtime as `agents/browser/ai` — the model\n * writes TypeScript against the `cdp` connector and browser sessions\n * survive pauses.\n *\n * The stateless Quick Action tools are not surfaced through this TanStack\n * wrapper (it exposes only `browser_execute`); use `createQuickActionTools`\n * from `agents/browser/ai` if you want them.\n *\n * @example\n * ```ts\n * import { createBrowserTools } from \"agents/browser/tanstack-ai\";\n * import { chat } from \"@tanstack/ai\";\n *\n * // inside a Durable Object / Agent:\n * const browserTools = createBrowserTools({\n * ctx: this.ctx,\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [...browserTools, ...otherTools],\n * messages,\n * });\n * ```\n */\nexport function createBrowserTools(\n options: CreateBrowserToolsOptions\n): ServerTool[] {\n // This wrapper only surfaces `browser_execute`, so don't build the default-on\n // Quick Action tools just to discard them.\n const { tools } = createBrowserRuntime({ ...options, quickActions: false });\n const executeTool = tools.browser_execute;\n\n const execute = toolDefinition({\n name: \"browser_execute\" as const,\n description: executeTool.description ?? \"\",\n inputSchema: z.object({\n code: z.string().meta({\n description:\n \"TypeScript async arrow function that uses the cdp connector\"\n })\n })\n }).server(async ({ code }) => {\n if (!executeTool.execute) {\n throw new Error(\"browser_execute tool is not executable\");\n }\n const result = (await executeTool.execute(\n { code },\n { toolCallId: crypto.randomUUID(), messages: [] }\n )) as ProxyToolOutput;\n return result;\n });\n\n return [execute];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,mBACd,SACc;CAGd,MAAM,EAAE,UAAU,qBAAqB;EAAE,GAAG;EAAS,cAAc;CAAM,CAAC;CAC1E,MAAM,cAAc,MAAM;CAsB1B,OAAO,CApBS,eAAe;EAC7B,MAAM;EACN,aAAa,YAAY,eAAe;EACxC,aAAa,EAAE,OAAO,EACpB,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,EACpB,aACE,8DACJ,CAAC,EACH,CAAC;CACH,CAAC,CAAC,CAAC,OAAO,OAAO,EAAE,WAAW;EAC5B,IAAI,CAAC,YAAY,SACf,MAAM,IAAI,MAAM,wCAAwC;EAM1D,OAAO,MAJe,YAAY,QAChC,EAAE,KAAK,GACP;GAAE,YAAY,OAAO,WAAW;GAAG,UAAU,CAAC;EAAE,CAClD;CAEF,CAEc,CAAC;AACjB"}
|
package/dist/chat/index.d.ts
CHANGED
|
@@ -3,11 +3,11 @@ import {
|
|
|
3
3
|
d as AgentToolRunState,
|
|
4
4
|
i as AgentToolEventMessage,
|
|
5
5
|
r as AgentToolEvent
|
|
6
|
-
} from "../agent-tool-types-
|
|
6
|
+
} from "../agent-tool-types-NofdbL9X.js";
|
|
7
7
|
import {
|
|
8
8
|
n as createAgentToolEventState,
|
|
9
9
|
t as applyAgentToolEvent
|
|
10
|
-
} from "../agent-tools-
|
|
10
|
+
} from "../agent-tools-DLquv-dp.js";
|
|
11
11
|
import { JSONSchema7, Tool, ToolSet, UIMessage } from "ai";
|
|
12
12
|
import { Connection } from "agents";
|
|
13
13
|
|
|
@@ -277,17 +277,38 @@ type ClientToolSchema = {
|
|
|
277
277
|
description?: Tool["description"] /** JSON Schema defining the tool's input parameters */;
|
|
278
278
|
parameters?: JSONSchema7;
|
|
279
279
|
};
|
|
280
|
+
/**
|
|
281
|
+
* Executes a client-defined tool and returns its output.
|
|
282
|
+
*
|
|
283
|
+
* Used for the RPC path (e.g. a parent agent delegating to a Think sub-agent)
|
|
284
|
+
* where the caller can run the client tools itself, rather than the
|
|
285
|
+
* browser/WebSocket path where results are sent back asynchronously.
|
|
286
|
+
*/
|
|
287
|
+
type ClientToolExecutor = (call: {
|
|
288
|
+
/** The name of the client tool the model called. */ toolName: string /** The model-generated input for the tool call. */;
|
|
289
|
+
input: unknown /** The AI SDK tool-call id for the invocation. */;
|
|
290
|
+
toolCallId: string;
|
|
291
|
+
}) => unknown | Promise<unknown>;
|
|
280
292
|
/**
|
|
281
293
|
* Converts client tool schemas to AI SDK tool format.
|
|
282
294
|
*
|
|
283
|
-
*
|
|
284
|
-
* the tool call is sent back to the client for execution.
|
|
295
|
+
* By default these tools have no `execute` function — when the AI model calls
|
|
296
|
+
* them, the tool call is sent back to the client for execution.
|
|
297
|
+
*
|
|
298
|
+
* When `options.execute` is provided, each tool is built WITH an `execute` that
|
|
299
|
+
* delegates to it. This is used by the RPC path (e.g. a parent agent driving a
|
|
300
|
+
* Think sub-agent) so the model's client-tool call is resolved inline within
|
|
301
|
+
* the same turn.
|
|
285
302
|
*
|
|
286
303
|
* @param clientTools - Array of tool schemas from the client
|
|
304
|
+
* @param options - Optional `execute` delegate to run the tools inline
|
|
287
305
|
* @returns Record of AI SDK tools that can be spread into your tools object
|
|
288
306
|
*/
|
|
289
307
|
declare function createToolsFromClientSchemas(
|
|
290
|
-
clientTools?: ClientToolSchema[]
|
|
308
|
+
clientTools?: ClientToolSchema[],
|
|
309
|
+
options?: {
|
|
310
|
+
execute?: ClientToolExecutor;
|
|
311
|
+
}
|
|
291
312
|
): ToolSet;
|
|
292
313
|
//#endregion
|
|
293
314
|
//#region src/chat/lifecycle.d.ts
|
|
@@ -672,6 +693,12 @@ declare class ResumableStream {
|
|
|
672
693
|
* DO was evicted.
|
|
673
694
|
*/
|
|
674
695
|
private _isLive;
|
|
696
|
+
/**
|
|
697
|
+
* Whether the active stream is a continuation. Mirrors the durable
|
|
698
|
+
* `is_continuation` column so replay frames can carry the flag without a
|
|
699
|
+
* per-replay query; restored from SQLite after hibernation in restore().
|
|
700
|
+
*/
|
|
701
|
+
private _activeIsContinuation;
|
|
675
702
|
private _chunkBuffer;
|
|
676
703
|
private _chunkBufferBytes;
|
|
677
704
|
private _isFlushingChunks;
|
|
@@ -702,6 +729,7 @@ declare class ResumableStream {
|
|
|
702
729
|
requestId: string,
|
|
703
730
|
options?: {
|
|
704
731
|
messageId?: string;
|
|
732
|
+
continuation?: boolean;
|
|
705
733
|
}
|
|
706
734
|
): string;
|
|
707
735
|
/**
|
|
@@ -768,6 +796,33 @@ declare class ResumableStream {
|
|
|
768
796
|
connection: Connection,
|
|
769
797
|
requestId: string
|
|
770
798
|
): boolean;
|
|
799
|
+
/**
|
|
800
|
+
* Replay the stored chunks of an errored stream for a request, WITHOUT a
|
|
801
|
+
* terminal frame — the caller follows up with the `done: true, error: true`
|
|
802
|
+
* frame carrying the durable terminal record's error text, mirroring what a
|
|
803
|
+
* live client observed (content chunks, then the error). Without this, a
|
|
804
|
+
* client that missed broadcast frames while disconnected has no other
|
|
805
|
+
* channel to the pre-error partial content: the server does not push
|
|
806
|
+
* messages on connect, and {@link replayCompletedChunksByRequestId} only
|
|
807
|
+
* serves `completed` streams (#1575).
|
|
808
|
+
*
|
|
809
|
+
* Returns true when the caller should proceed to send its terminal frame:
|
|
810
|
+
* either no errored stream existed (nothing to replay) or its chunks were
|
|
811
|
+
* replayed successfully. Returns false only when a send failed mid-replay,
|
|
812
|
+
* signalling the caller to skip the terminal frame — the connection is gone
|
|
813
|
+
* and the next reconnect retries the whole sequence.
|
|
814
|
+
*/
|
|
815
|
+
replayErroredChunksByRequestId(
|
|
816
|
+
connection: Connection,
|
|
817
|
+
requestId: string
|
|
818
|
+
): boolean;
|
|
819
|
+
/** Latest stream row for a request with the given terminal status. */
|
|
820
|
+
private _latestStreamForRequest;
|
|
821
|
+
/**
|
|
822
|
+
* Send a finished stream's stored chunks to a connection as replay frames.
|
|
823
|
+
* Returns false if the connection closed mid-replay.
|
|
824
|
+
*/
|
|
825
|
+
private _replayStoredChunks;
|
|
771
826
|
/**
|
|
772
827
|
* Restore active stream state if the agent was restarted during streaming.
|
|
773
828
|
* All streams are restored regardless of age — stale cleanup happens
|
|
@@ -782,7 +837,26 @@ declare class ResumableStream {
|
|
|
782
837
|
* Drop all stream tables (called on destroy).
|
|
783
838
|
*/
|
|
784
839
|
destroy(): void;
|
|
840
|
+
/**
|
|
841
|
+
* Force a sweep of aged stream buffers now, bypassing the lazy interval
|
|
842
|
+
* gate used by {@link _maybeCleanupOldStreams}. Intended to be driven by an
|
|
843
|
+
* alarm so idle/hibernated chat DOs still reclaim buffers even when no
|
|
844
|
+
* further stream ever completes to trigger the lazy path.
|
|
845
|
+
*/
|
|
846
|
+
cleanup(now?: number): void;
|
|
847
|
+
/**
|
|
848
|
+
* True if any stream rows remain at all. Used by alarm-driven cleanup to
|
|
849
|
+
* decide whether to re-arm: once no rows remain there is nothing left to
|
|
850
|
+
* sweep, so the DO can stop waking itself.
|
|
851
|
+
*/
|
|
852
|
+
hasReclaimableStreams(): boolean;
|
|
785
853
|
private _maybeCleanupOldStreams;
|
|
854
|
+
/** Delete completed/errored buffers past the completion grace window, plus
|
|
855
|
+
* abandoned "streaming" rows past the stale-in-flight window. The two use
|
|
856
|
+
* different retentions: a completed buffer is redundant with the persisted
|
|
857
|
+
* message and needs only a brief replay grace, whereas an in-flight buffer
|
|
858
|
+
* must outlive resume/recovery before it is presumed dead. */
|
|
859
|
+
private _sweepOldStreams;
|
|
786
860
|
/**
|
|
787
861
|
* Return the stored chunks for a stream as individual chunk bodies in order,
|
|
788
862
|
* unpacking packed segment rows. The returned `chunk_index` is a running
|
|
@@ -807,6 +881,13 @@ declare class ResumableStream {
|
|
|
807
881
|
}>;
|
|
808
882
|
/** @internal For testing only */
|
|
809
883
|
insertStaleStream(streamId: string, requestId: string, ageMs: number): void;
|
|
884
|
+
/**
|
|
885
|
+
* Append a chunk to a stream dated `ageMs` in the past. Used to exercise the
|
|
886
|
+
* last-activity sweep threshold: a long-running streaming row with a *recent*
|
|
887
|
+
* chunk must survive even when its start time is older than the cutoff.
|
|
888
|
+
* @internal For testing only
|
|
889
|
+
*/
|
|
890
|
+
insertChunkAt(streamId: string, body: string, ageMs: number): void;
|
|
810
891
|
}
|
|
811
892
|
//#endregion
|
|
812
893
|
//#region src/chat/sql-batch.d.ts
|
|
@@ -1083,6 +1164,29 @@ declare function crossMessageToolResultUpdate(
|
|
|
1083
1164
|
errorText?: string,
|
|
1084
1165
|
preliminary?: boolean
|
|
1085
1166
|
): ToolPartUpdate;
|
|
1167
|
+
/**
|
|
1168
|
+
* Build an update descriptor that replaces the output of a *paused durable
|
|
1169
|
+
* execution* tool part (e.g. a codemode runtime tool that paused for
|
|
1170
|
+
* approval).
|
|
1171
|
+
*
|
|
1172
|
+
* A paused execution completes its tool call normally — the part is already
|
|
1173
|
+
* `output-available` with an output of `{ status: "paused", executionId }`.
|
|
1174
|
+
* When the host later approves/rejects the execution, the new outcome
|
|
1175
|
+
* (completed / rejected / paused-again) must replace that output in place.
|
|
1176
|
+
*
|
|
1177
|
+
* Matching is deliberately narrow and idempotent:
|
|
1178
|
+
*
|
|
1179
|
+
* - only `output-available` parts are considered;
|
|
1180
|
+
* - the existing output must be a paused-execution object carrying the same
|
|
1181
|
+
* `executionId` — anything else (already replaced, different execution)
|
|
1182
|
+
* returns the *same part reference*, which callers treat as a no-op signal
|
|
1183
|
+
* (skip persist + broadcast), mirroring {@link crossMessageToolResultUpdate}.
|
|
1184
|
+
*/
|
|
1185
|
+
declare function pausedExecutionUpdate(
|
|
1186
|
+
toolCallId: string,
|
|
1187
|
+
executionId: string,
|
|
1188
|
+
output: unknown
|
|
1189
|
+
): ToolPartUpdate;
|
|
1086
1190
|
/**
|
|
1087
1191
|
* Build an update descriptor for applying a tool approval.
|
|
1088
1192
|
*
|
|
@@ -1278,6 +1382,7 @@ export {
|
|
|
1278
1382
|
type ChatResponseResult,
|
|
1279
1383
|
type ChunkAction,
|
|
1280
1384
|
type ChunkResult,
|
|
1385
|
+
type ClientToolExecutor,
|
|
1281
1386
|
type ClientToolSchema,
|
|
1282
1387
|
type ContinuationConnection,
|
|
1283
1388
|
type ContinuationDeferred,
|
|
@@ -1318,6 +1423,7 @@ export {
|
|
|
1318
1423
|
isReplayChunk,
|
|
1319
1424
|
normalizeToolInput,
|
|
1320
1425
|
parseProtocolMessage,
|
|
1426
|
+
pausedExecutionUpdate,
|
|
1321
1427
|
reconcileMessages,
|
|
1322
1428
|
resolveToolMergeId,
|
|
1323
1429
|
sanitizeMessage,
|