@cloudflare/think 0.22.0 → 0.24.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.
- package/README.md +79 -117
- package/dist/extensions/index.d.ts +4 -14
- package/dist/extensions/index.js +2 -15
- package/dist/extensions/index.js.map +1 -1
- package/dist/{index-BFK9bpzz.d.ts → index-DIQ9oY1t.d.ts} +208 -75
- package/dist/{manager-dOcdCX4u.d.ts → manager-CtXhU1fK.d.ts} +9 -2
- package/dist/{manager-BubfmA3q.js → manager-sfWIcYJT.js} +24 -4
- package/dist/manager-sfWIcYJT.js.map +1 -0
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
- package/dist/think.d.ts +2 -2
- package/dist/think.js +135 -88
- package/dist/think.js.map +1 -1
- package/dist/tools/browser.d.ts +1 -1
- package/dist/tools/browser.js +1 -1
- package/dist/tools/browser.js.map +1 -1
- package/dist/tools/execute.d.ts +2 -2
- package/dist/tools/execute.js +2 -2
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/getting-started.md +3 -3
- package/docs/index.md +100 -95
- package/docs/lifecycle-hooks.md +13 -13
- package/docs/multi-chat.md +8 -7
- package/docs/tools.md +12 -14
- package/docs/workflows.md +1 -1
- package/package.json +6 -6
- package/dist/manager-BubfmA3q.js.map +0 -1
package/dist/tools/browser.d.ts
CHANGED
|
@@ -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/
|
|
66
|
+
* return createWorkersAI({ binding: this.env.AI })("@cf/deepseek-ai/deepseek-v4.1-flash-1017");
|
|
67
67
|
* }
|
|
68
68
|
*
|
|
69
69
|
* getTools() {
|
package/dist/tools/browser.js
CHANGED
|
@@ -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/
|
|
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/
|
|
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"}
|
package/dist/tools/execute.d.ts
CHANGED
|
@@ -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
|
-
*
|
|
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
|
-
*
|
|
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`.
|
package/dist/tools/execute.js
CHANGED
|
@@ -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
|
-
*
|
|
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
|
-
*
|
|
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<CreateExecuteToolOpt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;GAC3B,OAAO;IACL,GAAG;IACH,MAAM,eAAe,EAAE,MAAM,EAAE,UAAU,uBAAuB,CAAC;GACnE;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,kBACd,QACA,WACM;CACN,OAAO,qBAAqB,QAAQ,SAAS,CAAC,CAAC;AACjD"}
|
|
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(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eAAe,EAAE,MAAM,EAAE,UAAU,uBAAuB,CAAC;GACnE;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,kBACd,QACA,WACM;CACN,OAAO,qBAAqB,QAAQ,SAAS,CAAC,CAAC;AACjD"}
|
package/dist/tools/extensions.js
CHANGED
package/dist/workflows.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Tn as ThinkSubmissionStatus, gn as Think } from "./index-DIQ9oY1t.js";
|
|
2
2
|
import { ZodObject, z } from "zod";
|
|
3
3
|
import { WorkflowEvent, WorkflowSleepDuration } from "cloudflare:workers";
|
|
4
4
|
import {
|
package/docs/getting-started.md
CHANGED
|
@@ -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/
|
|
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/
|
|
210
|
+
return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
|
|
211
211
|
}
|
|
212
212
|
|
|
213
213
|
configureContext(): ContextConfig[] {
|
|
@@ -231,7 +231,7 @@ export class MyAgent extends Think<Env> {
|
|
|
231
231
|
|
|
232
232
|
Now the model sees a `MEMORY` section in its system prompt and gets a `set_context` tool to update it. A block declared without a `provider` is auto-wired to durable per-agent SQLite, so facts written to memory survive DO hibernation and restarts.
|
|
233
233
|
|
|
234
|
-
When you declare context blocks, the system prompt is built from those blocks
|
|
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
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.
|
|
237
237
|
|
package/docs/index.md
CHANGED
|
@@ -47,7 +47,7 @@ export class MyAgent extends Think<Env> {
|
|
|
47
47
|
// Resolved via Think's built-in workers-ai-provider off the `AI` binding.
|
|
48
48
|
// Use a "@cf/..." id for Workers AI, or a "provider/model" slug like
|
|
49
49
|
// "openai/gpt-5.5" to route through AI Gateway.
|
|
50
|
-
return "@cf/
|
|
50
|
+
return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
|
|
@@ -397,7 +397,7 @@ path.
|
|
|
397
397
|
| `getModel()` | throws | Return a model id `string` (resolved via the bundled `workers-ai-provider` off `getAIBinding()` — a `@cf/...` id hits Workers AI, a `"provider/model"` slug routes through AI Gateway) or a `LanguageModel` |
|
|
398
398
|
| `getGateway(model)` | `undefined` | AI Gateway options (`id`, `metadata`, cache settings) for a string model — see [AI Gateway options](#ai-gateway-options) |
|
|
399
399
|
| `getAIBinding()` | `this.env.AI` | Workers AI binding used to resolve string models from `getModel()` |
|
|
400
|
-
| `getSystemPrompt()` | `"You are a helpful assistant."` |
|
|
400
|
+
| `getSystemPrompt()` | `"You are a helpful assistant."` | Instructions at the top of the system prompt, above context blocks. The default is used only with no context blocks |
|
|
401
401
|
| `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
|
|
402
402
|
| `getScheduledTasks()` | `{}` | Code-declared recurring prompts or handlers |
|
|
403
403
|
| `getScheduledTasksScope()` | `"root"` | Which instances arm the declared tasks — `"root"` (top-level agent only) or `"all"` (sub-agents too) |
|
|
@@ -414,7 +414,6 @@ path.
|
|
|
414
414
|
| `hydrationByteBudget` | 32 MiB | Byte budget for startup transcript hydration. Charges each row its stored bytes plus the attachment bytes it re-inflates |
|
|
415
415
|
| `mediaEviction` | `true` | Media eviction policy: aged media leaves the conversation and is preserved as a Workspace file. `false` keeps aged media in the conversation |
|
|
416
416
|
| `getSkills()` | `[]` | Return Agent Skills sources for on-demand skill activation |
|
|
417
|
-
| `skillWorkspace` | `false` | Project skills into the Workspace as files; `{}` enables with defaults |
|
|
418
417
|
| `getSkillScriptRunner()` | `null` | Enable the optional `run_skill_script` tool |
|
|
419
418
|
| `fetchTools` | `false` | Opt-in allowlisted, read-only HTTP fetch tools (`fetch_url` + per-binding `fetch_<name>`). Set to a config object; see [Fetch tool](#fetch-tool) |
|
|
420
419
|
| `messageConcurrency` | `"queue"` | How overlapping submits behave — see [Client Tools](./client-tools.md) |
|
|
@@ -472,84 +471,72 @@ See [Tools](./tools.md#mcp-tools) for MCP setup and alternative exposure paths.
|
|
|
472
471
|
|
|
473
472
|
## Agent Skills
|
|
474
473
|
|
|
475
|
-
Think supports [Agent Skills](https://agentskills.io/)
|
|
476
|
-
instructions. A skill
|
|
477
|
-
Think adds
|
|
478
|
-
when a
|
|
474
|
+
Think supports [Agent Skills](https://agentskills.io/): on-demand
|
|
475
|
+
instructions, references, and scripts. A skill is a directory with a
|
|
476
|
+
`SKILL.md` file. Think adds each skill's name and description to the system
|
|
477
|
+
prompt and gives the model tools to load a skill when a task matches it.
|
|
479
478
|
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
```typescript
|
|
484
|
-
import { cloudflare } from "@cloudflare/vite-plugin";
|
|
485
|
-
import agents from "agents/vite";
|
|
486
|
-
import { defineConfig } from "vite";
|
|
487
|
-
|
|
488
|
-
export default defineConfig({
|
|
489
|
-
plugins: [agents(), cloudflare()]
|
|
490
|
-
});
|
|
491
|
-
```
|
|
492
|
-
|
|
493
|
-
Then import the bundled skill manifest:
|
|
479
|
+
The simplest place to keep skills is the agent's Workspace. Every
|
|
480
|
+
`/workspace/.agents/skills/<name>/SKILL.md` is a skill, and the files beside it
|
|
481
|
+
are its resources:
|
|
494
482
|
|
|
495
483
|
```typescript
|
|
496
484
|
import { Think, skills } from "@cloudflare/think";
|
|
497
|
-
import bundledSkills from "agents:skills"; // resolves to ./skills next to this file
|
|
498
485
|
|
|
499
486
|
export class MyAgent extends Think<Env> {
|
|
500
487
|
getSkills() {
|
|
501
|
-
return [
|
|
502
|
-
bundledSkills,
|
|
503
|
-
skills.r2(this.env.SKILLS_BUCKET, { prefix: "skills/" })
|
|
504
|
-
];
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
getSkillScriptRunner() {
|
|
508
|
-
return skills.runner({
|
|
509
|
-
loader: this.env.LOADER,
|
|
510
|
-
workspaceInstance: this.workspace
|
|
511
|
-
});
|
|
488
|
+
return [skills.workspace(this.workspace)];
|
|
512
489
|
}
|
|
513
490
|
}
|
|
514
491
|
```
|
|
515
492
|
|
|
516
|
-
`agents:skills` resolves to a `./skills` directory next to the importing file;
|
|
517
|
-
use `agents:skills/<dir>` to point at a differently named sibling directory.
|
|
518
|
-
The `agents:skills` import is typed by ambient declarations that ship with
|
|
519
|
-
`agents`, so importing `Think` in the same file brings the type into scope (for
|
|
520
|
-
a file that imports only the specifier, add
|
|
521
|
-
`/// <reference types="agents/skills-module" />`). If you are not using the
|
|
522
|
-
Agents Vite plugin, build a source with `skills.fromManifest(...)` instead.
|
|
523
|
-
|
|
524
|
-
The skills engine lives in `agents/skills` and is framework-agnostic, so any
|
|
525
|
-
agent (including a plain `@cloudflare/ai-chat` `onChatMessage`) can build a
|
|
526
|
-
`SkillRegistry`; `@cloudflare/think` re-exports it as `skills` and wires
|
|
527
|
-
`getSkills()` into the turn automatically.
|
|
528
|
-
|
|
529
|
-
Think can also project each resolved `SKILL.md` into the active workspace so
|
|
530
|
-
the agent can read and edit skills as files. This is off by default: skills
|
|
531
|
-
load from their sources and nothing is written to the Workspace. Set
|
|
532
|
-
`skillWorkspace = {}` to enable it. Skills land under `/workspace/.agents/skills`.
|
|
533
|
-
Existing workspace edits are preserved and
|
|
534
|
-
affect later activation. Resources copy into the workspace when first requested
|
|
535
|
-
rather than at startup. A durable source fingerprint lets unchanged cold wakes
|
|
536
|
-
attach to the existing projection without statting or rewriting every file.
|
|
537
|
-
|
|
538
|
-
Set `skillWorkspace = { root: "/some/other/dir" }` to project skills somewhere
|
|
539
|
-
else.
|
|
540
|
-
|
|
541
|
-
Sources are applied in order; the first source to register a skill name wins,
|
|
542
|
-
and later duplicates (or a source that fails to load) are skipped with a logged
|
|
543
|
-
warning rather than failing the agent.
|
|
544
|
-
|
|
545
|
-
The imported directory should contain one child directory per skill:
|
|
546
|
-
|
|
547
493
|
```text
|
|
548
|
-
agents/
|
|
549
|
-
agents/
|
|
550
|
-
agents/
|
|
494
|
+
/workspace/.agents/skills/release-notes/SKILL.md
|
|
495
|
+
/workspace/.agents/skills/release-notes/scripts/format-release-notes.js
|
|
496
|
+
/workspace/.agents/skills/release-notes/references/style-guide.md
|
|
551
497
|
```
|
|
552
498
|
|
|
499
|
+
Think lists every source before each turn, so a skill written, edited, or
|
|
500
|
+
deleted in the Workspace (by you, a user, or the agent itself) takes effect on
|
|
501
|
+
the next turn. Pass `{ root }` to read from another directory. Skill scripts
|
|
502
|
+
are Workspace files too: give the Workspace a backend and the model runs them
|
|
503
|
+
with the `exec` tool.
|
|
504
|
+
|
|
505
|
+
Other sources:
|
|
506
|
+
|
|
507
|
+
| Source | Reads skills from |
|
|
508
|
+
| --------------------------------------- | ------------------------------------------------------ |
|
|
509
|
+
| `skills.workspace(workspace, { root })` | A `@cloudflare/computer` Workspace |
|
|
510
|
+
| `skills.r2(bucket, { prefix })` | An R2 bucket with the same layout under `prefix` |
|
|
511
|
+
| `skills.manifest({ id, skills })` | Skills defined in code, for tests and small fixed sets |
|
|
512
|
+
|
|
513
|
+
Sources are applied in order. The first source to provide a skill name wins,
|
|
514
|
+
and later duplicates are skipped with a logged warning. `skills.r2()` reuses
|
|
515
|
+
a bucket listing for 60 seconds by default; set `refreshIntervalMs` to change
|
|
516
|
+
that.
|
|
517
|
+
|
|
518
|
+
Every `SKILL.md` is checked against the
|
|
519
|
+
[spec](https://agentskills.io/specification) and loaded the way the spec's
|
|
520
|
+
[guide for agents](https://agentskills.io/client-implementation/adding-skills-support)
|
|
521
|
+
recommends. A skill that breaks a rule, such as a `name` that is not 1-64
|
|
522
|
+
lowercase letters, digits, and hyphens, does not match its directory, or a
|
|
523
|
+
`description` over 1024 characters, still loads, and Think logs a warning for
|
|
524
|
+
each broken rule. A skill with no `description`, a `name` that is not a safe
|
|
525
|
+
single path segment, or frontmatter that is not YAML is skipped and logged.
|
|
526
|
+
Frontmatter whose values contain an unquoted `: ` is read again with those
|
|
527
|
+
values quoted. To check a skill before you write it, parse it with
|
|
528
|
+
`skills.parseSkill(markdown, { directory })` and require `warnings` to be
|
|
529
|
+
empty. Frontmatter keys the spec does not define are kept in
|
|
530
|
+
`skill.extraFields`. A skill with `disable-model-invocation: true` is not
|
|
531
|
+
shown to the model.
|
|
532
|
+
|
|
533
|
+
The parser, sources, and catalog live in `agents/skills` and work without
|
|
534
|
+
Think: `skills.parseSkill()` parses a `SKILL.md`, `skills.loadSkillCatalog()`
|
|
535
|
+
merges sources, and `createSkillTools()` from `agents/skills/tools/ai-sdk`
|
|
536
|
+
builds the AI SDK tools.
|
|
537
|
+
`@cloudflare/think` re-exports the module as `skills` and wires `getSkills()`
|
|
538
|
+
into every turn.
|
|
539
|
+
|
|
553
540
|
When skills are available, Think exposes:
|
|
554
541
|
|
|
555
542
|
| Tool | Purpose |
|
|
@@ -563,13 +550,23 @@ Skills are not always-on system prompt text. Use a context block from
|
|
|
563
550
|
for task-specific procedures, references, scripts, templates, and assets that
|
|
564
551
|
should be loaded only when relevant.
|
|
565
552
|
|
|
566
|
-
Skills register a context block of their own
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
553
|
+
Skills register a context block of their own. An overridden `getSystemPrompt()`
|
|
554
|
+
stays at the top of the system prompt, above every context block, so adding
|
|
555
|
+
skills never removes it.
|
|
556
|
+
|
|
557
|
+
The skills block is a `whenChanged: "remind"` block. When a skill is added,
|
|
558
|
+
edited, or removed mid-conversation, the frozen system prompt stays the same,
|
|
559
|
+
so the model provider's prompt cache stays warm. The new catalog goes to the
|
|
560
|
+
model as a reminder after the cached prefix on the next turn, and Think folds
|
|
561
|
+
it into the system prompt at the next rebuild: compaction, or clearing the
|
|
562
|
+
history.
|
|
571
563
|
|
|
572
|
-
|
|
564
|
+
### Skill script runner
|
|
565
|
+
|
|
566
|
+
For skills that live outside a Workspace, such as in R2, `skills.runner()` runs
|
|
567
|
+
bundled scripts through `run_skill_script`. It is experimental; prefer keeping
|
|
568
|
+
skills in a Workspace and running scripts with `exec`. It needs a Worker Loader
|
|
569
|
+
binding:
|
|
573
570
|
|
|
574
571
|
```jsonc
|
|
575
572
|
{
|
|
@@ -577,17 +574,25 @@ Script execution is opt-in and requires a Worker Loader binding:
|
|
|
577
574
|
}
|
|
578
575
|
```
|
|
579
576
|
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
577
|
+
```typescript
|
|
578
|
+
getSkillScriptRunner() {
|
|
579
|
+
return skills.runner({ loader: this.env.LOADER });
|
|
580
|
+
}
|
|
581
|
+
```
|
|
584
582
|
|
|
585
|
-
|
|
583
|
+
Outside Think, import it from `agents/skills/runner`. It is a separate entry
|
|
584
|
+
point because it loads `just-bash` and `@cloudflare/codemode`.
|
|
586
585
|
|
|
587
|
-
|
|
588
|
-
|
|
586
|
+
The runner runs JavaScript, Python, and Bash scripts under `scripts/`. Python
|
|
587
|
+
runs as Python Dynamic Workers and Bash runs through `just-bash`. There is no
|
|
588
|
+
in-Worker bundler: a JavaScript script must be one self-contained module, so
|
|
589
|
+
compile TypeScript or multi-file scripts (for example with esbuild) before
|
|
590
|
+
storing the skill.
|
|
591
|
+
|
|
592
|
+
JavaScript scripts are function-style:
|
|
589
593
|
|
|
590
|
-
|
|
594
|
+
```javascript
|
|
595
|
+
export default async function run(input, ctx) {
|
|
591
596
|
const guide = ctx.files["references/style-guide.md"]; // bundled text resources
|
|
592
597
|
const docs = await ctx.workspace.readFile("README.md"); // gated by permission
|
|
593
598
|
const summary = await ctx.tools.call("summarize", { input }); // explicit tools
|
|
@@ -596,13 +601,13 @@ export default async function run(input: unknown, ctx: SkillRunContext) {
|
|
|
596
601
|
}
|
|
597
602
|
```
|
|
598
603
|
|
|
599
|
-
`ctx` is `{ skill, files, workspace, tools, output }
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
`ctx.output.writeFile(name, content)` returns
|
|
603
|
-
(it does not mutate the workspace). Python and
|
|
604
|
-
instead: `/input.json`, `/context.json`,
|
|
605
|
-
`/output` for artifacts.
|
|
604
|
+
`ctx` is `{ skill, files, workspace, tools, output }` (typed as
|
|
605
|
+
`SkillRunContext`). `ctx.files` holds bundled text resources by relative path,
|
|
606
|
+
`ctx.workspace` is gated by the workspace permission, `ctx.tools` only exposes
|
|
607
|
+
tools the runner was given, and `ctx.output.writeFile(name, content)` returns
|
|
608
|
+
scratch artifacts to the model (it does not mutate the workspace). Python and
|
|
609
|
+
Bash use the path-based contract instead: `/input.json`, `/context.json`,
|
|
610
|
+
bundled resources under `/skill`, and `/output` for artifacts.
|
|
606
611
|
|
|
607
612
|
Passing `workspaceInstance` gives scripts read-only workspace access by default.
|
|
608
613
|
Network access, tools, and workspace writes are opt-in. The default timeout is
|
|
@@ -721,8 +726,8 @@ export class MyAgent extends Think<Env> {
|
|
|
721
726
|
getModel() {
|
|
722
727
|
const tier = this.getConfig<MyConfig>()?.modelTier ?? "fast";
|
|
723
728
|
const models = {
|
|
724
|
-
fast: "@cf/
|
|
725
|
-
capable: "@cf/
|
|
729
|
+
fast: "@cf/qwen/qwen3.8-27b",
|
|
730
|
+
capable: "@cf/deepseek-ai/deepseek-v4.1-flash-1017"
|
|
726
731
|
};
|
|
727
732
|
return models[tier];
|
|
728
733
|
}
|
|
@@ -1028,13 +1033,13 @@ Think's workspace is a `Workspace` from [`@cloudflare/computer`](https://github.
|
|
|
1028
1033
|
- Install `@cloudflare/computer`; it is a peer dependency. Import `Workspace` from it rather than from `@cloudflare/think`.
|
|
1029
1034
|
- `workspace` is typed `ThinkWorkspace`, which needs only `workspace.fs`. `WorkspaceLike` is gone.
|
|
1030
1035
|
- The default Workspace lives on the agent's own storage and has no execution backends. Override `workspace` with `new Workspace({ storage: this.ctx.storage, ... })` to add backends, mounts, or git.
|
|
1031
|
-
- Think writes its own files under `/workspace`: evicted media under `/workspace/attachments/evicted
|
|
1036
|
+
- Think writes its own files under `/workspace`: evicted media under `/workspace/attachments/evicted/` and fetched responses under `/workspace/fetched/`. `skills.workspace()` reads skills from `/workspace/.agents/skills`.
|
|
1032
1037
|
- The execute tool's `state` option and `state.*` namespace are removed. Pass `createAITools({ workspace: this.workspace })` as `tools` to give sandboxed code the workspace.
|
|
1033
1038
|
- The workspace tools are `@cloudflare/computer`'s `createAITools`: `read`, `ls`, `find`, `grep`, `write`, `edit`, and `delete`, plus `exec` when the Workspace has backends. `list` is now `ls`. `exec` offers every backend the Workspace has.
|
|
1034
1039
|
- `workspaceBash`, `createWorkspaceTools`, and `@cloudflare/think/tools/workspace` are removed, with no replacement. There is no in-process `bash` tool: add a backend to the Workspace to get `exec`. To change a built-in tool, return a same-name tool from `getTools()`; to hide tools for a turn, return `activeTools` from `beforeTurn`.
|
|
1035
1040
|
- Every Think agent has `__getWorkspaceStub()`, so `getWorkspace(stub)` and the Worker shell backend can reach a Workspace it owns.
|
|
1036
1041
|
- Image and PDF reads stored by the old `read` tool replay as an error asking the model to read the file again.
|
|
1037
|
-
- Agent Skills (`agents/skills`) accept only a Computer Workspace, for both
|
|
1042
|
+
- Agent Skills (`agents/skills`) accept only a Computer Workspace, for both `skills.workspace()` and `skills.runner({ workspaceInstance })`. Relative paths in skill scripts resolve against `/workspace`.
|
|
1038
1043
|
|
|
1039
1044
|
Files a Shell Workspace stored are not moved. [Migrating to `@cloudflare/computer`](../shell/migrating-to-computer.md) documents both storage schemas and a copy script.
|
|
1040
1045
|
|
|
@@ -1056,9 +1061,9 @@ Bundled with `@cloudflare/think`:
|
|
|
1056
1061
|
| ---------------------- | ---------------------------------------- |
|
|
1057
1062
|
| `@cloudflare/codemode` | Code execution for `createExecuteTool()` |
|
|
1058
1063
|
|
|
1059
|
-
The Agent Skills
|
|
1060
|
-
[`agents/skills`](https://github.com/cloudflare/agents/blob/main/packages/agents/AGENTS.md) (so
|
|
1061
|
-
|
|
1064
|
+
The Agent Skills parser, sources, and script runner live in
|
|
1065
|
+
[`agents/skills`](https://github.com/cloudflare/agents/blob/main/packages/agents/AGENTS.md) (so the script runner pulls
|
|
1066
|
+
`just-bash` through `agents`, not Think).
|
|
1062
1067
|
|
|
1063
1068
|
## Docs
|
|
1064
1069
|
|
package/docs/lifecycle-hooks.md
CHANGED
|
@@ -126,7 +126,7 @@ export class MyAgent extends Think<Env> {
|
|
|
126
126
|
}
|
|
127
127
|
```
|
|
128
128
|
|
|
129
|
-
A block declared without a `provider` is auto-wired to durable per-agent SQLite, so `memory` above is writable through the `set_context` tool with no extra wiring. When context blocks are configured, Think builds the system prompt from those blocks
|
|
129
|
+
A block declared without a `provider` is auto-wired to durable per-agent SQLite, so `memory` above is writable through the `set_context` tool with no extra wiring. When context blocks are configured, Think builds the system prompt from an overridden `getSystemPrompt()` followed by those blocks. Think's default `getSystemPrompt()` is only used when there are no blocks. The frozen system prompt is always persisted, so a cold wake reuses the exact prompt string the model already cached.
|
|
130
130
|
|
|
131
131
|
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.
|
|
132
132
|
|
|
@@ -142,18 +142,18 @@ beforeTurn(ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>
|
|
|
142
142
|
|
|
143
143
|
### TurnContext
|
|
144
144
|
|
|
145
|
-
| Field | Type | Description
|
|
146
|
-
| -------------- | ------------------------------- |
|
|
147
|
-
| `system` | `string` | Assembled system prompt (
|
|
148
|
-
| `messages` | `ModelMessage[]` | Assembled model messages (truncated)
|
|
149
|
-
| `tools` | `ToolSet` | Merged tool set (workspace + getTools + context + MCP + client + caller)
|
|
150
|
-
| `model` | `LanguageModel` | The resolved model (a string from `getModel()` is already resolved here)
|
|
151
|
-
| `continuation` | `boolean` | Whether this is a continuation turn (auto-continue after tool result)
|
|
152
|
-
| `body` | `Record<string, unknown>` | Custom body fields from the client request
|
|
153
|
-
| `requestId` | `string \| undefined` | The request this turn runs for. See [Turn identity](#turn-identity)
|
|
154
|
-
| `trigger` | `TurnTrigger \| undefined` | What admitted the turn: `"ws-chat"`, `"rpc"`, `"submission"`, and so on
|
|
155
|
-
| `abortSignal` | `AbortSignal \| undefined` | Aborts when the turn is cancelled. Pass it to I/O the hook awaits
|
|
156
|
-
| `messenger` | `MessengerContext \| undefined` | The messenger thread this turn answers, fixed when the turn was admitted
|
|
145
|
+
| Field | Type | Description |
|
|
146
|
+
| -------------- | ------------------------------- | --------------------------------------------------------------------------- |
|
|
147
|
+
| `system` | `string` | Assembled system prompt (`getSystemPrompt()` override, then context blocks) |
|
|
148
|
+
| `messages` | `ModelMessage[]` | Assembled model messages (truncated) |
|
|
149
|
+
| `tools` | `ToolSet` | Merged tool set (workspace + getTools + context + MCP + client + caller) |
|
|
150
|
+
| `model` | `LanguageModel` | The resolved model (a string from `getModel()` is already resolved here) |
|
|
151
|
+
| `continuation` | `boolean` | Whether this is a continuation turn (auto-continue after tool result) |
|
|
152
|
+
| `body` | `Record<string, unknown>` | Custom body fields from the client request |
|
|
153
|
+
| `requestId` | `string \| undefined` | The request this turn runs for. See [Turn identity](#turn-identity) |
|
|
154
|
+
| `trigger` | `TurnTrigger \| undefined` | What admitted the turn: `"ws-chat"`, `"rpc"`, `"submission"`, and so on |
|
|
155
|
+
| `abortSignal` | `AbortSignal \| undefined` | Aborts when the turn is cancelled. Pass it to I/O the hook awaits |
|
|
156
|
+
| `messenger` | `MessengerContext \| undefined` | The messenger thread this turn answers, fixed when the turn was admitted |
|
|
157
157
|
|
|
158
158
|
### Turn identity
|
|
159
159
|
|
package/docs/multi-chat.md
CHANGED
|
@@ -19,10 +19,11 @@ one Durable Object would serialize all of a user's turns on one single-threaded
|
|
|
19
19
|
object, so each chat gets its own.
|
|
20
20
|
|
|
21
21
|
This guide walks through the pattern as implemented in
|
|
22
|
-
|
|
23
|
-
the
|
|
22
|
+
the assistant example, a reference Think app that has since been removed from
|
|
23
|
+
the repository ([last version](https://github.com/cloudflare/agents/tree/786d30e305baebc5fbf5ad5ed80461f88a728468/examples/assistant)). The code below is taken from that
|
|
24
|
+
example.
|
|
24
25
|
|
|
25
|
-
> **Topology note.**
|
|
26
|
+
> **Topology note.** The assistant example hosts each chat as a facet (a
|
|
26
27
|
> [dynamic agent](https://github.com/cloudflare/agents/blob/main/docs/agents/sub-agents.md))
|
|
27
28
|
> of the directory, using `subAgent()`, `hasSubAgent()`, `listSubAgents()`,
|
|
28
29
|
> and `deleteSubAgent()`. Those methods are aliases for `this.dynamicAgents`.
|
|
@@ -83,7 +84,7 @@ export class AssistantDirectory extends Think<Env, DirectoryState> {
|
|
|
83
84
|
|
|
84
85
|
// Required by Think; nothing in the directory role calls it.
|
|
85
86
|
override getModel() {
|
|
86
|
-
return "@cf/
|
|
87
|
+
return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
onStart() {
|
|
@@ -280,7 +281,7 @@ export class AssistantDirectory extends Think<Env, DirectoryState> {
|
|
|
280
281
|
### Connect from React
|
|
281
282
|
|
|
282
283
|
The client opens one connection to the directory for the sidebar and one to the
|
|
283
|
-
active chat.
|
|
284
|
+
active chat. The assistant example wraps the directory connection in a local
|
|
284
285
|
`useChats()` hook (`src/use-chats.ts`):
|
|
285
286
|
|
|
286
287
|
```typescript
|
|
@@ -563,7 +564,7 @@ See [Scheduled Tasks](./index.md#scheduled-tasks) for the schedule syntax.
|
|
|
563
564
|
The example has no directory-level search index.
|
|
564
565
|
- **No packaged helpers.** There is no `Chats` base class and `useChats()` is not
|
|
565
566
|
exported from any package. The pattern is documented through
|
|
566
|
-
|
|
567
|
+
the assistant example until the shape settles.
|
|
567
568
|
|
|
568
569
|
## Related
|
|
569
570
|
|
|
@@ -572,4 +573,4 @@ See [Scheduled Tasks](./index.md#scheduled-tasks) for the schedule syntax.
|
|
|
572
573
|
- [Lifecycle Hooks](./lifecycle-hooks.md) — `beforeTurn` and `onChatResponse`
|
|
573
574
|
- [Dynamic agents](https://github.com/cloudflare/agents/blob/main/docs/agents/sub-agents.md) — `onBeforeSubAgent`, `parentAgent()`, `useAgent({ sub })`, and routing
|
|
574
575
|
- [Routing to independent Agents](https://github.com/cloudflare/agents/blob/main/docs/agents/routing.md#routing-to-independent-agents) — `RoutedAgents` for top-level chat Durable Objects
|
|
575
|
-
- [
|
|
576
|
+
- [Assistant example (last version)](https://github.com/cloudflare/agents/tree/786d30e305baebc5fbf5ad5ed80461f88a728468/examples/assistant) — the full reference app
|