@cloudflare/think 0.13.0 → 0.14.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.
Files changed (88) hide show
  1. package/README.md +20 -6
  2. package/dist/{index-Cm0jriTY.d.ts → index-CDNxUctz.d.ts} +39 -6
  3. package/dist/messengers/index.d.ts +1 -1
  4. package/dist/messengers/telegram.d.ts +1 -1
  5. package/dist/studio/assets/{angular-html--XgCyfPu.js → angular-html-Dl5doFtz.js} +1 -1
  6. package/dist/studio/assets/{angular-ts-Dt-feQIe.js → angular-ts-CbN7_mlY.js} +1 -1
  7. package/dist/studio/assets/{apl-B7ymkyp4.js → apl-CUTyCKtR.js} +1 -1
  8. package/dist/studio/assets/{astro-Ce5cw2JI.js → astro-4sWs7Jg3.js} +1 -1
  9. package/dist/studio/assets/{blade-DL-aXwjv.js → blade-NmhW_pJp.js} +1 -1
  10. package/dist/studio/assets/{c-CFfr09UF.js → c-_ropPcoN.js} +1 -1
  11. package/dist/studio/assets/{cobol-Ba1f5ZqR.js → cobol-BacpIX4U.js} +1 -1
  12. package/dist/studio/assets/{coffee-BG2_viYI.js → coffee-DcwgCl9J.js} +1 -1
  13. package/dist/studio/assets/{cpp-pU5HgBva.js → cpp-BCPbrI0m.js} +1 -1
  14. package/dist/studio/assets/{crystal-Dlm_uR4r.js → crystal-DZXQ6wBH.js} +1 -1
  15. package/dist/studio/assets/{css-tUC4TMTn.js → css-BYyCaTYR.js} +1 -1
  16. package/dist/studio/assets/{edge-CQuSKMUt.js → edge-CVh9HJt8.js} +1 -1
  17. package/dist/studio/assets/{elixir-BmIB-Wi1.js → elixir-9uvyi7ZY.js} +1 -1
  18. package/dist/studio/assets/{elm-ByVNCtDB.js → elm-DDSgRIyn.js} +1 -1
  19. package/dist/studio/assets/{erb-DO4uDxTq.js → erb-DAVyz0cP.js} +1 -1
  20. package/dist/studio/assets/{git-rebase-CT8LXapC.js → git-rebase-z3txLW9w.js} +1 -1
  21. package/dist/studio/assets/{glimmer-js-DzIT0v-m.js → glimmer-js-BRADiKXN.js} +1 -1
  22. package/dist/studio/assets/{glimmer-ts-znG2j9R4.js → glimmer-ts-B6C6vVGo.js} +1 -1
  23. package/dist/studio/assets/{glsl-C1p8U_gW.js → glsl-34bCtA9U.js} +1 -1
  24. package/dist/studio/assets/{graphql-CFqegryf.js → graphql-CL83z2DV.js} +1 -1
  25. package/dist/studio/assets/{hack-BfVsNhqs.js → hack-B9WxPQav.js} +1 -1
  26. package/dist/studio/assets/{haml-DVcEksY5.js → haml-oavex6g4.js} +1 -1
  27. package/dist/studio/assets/{handlebars-DSWgWCJ4.js → handlebars-pd64xhEq.js} +1 -1
  28. package/dist/studio/assets/{highlighted-body-OFNGDK62-BIm4UpTS.js → highlighted-body-OFNGDK62-DB3-I0_d.js} +1 -1
  29. package/dist/studio/assets/{html-C-lP7-T4.js → html-A_mALprL.js} +1 -1
  30. package/dist/studio/assets/{html-derivative-ByukJopb.js → html-derivative-CBwZyoIR.js} +1 -1
  31. package/dist/studio/assets/{http-Bax2fYIk.js → http-Cua_-o-V.js} +1 -1
  32. package/dist/studio/assets/{hurl-BrI2qfvy.js → hurl-Dpr8mC4K.js} +1 -1
  33. package/dist/studio/assets/{index-DNSTOyBe.js → index-DmVgVRjr.js} +86 -86
  34. package/dist/studio/assets/{java-ZiR-uym-.js → java-B1Ptmnmm.js} +1 -1
  35. package/dist/studio/assets/{javascript-Dhhw85Vr.js → javascript-waNlhfIS.js} +1 -1
  36. package/dist/studio/assets/{jinja-DqSGkgE4.js → jinja-D06CyNkk.js} +1 -1
  37. package/dist/studio/assets/{jison-CwQ0BO-q.js → jison-CQo2g2q_.js} +1 -1
  38. package/dist/studio/assets/{json-Je3YfUTE.js → json-T8-gmbyP.js} +1 -1
  39. package/dist/studio/assets/{jsx-Da-dLbW1.js → jsx-pi8aEi7y.js} +1 -1
  40. package/dist/studio/assets/{julia-CBJ0H-0z.js → julia-DQ0CkLQi.js} +1 -1
  41. package/dist/studio/assets/{just-CnuRC_nd.js → just-BaZbjeHH.js} +1 -1
  42. package/dist/studio/assets/{latex-gZANCito.js → latex-CKRYEGLe.js} +1 -1
  43. package/dist/studio/assets/{liquid-0U9aXoFI.js → liquid-KfgQvxVp.js} +1 -1
  44. package/dist/studio/assets/{lua-CX_TqMxt.js → lua-BDYsw9Eb.js} +1 -1
  45. package/dist/studio/assets/{marko-StSURz0o.js → marko-BSPq2tuh.js} +1 -1
  46. package/dist/studio/assets/{mdc-CXZpf9k1.js → mdc-ZTdTy2-Y.js} +1 -1
  47. package/dist/studio/assets/mermaid-GHXKKRXX-UMXpy7w5.js +1 -0
  48. package/dist/studio/assets/{nginx-3Q2L4366.js → nginx-BsBsElo9.js} +1 -1
  49. package/dist/studio/assets/{nim-CqX_5eXP.js → nim-Fud12WJN.js} +1 -1
  50. package/dist/studio/assets/{perl-CLOu1GnZ.js → perl-BcRrrqpJ.js} +1 -1
  51. package/dist/studio/assets/{php-C1vkiu4h.js → php-CvBMy7ll.js} +1 -1
  52. package/dist/studio/assets/{pug-Cg3cFp5y.js → pug-9fn0F-sp.js} +1 -1
  53. package/dist/studio/assets/{qml-DhKeHMwt.js → qml-DPYDKGeG.js} +1 -1
  54. package/dist/studio/assets/{r--Lg2-Sir.js → r-B-BlSOk_.js} +1 -1
  55. package/dist/studio/assets/{razor-Cjptf146.js → razor-BBsuDNIH.js} +1 -1
  56. package/dist/studio/assets/{regexp-fS0DAwei.js → regexp-siAWelih.js} +1 -1
  57. package/dist/studio/assets/{rst-BBajBzk-.js → rst-DpBCyEwj.js} +1 -1
  58. package/dist/studio/assets/{ruby-KvFedogM.js → ruby-BQ1xX5ej.js} +1 -1
  59. package/dist/studio/assets/{sas-D6p27LWr.js → sas-Dft5mTiQ.js} +1 -1
  60. package/dist/studio/assets/{scss-6jXfJVsd.js → scss-BFMJsYGZ.js} +1 -1
  61. package/dist/studio/assets/{shellscript-BK0Qbt1B.js → shellscript-Cncrs_5T.js} +1 -1
  62. package/dist/studio/assets/{shellsession-BsXmVRU4.js → shellsession-BngbHbQf.js} +1 -1
  63. package/dist/studio/assets/{soy-BKtGCXkJ.js → soy-BY5W-W7z.js} +1 -1
  64. package/dist/studio/assets/{sql-vSUKslBj.js → sql-rEN1gzdE.js} +1 -1
  65. package/dist/studio/assets/{stata-BQ0iXcs9.js → stata-BDRzO3gs.js} +1 -1
  66. package/dist/studio/assets/{surrealql-v5pXHIwP.js → surrealql-DgF3SPLS.js} +1 -1
  67. package/dist/studio/assets/{svelte-BMFjqgJb.js → svelte-BsPFEf_A.js} +1 -1
  68. package/dist/studio/assets/{templ-DYMTOmIJ.js → templ-D4eIDjcz.js} +1 -1
  69. package/dist/studio/assets/{tex-BoQem9gj.js → tex-hl_BDesm.js} +1 -1
  70. package/dist/studio/assets/{ts-tags-Kp2pAlsd.js → ts-tags-mYERLvfx.js} +1 -1
  71. package/dist/studio/assets/{tsx-DaB2J5uo.js → tsx-4zmdohFv.js} +1 -1
  72. package/dist/studio/assets/{twig-DohCGJPH.js → twig-J6ElH33g.js} +1 -1
  73. package/dist/studio/assets/{typescript-BGG-5I-T.js → typescript-DaBxXTXh.js} +1 -1
  74. package/dist/studio/assets/{vue-CCDLUl9R.js → vue-CnJAvLlE.js} +1 -1
  75. package/dist/studio/assets/{vue-html-et9GYlaF.js → vue-html-5M7J-A2F.js} +1 -1
  76. package/dist/studio/assets/{vue-vine-C561z6bx.js → vue-vine-BgG3D4Fz.js} +1 -1
  77. package/dist/studio/assets/{xml-CJBA1ZPm.js → xml-BuA8iyrb.js} +1 -1
  78. package/dist/studio/assets/{xsl-De-lf9XG.js → xsl-CEhAy4QP.js} +1 -1
  79. package/dist/studio/assets/{yaml-BcMKxf75.js → yaml-CKMEvlUE.js} +1 -1
  80. package/dist/studio/index.html +1 -1
  81. package/dist/think.d.ts +1 -1
  82. package/dist/think.js +340 -181
  83. package/dist/think.js.map +1 -1
  84. package/dist/workflows.d.ts +1 -1
  85. package/docs/index.md +16 -0
  86. package/docs/tools.md +19 -2
  87. package/package.json +6 -6
  88. package/dist/studio/assets/mermaid-GHXKKRXX-CqDQH2-r.js +0 -1
