@cloudflare/think 0.12.1 → 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 (94) hide show
  1. package/README.md +29 -14
  2. package/dist/{chat-sdk-Dm0R3pdR.js → chat-sdk-iuBa-CGM.js} +39 -7
  3. package/dist/chat-sdk-iuBa-CGM.js.map +1 -0
  4. package/dist/{index-WF0HQmkk.d.ts → index-CDNxUctz.d.ts} +254 -142
  5. package/dist/messengers/index.d.ts +44 -38
  6. package/dist/messengers/index.js +2 -2
  7. package/dist/messengers/telegram.d.ts +2 -2
  8. package/dist/messengers/telegram.js +1 -1
  9. package/dist/studio/assets/{angular-html--XgCyfPu.js → angular-html-Dl5doFtz.js} +1 -1
  10. package/dist/studio/assets/{angular-ts-Dt-feQIe.js → angular-ts-CbN7_mlY.js} +1 -1
  11. package/dist/studio/assets/{apl-B7ymkyp4.js → apl-CUTyCKtR.js} +1 -1
  12. package/dist/studio/assets/{astro-Ce5cw2JI.js → astro-4sWs7Jg3.js} +1 -1
  13. package/dist/studio/assets/{blade-DL-aXwjv.js → blade-NmhW_pJp.js} +1 -1
  14. package/dist/studio/assets/{c-CFfr09UF.js → c-_ropPcoN.js} +1 -1
  15. package/dist/studio/assets/{cobol-Ba1f5ZqR.js → cobol-BacpIX4U.js} +1 -1
  16. package/dist/studio/assets/{coffee-BG2_viYI.js → coffee-DcwgCl9J.js} +1 -1
  17. package/dist/studio/assets/{cpp-pU5HgBva.js → cpp-BCPbrI0m.js} +1 -1
  18. package/dist/studio/assets/{crystal-Dlm_uR4r.js → crystal-DZXQ6wBH.js} +1 -1
  19. package/dist/studio/assets/{css-tUC4TMTn.js → css-BYyCaTYR.js} +1 -1
  20. package/dist/studio/assets/{edge-CQuSKMUt.js → edge-CVh9HJt8.js} +1 -1
  21. package/dist/studio/assets/{elixir-BmIB-Wi1.js → elixir-9uvyi7ZY.js} +1 -1
  22. package/dist/studio/assets/{elm-ByVNCtDB.js → elm-DDSgRIyn.js} +1 -1
  23. package/dist/studio/assets/{erb-DO4uDxTq.js → erb-DAVyz0cP.js} +1 -1
  24. package/dist/studio/assets/{git-rebase-CT8LXapC.js → git-rebase-z3txLW9w.js} +1 -1
  25. package/dist/studio/assets/{glimmer-js-DzIT0v-m.js → glimmer-js-BRADiKXN.js} +1 -1
  26. package/dist/studio/assets/{glimmer-ts-znG2j9R4.js → glimmer-ts-B6C6vVGo.js} +1 -1
  27. package/dist/studio/assets/{glsl-C1p8U_gW.js → glsl-34bCtA9U.js} +1 -1
  28. package/dist/studio/assets/{graphql-CFqegryf.js → graphql-CL83z2DV.js} +1 -1
  29. package/dist/studio/assets/{hack-BfVsNhqs.js → hack-B9WxPQav.js} +1 -1
  30. package/dist/studio/assets/{haml-DVcEksY5.js → haml-oavex6g4.js} +1 -1
  31. package/dist/studio/assets/{handlebars-DSWgWCJ4.js → handlebars-pd64xhEq.js} +1 -1
  32. package/dist/studio/assets/{highlighted-body-OFNGDK62-BIm4UpTS.js → highlighted-body-OFNGDK62-DB3-I0_d.js} +1 -1
  33. package/dist/studio/assets/{html-C-lP7-T4.js → html-A_mALprL.js} +1 -1
  34. package/dist/studio/assets/{html-derivative-ByukJopb.js → html-derivative-CBwZyoIR.js} +1 -1
  35. package/dist/studio/assets/{http-Bax2fYIk.js → http-Cua_-o-V.js} +1 -1
  36. package/dist/studio/assets/{hurl-BrI2qfvy.js → hurl-Dpr8mC4K.js} +1 -1
  37. package/dist/studio/assets/{index-DNSTOyBe.js → index-DmVgVRjr.js} +86 -86
  38. package/dist/studio/assets/{java-ZiR-uym-.js → java-B1Ptmnmm.js} +1 -1
  39. package/dist/studio/assets/{javascript-Dhhw85Vr.js → javascript-waNlhfIS.js} +1 -1
  40. package/dist/studio/assets/{jinja-DqSGkgE4.js → jinja-D06CyNkk.js} +1 -1
  41. package/dist/studio/assets/{jison-CwQ0BO-q.js → jison-CQo2g2q_.js} +1 -1
  42. package/dist/studio/assets/{json-Je3YfUTE.js → json-T8-gmbyP.js} +1 -1
  43. package/dist/studio/assets/{jsx-Da-dLbW1.js → jsx-pi8aEi7y.js} +1 -1
  44. package/dist/studio/assets/{julia-CBJ0H-0z.js → julia-DQ0CkLQi.js} +1 -1
  45. package/dist/studio/assets/{just-CnuRC_nd.js → just-BaZbjeHH.js} +1 -1
  46. package/dist/studio/assets/{latex-gZANCito.js → latex-CKRYEGLe.js} +1 -1
  47. package/dist/studio/assets/{liquid-0U9aXoFI.js → liquid-KfgQvxVp.js} +1 -1
  48. package/dist/studio/assets/{lua-CX_TqMxt.js → lua-BDYsw9Eb.js} +1 -1
  49. package/dist/studio/assets/{marko-StSURz0o.js → marko-BSPq2tuh.js} +1 -1
  50. package/dist/studio/assets/{mdc-CXZpf9k1.js → mdc-ZTdTy2-Y.js} +1 -1
  51. package/dist/studio/assets/mermaid-GHXKKRXX-UMXpy7w5.js +1 -0
  52. package/dist/studio/assets/{nginx-3Q2L4366.js → nginx-BsBsElo9.js} +1 -1
  53. package/dist/studio/assets/{nim-CqX_5eXP.js → nim-Fud12WJN.js} +1 -1
  54. package/dist/studio/assets/{perl-CLOu1GnZ.js → perl-BcRrrqpJ.js} +1 -1
  55. package/dist/studio/assets/{php-C1vkiu4h.js → php-CvBMy7ll.js} +1 -1
  56. package/dist/studio/assets/{pug-Cg3cFp5y.js → pug-9fn0F-sp.js} +1 -1
  57. package/dist/studio/assets/{qml-DhKeHMwt.js → qml-DPYDKGeG.js} +1 -1
  58. package/dist/studio/assets/{r--Lg2-Sir.js → r-B-BlSOk_.js} +1 -1
  59. package/dist/studio/assets/{razor-Cjptf146.js → razor-BBsuDNIH.js} +1 -1
  60. package/dist/studio/assets/{regexp-fS0DAwei.js → regexp-siAWelih.js} +1 -1
  61. package/dist/studio/assets/{rst-BBajBzk-.js → rst-DpBCyEwj.js} +1 -1
  62. package/dist/studio/assets/{ruby-KvFedogM.js → ruby-BQ1xX5ej.js} +1 -1
  63. package/dist/studio/assets/{sas-D6p27LWr.js → sas-Dft5mTiQ.js} +1 -1
  64. package/dist/studio/assets/{scss-6jXfJVsd.js → scss-BFMJsYGZ.js} +1 -1
  65. package/dist/studio/assets/{shellscript-BK0Qbt1B.js → shellscript-Cncrs_5T.js} +1 -1
  66. package/dist/studio/assets/{shellsession-BsXmVRU4.js → shellsession-BngbHbQf.js} +1 -1
  67. package/dist/studio/assets/{soy-BKtGCXkJ.js → soy-BY5W-W7z.js} +1 -1
  68. package/dist/studio/assets/{sql-vSUKslBj.js → sql-rEN1gzdE.js} +1 -1
  69. package/dist/studio/assets/{stata-BQ0iXcs9.js → stata-BDRzO3gs.js} +1 -1
  70. package/dist/studio/assets/{surrealql-v5pXHIwP.js → surrealql-DgF3SPLS.js} +1 -1
  71. package/dist/studio/assets/{svelte-BMFjqgJb.js → svelte-BsPFEf_A.js} +1 -1
  72. package/dist/studio/assets/{templ-DYMTOmIJ.js → templ-D4eIDjcz.js} +1 -1
  73. package/dist/studio/assets/{tex-BoQem9gj.js → tex-hl_BDesm.js} +1 -1
  74. package/dist/studio/assets/{ts-tags-Kp2pAlsd.js → ts-tags-mYERLvfx.js} +1 -1
  75. package/dist/studio/assets/{tsx-DaB2J5uo.js → tsx-4zmdohFv.js} +1 -1
  76. package/dist/studio/assets/{twig-DohCGJPH.js → twig-J6ElH33g.js} +1 -1
  77. package/dist/studio/assets/{typescript-BGG-5I-T.js → typescript-DaBxXTXh.js} +1 -1
  78. package/dist/studio/assets/{vue-CCDLUl9R.js → vue-CnJAvLlE.js} +1 -1
  79. package/dist/studio/assets/{vue-html-et9GYlaF.js → vue-html-5M7J-A2F.js} +1 -1
  80. package/dist/studio/assets/{vue-vine-C561z6bx.js → vue-vine-BgG3D4Fz.js} +1 -1
  81. package/dist/studio/assets/{xml-CJBA1ZPm.js → xml-BuA8iyrb.js} +1 -1
  82. package/dist/studio/assets/{xsl-De-lf9XG.js → xsl-CEhAy4QP.js} +1 -1
  83. package/dist/studio/assets/{yaml-BcMKxf75.js → yaml-CKMEvlUE.js} +1 -1
  84. package/dist/studio/index.html +1 -1
  85. package/dist/think.d.ts +1 -1
  86. package/dist/think.js +396 -195
  87. package/dist/think.js.map +1 -1
  88. package/dist/workflows.d.ts +1 -1
  89. package/docs/index.md +16 -0
  90. package/docs/messengers.md +52 -0
  91. package/docs/tools.md +19 -2
  92. package/package.json +6 -6
  93. package/dist/chat-sdk-Dm0R3pdR.js.map +0 -1
  94. package/dist/studio/assets/mermaid-GHXKKRXX-CqDQH2-r.js +0 -1
