@cloudflare/think 0.11.0 → 0.11.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/dist/think.js CHANGED
@@ -1,13 +1,14 @@
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
5
  import { t as ThinkMessengerRuntime } from "./chat-sdk-D6cUghsQ.js";
5
6
  import { AsyncLocalStorage } from "node:async_hooks";
6
7
  import { convertToModelMessages, hasToolCall, jsonSchema, stepCountIs, streamText, tool } from "ai";
7
8
  import * as skills from "agents/skills";
8
9
  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";
10
+ import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, callable, getCurrentAgent, isDurableObjectMemoryLimitReset, isPlatformTransientError } from "agents";
11
+ 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
12
  import { Session, Session as Session$1 } from "agents/experimental/memory/session";
12
13
  import { truncateOlderMessages } from "agents/experimental/memory/utils";
13
14
  import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
@@ -850,6 +851,7 @@ var Think = class Think extends Agent {
850
851
  this._cachedMessages = [];
851
852
  this._onStartDegradations = [];
852
853
  this.workspaceBash = true;
854
+ this.fetchTools = false;
853
855
  this._mediaEvictionRunning = false;
854
856
  this._mediaEvictionScheduled = false;
855
857
  this._mediaEvictionObservedOversized = false;
@@ -1796,6 +1798,7 @@ var Think = class Think extends Agent {
1796
1798
  const hasContextTools = toolNames.has("load_context") || toolNames.has("unload_context");
1797
1799
  const hasExtensionTools = toolNames.has("load_extension") || toolNames.has("list_extensions");
1798
1800
  const hasExecuteTool = toolNames.has("execute");
1801
+ const hasFetchTools = [...toolNames].some((name) => name.startsWith("fetch_"));
1799
1802
  const lines = [
1800
1803
  "You are running inside a Think agent.",
1801
1804
  "",
@@ -1809,6 +1812,7 @@ var Think = class Think extends Agent {
1809
1812
  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
1813
  if (hasExtensionTools) lines.push("- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.");
1811
1814
  if (hasExecuteTool) lines.push("- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.");
1815
+ 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
1816
  lines.push("- Do not claim access to capabilities that are not exposed as tools in this turn.");
1813
1817
  return lines.join("\n");
1814
1818
  }
@@ -2347,6 +2351,13 @@ var Think = class Think extends Agent {
2347
2351
  await this.mcp.waitForConnections({ timeout });
2348
2352
  }
2349
2353
  const workspaceTools = createWorkspaceTools(this.workspace, { bash: this.workspaceBash });
2354
+ const fetchToolSet = this.fetchTools ? createFetchTools({
2355
+ ...this.fetchTools,
2356
+ workspace: this.workspace,
2357
+ onEvent: (event) => {
2358
+ this._emit.call(this, "tool:fetch", { ...event });
2359
+ }
2360
+ }) : {};
2350
2361
  const baseTools = this.getTools();
2351
2362
  const actionTools = await this._compileActionTools();
2352
2363
  const extensionTools = this.extensionManager?.getTools() ?? {};
@@ -2356,6 +2367,7 @@ var Think = class Think extends Agent {
2356
2367
  const clientToolSet = createToolsFromClientSchemas(input.clientTools, input.clientToolExecutor ? { execute: input.clientToolExecutor } : void 0);
2357
2368
  let tools = {
2358
2369
  ...workspaceTools,
2370
+ ...fetchToolSet,
2359
2371
  ...baseTools,
2360
2372
  ...actionTools,
2361
2373
  ...extensionTools,
@@ -3007,17 +3019,23 @@ var Think = class Think extends Agent {
3007
3019
  *
3008
3020
  * **Streaming tools (AsyncIterable):** the AI SDK supports tools whose
3009
3021
  * `execute` returns `AsyncIterable<output>` to emit preliminary
3010
- * results before a final value. This works whether the iterator is
3011
- * returned directly (sync function, `async function*`) or wrapped in
3012
- * a Promise (`async function execute(...) { return makeIter(); }`).
3013
- * Because the wrapper must `await beforeToolCall` first, preliminary
3014
- * chunks are collapsed — only the *final* yielded value reaches the
3015
- * model. If you need true preliminary streaming, override
3016
- * `getTools()` to provide such tools and avoid using `beforeToolCall`
3017
- * for them (or accept the collapse).
3022
+ * results before a final value. The canonical form is an async
3023
+ * generator (`async function* execute(...)`), where calling `execute`
3024
+ * synchronously returns a direct `AsyncIterable`. For that form Think
3025
+ * preserves preliminary streaming: the wrapper is itself an async
3026
+ * generator that `await`s `beforeToolCall` and then yields every
3027
+ * chunk through unchanged. Non-streaming tools keep a scalar wrapper
3028
+ * so they never emit a synthetic `preliminary` tool-result chunk.
3029
+ *
3030
+ * The non-canonical `async function execute(...) { return makeIter(); }`
3031
+ * form returns a `Promise<AsyncIterable>`, which does not stream even
3032
+ * in the raw AI SDK (it would surface the iterator object as the final
3033
+ * output). Think collapses it to the last yielded value instead. If
3034
+ * you need preliminary streaming, use an `async function*` `execute`.
3018
3035
  */
3019
3036
  _wrapToolsWithDecision(tools) {
3020
3037
  const wrapped = {};
3038
+ const self = this;
3021
3039
  for (const [toolName, originalTool] of Object.entries(tools)) {
3022
3040
  const t = originalTool;
3023
3041
  const originalExecute = t.execute;
@@ -3028,43 +3046,25 @@ var Think = class Think extends Agent {
3028
3046
  const isDynamic = t.type === "dynamic";
3029
3047
  const metadata = t.metadata;
3030
3048
  const isApprovalConfiguredAction = metadata?.cfThinkAction === true && metadata.cfThinkActionApprovalConfigured === true;
3031
- const wrappedExecute = async (input, options) => {
3032
- const toolCallBase = {
3033
- type: "tool-call",
3034
- toolCallId: options.toolCallId,
3035
- toolName,
3036
- input,
3037
- ...isDynamic ? { dynamic: true } : {}
3038
- };
3039
- const ctx = {
3040
- ...toolCallBase,
3041
- stepNumber: void 0,
3042
- messages: options.messages,
3043
- abortSignal: options.abortSignal
3044
- };
3045
- const decision = await this.beforeToolCall(ctx);
3046
- const dispatchInput = decision && decision.action === "allow" && decision.input ? decision.input : input;
3047
- await this._pipelineExtensionToolCallStart({
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;
3049
+ const wrappedExecute = originalExecute.constructor?.name === "AsyncGeneratorFunction" ? (input, options) => (async function* () {
3050
+ const resolved = await self._resolveToolCallDecision(toolName, input, options, isDynamic, isApprovalConfiguredAction);
3051
+ if (!resolved.execute) {
3052
+ yield resolved.output;
3053
+ return;
3054
+ }
3055
+ const result = await originalExecute(resolved.finalInput, options);
3056
+ if (result != null && typeof result === "object" && Symbol.asyncIterator in result) yield* result;
3057
+ else yield result;
3058
+ })() : async (input, options) => {
3059
+ const resolved = await self._resolveToolCallDecision(toolName, input, options, isDynamic, isApprovalConfiguredAction);
3060
+ if (!resolved.execute) return resolved.output;
3061
+ const result = await originalExecute(resolved.finalInput, options);
3062
+ if (result != null && typeof result === "object" && Symbol.asyncIterator in result) {
3063
+ let last;
3064
+ for await (const part of result) last = part;
3065
+ return last;
3065
3066
  }
3066
- if (decision.action === "block") return decision.reason ?? `Tool "${toolName}" was blocked by beforeToolCall.`;
3067
- return decision.output;
3067
+ return result;
3068
3068
  };
3069
3069
  wrapped[toolName] = {
3070
3070
  ...originalTool,
@@ -3073,6 +3073,58 @@ var Think = class Think extends Agent {
3073
3073
  }
3074
3074
  return wrapped;
3075
3075
  }
3076
+ /**
3077
+ * Shared `beforeToolCall` resolution for both the scalar and streaming
3078
+ * tool wrappers (see {@link _wrapToolsWithDecision}). Builds the
3079
+ * `ToolCallContext`, consults the subclass `beforeToolCall` hook,
3080
+ * dispatches the extension observation snapshot, and resolves the
3081
+ * returned `ToolCallDecision` into either "run `execute` with this
3082
+ * input" or "short-circuit with this output".
3083
+ */
3084
+ async _resolveToolCallDecision(toolName, input, options, isDynamic, isApprovalConfiguredAction) {
3085
+ const toolCallBase = {
3086
+ type: "tool-call",
3087
+ toolCallId: options.toolCallId,
3088
+ toolName,
3089
+ input,
3090
+ ...isDynamic ? { dynamic: true } : {}
3091
+ };
3092
+ const ctx = {
3093
+ ...toolCallBase,
3094
+ stepNumber: void 0,
3095
+ messages: options.messages,
3096
+ abortSignal: options.abortSignal
3097
+ };
3098
+ const decision = await this.beforeToolCall(ctx);
3099
+ const dispatchInput = decision && decision.action === "allow" && decision.input ? decision.input : input;
3100
+ await this._pipelineExtensionToolCallStart({
3101
+ toolCall: {
3102
+ ...toolCallBase,
3103
+ input: dispatchInput
3104
+ },
3105
+ stepNumber: void 0
3106
+ });
3107
+ if (!decision || decision.action === "allow") {
3108
+ const finalInput = decision?.input ?? input;
3109
+ const approvedInput = isApprovalConfiguredAction ? this._activeTurnApprovedActionInputs.get(options.toolCallId) : void 0;
3110
+ if (approvedInput !== void 0 && !stableJsonEqual(finalInput, approvedInput)) return {
3111
+ execute: false,
3112
+ output: actionApprovalInputErrorEnvelope()
3113
+ };
3114
+ return {
3115
+ execute: true,
3116
+ finalInput
3117
+ };
3118
+ }
3119
+ if (decision.action === "block") return {
3120
+ execute: false,
3121
+ output: decision.reason ?? `Tool "${toolName}" was blocked by beforeToolCall.`
3122
+ };
3123
+ return {
3124
+ execute: false,
3125
+ output: decision.output
3126
+ };
3127
+ }
3076
3128
  async _pipelineExtensionToolCallStart(event) {
3077
3129
  if (!this.extensionManager) return;
3078
3130
  if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
@@ -7609,6 +7661,27 @@ var Think = class Think extends Agent {
7609
7661
  * broadcast — the deferred re-run re-fires `onExhausted` + the banner
7610
7662
  * (the terminal writes themselves are idempotent).
7611
7663
  */
7664
+ /**
7665
+ * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
7666
+ * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
7667
+ */
7668
+ _cf_recoveryAlarmCallbacks() {
7669
+ return ["_chatRecoveryContinue", "_chatRecoveryRetry"];
7670
+ }
7671
+ /**
7672
+ * Seal any still-live recovery incident as an out-of-memory exhaustion when
7673
+ * the alarm circuit breaker trips at its strike budget (#1825). Runs at the
7674
+ * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
7675
+ * and the sealed-incident write can land where the mid-turn give-up's writes
7676
+ * OOMed. Reuses the shared give-up spine via `_exhaustRecoveryGiveUp`.
7677
+ */
7678
+ async _cf_sealMemoryLimitedRecovery() {
7679
+ const active = await listActiveChatRecoveryIncidents(this.ctx.storage);
7680
+ for (const { incident } of active) {
7681
+ const callback = incident.recoveryKind === "retry" ? "_chatRecoveryRetry" : "_chatRecoveryContinue";
7682
+ await this._exhaustRecoveryGiveUp(callback, { incidentId: incident.incidentId }, "out_of_memory");
7683
+ }
7684
+ }
7612
7685
  _exhaustRecoveryGiveUp(callback, data, reason) {
7613
7686
  return this._chatRecoveryEngine().exhaustRecoveryGiveUp({
7614
7687
  callback,
@@ -7625,6 +7698,46 @@ var Think = class Think extends Agent {
7625
7698
  return this._exhaustRecoveryGiveUp(callback, data, "stable_timeout");
7626
7699
  }
7627
7700
  /**
7701
+ * Apply the tight OOM-retry budget to a recovery error (#1825). Invoked from
7702
+ * `_handleRecoveryCallbackError`, i.e. for an OOM that is *thrown* out of a
7703
+ * recovery turn (typically from recovery bookkeeping or storage/SQL ops that
7704
+ * reject with the memory-limit-reset message after an isolate reset). An OOM
7705
+ * that surfaces as a returned `error` result means `continueLastTurn` already
7706
+ * terminalized the turn (client error frame + `onError`), so it is NOT routed
7707
+ * here — re-driving a terminalized turn would be wasteful and risk a second
7708
+ * terminal signal. `error` may be an Error or a wrapper with a `cause` chain.
7709
+ *
7710
+ * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
7711
+ * which seals once `oomAttempts` exceeds the budget; that runs before the
7712
+ * memory-heavy turn, in the low-memory window where writes succeed. This
7713
+ * method's job is to persist `oomAttempts` (small writes) so the begin path
7714
+ * can act on it, and to schedule a delayed re-run while under budget.
7715
+ *
7716
+ * Returns `true` when the error was an OOM and this method owns the outcome:
7717
+ * - under budget → a delayed re-run was scheduled (best-effort: a transient
7718
+ * spike may clear);
7719
+ * - over budget (or untrackable, or the bookkeeping itself OOMed) →
7720
+ * terminalized via the give-up path with `reason="out_of_memory"`.
7721
+ * Returns `false` for non-OOM errors so the caller proceeds normally.
7722
+ */
7723
+ async _handleRecoveryOom(callback, data, error) {
7724
+ if (!isDurableObjectMemoryLimitReset(error)) return false;
7725
+ let decision = "exhausted";
7726
+ try {
7727
+ decision = await this._chatRecoveryEngine().recordOomAndDecide({
7728
+ incidentId: data?.incidentId,
7729
+ callback,
7730
+ data,
7731
+ maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries
7732
+ });
7733
+ } catch (bookkeepingError) {
7734
+ console.error("[Think] failed to record OOM recovery attempt; terminalizing", bookkeepingError);
7735
+ decision = "exhausted";
7736
+ }
7737
+ if (decision === "exhausted") await this._exhaustRecoveryGiveUp(callback, data, "out_of_memory");
7738
+ return true;
7739
+ }
7740
+ /**
7628
7741
  * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
7629
7742
  * after the incident was opened.
7630
7743
  *
@@ -7652,6 +7765,7 @@ var Think = class Think extends Agent {
7652
7765
  * message until they send something new).
7653
7766
  */
7654
7767
  async _handleRecoveryCallbackError(callback, data, error) {
7768
+ if (await this._handleRecoveryOom(callback, data, error)) return;
7655
7769
  if (isPlatformTransientError(error)) {
7656
7770
  const message = error instanceof Error ? error.message : String(error);
7657
7771
  try {