@cloudflare/think 0.23.0 → 0.25.0

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.
Files changed (49) hide show
  1. package/README.md +30 -40
  2. package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
  3. package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
  4. package/dist/extensions/index.d.ts +30 -72
  5. package/dist/extensions/index.js +45 -47
  6. package/dist/extensions/index.js.map +1 -1
  7. package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
  8. package/dist/fetch-BbYxtlff.js.map +1 -0
  9. package/dist/manager-B3rcb_6p.js +493 -0
  10. package/dist/manager-B3rcb_6p.js.map +1 -0
  11. package/dist/manager-CWGumyKi.d.ts +3391 -0
  12. package/dist/messengers/index.d.ts +54 -66
  13. package/dist/messengers/index.js +2 -2
  14. package/dist/messengers/telegram.d.ts +4 -4
  15. package/dist/messengers/telegram.js +1 -1
  16. package/dist/think.d.ts +2 -2
  17. package/dist/think.js +8493 -10725
  18. package/dist/think.js.map +1 -1
  19. package/dist/tools/browser.d.ts +1 -1
  20. package/dist/tools/browser.js +1 -1
  21. package/dist/tools/browser.js.map +1 -1
  22. package/dist/tools/execute.d.ts +2 -2
  23. package/dist/tools/execute.js +2 -2
  24. package/dist/tools/execute.js.map +1 -1
  25. package/dist/tools/extensions.d.ts +1 -1
  26. package/dist/tools/extensions.js +1 -1
  27. package/dist/tools/fetch.js +1 -1
  28. package/dist/workflows.d.ts +5 -2
  29. package/docs/actions.md +12 -0
  30. package/docs/channels.md +10 -4
  31. package/docs/client-tools.md +57 -27
  32. package/docs/context.md +92 -0
  33. package/docs/getting-started.md +4 -4
  34. package/docs/index.md +112 -52
  35. package/docs/lifecycle-hooks.md +10 -21
  36. package/docs/multi-chat.md +6 -6
  37. package/docs/programmatic-submissions.md +28 -10
  38. package/docs/sub-agents.md +45 -51
  39. package/docs/tools.md +41 -15
  40. package/docs/workflows.md +5 -4
  41. package/package.json +15 -10
  42. package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
  43. package/dist/fetch-DO3uQ9py.js.map +0 -1
  44. package/dist/hook-proxy-DY2sBNa0.js +0 -117
  45. package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
  46. package/dist/index-DDnny6kt.d.ts +0 -5847
  47. package/dist/manager-BubfmA3q.js +0 -313
  48. package/dist/manager-BubfmA3q.js.map +0 -1
  49. package/dist/manager-rze95KCk.d.ts +0 -235