package/dist/think.js CHANGED
@@ -4,7 +4,8 @@ import { createFetchTools } from "./tools/fetch.js";
4
4
  import { truncatePausedExecutionOutput } from "./tools/execute.js";
5
5
  import { t as ThinkMessengerRuntime } from "./chat-sdk-iuBa-CGM.js";
6
6
  import { AsyncLocalStorage } from "node:async_hooks";
7
- import { convertToModelMessages, hasToolCall, jsonSchema, stepCountIs, streamText, tool } from "ai";
7
+ import { convertToModelMessages, hasToolCall, jsonSchema, stepCountIs, streamText, tool, wrapLanguageModel } from "ai";
8
+ import { wrapAISDK } from "agents/observability/ai";
8
9
  import { createWorkersAI } from "workers-ai-provider";
9
10
  import { anthropic } from "workers-ai-provider/anthropic";
10
11
  import { openai } from "workers-ai-provider/openai";
@@ -224,7 +225,7 @@ function resolveChannels(configured, messengers) {
224
225
  * Configuration overrides:
225
226
  * - getModel() — return a model id string (resolved via the
226
227
  * built-in workers-ai-provider) or a LanguageModel
227
- * - getSystemPrompt() — return the system prompt (fallback when no context blocks)
228
+ * - getSystemPrompt() — return the legacy fallback system prompt
228
229
  * - getTools() — return the ToolSet for the agentic loop
229
230
  * - maxSteps — max tool-call rounds per turn (default: 10)
230
231
  * - configureSession() — add context blocks, compaction, search, skills
@@ -317,6 +318,9 @@ const ACTION_PENDING_SWEEP_INTERVAL_MS = 3600 * 1e3;
317
318
  const ACTION_PENDING_LAST_SWEPT_KEY = "cf_think_action_pending_approvals:last_swept_at";
318
319
  /** Prefix for durable-pause action execution ids (vs codemode execution ids). */
319
320
  const ACTION_PAUSE_ID_PREFIX = "actpause_";
321
+ function withAgentSpan(host, operation, storagePhase, attributes, run) {
322
+ return host._withAgentSpan(operation, storagePhase, attributes, run);
323
+ }
320
324
  const MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;
321
325
  const MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;
322
326
  const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
@@ -738,6 +742,7 @@ function isAction(value) {
738
742
  return typeof value === "object" && value !== null && value[ACTION_BRAND] === true;
739
743
  }
740
744
  const admittedTurnContext = new AsyncLocalStorage();
745
+ const inferenceStreamFinalizers = /* @__PURE__ */ new WeakMap();
741
746
  const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
742
747
  /**
743
748
  * Message-metadata keys that are server-written turn context (stamped by
@@ -847,7 +852,10 @@ var Think = class Think extends Agent {
847
852
  }
848
853
  constructor(ctx, env) {
849
854
  super(ctx, env);
855
+ this.includeMcpTools = true;
850
856
  this.waitForMcpConnections = false;
857
+ this.storeMessages = false;
858
+ this.storeTools = false;
851
859
  this._skillRegistry = null;
852
860
  this._loggedSkillWarnings = /* @__PURE__ */ new Set();
853
861
  this._loggedProtocolWarnings = /* @__PURE__ */ new Set();
@@ -931,54 +939,67 @@ var Think = class Think extends Agent {
931
939
  this._streamProgressCredit = new StreamProgressCreditThrottle();
932
940
  this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
933
941
  const _onStart = this.onStart.bind(this);
934
- this.onStart = async () => {
935
- if (!this.workspace) this.workspace = new Workspace$1({
936
- sql: this.ctx.storage.sql,
937
- name: () => this.name
938
- });
939
- const baseSession = Session$1.create(this);
940
- this.session = await this.configureSession(baseSession);
941
- this.session.internal_onMessagesChanged(async (event) => {
942
- switch (event.type) {
943
- case "append":
944
- if (!event.inserted || event.parentId !== void 0) await this._syncMessages();
945
- else this._upsertCachedMessage(event.message);
946
- this._scheduleMediaEvictionAfterAppend(event.message);
947
- break;
948
- case "update":
949
- this._patchCachedMessage(event.message);
950
- break;
951
- case "clear":
952
- this._replaceCachedMessages([]);
953
- break;
954
- case "delete":
955
- case "compact":
956
- await this._syncMessages();
957
- break;
958
- }
942
+ const startThink = async (props, update) => {
943
+ await withAgentSpan(this, "initialize_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
944
+ if (!this.workspace) this.workspace = new Workspace$1({
945
+ sql: this.ctx.storage.sql,
946
+ name: () => this.name
947
+ });
948
+ const baseSession = Session$1.create(this);
949
+ this.session = await this.configureSession(baseSession);
950
+ this.session.internal_onMessagesChanged(async (event) => {
951
+ switch (event.type) {
952
+ case "append":
953
+ if (!event.inserted || event.parentId !== void 0) await this._syncMessages();
954
+ else this._upsertCachedMessage(event.message);
955
+ this._scheduleMediaEvictionAfterAppend(event.message);
956
+ break;
957
+ case "update":
958
+ this._patchCachedMessage(event.message);
959
+ break;
960
+ case "clear":
961
+ this._replaceCachedMessages([]);
962
+ break;
963
+ case "delete":
964
+ case "compact":
965
+ await this._syncMessages();
966
+ break;
967
+ }
968
+ });
969
+ await this._initializeSkills();
959
970
  });
960
- await this._initializeSkills();
961
971
  this._onStartDegradations = [];
962
- if (!await this._runBestEffortOnStartStep("transcript-hydration", () => this._syncMessages(), "The agent is starting with an empty in-memory message view; persisted history is untouched. If the error is SQLITE_NOMEM, the stored transcript is too large to hydrate (often inline base64 media in tool results) — compact or clear the session to recover.")) this._replaceCachedMessages([]);
963
- this._refreshMediaEvictionSignalFromCache();
964
- if (this.extensionLoader) await this._initializeExtensions();
965
- this._resumableStream = new ResumableStream(this.sql.bind(this));
966
- this._restoreClientTools();
967
- this._restoreBody();
968
- this._setupProtocolHandlers();
969
- await this._initializeChannels();
970
- await _onStart();
971
- await this._runBestEffortOnStartStep("scheduled-task-reconcile", () => this._reconcileDeclaredScheduledTasks(), "Declared scheduled tasks were not reconciled on this wake; the next successful wake will reconcile them.");
972
- await this._runBestEffortOnStartStep("durable-work-recovery", async () => {
972
+ await withAgentSpan(this, "hydrate_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
973
+ if (!await this._runBestEffortOnStartStep("transcript-hydration", () => this._syncMessages(), "The agent is starting with an empty in-memory message view; persisted history is untouched. If the error is SQLITE_NOMEM, the stored transcript is too large to hydrate (often inline base64 media in tool results) — compact or clear the session to recover.")) this._replaceCachedMessages([]);
974
+ this._refreshMediaEvictionSignalFromCache();
975
+ });
976
+ if (this.extensionLoader) await withAgentSpan(this, "initialize_think_extensions", "startup", { "cloudflare.agents.component": "think" }, () => this._initializeExtensions());
977
+ await withAgentSpan(this, "initialize_think_chat", "startup", { "cloudflare.agents.component": "think" }, async () => {
978
+ this._resumableStream = new ResumableStream(this.sql.bind(this));
979
+ this._restoreClientTools();
980
+ this._restoreBody();
981
+ this._setupProtocolHandlers();
982
+ await this._initializeChannels();
983
+ });
984
+ await _onStart(props);
985
+ await withAgentSpan(this, "reconcile_think_schedules", "startup", { "cloudflare.agents.component": "think" }, () => this._runBestEffortOnStartStep("scheduled-task-reconcile", () => this._reconcileDeclaredScheduledTasks(), "Declared scheduled tasks were not reconciled on this wake; the next successful wake will reconcile them."));
986
+ await withAgentSpan(this, "recover_think_durable_work", "startup", { "cloudflare.agents.component": "think" }, () => this._runBestEffortOnStartStep("durable-work-recovery", async () => {
973
987
  await this._sweepActionLedger();
974
988
  await this._sweepActionPendingApprovals();
975
989
  await this._recoverSubmissionsOnStart();
976
990
  this._recoverWorkflowNotifications();
977
- if (this._hasPendingSubmissions()) this._startSubmissionDrain();
991
+ if (this._hasPendingSubmissions()) await this._scheduleSubmissionDrain();
978
992
  if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
979
- }, "Pending submissions / workflow notifications were not recovered on this wake; the next successful wake will recover them.");
993
+ }, "Pending submissions / workflow notifications were not recovered on this wake; the next successful wake will recover them."));
980
994
  if (this._lastHydration?.truncated) this._scheduleMediaEvictionPass({ force: true });
995
+ update({
996
+ "cloudflare.agents.hydration.messages": this._lastHydration?.hydratedMessages,
997
+ "cloudflare.agents.hydration.content_bytes": this._lastHydration?.totalContentBytes,
998
+ "cloudflare.agents.hydration.truncated": this._lastHydration?.truncated,
999
+ "cloudflare.agents.start.degradations": this._onStartDegradations.length
1000
+ });
981
1001
  };
1002
+ this.onStart = (props) => withAgentSpan(this, "think_start", "startup", { "cloudflare.agents.component": "think" }, (update) => startThink(props, update));
982
1003
  }
983
1004
  /**
984
1005
  * Conversation history as Think's live in-memory view.
@@ -1595,8 +1616,10 @@ var Think = class Think extends Agent {
1595
1616
  return model.startsWith("@cf/") ? this._defaultProvider(model, { sessionAffinity: this.sessionAffinity }) : this._defaultProvider(model);
1596
1617
  }
1597
1618
  /**
1598
- * Return the system prompt for the assistant.
1599
- * Used as fallback when no context blocks are configured via `configureSession`.
1619
+ * Return the fallback system prompt for the assistant.
1620
+ * Ignored when Session context blocks are configured. Use
1621
+ * `configureSession().withContext()` for always-on instructions that should
1622
+ * coexist with context blocks or skills.
1600
1623
  */
1601
1624
  getSystemPrompt() {
1602
1625
  return [
@@ -1953,6 +1976,13 @@ var Think = class Think extends Agent {
1953
1976
  try {
1954
1977
  const sources = await this.getSkills();
1955
1978
  if (sources.length === 0) return;
1979
+ if (this.getSystemPrompt !== Think.prototype.getSystemPrompt) {
1980
+ const warning = "getSystemPrompt() is only used as a fallback when no Session context blocks are configured. getSkills() registers a skills context block, so move always-on instructions into configureSession().withContext(...) instead.";
1981
+ if (!this._loggedSkillWarnings.has(warning)) {
1982
+ this._loggedSkillWarnings.add(warning);
1983
+ console.warn(`[think] ${warning}`);
1984
+ }
1985
+ }
1956
1986
  const registry = new SkillRegistry(sources, this.getSkillScriptRunner());
1957
1987
  await registry.load();
1958
1988
  this._logSkillWarnings(registry);
@@ -2423,11 +2453,68 @@ var Think = class Think extends Agent {
2423
2453
  }
2424
2454
  }
2425
2455
  /**
2456
+ * Finalizes the traced inference stream after a drain loop exits: drains the
2457
+ * abandoned tee branch so the operation span closes even on early exits.
2458
+ * Idempotent (the finalizer is removed before it runs); the drain rides
2459
+ * `ctx.waitUntil` so it survives turn completion without blocking it.
2460
+ */
2461
+ _drainInferenceStream(result) {
2462
+ const finalizer = inferenceStreamFinalizers.get(result);
2463
+ inferenceStreamFinalizers.delete(result);
2464
+ if (!finalizer || finalizer.started) return;
2465
+ finalizer.started = true;
2466
+ const completion = finalizer.run();
2467
+ try {
2468
+ this.ctx.waitUntil(completion);
2469
+ } catch {}
2470
+ }
2471
+ /**
2472
+ * Adds default identity and current-turn metadata to the AI SDK telemetry
2473
+ * options. The class identifies the logical agent implementation, the named
2474
+ * instance identifies the agent resource, and the opaque Durable Object id
2475
+ * identifies its one persisted conversation. Caller values override defaults.
2476
+ */
2477
+ _turnTelemetry(base) {
2478
+ const turn = admittedTurnContext.getStore();
2479
+ return {
2480
+ ...base,
2481
+ functionId: base?.functionId ?? this.constructor.name,
2482
+ metadata: {
2483
+ agentId: this.name,
2484
+ conversationId: this.ctx.id.toString(),
2485
+ ...turn?.agent === this ? {
2486
+ "cloudflare.agents.turn.request_id": turn.requestId,
2487
+ "cloudflare.agents.turn.trigger": turn.trigger,
2488
+ "cloudflare.agents.turn.admission": turn.admission,
2489
+ ...turn.channel !== void 0 && { "cloudflare.agents.turn.channel": turn.channel },
2490
+ ...turn.continuation !== void 0 && { "cloudflare.agents.turn.continuation": turn.continuation },
2491
+ ...turn.generation !== void 0 && { "cloudflare.agents.turn.generation": turn.generation }
2492
+ } : {},
2493
+ ...base?.metadata
2494
+ }
2495
+ };
2496
+ }
2497
+ /**
2426
2498
  * The single convergence point for all chat turn entry paths.
2427
2499
  * Merges tools, assembles context, fires lifecycle hooks, wraps tools
2428
2500
  * for interception, and calls streamText.
2429
2501
  */
2430
2502
  async _runInferenceLoop(input) {
2503
+ const turn = admittedTurnContext.getStore();
2504
+ return (await withAgentSpan(this, "prepare_agent", "turn", {
2505
+ "cloudflare.agents.component": "think",
2506
+ ...turn?.agent === this ? {
2507
+ "cloudflare.agents.turn.request_id": turn.requestId,
2508
+ "cloudflare.agents.turn.trigger": turn.trigger,
2509
+ "cloudflare.agents.turn.admission": turn.admission,
2510
+ "cloudflare.agents.turn.channel": turn.channel,
2511
+ "cloudflare.agents.turn.continuation": turn.continuation,
2512
+ "cloudflare.agents.turn.generation": turn.generation
2513
+ } : {}
2514
+ }, () => this._prepareInferenceInvocation(input)))();
2515
+ }
2516
+ async _prepareInferenceInvocation(input) {
2517
+ const includeMcpTools = this.includeMcpTools;
2431
2518
  this._activeStallTimeoutMs = void 0;
2432
2519
  this._activeTurnAuthorization = { allowed: true };
2433
2520
  this._activeTurnApprovedActionInputs = this._approvedActionInputsFromTranscript();
@@ -2459,7 +2546,7 @@ var Think = class Think extends Agent {
2459
2546
  ...extensionTools,
2460
2547
  ...contextTools,
2461
2548
  ...skillTools,
2462
- ...this.mcp?.getAITools?.() ?? {},
2549
+ ...includeMcpTools ? this.mcp?.getAITools?.() ?? {} : {},
2463
2550
  ...clientToolSet
2464
2551
  };
2465
2552
  const channelContext = this._activeChannelContext;
@@ -2531,98 +2618,114 @@ var Think = class Think extends Agent {
2531
2618
  ...wantsStructuredOutput ? [hasToolCall(finalAnswerToolName)] : [],
2532
2619
  ...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []
2533
2620
  ];
2534
- const result = streamText({
2535
- model: finalModel,
2536
- system: turnSystem,
2537
- messages: finalMessages,
2538
- tools: finalTools,
2539
- activeTools: wantsStructuredOutput && config.activeTools ? [...config.activeTools, finalAnswerToolName] : config.activeTools,
2540
- toolChoice: finalToolChoice,
2541
- maxOutputTokens: config.maxOutputTokens,
2542
- temperature: config.temperature,
2543
- topP: config.topP,
2544
- topK: config.topK,
2545
- presencePenalty: config.presencePenalty,
2546
- frequencyPenalty: config.frequencyPenalty,
2547
- stopSequences: config.stopSequences,
2548
- seed: config.seed,
2549
- maxRetries: config.maxRetries,
2550
- timeout: config.timeout,
2551
- headers: config.headers,
2552
- stopWhen: finalStopWhen,
2553
- providerOptions: config.providerOptions,
2554
- experimental_telemetry: config.experimental_telemetry,
2555
- experimental_transform: config.experimental_transform,
2556
- output: finalOutput,
2557
- abortSignal: input.signal,
2558
- prepareStep: (async (event) => {
2559
- const guarded = await this._maybeProactiveContextCompact(event);
2560
- const result = await this.beforeStep(event);
2561
- const base = result == null ? {} : result;
2562
- const baseMessages = base.messages;
2563
- const withMessages = guarded && baseMessages === void 0 ? {
2564
- ...base,
2565
- messages: guarded
2566
- } : base;
2567
- const stepResult = wantsStructuredOutput && event.stepNumber >= finalMaxSteps - 1 && withMessages.toolChoice === void 0 ? {
2568
- ...withMessages,
2569
- toolChoice: {
2570
- type: "tool",
2571
- toolName: finalAnswerToolName
2572
- },
2573
- activeTools: [finalAnswerToolName]
2574
- } : withMessages;
2575
- const stepModel = stepResult.model;
2576
- if (typeof stepModel === "string") return {
2577
- ...stepResult,
2578
- model: this.resolveModel(stepModel)
2579
- };
2580
- return stepResult;
2581
- }),
2582
- onChunk: async (event) => {
2583
- await this.onChunk(event);
2584
- await this._pipelineExtensionChunk(event);
2585
- },
2586
- onStepFinish: async (event) => {
2587
- await this.onStepFinish(event);
2588
- await this._pipelineExtensionStepFinish(event);
2589
- },
2590
- experimental_onToolCallFinish: (async (event) => {
2591
- if (event.toolCall.toolName === finalAnswerToolName) return;
2592
- const base = {
2593
- ...event.toolCall,
2594
- stepNumber: event.stepNumber,
2595
- messages: event.messages,
2596
- durationMs: event.durationMs
2597
- };
2598
- const ctx = event.success ? {
2599
- ...base,
2600
- success: true,
2601
- output: event.output
2602
- } : {
2603
- ...base,
2604
- success: false,
2605
- error: event.error
2606
- };
2607
- await this.afterToolCall(ctx);
2608
- await this._pipelineExtensionToolCallFinish(event);
2609
- })
2610
- });
2611
- const outputPromise = wantsStructuredOutput ? Promise.resolve(result.toolCalls).then((calls) => {
2612
- const finalCalls = calls.filter((call) => call.toolName === finalAnswerToolName);
2613
- const last = finalCalls[finalCalls.length - 1];
2614
- if (!last) throw new Error(`Model ended the turn without calling the ${finalAnswerToolName} tool`);
2615
- return last.input;
2616
- }) : finalOutput && result.output ? Promise.resolve(result.output) : void 0;
2617
- if (outputPromise) outputPromise.catch(() => {});
2618
- const streamResult = {
2619
- toUIMessageStream: (options) => result.toUIMessageStream({
2620
- sendReasoning: options?.sendReasoning ?? finalSendReasoning,
2621
- onError: options?.onError ?? streamErrorToString
2622
- }),
2623
- output: outputPromise
2621
+ const tracedStreamText = wrapAISDK({
2622
+ streamText,
2623
+ wrapLanguageModel
2624
+ }, {
2625
+ storeMessages: this.storeMessages,
2626
+ storeTools: this.storeTools
2627
+ }).streamText;
2628
+ return () => {
2629
+ const result = tracedStreamText({
2630
+ model: finalModel,
2631
+ system: turnSystem,
2632
+ messages: finalMessages,
2633
+ tools: finalTools,
2634
+ activeTools: wantsStructuredOutput && config.activeTools ? [...config.activeTools, finalAnswerToolName] : config.activeTools,
2635
+ toolChoice: finalToolChoice,
2636
+ maxOutputTokens: config.maxOutputTokens,
2637
+ temperature: config.temperature,
2638
+ topP: config.topP,
2639
+ topK: config.topK,
2640
+ presencePenalty: config.presencePenalty,
2641
+ frequencyPenalty: config.frequencyPenalty,
2642
+ stopSequences: config.stopSequences,
2643
+ seed: config.seed,
2644
+ maxRetries: config.maxRetries,
2645
+ timeout: config.timeout,
2646
+ headers: config.headers,
2647
+ stopWhen: finalStopWhen,
2648
+ providerOptions: config.providerOptions,
2649
+ experimental_telemetry: this._turnTelemetry(config.experimental_telemetry),
2650
+ experimental_transform: config.experimental_transform,
2651
+ output: finalOutput,
2652
+ abortSignal: input.signal,
2653
+ prepareStep: (async (event) => {
2654
+ const guarded = await this._maybeProactiveContextCompact(event);
2655
+ const result = await this.beforeStep(event);
2656
+ const base = result == null ? {} : result;
2657
+ const baseMessages = base.messages;
2658
+ const withMessages = guarded && baseMessages === void 0 ? {
2659
+ ...base,
2660
+ messages: guarded
2661
+ } : base;
2662
+ const stepResult = wantsStructuredOutput && event.stepNumber >= finalMaxSteps - 1 && withMessages.toolChoice === void 0 ? {
2663
+ ...withMessages,
2664
+ toolChoice: {
2665
+ type: "tool",
2666
+ toolName: finalAnswerToolName
2667
+ },
2668
+ activeTools: [finalAnswerToolName]
2669
+ } : withMessages;
2670
+ const stepModel = stepResult.model;
2671
+ if (typeof stepModel === "string") return {
2672
+ ...stepResult,
2673
+ model: this.resolveModel(stepModel)
2674
+ };
2675
+ return stepResult;
2676
+ }),
2677
+ onChunk: async (event) => {
2678
+ await this.onChunk(event);
2679
+ await this._pipelineExtensionChunk(event);
2680
+ },
2681
+ onStepFinish: async (event) => {
2682
+ await this.onStepFinish(event);
2683
+ await this._pipelineExtensionStepFinish(event);
2684
+ },
2685
+ experimental_onToolCallFinish: (async (event) => {
2686
+ if (event.toolCall.toolName === finalAnswerToolName) return;
2687
+ const base = {
2688
+ ...event.toolCall,
2689
+ stepNumber: event.stepNumber,
2690
+ messages: event.messages,
2691
+ durationMs: event.durationMs
2692
+ };
2693
+ const ctx = event.success ? {
2694
+ ...base,
2695
+ success: true,
2696
+ output: event.output
2697
+ } : {
2698
+ ...base,
2699
+ success: false,
2700
+ error: event.error
2701
+ };
2702
+ await this.afterToolCall(ctx);
2703
+ await this._pipelineExtensionToolCallFinish(event);
2704
+ })
2705
+ });
2706
+ const outputPromise = wantsStructuredOutput ? Promise.resolve(result.toolCalls).then((calls) => {
2707
+ const finalCalls = calls.filter((call) => call.toolName === finalAnswerToolName);
2708
+ const last = finalCalls[finalCalls.length - 1];
2709
+ if (!last) throw new Error(`Model ended the turn without calling the ${finalAnswerToolName} tool`);
2710
+ return last.input;
2711
+ }) : finalOutput && result.output ? Promise.resolve(result.output) : void 0;
2712
+ if (outputPromise) outputPromise.catch(() => {});
2713
+ const streamResult = {
2714
+ toUIMessageStream: (options) => result.toUIMessageStream({
2715
+ sendReasoning: options?.sendReasoning ?? finalSendReasoning,
2716
+ onError: options?.onError ?? streamErrorToString
2717
+ }),
2718
+ output: outputPromise
2719
+ };
2720
+ const finalizer = {
2721
+ started: false,
2722
+ run: () => Promise.resolve(result.consumeStream({ onError: () => {} }))
2723
+ };
2724
+ inferenceStreamFinalizers.set(streamResult, finalizer);
2725
+ const finalized = this._transformInferenceResult(streamResult);
2726
+ if (finalized !== streamResult) inferenceStreamFinalizers.set(finalized, finalizer);
2727
+ return finalized;
2624
2728
  };
2625
- return this._transformInferenceResult(streamResult);
2626
2729
  }
2627
2730
  /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
2628
2731
  _transformInferenceResult(result) {
@@ -3291,7 +3394,17 @@ var Think = class Think extends Agent {
3291
3394
  return { messageCount: this.messages.length };
3292
3395
  }
3293
3396
  async _admitTurn(spec) {
3294
- if (spec.admission !== "queue") return this._withChannelContext(spec.channel, () => spec.execute());
3397
+ if (spec.admission !== "queue") return withAgentSpan(this, "chat_submission", "submission", {
3398
+ "cloudflare.agents.component": "think",
3399
+ "cloudflare.agents.turn.trigger": spec.trigger,
3400
+ "cloudflare.agents.turn.admission": spec.admission,
3401
+ "cloudflare.agents.turn.channel": spec.channel
3402
+ }, () => withAgentSpan(this, spec.admission === "submit" ? "accept_chat_submission" : "execute_chat_submission", "submission", {
3403
+ "cloudflare.agents.component": "think",
3404
+ "cloudflare.agents.turn.trigger": spec.trigger,
3405
+ "cloudflare.agents.turn.admission": spec.admission,
3406
+ "cloudflare.agents.turn.channel": spec.channel
3407
+ }, () => this._withChannelContext(spec.channel, () => spec.execute())));
3295
3408
  if (!spec.allowNested) this._assertNotInsideAdmittedTurn(spec.trigger);
3296
3409
  return this.keepAliveWhile(async () => {
3297
3410
  const turnPromise = this._turnQueue.enqueue(spec.requestId, () => this._runInsideAdmittedTurnBody(spec), spec.generation === void 0 ? void 0 : { generation: spec.generation });
@@ -3304,9 +3417,22 @@ var Think = class Think extends Agent {
3304
3417
  throw new Error(`Think turn admission (${trigger}) cannot be called from inside an active turn; use runTurn({ mode: "submit" }) or addMessages() instead`);
3305
3418
  }
3306
3419
  async _runInsideAdmittedTurnBody(spec) {
3307
- return admittedTurnContext.run({
3420
+ return withAgentSpan(this, "chat_turn", "turn", {
3421
+ "cloudflare.agents.component": "think",
3422
+ "cloudflare.agents.turn.request_id": spec.requestId,
3423
+ "cloudflare.agents.turn.trigger": spec.trigger,
3424
+ "cloudflare.agents.turn.admission": spec.admission,
3425
+ "cloudflare.agents.turn.channel": spec.channel,
3426
+ "cloudflare.agents.turn.continuation": spec.continuation,
3427
+ "cloudflare.agents.turn.generation": spec.generation
3428
+ }, (update) => admittedTurnContext.run({
3308
3429
  agent: this,
3309
- requestId: spec.requestId
3430
+ requestId: spec.requestId,
3431
+ trigger: spec.trigger,
3432
+ admission: spec.admission,
3433
+ channel: spec.channel,
3434
+ continuation: spec.continuation,
3435
+ generation: spec.generation
3310
3436
  }, async () => {
3311
3437
  const startedAt = Date.now();
3312
3438
  this._emit("chat:turn:start", {
@@ -3320,15 +3446,17 @@ var Think = class Think extends Agent {
3320
3446
  this._activeTurnReplyAttachmentsRequestId = spec.requestId;
3321
3447
  try {
3322
3448
  const value = await this._withChannelContext(spec.channel, () => spec.execute());
3449
+ const status = spec.getStatus?.() ?? "completed";
3323
3450
  this._emit("chat:turn:finish", {
3324
3451
  requestId: spec.requestId,
3325
3452
  trigger: spec.trigger,
3326
3453
  admission: spec.admission,
3327
3454
  ...spec.continuation !== void 0 && { continuation: spec.continuation },
3328
3455
  ...spec.generation !== void 0 && { generation: spec.generation },
3329
- status: spec.getStatus?.() ?? "completed",
3456
+ status,
3330
3457
  durationMs: Date.now() - startedAt
3331
3458
  });
3459
+ update({ "cloudflare.agents.turn.status": status });
3332
3460
  return value;
3333
3461
  } catch (error) {
3334
3462
  const message = error instanceof Error ? error.message : String(error);
@@ -3342,9 +3470,10 @@ var Think = class Think extends Agent {
3342
3470
  durationMs: Date.now() - startedAt,
3343
3471
  error: message
3344
3472
  });
3473
+ update({ "cloudflare.agents.turn.status": "error" });
3345
3474
  throw error;
3346
3475
  }
3347
- });
3476
+ }));
3348
3477
  }
3349
3478
  /**
3350
3479
  * Run a chat turn: persist the user message, run the agentic loop,
@@ -5181,10 +5310,7 @@ var Think = class Think extends Agent {
5181
5310
  if (existingById && options?.idempotencyKey && existingById.idempotency_key !== null && existingById.idempotency_key !== options.idempotencyKey) throw new Error("submissionId and idempotencyKey refer to different submissions");
5182
5311
  const existing = existingById ?? existingByKey;
5183
5312
  if (existing) {
5184
- if (existing.status === "pending") {
5185
- await this._scheduleSubmissionDrain();
5186
- this._startSubmissionDrain();
5187
- }
5313
+ if (existing.status === "pending") await this._scheduleSubmissionDrain();
5188
5314
  return {
5189
5315
  ...this._inspectionFromSubmissionRow(existing),
5190
5316
  accepted: false
@@ -5216,7 +5342,6 @@ var Think = class Think extends Agent {
5216
5342
  });
5217
5343
  await this._emitSubmissionStatus(row);
5218
5344
  await this._scheduleSubmissionDrain();
5219
- this._startSubmissionDrain();
5220
5345
  return {
5221
5346
  ...this._inspectionFromSubmissionRow(row),
5222
5347
  accepted: true
@@ -5227,11 +5352,6 @@ var Think = class Think extends Agent {
5227
5352
  async _scheduleSubmissionDrain() {
5228
5353
  await this.schedule(0, "_drainThinkSubmissions", void 0, { idempotent: true });
5229
5354
  }
5230
- _startSubmissionDrain() {
5231
- this.keepAliveWhile(() => this._drainSubmissions()).catch((error) => {
5232
- console.error("[Think] Failed to drain submissions", error);
5233
- });
5234
- }
5235
5355
  _hasPendingSubmissions() {
5236
5356
  this._ensureSubmissionTable();
5237
5357
  return this.sql`
@@ -5869,7 +5989,11 @@ var Think = class Think extends Agent {
5869
5989
  if (typeof message === "string") {
5870
5990
  const event = parseProtocolMessage(message);
5871
5991
  if (event) {
5872
- await this._handleProtocolEvent(connection, event);
5992
+ if (event.type === "chat-request") await withAgentSpan(this, "chat_interaction", "interaction", {
5993
+ "cloudflare.agents.component": "think",
5994
+ "cloudflare.agents.turn.request_id": event.id
5995
+ }, () => this._handleProtocolEvent(connection, event));
5996
+ else await this._handleProtocolEvent(connection, event);
5873
5997
  return;
5874
5998
  }
5875
5999
  }
@@ -5887,7 +6011,7 @@ var Think = class Think extends Agent {
5887
6011
  async _handleProtocolEvent(connection, event) {
5888
6012
  switch (event.type) {
5889
6013
  case "stream-resume-request":
5890
- await this._handleStreamResumeRequest(connection);
6014
+ await this._handleStreamResumeRequest(connection, event.probeId);
5891
6015
  break;
5892
6016
  case "stream-resume-ack":
5893
6017
  await this._handleStreamResumeAck(connection, event.id);
@@ -5923,8 +6047,8 @@ var Think = class Think extends Agent {
5923
6047
  break;
5924
6048
  }
5925
6049
  }
5926
- async _handleStreamResumeRequest(connection) {
5927
- await this._resumeHandshake().handleResumeRequest(connection);
6050
+ async _handleStreamResumeRequest(connection, probeId) {
6051
+ await this._resumeHandshake().handleResumeRequest(connection, probeId);
5928
6052
  }
5929
6053
  async _handleStreamResumeAck(connection, requestId) {
5930
6054
  await this._resumeHandshake().handleResumeAck(connection, requestId);
@@ -5961,7 +6085,11 @@ var Think = class Think extends Agent {
5961
6085
  this._completeSkippedRequest(connection, requestId);
5962
6086
  return;
5963
6087
  }
5964
- await this._clearChatTerminal();
6088
+ await withAgentSpan(this, "clear_previous_chat_state", "interaction", {
6089
+ "cloudflare.agents.component": "think",
6090
+ "cloudflare.agents.turn.request_id": requestId,
6091
+ "cloudflare.agents.turn.trigger": "ws-chat"
6092
+ }, () => this._clearChatTerminal());
5965
6093
  this._preStream.begin(requestId);
5966
6094
  const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
5967
6095
  let pendingEnqueue = true;
@@ -5973,38 +6101,49 @@ var Think = class Think extends Agent {
5973
6101
  };
5974
6102
  try {
5975
6103
  const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
5976
- if (requestClientTools) {
5977
- this._lastClientTools = requestClientTools;
5978
- this._persistClientTools();
5979
- } else if (rawClientTools !== void 0) {
5980
- this._lastClientTools = void 0;
5981
- this._persistClientTools();
5982
- }
5983
6104
  const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
5984
- this._lastBody = requestBody;
5985
- this._persistBody();
6105
+ withAgentSpan(this, "persist_chat_request_context", "interaction", {
6106
+ "cloudflare.agents.component": "think",
6107
+ "cloudflare.agents.turn.request_id": requestId,
6108
+ "cloudflare.agents.turn.trigger": "ws-chat"
6109
+ }, () => {
6110
+ if (requestClientTools) {
6111
+ this._lastClientTools = requestClientTools;
6112
+ this._persistClientTools();
6113
+ } else if (rawClientTools !== void 0) {
6114
+ this._lastClientTools = void 0;
6115
+ this._persistClientTools();
6116
+ }
6117
+ this._lastBody = requestBody;
6118
+ this._persistBody();
6119
+ });
5986
6120
  const clientToolsForTurn = this._lastClientTools;
5987
6121
  const bodyForTurn = this._lastBody;
5988
- const serverMessages = await this._readMessagesFromStorage();
6122
+ const serverMessages = await withAgentSpan(this, "load_chat_history", "interaction", {
6123
+ "cloudflare.agents.component": "think",
6124
+ "cloudflare.agents.turn.request_id": requestId,
6125
+ "cloudflare.agents.turn.trigger": "ws-chat"
6126
+ }, () => this._readMessagesFromStorage());
5989
6127
  const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
5990
6128
  let branchParentId;
5991
6129
  if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
5992
- if (this._turnQueue.generation !== epoch) {
5993
- this._completeSkippedRequest(connection, requestId);
5994
- return;
5995
- }
5996
- for (const msg of reconciled) {
5997
- if (this._turnQueue.generation !== epoch) {
5998
- this._completeSkippedRequest(connection, requestId);
5999
- return;
6130
+ if (!await withAgentSpan(this, "persist_incoming_messages", "interaction", {
6131
+ "cloudflare.agents.component": "think",
6132
+ "cloudflare.agents.turn.request_id": requestId,
6133
+ "cloudflare.agents.turn.trigger": "ws-chat"
6134
+ }, async () => {
6135
+ if (this._turnQueue.generation !== epoch) return false;
6136
+ for (const msg of reconciled) {
6137
+ if (this._turnQueue.generation !== epoch) return false;
6138
+ await this._persistIncomingMessage(msg, serverMessages);
6000
6139
  }
6001
- await this._persistIncomingMessage(msg, serverMessages);
6002
- }
6003
- if (this._turnQueue.generation !== epoch) {
6140
+ if (this._turnQueue.generation !== epoch) return false;
6141
+ await this._syncMessages();
6142
+ return true;
6143
+ })) {
6004
6144
  this._completeSkippedRequest(connection, requestId);
6005
6145
  return;
6006
6146
  }
6007
- await this._syncMessages();
6008
6147
  this._broadcastMessages([connection.id]);
6009
6148
  messagesPersisted = true;
6010
6149
  failureStage = "turn";
@@ -6061,16 +6200,30 @@ var Think = class Think extends Agent {
6061
6200
  overflowRequested = true;
6062
6201
  overflowError = error;
6063
6202
  } } : void 0;
6064
- await this._streamResult(requestId, result, abortSignal, {
6203
+ await withAgentSpan(this, "persist_chat_result", "turn", {
6204
+ "cloudflare.agents.component": "think",
6205
+ "cloudflare.agents.turn.request_id": requestId,
6206
+ "cloudflare.agents.turn.trigger": "ws-chat",
6207
+ "cloudflare.agents.turn.admission": "queue",
6208
+ "cloudflare.agents.turn.generation": epoch,
6209
+ "cloudflare.agents.turn.continuation": false
6210
+ }, () => this._streamResult(requestId, result, abortSignal, {
6065
6211
  parentId: branchParentId,
6066
6212
  overflowRecovery
6067
- });
6213
+ }));
6068
6214
  if (overflowRequested) {
6069
6215
  if (attempt < this._overflowMaxRetries && !abortSignal?.aborted) {
6070
- if (await this._compactForContextOverflow("reactive", {
6216
+ if (await withAgentSpan(this, "compact_chat_history", "turn", {
6217
+ "cloudflare.agents.component": "think",
6218
+ "cloudflare.agents.turn.request_id": requestId,
6219
+ "cloudflare.agents.turn.trigger": "ws-chat",
6220
+ "cloudflare.agents.turn.admission": "queue",
6221
+ "cloudflare.agents.turn.generation": epoch,
6222
+ "cloudflare.agents.turn.continuation": false
6223
+ }, () => this._compactForContextOverflow("reactive", {
6071
6224
  requestId,
6072
6225
  attempt: attempt + 1
6073
- })) continue;
6226
+ }))) continue;
6074
6227
  }
6075
6228
  const message = this._finalizeContextOverflowError(requestId, overflowError);
6076
6229
  this._broadcastChat({
@@ -6348,6 +6501,7 @@ var Think = class Think extends Agent {
6348
6501
  let skipFinalizeRearm = false;
6349
6502
  let overflowRetry = false;
6350
6503
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
6504
+ let streamDrainedNaturally = false;
6351
6505
  try {
6352
6506
  this._insideInferenceLoop = true;
6353
6507
  const flushState = {
@@ -6404,8 +6558,10 @@ var Think = class Think extends Agent {
6404
6558
  });
6405
6559
  await callback.onEvent(chunkBody);
6406
6560
  }
6561
+ streamDrainedNaturally = !(aborted || overflowRetry || streamError !== void 0);
6407
6562
  } finally {
6408
6563
  this._insideInferenceLoop = false;
6564
+ if (!streamDrainedNaturally) this._drainInferenceStream(result);
6409
6565
  }
6410
6566
  if (overflowRetry) {
6411
6567
  this._completeResumableStream(streamId);
@@ -6602,6 +6758,7 @@ var Think = class Think extends Agent {
6602
6758
  };
6603
6759
  const pendingActionCalls = /* @__PURE__ */ new Map();
6604
6760
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
6761
+ let streamDrainedNaturally = false;
6605
6762
  try {
6606
6763
  this._insideInferenceLoop = true;
6607
6764
  try {
@@ -6656,8 +6813,10 @@ var Think = class Think extends Agent {
6656
6813
  ...continuation && { continuation: true }
6657
6814
  });
6658
6815
  }
6816
+ streamDrainedNaturally = !(streamAborted || overflowRetry || streamError !== void 0);
6659
6817
  } finally {
6660
6818
  this._insideInferenceLoop = false;
6819
+ if (!streamDrainedNaturally) this._drainInferenceStream(result);
6661
6820
  }
6662
6821
  if (overflowRetry && options?.overflowRecovery) {
6663
6822
  this._completeResumableStream(streamId);