package/dist/think.js CHANGED
@@ -2,9 +2,10 @@ import { a as _classPrivateFieldSet2, i as _classPrivateFieldGet2, n as sanitize
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
3
  import { createFetchTools } from "./tools/fetch.js";
4
4
  import { truncatePausedExecutionOutput } from "./tools/execute.js";
5
- import { t as ThinkMessengerRuntime } from "./chat-sdk-Dm0R3pdR.js";
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,8 +742,15 @@ 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
  /**
748
+ * Message-metadata keys that are server-written turn context (stamped by
749
+ * `_stampChannel`) and trusted by hooks and recovery. They are stripped from
750
+ * client-supplied messages at intake so a client can never forge them.
751
+ */
752
+ const RESERVED_MESSAGE_METADATA_KEYS = ["channel", "turnMetadata"];
753
+ /**
743
754
  * Reserved name for the synthetic tool a workflow `step.prompt` turn uses to
744
755
  * deliver its structured final answer. The agent runs a full multi-step,
745
756
  * tool-using turn and ends it by calling this tool with arguments matching the
@@ -841,7 +852,10 @@ var Think = class Think extends Agent {
841
852
  }
842
853
  constructor(ctx, env) {
843
854
  super(ctx, env);
855
+ this.includeMcpTools = true;
844
856
  this.waitForMcpConnections = false;
857
+ this.storeMessages = false;
858
+ this.storeTools = false;
845
859
  this._skillRegistry = null;
846
860
  this._loggedSkillWarnings = /* @__PURE__ */ new Set();
847
861
  this._loggedProtocolWarnings = /* @__PURE__ */ new Set();
@@ -925,54 +939,67 @@ var Think = class Think extends Agent {
925
939
  this._streamProgressCredit = new StreamProgressCreditThrottle();
926
940
  this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
927
941
  const _onStart = this.onStart.bind(this);
928
- this.onStart = async () => {
929
- if (!this.workspace) this.workspace = new Workspace$1({
930
- sql: this.ctx.storage.sql,
931
- name: () => this.name
932
- });
933
- const baseSession = Session$1.create(this);
934
- this.session = await this.configureSession(baseSession);
935
- this.session.internal_onMessagesChanged(async (event) => {
936
- switch (event.type) {
937
- case "append":
938
- if (!event.inserted || event.parentId !== void 0) await this._syncMessages();
939
- else this._upsertCachedMessage(event.message);
940
- this._scheduleMediaEvictionAfterAppend(event.message);
941
- break;
942
- case "update":
943
- this._patchCachedMessage(event.message);
944
- break;
945
- case "clear":
946
- this._replaceCachedMessages([]);
947
- break;
948
- case "delete":
949
- case "compact":
950
- await this._syncMessages();
951
- break;
952
- }
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();
953
970
  });
954
- await this._initializeSkills();
955
971
  this._onStartDegradations = [];
956
- 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([]);
957
- this._refreshMediaEvictionSignalFromCache();
958
- if (this.extensionLoader) await this._initializeExtensions();
959
- this._resumableStream = new ResumableStream(this.sql.bind(this));
960
- this._restoreClientTools();
961
- this._restoreBody();
962
- this._setupProtocolHandlers();
963
- await this._initializeChannels();
964
- await _onStart();
965
- await this._runBestEffortOnStartStep("scheduled-task-reconcile", () => this._reconcileDeclaredScheduledTasks(), "Declared scheduled tasks were not reconciled on this wake; the next successful wake will reconcile them.");
966
- 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 () => {
967
987
  await this._sweepActionLedger();
968
988
  await this._sweepActionPendingApprovals();
969
989
  await this._recoverSubmissionsOnStart();
970
990
  this._recoverWorkflowNotifications();
971
- if (this._hasPendingSubmissions()) this._startSubmissionDrain();
991
+ if (this._hasPendingSubmissions()) await this._scheduleSubmissionDrain();
972
992
  if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
973
- }, "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."));
974
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
+ });
975
1001
  };
