@cloudflare/think 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -82,6 +82,7 @@ Think owns the `streamText` call. Hooks fire on every turn regardless of entry p
82
82
  | Hook | When it fires | Return |
83
83
  | ------------------------ | ------------------------------------------- | ------------------------------ |
84
84
  | `beforeTurn(ctx)` | Before `streamText` — see assembled context | `TurnConfig` overrides or void |
85
+ | `beforeStep(ctx)` | Before each model step | `StepConfig` overrides or void |
85
86
  | `beforeToolCall(ctx)` | Before tool's `execute` runs | `ToolCallDecision` or void |
86
87
  | `afterToolCall(ctx)` | After tool execution (success or failure) | void |
87
88
  | `onStepFinish(ctx)` | After each step completes | void |
@@ -89,15 +90,20 @@ Think owns the `streamText` call. Hooks fire on every turn regardless of entry p
89
90
  | `onChatResponse(result)` | After turn completes + message persisted | void |
90
91
  | `onChatError(error)` | On error during a turn | error to propagate |
91
92
 
92
- The four AI SDK–derived contexts spread the SDK's own types at the top level — no information is dropped:
93
+ The AI SDK-derived contexts spread the SDK's own types at the top level — no information is dropped:
93
94
 
94
95
  | Context | Backed by |
95
96
  | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
97
+ | `PrepareStepContext<TOOLS>` | `Parameters<PrepareStepFunction<TOOLS>>[0]` (`steps`, `stepNumber`, `model`, `messages`, `experimental_context`) |
96
98
  | `ToolCallContext<TOOLS>` | `TypedToolCall<TOOLS>` + per-call extras from `OnToolCallStartEvent` (`stepNumber`, `messages`, `abortSignal`) |
97
99
  | `ToolCallResultContext<TOOLS>` | `TypedToolCall<TOOLS>` + per-call extras (`durationMs`, `messages`, `stepNumber`) + discriminated `success`/`output`/`error` outcome |
98
100
  | `StepContext<TOOLS>` | `StepResult<TOOLS>` (full step incl. `reasoning`, `sources`, `files`, `usage`, `providerMetadata`, `request`, `response`, `warnings`) |
99
101
  | `ChunkContext<TOOLS>` | `Parameters<StreamTextOnChunkCallback<TOOLS>>[0]` (discriminated `TextStreamPart`) |
100
102
 
103
+ `beforeStep` is wired to the AI SDK's `prepareStep` callback. Return a `StepConfig` to override `model`, `toolChoice`, `activeTools`, `system`, `messages`, `experimental_context`, or `providerOptions` for the current step. The AI SDK does not expose `output` or `maxSteps` per step — set those at the turn level via `TurnConfig` (returned from `beforeTurn`). `beforeStep` is subclass-only; it is not dispatched to extensions because the prepareStep event surface includes a live `LanguageModel` instance which is not JSON-safe to snapshot.
104
+
105
+ `TurnConfig` also accepts an `output` field that is forwarded to `streamText` as the AI SDK's structured-output spec. Combine with `activeTools: []` for providers (e.g. `workers-ai-provider`) that strip tools when `responseFormat: "json"` is active.
106
+
101
107
  Per-tool hooks are wired so `beforeToolCall` fires _before_ `execute` (Think wraps every tool's `execute`) and `afterToolCall` fires _after_ (via the AI SDK's `experimental_onToolCallFinish`) with `durationMs` and a discriminated outcome. `beforeToolCall` can return a `ToolCallDecision` to:
102
108
 
103
109
  - `{ action: "allow", input? }` — run the original `execute`, optionally with a substituted `input`.
@@ -107,10 +113,24 @@ Per-tool hooks are wired so `beforeToolCall` fires _before_ `execute` (Think wra
107
113
  Pass an explicit `TOOLS` generic when you want full input typing:
108
114
 
109
115
  ```ts
110
- import type { StepContext, ToolCallContext, ToolCallResultContext } from "@cloudflare/think";
116
+ import type {
117
+ PrepareStepContext,
118
+ StepContext,
119
+ ToolCallContext,
120
+ ToolCallResultContext
121
+ } from "@cloudflare/think";
111
122
 
112
123
  const tools = { search: tool({ inputSchema: z.object({ query: z.string() }), ... }) };
113
124
 
125
+ beforeStep(ctx: PrepareStepContext<typeof tools>) {
126
+ if (ctx.stepNumber === 0) {
127
+ return {
128
+ activeTools: ["search"],
129
+ toolChoice: { type: "tool", toolName: "search" }
130
+ };
131
+ }
132
+ }
133
+
114
134
  beforeToolCall(ctx: ToolCallContext<typeof tools>) {
115
135
  if (ctx.toolName === "search") {
116
136
  ctx.input.query; // typed as string
@@ -143,7 +163,7 @@ onStepFinish(ctx: StepContext<typeof tools>) {
143
163
 
144
164
  ### Extension hook subscriptions
145
165
 
146
- Extensions can subscribe to any of the five lifecycle hooks via their manifest's `hooks` array. Think dispatches to extension-side handlers in load order with a JSON-safe snapshot of the event:
166
+ Extensions can subscribe to `beforeTurn`, `beforeToolCall`, `afterToolCall`, `onStepFinish`, and `onChunk` via their manifest's `hooks` array. Think dispatches to extension-side handlers in load order with a JSON-safe snapshot of the event. `beforeStep` is available to subclasses only and is not dispatched to extensions.
147
167
 
148
168
  ```js
149
169
  // extension source (loaded via getExtensions())
@@ -169,7 +189,7 @@ Extensions can subscribe to any of the five lifecycle hooks via their manifest's
169
189
  });