@@ -63,7 +63,7 @@ import {
63
63
  *
64
64
  * export class MyAgent extends Think<Env> {
65
65
  * getModel() {
66
- * return createWorkersAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.7-code");
66
+ * return createWorkersAI({ binding: this.env.AI })("@cf/deepseek-ai/deepseek-v4.1-flash-1017");
67
67
  * }
68
68
  *
69
69
  * getTools() {
@@ -33,7 +33,7 @@ import { createBrowserRuntime, createBrowserTools as createBrowserTools$1, creat
33
33
  *
34
34
  * export class MyAgent extends Think<Env> {
35
35
  * getModel() {
36
- * return createWorkersAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.7-code");
36
+ * return createWorkersAI({ binding: this.env.AI })("@cf/deepseek-ai/deepseek-v4.1-flash-1017");
37
37
  * }
38
38
  *
39
39
  * getTools() {
@@ -1 +1 @@
1
- {"version":3,"file":"browser.js","names":["createBrowserToolsForAi"],"sources":["../../src/tools/browser.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\nimport {\n createBrowserRuntime,\n createBrowserTools as createBrowserToolsForAi,\n createQuickActionTools,\n type BrowserRuntime,\n type CreateBrowserToolsOptions,\n type CreateQuickActionToolsOptions,\n type QuickActionToolName\n} from \"agents/browser/ai\";\n\nexport {\n createBrowserRuntime,\n type BrowserRuntime,\n type CreateBrowserToolsOptions\n};\n\n// Stateless Quick Action tools — re-exported so a Think agent can expose them\n// from `getTools()` with a single import, including the loader-free path\n// (`createQuickActionTools`) that needs only the `browser` binding.\nexport {\n createQuickActionTools,\n type CreateQuickActionToolsOptions,\n type QuickActionToolName\n};\nexport {\n browserContent,\n browserExtract,\n browserLinks,\n browserMarkdown,\n browserPdf,\n browserScrape,\n browserScreenshot,\n browserSnapshot,\n runQuickAction,\n type QuickAction,\n type QuickActionBinary,\n type QuickActionBinding,\n type QuickActionCommonOptions,\n type QuickActionExtractInput,\n type QuickActionInput,\n type QuickActionPage,\n type QuickActionScrapeInput,\n type QuickActionScrapeResult,\n type QuickActionScreenshotInput,\n type QuickActionSnapshot\n} from \"agents/browser\";\n\n/**\n * Create browser automation tools for Think agents.\n *\n * Returns the durable `browser_execute` tool backed by a codemode runtime —\n * the model writes TypeScript against the `cdp` connector (`cdp.send`,\n * `cdp.attachToTarget`, `cdp.spec`, …); executions are recorded for\n * abort-and-replay, and browser sessions are keyed by execution (they survive\n * pauses and, in `reuse`/`dynamic` modes, span executions) — plus the stateless\n * {@link createQuickActionTools | Quick Action} tools (`browser_markdown`,\n * `browser_extract`, …) by default whenever a `browser` binding is present.\n * Pass `quickActions: false` to omit them, or use `createQuickActionTools`\n * directly for the stateless tools alone (no Worker Loader required).\n *\n * Setup checklist:\n *\n * - `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc\n * - `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc\n * - export the runtime class from your worker entry:\n * `export { CodemodeRuntime } from \"@cloudflare/codemode\"`\n * (the `@cloudflare/codemode/vite` plugin does this automatically)\n *\n * Use {@link createBrowserRuntime} instead when you also need the runtime\n * handle (approvals, audit, `expirePaused`) or the connector's host-side\n * session helpers (`sessionInfo`, `closeSession`, `sweep`).\n *\n * @example\n * ```ts\n * import { Think } from \"@cloudflare/think\";\n * import { createBrowserTools } from \"@cloudflare/think/tools/browser\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.7-code\");\n * }\n *\n * getTools() {\n * return {\n * ...createBrowserTools({\n * ctx: this.ctx,\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * session: { mode: \"dynamic\" }\n * }),\n * };\n * }\n * }\n * ```\n */\nexport function createBrowserTools(\n options: CreateBrowserToolsOptions\n): ToolSet {\n return createBrowserToolsForAi(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,mBACd,SACS;CACT,OAAOA,qBAAwB,OAAO;AACxC"}
1
+ {"version":3,"file":"browser.js","names":["createBrowserToolsForAi"],"sources":["../../src/tools/browser.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\nimport {\n createBrowserRuntime,\n createBrowserTools as createBrowserToolsForAi,\n createQuickActionTools,\n type BrowserRuntime,\n type CreateBrowserToolsOptions,\n type CreateQuickActionToolsOptions,\n type QuickActionToolName\n} from \"agents/browser/ai\";\n\nexport {\n createBrowserRuntime,\n type BrowserRuntime,\n type CreateBrowserToolsOptions\n};\n\n// Stateless Quick Action tools — re-exported so a Think agent can expose them\n// from `getTools()` with a single import, including the loader-free path\n// (`createQuickActionTools`) that needs only the `browser` binding.\nexport {\n createQuickActionTools,\n type CreateQuickActionToolsOptions,\n type QuickActionToolName\n};\nexport {\n browserContent,\n browserExtract,\n browserLinks,\n browserMarkdown,\n browserPdf,\n browserScrape,\n browserScreenshot,\n browserSnapshot,\n runQuickAction,\n type QuickAction,\n type QuickActionBinary,\n type QuickActionBinding,\n type QuickActionCommonOptions,\n type QuickActionExtractInput,\n type QuickActionInput,\n type QuickActionPage,\n type QuickActionScrapeInput,\n type QuickActionScrapeResult,\n type QuickActionScreenshotInput,\n type QuickActionSnapshot\n} from \"agents/browser\";\n\n/**\n * Create browser automation tools for Think agents.\n *\n * Returns the durable `browser_execute` tool backed by a codemode runtime —\n * the model writes TypeScript against the `cdp` connector (`cdp.send`,\n * `cdp.attachToTarget`, `cdp.spec`, …); executions are recorded for\n * abort-and-replay, and browser sessions are keyed by execution (they survive\n * pauses and, in `reuse`/`dynamic` modes, span executions) — plus the stateless\n * {@link createQuickActionTools | Quick Action} tools (`browser_markdown`,\n * `browser_extract`, …) by default whenever a `browser` binding is present.\n * Pass `quickActions: false` to omit them, or use `createQuickActionTools`\n * directly for the stateless tools alone (no Worker Loader required).\n *\n * Setup checklist:\n *\n * - `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc\n * - `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc\n * - export the runtime class from your worker entry:\n * `export { CodemodeRuntime } from \"@cloudflare/codemode\"`\n * (the `@cloudflare/codemode/vite` plugin does this automatically)\n *\n * Use {@link createBrowserRuntime} instead when you also need the runtime\n * handle (approvals, audit, `expirePaused`) or the connector's host-side\n * session helpers (`sessionInfo`, `closeSession`, `sweep`).\n *\n * @example\n * ```ts\n * import { Think } from \"@cloudflare/think\";\n * import { createBrowserTools } from \"@cloudflare/think/tools/browser\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/deepseek-ai/deepseek-v4.1-flash-1017\");\n * }\n *\n * getTools() {\n * return {\n * ...createBrowserTools({\n * ctx: this.ctx,\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * session: { mode: \"dynamic\" }\n * }),\n * };\n * }\n * }\n * ```\n */\nexport function createBrowserTools(\n options: CreateBrowserToolsOptions\n): ToolSet {\n return createBrowserToolsForAi(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,mBACd,SACS;CACT,OAAOA,qBAAwB,OAAO;AACxC"}
@@ -119,7 +119,7 @@ interface ExecuteRuntime {
119
119
  * reach it.
120
120
  *
121
121
  * @deprecated Code execution is moving to the Workspace: give it a
122
- * JavaScript backend with a `ws:tools` module
122
+ * codemode backend with a `codemode:tools` module
123
123
  * (`createToolBindings(forAISDKTools(() => this.getTools()))` from
124
124
  * `@cloudflare/computer`), so code the model runs with `exec` imports the
125
125
  * agent's tools and reads files through `node:fs`.
@@ -182,7 +182,7 @@ declare function truncatePausedExecutionOutput(output: unknown): unknown;
182
182
  * (approvals, audit, snippets) and the connector set.
183
183
  *
184
184
  * @deprecated Code execution is moving to the Workspace: give it a
185
- * JavaScript backend with a `ws:tools` module
185
+ * codemode backend with a `codemode:tools` module
186
186
  * (`createToolBindings(forAISDKTools(() => this.getTools()))` from
187
187
  * `@cloudflare/computer`), so code the model runs with `exec` imports the
188
188
  * agent's tools and reads files through `node:fs`.
@@ -26,7 +26,7 @@ function optionsFromAgent(agent) {
26
26
  * reach it.
27
27
  *
28
28
  * @deprecated Code execution is moving to the Workspace: give it a
29
- * JavaScript backend with a `ws:tools` module
29
+ * codemode backend with a `codemode:tools` module
30
30
  * (`createToolBindings(forAISDKTools(() => this.getTools()))` from
31
31
  * `@cloudflare/computer`), so code the model runs with `exec` imports the
32
32
  * agent's tools and reads files through `node:fs`.
@@ -168,7 +168,7 @@ function truncatePausedExecutionOutput(output) {
168
168
  * (approvals, audit, snippets) and the connector set.
169
169
  *
170
170
  * @deprecated Code execution is moving to the Workspace: give it a
171
- * JavaScript backend with a `ws:tools` module
171
+ * codemode backend with a `codemode:tools` module
172
172
  * (`createToolBindings(forAISDKTools(() => this.getTools()))` from
173
173
  * `@cloudflare/computer`), so code the model runs with `exec` imports the
174
174
  * agent's tools and reads files through `node:fs`.
@@ -1 +1 @@
1
- {"version":3,"file":"execute.js","names":[],"sources":["../../src/tools/execute.ts"],"sourcesContent":["import type { Tool, ToolSet } from \"ai\";\nimport {\n createCodemodeRuntime,\n DynamicWorkerExecutor,\n truncateResult,\n type CodemodeConnector,\n type CodemodeRuntimeHandle,\n type Executor\n} from \"@cloudflare/codemode\";\nimport { ToolSetConnector } from \"@cloudflare/codemode/ai\";\nimport {\n BrowserConnector,\n DurableBrowserSessionStore,\n type BrowserBinding,\n type BrowserConnectorSessionOptions\n} from \"agents/browser\";\n\n/**\n * The minimum agent surface for the `createExecuteTool(this)` one-liner.\n * Any Think agent satisfies it. The agent must be a Durable Object — its\n * `ctx` hosts the codemode runtime facet, and its `env` provides the\n * LOADER/BROWSER bindings. (`ctx` and `env` are not declared here because\n * they are `protected` on the DO base class in some type configurations,\n * which would break structural assignability of `this`.)\n */\nexport interface ExecuteToolAgent {\n /** Set by `createExecuteRuntime(agent)` so callables can reach the runtime. */\n codemode?: CodemodeRuntimeHandle;\n}\n\nexport interface CreateExecuteToolOptions {\n /**\n * Durable Object state. The codemode runtime that backs the execute tool\n * lives in a facet of this DO — the tool must be created from inside a\n * Durable Object (e.g. a Think agent: pass `this.ctx`).\n */\n ctx: DurableObjectState;\n\n /**\n * AI SDK tools exposed inside the sandbox as `tools.*`. Tools with\n * `needsApproval` get the runtime's durable pause/approve/resume flow:\n * calling one pauses the execution until `approveExecution` /\n * `rejectExecution`. A function-valued `needsApproval` can't be evaluated\n * against sandbox arguments ahead of time, so it conservatively always\n * requires approval. Tools without an `execute` function (client-side /\n * provider-executed) are skipped — the sandbox can't call them.\n */\n tools?: ToolSet;\n\n /**\n * Browser Rendering binding. When provided, the sandbox gets the `cdp.*`\n * connector (cdp.send, cdp.attachToTarget, cdp.spec, …) — a live browser\n * over the Chrome DevTools Protocol.\n *\n * Requires `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc.\n */\n browser?: BrowserBinding;\n\n /**\n * Browser session lifecycle (only with `browser`). Defaults to `dynamic`:\n * one-shot sessions the model can promote with `cdp.startSession()`.\n */\n session?: BrowserConnectorSessionOptions;\n\n /**\n * Additional connectors for the sandbox beyond `tools` and `cdp`.\n * Each adds its own named namespace.\n */\n connectors?: CodemodeConnector[];\n\n /**\n * The executor that runs the generated code. If not provided, a\n * `DynamicWorkerExecutor` is created from `loader`.\n */\n executor?: Executor;\n\n /**\n * WorkerLoader binding for creating a `DynamicWorkerExecutor`.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader?: WorkerLoader;\n\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n * Only used when `loader` is provided (ignored if `executor` is given).\n */\n timeout?: number;\n\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access.\n * - A `Fetcher`: all outbound requests route through this handler.\n *\n * Only used when `loader` is provided (ignored if `executor` is given).\n */\n globalOutbound?: Fetcher | null;\n\n /**\n * Custom tool description. Replaces the generated default entirely — the\n * default explains the codemode workflow and lists each configured\n * namespace (`tools.*`, `cdp.*`) with a usage hint.\n */\n description?: string;\n\n /**\n * Codemode runtime name — the durable identity of the tool's executions\n * and snippets. Defaults to `\"execute\"`. Adding or removing connectors\n * does NOT change the identity, so histories survive configuration\n * changes.\n */\n name?: string;\n}\n\n/**\n * The execute tool's moving parts, for hosts that need more than the tool:\n *\n * - `runtime` — the codemode runtime handle (approve/reject paused runs,\n * `expirePaused`, audit via `executions()`, snippets).\n * - `connectors` — the connector set backing the runtime (e.g. the\n * `BrowserConnector` for host-side `sessionInfo()` / `closeSession()` /\n * `sweep()`).\n * - `tool` — what `createExecuteTool` returns.\n */\nexport interface ExecuteRuntime {\n runtime: CodemodeRuntimeHandle;\n connectors: CodemodeConnector[];\n tool: Tool;\n}\n\nfunction isAgent(\n source: CreateExecuteToolOptions | ExecuteToolAgent\n): source is ExecuteToolAgent {\n // An options bag has no `env`, but guard against a hand-built object that\n // happens to carry one (e.g. spread from a worker handler): an explicit\n // `executor`/`loader` key marks it as options — agents never have those.\n // (Other option keys like `tools`/`browser` can legitimately exist on agent\n // subclasses, so they can't discriminate.)\n return \"env\" in source && !(\"executor\" in source) && !(\"loader\" in source);\n}\n\nfunction optionsFromAgent(agent: ExecuteToolAgent): CreateExecuteToolOptions {\n const env = ((agent as unknown as { env?: unknown }).env ?? {}) as {\n LOADER?: WorkerLoader;\n BROWSER?: BrowserBinding;\n };\n const ctx = (agent as unknown as { ctx?: DurableObjectState }).ctx;\n if (!ctx) {\n throw new Error(\n \"createExecuteTool(agent) requires a Durable Object agent — \" +\n \"call createExecuteTool({ ctx, loader, ... }) with explicit options.\"\n );\n }\n return {\n ctx,\n loader: env.LOADER,\n browser: env.BROWSER\n };\n}\n\n/**\n * Build the codemode runtime behind the execute tool, returning the runtime\n * handle and connectors alongside the tool. Use this instead of\n * {@link createExecuteTool} when the host needs approvals, the audit trail,\n * snippets, or browser session management.\n *\n * When called with an agent, the runtime handle is also assigned to\n * `agent.codemode` so callables (and Think's built-in approval flow) can\n * reach it.\n *\n * @deprecated Code execution is moving to the Workspace: give it a\n * JavaScript backend with a `ws:tools` module\n * (`createToolBindings(forAISDKTools(() => this.getTools()))` from\n * `@cloudflare/computer`), so code the model runs with `exec` imports the\n * agent's tools and reads files through `node:fs`.\n */\nexport function createExecuteRuntime(\n source: CreateExecuteToolOptions | ExecuteToolAgent,\n overrides?: Partial<Omit<CreateExecuteToolOptions, \"ctx\">>\n): ExecuteRuntime {\n const agent = isAgent(source) ? source : undefined;\n const options: CreateExecuteToolOptions = isAgent(source)\n ? { ...optionsFromAgent(source), ...overrides }\n : { ...source, ...overrides };\n\n if (agent && !options.executor && !options.loader) {\n throw new Error(\n \"createExecuteTool(agent) requires a WorkerLoader binding named LOADER — \" +\n 'add `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` to wrangler.jsonc, ' +\n \"or call createExecuteTool({ ctx, loader, ... }) with explicit options.\"\n );\n }\n\n let executor: Executor;\n if (options.executor) {\n executor = options.executor;\n } else if (options.loader) {\n executor = new DynamicWorkerExecutor({\n loader: options.loader,\n timeout: options.timeout,\n globalOutbound: options.globalOutbound\n });\n } else {\n throw new Error(\n \"createExecuteTool requires either an `executor` or a `loader` \" +\n '(WorkerLoader binding — `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` ' +\n \"in wrangler.jsonc).\"\n );\n }\n\n const connectors: CodemodeConnector[] = [];\n if (options.tools && Object.keys(options.tools).length > 0) {\n connectors.push(\n new ToolSetConnector(options.ctx, { tools: options.tools })\n );\n }\n if (options.browser) {\n connectors.push(\n new BrowserConnector(options.ctx, {\n browser: options.browser,\n store: new DurableBrowserSessionStore(options.ctx.storage),\n session: options.session ?? { mode: \"dynamic\" },\n timeout: options.timeout\n })\n );\n }\n connectors.push(...(options.connectors ?? []));\n\n if (connectors.length === 0) {\n throw new Error(\n \"createExecuteTool has nothing to expose — provide at least one of \" +\n \"`tools`, `browser`, or `connectors`.\"\n );\n }\n\n const runtime = createCodemodeRuntime({\n ctx: options.ctx,\n executor,\n connectors,\n name: options.name ?? \"execute\",\n transformResult: truncateResult\n });\n\n if (agent) {\n agent.codemode = runtime;\n }\n\n const baseTool = runtime.tool({\n description: options.description,\n connectorHints: connectorHints(options)\n });\n const baseExecute = baseTool.execute;\n const tool: Tool = baseExecute\n ? ({\n ...baseTool,\n // Paused outputs land in the transcript (and the model context) as a\n // normal tool result; a gated call's raw args (e.g. a writeFile\n // payload) can be huge. Truncate them in the model-facing payload —\n // the runtime facet keeps the full args for the actual resume, and\n // the host can fetch detail via `pendingExecutions`.\n execute: async (input: unknown, callOptions: unknown) =>\n truncatePausedExecutionOutput(\n await (baseExecute as (i: unknown, o: unknown) => Promise<unknown>)(\n input,\n callOptions\n )\n )\n } as Tool)\n : baseTool;\n\n return {\n runtime,\n connectors,\n tool\n };\n}\n\n/**\n * One-line usage hints for the namespaces createExecuteTool itself wires up,\n * rendered into the default tool description. Models otherwise tend to guess\n * a filesystem API (`host.*`, `fs.*`) instead of discovering `tools.*` via\n * `codemode.search`.\n */\nfunction connectorHints(\n options: CreateExecuteToolOptions\n): Record<string, string> {\n const hints: Record<string, string> = {};\n if (options.tools) {\n const names = Object.entries(options.tools)\n .filter(([, t]) => typeof t.execute === \"function\")\n .map(([name]) => name);\n if (names.length > 0) {\n hints.tools =\n `your host tools as async functions — e.g. \\`await tools.${names[0]}({ ... })\\`. ` +\n `Available: ${names.join(\", \")}`;\n }\n }\n if (options.browser) {\n hints.cdp =\n \"a live browser over the Chrome DevTools Protocol. \" +\n 'Target-scoped commands need no sessionId: `cdp.send({ method: \"Target.createTarget\", params: { url } })`. ' +\n \"Page-scoped commands (Page.*, Runtime.*, DOM.*) need one: \" +\n \"`const { sessionId } = await cdp.attachToTarget({ targetId })`, then \" +\n \"`cdp.send({ method, params, sessionId })`. Discover commands with `cdp.spec()`\";\n }\n return hints;\n}\n\n/** Character budget for a pending action's args in the transcript. */\nconst PENDING_ARGS_MAX_CHARS = 2_000;\n\n/**\n * Truncate the `pending[].args` of a paused execution output for transcript /\n * model consumption. The full args stay on the runtime facet (used by the\n * actual resume); only the model-facing copy is bounded. Non-paused outputs\n * pass through unchanged.\n */\nexport function truncatePausedExecutionOutput(output: unknown): unknown {\n if (typeof output !== \"object\" || output === null) return output;\n const o = output as { status?: unknown; pending?: unknown };\n if (o.status !== \"paused\" || !Array.isArray(o.pending)) return output;\n return {\n ...o,\n pending: o.pending.map((action) => {\n if (typeof action !== \"object\" || action === null) return action;\n const a = action as { args?: unknown };\n if (!(\"args\" in a)) return action;\n return {\n ...a,\n args: truncateResult(a.args, { maxChars: PENDING_ARGS_MAX_CHARS })\n };\n })\n };\n}\n\n/**\n * Create a code execution tool that lets the LLM write and run TypeScript\n * against your tools and (optionally) a live browser — all inside a sandboxed Worker, recorded on a durable codemode\n * runtime (abort-and-replay, approvals, snippets).\n *\n * The model sees typed namespaces: `tools.*` for your AI SDK tools and\n * `cdp.*` for the browser. To give the sandbox the workspace, pass the\n * workspace tools: `tools: createAITools({ workspace: this.workspace })`.\n *\n * Setup checklist:\n *\n * - `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc\n * - `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc (for `cdp.*`)\n * - export the runtime class from your worker entry:\n * `export { CodemodeRuntime } from \"@cloudflare/codemode\"`\n * (the `@cloudflare/codemode/vite` plugin does this automatically)\n *\n * @example One-liner — defaults from the agent\n * ```ts\n * getTools() {\n * return {\n * // cdp.* if env.BROWSER is bound,\n * // executor from env.LOADER\n * execute: createExecuteTool(this)\n * };\n * }\n * ```\n *\n * @example Agent defaults plus overrides (e.g. custom tools.*)\n * ```ts\n * execute: createExecuteTool(this, { tools: myDomainTools })\n * ```\n *\n * @example Explicit options\n * ```ts\n * execute: createExecuteTool({\n * ctx: this.ctx,\n * tools: myDomainTools, // tools.*\n * browser: this.env.BROWSER, // cdp.*\n * loader: this.env.LOADER\n * })\n * ```\n *\n * Use {@link createExecuteRuntime} to also get the runtime handle\n * (approvals, audit, snippets) and the connector set.\n *\n * @deprecated Code execution is moving to the Workspace: give it a\n * JavaScript backend with a `ws:tools` module\n * (`createToolBindings(forAISDKTools(() => this.getTools()))` from\n * `@cloudflare/computer`), so code the model runs with `exec` imports the\n * agent's tools and reads files through `node:fs`.\n */\nexport function createExecuteTool(\n source: CreateExecuteToolOptions | ExecuteToolAgent,\n overrides?: Partial<Omit<CreateExecuteToolOptions, \"ctx\">>\n): Tool {\n return createExecuteRuntime(source, overrides).tool;\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"execute.js","names":[],"sources":["../../src/tools/execute.ts"],"sourcesContent":["import type { Tool, ToolSet } from \"ai\";\nimport {\n createCodemodeRuntime,\n DynamicWorkerExecutor,\n truncateResult,\n type CodemodeConnector,\n type CodemodeRuntimeHandle,\n type Executor\n} from \"@cloudflare/codemode\";\nimport { ToolSetConnector } from \"@cloudflare/codemode/ai\";\nimport {\n BrowserConnector,\n DurableBrowserSessionStore,\n type BrowserBinding,\n type BrowserConnectorSessionOptions\n} from \"agents/browser\";\n\n/**\n * The minimum agent surface for the `createExecuteTool(this)` one-liner.\n * Any Think agent satisfies it. The agent must be a Durable Object — its\n * `ctx` hosts the codemode runtime facet, and its `env` provides the\n * LOADER/BROWSER bindings. (`ctx` and `env` are not declared here because\n * they are `protected` on the DO base class in some type configurations,\n * which would break structural assignability of `this`.)\n */\nexport interface ExecuteToolAgent {\n /** Set by `createExecuteRuntime(agent)` so callables can reach the runtime. */\n codemode?: CodemodeRuntimeHandle;\n}\n\nexport interface CreateExecuteToolOptions {\n /**\n * Durable Object state. The codemode runtime that backs the execute tool\n * lives in a facet of this DO — the tool must be created from inside a\n * Durable Object (e.g. a Think agent: pass `this.ctx`).\n */\n ctx: DurableObjectState;\n\n /**\n * AI SDK tools exposed inside the sandbox as `tools.*`. Tools with\n * `needsApproval` get the runtime's durable pause/approve/resume flow:\n * calling one pauses the execution until `approveExecution` /\n * `rejectExecution`. A function-valued `needsApproval` can't be evaluated\n * against sandbox arguments ahead of time, so it conservatively always\n * requires approval. Tools without an `execute` function (client-side /\n * provider-executed) are skipped — the sandbox can't call them.\n */\n tools?: ToolSet;\n\n /**\n * Browser Rendering binding. When provided, the sandbox gets the `cdp.*`\n * connector (cdp.send, cdp.attachToTarget, cdp.spec, …) — a live browser\n * over the Chrome DevTools Protocol.\n *\n * Requires `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc.\n */\n browser?: BrowserBinding;\n\n /**\n * Browser session lifecycle (only with `browser`). Defaults to `dynamic`:\n * one-shot sessions the model can promote with `cdp.startSession()`.\n */\n session?: BrowserConnectorSessionOptions;\n\n /**\n * Additional connectors for the sandbox beyond `tools` and `cdp`.\n * Each adds its own named namespace.\n */\n connectors?: CodemodeConnector[];\n\n /**\n * The executor that runs the generated code. If not provided, a\n * `DynamicWorkerExecutor` is created from `loader`.\n */\n executor?: Executor;\n\n /**\n * WorkerLoader binding for creating a `DynamicWorkerExecutor`.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader?: WorkerLoader;\n\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n * Only used when `loader` is provided (ignored if `executor` is given).\n */\n timeout?: number;\n\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access.\n * - A `Fetcher`: all outbound requests route through this handler.\n *\n * Only used when `loader` is provided (ignored if `executor` is given).\n */\n globalOutbound?: Fetcher | null;\n\n /**\n * Custom tool description. Replaces the generated default entirely — the\n * default explains the codemode workflow and lists each configured\n * namespace (`tools.*`, `cdp.*`) with a usage hint.\n */\n description?: string;\n\n /**\n * Codemode runtime name — the durable identity of the tool's executions\n * and snippets. Defaults to `\"execute\"`. Adding or removing connectors\n * does NOT change the identity, so histories survive configuration\n * changes.\n */\n name?: string;\n}\n\n/**\n * The execute tool's moving parts, for hosts that need more than the tool:\n *\n * - `runtime` — the codemode runtime handle (approve/reject paused runs,\n * `expirePaused`, audit via `executions()`, snippets).\n * - `connectors` — the connector set backing the runtime (e.g. the\n * `BrowserConnector` for host-side `sessionInfo()` / `closeSession()` /\n * `sweep()`).\n * - `tool` — what `createExecuteTool` returns.\n */\nexport interface ExecuteRuntime {\n runtime: CodemodeRuntimeHandle;\n connectors: CodemodeConnector[];\n tool: Tool;\n}\n\nfunction isAgent(\n source: CreateExecuteToolOptions | ExecuteToolAgent\n): source is ExecuteToolAgent {\n // An options bag has no `env`, but guard against a hand-built object that\n // happens to carry one (e.g. spread from a worker handler): an explicit\n // `executor`/`loader` key marks it as options — agents never have those.\n // (Other option keys like `tools`/`browser` can legitimately exist on agent\n // subclasses, so they can't discriminate.)\n return \"env\" in source && !(\"executor\" in source) && !(\"loader\" in source);\n}\n\nfunction optionsFromAgent(agent: ExecuteToolAgent): CreateExecuteToolOptions {\n const env = ((agent as unknown as { env?: unknown }).env ?? {}) as {\n LOADER?: WorkerLoader;\n BROWSER?: BrowserBinding;\n };\n const ctx = (agent as unknown as { ctx?: DurableObjectState }).ctx;\n if (!ctx) {\n throw new Error(\n \"createExecuteTool(agent) requires a Durable Object agent — \" +\n \"call createExecuteTool({ ctx, loader, ... }) with explicit options.\"\n );\n }\n return {\n ctx,\n loader: env.LOADER,\n browser: env.BROWSER\n };\n}\n\n/**\n * Build the codemode runtime behind the execute tool, returning the runtime\n * handle and connectors alongside the tool. Use this instead of\n * {@link createExecuteTool} when the host needs approvals, the audit trail,\n * snippets, or browser session management.\n *\n * When called with an agent, the runtime handle is also assigned to\n * `agent.codemode` so callables (and Think's built-in approval flow) can\n * reach it.\n *\n * @deprecated Code execution is moving to the Workspace: give it a\n * codemode backend with a `codemode:tools` module\n * (`createToolBindings(forAISDKTools(() => this.getTools()))` from\n * `@cloudflare/computer`), so code the model runs with `exec` imports the\n * agent's tools and reads files through `node:fs`.\n */\nexport function createExecuteRuntime(\n source: CreateExecuteToolOptions | ExecuteToolAgent,\n overrides?: Partial<Omit<CreateExecuteToolOptions, \"ctx\">>\n): ExecuteRuntime {\n const agent = isAgent(source) ? source : undefined;\n const options: CreateExecuteToolOptions = isAgent(source)\n ? { ...optionsFromAgent(source), ...overrides }\n : { ...source, ...overrides };\n\n if (agent && !options.executor && !options.loader) {\n throw new Error(\n \"createExecuteTool(agent) requires a WorkerLoader binding named LOADER — \" +\n 'add `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` to wrangler.jsonc, ' +\n \"or call createExecuteTool({ ctx, loader, ... }) with explicit options.\"\n );\n }\n\n let executor: Executor;\n if (options.executor) {\n executor = options.executor;\n } else if (options.loader) {\n executor = new DynamicWorkerExecutor({\n loader: options.loader,\n timeout: options.timeout,\n globalOutbound: options.globalOutbound\n });\n } else {\n throw new Error(\n \"createExecuteTool requires either an `executor` or a `loader` \" +\n '(WorkerLoader binding — `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` ' +\n \"in wrangler.jsonc).\"\n );\n }\n\n const connectors: CodemodeConnector[] = [];\n if (options.tools && Object.keys(options.tools).length > 0) {\n connectors.push(\n new ToolSetConnector(options.ctx, { tools: options.tools })\n );\n }\n if (options.browser) {\n connectors.push(\n new BrowserConnector(options.ctx, {\n browser: options.browser,\n store: new DurableBrowserSessionStore(options.ctx.storage),\n session: options.session ?? { mode: \"dynamic\" },\n timeout: options.timeout\n })\n );\n }\n connectors.push(...(options.connectors ?? []));\n\n if (connectors.length === 0) {\n throw new Error(\n \"createExecuteTool has nothing to expose — provide at least one of \" +\n \"`tools`, `browser`, or `connectors`.\"\n );\n }\n\n const runtime = createCodemodeRuntime({\n ctx: options.ctx,\n executor,\n connectors,\n name: options.name ?? \"execute\",\n transformResult: truncateResult\n });\n\n if (agent) {\n agent.codemode = runtime;\n }\n\n const baseTool = runtime.tool({\n description: options.description,\n connectorHints: connectorHints(options)\n });\n const baseExecute = baseTool.execute;\n const tool: Tool = baseExecute\n ? ({\n ...baseTool,\n // Paused outputs land in the transcript (and the model context) as a\n // normal tool result; a gated call's raw args (e.g. a writeFile\n // payload) can be huge. Truncate them in the model-facing payload —\n // the runtime facet keeps the full args for the actual resume, and\n // the host can fetch detail via `pendingExecutions`.\n execute: async (input: unknown, callOptions: unknown) =>\n truncatePausedExecutionOutput(\n await (baseExecute as (i: unknown, o: unknown) => Promise<unknown>)(\n input,\n callOptions\n )\n )\n } as Tool)\n : baseTool;\n\n return {\n runtime,\n connectors,\n tool\n };\n}\n\n/**\n * One-line usage hints for the namespaces createExecuteTool itself wires up,\n * rendered into the default tool description. Models otherwise tend to guess\n * a filesystem API (`host.*`, `fs.*`) instead of discovering `tools.*` via\n * `codemode.search`.\n */\nfunction connectorHints(\n options: CreateExecuteToolOptions\n): Record<string, string> {\n const hints: Record<string, string> = {};\n if (options.tools) {\n const names = Object.entries(options.tools)\n .filter(([, t]) => typeof t.execute === \"function\")\n .map(([name]) => name);\n if (names.length > 0) {\n hints.tools =\n `your host tools as async functions — e.g. \\`await tools.${names[0]}({ ... })\\`. ` +\n `Available: ${names.join(\", \")}`;\n }\n }\n if (options.browser) {\n hints.cdp =\n \"a live browser over the Chrome DevTools Protocol. \" +\n 'Target-scoped commands need no sessionId: `cdp.send({ method: \"Target.createTarget\", params: { url } })`. ' +\n \"Page-scoped commands (Page.*, Runtime.*, DOM.*) need one: \" +\n \"`const { sessionId } = await cdp.attachToTarget({ targetId })`, then \" +\n \"`cdp.send({ method, params, sessionId })`. Discover commands with `cdp.spec()`\";\n }\n return hints;\n}\n\n/** Character budget for a pending action's args in the transcript. */\nconst PENDING_ARGS_MAX_CHARS = 2_000;\n\n/**\n * Truncate the `pending[].args` of a paused execution output for transcript /\n * model consumption. The full args stay on the runtime facet (used by the\n * actual resume); only the model-facing copy is bounded. Non-paused outputs\n * pass through unchanged.\n */\nexport function truncatePausedExecutionOutput(output: unknown): unknown {\n if (typeof output !== \"object\" || output === null) return output;\n const o = output as { status?: unknown; pending?: unknown };\n if (o.status !== \"paused\" || !Array.isArray(o.pending)) return output;\n return {\n ...o,\n pending: o.pending.map((action) => {\n if (typeof action !== \"object\" || action === null) return action;\n const a = action as { args?: unknown };\n if (!(\"args\" in a)) return action;\n return {\n ...a,\n args: truncateResult(a.args, { maxChars: PENDING_ARGS_MAX_CHARS })\n };\n })\n };\n}\n\n/**\n * Create a code execution tool that lets the LLM write and run TypeScript\n * against your tools and (optionally) a live browser — all inside a sandboxed Worker, recorded on a durable codemode\n * runtime (abort-and-replay, approvals, snippets).\n *\n * The model sees typed namespaces: `tools.*` for your AI SDK tools and\n * `cdp.*` for the browser. To give the sandbox the workspace, pass the\n * workspace tools: `tools: createAITools({ workspace: this.workspace })`.\n *\n * Setup checklist:\n *\n * - `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc\n * - `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc (for `cdp.*`)\n * - export the runtime class from your worker entry:\n * `export { CodemodeRuntime } from \"@cloudflare/codemode\"`\n * (the `@cloudflare/codemode/vite` plugin does this automatically)\n *\n * @example One-liner — defaults from the agent\n * ```ts\n * getTools() {\n * return {\n * // cdp.* if env.BROWSER is bound,\n * // executor from env.LOADER\n * execute: createExecuteTool(this)\n * };\n * }\n * ```\n *\n * @example Agent defaults plus overrides (e.g. custom tools.*)\n * ```ts\n * execute: createExecuteTool(this, { tools: myDomainTools })\n * ```\n *\n * @example Explicit options\n * ```ts\n * execute: createExecuteTool({\n * ctx: this.ctx,\n * tools: myDomainTools, // tools.*\n * browser: this.env.BROWSER, // cdp.*\n * loader: this.env.LOADER\n * })\n * ```\n *\n * Use {@link createExecuteRuntime} to also get the runtime handle\n * (approvals, audit, snippets) and the connector set.\n *\n * @deprecated Code execution is moving to the Workspace: give it a\n * codemode backend with a `codemode:tools` module\n * (`createToolBindings(forAISDKTools(() => this.getTools()))` from\n * `@cloudflare/computer`), so code the model runs with `exec` imports the\n * agent's tools and reads files through `node:fs`.\n */\nexport function createExecuteTool(\n source: CreateExecuteToolOptions | ExecuteToolAgent,\n overrides?: Partial<Omit<CreateExecuteToolOptions, \"ctx\">>\n): Tool {\n return createExecuteRuntime(source, overrides).tool;\n}\n"],"mappings":"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"}
@@ -1,4 +1,4 @@
1
- import { t as ExtensionManager } from "../manager-rze95KCk.js";
1
+ import { t as ExtensionManager } from "../manager-CWGumyKi.js";
2
2
  import { ToolSet } from "ai";
3
3
 
4
4
  //#region src/tools/extensions.d.ts
@@ -1,4 +1,4 @@
1
- import { n as sanitizeName } from "../manager-BubfmA3q.js";
1
+ import { c as sanitizeName } from "../manager-B3rcb_6p.js";
2
2
  import { tool } from "ai";
3
3
  import { z } from "zod";
4
4
  //#region src/tools/extensions.ts
@@ -1,2 +1,2 @@
1
- import { t as createFetchTools } from "../fetch-DO3uQ9py.js";
1
+ import { t as createFetchTools } from "../fetch-BbYxtlff.js";
2
2
  export { createFetchTools };
@@ -1,6 +1,9 @@
1
- import { Tn as ThinkSubmissionStatus, gn as Think } from "./index-DDnny6kt.js";
2
- import { ZodObject, z } from "zod";
1
+ import {
2
+ un as Think,
3
+ wn as ThinkSubmissionStatus
4
+ } from "./manager-CWGumyKi.js";
3
5
  import { WorkflowEvent, WorkflowSleepDuration } from "cloudflare:workers";
6
+ import { ZodObject, z } from "zod";
4
7
  import {
5
8
  AgentWorkflow,
6
9
  AgentWorkflowStep,
package/docs/actions.md CHANGED
@@ -186,6 +186,14 @@ await agent.rejectExecution(executionId, "Stop here", { autoContinue: false });
186
186
 
187
187
  The rejection is still recorded in the transcript, so the next user message
188
188
  continues the conversation with it in view.
189
+
190
+ If `getActions()` no longer returns the action when the approval is taken,
191
+ `execute` does not run: the approval is consumed and the call is answered with
192
+ an error that says the action is no longer registered. The action is looked up
193
+ each time Think tries the approved call: when the approval is taken, and again
194
+ if a restart interrupts the call and it is tried again. An action you withdraw
195
+ while a try is already running still runs to its end.
196
+
189
197
  `pendingApprovals()` merges parked actions and paused Codemode executions, so a
190
198
  single approval UI can drive both. (`durable-pause` requires an `approval`
191
199
  policy — an action that would never park is rejected at definition time.)
@@ -205,6 +213,10 @@ removal are applied before the next model call. A client that resubmits an
205
213
  older copy of the message, still showing the paused output, does not restore
206
214
  the paused output or the removed text.
207
215
 
216
+ A durable pause that has waited for its approval longer than
217
+ `actionPendingApprovalTtlMs` (30 days by default) is dropped when the agent
218
+ starts; 0.24 kept it across a restart. Set it to `false` to keep them.
219
+
208
220
  Both approval-gated and durable-pause parts carry a stable
209
221
  `ActionApprovalDescriptor` (`{ requestId, toolCallId, action, summary, input,
210
222
  permissions, risk, kind }`) so your UI has everything it needs to render the
package/docs/channels.md CHANGED
@@ -22,11 +22,11 @@ Override `configureChannels()` to return a map of channel id to
22
22
  `ChannelDefinition`. The id is how you select the channel on a turn:
23
23
 
24
24
  ```typescript
25
- import { Think, messengerChannel } from "@cloudflare/think";
26
- import { telegram } from "@chat-adapter/telegram";
25
+ import { Think, messengerChannel, type ThinkChannels } from "@cloudflare/think";
26
+ import { telegramMessenger } from "@cloudflare/think/messengers/telegram";
27
27
 
28
28
  export class Assistant extends Think<Env> {
29
- configureChannels() {
29
+ configureChannels(): ThinkChannels {
30
30
  return {
31
31
  // Override policy for the built-in web channel.
32
32
  web: {
@@ -42,7 +42,13 @@ export class Assistant extends Think<Env> {
42
42
  maxTurns: 3
43
43
  },
44
44
  // A messenger channel (Chat SDK webhook).
45
- telegram: messengerChannel(telegram({/* adapter config */}))
45
+ telegram: messengerChannel(
46
+ telegramMessenger({
47
+ token: this.env.TELEGRAM_BOT_TOKEN,
48
+ userName: "support_bot",
49
+ secretToken: this.env.TELEGRAM_WEBHOOK_SECRET_TOKEN
50
+ })
51
+ )
46
52
  };
47
53
  }
48
54
  }
@@ -14,31 +14,44 @@ Client tools are tools without an `execute` function on the server — they only
14
14
 
15
15
  ## Defining Client Tools
16
16
 
17
- On the client, pass `clientTools` to `useAgentChat`:
17
+ On the client, pass the tools to `useAgentChat` as `tools`, and run them in `onToolCall`. The hook sends the schema of each tool that has an `execute` with every request. When the model calls one, `onToolCall` runs it and sends its output back with `addToolOutput`:
18
18
 
19
19
  ```tsx
20
20
  import { useAgent } from "agents/react";
21
21
  import { useAgentChat } from "@cloudflare/think/react";
22
22
 
23
+ const tools = {
24
+ getUserTimezone: {
25
+ description: "Get the user's timezone from their browser",
26
+ parameters: { type: "object" as const, properties: {} },
27
+ execute: async () => Intl.DateTimeFormat().resolvedOptions().timeZone
28
+ },
29
+ getUserLanguage: {
30
+ description: "Get the language the user's browser is set to",
31
+ parameters: { type: "object" as const, properties: {} },
32
+ execute: async () => navigator.language
33
+ }
34
+ };
35
+
23
36
  function Chat() {
24
37
  const agent = useAgent({ agent: "MyAgent" });
25
38
  const { messages, sendMessage } = useAgentChat({
26
39
  agent,
27
- clientTools: {
28
- getUserTimezone: {
29
- description: "Get the user's timezone from their browser",
30
- parameters: {},
31
- execute: async () => {
32
- return Intl.DateTimeFormat().resolvedOptions().timeZone;
33
- }
34
- },
35
- getClipboard: {
36
- description: "Read text from the user's clipboard",
37
- parameters: {},
38
- execute: async () => {
39
- return navigator.clipboard.readText();
40
- }
40
+ tools,
41
+ onToolCall: async ({ toolCall, addToolOutput }) => {
42
+ const tool = tools[toolCall.toolName as keyof typeof tools];
43
+ if (!tool) {
44
+ addToolOutput({
45
+ toolCallId: toolCall.toolCallId,
46
+ state: "output-error",
47
+ errorText: `No client tool named ${toolCall.toolName}`
48
+ });
49
+ return;
41
50
  }
51
+ addToolOutput({
52
+ toolCallId: toolCall.toolCallId,
53
+ output: await tool.execute()
54
+ });
42
55
  }
43
56
  });
44
57
 
@@ -46,7 +59,7 @@ function Chat() {
46
59
  }
47
60
  ```
48
61
 
49
- The `parameters` field is a JSON Schema object describing the tool's input. The `execute` function runs in the browser.
62
+ The `parameters` field is a JSON Schema object describing the tool's input. A tool in `tools` without an `execute` is not sent. A tool the server declares in `getTools()` without an `execute` still reaches the client: its calls come to `onToolCall` the same way. `useAgentChat` does not run `execute` by itself: `onToolCall` must answer every call, with an output or an error, or the turn waits for a result.
50
63
 
51
64
  ## Client Tools over the Sub-Agent RPC `chat()` Path
52
65
 
@@ -125,26 +138,41 @@ When `needsApproval` returns `true`:
125
138
 
126
139
  ### Handling approvals on the client
127
140
 
128
- `useAgentChat` provides approval helpers:
141
+ A tool call that waits for approval is a tool part in the `approval-requested` state. Render your approval UI from it, and answer with `addToolApprovalResponse`, passing the part's approval id:
129
142
 
130
143
  ```tsx
131
- const { messages, sendMessage, addToolResult } = useAgentChat({
132
- agent,
133
- onToolCall: ({ toolCall }) => {
134
- // Auto-approve safe tools
135
- if (toolCall.toolName === "read") {
136
- return { approve: true };
137
- }
138
- // Others go through the UI approval flow
139
- }
144
+ const { messages, sendMessage, addToolApprovalResponse } = useAgentChat({
145
+ agent
140
146
  });
147
+
148
+ // In the render of a tool part:
149
+ if (part.state === "approval-requested") {
150
+ return (
151
+ <>
152
+ <button
153
+ onClick={() =>
154
+ addToolApprovalResponse({ id: part.approval.id, approved: true })
155
+ }
156
+ >
157
+ Approve
158
+ </button>
159
+ <button
160
+ onClick={() =>
161
+ addToolApprovalResponse({ id: part.approval.id, approved: false })
162
+ }
163
+ >
164
+ Deny
165
+ </button>
166
+ </>
167
+ );
168
+ }
141
169
  ```
142
170
 
143
171
  See [Client Tools Continuation](https://github.com/cloudflare/agents/blob/main/docs/agents/client-tools-continuation.md) for the full protocol reference.
144
172
 
145
173
  ## Auto-Continuation
146
174
 
147
- After a client tool result is received, Think can automatically continue the conversation without a new user message. This is the default behavior — when all pending tool results are received, Think starts a new model turn with the tool results in context.
175
+ After a client tool result is received, Think can automatically continue the conversation without a new user message. This is the default behavior — when all pending tool results are received, Think starts a new model turn with the tool results in context. A result sent with `state: "output-error"` does not ask for that continuation itself: when it is the only result, it is stored and the turn does not continue; when another result in the same batch asks to continue, the turn continues with both.
148
176
 
149
177
  The continuation turn has `continuation: true` in the `TurnContext`, which you can use in `beforeTurn` to adjust model or tool selection:
150
178
 
@@ -183,6 +211,8 @@ export class MyAgent extends Think<Env> {
183
211
  | `"drop"` | Ignore overlapping submits entirely. Messages are not persisted. |
184
212
  | `{ strategy: "debounce", debounceMs?: number }` | Trailing-edge latest with a quiet window (default 750ms). |
185
213
 
214
+ A message that arrives while a turn runs waits until its own turn starts before it is stored in the Session, as a child of the reply it waited behind. Each turn answers its own message: the conversation reads `U1, A1, U2, A2`, and the model never sees a question queued behind the turn it is answering. Every tab sees the waiting message at once: the message list Think sends ends with it and names it in `queuedMessageIds`, and `useAgentChat` draws it after the reply that is streaming. A superseded message under `"latest"`, `"merge"` or `"debounce"`, or a message whose request is stopped while it waits, is stored when its turn would have started. A clear drops it.
215
+
186
216
  Concurrency strategies only apply to `submit-message` requests. Regenerations, tool continuations, approvals, clears, `saveMessages`, durable `submitMessages` submissions, and `continueLastTurn` keep their serialized behavior.
187
217
 
188
218
  ### Examples
@@ -0,0 +1,92 @@
1
+ # Context
2
+
3
+ > **Experimental.** Think's context API may change between releases while it stabilizes.
4
+
5
+ Context is how a Think agent arranges its system prompt and keeps data the model reads and writes across turns: who the agent is, what it has learned about the user, a knowledge base it can search. You declare it as labelled blocks. Think renders the blocks into the system prompt, gives the model tools for the blocks it can change, and records on the session what each turn was sent, so a long conversation keeps hitting the model provider's prompt cache.
6
+
7
+ The [session](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) is the transcript: messages, branches, compaction. Context sits beside it. It never changes a message, and the transcript never holds the prompt text.
8
+
9
+ ## Declare blocks
10
+
11
+ ```ts
12
+ import { Think } from "@cloudflare/think";
13
+ import type { ContextConfig } from "agents/context";
14
+
15
+ export class MyAgent extends Think<Env> {
16
+ configureContext(): ContextConfig[] {
17
+ return [
18
+ {
19
+ label: "soul",
20
+ provider: { get: async () => "You are a helpful coding assistant." }
21
+ },
22
+ {
23
+ label: "memory",
24
+ description: "Facts learned about the user",
25
+ maxTokens: 1_100
26
+ },
27
+ {
28
+ label: "environment",
29
+ provider: {
30
+ get: async () => `Today is ${new Date().toISOString().slice(0, 10)}.`
31
+ },
32
+ whenChanged: "remind"
33
+ }
34
+ ];
35
+ }
36
+ }
37
+ ```
38
+
39
+ Each block renders as a section of the system prompt with a header: the label, the description, how much of `maxTokens` it uses, and whether the model can change it (`[readonly]`, `[writable]`, `[searchable]`). An empty read-only block is left out.
40
+
41
+ What a block can do depends on its provider:
42
+
43
+ | Provider | The block is |
44
+ | ---------------------- | ------------------------------------------------ |
45
+ | none | writable, stored in the agent's SQLite |
46
+ | `get()` | read-only text |
47
+ | `get()` and `set()` | writable, stored wherever your provider keeps it |
48
+ | `get()` and `search()` | a summary in the prompt, searched through a tool |
49
+
50
+ The model writes a writable block with the `set_context` tool and searches a searchable one with `search_context`. `AgentSearchProvider` from `agents/context` is a searchable block backed by full-text search in the agent's SQLite.
51
+
52
+ Blocks can also come from the `withContext()` chain in `configureSession()`; those render after the ones `configureContext()` returns.
53
+
54
+ ## What the model is sent
55
+
56
+ The first turn renders every block and records that exact prompt on the session. Every later turn opens with the same text, so the provider can reuse the cached prefix.
57
+
58
+ When the model writes a block with `set_context`, the block is saved at once and the prompt stays as it is: the tool call and its result in the conversation are the model's record of the write, so nothing sends it again. The prompt is rebuilt from the blocks at the first turn after a compaction, when the cached prefix is gone anyway, and a change the model did not make (a write from your code, or a `whenChanged: "remind"` block whose value moved on) is sent once, after the next user message.
59
+
60
+ A block declared `whenChanged: "remind"` is for values that move on while the conversation runs: the date, the state of a workspace. When its value changes, the next turn sends the new value once, after that turn's user message, and records it there. Every later request shows it in the same place, so nothing already sent is rewritten. A value that changes in an ordinary block's provider, without a write through `this.context`, reaches the model at the next rebuild.
61
+
62
+ `this.context.refreshSystemPrompt()` renders the blocks again; the next turn records the new prompt. That costs one prompt-cache miss, so Think does it where the cache is already gone: after a compaction and after the history is cleared. A refresh survives the agent being evicted before its next turn.
63
+
64
+ A regenerated answer is sent the prompt its own branch was sent, never a newer one. A turn that is recovered or retried after being cut off is sent again exactly as it was first sent; a change or a refresh that arrived in between waits for the next user message.
65
+
66
+ A compaction summary is written from the stored messages, which never hold a reminder. A request after a compaction that cannot rebuild the prompt (a continuation of the last answer) restates, once and right after the summary, a value the hidden turns delivered. A forked session keeps the prompt and reminders its copied turns were sent with.
67
+
68
+ ## Change blocks from code
69
+
70
+ `this.context` is available inside your agent class once the agent has started:
71
+
72
+ ```ts
73
+ await this.context.setBlock("memory", "Prefers TypeScript.");
74
+ await this.context.appendToBlock("memory", "Deploys on Fridays.");
75
+ this.context.getBlock("memory")?.content;
76
+
77
+ await this.context.addBlock({ label: "project", provider: projectBrief });
78
+ this.context.removeBlock("project");
79
+ await this.context.refreshSystemPrompt();
80
+ ```
81
+
82
+ A block written with `setBlock()` or `appendToBlock()` reaches the model once, after the next user message, and stays there. If a request goes out before that message (a continuation of an answer, or a regenerated one), the value also rides on that request, so the model is not working from the old one; that copy is not kept. Added and removed blocks enter or leave the prompt at the next rebuild: after a compaction, or a refresh.
83
+
84
+ ## What changed
85
+
86
+ If you used `agents/context` directly before this release:
87
+
88
+ - `freezeSystemPrompt()`, `refreshSystemPrompt()` and `reminder()` moved from `ContextBlocks` to `Context`, Think's context bound to a session. `ContextBlocks` keeps the blocks and their tools, and no longer takes a prompt store; `renderSystemPrompt()` renders the blocks as they stand.
89
+ - Think's `this.context` is a `Context`. The methods you called on it keep their names and signatures.
90
+ - An agent upgraded from an earlier release keeps the prompt it last froze: its first turn opens with exactly that text, and an answer from before the upgrade is regenerated with it. A remind block that changed since is sent once on that turn. A conversation started after the upgrade, or after the chat is cleared, does not use it.
91
+ - Think no longer writes a `_system_prompt` row; each prompt it records lives on the session.
92
+ - A store passed to `withCachedPrompt(provider)` is no longer written. It is only read, for the prompt frozen before the upgrade, which the turns from before the upgrade are sent until the chat is cleared. A store that throws or holds nothing is treated as having no prompt.
@@ -87,7 +87,7 @@ export class MyAgent extends Think<Env> {
87
87
  // A string is resolved through Think's built-in workers-ai-provider off the
88
88
  // `AI` binding. Use a "@cf/..." id for Workers AI, or a "provider/model"
89
89
  // slug like "openai/gpt-5.5" to route through AI Gateway.
90
- return "@cf/moonshotai/kimi-k2.7-code";
90
+ return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
91
91
  }
92
92
 
93
93
  getSystemPrompt() {
@@ -207,7 +207,7 @@ import type { ContextConfig } from "agents/context";
207
207
 
208
208
  export class MyAgent extends Think<Env> {
209
209
  getModel() {
210
- return "@cf/moonshotai/kimi-k2.7-code";
210
+ return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
211
211
  }
212
212
 
213
213
  configureContext(): ContextConfig[] {
@@ -233,7 +233,7 @@ Now the model sees a `MEMORY` section in its system prompt and gets a `set_conte
233
233
 
234
234
  When you declare context blocks, the system prompt is built from those blocks, with an overridden `getSystemPrompt()` at the top. The `"soul"` block above acts as the system identity: it is read-only and always appears first. The `"memory"` block is writable, and the model updates it when it learns something useful. The frozen system prompt is always persisted, so a cold wake reuses the exact prompt string the model already cached.
235
235
 
236
- The assembled blocks are available as `this.context` once the Lifecycle has started. See the [Context documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/context.md) for providers, tools, and frozen-prompt behavior, and the [Sessions documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for compaction, search, and multi-session support.
236
+ The assembled blocks are available as `this.context` once the Lifecycle has started. See [Context](./context.md) for providers, tools, and what the model is sent, and the [Sessions documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for compaction, search, and multi-session support.
237
237
 
238
238
  ## 7. Add custom tools
239
239
 
@@ -315,5 +315,5 @@ See [Lifecycle Hooks](./lifecycle-hooks.md) for the full reference.
315
315
  - [Tools](./tools.md) — workspace tools, code execution, extensions
316
316
  - [Client Tools](./client-tools.md) — browser-side tools, approval flows, concurrency
317
317
  - [Sub-agents and Programmatic Turns](./sub-agents.md) — RPC streaming, scheduled turns, recovery
318
- - [Context](https://github.com/cloudflare/agents/blob/main/docs/agents/context.md) — context blocks, providers, prompt assembly
318
+ - [Context](./context.md) — context blocks, providers, what the model is sent
319
319
  - [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) — compaction, search, attachments, multi-session