1002
+ this.onStart = (props) => withAgentSpan(this, "think_start", "startup", { "cloudflare.agents.component": "think" }, (update) => startThink(props, update));
976
1003
  }
977
1004
  /**
978
1005
  * Conversation history as Think's live in-memory view.
@@ -1589,8 +1616,10 @@ var Think = class Think extends Agent {
1589
1616
  return model.startsWith("@cf/") ? this._defaultProvider(model, { sessionAffinity: this.sessionAffinity }) : this._defaultProvider(model);
1590
1617
  }
1591
1618
  /**
1592
- * Return the system prompt for the assistant.
1593
- * 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.
1594
1623
  */
1595
1624
  getSystemPrompt() {
1596
1625
  return [
@@ -1660,6 +1689,16 @@ var Think = class Think extends Agent {
1660
1689
  get activeChannel() {
1661
1690
  return this._activeChannelContext;
1662
1691
  }
1692
+ /**
1693
+ * The server-supplied metadata stamped on the active turn's user message
1694
+ * ({@link ChatOptions.metadata}). Like the channel stamp, it is persisted on
1695
+ * the durable user message, so recovered/continued turns re-resolve the same
1696
+ * value; client-supplied message metadata can never populate it (reserved
1697
+ * keys are stripped at intake). `undefined` when the turn carried none.
1698
+ */
1699
+ get activeTurnMetadata() {
1700
+ return this._turnMetadataFromMessages(this.messages);
1701
+ }
1663
1702
  /** Resolve a channel id to a turn-scoped {@link ChannelContext}, if registered. */
1664
1703
  _resolveChannelContext(channel) {
1665
1704
  if (!channel) return;
@@ -1700,29 +1739,38 @@ var Think = class Think extends Agent {
1700
1739
  }
1701
1740
  }
1702
1741
  /**
1703
- * Stamp the channel id onto user messages so a recovered/continued turn can
1704
- * re-resolve the channel from durable history.
1742
+ * Stamp the channel id — and, when supplied, the caller's turn metadata —
1743
+ * onto user messages so a recovered/continued turn can re-resolve both from
1744
+ * durable history.
1705
1745
  */
1706
- _stampChannel(messages, channel) {
1707
- if (!channel) return messages;
1746
+ _stampChannel(messages, channel, turnMetadata) {
1747
+ if (!channel && !turnMetadata) return messages;
1708
1748
  return messages.map((message) => message.role === "user" ? {
1709
1749
  ...message,
1710
1750
  metadata: {
1711
1751
  ...message.metadata,
1712
- channel
1752
+ ...channel ? { channel } : {},
1753
+ ...turnMetadata ? { turnMetadata } : {}
1713
1754
  }
1714
1755
  } : message);
1715
1756
  }
1716
- /** The channel stamped on the latest user message in the given list, if any. */
1717
- _channelFromMessages(messages) {
1757
+ /** Metadata of the latest user message in the given list, if any. */
1758
+ _latestUserMessageMetadata(messages) {
1718
1759
  for (let i = messages.length - 1; i >= 0; i--) {
1719
1760
  const message = messages[i];
1720
- if (message.role === "user") {
1721
- const channel = message.metadata?.channel;
1722
- return typeof channel === "string" ? channel : void 0;
1723
- }
1761
+ if (message.role === "user") return message.metadata;
1724
1762
  }
1725
1763
  }
1764
+ /** The channel stamped on the latest user message in the given list, if any. */
1765
+ _channelFromMessages(messages) {
1766
+ const channel = this._latestUserMessageMetadata(messages)?.channel;
1767
+ return typeof channel === "string" ? channel : void 0;
1768
+ }
1769
+ /** The turn metadata stamped on the latest user message, if any. */
1770
+ _turnMetadataFromMessages(messages) {
1771
+ const turnMetadata = this._latestUserMessageMetadata(messages)?.turnMetadata;
1772
+ return turnMetadata && typeof turnMetadata === "object" && !Array.isArray(turnMetadata) ? turnMetadata : void 0;
1773
+ }
1726
1774
  /** Re-resolve the channel for a continuation from the latest user message. */
1727
1775
  _channelFromLatestUserMessage() {
1728
1776
  return this._channelFromMessages(this.messages);
@@ -1928,6 +1976,13 @@ var Think = class Think extends Agent {
1928
1976
  try {
1929
1977
  const sources = await this.getSkills();
1930
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
+ }
1931
1986
  const registry = new SkillRegistry(sources, this.getSkillScriptRunner());
1932
1987
  await registry.load();
1933
1988
  this._logSkillWarnings(registry);
@@ -2398,11 +2453,68 @@ var Think = class Think extends Agent {
2398
2453
  }
2399
2454
  }
2400
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
+ /**
2401
2498
  * The single convergence point for all chat turn entry paths.
2402
2499
  * Merges tools, assembles context, fires lifecycle hooks, wraps tools
2403
2500
  * for interception, and calls streamText.
2404
2501
  */
2405
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;
2406
2518
  this._activeStallTimeoutMs = void 0;
2407
2519
  this._activeTurnAuthorization = { allowed: true };
2408
2520
  this._activeTurnApprovedActionInputs = this._approvedActionInputsFromTranscript();
@@ -2434,7 +2546,7 @@ var Think = class Think extends Agent {
2434
2546
  ...extensionTools,
2435
2547
  ...contextTools,
2436
2548
  ...skillTools,
2437
- ...this.mcp?.getAITools?.() ?? {},
2549
+ ...includeMcpTools ? this.mcp?.getAITools?.() ?? {} : {},
2438
2550
  ...clientToolSet
2439
2551
  };
2440
2552
  const channelContext = this._activeChannelContext;
@@ -2506,98 +2618,114 @@ var Think = class Think extends Agent {
2506
2618
  ...wantsStructuredOutput ? [hasToolCall(finalAnswerToolName)] : [],
2507
2619
  ...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []
2508
2620
  ];
2509
- const result = streamText({
2510
- model: finalModel,
2511
- system: turnSystem,
2512
- messages: finalMessages,
2513
- tools: finalTools,
2514
- activeTools: wantsStructuredOutput && config.activeTools ? [...config.activeTools, finalAnswerToolName] : config.activeTools,
2515
- toolChoice: finalToolChoice,
2516
- maxOutputTokens: config.maxOutputTokens,
2517
- temperature: config.temperature,
2518
- topP: config.topP,
2519
- topK: config.topK,
2520
- presencePenalty: config.presencePenalty,
2521
- frequencyPenalty: config.frequencyPenalty,
2522
- stopSequences: config.stopSequences,
2523
- seed: config.seed,
2524
- maxRetries: config.maxRetries,
2525
- timeout: config.timeout,
2526
- headers: config.headers,
2527
- stopWhen: finalStopWhen,
2528
- providerOptions: config.providerOptions,
2529
- experimental_telemetry: config.experimental_telemetry,
2530
- experimental_transform: config.experimental_transform,
2531
- output: finalOutput,
2532
- abortSignal: input.signal,
2533
- prepareStep: (async (event) => {
2534
- const guarded = await this._maybeProactiveContextCompact(event);
2535
- const result = await this.beforeStep(event);
2536
- const base = result == null ? {} : result;
2537
- const baseMessages = base.messages;
2538
- const withMessages = guarded && baseMessages === void 0 ? {
2539
- ...base,
2540
- messages: guarded
2541
- } : base;
2542
- const stepResult = wantsStructuredOutput && event.stepNumber >= finalMaxSteps - 1 && withMessages.toolChoice === void 0 ? {
2543
- ...withMessages,
2544
- toolChoice: {
2545
- type: "tool",
2546
- toolName: finalAnswerToolName
2547
- },
2548
- activeTools: [finalAnswerToolName]
2549
- } : withMessages;
2550
- const stepModel = stepResult.model;
2551
- if (typeof stepModel === "string") return {
2552
- ...stepResult,
2553
- model: this.resolveModel(stepModel)
2554
- };
2555
- return stepResult;
2556
- }),
2557
- onChunk: async (event) => {
2558
- await this.onChunk(event);
2559
- await this._pipelineExtensionChunk(event);
2560
- },
2561
- onStepFinish: async (event) => {
2562
- await this.onStepFinish(event);
2563
- await this._pipelineExtensionStepFinish(event);
2564
- },
2565
- experimental_onToolCallFinish: (async (event) => {
2566
- if (event.toolCall.toolName === finalAnswerToolName) return;
2567
- const base = {
2568
- ...event.toolCall,
2569
- stepNumber: event.stepNumber,
2570
- messages: event.messages,
2571
- durationMs: event.durationMs
2572
- };
2573
- const ctx = event.success ? {
2574
- ...base,
2575
- success: true,
2576
- output: event.output
2577
- } : {
2578
- ...base,
2579
- success: false,
2580
- error: event.error
2581
- };
2582
- await this.afterToolCall(ctx);
2583
- await this._pipelineExtensionToolCallFinish(event);
2584
- })
2585
- });
2586
- const outputPromise = wantsStructuredOutput ? Promise.resolve(result.toolCalls).then((calls) => {
2587
- const finalCalls = calls.filter((call) => call.toolName === finalAnswerToolName);
2588
- const last = finalCalls[finalCalls.length - 1];
2589
- if (!last) throw new Error(`Model ended the turn without calling the ${finalAnswerToolName} tool`);
2590
- return last.input;
2591
- }) : finalOutput && result.output ? Promise.resolve(result.output) : void 0;
2592
- if (outputPromise) outputPromise.catch(() => {});
2593
- const streamResult = {
2594
- toUIMessageStream: (options) => result.toUIMessageStream({
2595
- sendReasoning: options?.sendReasoning ?? finalSendReasoning,
2596
- onError: options?.onError ?? streamErrorToString
2597
- }),
2598
- 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;
2599
2728
  };
2600
- return this._transformInferenceResult(streamResult);
2601
2729
  }
2602
2730
  /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
2603
2731
  _transformInferenceResult(result) {
@@ -3266,7 +3394,17 @@ var Think = class Think extends Agent {
3266
3394
  return { messageCount: this.messages.length };
3267
3395
  }
3268
3396
  async _admitTurn(spec) {
3269
- 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())));
3270
3408
  if (!spec.allowNested) this._assertNotInsideAdmittedTurn(spec.trigger);
3271
3409
  return this.keepAliveWhile(async () => {
3272
3410
  const turnPromise = this._turnQueue.enqueue(spec.requestId, () => this._runInsideAdmittedTurnBody(spec), spec.generation === void 0 ? void 0 : { generation: spec.generation });
@@ -3279,9 +3417,22 @@ var Think = class Think extends Agent {
3279
3417
  throw new Error(`Think turn admission (${trigger}) cannot be called from inside an active turn; use runTurn({ mode: "submit" }) or addMessages() instead`);
3280
3418
  }
3281
3419
  async _runInsideAdmittedTurnBody(spec) {
3282
- 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({
3283
3429
  agent: this,
3284
- 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
3285
3436
  }, async () => {
3286
3437
  const startedAt = Date.now();
3287
3438
  this._emit("chat:turn:start", {
@@ -3295,15 +3446,17 @@ var Think = class Think extends Agent {
3295
3446
  this._activeTurnReplyAttachmentsRequestId = spec.requestId;
3296
3447
  try {
3297
3448
  const value = await this._withChannelContext(spec.channel, () => spec.execute());
3449
+ const status = spec.getStatus?.() ?? "completed";
3298
3450
  this._emit("chat:turn:finish", {
3299
3451
  requestId: spec.requestId,
3300
3452
  trigger: spec.trigger,
3301
3453
  admission: spec.admission,
3302
3454
  ...spec.continuation !== void 0 && { continuation: spec.continuation },
3303
3455
  ...spec.generation !== void 0 && { generation: spec.generation },
3304
- status: spec.getStatus?.() ?? "completed",
3456
+ status,
3305
3457
  durationMs: Date.now() - startedAt
3306
3458
  });
3459
+ update({ "cloudflare.agents.turn.status": status });
3307
3460
  return value;
3308
3461
  } catch (error) {
3309
3462
  const message = error instanceof Error ? error.message : String(error);
@@ -3317,9 +3470,10 @@ var Think = class Think extends Agent {
3317
3470
  durationMs: Date.now() - startedAt,
3318
3471
  error: message
3319
3472
  });
3473
+ update({ "cloudflare.agents.turn.status": "error" });
3320
3474
  throw error;
3321
3475
  }
3322
- });
3476
+ }));
3323
3477
  }
3324
3478
  /**
3325
3479
  * Run a chat turn: persist the user message, run the agentic loop,
@@ -3349,7 +3503,7 @@ var Think = class Think extends Agent {
3349
3503
  channel: options?.channel,
3350
3504
  execute: async () => {
3351
3505
  const resolved = typeof userMessage === "function" ? await userMessage(this.messages) : this._normalizeChatMessages(userMessage);
3352
- for (const msg of this._stampChannel(resolved, options?.channel)) await this._appendMessageToHistory(msg);
3506
+ for (const msg of this._stampChannel(resolved, options?.channel, options?.metadata)) await this._appendMessageToHistory(msg);
3353
3507
  this._broadcastMessages();
3354
3508
  const chatBody = async () => {
3355
3509
  for (let attempt = 0;; attempt++) {
@@ -5156,10 +5310,7 @@ var Think = class Think extends Agent {
5156
5310
  if (existingById && options?.idempotencyKey && existingById.idempotency_key !== null && existingById.idempotency_key !== options.idempotencyKey) throw new Error("submissionId and idempotencyKey refer to different submissions");
5157
5311
  const existing = existingById ?? existingByKey;
5158
5312
  if (existing) {
5159
- if (existing.status === "pending") {
5160
- await this._scheduleSubmissionDrain();
5161
- this._startSubmissionDrain();
5162
- }
5313
+ if (existing.status === "pending") await this._scheduleSubmissionDrain();
5163
5314
  return {
5164
5315
  ...this._inspectionFromSubmissionRow(existing),
5165
5316
  accepted: false
@@ -5191,7 +5342,6 @@ var Think = class Think extends Agent {
5191
5342
  });
5192
5343
  await this._emitSubmissionStatus(row);
5193
5344
  await this._scheduleSubmissionDrain();
5194
- this._startSubmissionDrain();
5195
5345
  return {
5196
5346
  ...this._inspectionFromSubmissionRow(row),
5197
5347
  accepted: true
@@ -5202,11 +5352,6 @@ var Think = class Think extends Agent {
5202
5352
  async _scheduleSubmissionDrain() {
5203
5353
  await this.schedule(0, "_drainThinkSubmissions", void 0, { idempotent: true });
5204
5354
  }
5205
- _startSubmissionDrain() {
5206
- this.keepAliveWhile(() => this._drainSubmissions()).catch((error) => {
5207
- console.error("[Think] Failed to drain submissions", error);
5208
- });
5209
- }
5210
5355
  _hasPendingSubmissions() {
5211
5356
  this._ensureSubmissionTable();
5212
5357
  return this.sql`
@@ -5844,7 +5989,11 @@ var Think = class Think extends Agent {
5844
5989
  if (typeof message === "string") {
5845
5990
  const event = parseProtocolMessage(message);
5846
5991
  if (event) {
5847
- 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);
5848
5997
  return;
5849
5998
  }
5850
5999
  }
@@ -5862,7 +6011,7 @@ var Think = class Think extends Agent {
5862
6011
  async _handleProtocolEvent(connection, event) {
5863
6012
  switch (event.type) {
5864
6013
  case "stream-resume-request":
5865
- await this._handleStreamResumeRequest(connection);
6014
+ await this._handleStreamResumeRequest(connection, event.probeId);
5866
6015
  break;
5867
6016
  case "stream-resume-ack":
5868
6017
  await this._handleStreamResumeAck(connection, event.id);
@@ -5898,8 +6047,8 @@ var Think = class Think extends Agent {
5898
6047
  break;
5899
6048
  }
5900
6049
  }
5901
- async _handleStreamResumeRequest(connection) {
5902
- await this._resumeHandshake().handleResumeRequest(connection);
6050
+ async _handleStreamResumeRequest(connection, probeId) {
6051
+ await this._resumeHandshake().handleResumeRequest(connection, probeId);
5903
6052
  }
5904
6053
  async _handleStreamResumeAck(connection, requestId) {
5905
6054
  await this._resumeHandshake().handleResumeAck(connection, requestId);
@@ -5936,7 +6085,11 @@ var Think = class Think extends Agent {
5936
6085
  this._completeSkippedRequest(connection, requestId);
5937
6086
  return;
5938
6087
  }
5939
- 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());
5940
6093
  this._preStream.begin(requestId);
5941
6094
  const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
5942
6095
  let pendingEnqueue = true;
@@ -5948,38 +6101,49 @@ var Think = class Think extends Agent {
5948
6101
  };
5949
6102
  try {
5950
6103
  const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
5951
- if (requestClientTools) {
5952
- this._lastClientTools = requestClientTools;
5953
- this._persistClientTools();
5954
- } else if (rawClientTools !== void 0) {
5955
- this._lastClientTools = void 0;
5956
- this._persistClientTools();
5957
- }
5958
6104
  const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
5959
- this._lastBody = requestBody;
5960
- 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
+ });
5961
6120
  const clientToolsForTurn = this._lastClientTools;
5962
6121
  const bodyForTurn = this._lastBody;
5963
- 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());
5964
6127
  const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
5965
6128
  let branchParentId;
5966
6129
  if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
5967
- if (this._turnQueue.generation !== epoch) {
5968
- this._completeSkippedRequest(connection, requestId);
5969
- return;
5970
- }
5971
- for (const msg of reconciled) {
5972
- if (this._turnQueue.generation !== epoch) {
5973
- this._completeSkippedRequest(connection, requestId);
5974
- 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);
5975
6139
  }
5976
- await this._persistIncomingMessage(msg, serverMessages);
5977
- }
5978
- if (this._turnQueue.generation !== epoch) {
6140
+ if (this._turnQueue.generation !== epoch) return false;
6141
+ await this._syncMessages();
6142
+ return true;
6143
+ })) {
5979
6144
  this._completeSkippedRequest(connection, requestId);
5980
6145
  return;
5981
6146
  }
5982
- await this._syncMessages();
5983
6147
  this._broadcastMessages([connection.id]);
5984
6148
  messagesPersisted = true;
5985
6149
  failureStage = "turn";
@@ -6036,16 +6200,30 @@ var Think = class Think extends Agent {
6036
6200
  overflowRequested = true;
6037
6201
  overflowError = error;
6038
6202
  } } : void 0;
6039
- 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, {
6040
6211
  parentId: branchParentId,
6041
6212
  overflowRecovery
6042
- });
6213
+ }));
6043
6214
  if (overflowRequested) {
6044
6215
  if (attempt < this._overflowMaxRetries && !abortSignal?.aborted) {
6045
- 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", {
6046
6224
  requestId,
6047
6225
  attempt: attempt + 1
6048
- })) continue;
6226
+ }))) continue;
6049
6227
  }
6050
6228
  const message = this._finalizeContextOverflowError(requestId, overflowError);
6051
6229
  this._broadcastChat({
@@ -6323,6 +6501,7 @@ var Think = class Think extends Agent {
6323
6501
  let skipFinalizeRearm = false;
6324
6502
  let overflowRetry = false;
6325
6503
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
6504
+ let streamDrainedNaturally = false;
6326
6505
  try {
6327
6506
  this._insideInferenceLoop = true;
6328
6507
  const flushState = {
@@ -6379,8 +6558,10 @@ var Think = class Think extends Agent {
6379
6558
  });
6380
6559
  await callback.onEvent(chunkBody);
6381
6560
  }
6561
+ streamDrainedNaturally = !(aborted || overflowRetry || streamError !== void 0);
6382
6562
  } finally {
6383
6563
  this._insideInferenceLoop = false;
6564
+ if (!streamDrainedNaturally) this._drainInferenceStream(result);
6384
6565
  }
6385
6566
  if (overflowRetry) {
6386
6567
  this._completeResumableStream(streamId);
@@ -6577,6 +6758,7 @@ var Think = class Think extends Agent {
6577
6758
  };
6578
6759
  const pendingActionCalls = /* @__PURE__ */ new Map();
6579
6760
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
6761
+ let streamDrainedNaturally = false;
6580
6762
  try {
6581
6763
  this._insideInferenceLoop = true;
6582
6764
  try {
@@ -6631,8 +6813,10 @@ var Think = class Think extends Agent {
6631
6813
  ...continuation && { continuation: true }
6632
6814
  });
6633
6815
  }
6816
+ streamDrainedNaturally = !(streamAborted || overflowRetry || streamError !== void 0);
6634
6817
  } finally {
6635
6818
  this._insideInferenceLoop = false;
6819
+ if (!streamDrainedNaturally) this._drainInferenceStream(result);
6636
6820
  }
6637
6821
  if (overflowRetry && options?.overflowRecovery) {
6638
6822
  this._completeResumableStream(streamId);
@@ -6799,9 +6983,26 @@ var Think = class Think extends Agent {
6799
6983
  * instead of inserting an orphan duplicate.
6800
6984
  */
6801
6985
  async _persistIncomingMessage(msg, serverMessages) {
6802
- const resolved = msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg;
6986
+ const sanitized = this._stripReservedMessageMetadata(msg);
6987
+ const resolved = sanitized.role === "assistant" ? resolveToolMergeId(sanitized, serverMessages) : sanitized;
6803
6988
  await this._upsertMessageInHistory(resolved);
6804
6989
  }
6990
+ /**
6991
+ * Strip {@link RESERVED_MESSAGE_METADATA_KEYS} from a client-supplied message
6992
+ * at intake. Those keys are server-written turn context (stamped by
6993
+ * `_stampChannel`) that hooks and recovery re-resolve and trust, so a client
6994
+ * must never be able to forge them.
6995
+ */
6996
+ _stripReservedMessageMetadata(msg) {
6997
+ const metadata = msg.metadata;
6998
+ if (!metadata || !RESERVED_MESSAGE_METADATA_KEYS.some((key) => key in metadata)) return msg;
6999
+ const rest = { ...metadata };
7000
+ for (const key of RESERVED_MESSAGE_METADATA_KEYS) delete rest[key];
7001
+ return {
7002
+ ...msg,
7003
+ metadata: rest
7004
+ };
7005
+ }
6805
7006
  _persistClientTools() {
6806
7007
  if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
6807
7008
  else this._configDelete("lastClientTools");