@cloudflare/think 0.11.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -6
- package/dist/{chat-sdk-D6cUghsQ.js → chat-sdk-Dm0R3pdR.js} +24 -1
- package/dist/{chat-sdk-D6cUghsQ.js.map → chat-sdk-Dm0R3pdR.js.map} +1 -1
- package/dist/cli/index.js +6 -15
- package/dist/cli/index.js.map +1 -1
- package/dist/fetch-By3eIQ-a.d.ts +147 -0
- package/dist/{index-D_S5mETO.d.ts → index-WF0HQmkk.d.ts} +299 -74
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/index.js +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/messengers/telegram.js +1 -1
- package/dist/studio/assets/{angular-html-D27LthTc.js → angular-html--XgCyfPu.js} +1 -1
- package/dist/studio/assets/{angular-ts-DtNL2gQ7.js → angular-ts-Dt-feQIe.js} +1 -1
- package/dist/studio/assets/{apl-BgEcDqM0.js → apl-B7ymkyp4.js} +1 -1
- package/dist/studio/assets/{astro-CstbRF9e.js → astro-Ce5cw2JI.js} +1 -1
- package/dist/studio/assets/{blade-CLG-7epG.js → blade-DL-aXwjv.js} +1 -1
- package/dist/studio/assets/{c-CssQqwxO.js → c-CFfr09UF.js} +1 -1
- package/dist/studio/assets/{cobol-CjmzHCjg.js → cobol-Ba1f5ZqR.js} +1 -1
- package/dist/studio/assets/{coffee-B_rqYPkp.js → coffee-BG2_viYI.js} +1 -1
- package/dist/studio/assets/{cpp-5YyZJlb7.js → cpp-pU5HgBva.js} +1 -1
- package/dist/studio/assets/{crystal-D7uKze0i.js → crystal-Dlm_uR4r.js} +1 -1
- package/dist/studio/assets/{css-k9oPgg7G.js → css-tUC4TMTn.js} +1 -1
- package/dist/studio/assets/{edge-CGgsSt0x.js → edge-CQuSKMUt.js} +1 -1
- package/dist/studio/assets/{elixir-BX_d5Evo.js → elixir-BmIB-Wi1.js} +1 -1
- package/dist/studio/assets/{elm-DENxDm5e.js → elm-ByVNCtDB.js} +1 -1
- package/dist/studio/assets/{erb-DvYOup03.js → erb-DO4uDxTq.js} +1 -1
- package/dist/studio/assets/{git-rebase-BsAdTS5A.js → git-rebase-CT8LXapC.js} +1 -1
- package/dist/studio/assets/{glimmer-js-e0h98Z67.js → glimmer-js-DzIT0v-m.js} +1 -1
- package/dist/studio/assets/{glimmer-ts-C9s5Kv8m.js → glimmer-ts-znG2j9R4.js} +1 -1
- package/dist/studio/assets/{glsl-CCiyeTRs.js → glsl-C1p8U_gW.js} +1 -1
- package/dist/studio/assets/{graphql-BRtHwsqk.js → graphql-CFqegryf.js} +1 -1
- package/dist/studio/assets/{hack-Dnt0QXHh.js → hack-BfVsNhqs.js} +1 -1
- package/dist/studio/assets/{haml-EXGmzuB1.js → haml-DVcEksY5.js} +1 -1
- package/dist/studio/assets/{handlebars-CzyBIDJE.js → handlebars-DSWgWCJ4.js} +1 -1
- package/dist/studio/assets/{highlighted-body-OFNGDK62-CQUFKLNu.js → highlighted-body-OFNGDK62-BIm4UpTS.js} +1 -1
- package/dist/studio/assets/{html-BAT8b_VM.js → html-C-lP7-T4.js} +1 -1
- package/dist/studio/assets/{html-derivative-7tkS-r6F.js → html-derivative-ByukJopb.js} +1 -1
- package/dist/studio/assets/{http-Cgka02Qq.js → http-Bax2fYIk.js} +1 -1
- package/dist/studio/assets/{hurl-Cbkh8WEw.js → hurl-BrI2qfvy.js} +1 -1
- package/dist/studio/assets/{index-D6n8vpkp.js → index-DNSTOyBe.js} +5 -5
- package/dist/studio/assets/{java-DrRKiUno.js → java-ZiR-uym-.js} +1 -1
- package/dist/studio/assets/{javascript-9LAnHOxD.js → javascript-Dhhw85Vr.js} +1 -1
- package/dist/studio/assets/{jinja-CqRt4prs.js → jinja-DqSGkgE4.js} +1 -1
- package/dist/studio/assets/{jison-BX-IOQpJ.js → jison-CwQ0BO-q.js} +1 -1
- package/dist/studio/assets/{json-dOrE-En8.js → json-Je3YfUTE.js} +1 -1
- package/dist/studio/assets/{jsx-BSTPfqWX.js → jsx-Da-dLbW1.js} +1 -1
- package/dist/studio/assets/{julia-Dvz-BPmf.js → julia-CBJ0H-0z.js} +1 -1
- package/dist/studio/assets/{just-BHQm0Atq.js → just-CnuRC_nd.js} +1 -1
- package/dist/studio/assets/{latex-CxdhxuXv.js → latex-gZANCito.js} +1 -1
- package/dist/studio/assets/{liquid-D-hM-Q_F.js → liquid-0U9aXoFI.js} +1 -1
- package/dist/studio/assets/{lua-5qtqjLHq.js → lua-CX_TqMxt.js} +1 -1
- package/dist/studio/assets/{marko-5FJaM2co.js → marko-StSURz0o.js} +1 -1
- package/dist/studio/assets/{mdc-BhYW7lCG.js → mdc-CXZpf9k1.js} +1 -1
- package/dist/studio/assets/mermaid-GHXKKRXX-CqDQH2-r.js +1 -0
- package/dist/studio/assets/{nginx-rtAXrRye.js → nginx-3Q2L4366.js} +1 -1
- package/dist/studio/assets/{nim-DQSmaN9U.js → nim-CqX_5eXP.js} +1 -1
- package/dist/studio/assets/{perl-B54AdcaE.js → perl-CLOu1GnZ.js} +1 -1
- package/dist/studio/assets/{php-DpvTxCny.js → php-C1vkiu4h.js} +1 -1
- package/dist/studio/assets/{pug-Cyffw0Ho.js → pug-Cg3cFp5y.js} +1 -1
- package/dist/studio/assets/{qml-CxRetSkO.js → qml-DhKeHMwt.js} +1 -1
- package/dist/studio/assets/{r-CXWRxrXc.js → r--Lg2-Sir.js} +1 -1
- package/dist/studio/assets/{razor-BJzI-zc9.js → razor-Cjptf146.js} +1 -1
- package/dist/studio/assets/{regexp-dqxdfrnE.js → regexp-fS0DAwei.js} +1 -1
- package/dist/studio/assets/{rst-BW7eKYj4.js → rst-BBajBzk-.js} +1 -1
- package/dist/studio/assets/{ruby-D5Npyj8-.js → ruby-KvFedogM.js} +1 -1
- package/dist/studio/assets/{sas-DZLppjul.js → sas-D6p27LWr.js} +1 -1
- package/dist/studio/assets/{scss-CbqoxyAe.js → scss-6jXfJVsd.js} +1 -1
- package/dist/studio/assets/{shellscript-CFHqBeXu.js → shellscript-BK0Qbt1B.js} +1 -1
- package/dist/studio/assets/{shellsession-CbZDA4Bf.js → shellsession-BsXmVRU4.js} +1 -1
- package/dist/studio/assets/{soy-PImjtV58.js → soy-BKtGCXkJ.js} +1 -1
- package/dist/studio/assets/{sql-DhGo8urW.js → sql-vSUKslBj.js} +1 -1
- package/dist/studio/assets/{stata-CjHWbU2v.js → stata-BQ0iXcs9.js} +1 -1
- package/dist/studio/assets/{surrealql-o8Qr4t56.js → surrealql-v5pXHIwP.js} +1 -1
- package/dist/studio/assets/{svelte-DlSIyEV1.js → svelte-BMFjqgJb.js} +1 -1
- package/dist/studio/assets/{templ-qizfwU1w.js → templ-DYMTOmIJ.js} +1 -1
- package/dist/studio/assets/{tex-Ca7T661H.js → tex-BoQem9gj.js} +1 -1
- package/dist/studio/assets/{ts-tags-DUmjLkgl.js → ts-tags-Kp2pAlsd.js} +1 -1
- package/dist/studio/assets/{tsx-CfwgIqHW.js → tsx-DaB2J5uo.js} +1 -1
- package/dist/studio/assets/{twig-D7NAYUBY.js → twig-DohCGJPH.js} +1 -1
- package/dist/studio/assets/{typescript-Bbz9oX-P.js → typescript-BGG-5I-T.js} +1 -1
- package/dist/studio/assets/{vue-vYpz06zQ.js → vue-CCDLUl9R.js} +1 -1
- package/dist/studio/assets/{vue-html-CcxTb_Jn.js → vue-html-et9GYlaF.js} +1 -1
- package/dist/studio/assets/{vue-vine-DW4RqCKF.js → vue-vine-C561z6bx.js} +1 -1
- package/dist/studio/assets/{xml-R4LZ_u4f.js → xml-CJBA1ZPm.js} +1 -1
- package/dist/studio/assets/{xsl-CS-xzp3L.js → xsl-De-lf9XG.js} +1 -1
- package/dist/studio/assets/{yaml-CqDWbYXd.js → yaml-BcMKxf75.js} +1 -1
- package/dist/studio/index.html +1 -1
- package/dist/think.d.ts +3 -2
- package/dist/think.js +281 -77
- package/dist/think.js.map +1 -1
- package/dist/tools/fetch.d.ts +22 -0
- package/dist/tools/fetch.js +646 -0
- package/dist/tools/fetch.js.map +1 -0
- package/dist/workflows.d.ts +1 -1
- package/docs/getting-started.md +11 -11
- package/docs/index.md +62 -13
- package/docs/lifecycle-hooks.md +39 -26
- package/docs/sub-agents.md +17 -13
- package/package.json +12 -7
- package/dist/studio/assets/mermaid-GHXKKRXX-CWM2EB-u.js +0 -1
package/dist/think.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import { a as _classPrivateFieldSet2, i as _classPrivateFieldGet2, n as sanitizeName, s as _classPrivateFieldInitSpec, t as ExtensionManager } from "./manager-CSk5htym.js";
|
|
2
2
|
import { createWorkspaceTools } from "./tools/workspace.js";
|
|
3
|
+
import { createFetchTools } from "./tools/fetch.js";
|
|
3
4
|
import { truncatePausedExecutionOutput } from "./tools/execute.js";
|
|
4
|
-
import { t as ThinkMessengerRuntime } from "./chat-sdk-
|
|
5
|
+
import { t as ThinkMessengerRuntime } from "./chat-sdk-Dm0R3pdR.js";
|
|
5
6
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
7
|
import { convertToModelMessages, hasToolCall, jsonSchema, stepCountIs, streamText, tool } from "ai";
|
|
8
|
+
import { createWorkersAI } from "workers-ai-provider";
|
|
9
|
+
import { anthropic } from "workers-ai-provider/anthropic";
|
|
10
|
+
import { openai } from "workers-ai-provider/openai";
|
|
7
11
|
import * as skills from "agents/skills";
|
|
8
12
|
import { SkillRegistry } from "agents/skills";
|
|
9
|
-
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, callable, getCurrentAgent, isPlatformTransientError } from "agents";
|
|
10
|
-
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, STREAM_CLEANUP_DELAY_SECONDS, StreamAccumulator, StreamProgressCreditThrottle, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyToolUpdate, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, bumpChatRecoveryProgress, chatRecoverySchedulePolicy, classifyAgentToolChildRecovery, cleanupStreamBuffers, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, iterateWithStallWatchdog, normalizeToolInput, parseProtocolMessage, partAwaitsClientInteraction, pausedExecutionUpdate, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, setChatRecovering, shouldCreditStreamProgress, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, toolPartHasSettledResult, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
13
|
+
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, callable, getCurrentAgent, isDurableObjectMemoryLimitReset, isPlatformTransientError } from "agents";
|
|
14
|
+
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, STREAM_CLEANUP_DELAY_SECONDS, StreamAccumulator, StreamProgressCreditThrottle, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyToolUpdate, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, bumpChatRecoveryProgress, chatRecoverySchedulePolicy, classifyAgentToolChildRecovery, cleanupStreamBuffers, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, normalizeToolInput, parseProtocolMessage, partAwaitsClientInteraction, pausedExecutionUpdate, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, setChatRecovering, shouldCreditStreamProgress, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, toolPartHasSettledResult, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
11
15
|
import { Session, Session as Session$1 } from "agents/experimental/memory/session";
|
|
12
16
|
import { truncateOlderMessages } from "agents/experimental/memory/utils";
|
|
13
17
|
import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
|
|
@@ -218,7 +222,8 @@ function resolveChannels(configured, messengers) {
|
|
|
218
222
|
* multi-session support.
|
|
219
223
|
*
|
|
220
224
|
* Configuration overrides:
|
|
221
|
-
* - getModel() — return
|
|
225
|
+
* - getModel() — return a model id string (resolved via the
|
|
226
|
+
* built-in workers-ai-provider) or a LanguageModel
|
|
222
227
|
* - getSystemPrompt() — return the system prompt (fallback when no context blocks)
|
|
223
228
|
* - getTools() — return the ToolSet for the agentic loop
|
|
224
229
|
* - maxSteps — max tool-call rounds per turn (default: 10)
|
|
@@ -252,11 +257,13 @@ function resolveChannels(configured, messengers) {
|
|
|
252
257
|
* @example
|
|
253
258
|
* ```typescript
|
|
254
259
|
* import { Think } from "@cloudflare/think";
|
|
255
|
-
* import { createWorkersAI } from "workers-ai-provider";
|
|
256
260
|
*
|
|
257
261
|
* export class MyAgent extends Think<Env> {
|
|
258
262
|
* getModel() {
|
|
259
|
-
*
|
|
263
|
+
* // A string is resolved via the built-in workers-ai-provider off env.AI.
|
|
264
|
+
* // Use a "@cf/..." id for Workers AI, or a "provider/model" slug like
|
|
265
|
+
* // "openai/gpt-5.5" to route through AI Gateway.
|
|
266
|
+
* return "@cf/moonshotai/kimi-k2.7-code";
|
|
260
267
|
* }
|
|
261
268
|
*
|
|
262
269
|
* getSystemPrompt() {
|
|
@@ -822,11 +829,6 @@ function defaultContextOverflowClassifier(error) {
|
|
|
822
829
|
}
|
|
823
830
|
var _configCache = /* @__PURE__ */ new WeakMap();
|
|
824
831
|
var _configTableReady = /* @__PURE__ */ new WeakMap();
|
|
825
|
-
/**
|
|
826
|
-
* An opinionated chat agent base class.
|
|
827
|
-
*
|
|
828
|
-
* @experimental The API surface may change before stabilizing.
|
|
829
|
-
*/
|
|
830
832
|
var Think = class Think extends Agent {
|
|
831
833
|
/**
|
|
832
834
|
* Internal onStart steps that failed on this wake and were skipped so the
|
|
@@ -850,6 +852,7 @@ var Think = class Think extends Agent {
|
|
|
850
852
|
this._cachedMessages = [];
|
|
851
853
|
this._onStartDegradations = [];
|
|
852
854
|
this.workspaceBash = true;
|
|
855
|
+
this.fetchTools = false;
|
|
853
856
|
this._mediaEvictionRunning = false;
|
|
854
857
|
this._mediaEvictionScheduled = false;
|
|
855
858
|
this._mediaEvictionObservedOversized = false;
|
|
@@ -1519,11 +1522,71 @@ var Think = class Think extends Agent {
|
|
|
1519
1522
|
`;
|
|
1520
1523
|
}
|
|
1521
1524
|
/**
|
|
1522
|
-
* Return the
|
|
1523
|
-
*
|
|
1525
|
+
* Return the model to use for inference. Must be overridden by subclasses.
|
|
1526
|
+
*
|
|
1527
|
+
* The return value can be either:
|
|
1528
|
+
*
|
|
1529
|
+
* - A **string** model id, resolved through the built-in
|
|
1530
|
+
* {@link https://www.npmjs.com/package/workers-ai-provider | workers-ai-provider}
|
|
1531
|
+
* off your `AI` binding (see {@link getAIBinding}). A `@cf/...` id hits
|
|
1532
|
+
* Workers AI directly; any other `"<provider>/<model>"` slug — e.g.
|
|
1533
|
+
* `"openai/gpt-5.5"`, `"anthropic/claude-sonnet-4-5"`, `"google/gemini-2.5-pro"`
|
|
1534
|
+
* — is routed through AI Gateway with resumable streaming on by default.
|
|
1535
|
+
* This is the common case: no extra package to install, no provider to wire.
|
|
1536
|
+
* - A fully-constructed AI SDK `LanguageModel`, for any other provider or for
|
|
1537
|
+
* full control over provider/gateway options.
|
|
1538
|
+
*
|
|
1539
|
+
* @example String (Workers AI)
|
|
1540
|
+
* ```typescript
|
|
1541
|
+
* getModel() {
|
|
1542
|
+
* return "@cf/moonshotai/kimi-k2.7-code";
|
|
1543
|
+
* }
|
|
1544
|
+
* ```
|
|
1545
|
+
*
|
|
1546
|
+
* @example String (third-party via AI Gateway)
|
|
1547
|
+
* ```typescript
|
|
1548
|
+
* getModel() {
|
|
1549
|
+
* return "openai/gpt-5.5";
|
|
1550
|
+
* }
|
|
1551
|
+
* ```
|
|
1552
|
+
*
|
|
1553
|
+
* @example Bring your own provider
|
|
1554
|
+
* ```typescript
|
|
1555
|
+
* import { createOpenAI } from "@ai-sdk/openai";
|
|
1556
|
+
* getModel() {
|
|
1557
|
+
* return createOpenAI({ apiKey: this.env.OPENAI_API_KEY })("gpt-5.5");
|
|
1558
|
+
* }
|
|
1559
|
+
* ```
|
|
1524
1560
|
*/
|
|
1525
1561
|
getModel() {
|
|
1526
|
-
throw new Error("Override getModel() to return a LanguageModel.");
|
|
1562
|
+
throw new Error("Override getModel() to return a model id string (e.g. \"@cf/moonshotai/kimi-k2.7-code\" or \"openai/gpt-5.5\") or a LanguageModel.");
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Return the Workers AI binding used by the built-in default provider when
|
|
1566
|
+
* {@link getModel} returns a string. Defaults to `this.env.AI`. Override if
|
|
1567
|
+
* your binding is named something other than `AI`.
|
|
1568
|
+
*/
|
|
1569
|
+
getAIBinding() {
|
|
1570
|
+
const binding = this.env.AI;
|
|
1571
|
+
if (!binding) throw new Error("Think's default model provider needs a Workers AI binding named \"AI\". Add `\"ai\": { \"binding\": \"AI\" }` to wrangler.jsonc, override getAIBinding() to return your binding, or override getModel() to return a LanguageModel.");
|
|
1572
|
+
return binding;
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* Resolve a model value into a concrete AI SDK `LanguageModel`.
|
|
1576
|
+
*
|
|
1577
|
+
* Defaults to resolving {@link getModel}. A `LanguageModel` is returned as-is;
|
|
1578
|
+
* a string is built through the bundled default provider (see {@link getModel}
|
|
1579
|
+
* for the slug rules). Use this whenever you need a usable model outside the
|
|
1580
|
+
* main turn — e.g. a side `generateText` call for summarization/compaction —
|
|
1581
|
+
* since `getModel()` may return a bare string.
|
|
1582
|
+
*/
|
|
1583
|
+
resolveModel(model = this.getModel()) {
|
|
1584
|
+
if (typeof model !== "string") return model;
|
|
1585
|
+
this._defaultProvider ??= createWorkersAI({
|
|
1586
|
+
binding: this.getAIBinding(),
|
|
1587
|
+
providers: [openai, anthropic]
|
|
1588
|
+
});
|
|
1589
|
+
return model.startsWith("@cf/") ? this._defaultProvider(model, { sessionAffinity: this.sessionAffinity }) : this._defaultProvider(model);
|
|
1527
1590
|
}
|
|
1528
1591
|
/**
|
|
1529
1592
|
* Return the system prompt for the assistant.
|
|
@@ -1796,6 +1859,7 @@ var Think = class Think extends Agent {
|
|
|
1796
1859
|
const hasContextTools = toolNames.has("load_context") || toolNames.has("unload_context");
|
|
1797
1860
|
const hasExtensionTools = toolNames.has("load_extension") || toolNames.has("list_extensions");
|
|
1798
1861
|
const hasExecuteTool = toolNames.has("execute");
|
|
1862
|
+
const hasFetchTools = [...toolNames].some((name) => name.startsWith("fetch_"));
|
|
1799
1863
|
const lines = [
|
|
1800
1864
|
"You are running inside a Think agent.",
|
|
1801
1865
|
"",
|
|
@@ -1809,6 +1873,7 @@ var Think = class Think extends Agent {
|
|
|
1809
1873
|
if (hasContextTools) lines.push("- If context-loading tools are available, use them to load relevant memory, skills, or project context before acting on incomplete information.");
|
|
1810
1874
|
if (hasExtensionTools) lines.push("- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.");
|
|
1811
1875
|
if (hasExecuteTool) lines.push("- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.");
|
|
1876
|
+
if (hasFetchTools) lines.push("- If fetch tools are available, use them to read allowlisted HTTP resources (documentation, APIs). They are read-only and bounded; respect their allowlist and do not assume access to other URLs.");
|
|
1812
1877
|
lines.push("- Do not claim access to capabilities that are not exposed as tools in this turn.");
|
|
1813
1878
|
return lines.join("\n");
|
|
1814
1879
|
}
|
|
@@ -2347,6 +2412,13 @@ var Think = class Think extends Agent {
|
|
|
2347
2412
|
await this.mcp.waitForConnections({ timeout });
|
|
2348
2413
|
}
|
|
2349
2414
|
const workspaceTools = createWorkspaceTools(this.workspace, { bash: this.workspaceBash });
|
|
2415
|
+
const fetchToolSet = this.fetchTools ? createFetchTools({
|
|
2416
|
+
...this.fetchTools,
|
|
2417
|
+
workspace: this.workspace,
|
|
2418
|
+
onEvent: (event) => {
|
|
2419
|
+
this._emit.call(this, "tool:fetch", { ...event });
|
|
2420
|
+
}
|
|
2421
|
+
}) : {};
|
|
2350
2422
|
const baseTools = this.getTools();
|
|
2351
2423
|
const actionTools = await this._compileActionTools();
|
|
2352
2424
|
const extensionTools = this.extensionManager?.getTools() ?? {};
|
|
@@ -2356,6 +2428,7 @@ var Think = class Think extends Agent {
|
|
|
2356
2428
|
const clientToolSet = createToolsFromClientSchemas(input.clientTools, input.clientToolExecutor ? { execute: input.clientToolExecutor } : void 0);
|
|
2357
2429
|
let tools = {
|
|
2358
2430
|
...workspaceTools,
|
|
2431
|
+
...fetchToolSet,
|
|
2359
2432
|
...baseTools,
|
|
2360
2433
|
...actionTools,
|
|
2361
2434
|
...extensionTools,
|
|
@@ -2373,7 +2446,7 @@ var Think = class Think extends Agent {
|
|
|
2373
2446
|
const system = this._systemPromptForTurn(baseSystem, tools);
|
|
2374
2447
|
const messages = await this._assembleModelMessages(tools);
|
|
2375
2448
|
if (messages.length === 0) throw new Error("No messages to send to the model. This usually means the chat request arrived before any messages were persisted.");
|
|
2376
|
-
const model = this.
|
|
2449
|
+
const model = this.resolveModel();
|
|
2377
2450
|
const ctx = {
|
|
2378
2451
|
system,
|
|
2379
2452
|
messages,
|
|
@@ -2387,7 +2460,7 @@ var Think = class Think extends Agent {
|
|
|
2387
2460
|
const workflowPrompt = input.workflowPrompt;
|
|
2388
2461
|
const structuredOutputSchema = workflowPrompt?.output ? jsonSchema(workflowPrompt.output.schema) : void 0;
|
|
2389
2462
|
const wantsStructuredOutput = structuredOutputSchema !== void 0;
|
|
2390
|
-
const finalModel = config.model
|
|
2463
|
+
const finalModel = config.model != null ? this.resolveModel(config.model) : model;
|
|
2391
2464
|
const finalSystem = config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
|
|
2392
2465
|
...tools,
|
|
2393
2466
|
...config.tools
|
|
@@ -2466,15 +2539,20 @@ var Think = class Think extends Agent {
|
|
|
2466
2539
|
...base,
|
|
2467
2540
|
messages: guarded
|
|
2468
2541
|
} : base;
|
|
2469
|
-
|
|
2542
|
+
const stepResult = wantsStructuredOutput && event.stepNumber >= finalMaxSteps - 1 && withMessages.toolChoice === void 0 ? {
|
|
2470
2543
|
...withMessages,
|
|
2471
2544
|
toolChoice: {
|
|
2472
2545
|
type: "tool",
|
|
2473
2546
|
toolName: finalAnswerToolName
|
|
2474
2547
|
},
|
|
2475
2548
|
activeTools: [finalAnswerToolName]
|
|
2549
|
+
} : withMessages;
|
|
2550
|
+
const stepModel = stepResult.model;
|
|
2551
|
+
if (typeof stepModel === "string") return {
|
|
2552
|
+
...stepResult,
|
|
2553
|
+
model: this.resolveModel(stepModel)
|
|
2476
2554
|
};
|
|
2477
|
-
return
|
|
2555
|
+
return stepResult;
|
|
2478
2556
|
}),
|
|
2479
2557
|
onChunk: async (event) => {
|
|
2480
2558
|
await this.onChunk(event);
|
|
@@ -3007,17 +3085,23 @@ var Think = class Think extends Agent {
|
|
|
3007
3085
|
*
|
|
3008
3086
|
* **Streaming tools (AsyncIterable):** the AI SDK supports tools whose
|
|
3009
3087
|
* `execute` returns `AsyncIterable<output>` to emit preliminary
|
|
3010
|
-
* results before a final value.
|
|
3011
|
-
*
|
|
3012
|
-
* a
|
|
3013
|
-
*
|
|
3014
|
-
*
|
|
3015
|
-
*
|
|
3016
|
-
*
|
|
3017
|
-
*
|
|
3088
|
+
* results before a final value. The canonical form is an async
|
|
3089
|
+
* generator (`async function* execute(...)`), where calling `execute`
|
|
3090
|
+
* synchronously returns a direct `AsyncIterable`. For that form Think
|
|
3091
|
+
* preserves preliminary streaming: the wrapper is itself an async
|
|
3092
|
+
* generator that `await`s `beforeToolCall` and then yields every
|
|
3093
|
+
* chunk through unchanged. Non-streaming tools keep a scalar wrapper
|
|
3094
|
+
* so they never emit a synthetic `preliminary` tool-result chunk.
|
|
3095
|
+
*
|
|
3096
|
+
* The non-canonical `async function execute(...) { return makeIter(); }`
|
|
3097
|
+
* form returns a `Promise<AsyncIterable>`, which does not stream even
|
|
3098
|
+
* in the raw AI SDK (it would surface the iterator object as the final
|
|
3099
|
+
* output). Think collapses it to the last yielded value instead. If
|
|
3100
|
+
* you need preliminary streaming, use an `async function*` `execute`.
|
|
3018
3101
|
*/
|
|
3019
3102
|
_wrapToolsWithDecision(tools) {
|
|
3020
3103
|
const wrapped = {};
|
|
3104
|
+
const self = this;
|
|
3021
3105
|
for (const [toolName, originalTool] of Object.entries(tools)) {
|
|
3022
3106
|
const t = originalTool;
|
|
3023
3107
|
const originalExecute = t.execute;
|
|
@@ -3028,43 +3112,25 @@ var Think = class Think extends Agent {
|
|
|
3028
3112
|
const isDynamic = t.type === "dynamic";
|
|
3029
3113
|
const metadata = t.metadata;
|
|
3030
3114
|
const isApprovalConfiguredAction = metadata?.cfThinkAction === true && metadata.cfThinkActionApprovalConfigured === true;
|
|
3031
|
-
const wrappedExecute =
|
|
3032
|
-
const
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
toolCall: {
|
|
3049
|
-
...toolCallBase,
|
|
3050
|
-
input: dispatchInput
|
|
3051
|
-
},
|
|
3052
|
-
stepNumber: void 0
|
|
3053
|
-
});
|
|
3054
|
-
if (!decision || decision.action === "allow") {
|
|
3055
|
-
const finalInput = decision?.input ?? input;
|
|
3056
|
-
const approvedInput = isApprovalConfiguredAction ? this._activeTurnApprovedActionInputs.get(options.toolCallId) : void 0;
|
|
3057
|
-
if (approvedInput !== void 0 && !stableJsonEqual(finalInput, approvedInput)) return actionApprovalInputErrorEnvelope();
|
|
3058
|
-
const result = await originalExecute(finalInput, options);
|
|
3059
|
-
if (result != null && typeof result === "object" && Symbol.asyncIterator in result) {
|
|
3060
|
-
let last;
|
|
3061
|
-
for await (const part of result) last = part;
|
|
3062
|
-
return last;
|
|
3063
|
-
}
|
|
3064
|
-
return result;
|
|
3115
|
+
const wrappedExecute = originalExecute.constructor?.name === "AsyncGeneratorFunction" ? (input, options) => (async function* () {
|
|
3116
|
+
const resolved = await self._resolveToolCallDecision(toolName, input, options, isDynamic, isApprovalConfiguredAction);
|
|
3117
|
+
if (!resolved.execute) {
|
|
3118
|
+
yield resolved.output;
|
|
3119
|
+
return;
|
|
3120
|
+
}
|
|
3121
|
+
const result = await originalExecute(resolved.finalInput, options);
|
|
3122
|
+
if (result != null && typeof result === "object" && Symbol.asyncIterator in result) yield* result;
|
|
3123
|
+
else yield result;
|
|
3124
|
+
})() : async (input, options) => {
|
|
3125
|
+
const resolved = await self._resolveToolCallDecision(toolName, input, options, isDynamic, isApprovalConfiguredAction);
|
|
3126
|
+
if (!resolved.execute) return resolved.output;
|
|
3127
|
+
const result = await originalExecute(resolved.finalInput, options);
|
|
3128
|
+
if (result != null && typeof result === "object" && Symbol.asyncIterator in result) {
|
|
3129
|
+
let last;
|
|
3130
|
+
for await (const part of result) last = part;
|
|
3131
|
+
return last;
|
|
3065
3132
|
}
|
|
3066
|
-
|
|
3067
|
-
return decision.output;
|
|
3133
|
+
return result;
|
|
3068
3134
|
};
|
|
3069
3135
|
wrapped[toolName] = {
|
|
3070
3136
|
...originalTool,
|
|
@@ -3073,6 +3139,58 @@ var Think = class Think extends Agent {
|
|
|
3073
3139
|
}
|
|
3074
3140
|
return wrapped;
|
|
3075
3141
|
}
|
|
3142
|
+
/**
|
|
3143
|
+
* Shared `beforeToolCall` resolution for both the scalar and streaming
|
|
3144
|
+
* tool wrappers (see {@link _wrapToolsWithDecision}). Builds the
|
|
3145
|
+
* `ToolCallContext`, consults the subclass `beforeToolCall` hook,
|
|
3146
|
+
* dispatches the extension observation snapshot, and resolves the
|
|
3147
|
+
* returned `ToolCallDecision` into either "run `execute` with this
|
|
3148
|
+
* input" or "short-circuit with this output".
|
|
3149
|
+
*/
|
|
3150
|
+
async _resolveToolCallDecision(toolName, input, options, isDynamic, isApprovalConfiguredAction) {
|
|
3151
|
+
const toolCallBase = {
|
|
3152
|
+
type: "tool-call",
|
|
3153
|
+
toolCallId: options.toolCallId,
|
|
3154
|
+
toolName,
|
|
3155
|
+
input,
|
|
3156
|
+
...isDynamic ? { dynamic: true } : {}
|
|
3157
|
+
};
|
|
3158
|
+
const ctx = {
|
|
3159
|
+
...toolCallBase,
|
|
3160
|
+
stepNumber: void 0,
|
|
3161
|
+
messages: options.messages,
|
|
3162
|
+
abortSignal: options.abortSignal
|
|
3163
|
+
};
|
|
3164
|
+
const decision = await this.beforeToolCall(ctx);
|
|
3165
|
+
const dispatchInput = decision && decision.action === "allow" && decision.input ? decision.input : input;
|
|
3166
|
+
await this._pipelineExtensionToolCallStart({
|
|
3167
|
+
toolCall: {
|
|
3168
|
+
...toolCallBase,
|
|
3169
|
+
input: dispatchInput
|
|
3170
|
+
},
|
|
3171
|
+
stepNumber: void 0
|
|
3172
|
+
});
|
|
3173
|
+
if (!decision || decision.action === "allow") {
|
|
3174
|
+
const finalInput = decision?.input ?? input;
|
|
3175
|
+
const approvedInput = isApprovalConfiguredAction ? this._activeTurnApprovedActionInputs.get(options.toolCallId) : void 0;
|
|
3176
|
+
if (approvedInput !== void 0 && !stableJsonEqual(finalInput, approvedInput)) return {
|
|
3177
|
+
execute: false,
|
|
3178
|
+
output: actionApprovalInputErrorEnvelope()
|
|
3179
|
+
};
|
|
3180
|
+
return {
|
|
3181
|
+
execute: true,
|
|
3182
|
+
finalInput
|
|
3183
|
+
};
|
|
3184
|
+
}
|
|
3185
|
+
if (decision.action === "block") return {
|
|
3186
|
+
execute: false,
|
|
3187
|
+
output: decision.reason ?? `Tool "${toolName}" was blocked by beforeToolCall.`
|
|
3188
|
+
};
|
|
3189
|
+
return {
|
|
3190
|
+
execute: false,
|
|
3191
|
+
output: decision.output
|
|
3192
|
+
};
|
|
3193
|
+
}
|
|
3076
3194
|
async _pipelineExtensionToolCallStart(event) {
|
|
3077
3195
|
if (!this.extensionManager) return;
|
|
3078
3196
|
if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
|
|
@@ -3935,7 +4053,9 @@ var Think = class Think extends Agent {
|
|
|
3935
4053
|
let forward;
|
|
3936
4054
|
const detach = () => {
|
|
3937
4055
|
if (forward) {
|
|
3938
|
-
self._agentToolForwarders.get(runId)
|
|
4056
|
+
const set = self._agentToolForwarders.get(runId);
|
|
4057
|
+
set?.delete(forward);
|
|
4058
|
+
if (set && set.size === 0) self._agentToolForwarders.delete(runId);
|
|
3939
4059
|
forward = void 0;
|
|
3940
4060
|
}
|
|
3941
4061
|
};
|
|
@@ -3954,20 +4074,10 @@ var Think = class Think extends Agent {
|
|
|
3954
4074
|
return;
|
|
3955
4075
|
}
|
|
3956
4076
|
signal?.addEventListener("abort", close, { once: true });
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
if (closed) return;
|
|
3960
|
-
|
|
3961
|
-
}
|
|
3962
|
-
const lastReplay = replayed[replayed.length - 1]?.sequence;
|
|
3963
|
-
if (lastReplay !== void 0) self._agentToolLiveSequences.set(runId, lastReplay + 1);
|
|
3964
|
-
const row = self._readAgentToolChildRun(runId);
|
|
3965
|
-
if (!row || row.completed_at !== null) {
|
|
3966
|
-
close();
|
|
3967
|
-
return;
|
|
3968
|
-
}
|
|
3969
|
-
forward = (chunk) => {
|
|
3970
|
-
if (closed || chunk.sequence <= (options?.afterSequence ?? -1)) return;
|
|
4077
|
+
let lastEmitted = options?.afterSequence ?? -1;
|
|
4078
|
+
const emit = (chunk) => {
|
|
4079
|
+
if (closed || chunk.sequence <= lastEmitted) return;
|
|
4080
|
+
lastEmitted = chunk.sequence;
|
|
3971
4081
|
try {
|
|
3972
4082
|
controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
|
|
3973
4083
|
} catch {
|
|
@@ -3975,12 +4085,44 @@ var Think = class Think extends Agent {
|
|
|
3975
4085
|
detach();
|
|
3976
4086
|
}
|
|
3977
4087
|
};
|
|
4088
|
+
let draining = true;
|
|
4089
|
+
const pending = [];
|
|
4090
|
+
forward = (chunk) => {
|
|
4091
|
+
if (closed) return;
|
|
4092
|
+
if (draining) {
|
|
4093
|
+
pending.push(chunk);
|
|
4094
|
+
return;
|
|
4095
|
+
}
|
|
4096
|
+
emit(chunk);
|
|
4097
|
+
};
|
|
3978
4098
|
const forwarders = self._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
|
|
3979
4099
|
forwarders.add(forward);
|
|
3980
4100
|
self._agentToolForwarders.set(runId, forwarders);
|
|
3981
4101
|
const closers = self._agentToolClosers.get(runId) ?? /* @__PURE__ */ new Set();
|
|
3982
4102
|
closers.add(close);
|
|
3983
4103
|
self._agentToolClosers.set(runId, closers);
|
|
4104
|
+
try {
|
|
4105
|
+
const replayed = await self.getAgentToolChunks(runId, options);
|
|
4106
|
+
for (const chunk of replayed) {
|
|
4107
|
+
if (closed) return;
|
|
4108
|
+
emit(chunk);
|
|
4109
|
+
}
|
|
4110
|
+
draining = false;
|
|
4111
|
+
for (const chunk of pending) emit(chunk);
|
|
4112
|
+
pending.length = 0;
|
|
4113
|
+
const row = self._readAgentToolChildRun(runId);
|
|
4114
|
+
if (!row || row.completed_at !== null) {
|
|
4115
|
+
close();
|
|
4116
|
+
return;
|
|
4117
|
+
}
|
|
4118
|
+
if (lastEmitted > (options?.afterSequence ?? -1)) self._agentToolLiveSequences.set(runId, lastEmitted + 1);
|
|
4119
|
+
} catch (error) {
|
|
4120
|
+
closed = true;
|
|
4121
|
+
detach();
|
|
4122
|
+
try {
|
|
4123
|
+
controller.error(error);
|
|
4124
|
+
} catch {}
|
|
4125
|
+
}
|
|
3984
4126
|
},
|
|
3985
4127
|
cancel() {
|
|
3986
4128
|
closed = true;
|
|
@@ -7609,6 +7751,27 @@ var Think = class Think extends Agent {
|
|
|
7609
7751
|
* broadcast — the deferred re-run re-fires `onExhausted` + the banner
|
|
7610
7752
|
* (the terminal writes themselves are idempotent).
|
|
7611
7753
|
*/
|
|
7754
|
+
/**
|
|
7755
|
+
* Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
|
|
7756
|
+
* back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
|
|
7757
|
+
*/
|
|
7758
|
+
_cf_recoveryAlarmCallbacks() {
|
|
7759
|
+
return ["_chatRecoveryContinue", "_chatRecoveryRetry"];
|
|
7760
|
+
}
|
|
7761
|
+
/**
|
|
7762
|
+
* Seal any still-live recovery incident as an out-of-memory exhaustion when
|
|
7763
|
+
* the alarm circuit breaker trips at its strike budget (#1825). Runs at the
|
|
7764
|
+
* outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
|
|
7765
|
+
* and the sealed-incident write can land where the mid-turn give-up's writes
|
|
7766
|
+
* OOMed. Reuses the shared give-up spine via `_exhaustRecoveryGiveUp`.
|
|
7767
|
+
*/
|
|
7768
|
+
async _cf_sealMemoryLimitedRecovery() {
|
|
7769
|
+
const active = await listActiveChatRecoveryIncidents(this.ctx.storage);
|
|
7770
|
+
for (const { incident } of active) {
|
|
7771
|
+
const callback = incident.recoveryKind === "retry" ? "_chatRecoveryRetry" : "_chatRecoveryContinue";
|
|
7772
|
+
await this._exhaustRecoveryGiveUp(callback, { incidentId: incident.incidentId }, "out_of_memory");
|
|
7773
|
+
}
|
|
7774
|
+
}
|
|
7612
7775
|
_exhaustRecoveryGiveUp(callback, data, reason) {
|
|
7613
7776
|
return this._chatRecoveryEngine().exhaustRecoveryGiveUp({
|
|
7614
7777
|
callback,
|
|
@@ -7625,6 +7788,46 @@ var Think = class Think extends Agent {
|
|
|
7625
7788
|
return this._exhaustRecoveryGiveUp(callback, data, "stable_timeout");
|
|
7626
7789
|
}
|
|
7627
7790
|
/**
|
|
7791
|
+
* Apply the tight OOM-retry budget to a recovery error (#1825). Invoked from
|
|
7792
|
+
* `_handleRecoveryCallbackError`, i.e. for an OOM that is *thrown* out of a
|
|
7793
|
+
* recovery turn (typically from recovery bookkeeping or storage/SQL ops that
|
|
7794
|
+
* reject with the memory-limit-reset message after an isolate reset). An OOM
|
|
7795
|
+
* that surfaces as a returned `error` result means `continueLastTurn` already
|
|
7796
|
+
* terminalized the turn (client error frame + `onError`), so it is NOT routed
|
|
7797
|
+
* here — re-driving a terminalized turn would be wasteful and risk a second
|
|
7798
|
+
* terminal signal. `error` may be an Error or a wrapper with a `cause` chain.
|
|
7799
|
+
*
|
|
7800
|
+
* The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
|
|
7801
|
+
* which seals once `oomAttempts` exceeds the budget; that runs before the
|
|
7802
|
+
* memory-heavy turn, in the low-memory window where writes succeed. This
|
|
7803
|
+
* method's job is to persist `oomAttempts` (small writes) so the begin path
|
|
7804
|
+
* can act on it, and to schedule a delayed re-run while under budget.
|
|
7805
|
+
*
|
|
7806
|
+
* Returns `true` when the error was an OOM and this method owns the outcome:
|
|
7807
|
+
* - under budget → a delayed re-run was scheduled (best-effort: a transient
|
|
7808
|
+
* spike may clear);
|
|
7809
|
+
* - over budget (or untrackable, or the bookkeeping itself OOMed) →
|
|
7810
|
+
* terminalized via the give-up path with `reason="out_of_memory"`.
|
|
7811
|
+
* Returns `false` for non-OOM errors so the caller proceeds normally.
|
|
7812
|
+
*/
|
|
7813
|
+
async _handleRecoveryOom(callback, data, error) {
|
|
7814
|
+
if (!isDurableObjectMemoryLimitReset(error)) return false;
|
|
7815
|
+
let decision = "exhausted";
|
|
7816
|
+
try {
|
|
7817
|
+
decision = await this._chatRecoveryEngine().recordOomAndDecide({
|
|
7818
|
+
incidentId: data?.incidentId,
|
|
7819
|
+
callback,
|
|
7820
|
+
data,
|
|
7821
|
+
maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries
|
|
7822
|
+
});
|
|
7823
|
+
} catch (bookkeepingError) {
|
|
7824
|
+
console.error("[Think] failed to record OOM recovery attempt; terminalizing", bookkeepingError);
|
|
7825
|
+
decision = "exhausted";
|
|
7826
|
+
}
|
|
7827
|
+
if (decision === "exhausted") await this._exhaustRecoveryGiveUp(callback, data, "out_of_memory");
|
|
7828
|
+
return true;
|
|
7829
|
+
}
|
|
7830
|
+
/**
|
|
7628
7831
|
* Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
|
|
7629
7832
|
* after the incident was opened.
|
|
7630
7833
|
*
|
|
@@ -7652,6 +7855,7 @@ var Think = class Think extends Agent {
|
|
|
7652
7855
|
* message until they send something new).
|
|
7653
7856
|
*/
|
|
7654
7857
|
async _handleRecoveryCallbackError(callback, data, error) {
|
|
7858
|
+
if (await this._handleRecoveryOom(callback, data, error)) return;
|
|
7655
7859
|
if (isPlatformTransientError(error)) {
|
|
7656
7860
|
const message = error instanceof Error ? error.message : String(error);
|
|
7657
7861
|
try {
|