@cloudflare/think 0.23.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -14
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/index.js +1 -1
- package/dist/{index-DDnny6kt.d.ts → index-DIQ9oY1t.d.ts} +22 -5
- package/dist/{manager-rze95KCk.d.ts → manager-CtXhU1fK.d.ts} +9 -1
- package/dist/{manager-BubfmA3q.js → manager-sfWIcYJT.js} +24 -4
- package/dist/manager-sfWIcYJT.js.map +1 -0
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/think.d.ts +1 -1
- package/dist/think.js +51 -17
- package/dist/think.js.map +1 -1
- package/dist/tools/browser.d.ts +1 -1
- package/dist/tools/browser.js +1 -1
- package/dist/tools/browser.js.map +1 -1
- package/dist/tools/execute.d.ts +2 -2
- package/dist/tools/execute.js +2 -2
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/getting-started.md +2 -2
- package/docs/index.md +3 -3
- package/docs/multi-chat.md +1 -1
- package/docs/tools.md +10 -12
- package/docs/workflows.md +1 -1
- package/package.json +5 -5
- package/dist/manager-BubfmA3q.js.map +0 -1
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ import { routeAgentRequest } from "agents";
|
|
|
16
16
|
|
|
17
17
|
export class MyAgent extends Think<Env> {
|
|
18
18
|
getModel() {
|
|
19
|
-
return "@cf/
|
|
19
|
+
return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
getSystemPrompt() {
|
|
@@ -187,17 +187,16 @@ Configure the backends, and the modules they offer, on the `Workspace`:
|
|
|
187
187
|
|
|
188
188
|
```ts
|
|
189
189
|
import { Workspace } from "@cloudflare/computer";
|
|
190
|
-
import {
|
|
190
|
+
import { CodemodeBackend } from "@cloudflare/computer/backends/codemode";
|
|
191
191
|
import { createGitModule } from "@cloudflare/computer/modules/git";
|
|
192
192
|
|
|
193
193
|
export class MyAgent extends Think<Env> {
|
|
194
194
|
override workspace = new Workspace({
|
|
195
195
|
storage: this.ctx.storage,
|
|
196
196
|
backends: [
|
|
197
|
-
new
|
|
198
|
-
id: "js",
|
|
197
|
+
new CodemodeBackend({
|
|
199
198
|
loader: this.env.LOADER,
|
|
200
|
-
modules: { "
|
|
199
|
+
modules: { "codemode:git": createGitModule() }
|
|
201
200
|
})
|
|
202
201
|
]
|
|
203
202
|
});
|
|
@@ -207,24 +206,23 @@ export class MyAgent extends Think<Env> {
|
|
|
207
206
|
To change a built-in tool, return a tool with the same name from `getTools()`.
|
|
208
207
|
To hide tools for a turn, return `activeTools` from `beforeTurn`.
|
|
209
208
|
|
|
210
|
-
Give a backend a `
|
|
211
|
-
import the agent's tools; files come from `node:fs`:
|
|
209
|
+
Give a backend a `codemode:tools` module, and code the model runs with `exec`
|
|
210
|
+
can import the agent's tools; files come from `node:fs`:
|
|
212
211
|
|
|
213
212
|
```ts
|
|
214
213
|
import { createToolBindings } from "@cloudflare/computer/modules/tools";
|
|
215
214
|
import { forAISDKTools } from "@cloudflare/computer/tools/ai-sdk";
|
|
216
215
|
|
|
217
|
-
new
|
|
218
|
-
id: "js",
|
|
216
|
+
new CodemodeBackend({
|
|
219
217
|
loader: this.env.LOADER,
|
|
220
218
|
modules: {
|
|
221
|
-
"
|
|
219
|
+
"codemode:tools": createToolBindings(forAISDKTools(() => this.getTools()))
|
|
222
220
|
}
|
|
223
221
|
});
|
|
224
222
|
```
|
|
225
223
|
|
|
226
224
|
```ts
|
|
227
|
-
import { getWeather } from "
|
|
225
|
+
import { getWeather } from "codemode:tools";
|
|
228
226
|
export default async () => (await getWeather({ city: "Lisbon" })).text;
|
|
229
227
|
```
|
|
230
228
|
|
|
@@ -977,8 +975,8 @@ import { Think } from "@cloudflare/think";
|
|
|
977
975
|
type MyConfig = { modelTier: "fast" | "capable"; systemPrompt: string };
|
|
978
976
|
|
|
979
977
|
const MODEL_IDS = {
|
|
980
|
-
fast: "@cf/
|
|
981
|
-
capable: "@cf/
|
|
978
|
+
fast: "@cf/qwen/qwen3.8-27b",
|
|
979
|
+
capable: "@cf/deepseek-ai/deepseek-v4.1-flash-1017"
|
|
982
980
|
} as const;
|
|
983
981
|
|
|
984
982
|
export class MyAgent extends Think<Env> {
|
|
@@ -1010,7 +1008,7 @@ For values you want broadcast to connected clients, use `state` / `setState` fro
|
|
|
1010
1008
|
|
|
1011
1009
|
## Code execution tool
|
|
1012
1010
|
|
|
1013
|
-
> **Deprecated.** Use `exec` with `
|
|
1011
|
+
> **Deprecated.** Use `exec` with `codemode:tools` (see [Built-in workspace](#built-in-workspace)).
|
|
1014
1012
|
|
|
1015
1013
|
Let the LLM write and run JavaScript in a sandboxed Worker:
|
|
1016
1014
|
|
package/dist/extensions/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as _assertClassBrand } from "../classPrivateFieldSet2-DwGJfC3w.js";
|
|
2
|
-
import { r as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-
|
|
2
|
+
import { r as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-sfWIcYJT.js";
|
|
3
3
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
4
4
|
//#region src/extensions/host-bridge.ts
|
|
5
5
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
i as ExtensionManifest,
|
|
3
3
|
t as ExtensionManager
|
|
4
|
-
} from "./manager-
|
|
4
|
+
} from "./manager-CtXhU1fK.js";
|
|
5
5
|
import {
|
|
6
6
|
l as ThinkWorkspace,
|
|
7
7
|
t as CreateFetchToolsOptions
|
|
@@ -2368,7 +2368,7 @@ declare class Think<
|
|
|
2368
2368
|
* @example String (Workers AI)
|
|
2369
2369
|
* ```typescript
|
|
2370
2370
|
* getModel() {
|
|
2371
|
-
* return "@cf/
|
|
2371
|
+
* return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
|
|
2372
2372
|
* }
|
|
2373
2373
|
* ```
|
|
2374
2374
|
*
|
|
@@ -4044,8 +4044,9 @@ declare class Think<
|
|
|
4044
4044
|
* tab briefly renders the turn twice before collapsing. Mirrors the fix in
|
|
4045
4045
|
* `@cloudflare/ai-chat`. Continuations are skipped — they reuse the existing
|
|
4046
4046
|
* assistant message via the `continuation` frame flag, so the id must not
|
|
4047
|
-
* change mid-message.
|
|
4048
|
-
* stored chunk
|
|
4047
|
+
* change mid-message. Orphan recovery inherits a new turn's id from the
|
|
4048
|
+
* stored chunk; a continuation's id is recorded with its stream instead
|
|
4049
|
+
* (`_streamResult`).
|
|
4049
4050
|
*/
|
|
4050
4051
|
private _alignStreamStartId;
|
|
4051
4052
|
private _annotateActionApprovalChunk;
|
|
@@ -5048,6 +5049,7 @@ declare class Think<
|
|
|
5048
5049
|
options?: {
|
|
5049
5050
|
messageId?: string;
|
|
5050
5051
|
parentMessageId?: string;
|
|
5052
|
+
basePartCount?: number;
|
|
5051
5053
|
continuation?: boolean;
|
|
5052
5054
|
}
|
|
5053
5055
|
): string;
|
|
@@ -5086,6 +5088,21 @@ declare class Think<
|
|
|
5086
5088
|
* that does not record the parent.
|
|
5087
5089
|
*/
|
|
5088
5090
|
private _orphanParentId;
|
|
5091
|
+
/**
|
|
5092
|
+
* The assistant message a leaf-extending stream continues, and how many parts
|
|
5093
|
+
* it held when the stream started; undefined for a stream that produces a
|
|
5094
|
+
* message of its own. `_streamResult` records both when it starts the stream.
|
|
5095
|
+
*
|
|
5096
|
+
* Recovery keeps that many leading parts of the stored message, so it relies
|
|
5097
|
+
* on them staying put until the stream is recovered. That holds today: the
|
|
5098
|
+
* stream itself only adds parts after them, and once a stream is recovered
|
|
5099
|
+
* it is marked completed and reclaimed when the next stream starts, so a
|
|
5100
|
+
* later stream that extends the message again cannot be overwritten by a
|
|
5101
|
+
* replay.
|
|
5102
|
+
* (`_dropGenerationAfterResolvedPause` can trim an orphaned leaf; it only
|
|
5103
|
+
* drops text and reasoning written against a paused tool result.)
|
|
5104
|
+
*/
|
|
5105
|
+
private _orphanContinuedMessage;
|
|
5089
5106
|
private _persistOrphanedStream;
|
|
5090
5107
|
private _broadcastChat;
|
|
5091
5108
|
/**
|
|
@@ -5844,4 +5861,4 @@ export {
|
|
|
5844
5861
|
WaitForSubmissionOptions as zn,
|
|
5845
5862
|
MessageConcurrency$1 as zt
|
|
5846
5863
|
};
|
|
5847
|
-
//# sourceMappingURL=index-
|
|
5864
|
+
//# sourceMappingURL=index-DIQ9oY1t.d.ts.map
|
|
@@ -157,6 +157,14 @@ interface ExtensionManagerOptions {
|
|
|
157
157
|
permissions: ExtensionPermissions,
|
|
158
158
|
ownContextLabels: string[]
|
|
159
159
|
) => Fetcher;
|
|
160
|
+
/**
|
|
161
|
+
* Identifies the agent that `createHostBinding` binds to (for example
|
|
162
|
+
* `${className}:${ctx.id}`). It is part of the Dynamic Worker id of
|
|
163
|
+
* extensions that receive `env.host`, so a cached worker is never shared
|
|
164
|
+
* with another agent. Without it, such extensions get a fresh id per
|
|
165
|
+
* manager instance.
|
|
166
|
+
*/
|
|
167
|
+
workerIdScope?: string;
|
|
160
168
|
}
|
|
161
169
|
declare class ExtensionManager {
|
|
162
170
|
#private;
|
|
@@ -232,4 +240,4 @@ export {
|
|
|
232
240
|
ExtensionInfo as r,
|
|
233
241
|
ExtensionManager as t
|
|
234
242
|
};
|
|
235
|
-
//# sourceMappingURL=manager-
|
|
243
|
+
//# sourceMappingURL=manager-CtXhU1fK.d.ts.map
|
|
@@ -44,9 +44,15 @@ function sanitizeName(name) {
|
|
|
44
44
|
return name.replace(/[^a-zA-Z0-9]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
|
|
45
45
|
}
|
|
46
46
|
const STORAGE_PREFIX = "ext:";
|
|
47
|
+
async function hashWorkerConfig(input) {
|
|
48
|
+
const data = new TextEncoder().encode(JSON.stringify(input));
|
|
49
|
+
const digest = await crypto.subtle.digest("SHA-256", data);
|
|
50
|
+
return Array.from(new Uint8Array(digest).slice(0, 16), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
51
|
+
}
|
|
47
52
|
var _loader = /* @__PURE__ */ new WeakMap();
|
|
48
53
|
var _storage = /* @__PURE__ */ new WeakMap();
|
|
49
54
|
var _createHostBinding = /* @__PURE__ */ new WeakMap();
|
|
55
|
+
var _workerIdScope = /* @__PURE__ */ new WeakMap();
|
|
50
56
|
var _extensions = /* @__PURE__ */ new WeakMap();
|
|
51
57
|
var _restored = /* @__PURE__ */ new WeakMap();
|
|
52
58
|
var _onUnload = /* @__PURE__ */ new WeakMap();
|
|
@@ -57,12 +63,14 @@ var ExtensionManager = class {
|
|
|
57
63
|
_classPrivateFieldInitSpec(this, _loader, void 0);
|
|
58
64
|
_classPrivateFieldInitSpec(this, _storage, void 0);
|
|
59
65
|
_classPrivateFieldInitSpec(this, _createHostBinding, void 0);
|
|
66
|
+
_classPrivateFieldInitSpec(this, _workerIdScope, void 0);
|
|
60
67
|
_classPrivateFieldInitSpec(this, _extensions, /* @__PURE__ */ new Map());
|
|
61
68
|
_classPrivateFieldInitSpec(this, _restored, false);
|
|
62
69
|
_classPrivateFieldInitSpec(this, _onUnload, null);
|
|
63
70
|
_classPrivateFieldSet2(_loader, this, options.loader);
|
|
64
71
|
_classPrivateFieldSet2(_storage, this, options.storage ?? null);
|
|
65
72
|
_classPrivateFieldSet2(_createHostBinding, this, options.createHostBinding ?? null);
|
|
73
|
+
_classPrivateFieldSet2(_workerIdScope, this, options.workerIdScope ?? crypto.randomUUID());
|
|
66
74
|
}
|
|
67
75
|
/**
|
|
68
76
|
* Load an extension from source code.
|
|
@@ -193,18 +201,30 @@ async function _loadInternal(manifest, source) {
|
|
|
193
201
|
const workerModule = wrapExtensionSource(source);
|
|
194
202
|
const permissions = manifest.permissions ?? {};
|
|
195
203
|
const workerEnv = {};
|
|
204
|
+
let ownLabels = [];
|
|
196
205
|
const needsHost = (permissions.workspace ?? "none") !== "none" || permissions.context?.read !== void 0 || permissions.context?.write !== void 0 || (permissions.messages ?? "none") !== "none" || permissions.session?.sendMessage || permissions.session?.metadata;
|
|
197
206
|
if (_classPrivateFieldGet2(_createHostBinding, this) && needsHost) {
|
|
198
207
|
const prefix = sanitizeName(manifest.name);
|
|
199
|
-
|
|
208
|
+
ownLabels = (manifest.context ?? []).map((c) => `${prefix}_${c.label}`);
|
|
200
209
|
workerEnv.host = _classPrivateFieldGet2(_createHostBinding, this).call(this, permissions, ownLabels);
|
|
201
210
|
}
|
|
202
|
-
const
|
|
211
|
+
const globalOutbound = permissions.network?.length ? void 0 : null;
|
|
212
|
+
const hash = await hashWorkerConfig({
|
|
213
|
+
workerModule,
|
|
214
|
+
globalOutbound: globalOutbound === null ? "null" : "inherit",
|
|
215
|
+
envBindings: Object.keys(workerEnv).sort(),
|
|
216
|
+
permissions,
|
|
217
|
+
...workerEnv.host ? {
|
|
218
|
+
hostScope: _classPrivateFieldGet2(_workerIdScope, this),
|
|
219
|
+
ownContextLabels: ownLabels
|
|
220
|
+
} : {}
|
|
221
|
+
});
|
|
222
|
+
const entrypoint = _classPrivateFieldGet2(_loader, this).get(`ext-${manifest.name}-${manifest.version}-${hash}`, () => ({
|
|
203
223
|
compatibilityDate: "2025-06-01",
|
|
204
224
|
compatibilityFlags: ["nodejs_compat"],
|
|
205
225
|
mainModule: "extension.js",
|
|
206
226
|
modules: { "extension.js": workerModule },
|
|
207
|
-
globalOutbound
|
|
227
|
+
globalOutbound,
|
|
208
228
|
...Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {}
|
|
209
229
|
})).getEntrypoint();
|
|
210
230
|
const descriptorsJson = await entrypoint.describe();
|
|
@@ -310,4 +330,4 @@ export default class Extension extends WorkerEntrypoint {
|
|
|
310
330
|
//#endregion
|
|
311
331
|
export { sanitizeName as n, _classPrivateMethodInitSpec as r, ExtensionManager as t };
|
|
312
332
|
|
|
313
|
-
//# sourceMappingURL=manager-
|
|
333
|
+
//# sourceMappingURL=manager-sfWIcYJT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manager-sfWIcYJT.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 * Identifies the agent that `createHostBinding` binds to (for example\n * `${className}:${ctx.id}`). It is part of the Dynamic Worker id of\n * extensions that receive `env.host`, so a cached worker is never shared\n * with another agent. Without it, such extensions get a fresh id per\n * manager instance.\n */\n workerIdScope?: string;\n}\n\nasync function hashWorkerConfig(input: unknown): Promise<string> {\n const data = new TextEncoder().encode(JSON.stringify(input));\n const digest = await crypto.subtle.digest(\"SHA-256\", data);\n return Array.from(new Uint8Array(digest).slice(0, 16), (b) =>\n b.toString(16).padStart(2, \"0\")\n ).join(\"\");\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 #workerIdScope: string;\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 this.#workerIdScope = options.workerIdScope ?? crypto.randomUUID();\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 let ownLabels: string[] = [];\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 ownLabels = (manifest.context ?? []).map((c) => `${prefix}_${c.label}`);\n workerEnv.host = this.#createHostBinding(permissions, ownLabels);\n }\n\n // Stable, content-derived id: Dynamic Workers are billed per distinct\n // id, so restarts must reuse the id while code/permissions are unchanged.\n // A cached worker keeps the env it was created with, so an id that\n // carries `env.host` must also cover the agent and the context labels\n // that binding was created for.\n const globalOutbound = permissions.network?.length ? undefined : null;\n const hash = await hashWorkerConfig({\n workerModule,\n globalOutbound: globalOutbound === null ? \"null\" : \"inherit\",\n envBindings: Object.keys(workerEnv).sort(),\n permissions,\n ...(workerEnv.host\n ? { hostScope: this.#workerIdScope, ownContextLabels: ownLabels }\n : {})\n });\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${hash}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound,\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;CACjD,IAAI,CAAC,QAAQ,KAAK,KAAK,CAAC,CAAC,WAAW,GAClC,MAAM,IAAI,MAAM,kCAAkC;CAEpD,OAAO,KACJ,QAAQ,iBAAiB,GAAG,CAAC,CAC7B,QAAQ,OAAO,GAAG,CAAC,CACnB,QAAQ,UAAU,EAAE;AACzB;AAsBA,MAAM,iBAAiB;AAyCvB,eAAe,iBAAiB,OAAiC;CAC/D,MAAM,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC;CAC3D,MAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI;CACzD,OAAO,MAAM,KAAK,IAAI,WAAW,MAAM,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI,MACtD,E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qIF,SAAS,gBACP,UACA,OACe;CACf,MAAM,SAAS,aAAa,SAAS,IAAI;CACzC,OAAO;EACL,MAAM,SAAS;EACf,SAAS,SAAS;EAClB,aAAa,SAAS;EACtB,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,MAAM;EAC7C,gBAAgB,SAAS,WAAW,CAAC,EAAA,CAAG,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EACzE,aAAa,SAAS,eAAe,CAAC;CACxC;AACF;;;;;;;;AASA,SAAS,oBAAoB,QAAwB;CACnD,OAAO;;iBAEQ,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DxB"}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
R as TextStreamCallback,
|
|
3
3
|
c as MessengerDefinition,
|
|
4
4
|
n as ChatSdkMessengerOptions
|
|
5
|
-
} from "../index-
|
|
5
|
+
} from "../index-DIQ9oY1t.js";
|
|
6
6
|
import { TelegramAdapterConfig } from "@chat-adapter/telegram";
|
|
7
7
|
|
|
8
8
|
//#region src/messengers/telegram.d.ts
|
package/dist/think.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $n as MediaEvictionConfig, $t as RunTurnWait, An as ToolCallResultContext, At as ChunkContext, Bn as action, Bt as MessageMetadataCallback, Cn as ThinkScheduledTasks, Ct as ChatRecoveryConfig, D as DeliveryKind, Dn as ThinkWallClockSchedule, Dt as ChatRecoveryProgressContext, En as ThinkTime, Et as ChatRecoveryOptions, Fn as TurnResult, Ft as ExtensionConfig, Gn as ChannelDefinition, Gt as PrepareStepResult, Hn as isAction, Ht as PendingApproval, In as TurnTrigger, It as FiberContext, Jn as ChannelIngress, Jt as ResolvedChatRecoveryConfig, Kn as ChannelDeliveryPolicy, Kt as RejectExecutionOptions, Ln as TypedToolCall, Lt as FiberRecoveryContext, Mn as TurnContext, Mt as ContextOverflowConfig, Nn as TurnInput, Nt as DeleteSubmissionsOptions, O as DeliveryTag, On as ToolCallContext, Ot as ChatResponseResult, Pn as TurnInputMessages, Pt as DeliverNoticeOptions, Qn as messengerChannel, Qt as RunTurnSubmit, Rn as TypedToolResult, Rt as ListSubmissionsOptions, Sn as ThinkScheduledTaskSchedule, St as ChatOptions, Tn as ThinkSubmissionStatus, Tt as ChatRecoveryExhaustedContext, Un as ChannelCapabilities, Ut as PrepareStepContext, Vn as defaultContextOverflowClassifier, Vt as OnStartDegradation, Wn as ChannelContext, Wt as PrepareStepFunction, Xn as NormalizedChannelDefinition, Xt as RunTurnOptions, Yn as ChannelKind, Yt as RunTurnBase, Zn as ThinkChannels, Zt as RunTurnStream, _n as ThinkIntervalSchedule, _t as AddMessagesOptions, an as SkillRunContext, bn as ThinkScheduledTask, bt as ChatErrorContext, cn as StepContext, ct as ActionApprovalPolicy, dn as StreamCallback, dt as ActionConfig, en as SaveMessagesOptions, er as CompactAfterOptions, fn as StreamableResult, ft as ActionContext, gn as Think, gt as ActiveTurn, hn as TextStreamPart, ht as ActionPermissionSpec, in as SkillCatalog, ir as skills_d_exports, jn as TurnConfig, jt as ChunkPart, kn as ToolCallDecision, kt as ChatStartEvent, ln as StepResult, lt as ActionAuthorizationContext, mn as SubmitMessagesResult, mt as ActionKind, nn as SessionMessage, nr as SessionContextOptions, on as SkillSource, ot as Action, pn as SubmitMessagesOptions, pt as ActionIdempotencyKey, qn as ChannelDeliverySurface, qt as ReplyAttachment, rn as Skill, rr as ThinkSession, sn as StepConfig, st as ActionApprovalDescriptor, tn as SaveMessagesResult, tr as CompactionErrorHandler, un as StopCondition, ut as ActionAuthorizationDecision, vn as ThinkModel, vt as CancelSubmissionResult, wn as ThinkSubmissionInspection, wt as ChatRecoveryContext, xn as ThinkScheduledTaskContext, xt as ChatInterruptedInfo, yn as ThinkModelId, yt as ChatErrorClassification, zn as WaitForSubmissionOptions, zt as MessageConcurrency } from "./index-
|
|
1
|
+
import { $n as MediaEvictionConfig, $t as RunTurnWait, An as ToolCallResultContext, At as ChunkContext, Bn as action, Bt as MessageMetadataCallback, Cn as ThinkScheduledTasks, Ct as ChatRecoveryConfig, D as DeliveryKind, Dn as ThinkWallClockSchedule, Dt as ChatRecoveryProgressContext, En as ThinkTime, Et as ChatRecoveryOptions, Fn as TurnResult, Ft as ExtensionConfig, Gn as ChannelDefinition, Gt as PrepareStepResult, Hn as isAction, Ht as PendingApproval, In as TurnTrigger, It as FiberContext, Jn as ChannelIngress, Jt as ResolvedChatRecoveryConfig, Kn as ChannelDeliveryPolicy, Kt as RejectExecutionOptions, Ln as TypedToolCall, Lt as FiberRecoveryContext, Mn as TurnContext, Mt as ContextOverflowConfig, Nn as TurnInput, Nt as DeleteSubmissionsOptions, O as DeliveryTag, On as ToolCallContext, Ot as ChatResponseResult, Pn as TurnInputMessages, Pt as DeliverNoticeOptions, Qn as messengerChannel, Qt as RunTurnSubmit, Rn as TypedToolResult, Rt as ListSubmissionsOptions, Sn as ThinkScheduledTaskSchedule, St as ChatOptions, Tn as ThinkSubmissionStatus, Tt as ChatRecoveryExhaustedContext, Un as ChannelCapabilities, Ut as PrepareStepContext, Vn as defaultContextOverflowClassifier, Vt as OnStartDegradation, Wn as ChannelContext, Wt as PrepareStepFunction, Xn as NormalizedChannelDefinition, Xt as RunTurnOptions, Yn as ChannelKind, Yt as RunTurnBase, Zn as ThinkChannels, Zt as RunTurnStream, _n as ThinkIntervalSchedule, _t as AddMessagesOptions, an as SkillRunContext, bn as ThinkScheduledTask, bt as ChatErrorContext, cn as StepContext, ct as ActionApprovalPolicy, dn as StreamCallback, dt as ActionConfig, en as SaveMessagesOptions, er as CompactAfterOptions, fn as StreamableResult, ft as ActionContext, gn as Think, gt as ActiveTurn, hn as TextStreamPart, ht as ActionPermissionSpec, in as SkillCatalog, ir as skills_d_exports, jn as TurnConfig, jt as ChunkPart, kn as ToolCallDecision, kt as ChatStartEvent, ln as StepResult, lt as ActionAuthorizationContext, mn as SubmitMessagesResult, mt as ActionKind, nn as SessionMessage, nr as SessionContextOptions, on as SkillSource, ot as Action, pn as SubmitMessagesOptions, pt as ActionIdempotencyKey, qn as ChannelDeliverySurface, qt as ReplyAttachment, rn as Skill, rr as ThinkSession, sn as StepConfig, st as ActionApprovalDescriptor, tn as SaveMessagesResult, tr as CompactionErrorHandler, un as StopCondition, ut as ActionAuthorizationDecision, vn as ThinkModel, vt as CancelSubmissionResult, wn as ThinkSubmissionInspection, wt as ChatRecoveryContext, xn as ThinkScheduledTaskContext, xt as ChatInterruptedInfo, yn as ThinkModelId, yt as ChatErrorClassification, zn as WaitForSubmissionOptions, zt as MessageConcurrency } from "./index-DIQ9oY1t.js";
|
|
2
2
|
import { a as FetchResponseMode, i as FetchRedirectPolicy, l as ThinkWorkspace, n as FetchBindingTarget, o as FetchResult, r as FetchErrorCode, s as FetchToolEvent, t as CreateFetchToolsOptions, u as ThinkWorkspaceFilesystem } from "./fetch-CU2fC7O6.js";
|
|
3
3
|
export { Action, ActionApprovalDescriptor, ActionApprovalPolicy, ActionAuthorizationContext, ActionAuthorizationDecision, ActionConfig, ActionContext, ActionIdempotencyKey, ActionKind, ActionPermissionSpec, ActiveTurn, AddMessagesOptions, CancelSubmissionResult, type ChannelCapabilities, type ChannelContext, type ChannelDefinition, type ChannelDeliveryPolicy, type ChannelDeliverySurface, type ChannelIngress, type ChannelKind, ChatErrorClassification, ChatErrorContext, ChatInterruptedInfo, ChatOptions, type ChatRecoveryConfig, type ChatRecoveryContext, type ChatRecoveryExhaustedContext, type ChatRecoveryOptions, type ChatRecoveryProgressContext, type ChatResponseResult, ChatStartEvent, ChunkContext, ChunkPart, type CompactAfterOptions, type CompactionErrorHandler, ContextOverflowConfig, type CreateFetchToolsOptions, DeleteSubmissionsOptions, DeliverNoticeOptions, type DeliveryKind, type DeliveryTag, ExtensionConfig, type FetchBindingTarget, type FetchErrorCode, type FetchRedirectPolicy, type FetchResponseMode, type FetchResult, type FetchToolEvent, type FiberContext, type FiberRecoveryContext, ListSubmissionsOptions, type MediaEvictionConfig, type MessageConcurrency, MessageMetadataCallback, type NormalizedChannelDefinition, OnStartDegradation, PendingApproval, PrepareStepContext, type PrepareStepFunction, type PrepareStepResult, RejectExecutionOptions, ReplyAttachment, type ResolvedChatRecoveryConfig, RunTurnBase, RunTurnOptions, RunTurnStream, RunTurnSubmit, RunTurnWait, type SaveMessagesOptions, type SaveMessagesResult, ThinkSession as Session, ThinkSession, type SessionContextOptions, type SessionMessage, type Skill, type SkillCatalog, type SkillRunContext, type SkillSource, StepConfig, StepContext, type StepResult, type StopCondition, StreamCallback, StreamableResult, SubmitMessagesOptions, SubmitMessagesResult, type TextStreamPart, Think, type ThinkChannels, ThinkIntervalSchedule, ThinkModel, ThinkModelId, ThinkScheduledTask, ThinkScheduledTaskContext, ThinkScheduledTaskSchedule, ThinkScheduledTasks, ThinkSubmissionInspection, ThinkSubmissionStatus, ThinkTime, ThinkWallClockSchedule, type ThinkWorkspace, type ThinkWorkspaceFilesystem, ToolCallContext, ToolCallDecision, ToolCallResultContext, TurnConfig, TurnContext, TurnInput, TurnInputMessages, TurnResult, TurnTrigger, type TypedToolCall, type TypedToolResult, WaitForSubmissionOptions, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills_d_exports as skills };
|
package/dist/think.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
2
|
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-DwGJfC3w.js";
|
|
3
|
-
import { n as sanitizeName, r as _classPrivateMethodInitSpec, t as ExtensionManager } from "./manager-
|
|
3
|
+
import { n as sanitizeName, r as _classPrivateMethodInitSpec, t as ExtensionManager } from "./manager-sfWIcYJT.js";
|
|
4
4
|
import { n as WorkspaceFiles, r as resolveWorkspacePath, t as createFetchTools } from "./fetch-DO3uQ9py.js";
|
|
5
5
|
import { truncatePausedExecutionOutput } from "./tools/execute.js";
|
|
6
6
|
import { _ as MESSENGER_REPLY_FIBER_NAME, n as ThinkMessengerRuntime, t as DEFAULT_MESSENGER_CONCURRENCY } from "./chat-sdk-BEjKXjCm.js";
|
|
@@ -570,7 +570,7 @@ function resolveChannels(configured, messengers) {
|
|
|
570
570
|
* // A string is resolved via the built-in workers-ai-provider off env.AI.
|
|
571
571
|
* // Use a "@cf/..." id for Workers AI, or a "provider/model" slug like
|
|
572
572
|
* // "openai/gpt-5.5" to route through AI Gateway.
|
|
573
|
-
* return "@cf/
|
|
573
|
+
* return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
|
|
574
574
|
* }
|
|
575
575
|
*
|
|
576
576
|
* getSystemPrompt() {
|
|
@@ -2419,7 +2419,7 @@ var Think = class Think extends Agent {
|
|
|
2419
2419
|
* @example String (Workers AI)
|
|
2420
2420
|
* ```typescript
|
|
2421
2421
|
* getModel() {
|
|
2422
|
-
* return "@cf/
|
|
2422
|
+
* return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
|
|
2423
2423
|
* }
|
|
2424
2424
|
* ```
|
|
2425
2425
|
*
|
|
@@ -2439,7 +2439,7 @@ var Think = class Think extends Agent {
|
|
|
2439
2439
|
* ```
|
|
2440
2440
|
*/
|
|
2441
2441
|
getModel() {
|
|
2442
|
-
throw new Error("Override getModel() to return a model id string (e.g. \"@cf/
|
|
2442
|
+
throw new Error("Override getModel() to return a model id string (e.g. \"@cf/deepseek-ai/deepseek-v4.1-flash-1017\" or \"openai/gpt-5.5\") or a LanguageModel.");
|
|
2443
2443
|
}
|
|
2444
2444
|
/**
|
|
2445
2445
|
* Return the Workers AI binding used by the built-in default provider when
|
|
@@ -2480,7 +2480,7 @@ var Think = class Think extends Agent {
|
|
|
2480
2480
|
if (typeof model !== "string") return model;
|
|
2481
2481
|
const isWorkersAI = isWorkersAIModelId(model);
|
|
2482
2482
|
const slash = model.indexOf("/");
|
|
2483
|
-
if (!isWorkersAI && (model.startsWith("@") || slash <= 0 || slash === model.length - 1)) throw new Error(`Invalid model id ${JSON.stringify(model)}. Use a Workers AI id (e.g. "@cf/
|
|
2483
|
+
if (!isWorkersAI && (model.startsWith("@") || slash <= 0 || slash === model.length - 1)) throw new Error(`Invalid model id ${JSON.stringify(model)}. Use a Workers AI id (e.g. "@cf/deepseek-ai/deepseek-v4.1-flash-1017") or a "<provider>/<model>" AI Gateway slug (e.g. "openai/gpt-5.5"), or return a LanguageModel.`);
|
|
2484
2484
|
const gateway = this.getGateway(model);
|
|
2485
2485
|
if (gateway !== null && typeof gateway === "object" && typeof gateway.then === "function") throw new Error(`getGateway() returned a Promise for model "${model}". It must return GatewayOptions (or undefined) synchronously; resolve any async lookup in beforeTurn and return the model from there instead.`);
|
|
2486
2486
|
this._defaultProvider ??= createWorkersAI({
|
|
@@ -3558,12 +3558,15 @@ var Think = class Think extends Agent {
|
|
|
3558
3558
|
this.extensionManager = new ExtensionManager({
|
|
3559
3559
|
loader: this.extensionLoader,
|
|
3560
3560
|
storage: this.ctx.storage,
|
|
3561
|
-
...hasBridge ? {
|
|
3562
|
-
agentClassName
|
|
3563
|
-
|
|
3564
|
-
|
|
3565
|
-
|
|
3566
|
-
|
|
3561
|
+
...hasBridge ? {
|
|
3562
|
+
workerIdScope: `${agentClassName}:${agentId}`,
|
|
3563
|
+
createHostBinding: (permissions, ownContextLabels) => ctxExports.HostBridgeLoopback({ props: {
|
|
3564
|
+
agentClassName,
|
|
3565
|
+
agentId,
|
|
3566
|
+
permissions,
|
|
3567
|
+
ownContextLabels
|
|
3568
|
+
} })
|
|
3569
|
+
} : {}
|
|
3567
3570
|
});
|
|
3568
3571
|
const configs = this.getExtensions();
|
|
3569
3572
|
for (const config of configs) await this.extensionManager.load(config.manifest, config.source);
|
|
@@ -8001,8 +8004,9 @@ var Think = class Think extends Agent {
|
|
|
8001
8004
|
* tab briefly renders the turn twice before collapsing. Mirrors the fix in
|
|
8002
8005
|
* `@cloudflare/ai-chat`. Continuations are skipped — they reuse the existing
|
|
8003
8006
|
* assistant message via the `continuation` frame flag, so the id must not
|
|
8004
|
-
* change mid-message.
|
|
8005
|
-
* stored chunk
|
|
8007
|
+
* change mid-message. Orphan recovery inherits a new turn's id from the
|
|
8008
|
+
* stored chunk; a continuation's id is recorded with its stream instead
|
|
8009
|
+
* (`_streamResult`).
|
|
8006
8010
|
*/
|
|
8007
8011
|
_alignStreamStartId(chunk, action, accumulator, continuation) {
|
|
8008
8012
|
if (action?.type === "start" && action.messageId == null && !continuation) chunk.messageId = accumulator.messageId;
|
|
@@ -8417,19 +8421,22 @@ var Think = class Think extends Agent {
|
|
|
8417
8421
|
const clearGen = this._turnQueue.generation;
|
|
8418
8422
|
const continuation = options?.continuation ?? false;
|
|
8419
8423
|
const parentId = options?.parentId;
|
|
8424
|
+
const leaf = this.messages.at(-1);
|
|
8425
|
+
const continuationAssistant = continuation && options?.extendLeafAssistant && leaf?.role === "assistant" ? leaf : void 0;
|
|
8426
|
+
const assistantId = continuationAssistant?.id ?? crypto.randomUUID();
|
|
8420
8427
|
const streamId = this._startResumableStream(requestId, {
|
|
8421
8428
|
continuation,
|
|
8429
|
+
...continuation && { messageId: assistantId },
|
|
8430
|
+
...continuationAssistant !== void 0 && { basePartCount: continuationAssistant.parts.length },
|
|
8422
8431
|
...parentId !== void 0 && { parentMessageId: parentId }
|
|
8423
8432
|
});
|
|
8424
8433
|
if (this._continuation.pending?.requestId === requestId) {
|
|
8425
8434
|
this._continuation.activatePending();
|
|
8426
8435
|
this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
|
|
8427
8436
|
}
|
|
8428
|
-
const leaf = this.messages.at(-1);
|
|
8429
|
-
const continuationAssistant = continuation && options?.extendLeafAssistant && leaf?.role === "assistant" ? leaf : void 0;
|
|
8430
8437
|
const leafMetadata = continuationAssistant?.metadata;
|
|
8431
8438
|
const accumulator = new StreamAccumulator({
|
|
8432
|
-
messageId:
|
|
8439
|
+
messageId: assistantId,
|
|
8433
8440
|
continuation: continuationAssistant !== void 0,
|
|
8434
8441
|
existingParts: continuationAssistant?.parts.map(settleInterruptedPart),
|
|
8435
8442
|
existingMetadata: leafMetadata !== null && typeof leafMetadata === "object" ? leafMetadata : void 0
|
|
@@ -11233,6 +11240,28 @@ var Think = class Think extends Agent {
|
|
|
11233
11240
|
_orphanParentId(streamId) {
|
|
11234
11241
|
return this._resumableStream.getStreamParentMessageId?.(streamId) ?? void 0;
|
|
11235
11242
|
}
|
|
11243
|
+
/**
|
|
11244
|
+
* The assistant message a leaf-extending stream continues, and how many parts
|
|
11245
|
+
* it held when the stream started; undefined for a stream that produces a
|
|
11246
|
+
* message of its own. `_streamResult` records both when it starts the stream.
|
|
11247
|
+
*
|
|
11248
|
+
* Recovery keeps that many leading parts of the stored message, so it relies
|
|
11249
|
+
* on them staying put until the stream is recovered. That holds today: the
|
|
11250
|
+
* stream itself only adds parts after them, and once a stream is recovered
|
|
11251
|
+
* it is marked completed and reclaimed when the next stream starts, so a
|
|
11252
|
+
* later stream that extends the message again cannot be overwritten by a
|
|
11253
|
+
* replay.
|
|
11254
|
+
* (`_dropGenerationAfterResolvedPause` can trim an orphaned leaf; it only
|
|
11255
|
+
* drops text and reasoning written against a paused tool result.)
|
|
11256
|
+
*/
|
|
11257
|
+
_orphanContinuedMessage(streamId) {
|
|
11258
|
+
const messageId = this._resumableStream.getStreamMessageId(streamId);
|
|
11259
|
+
const basePartCount = this._resumableStream.getStreamBasePartCount(streamId);
|
|
11260
|
+
return messageId !== null && basePartCount !== null ? {
|
|
11261
|
+
messageId,
|
|
11262
|
+
basePartCount
|
|
11263
|
+
} : void 0;
|
|
11264
|
+
}
|
|
11236
11265
|
async _persistOrphanedStream(streamId) {
|
|
11237
11266
|
this._resumableStream.flushBuffer();
|
|
11238
11267
|
const chunks = this._resumableStream.getStreamChunks(streamId);
|
|
@@ -11240,12 +11269,17 @@ var Think = class Think extends Agent {
|
|
|
11240
11269
|
let persistedId;
|
|
11241
11270
|
const store = this._orphanStore();
|
|
11242
11271
|
const parentId = this._orphanParentId(streamId);
|
|
11272
|
+
const continued = this._orphanContinuedMessage(streamId);
|
|
11243
11273
|
if (!await persistReconstructedOrphan(chunks, {
|
|
11244
11274
|
store: parentId === void 0 ? store : {
|
|
11245
11275
|
...store,
|
|
11246
11276
|
appendMessage: (message) => store.appendMessage(message, parentId)
|
|
11247
11277
|
},
|
|
11248
|
-
|
|
11278
|
+
...continued && { continues: {
|
|
11279
|
+
...continued,
|
|
11280
|
+
settleBasePart: settleInterruptedPart
|
|
11281
|
+
} },
|
|
11282
|
+
fallbackId: this._resumableStream.getStreamMessageId(streamId) ?? crypto.randomUUID(),
|
|
11249
11283
|
prepare: (message) => {
|
|
11250
11284
|
const prepared = this._strippedForPersist(message);
|
|
11251
11285
|
persistedId = prepared?.id;
|