@cloudflare/think 0.4.0 → 0.4.2
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 +25 -5
- package/dist/{classPrivateFieldGet2-C7fYS0JL.js → classPrivateFieldGet2-Bvcn7kEw.js} +5 -5
- package/dist/extensions/index.js +2 -2
- package/dist/{manager-CR9ZdLiu.js → manager-DDC3Gb0V.js} +3 -3
- package/dist/{manager-CR9ZdLiu.js.map → manager-DDC3Gb0V.js.map} +1 -1
- package/dist/think.d.ts +170 -19
- package/dist/think.js +214 -113
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.d.ts +11 -2
- package/dist/tools/workspace.js +5 -1
- package/dist/tools/workspace.js.map +1 -1
- package/package.json +5 -5
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
|
|
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 {
|
|
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
|
|
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
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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
|
}
|
package/dist/extensions/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-
|
|
2
|
-
import { r as _assertClassBrand } from "../classPrivateFieldGet2-
|
|
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-
|
|
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.
|
|
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-
|
|
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;8DAM7B;gEACK,IAAI,KAA8B,CAAC;8CACrC,MAAM;8CAGP,KAAK;AAGd,yBAAA,SAAA,MAAe,QAAQ,OAAM;AAC7B,yBAAA,UAAA,MAAgB,QAAQ,WAAW,KAAI;AACvC,yBAAA,oBAAA,MAA0B,QAAQ,qBAAqB,KAAI;;;;;;;;;;;;;;;;;CAkB7D,MAAM,UAAyB;AAC7B,MAAA,uBAAA,WAAI,KAAc,IAAI,CAAA,uBAAA,UAAC,KAAa,CAAE;AACtC,yBAAA,WAAA,MAAiB,KAAI;E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E;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,yBAAA,SAAA,MAAe,QAAQ,OAAM;AAC7B,yBAAA,UAAA,MAAgB,QAAQ,WAAW,KAAI;AACvC,yBAAA,oBAAA,MAA0B,QAAQ,qBAAqB,KAAI;;;;;;;;;;;;;;;;;CAkB7D,MAAM,UAAyB;AAC7B,MAAA,uBAAA,WAAI,KAAc,IAAI,CAAA,uBAAA,UAAC,KAAa,CAAE;AACtC,yBAAA,WAAA,MAAiB,KAAI;EAErB,MAAM,UAAU,MAAA,uBAAA,UAAM,KAAa,CAAC,KAAyB,EAC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AHwB,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,9 @@ import {
|
|
|
32
37
|
ClientToolSchema,
|
|
33
38
|
MessageConcurrency,
|
|
34
39
|
MessageConcurrency as MessageConcurrency$1,
|
|
40
|
+
ResumableStream,
|
|
41
|
+
SaveMessagesOptions,
|
|
42
|
+
SaveMessagesOptions as SaveMessagesOptions$1,
|
|
35
43
|
SaveMessagesResult,
|
|
36
44
|
SaveMessagesResult as SaveMessagesResult$1
|
|
37
45
|
} from "agents/chat";
|
|
@@ -39,7 +47,7 @@ import {
|
|
|
39
47
|
Session,
|
|
40
48
|
Session as Session$1
|
|
41
49
|
} from "agents/experimental/memory/session";
|
|
42
|
-
import { Workspace
|
|
50
|
+
import { Workspace } from "@cloudflare/shell";
|
|
43
51
|
|
|
44
52
|
//#region src/think.d.ts
|
|
45
53
|
/**
|
|
@@ -122,7 +130,43 @@ interface TurnConfig {
|
|
|
122
130
|
maxSteps?: number;
|
|
123
131
|
/** Provider-specific options (AI SDK providerOptions). */
|
|
124
132
|
providerOptions?: Record<string, unknown>;
|
|
133
|
+
/**
|
|
134
|
+
* Optional structured-output specification (AI SDK `output`).
|
|
135
|
+
* Forwarded to `streamText` so the model's final response is parsed
|
|
136
|
+
* against the supplied schema. Use the AI SDK's `Output.object({ schema })`
|
|
137
|
+
* / `Output.text()` helpers. Combine with `activeTools: []` on the
|
|
138
|
+
* terminal turn if your provider strips tools when structured output
|
|
139
|
+
* is active (e.g. workers-ai-provider).
|
|
140
|
+
*/
|
|
141
|
+
output?: Parameters<typeof streamText>[0]["output"];
|
|
125
142
|
}
|
|
143
|
+
/**
|
|
144
|
+
* Context passed to the `beforeStep` hook before each AI SDK step in
|
|
145
|
+
* the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`
|
|
146
|
+
* parameter — exposes the previous `steps`, the zero-based `stepNumber`,
|
|
147
|
+
* the currently selected `model`, the `messages` about to be sent, and
|
|
148
|
+
* `experimental_context`.
|
|
149
|
+
*
|
|
150
|
+
* Pass an explicit `TOOLS` generic for typed previous tool calls / results.
|
|
151
|
+
*
|
|
152
|
+
* Limitations (AI SDK boundary, not Think):
|
|
153
|
+
* - No `abortSignal` is exposed in the context. If you do remote work
|
|
154
|
+
* inside `beforeStep`, it cannot be cancelled by turn-level abort.
|
|
155
|
+
* - `experimental_context` is typed `unknown`; users must narrow it.
|
|
156
|
+
* - `output` cannot be overridden per-step — set it at the turn level
|
|
157
|
+
* via `TurnConfig.output` (returned from `beforeTurn`).
|
|
158
|
+
*/
|
|
159
|
+
type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
160
|
+
PrepareStepFunction$1<TOOLS>
|
|
161
|
+
>[0];
|
|
162
|
+
/**
|
|
163
|
+
* Configuration returned by `beforeStep` to override defaults for the
|
|
164
|
+
* current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —
|
|
165
|
+
* return only the fields you want to override (`model`, `toolChoice`,
|
|
166
|
+
* `activeTools`, `system`, `messages`, `experimental_context`,
|
|
167
|
+
* `providerOptions`).
|
|
168
|
+
*/
|
|
169
|
+
type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult$1<TOOLS>;
|
|
126
170
|
/**
|
|
127
171
|
* Context passed to the `beforeToolCall` hook **before** the tool's
|
|
128
172
|
* `execute` function runs.
|
|
@@ -279,6 +323,7 @@ declare class Think<
|
|
|
279
323
|
Props extends Record<string, unknown> = Record<string, unknown>
|
|
280
324
|
> extends Agent<Env, State, Props> {
|
|
281
325
|
#private;
|
|
326
|
+
private static readonly CONFIG_KEYS;
|
|
282
327
|
/**
|
|
283
328
|
* Wait for MCP server connections to be ready before the inference
|
|
284
329
|
* loop. MCP tools are auto-merged into the tool set.
|
|
@@ -317,19 +362,27 @@ declare class Think<
|
|
|
317
362
|
*/
|
|
318
363
|
extensionManager?: ExtensionManager;
|
|
319
364
|
/**
|
|
320
|
-
* Workspace filesystem
|
|
321
|
-
*
|
|
365
|
+
* Workspace filesystem available in `getTools()` and lifecycle hooks.
|
|
366
|
+
* Defaults to a full `Workspace` backed by the DO's SQLite storage.
|
|
367
|
+
*
|
|
368
|
+
* Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
|
|
369
|
+
* replace it with anything that satisfies the interface — e.g. a proxy
|
|
370
|
+
* that forwards to a shared workspace owned by a parent DO. Override as
|
|
371
|
+
* a class field to skip the default init entirely:
|
|
322
372
|
*
|
|
323
|
-
* Override to add R2 spillover for large files:
|
|
324
373
|
* ```typescript
|
|
374
|
+
* // Default init with R2 spillover for large files.
|
|
325
375
|
* override workspace = new Workspace({
|
|
326
376
|
* sql: this.ctx.storage.sql,
|
|
327
377
|
* r2: this.env.R2,
|
|
328
378
|
* name: () => this.name
|
|
329
379
|
* });
|
|
380
|
+
*
|
|
381
|
+
* // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
|
|
382
|
+
* override workspace: WorkspaceLike = new SharedWorkspace(this);
|
|
330
383
|
* ```
|
|
331
384
|
*/
|
|
332
|
-
workspace:
|
|
385
|
+
workspace: WorkspaceLike;
|
|
333
386
|
constructor(ctx: DurableObjectState, env: Env);
|
|
334
387
|
/**
|
|
335
388
|
* Conversation history. Computed from the active session.
|
|
@@ -338,7 +391,7 @@ declare class Think<
|
|
|
338
391
|
get messages(): UIMessage[];
|
|
339
392
|
private _aborts;
|
|
340
393
|
private _turnQueue;
|
|
341
|
-
|
|
394
|
+
protected _resumableStream: ResumableStream;
|
|
342
395
|
private _pendingResumeConnections;
|
|
343
396
|
private _lastClientTools;
|
|
344
397
|
private _lastBody;
|
|
@@ -347,14 +400,12 @@ declare class Think<
|
|
|
347
400
|
private _insideResponseHook;
|
|
348
401
|
private _insideInferenceLoop;
|
|
349
402
|
private _pendingInteractionPromise;
|
|
350
|
-
private
|
|
351
|
-
private _latestOverlappingSubmitSequence;
|
|
352
|
-
private _activeDebounceTimer;
|
|
353
|
-
private _activeDebounceResolve;
|
|
403
|
+
private _submitConcurrency;
|
|
354
404
|
private static MESSAGE_DEBOUNCE_MS;
|
|
355
405
|
/**
|
|
356
406
|
* Persist an arbitrary JSON-serializable configuration object for this
|
|
357
|
-
* agent instance. Stored in the
|
|
407
|
+
* agent instance. Stored in the Think-private `think_config` table —
|
|
408
|
+
* survives
|
|
358
409
|
* restarts and hibernation. Pass the config shape as a method generic
|
|
359
410
|
* for typed call sites:
|
|
360
411
|
*
|
|
@@ -376,11 +427,11 @@ declare class Think<
|
|
|
376
427
|
* ```
|
|
377
428
|
*/
|
|
378
429
|
getConfig<T = Record<string, unknown>>(): T | null;
|
|
430
|
+
protected _migrateLegacyConfigToThinkTable(): void;
|
|
379
431
|
private _ensureConfigTable;
|
|
380
432
|
private _configSet;
|
|
381
433
|
private _configGet;
|
|
382
434
|
private _configDelete;
|
|
383
|
-
private _sessionId;
|
|
384
435
|
/**
|
|
385
436
|
* Return the language model to use for inference.
|
|
386
437
|
* Must be overridden by subclasses.
|
|
@@ -437,6 +488,42 @@ declare class Think<
|
|
|
437
488
|
* ```
|
|
438
489
|
*/
|
|
439
490
|
beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
|
|
491
|
+
/**
|
|
492
|
+
* Called before each AI SDK step in the agentic loop. Backed by
|
|
493
|
+
* `streamText({ prepareStep })`.
|
|
494
|
+
*
|
|
495
|
+
* Return `void` to accept the current step defaults, or return a
|
|
496
|
+
* `StepConfig` to override the model, tool choice, active tools,
|
|
497
|
+
* system prompt, messages, experimental context, or provider options
|
|
498
|
+
* for this step. Use `beforeTurn` for turn-wide assembly and
|
|
499
|
+
* `beforeStep` when the decision depends on the step number or
|
|
500
|
+
* previous step results.
|
|
501
|
+
*
|
|
502
|
+
* @example Force search on the first step
|
|
503
|
+
* ```typescript
|
|
504
|
+
* beforeStep(ctx: PrepareStepContext) {
|
|
505
|
+
* if (ctx.stepNumber === 0) {
|
|
506
|
+
* return {
|
|
507
|
+
* activeTools: ["search"],
|
|
508
|
+
* toolChoice: { type: "tool", toolName: "search" }
|
|
509
|
+
* };
|
|
510
|
+
* }
|
|
511
|
+
* }
|
|
512
|
+
* ```
|
|
513
|
+
*
|
|
514
|
+
* @example Switch to a cheaper model after tool results land
|
|
515
|
+
* ```typescript
|
|
516
|
+
* beforeStep(ctx: PrepareStepContext) {
|
|
517
|
+
* // assumes a `fastSummaryModel` field on your Think subclass
|
|
518
|
+
* if (ctx.steps.some((s) => s.toolResults.length > 0)) {
|
|
519
|
+
* return { model: this.fastSummaryModel };
|
|
520
|
+
* }
|
|
521
|
+
* }
|
|
522
|
+
* ```
|
|
523
|
+
*/
|
|
524
|
+
beforeStep(
|
|
525
|
+
_ctx: PrepareStepContext
|
|
526
|
+
): StepConfig | void | Promise<StepConfig | void>;
|
|
440
527
|
/**
|
|
441
528
|
* Called **before** the tool's `execute` function runs. Think wraps
|
|
442
529
|
* every tool's `execute` so it can consult this hook and act on the
|
|
@@ -663,6 +750,13 @@ declare class Think<
|
|
|
663
750
|
* current state (useful when multiple calls queue up — the callback runs
|
|
664
751
|
* with the latest messages when the turn actually starts).
|
|
665
752
|
*
|
|
753
|
+
* Pass `options.signal` to cancel the turn from outside without knowing
|
|
754
|
+
* the internally-generated request id. The signal is linked to the
|
|
755
|
+
* registry's controller for this turn — when it aborts, the inference
|
|
756
|
+
* loop's signal aborts and the result reports `status: "aborted"`.
|
|
757
|
+
* Pre-aborted signals short-circuit before any model work runs. See
|
|
758
|
+
* {@link SaveMessagesOptions} for the integration point.
|
|
759
|
+
*
|
|
666
760
|
* @example Scheduled follow-up
|
|
667
761
|
* ```typescript
|
|
668
762
|
* async onScheduled() {
|
|
@@ -681,11 +775,19 @@ declare class Think<
|
|
|
681
775
|
* { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
|
|
682
776
|
* ]);
|
|
683
777
|
* ```
|
|
778
|
+
*
|
|
779
|
+
* @example External cancellation (helper-as-sub-agent)
|
|
780
|
+
* ```typescript
|
|
781
|
+
* // Inside a parent agent's tool execute — forward the AI SDK's
|
|
782
|
+
* // abortSignal so a parent stop / tab close cancels the helper.
|
|
783
|
+
* await helper.saveMessages([userMsg], { signal: abortSignal });
|
|
784
|
+
* ```
|
|
684
785
|
*/
|
|
685
786
|
saveMessages(
|
|
686
787
|
messages:
|
|
687
788
|
| UIMessage[]
|
|
688
|
-
| ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
|
|
789
|
+
| ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),
|
|
790
|
+
options?: SaveMessagesOptions$1
|
|
689
791
|
): Promise<SaveMessagesResult$1>;
|
|
690
792
|
/**
|
|
691
793
|
* Run a new LLM call following the last assistant message.
|
|
@@ -700,9 +802,13 @@ declare class Think<
|
|
|
700
802
|
*
|
|
701
803
|
* Returns early with `status: "skipped"` if there is no assistant message
|
|
702
804
|
* to continue from.
|
|
805
|
+
*
|
|
806
|
+
* Pass `options.signal` to cancel the continuation from outside —
|
|
807
|
+
* matches the {@link saveMessages} contract.
|
|
703
808
|
*/
|
|
704
809
|
protected continueLastTurn(
|
|
705
|
-
body?: Record<string, unknown
|
|
810
|
+
body?: Record<string, unknown>,
|
|
811
|
+
options?: SaveMessagesOptions$1
|
|
706
812
|
): Promise<SaveMessagesResult$1>;
|
|
707
813
|
private _setupProtocolHandlers;
|
|
708
814
|
private _handleProtocolEvent;
|
|
@@ -718,9 +824,52 @@ declare class Think<
|
|
|
718
824
|
* only turn execution state.
|
|
719
825
|
*/
|
|
720
826
|
protected resetTurnState(): void;
|
|
827
|
+
/**
|
|
828
|
+
* Abort a single in-flight chat turn by request id.
|
|
829
|
+
*
|
|
830
|
+
* Equivalent to the cancel path that fires when a client sends a
|
|
831
|
+
* `chat-request-cancel` WebSocket message — the inference loop's
|
|
832
|
+
* signal aborts, partial chunks already streamed are still
|
|
833
|
+
* persisted, and the turn's `ChatResponseResult` reports
|
|
834
|
+
* `status: "aborted"`.
|
|
835
|
+
*
|
|
836
|
+
* No-op if no controller exists for `requestId` (the turn already
|
|
837
|
+
* completed, was never started, or used a different id).
|
|
838
|
+
*
|
|
839
|
+
* Most callers don't have the request id and want
|
|
840
|
+
* {@link abortAllRequests} instead. This method is here for
|
|
841
|
+
* symmetry with the WebSocket cancel surface and for callers that
|
|
842
|
+
* happen to know the id (e.g. via a stash from an earlier
|
|
843
|
+
* `saveMessages` return).
|
|
844
|
+
*
|
|
845
|
+
* Prefer {@link SaveMessagesOptions.signal} when driving a turn
|
|
846
|
+
* programmatically — it threads the abort intent in from the start
|
|
847
|
+
* without requiring the caller to know the id.
|
|
848
|
+
*/
|
|
849
|
+
protected abortRequest(requestId: string, reason?: unknown): void;
|
|
850
|
+
/**
|
|
851
|
+
* Abort every in-flight chat turn on this agent.
|
|
852
|
+
*
|
|
853
|
+
* Aborts all controllers in the registry and clears it. Used by
|
|
854
|
+
* subclasses that drive single-purpose turns (e.g. a sub-agent
|
|
855
|
+
* helper that runs one turn at a time over RPC) and want a coarse
|
|
856
|
+
* "cancel whatever is running" handle without tracking request ids.
|
|
857
|
+
*
|
|
858
|
+
* Does NOT reset queued turns, continuation timers, or submit
|
|
859
|
+
* concurrency state — use {@link resetTurnState} for the full
|
|
860
|
+
* teardown that runs on `chat-clear`.
|
|
861
|
+
*/
|
|
862
|
+
protected abortAllRequests(): void;
|
|
721
863
|
private _handleClear;
|
|
722
864
|
private _streamResult;
|
|
723
865
|
private _persistAssistantMessage;
|
|
866
|
+
/**
|
|
867
|
+
* Persist an incoming message after reconciliation. For assistant
|
|
868
|
+
* messages, also resolve their ID against any server-side row that
|
|
869
|
+
* already owns the same `toolCallId` so we update the existing row
|
|
870
|
+
* instead of inserting an orphan duplicate.
|
|
871
|
+
*/
|
|
872
|
+
private _persistIncomingMessage;
|
|
724
873
|
private _persistClientTools;
|
|
725
874
|
private _restoreClientTools;
|
|
726
875
|
private _persistBody;
|
|
@@ -740,11 +889,7 @@ declare class Think<
|
|
|
740
889
|
): Promise<ChatRecoveryOptions$1>;
|
|
741
890
|
_chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
|
|
742
891
|
private _getPartialStreamText;
|
|
743
|
-
private _normalizeMessageConcurrency;
|
|
744
892
|
private _getSubmitConcurrencyDecision;
|
|
745
|
-
private _isSupersededSubmit;
|
|
746
|
-
private _waitForTimestamp;
|
|
747
|
-
private _cancelActiveDebounce;
|
|
748
893
|
private _completeSkippedRequest;
|
|
749
894
|
private _rollbackDroppedSubmit;
|
|
750
895
|
private _scheduleAutoContinuation;
|
|
@@ -769,8 +914,13 @@ export {
|
|
|
769
914
|
type FiberContext,
|
|
770
915
|
type FiberRecoveryContext,
|
|
771
916
|
type MessageConcurrency,
|
|
917
|
+
PrepareStepContext,
|
|
918
|
+
type PrepareStepFunction,
|
|
919
|
+
type PrepareStepResult,
|
|
920
|
+
type SaveMessagesOptions,
|
|
772
921
|
type SaveMessagesResult,
|
|
773
922
|
Session,
|
|
923
|
+
StepConfig,
|
|
774
924
|
StepContext,
|
|
775
925
|
type StepResult,
|
|
776
926
|
StreamCallback,
|
|
@@ -785,6 +935,7 @@ export {
|
|
|
785
935
|
TurnInput,
|
|
786
936
|
type TypedToolCall,
|
|
787
937
|
type TypedToolResult,
|
|
788
|
-
Workspace
|
|
938
|
+
Workspace,
|
|
939
|
+
type WorkspaceLike
|
|
789
940
|
};
|
|
790
941
|
//# sourceMappingURL=think.d.ts.map
|