170
190
  ```
171
191
 
172
- The handler signature is `(snapshot, host) => void`, symmetric with tool `execute`. Errors from extension hooks are caught and logged; they do not abort the turn. Only `beforeTurn` honors return values — the other four are observation-only. See [docs/think/lifecycle-hooks.md](https://github.com/cloudflare/agents/blob/main/docs/think/lifecycle-hooks.md#extension-hook-subscriptions) for the full snapshot shapes.
192
+ The handler signature is `(snapshot, host) => void`, symmetric with tool `execute`. Errors from extension hooks are caught and logged; they do not abort the turn. Only `beforeTurn` honors return values — the other extension hooks are observation-only. See [docs/think/lifecycle-hooks.md](https://github.com/cloudflare/agents/blob/main/docs/think/lifecycle-hooks.md#extension-hook-subscriptions) for the full snapshot shapes.
173
193
 
174
194
  #### beforeTurn example
175
195
 
@@ -303,7 +323,7 @@ For values you want broadcast to connected clients, use `state` / `setState` fro
303
323
 
304
324
  - **WebSocket protocol** — wire-compatible with `useAgentChat` from `@cloudflare/ai-chat`
305
325
  - **Built-in workspace** — every agent gets `this.workspace` with file tools auto-wired
306
- - **Lifecycle hooks** — `beforeTurn`, `onStepFinish`, `onChunk`, `onChatResponse` fire on every turn
326
+ - **Lifecycle hooks** — `beforeTurn`, `beforeStep`, `onStepFinish`, `onChunk`, `onChatResponse` fire on every turn
307
327
  - **Stream resumption** — page refresh replays buffered chunks via `ResumableStream`
308
328
  - **Client tools** — accept tool schemas from clients, handle results and approvals
309
329
  - **Auto-continuation** — debounce-based continuation after tool results
@@ -1,25 +1,25 @@
1
- //#region \0@oxc-project+runtime@0.126.0/helpers/checkPrivateRedeclaration.js
1
+ //#region \0@oxc-project+runtime@0.127.0/helpers/checkPrivateRedeclaration.js
2
2
  function _checkPrivateRedeclaration(e, t) {
3
3
  if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
4
4
  }
5
5
  //#endregion
6
- //#region \0@oxc-project+runtime@0.126.0/helpers/classPrivateFieldInitSpec.js
6
+ //#region \0@oxc-project+runtime@0.127.0/helpers/classPrivateFieldInitSpec.js
7
7
  function _classPrivateFieldInitSpec(e, t, a) {
8
8
  _checkPrivateRedeclaration(e, t), t.set(e, a);
9
9
  }
10
10
  //#endregion
11
- //#region \0@oxc-project+runtime@0.126.0/helpers/assertClassBrand.js
11
+ //#region \0@oxc-project+runtime@0.127.0/helpers/assertClassBrand.js
12
12
  function _assertClassBrand(e, t, n) {
13
13
  if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
14
14
  throw new TypeError("Private element is not present on this object");
15
15
  }
16
16
  //#endregion
17
- //#region \0@oxc-project+runtime@0.126.0/helpers/classPrivateFieldSet2.js
17
+ //#region \0@oxc-project+runtime@0.127.0/helpers/classPrivateFieldSet2.js
18
18
  function _classPrivateFieldSet2(s, a, r) {
19
19
  return s.set(_assertClassBrand(s, a), r), r;
20
20
  }
21
21
  //#endregion
22
- //#region \0@oxc-project+runtime@0.126.0/helpers/classPrivateFieldGet2.js
22
+ //#region \0@oxc-project+runtime@0.127.0/helpers/classPrivateFieldGet2.js
23
23
  function _classPrivateFieldGet2(s, a) {
24
24
  return s.get(_assertClassBrand(s, a));
25
25
  }
@@ -1,5 +1,5 @@
1
- import { i as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-CR9ZdLiu.js";
2
- import { r as _assertClassBrand } from "../classPrivateFieldGet2-C7fYS0JL.js";
1
+ import { i as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-DDC3Gb0V.js";
2
+ import { r as _assertClassBrand } from "../classPrivateFieldGet2-Bvcn7kEw.js";
3
3
  import { WorkerEntrypoint } from "cloudflare:workers";
4
4
  //#region src/extensions/host-bridge.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { a as _checkPrivateRedeclaration, i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-C7fYS0JL.js";
1
+ import { a as _checkPrivateRedeclaration, i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-Bvcn7kEw.js";
2
2
  import { jsonSchema, tool } from "ai";
3
3
  //#region \0rolldown/runtime.js
4
4
  var __defProp = Object.defineProperty;
@@ -12,7 +12,7 @@ var __exportAll = (all, no_symbols) => {
12
12
  return target;
13
13
  };
14
14
  //#endregion
15
- //#region \0@oxc-project+runtime@0.126.0/helpers/classPrivateMethodInitSpec.js
15
+ //#region \0@oxc-project+runtime@0.127.0/helpers/classPrivateMethodInitSpec.js
16
16
  function _classPrivateMethodInitSpec(e, a) {
17
17
  _checkPrivateRedeclaration(e, a), a.add(e);
18
18
  }
@@ -326,4 +326,4 @@ export default class Extension extends WorkerEntrypoint {
326
326
  //#endregion
327
327
  export { _classPrivateMethodInitSpec as i, manager_exports as n, sanitizeName as r, ExtensionManager as t };
328
328
 
329
- //# sourceMappingURL=manager-CR9ZdLiu.js.map
329
+ //# sourceMappingURL=manager-DDC3Gb0V.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"manager-CR9ZdLiu.js","names":[],"sources":["../src/extensions/manager.ts"],"sourcesContent":["/**\n * ExtensionManager — loads, manages, and exposes tools from extension Workers.\n *\n * Extensions are sandboxed Workers created via WorkerLoader. Each extension\n * declares tools (with JSON Schema inputs) and permissions. The manager:\n *\n * 1. Wraps extension source in a Worker module with describe/execute RPC\n * 2. Loads it via WorkerLoader with permission-gated bindings\n * 3. Discovers tools via describe() RPC call\n * 4. Exposes them as AI SDK tools via getTools()\n *\n * Extension source format — a JS object expression defining tools:\n *\n * ```js\n * ({\n * greet: {\n * description: \"Greet someone\",\n * parameters: { name: { type: \"string\" } },\n * required: [\"name\"],\n * execute: async (args, host) => `Hello, ${args.name}!`\n * }\n * })\n * ```\n *\n * The `host` parameter in execute is provided via `env.host` — a loopback\n * binding that resolves the parent agent and delegates workspace operations\n * (gated by permissions). See HostBridgeLoopback.\n */\n\nimport { tool, jsonSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo,\n ExtensionToolDescriptor\n} from \"./types\";\n\n/**\n * Sanitize a name for use as a tool name prefix.\n * Replaces any non-alphanumeric characters with underscores and\n * collapses consecutive underscores.\n */\nexport function sanitizeName(name: string): string {\n if (!name || name.trim().length === 0) {\n throw new Error(\"Extension name must not be empty\");\n }\n return name\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\ninterface ExtensionEntrypoint {\n describe(): Promise<string>;\n manifest(): Promise<string>;\n execute(toolName: string, argsJson: string): Promise<string>;\n hook(name: string, ctxProxy: unknown): Promise<string>;\n}\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n tools: ExtensionToolDescriptor[];\n hooks: string[];\n entrypoint: ExtensionEntrypoint;\n}\n\n/** Shape persisted to DO storage for each extension. */\ninterface PersistedExtension {\n manifest: ExtensionManifest;\n source: string;\n}\n\nconst STORAGE_PREFIX = \"ext:\";\n\nexport interface ExtensionManagerOptions {\n /** WorkerLoader binding for creating sandboxed extension Workers. */\n loader: WorkerLoader;\n /**\n * Durable Object storage for persisting extensions across hibernation.\n * If provided, loaded extensions survive DO restarts. Call `restore()`\n * on each turn to rebuild in-memory state from storage.\n */\n storage?: DurableObjectStorage;\n /**\n * Factory that creates a loopback Fetcher for workspace access, given\n * an extension's declared permissions. The returned binding is injected\n * into the extension worker's `env.host`.\n *\n * If not provided, extensions receive no host binding (workspace tools\n * will get `null` for the host parameter).\n *\n * Typically wired up using HostBridgeLoopback via `ctx.exports`:\n * ```typescript\n * createHostBinding: (permissions, ownContextLabels) =>\n * ctx.exports.HostBridgeLoopback({\n * props: { agentClassName: \"ChatSession\", agentId: ctx.id.toString(), permissions, ownContextLabels }\n * })\n * ```\n */\n createHostBinding?: (\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher;\n}\n\nexport class ExtensionManager {\n #loader: WorkerLoader;\n #storage: DurableObjectStorage | null;\n #createHostBinding:\n | ((\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher)\n | null;\n #extensions = new Map<string, LoadedExtension>();\n #restored = false;\n #onUnload:\n | ((name: string, contextLabels: string[]) => void | Promise<void>)\n | null = null;\n\n constructor(options: ExtensionManagerOptions) {\n this.#loader = options.loader;\n this.#storage = options.storage ?? null;\n this.#createHostBinding = options.createHostBinding ?? null;\n }\n\n /**\n * Load an extension from source code.\n *\n * The source is a JS object expression defining tools. Each tool has\n * `description`, `parameters` (JSON Schema properties), optional\n * `required` array, and an `execute` async function.\n *\n * @returns Summary of the loaded extension including discovered tools.\n */\n /**\n * Restore extensions from DO storage after hibernation.\n *\n * Idempotent — skips extensions already in memory. Call this at the\n * start of each chat turn (e.g. in onChatMessage before getTools).\n */\n async restore(): Promise<void> {\n if (this.#restored || !this.#storage) return;\n this.#restored = true;\n\n const entries = await this.#storage.list<PersistedExtension>({\n prefix: STORAGE_PREFIX\n });\n\n for (const persisted of entries.values()) {\n if (this.#extensions.has(persisted.manifest.name)) continue;\n await this.#loadInternal(persisted.manifest, persisted.source);\n }\n }\n\n async load(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n if (this.#extensions.has(manifest.name)) {\n throw new Error(\n `Extension \"${manifest.name}\" is already loaded. Unload it first.`\n );\n }\n\n const info = await this.#loadInternal(manifest, source);\n\n // Persist to storage so it survives hibernation\n if (this.#storage) {\n await this.#storage.put<PersistedExtension>(\n `${STORAGE_PREFIX}${manifest.name}`,\n { manifest, source }\n );\n }\n\n return info;\n }\n\n async #loadInternal(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n const workerModule = wrapExtensionSource(source);\n const permissions = manifest.permissions ?? {};\n\n // Build env bindings for the dynamic worker. Inject a loopback\n // Fetcher as env.host when the extension declares ANY permission\n // that requires host access (workspace, context, messages, session).\n const workerEnv: Record<string, Fetcher> = {};\n const needsHost =\n (permissions.workspace ?? \"none\") !== \"none\" ||\n permissions.context?.read !== undefined ||\n permissions.context?.write !== undefined ||\n (permissions.messages ?? \"none\") !== \"none\" ||\n permissions.session?.sendMessage ||\n permissions.session?.metadata;\n if (this.#createHostBinding && needsHost) {\n const prefix = sanitizeName(manifest.name);\n const ownLabels = (manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n workerEnv.host = this.#createHostBinding(permissions, ownLabels);\n }\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${Date.now()}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound: permissions.network?.length ? undefined : null,\n ...(Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {})\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as ExtensionEntrypoint;\n\n // Discover tools and hooks via RPC\n const descriptorsJson = await entrypoint.describe();\n const tools = JSON.parse(descriptorsJson) as ExtensionToolDescriptor[];\n\n let hooks: string[] = [];\n try {\n const manifestJson = await entrypoint.manifest();\n const runtimeManifest = JSON.parse(manifestJson) as {\n hooks?: string[];\n };\n hooks = runtimeManifest.hooks ?? [];\n } catch {\n // Legacy extensions may not have manifest() — treat as no hooks\n }\n\n this.#extensions.set(manifest.name, {\n manifest,\n tools,\n hooks,\n entrypoint\n });\n\n return toExtensionInfo(manifest, tools);\n }\n\n /**\n * Unload an extension, removing its tools from the agent.\n * If an onUnload callback is registered, it fires with the\n * extension's namespaced context labels so the caller can\n * remove context blocks from the Session.\n */\n async unload(name: string): Promise<boolean> {\n const ext = this.#extensions.get(name);\n if (!ext) return false;\n\n const removed = this.#extensions.delete(name);\n if (removed && this.#storage) {\n await this.#storage.delete(`${STORAGE_PREFIX}${name}`);\n }\n\n if (removed && this.#onUnload) {\n const prefix = sanitizeName(name);\n const contextLabels = (ext.manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n await this.#onUnload(name, contextLabels);\n }\n\n return removed;\n }\n\n /**\n * Register a callback invoked when an extension is unloaded.\n * Think uses this to remove the extension's context blocks from Session.\n */\n onUnload(\n cb: (name: string, contextLabels: string[]) => void | Promise<void>\n ): void {\n this.#onUnload = cb;\n }\n\n /**\n * Get the namespaced context labels for all loaded extensions\n * that declare context blocks in their manifests.\n */\n getContextLabels(): Array<{ extName: string; label: string }> {\n const result: Array<{ extName: string; label: string }> = [];\n for (const ext of this.#extensions.values()) {\n if (!ext.manifest.context) continue;\n const prefix = sanitizeName(ext.manifest.name);\n for (const ctx of ext.manifest.context) {\n result.push({\n extName: ext.manifest.name,\n label: `${prefix}_${ctx.label}`\n });\n }\n }\n return result;\n }\n\n /**\n * Get extension manifest by name.\n */\n getManifest(name: string): ExtensionManifest | null {\n return this.#extensions.get(name)?.manifest ?? null;\n }\n\n /**\n * Get extensions that subscribe to a specific hook, in load order.\n */\n getHookSubscribers(\n hookName: string\n ): Array<{ name: string; entrypoint: ExtensionEntrypoint }> {\n const result: Array<{ name: string; entrypoint: ExtensionEntrypoint }> = [];\n for (const ext of this.#extensions.values()) {\n if (ext.hooks.includes(hookName)) {\n result.push({ name: ext.manifest.name, entrypoint: ext.entrypoint });\n }\n }\n return result;\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.tools)\n );\n }\n\n /**\n * Get AI SDK tools from all loaded extensions.\n *\n * Tool names are prefixed with the sanitized extension name to avoid\n * collisions: e.g. extension \"github\" with tool \"create_pr\" → \"github_create_pr\".\n */\n getTools(): ToolSet {\n const tools: ToolSet = {};\n\n for (const ext of this.#extensions.values()) {\n const prefix = sanitizeName(ext.manifest.name);\n\n for (const descriptor of ext.tools) {\n const toolName = `${prefix}_${descriptor.name}`;\n\n tools[toolName] = tool({\n description: `[${ext.manifest.name}] ${descriptor.description}`,\n inputSchema: jsonSchema(\n descriptor.inputSchema as Record<string, unknown>\n ),\n execute: async (args: Record<string, unknown>) => {\n if (!this.#extensions.has(ext.manifest.name)) {\n throw new Error(\n `Extension \"${ext.manifest.name}\" has been unloaded. Tool \"${toolName}\" is no longer available.`\n );\n }\n const resultJson = await ext.entrypoint.execute(\n descriptor.name,\n JSON.stringify(args)\n );\n const parsed = JSON.parse(resultJson) as {\n result?: unknown;\n error?: string;\n };\n if (parsed.error) throw new Error(parsed.error);\n return parsed.result;\n }\n });\n }\n }\n\n return tools;\n }\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n tools: ExtensionToolDescriptor[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: tools.map((t) => `${prefix}_${t.name}`),\n contextLabels: (manifest.context ?? []).map((c) => `${prefix}_${c.label}`),\n permissions: manifest.permissions ?? {}\n };\n}\n\n/**\n * Wrap an extension source in a Worker module that exposes\n * describe(), execute(), manifest(), and hook RPC methods.\n *\n * Source format: `({ tools: {...}, hooks: {...} })`\n * Both `tools` and `hooks` are optional.\n */\nfunction wrapExtensionSource(source: string): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\n\nconst __ext = (${source});\nif (__ext && typeof __ext === \"object\" && !(\"tools\" in __ext) && !(\"hooks\" in __ext)) {\n throw new Error(\n \"Invalid extension source format. Expected { tools: {...}, hooks: {...} } \" +\n \"but got a flat object. Wrap your tools in a 'tools' key.\"\n );\n}\nconst __tools = __ext.tools || {};\nconst __hooks = __ext.hooks || {};\n\nexport default class Extension extends WorkerEntrypoint {\n describe() {\n const descriptors = [];\n for (const [name, def] of Object.entries(__tools)) {\n descriptors.push({\n name,\n description: def.description || name,\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n }\n });\n }\n return JSON.stringify(descriptors);\n }\n\n manifest() {\n return JSON.stringify({\n hooks: Object.keys(__hooks)\n });\n }\n\n async execute(toolName, argsJson) {\n const def = __tools[toolName];\n if (!def || !def.execute) {\n return JSON.stringify({ error: \"Unknown tool: \" + toolName });\n }\n try {\n const args = JSON.parse(argsJson);\n const result = await def.execute(args, this.env.host ?? null);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n\n async hook(name, ctxSnapshot) {\n const fn = __hooks[name];\n if (!fn) return JSON.stringify({ skipped: true });\n try {\n // Hook handlers receive (ctxSnapshot, host) — symmetric with tool\n // executes. \\`host\\` is null when the extension was loaded without\n // host-requiring permissions or when the worker entry point doesn't\n // re-export HostBridgeLoopback.\n const result = await fn(ctxSnapshot, this.env.host ?? null);\n return JSON.stringify({ result: result ?? {} });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aAAa,MAAsB;AACjD,KAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,WAAW,EAClC,OAAM,IAAI,MAAM,mCAAmC;AAErD,QAAO,KACJ,QAAQ,iBAAiB,IAAI,CAC7B,QAAQ,OAAO,IAAI,CACnB,QAAQ,UAAU,GAAG;;AAuB1B,MAAM,iBAAiB;;;;;;;;AAiCvB,IAAa,mBAAb,MAA8B;CAe5B,YAAY,SAAkC;;mDAdxB;oDACgB;8DAM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,mBAAmB;EACnB,oBAAoB,CAAC,gBAAgB;EACrC,YAAY;EACZ,SAAS,EAAE,gBAAgB,cAAc;EACzC,gBAAgB,YAAY,SAAS,SAAS,KAAA,IAAY;EAC1D,GAAI,OAAO,KAAK,UAAU,CAAC,SAAS,IAAI,EAAE,KAAK,WAAW,GAAG,EAAE;EAChE,EACF,CAEyB,eAAe;CAGzC,MAAM,kBAAkB,MAAM,WAAW,UAAU;CACnD,MAAM,QAAQ,KAAK,MAAM,gBAAgB;CAEzC,IAAI,QAAkB,EAAE;AACxB,KAAI;EACF,MAAM,eAAe,MAAM,WAAW,UAAU;AAIhD,UAHwB,KAAK,MAAM,aAAa,CAGxB,SAAS,EAAE;SAC7B;AAIR,wBAAA,aAAA,KAAgB,CAAC,IAAI,SAAS,MAAM;EAClC;EACA;EACA;EACA;EACD,CAAC;AAEF,QAAO,gBAAgB,UAAU,MAAM;;AAsI3C,SAAS,gBACP,UACA,OACe;CACf,MAAM,SAAS,aAAa,SAAS,KAAK;AAC1C,QAAO;EACL,MAAM,SAAS;EACf,SAAS,SAAS;EAClB,aAAa,SAAS;EACtB,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EAC9C,gBAAgB,SAAS,WAAW,EAAE,EAAE,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,QAAQ;EAC1E,aAAa,SAAS,eAAe,EAAE;EACxC;;;;;;;;;AAUH,SAAS,oBAAoB,QAAwB;AACnD,QAAO;;iBAEQ,OAAO"}
1
+ {"version":3,"file":"manager-DDC3Gb0V.js","names":[],"sources":["../src/extensions/manager.ts"],"sourcesContent":["/**\n * ExtensionManager — loads, manages, and exposes tools from extension Workers.\n *\n * Extensions are sandboxed Workers created via WorkerLoader. Each extension\n * declares tools (with JSON Schema inputs) and permissions. The manager:\n *\n * 1. Wraps extension source in a Worker module with describe/execute RPC\n * 2. Loads it via WorkerLoader with permission-gated bindings\n * 3. Discovers tools via describe() RPC call\n * 4. Exposes them as AI SDK tools via getTools()\n *\n * Extension source format — a JS object expression defining tools:\n *\n * ```js\n * ({\n * greet: {\n * description: \"Greet someone\",\n * parameters: { name: { type: \"string\" } },\n * required: [\"name\"],\n * execute: async (args, host) => `Hello, ${args.name}!`\n * }\n * })\n * ```\n *\n * The `host` parameter in execute is provided via `env.host` — a loopback\n * binding that resolves the parent agent and delegates workspace operations\n * (gated by permissions). See HostBridgeLoopback.\n */\n\nimport { tool, jsonSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo,\n ExtensionToolDescriptor\n} from \"./types\";\n\n/**\n * Sanitize a name for use as a tool name prefix.\n * Replaces any non-alphanumeric characters with underscores and\n * collapses consecutive underscores.\n */\nexport function sanitizeName(name: string): string {\n if (!name || name.trim().length === 0) {\n throw new Error(\"Extension name must not be empty\");\n }\n return name\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\ninterface ExtensionEntrypoint {\n describe(): Promise<string>;\n manifest(): Promise<string>;\n execute(toolName: string, argsJson: string): Promise<string>;\n hook(name: string, ctxProxy: unknown): Promise<string>;\n}\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n tools: ExtensionToolDescriptor[];\n hooks: string[];\n entrypoint: ExtensionEntrypoint;\n}\n\n/** Shape persisted to DO storage for each extension. */\ninterface PersistedExtension {\n manifest: ExtensionManifest;\n source: string;\n}\n\nconst STORAGE_PREFIX = \"ext:\";\n\nexport interface ExtensionManagerOptions {\n /** WorkerLoader binding for creating sandboxed extension Workers. */\n loader: WorkerLoader;\n /**\n * Durable Object storage for persisting extensions across hibernation.\n * If provided, loaded extensions survive DO restarts. Call `restore()`\n * on each turn to rebuild in-memory state from storage.\n */\n storage?: DurableObjectStorage;\n /**\n * Factory that creates a loopback Fetcher for workspace access, given\n * an extension's declared permissions. The returned binding is injected\n * into the extension worker's `env.host`.\n *\n * If not provided, extensions receive no host binding (workspace tools\n * will get `null` for the host parameter).\n *\n * Typically wired up using HostBridgeLoopback via `ctx.exports`:\n * ```typescript\n * createHostBinding: (permissions, ownContextLabels) =>\n * ctx.exports.HostBridgeLoopback({\n * props: { agentClassName: \"ChatSession\", agentId: ctx.id.toString(), permissions, ownContextLabels }\n * })\n * ```\n */\n createHostBinding?: (\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher;\n}\n\nexport class ExtensionManager {\n #loader: WorkerLoader;\n #storage: DurableObjectStorage | null;\n #createHostBinding:\n | ((\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher)\n | null;\n #extensions = new Map<string, LoadedExtension>();\n #restored = false;\n #onUnload:\n | ((name: string, contextLabels: string[]) => void | Promise<void>)\n | null = null;\n\n constructor(options: ExtensionManagerOptions) {\n this.#loader = options.loader;\n this.#storage = options.storage ?? null;\n this.#createHostBinding = options.createHostBinding ?? null;\n }\n\n /**\n * Load an extension from source code.\n *\n * The source is a JS object expression defining tools. Each tool has\n * `description`, `parameters` (JSON Schema properties), optional\n * `required` array, and an `execute` async function.\n *\n * @returns Summary of the loaded extension including discovered tools.\n */\n /**\n * Restore extensions from DO storage after hibernation.\n *\n * Idempotent — skips extensions already in memory. Call this at the\n * start of each chat turn (e.g. in onChatMessage before getTools).\n */\n async restore(): Promise<void> {\n if (this.#restored || !this.#storage) return;\n this.#restored = true;\n\n const entries = await this.#storage.list<PersistedExtension>({\n prefix: STORAGE_PREFIX\n });\n\n for (const persisted of entries.values()) {\n if (this.#extensions.has(persisted.manifest.name)) continue;\n await this.#loadInternal(persisted.manifest, persisted.source);\n }\n }\n\n async load(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n if (this.#extensions.has(manifest.name)) {\n throw new Error(\n `Extension \"${manifest.name}\" is already loaded. Unload it first.`\n );\n }\n\n const info = await this.#loadInternal(manifest, source);\n\n // Persist to storage so it survives hibernation\n if (this.#storage) {\n await this.#storage.put<PersistedExtension>(\n `${STORAGE_PREFIX}${manifest.name}`,\n { manifest, source }\n );\n }\n\n return info;\n }\n\n async #loadInternal(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n const workerModule = wrapExtensionSource(source);\n const permissions = manifest.permissions ?? {};\n\n // Build env bindings for the dynamic worker. Inject a loopback\n // Fetcher as env.host when the extension declares ANY permission\n // that requires host access (workspace, context, messages, session).\n const workerEnv: Record<string, Fetcher> = {};\n const needsHost =\n (permissions.workspace ?? \"none\") !== \"none\" ||\n permissions.context?.read !== undefined ||\n permissions.context?.write !== undefined ||\n (permissions.messages ?? \"none\") !== \"none\" ||\n permissions.session?.sendMessage ||\n permissions.session?.metadata;\n if (this.#createHostBinding && needsHost) {\n const prefix = sanitizeName(manifest.name);\n const ownLabels = (manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n workerEnv.host = this.#createHostBinding(permissions, ownLabels);\n }\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${Date.now()}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound: permissions.network?.length ? undefined : null,\n ...(Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {})\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as ExtensionEntrypoint;\n\n // Discover tools and hooks via RPC\n const descriptorsJson = await entrypoint.describe();\n const tools = JSON.parse(descriptorsJson) as ExtensionToolDescriptor[];\n\n let hooks: string[] = [];\n try {\n const manifestJson = await entrypoint.manifest();\n const runtimeManifest = JSON.parse(manifestJson) as {\n hooks?: string[];\n };\n hooks = runtimeManifest.hooks ?? [];\n } catch {\n // Legacy extensions may not have manifest() — treat as no hooks\n }\n\n this.#extensions.set(manifest.name, {\n manifest,\n tools,\n hooks,\n entrypoint\n });\n\n return toExtensionInfo(manifest, tools);\n }\n\n /**\n * Unload an extension, removing its tools from the agent.\n * If an onUnload callback is registered, it fires with the\n * extension's namespaced context labels so the caller can\n * remove context blocks from the Session.\n */\n async unload(name: string): Promise<boolean> {\n const ext = this.#extensions.get(name);\n if (!ext) return false;\n\n const removed = this.#extensions.delete(name);\n if (removed && this.#storage) {\n await this.#storage.delete(`${STORAGE_PREFIX}${name}`);\n }\n\n if (removed && this.#onUnload) {\n const prefix = sanitizeName(name);\n const contextLabels = (ext.manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n await this.#onUnload(name, contextLabels);\n }\n\n return removed;\n }\n\n /**\n * Register a callback invoked when an extension is unloaded.\n * Think uses this to remove the extension's context blocks from Session.\n */\n onUnload(\n cb: (name: string, contextLabels: string[]) => void | Promise<void>\n ): void {\n this.#onUnload = cb;\n }\n\n /**\n * Get the namespaced context labels for all loaded extensions\n * that declare context blocks in their manifests.\n */\n getContextLabels(): Array<{ extName: string; label: string }> {\n const result: Array<{ extName: string; label: string }> = [];\n for (const ext of this.#extensions.values()) {\n if (!ext.manifest.context) continue;\n const prefix = sanitizeName(ext.manifest.name);\n for (const ctx of ext.manifest.context) {\n result.push({\n extName: ext.manifest.name,\n label: `${prefix}_${ctx.label}`\n });\n }\n }\n return result;\n }\n\n /**\n * Get extension manifest by name.\n */\n getManifest(name: string): ExtensionManifest | null {\n return this.#extensions.get(name)?.manifest ?? null;\n }\n\n /**\n * Get extensions that subscribe to a specific hook, in load order.\n */\n getHookSubscribers(\n hookName: string\n ): Array<{ name: string; entrypoint: ExtensionEntrypoint }> {\n const result: Array<{ name: string; entrypoint: ExtensionEntrypoint }> = [];\n for (const ext of this.#extensions.values()) {\n if (ext.hooks.includes(hookName)) {\n result.push({ name: ext.manifest.name, entrypoint: ext.entrypoint });\n }\n }\n return result;\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.tools)\n );\n }\n\n /**\n * Get AI SDK tools from all loaded extensions.\n *\n * Tool names are prefixed with the sanitized extension name to avoid\n * collisions: e.g. extension \"github\" with tool \"create_pr\" → \"github_create_pr\".\n */\n getTools(): ToolSet {\n const tools: ToolSet = {};\n\n for (const ext of this.#extensions.values()) {\n const prefix = sanitizeName(ext.manifest.name);\n\n for (const descriptor of ext.tools) {\n const toolName = `${prefix}_${descriptor.name}`;\n\n tools[toolName] = tool({\n description: `[${ext.manifest.name}] ${descriptor.description}`,\n inputSchema: jsonSchema(\n descriptor.inputSchema as Record<string, unknown>\n ),\n execute: async (args: Record<string, unknown>) => {\n if (!this.#extensions.has(ext.manifest.name)) {\n throw new Error(\n `Extension \"${ext.manifest.name}\" has been unloaded. Tool \"${toolName}\" is no longer available.`\n );\n }\n const resultJson = await ext.entrypoint.execute(\n descriptor.name,\n JSON.stringify(args)\n );\n const parsed = JSON.parse(resultJson) as {\n result?: unknown;\n error?: string;\n };\n if (parsed.error) throw new Error(parsed.error);\n return parsed.result;\n }\n });\n }\n }\n\n return tools;\n }\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n tools: ExtensionToolDescriptor[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: tools.map((t) => `${prefix}_${t.name}`),\n contextLabels: (manifest.context ?? []).map((c) => `${prefix}_${c.label}`),\n permissions: manifest.permissions ?? {}\n };\n}\n\n/**\n * Wrap an extension source in a Worker module that exposes\n * describe(), execute(), manifest(), and hook RPC methods.\n *\n * Source format: `({ tools: {...}, hooks: {...} })`\n * Both `tools` and `hooks` are optional.\n */\nfunction wrapExtensionSource(source: string): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\n\nconst __ext = (${source});\nif (__ext && typeof __ext === \"object\" && !(\"tools\" in __ext) && !(\"hooks\" in __ext)) {\n throw new Error(\n \"Invalid extension source format. Expected { tools: {...}, hooks: {...} } \" +\n \"but got a flat object. Wrap your tools in a 'tools' key.\"\n );\n}\nconst __tools = __ext.tools || {};\nconst __hooks = __ext.hooks || {};\n\nexport default class Extension extends WorkerEntrypoint {\n describe() {\n const descriptors = [];\n for (const [name, def] of Object.entries(__tools)) {\n descriptors.push({\n name,\n description: def.description || name,\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n }\n });\n }\n return JSON.stringify(descriptors);\n }\n\n manifest() {\n return JSON.stringify({\n hooks: Object.keys(__hooks)\n });\n }\n\n async execute(toolName, argsJson) {\n const def = __tools[toolName];\n if (!def || !def.execute) {\n return JSON.stringify({ error: \"Unknown tool: \" + toolName });\n }\n try {\n const args = JSON.parse(argsJson);\n const result = await def.execute(args, this.env.host ?? null);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n\n async hook(name, ctxSnapshot) {\n const fn = __hooks[name];\n if (!fn) return JSON.stringify({ skipped: true });\n try {\n // Hook handlers receive (ctxSnapshot, host) — symmetric with tool\n // executes. \\`host\\` is null when the extension was loaded without\n // host-requiring permissions or when the worker entry point doesn't\n // re-export HostBridgeLoopback.\n const result = await fn(ctxSnapshot, this.env.host ?? null);\n return JSON.stringify({ result: result ?? {} });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aAAa,MAAsB;AACjD,KAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,WAAW,EAClC,OAAM,IAAI,MAAM,mCAAmC;AAErD,QAAO,KACJ,QAAQ,iBAAiB,IAAI,CAC7B,QAAQ,OAAO,IAAI,CACnB,QAAQ,UAAU,GAAG;;AAuB1B,MAAM,iBAAiB;;;;;;;;AAiCvB,IAAa,mBAAb,MAA8B;CAe5B,YAAY,SAAkC;;mDAdxB;oDACgB;8DAM7B;gEACK,IAAI,KAA8B,CAAC;8CACrC,MAAM;8CAGP,KAAK;AAGd,yBAA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E,gBAAgB,cAAc;EACzC,gBAAgB,YAAY,SAAS,SAAS,KAAA,IAAY;EAC1D,GAAI,OAAO,KAAK,UAAU,CAAC,SAAS,IAAI,EAAE,KAAK,WAAW,GAAG,EAAE;EAChE,EAGsB,CAAC,eAAe;CAGzC,MAAM,kBAAkB,MAAM,WAAW,UAAU;CACnD,MAAM,QAAQ,KAAK,MAAM,gBAAgB;CAEzC,IAAI,QAAkB,EAAE;AACxB,KAAI;EACF,MAAM,eAAe,MAAM,WAAW,UAAU;AAIhD,UAHwB,KAAK,MAAM,aAGZ,CAAC,SAAS,EAAE;SAC7B;AAIR,wBAAA,aAAA,KAAgB,CAAC,IAAI,SAAS,MAAM;EAClC;EACA;EACA;EACA;EACD,CAAC;AAEF,QAAO,gBAAgB,UAAU,MAAM;;AAsI3C,SAAS,gBACP,UACA,OACe;CACf,MAAM,SAAS,aAAa,SAAS,KAAK;AAC1C,QAAO;EACL,MAAM,SAAS;EACf,SAAS,SAAS;EAClB,aAAa,SAAS;EACtB,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EAC9C,gBAAgB,SAAS,WAAW,EAAE,EAAE,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,QAAQ;EAC1E,aAAa,SAAS,eAAe,EAAE;EACxC;;;;;;;;;AAUH,SAAS,oBAAoB,QAAwB;AACnD,QAAO;;iBAEQ,OAAO"}
package/dist/think.d.ts CHANGED
@@ -2,9 +2,14 @@ import {
2
2
  i as ExtensionManifest,
3
3
  t as ExtensionManager
4
4
  } from "./manager-DCbSiSWT.js";
5
+ import { WorkspaceLike } from "./tools/workspace.js";
5
6
  import {
6
7
  LanguageModel,
7
8
  ModelMessage,
9
+ PrepareStepFunction,
10
+ PrepareStepFunction as PrepareStepFunction$1,
11
+ PrepareStepResult,
12
+ PrepareStepResult as PrepareStepResult$1,
8
13
  StepResult,
9
14
  StreamTextOnChunkCallback,
10
15
  StreamTextOnStepFinishCallback,
@@ -32,6 +37,7 @@ import {
32
37
  ClientToolSchema,
33
38
  MessageConcurrency,
34
39
  MessageConcurrency as MessageConcurrency$1,
40
+ ResumableStream,
35
41
  SaveMessagesResult,
36
42
  SaveMessagesResult as SaveMessagesResult$1
37
43
  } from "agents/chat";
@@ -39,7 +45,7 @@ import {
39
45
  Session,
40
46
  Session as Session$1
41
47
  } from "agents/experimental/memory/session";
42
- import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
48
+ import { Workspace } from "@cloudflare/shell";
43
49
 
44
50
  //#region src/think.d.ts
45
51
  /**
@@ -122,7 +128,43 @@ interface TurnConfig {
122
128
  maxSteps?: number;
123
129
  /** Provider-specific options (AI SDK providerOptions). */
124
130
  providerOptions?: Record<string, unknown>;
131
+ /**
132
+ * Optional structured-output specification (AI SDK `output`).
133
+ * Forwarded to `streamText` so the model's final response is parsed
134
+ * against the supplied schema. Use the AI SDK's `Output.object({ schema })`
135
+ * / `Output.text()` helpers. Combine with `activeTools: []` on the
136
+ * terminal turn if your provider strips tools when structured output
137
+ * is active (e.g. workers-ai-provider).
138
+ */
139
+ output?: Parameters<typeof streamText>[0]["output"];
125
140
  }
141
+ /**
142
+ * Context passed to the `beforeStep` hook before each AI SDK step in
143
+ * the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`
144
+ * parameter — exposes the previous `steps`, the zero-based `stepNumber`,
145
+ * the currently selected `model`, the `messages` about to be sent, and
146
+ * `experimental_context`.
147
+ *
148
+ * Pass an explicit `TOOLS` generic for typed previous tool calls / results.
149
+ *
150
+ * Limitations (AI SDK boundary, not Think):
151
+ * - No `abortSignal` is exposed in the context. If you do remote work
152
+ * inside `beforeStep`, it cannot be cancelled by turn-level abort.
153
+ * - `experimental_context` is typed `unknown`; users must narrow it.
154
+ * - `output` cannot be overridden per-step — set it at the turn level
155
+ * via `TurnConfig.output` (returned from `beforeTurn`).
156
+ */
157
+ type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
158
+ PrepareStepFunction$1<TOOLS>
159
+ >[0];
160
+ /**
161
+ * Configuration returned by `beforeStep` to override defaults for the
162
+ * current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —
163
+ * return only the fields you want to override (`model`, `toolChoice`,
164
+ * `activeTools`, `system`, `messages`, `experimental_context`,
165
+ * `providerOptions`).
166
+ */
167
+ type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult$1<TOOLS>;
126
168
  /**
127
169
  * Context passed to the `beforeToolCall` hook **before** the tool's
128
170
  * `execute` function runs.
@@ -279,6 +321,7 @@ declare class Think<
279
321
  Props extends Record<string, unknown> = Record<string, unknown>
280
322
  > extends Agent<Env, State, Props> {
281
323
  #private;
324
+ private static readonly CONFIG_KEYS;
282
325
  /**
283
326
  * Wait for MCP server connections to be ready before the inference
284
327
  * loop. MCP tools are auto-merged into the tool set.
@@ -317,19 +360,27 @@ declare class Think<
317
360
  */
318
361
  extensionManager?: ExtensionManager;
319
362
  /**
320
- * Workspace filesystem backed by the DO's SQLite storage.
321
- * Available in `getTools()` and lifecycle hooks.
363
+ * Workspace filesystem available in `getTools()` and lifecycle hooks.
364
+ * Defaults to a full `Workspace` backed by the DO's SQLite storage.
365
+ *
366
+ * Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
367
+ * replace it with anything that satisfies the interface — e.g. a proxy
368
+ * that forwards to a shared workspace owned by a parent DO. Override as
369
+ * a class field to skip the default init entirely:
322
370
  *
323
- * Override to add R2 spillover for large files:
324
371
  * ```typescript
372
+ * // Default init with R2 spillover for large files.
325
373
  * override workspace = new Workspace({
326
374
  * sql: this.ctx.storage.sql,
327
375
  * r2: this.env.R2,
328
376
  * name: () => this.name
329
377
  * });
378
+ *
379
+ * // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
380
+ * override workspace: WorkspaceLike = new SharedWorkspace(this);
330
381
  * ```
331
382
  */
332
- workspace: Workspace$1;
383
+ workspace: WorkspaceLike;
333
384
  constructor(ctx: DurableObjectState, env: Env);
334
385
  /**
335
386
  * Conversation history. Computed from the active session.
@@ -338,7 +389,7 @@ declare class Think<
338
389
  get messages(): UIMessage[];
339
390
  private _aborts;
340
391
  private _turnQueue;
341
- private _resumableStream;
392
+ protected _resumableStream: ResumableStream;
342
393
  private _pendingResumeConnections;
343
394
  private _lastClientTools;
344
395
  private _lastBody;
@@ -347,14 +398,12 @@ declare class Think<
347
398
  private _insideResponseHook;
348
399
  private _insideInferenceLoop;
349
400
  private _pendingInteractionPromise;
350
- private _submitSequence;
351
- private _latestOverlappingSubmitSequence;
352
- private _activeDebounceTimer;
353
- private _activeDebounceResolve;
401
+ private _submitConcurrency;
354
402
  private static MESSAGE_DEBOUNCE_MS;
355
403
  /**
356
404
  * Persist an arbitrary JSON-serializable configuration object for this
357
- * agent instance. Stored in the assistant_config table — survives
405
+ * agent instance. Stored in the Think-private `think_config` table —
406
+ * survives
358
407
  * restarts and hibernation. Pass the config shape as a method generic
359
408
  * for typed call sites:
360
409
  *
@@ -376,11 +425,11 @@ declare class Think<
376
425
  * ```
377
426
  */
378
427
  getConfig<T = Record<string, unknown>>(): T | null;
428
+ protected _migrateLegacyConfigToThinkTable(): void;
379
429
  private _ensureConfigTable;
380
430
  private _configSet;
381
431
  private _configGet;
382
432
  private _configDelete;
383
- private _sessionId;
384
433
  /**
385
434
  * Return the language model to use for inference.
386
435
  * Must be overridden by subclasses.
@@ -437,6 +486,42 @@ declare class Think<
437
486
  * ```
438
487
  */
439
488
  beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
489
+ /**
490
+ * Called before each AI SDK step in the agentic loop. Backed by
491
+ * `streamText({ prepareStep })`.
492
+ *
493
+ * Return `void` to accept the current step defaults, or return a
494
+ * `StepConfig` to override the model, tool choice, active tools,
495
+ * system prompt, messages, experimental context, or provider options
496
+ * for this step. Use `beforeTurn` for turn-wide assembly and
497
+ * `beforeStep` when the decision depends on the step number or
498
+ * previous step results.
499
+ *
500
+ * @example Force search on the first step
501
+ * ```typescript
502
+ * beforeStep(ctx: PrepareStepContext) {
503
+ * if (ctx.stepNumber === 0) {
504
+ * return {
505
+ * activeTools: ["search"],
506
+ * toolChoice: { type: "tool", toolName: "search" }
507
+ * };
508
+ * }
509
+ * }
510
+ * ```
511
+ *
512
+ * @example Switch to a cheaper model after tool results land
513
+ * ```typescript
514
+ * beforeStep(ctx: PrepareStepContext) {
515
+ * // assumes a `fastSummaryModel` field on your Think subclass
516
+ * if (ctx.steps.some((s) => s.toolResults.length > 0)) {
517
+ * return { model: this.fastSummaryModel };
518
+ * }
519
+ * }
520
+ * ```
521
+ */
522
+ beforeStep(
523
+ _ctx: PrepareStepContext
524
+ ): StepConfig | void | Promise<StepConfig | void>;
440
525
  /**
441
526
  * Called **before** the tool's `execute` function runs. Think wraps
442
527
  * every tool's `execute` so it can consult this hook and act on the
@@ -721,6 +806,13 @@ declare class Think<
721
806
  private _handleClear;
722
807
  private _streamResult;
723
808
  private _persistAssistantMessage;
809
+ /**
810
+ * Persist an incoming message after reconciliation. For assistant
811
+ * messages, also resolve their ID against any server-side row that
812
+ * already owns the same `toolCallId` so we update the existing row
813
+ * instead of inserting an orphan duplicate.
814
+ */
815
+ private _persistIncomingMessage;
724
816
  private _persistClientTools;
725
817
  private _restoreClientTools;
726
818
  private _persistBody;
@@ -740,11 +832,7 @@ declare class Think<
740
832
  ): Promise<ChatRecoveryOptions$1>;
741
833
  _chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
742
834
  private _getPartialStreamText;
743
- private _normalizeMessageConcurrency;
744
835
  private _getSubmitConcurrencyDecision;
745
- private _isSupersededSubmit;
746
- private _waitForTimestamp;
747
- private _cancelActiveDebounce;
748
836
  private _completeSkippedRequest;
749
837
  private _rollbackDroppedSubmit;
750
838
  private _scheduleAutoContinuation;
@@ -769,8 +857,12 @@ export {
769
857
  type FiberContext,
770
858
  type FiberRecoveryContext,
771
859
  type MessageConcurrency,
860
+ PrepareStepContext,
861
+ type PrepareStepFunction,
862
+ type PrepareStepResult,
772
863
  type SaveMessagesResult,
773
864
  Session,
865
+ StepConfig,
774
866
  StepContext,
775
867
  type StepResult,
776
868
  StreamCallback,
@@ -785,6 +877,7 @@ export {
785
877
  TurnInput,
786
878
  type TypedToolCall,
787
879
  type TypedToolResult,
788
- Workspace
880
+ Workspace,
881
+ type WorkspaceLike
789
882
  };
790
883
  //# sourceMappingURL=think.d.ts.map