@cloudflare/ai-chat 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,55 @@
1
1
  # @cloudflare/ai-chat
2
2
 
3
+ ## 0.1.4
4
+
5
+ ### Patch Changes
6
+
7
+ - [#967](https://github.com/cloudflare/agents/pull/967) [`c128447`](https://github.com/cloudflare/agents/commit/c1284478fe212ddd6e1bc915877cee5c10fcfd49) Thanks [@threepointone](https://github.com/threepointone)! - Follow-up to #956. Allow `addToolOutput` to work with tools in `approval-requested` and `approval-responded` states, not just `input-available`. Also adds support for `state: "output-error"` and `errorText` fields, enabling custom denial messages when rejecting tool approvals (addresses remaining items from #955).
8
+
9
+ Additionally, tool approval rejections (`approved: false`) now auto-continue the conversation when `autoContinue` is set, so the LLM sees the denial and can respond naturally (e.g. suggest alternatives).
10
+
11
+ This enables the Vercel AI SDK recommended pattern for client-side tool denial:
12
+
13
+ ```ts
14
+ addToolOutput({
15
+ toolCallId: invocation.toolCallId,
16
+ state: "output-error",
17
+ errorText: "User declined: insufficient permissions",
18
+ });
19
+ ```
20
+
21
+ - [#958](https://github.com/cloudflare/agents/pull/958) [`f70a8b9`](https://github.com/cloudflare/agents/commit/f70a8b9e2774d729825b8d85152c403d0c1e6dba) Thanks [@whoiskatrin](https://github.com/whoiskatrin)! - Fix duplicate assistant message persistence when clients resend full history with local assistant IDs that differ from server IDs.
22
+
23
+ `AIChatAgent.persistMessages()` now reconciles non-tool assistant messages against existing server history by content and order, reusing the server ID instead of inserting duplicate rows.
24
+
25
+ - [#977](https://github.com/cloudflare/agents/pull/977) [`5426b6f`](https://github.com/cloudflare/agents/commit/5426b6f3a8f394bdbad5e6b5cf22e279249bcdae) Thanks [@dmmulroy](https://github.com/dmmulroy)! - Expose `requestId` in `OnChatMessageOptions` so handlers can send properly-tagged error responses for pre-stream failures.
26
+
27
+ Also fix `saveMessages()` to pass the full options object (`requestId`, `abortSignal`, `clientTools`, `body`) to `onChatMessage` and use a consistent request ID for `_reply`.
28
+
29
+ - [#973](https://github.com/cloudflare/agents/pull/973) [`969fbff`](https://github.com/cloudflare/agents/commit/969fbff702d5702c1f0ea6faaecb3dfd0431a01b) Thanks [@threepointone](https://github.com/threepointone)! - Update dependencies
30
+
31
+ - [#983](https://github.com/cloudflare/agents/pull/983) [`2785f10`](https://github.com/cloudflare/agents/commit/2785f104f187834a0d568ad7db668d961b33707f) Thanks [@threepointone](https://github.com/threepointone)! - Fix abort/cancel support for streaming responses. The framework now properly cancels the reader loop when the abort signal fires and sends a done signal to the client. Added a warning log when cancellation arrives but the stream has not closed (indicating the user forgot to pass `abortSignal` to their LLM call). Also fixed vitest project configs to scope test file discovery and prevent e2e/react tests from being picked up by the wrong runner.
32
+
33
+ - [#979](https://github.com/cloudflare/agents/pull/979) [`23c90ea`](https://github.com/cloudflare/agents/commit/23c90ea4bdd63c03f28c40e1c3594b34ff523bf7) Thanks [@mattzcarey](https://github.com/mattzcarey)! - Fix jsonSchema not initialized error when calling getAITools() in onChatMessage
34
+
35
+ - [#980](https://github.com/cloudflare/agents/pull/980) [`00c576d`](https://github.com/cloudflare/agents/commit/00c576de0ddcbac1ae4496abb14804cfb34e251e) Thanks [@threepointone](https://github.com/threepointone)! - Fix `_sanitizeMessageForPersistence` stripping Anthropic `redacted_thinking` blocks. The sanitizer now strips OpenAI ephemeral metadata first, then filters out only reasoning parts that are truly empty (no text and no remaining `providerMetadata`). This preserves Anthropic's `redacted_thinking` blocks (stored as empty-text reasoning parts with `providerMetadata.anthropic.redactedData`) while still removing OpenAI placeholders. Fixes #978.
36
+
37
+ - [#953](https://github.com/cloudflare/agents/pull/953) [`bd22d60`](https://github.com/cloudflare/agents/commit/bd22d6005fab16d0dc358274dcb12d368a31e076) Thanks [@mattzcarey](https://github.com/mattzcarey)! - Moved `/get-messages` endpoint handling from a prototype `override onRequest()` method to a constructor wrapper. This ensures the endpoint always works, even when users override `onRequest` without calling `super.onRequest()`.
38
+
39
+ - [#956](https://github.com/cloudflare/agents/pull/956) [`ab401a0`](https://github.com/cloudflare/agents/commit/ab401a0e0b6942490e845cc9e34d9f17f65cbde8) Thanks [@whoiskatrin](https://github.com/whoiskatrin)! - Fix denied tool approvals (`CF_AGENT_TOOL_APPROVAL` with `approved: false`) to transition tool parts to `output-denied` instead of `approval-responded`.
40
+
41
+ This ensures `convertToModelMessages` emits a `tool_result` for denied approvals, which is required by providers like Anthropic.
42
+
43
+ Also adds regression tests for denied approval behavior, including rejection from `approval-requested` state.
44
+
45
+ - [#982](https://github.com/cloudflare/agents/pull/982) [`5a851be`](https://github.com/cloudflare/agents/commit/5a851bef389683a13380626c8bed515a6351b172) Thanks [@threepointone](https://github.com/threepointone)! - Undeprecate client tool APIs (`createToolsFromClientSchemas`, `clientTools`, `AITool`, `extractClientToolSchemas`, and the `tools` option on `useAgentChat`) for SDK/platform use cases where tools are defined dynamically at runtime. Fix spurious `detectToolsRequiringConfirmation` deprecation warning when using the `tools` option.
46
+
47
+ ## 0.1.3
48
+
49
+ ### Patch Changes
50
+
51
+ - [#954](https://github.com/cloudflare/agents/pull/954) [`943c407`](https://github.com/cloudflare/agents/commit/943c4070992bb836625abb5bf4e3271a6f52f7a2) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
52
+
3
53
  ## 0.1.2
4
54
 
5
55
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -13,12 +13,16 @@ import { Agent, AgentContext } from "agents";
13
13
  * Schema for a client-defined tool sent from the browser.
14
14
  * These tools are executed on the client, not the server.
15
15
  *
16
- * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema` (FlexibleSchema)
17
- * because this is the wire format. Zod schemas cannot be serialized.
16
+ * **For most apps**, define tools on the server with `tool()` from `"ai"` —
17
+ * you get full Zod type safety, server-side execution, and simpler code.
18
+ * Use `onToolCall` in `useAgentChat` for tools that need client-side execution.
19
+ *
20
+ * **For SDKs and platforms** where the tool surface is determined dynamically
21
+ * by the embedding application at runtime, client tool schemas let the
22
+ * client register tools the server does not know about at deploy time.
18
23
  *
19
- * @deprecated Define tools on the server using `tool()` from "ai" instead.
20
- * For tools that need client-side execution, omit the `execute` function
21
- * and handle them via the `onToolCall` callback in `useAgentChat`.
24
+ * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema`
25
+ * because this is the wire format. Zod schemas cannot be serialized.
22
26
  */
23
27
  type ClientToolSchema = {
24
28
  /** Unique name for the tool */ name: string /** Human-readable description of what the tool does */;
@@ -29,14 +33,27 @@ type ClientToolSchema = {
29
33
  * Options passed to the onChatMessage handler.
30
34
  */
31
35
  type OnChatMessageOptions = {
32
- /** AbortSignal for cancelling the request */ abortSignal?: AbortSignal;
36
+ /**
37
+ * Unique ID for this chat message exchange.
38
+ *
39
+ * For initial user messages this is the client-generated ID from the
40
+ * `CF_AGENT_USE_CHAT_REQUEST` WebSocket frame. For tool continuations
41
+ * (auto-continue after client tool results or approvals) this is a
42
+ * server-generated ID.
43
+ */
44
+ requestId: string /** AbortSignal for cancelling the request */;
45
+ abortSignal?: AbortSignal;
33
46
  /**
34
47
  * Tool schemas sent from the client for dynamic tool registration.
35
48
  * These represent tools that will be executed on the client side.
36
49
  * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
37
50
  *
38
- * @deprecated Define tools on the server instead. Use `onToolCall` callback
39
- * in `useAgentChat` for client-side execution.
51
+ * **For most apps**, you do not need this — define tools on the server with
52
+ * `tool()` from `"ai"` and use `onToolCall` for client-side execution.
53
+ *
54
+ * **For SDKs and platforms** where tools are defined dynamically by the
55
+ * client at runtime and the server does not know the tool surface ahead
56
+ * of time, this field carries the client-provided tool schemas.
40
57
  */
41
58
  clientTools?: ClientToolSchema[];
42
59
  /**
@@ -56,36 +73,24 @@ type OnChatMessageOptions = {
56
73
  /**
57
74
  * Converts client tool schemas to AI SDK tool format.
58
75
  *
59
- * These tools have no `execute` function - when the AI model calls them,
76
+ * These tools have no `execute` function — when the AI model calls them,
60
77
  * the tool call is sent back to the client for execution.
61
78
  *
79
+ * **For most apps**, define tools on the server with `tool()` from `"ai"`
80
+ * for full Zod type safety. This helper is intended for SDK/platform use
81
+ * cases where the tool surface is determined dynamically by the client.
82
+ *
62
83
  * @param clientTools - Array of tool schemas from the client
63
84
  * @returns Record of AI SDK tools that can be spread into your tools object
64
85
  *
65
- * @deprecated Define tools on the server using `tool()` from "ai" instead.
66
- * For tools that need client-side execution, omit the `execute` function
67
- * and handle them via the `onToolCall` callback in `useAgentChat`.
68
- *
69
86
  * @example
70
87
  * ```typescript
71
- * // Server: Define tool without execute
88
+ * // In onChatMessage:
72
89
  * const tools = {
73
- * getLocation: tool({
74
- * description: "Get user's location",
75
- * inputSchema: z.object({})
76
- * // No execute = client must handle
77
- * })
90
+ * ...createToolsFromClientSchemas(options.clientTools),
91
+ * // server-defined tools with execute:
92
+ * myServerTool: tool({ ... }),
78
93
  * };
79
- *
80
- * // Client: Handle in onToolCall
81
- * useAgentChat({
82
- * onToolCall: async ({ toolCall, addToolOutput }) => {
83
- * if (toolCall.toolName === 'getLocation') {
84
- * const pos = await navigator.geolocation.getCurrentPosition();
85
- * addToolOutput({ toolCallId: toolCall.toolCallId, output: pos });
86
- * }
87
- * }
88
- * });
89
94
  * ```
90
95
  */
91
96
  declare function createToolsFromClientSchemas(
@@ -224,7 +229,6 @@ declare class AIChatAgent<
224
229
  */
225
230
  private _broadcastTextEvent;
226
231
  private _loadMessagesFromDb;
227
- onRequest(request: Request): Promise<Response>;
228
232
  private _tryCatchChat;
229
233
  /**
230
234
  * Handle incoming chat messages and generate a response
@@ -254,6 +258,18 @@ declare class AIChatAgent<
254
258
  * @returns Messages with server's tool outputs preserved
255
259
  */
256
260
  private _mergeIncomingWithServerState;
261
+ /**
262
+ * Reconciles assistant message IDs between incoming client state and server state.
263
+ *
264
+ * The client can keep a different local ID for an assistant message than the one
265
+ * persisted on the server (e.g. optimistic/local IDs). When that full history is
266
+ * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
267
+ * this, we reuse the server ID for assistant messages that match by content and
268
+ * order, while leaving tool-call messages to _resolveMessageForToolMerge.
269
+ */
270
+ private _reconcileAssistantIdsWithServerState;
271
+ private _hasToolCallPart;
272
+ private _assistantMessageContentKey;
257
273
  /**
258
274
  * Resolves a message for persistence, handling tool result merging.
259
275
  * If the message contains tool parts with output-available state, checks if there's
@@ -278,16 +294,18 @@ declare class AIChatAgent<
278
294
  * Sanitizes a message for persistence by removing ephemeral provider-specific
279
295
  * data that should not be stored or sent back in subsequent requests.
280
296
  *
281
- * This handles two issues with the OpenAI Responses API:
297
+ * Two-step process:
282
298
  *
283
- * 1. **Duplicate item IDs**: The AI SDK's @ai-sdk/openai provider (v2.0.x+)
284
- * defaults to using OpenAI's Responses API which assigns unique itemIds
285
- * to each message part. When these IDs are persisted and sent back,
286
- * OpenAI rejects them as duplicates.
299
+ * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
300
+ * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
301
+ * itemIds and reasoningEncryptedContent to message parts. When persisted
302
+ * and sent back, OpenAI rejects duplicate itemIds.
287
303
  *
288
- * 2. **Empty reasoning parts**: OpenAI may return reasoning parts with empty
289
- * text and encrypted content. These cause "Non-OpenAI reasoning parts are
290
- * not supported" warnings when sent back via convertToModelMessages().
304
+ * 2. **Filter truly empty reasoning parts**: After stripping, reasoning parts
305
+ * with no text and no remaining providerMetadata are removed. Parts that
306
+ * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
307
+ * with providerMetadata.anthropic.redactedData) are preserved, as they
308
+ * contain data required for round-tripping with the provider API.
291
309
  *
292
310
  * @param message - The message to sanitize
293
311
  * @returns A new message with ephemeral provider data removed
@@ -349,6 +367,8 @@ declare class AIChatAgent<
349
367
  * @param toolCallId - The tool call ID this result is for
350
368
  * @param _toolName - The name of the tool (unused, kept for API compat)
351
369
  * @param output - The output from the tool execution
370
+ * @param overrideState - Optional state override ("output-error" to signal denial/failure)
371
+ * @param errorText - Error message when overrideState is "output-error"
352
372
  * @returns true if the result was applied, false if the message was not found
353
373
  */
354
374
  private _applyToolResult;
@@ -357,7 +377,10 @@ declare class AIChatAgent<
357
377
  /**
358
378
  * Applies a tool approval response from the client, updating the persisted message.
359
379
  * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
360
- * Updates the tool part state from input-available/approval-requested to approval-responded.
380
+ *
381
+ * - approved=true transitions to approval-responded
382
+ * - approved=false transitions to output-denied so convertToModelMessages
383
+ * emits a tool_result for providers (e.g. Anthropic) that require it.
361
384
  *
362
385
  * @param toolCallId - The tool call ID this approval is for
363
386
  * @param approved - Whether the tool execution was approved
package/dist/index.js CHANGED
@@ -312,52 +312,29 @@ function isValidMessageStructure(msg) {
312
312
  return true;
313
313
  }
314
314
  /**
315
- * One-shot deprecation warnings (warns once per key per session).
316
- */
317
- const _deprecationWarnings = /* @__PURE__ */ new Set();
318
- function warnDeprecated(id, message) {
319
- if (!_deprecationWarnings.has(id)) {
320
- _deprecationWarnings.add(id);
321
- console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
322
- }
323
- }
324
- /**
325
315
  * Converts client tool schemas to AI SDK tool format.
326
316
  *
327
- * These tools have no `execute` function - when the AI model calls them,
317
+ * These tools have no `execute` function — when the AI model calls them,
328
318
  * the tool call is sent back to the client for execution.
329
319
  *
320
+ * **For most apps**, define tools on the server with `tool()` from `"ai"`
321
+ * for full Zod type safety. This helper is intended for SDK/platform use
322
+ * cases where the tool surface is determined dynamically by the client.
323
+ *
330
324
  * @param clientTools - Array of tool schemas from the client
331
325
  * @returns Record of AI SDK tools that can be spread into your tools object
332
326
  *
333
- * @deprecated Define tools on the server using `tool()` from "ai" instead.
334
- * For tools that need client-side execution, omit the `execute` function
335
- * and handle them via the `onToolCall` callback in `useAgentChat`.
336
- *
337
327
  * @example
338
328
  * ```typescript
339
- * // Server: Define tool without execute
329
+ * // In onChatMessage:
340
330
  * const tools = {
341
- * getLocation: tool({
342
- * description: "Get user's location",
343
- * inputSchema: z.object({})
344
- * // No execute = client must handle
345
- * })
331
+ * ...createToolsFromClientSchemas(options.clientTools),
332
+ * // server-defined tools with execute:
333
+ * myServerTool: tool({ ... }),
346
334
  * };
347
- *
348
- * // Client: Handle in onToolCall
349
- * useAgentChat({
350
- * onToolCall: async ({ toolCall, addToolOutput }) => {
351
- * if (toolCall.toolName === 'getLocation') {
352
- * const pos = await navigator.geolocation.getCurrentPosition();
353
- * addToolOutput({ toolCallId: toolCall.toolCallId, output: pos });
354
- * }
355
- * }
356
- * });
357
335
  * ```
358
336
  */
359
337
  function createToolsFromClientSchemas(clientTools) {
360
- warnDeprecated("createToolsFromClientSchemas", "createToolsFromClientSchemas() is deprecated. Define tools on the server using tool() from 'ai' and handle client execution via onToolCall in useAgentChat. Will be removed in the next major version.");
361
338
  if (!clientTools || clientTools.length === 0) return {};
362
339
  const seenNames = /* @__PURE__ */ new Set();
363
340
  for (const t of clientTools) {
@@ -416,6 +393,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
416
393
  };
417
394
  const _onMessage = this.onMessage.bind(this);
418
395
  this.onMessage = async (connection, message) => {
396
+ await this.mcp.ensureJsonSchema();
419
397
  if (typeof message === "string") {
420
398
  let data;
421
399
  try {
@@ -463,6 +441,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
463
441
  email: void 0
464
442
  }, async () => {
465
443
  const response = await this.onChatMessage(async (_finishResult) => {}, {
444
+ requestId: chatMessageId,
466
445
  abortSignal,
467
446
  clientTools,
468
447
  body: this._lastBody
@@ -512,12 +491,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
512
491
  return;
513
492
  }
514
493
  if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
515
- const { toolCallId, toolName, output, autoContinue, clientTools } = data;
494
+ const { toolCallId, toolName, output, state, errorText, autoContinue, clientTools } = data;
516
495
  if (clientTools?.length) {
517
496
  this._lastClientTools = clientTools;
518
497
  this._persistRequestContext();
519
498
  }
520
- this._applyToolResult(toolCallId, toolName, output).then((applied) => {
499
+ const overrideState = state === "output-error" ? "output-error" : void 0;
500
+ this._applyToolResult(toolCallId, toolName, output, overrideState, errorText).then((applied) => {
521
501
  if (applied && autoContinue) {
522
502
  const waitForStream = async () => {
523
503
  if (this._streamCompletionPromise) await this._streamCompletionPromise;
@@ -534,6 +514,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
534
514
  email: void 0
535
515
  }, async () => {
536
516
  const response = await this.onChatMessage(async (_finishResult) => {}, {
517
+ requestId: continuationId,
537
518
  abortSignal,
538
519
  clientTools: clientTools ?? this._lastClientTools,
539
520
  body: this._lastBody
@@ -554,7 +535,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
554
535
  if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
555
536
  const { toolCallId, approved, autoContinue } = data;
556
537
  this._applyToolApproval(toolCallId, approved).then((applied) => {
557
- if (applied && approved && autoContinue) {
538
+ if (applied && autoContinue) {
558
539
  const waitForStream = async () => {
559
540
  if (this._streamCompletionPromise) await this._streamCompletionPromise;
560
541
  else await new Promise((resolve) => setTimeout(resolve, 500));
@@ -570,6 +551,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
570
551
  email: void 0
571
552
  }, async () => {
572
553
  const response = await this.onChatMessage(async (_finishResult) => {}, {
554
+ requestId: continuationId,
573
555
  abortSignal,
574
556
  clientTools: this._lastClientTools,
575
557
  body: this._lastBody
@@ -590,6 +572,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
590
572
  }
591
573
  return _onMessage(connection, message);
592
574
  };
575
+ const _onRequest = this.onRequest.bind(this);
576
+ this.onRequest = async (request) => {
577
+ return this._tryCatchChat(async () => {
578
+ if (new URL(request.url).pathname.split("/").pop() === "get-messages") return Response.json(this._loadMessagesFromDb());
579
+ return _onRequest(request);
580
+ });
581
+ };
593
582
  }
594
583
  /**
595
584
  * Notify a connection about an active stream that can be resumed.
@@ -710,15 +699,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
710
699
  }
711
700
  }).filter((msg) => msg !== null);
712
701
  }
713
- async onRequest(request) {
714
- return this._tryCatchChat(async () => {
715
- if (new URL(request.url).pathname.endsWith("/get-messages")) {
716
- const messages = this._loadMessagesFromDb();
717
- return Response.json(messages);
718
- }
719
- return super.onRequest(request);
720
- });
721
- }
722
702
  async _tryCatchChat(fn) {
723
703
  try {
724
704
  return await fn();
@@ -742,8 +722,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
742
722
  async saveMessages(messages) {
743
723
  await this.persistMessages(messages);
744
724
  await this._tryCatchChat(async () => {
745
- const response = await this.onChatMessage(() => {});
746
- if (response) this._reply(crypto.randomUUID(), response);
725
+ const requestId = nanoid();
726
+ const abortSignal = this._getAbortSignal(requestId);
727
+ const response = await this.onChatMessage(() => {}, {
728
+ requestId,
729
+ abortSignal,
730
+ clientTools: this._lastClientTools,
731
+ body: this._lastBody
732
+ });
733
+ if (response) this._reply(requestId, response);
747
734
  });
748
735
  }
749
736
  async persistMessages(messages, excludeBroadcastIds = []) {
@@ -782,8 +769,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
782
769
  if (msg.role !== "assistant") continue;
783
770
  for (const part of msg.parts) if ("toolCallId" in part && "state" in part && part.state === "output-available" && "output" in part) serverToolOutputs.set(part.toolCallId, part.output);
784
771
  }
785
- if (serverToolOutputs.size === 0) return incomingMessages;
786
- return incomingMessages.map((msg) => {
772
+ const withMergedToolOutputs = serverToolOutputs.size === 0 ? incomingMessages : incomingMessages.map((msg) => {
787
773
  if (msg.role !== "assistant") return msg;
788
774
  let hasChanges = false;
789
775
  const updatedParts = msg.parts.map((part) => {
@@ -802,6 +788,50 @@ var AIChatAgent = class AIChatAgent extends Agent {
802
788
  parts: updatedParts
803
789
  } : msg;
804
790
  });
791
+ return this._reconcileAssistantIdsWithServerState(withMergedToolOutputs);
792
+ }
793
+ /**
794
+ * Reconciles assistant message IDs between incoming client state and server state.
795
+ *
796
+ * The client can keep a different local ID for an assistant message than the one
797
+ * persisted on the server (e.g. optimistic/local IDs). When that full history is
798
+ * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
799
+ * this, we reuse the server ID for assistant messages that match by content and
800
+ * order, while leaving tool-call messages to _resolveMessageForToolMerge.
801
+ */
802
+ _reconcileAssistantIdsWithServerState(incomingMessages) {
803
+ if (this.messages.length === 0) return incomingMessages;
804
+ let serverCursor = 0;
805
+ return incomingMessages.map((incomingMessage) => {
806
+ const exactMatchIndex = this.messages.findIndex((serverMessage, index) => index >= serverCursor && serverMessage.id === incomingMessage.id);
807
+ if (exactMatchIndex !== -1) {
808
+ serverCursor = exactMatchIndex + 1;
809
+ return incomingMessage;
810
+ }
811
+ if (incomingMessage.role !== "assistant" || this._hasToolCallPart(incomingMessage)) return incomingMessage;
812
+ const incomingKey = this._assistantMessageContentKey(incomingMessage);
813
+ if (!incomingKey) return incomingMessage;
814
+ for (let i = serverCursor; i < this.messages.length; i++) {
815
+ const serverMessage = this.messages[i];
816
+ if (serverMessage.role !== "assistant" || this._hasToolCallPart(serverMessage)) continue;
817
+ if (this._assistantMessageContentKey(serverMessage) === incomingKey) {
818
+ serverCursor = i + 1;
819
+ return {
820
+ ...incomingMessage,
821
+ id: serverMessage.id
822
+ };
823
+ }
824
+ }
825
+ return incomingMessage;
826
+ });
827
+ }
828
+ _hasToolCallPart(message) {
829
+ return message.parts.some((part) => "toolCallId" in part);
830
+ }
831
+ _assistantMessageContentKey(message) {
832
+ if (message.role !== "assistant") return;
833
+ const sanitized = this._sanitizeMessageForPersistence(message);
834
+ return JSON.stringify(sanitized.parts);
805
835
  }
806
836
  /**
807
837
  * Resolves a message for persistence, handling tool result merging.
@@ -815,7 +845,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
815
845
  */
816
846
  _resolveMessageForToolMerge(message) {
817
847
  if (message.role !== "assistant") return message;
818
- for (const part of message.parts) if ("toolCallId" in part && "state" in part && (part.state === "output-available" || part.state === "approval-responded" || part.state === "approval-requested")) {
848
+ for (const part of message.parts) if ("toolCallId" in part && "state" in part && (part.state === "output-available" || part.state === "output-error" || part.state === "approval-responded" || part.state === "approval-requested")) {
819
849
  const toolCallId = part.toolCallId;
820
850
  const existingMessage = this._findMessageByToolCallId(toolCallId);
821
851
  if (existingMessage && existingMessage.id !== message.id) return {
@@ -843,32 +873,37 @@ var AIChatAgent = class AIChatAgent extends Agent {
843
873
  * Sanitizes a message for persistence by removing ephemeral provider-specific
844
874
  * data that should not be stored or sent back in subsequent requests.
845
875
  *
846
- * This handles two issues with the OpenAI Responses API:
876
+ * Two-step process:
847
877
  *
848
- * 1. **Duplicate item IDs**: The AI SDK's @ai-sdk/openai provider (v2.0.x+)
849
- * defaults to using OpenAI's Responses API which assigns unique itemIds
850
- * to each message part. When these IDs are persisted and sent back,
851
- * OpenAI rejects them as duplicates.
878
+ * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
879
+ * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
880
+ * itemIds and reasoningEncryptedContent to message parts. When persisted
881
+ * and sent back, OpenAI rejects duplicate itemIds.
852
882
  *
853
- * 2. **Empty reasoning parts**: OpenAI may return reasoning parts with empty
854
- * text and encrypted content. These cause "Non-OpenAI reasoning parts are
855
- * not supported" warnings when sent back via convertToModelMessages().
883
+ * 2. **Filter truly empty reasoning parts**: After stripping, reasoning parts
884
+ * with no text and no remaining providerMetadata are removed. Parts that
885
+ * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
886
+ * with providerMetadata.anthropic.redactedData) are preserved, as they
887
+ * contain data required for round-tripping with the provider API.
856
888
  *
857
889
  * @param message - The message to sanitize
858
890
  * @returns A new message with ephemeral provider data removed
859
891
  */
860
892
  _sanitizeMessageForPersistence(message) {
861
- const sanitizedParts = message.parts.filter((part) => {
862
- if (part.type === "reasoning") {
863
- const reasoningPart = part;
864
- if (!reasoningPart.text || reasoningPart.text.trim() === "") return false;
865
- }
866
- return true;
867
- }).map((part) => {
893
+ const sanitizedParts = message.parts.map((part) => {
868
894
  let sanitizedPart = part;
869
895
  if ("providerMetadata" in sanitizedPart && sanitizedPart.providerMetadata && typeof sanitizedPart.providerMetadata === "object" && "openai" in sanitizedPart.providerMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "providerMetadata");
870
896
  if ("callProviderMetadata" in sanitizedPart && sanitizedPart.callProviderMetadata && typeof sanitizedPart.callProviderMetadata === "object" && "openai" in sanitizedPart.callProviderMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "callProviderMetadata");
871
897
  return sanitizedPart;
898
+ }).filter((part) => {
899
+ if (part.type === "reasoning") {
900
+ const reasoningPart = part;
901
+ if (!reasoningPart.text || reasoningPart.text.trim() === "") {
902
+ if ("providerMetadata" in reasoningPart && reasoningPart.providerMetadata && typeof reasoningPart.providerMetadata === "object" && Object.keys(reasoningPart.providerMetadata).length > 0) return true;
903
+ return false;
904
+ }
905
+ }
906
+ return true;
872
907
  });
873
908
  return {
874
909
  ...message,
@@ -1097,20 +1132,41 @@ var AIChatAgent = class AIChatAgent extends Agent {
1097
1132
  * @param toolCallId - The tool call ID this result is for
1098
1133
  * @param _toolName - The name of the tool (unused, kept for API compat)
1099
1134
  * @param output - The output from the tool execution
1135
+ * @param overrideState - Optional state override ("output-error" to signal denial/failure)
1136
+ * @param errorText - Error message when overrideState is "output-error"
1100
1137
  * @returns true if the result was applied, false if the message was not found
1101
1138
  */
1102
- async _applyToolResult(toolCallId, _toolName, output) {
1103
- return this._findAndUpdateToolPart(toolCallId, "_applyToolResult", ["input-available"], (part) => ({
1139
+ async _applyToolResult(toolCallId, _toolName, output, overrideState, errorText) {
1140
+ return this._findAndUpdateToolPart(toolCallId, "_applyToolResult", [
1141
+ "input-available",
1142
+ "approval-requested",
1143
+ "approval-responded"
1144
+ ], (part) => ({
1104
1145
  ...part,
1105
- state: "output-available",
1106
- output,
1107
- preliminary: false
1146
+ ...overrideState === "output-error" ? {
1147
+ state: "output-error",
1148
+ errorText: errorText ?? "Tool execution denied by user"
1149
+ } : {
1150
+ state: "output-available",
1151
+ output,
1152
+ preliminary: false
1153
+ }
1108
1154
  }));
1109
1155
  }
1110
- async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false) {
1156
+ async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
1111
1157
  streamCompleted.value = false;
1158
+ if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
1159
+ reader.cancel().catch(() => {});
1160
+ }, { once: true });
1112
1161
  while (true) {
1113
- const { done, value } = await reader.read();
1162
+ if (abortSignal?.aborted) break;
1163
+ let readResult;
1164
+ try {
1165
+ readResult = await reader.read();
1166
+ } catch {
1167
+ break;
1168
+ }
1169
+ const { done, value } = readResult;
1114
1170
  if (done) {
1115
1171
  this._completeStream(streamId);
1116
1172
  streamCompleted.value = true;
@@ -1210,8 +1266,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
1210
1266
  });
1211
1267
  } catch (_error) {}
1212
1268
  }
1269
+ if (!streamCompleted.value) {
1270
+ console.warn("[AIChatAgent] Stream was still active when cancel was received. Pass options.abortSignal to streamText() in your onChatMessage() to cancel the upstream LLM call and avoid wasted work.");
1271
+ this._completeStream(streamId);
1272
+ streamCompleted.value = true;
1273
+ this._broadcastChatMessage({
1274
+ body: "",
1275
+ done: true,
1276
+ id,
1277
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1278
+ ...continuation && { continuation: true }
1279
+ });
1280
+ }
1213
1281
  }
1214
- async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false) {
1282
+ async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
1215
1283
  this._broadcastTextEvent(streamId, {
1216
1284
  type: "text-start",
1217
1285
  id
@@ -1222,8 +1290,18 @@ var AIChatAgent = class AIChatAgent extends Agent {
1222
1290
  state: "streaming"
1223
1291
  };
1224
1292
  message.parts.push(textPart);
1293
+ if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
1294
+ reader.cancel().catch(() => {});
1295
+ }, { once: true });
1225
1296
  while (true) {
1226
- const { done, value } = await reader.read();
1297
+ if (abortSignal?.aborted) break;
1298
+ let readResult;
1299
+ try {
1300
+ readResult = await reader.read();
1301
+ } catch {
1302
+ break;
1303
+ }
1304
+ const { done, value } = readResult;
1227
1305
  if (done) {
1228
1306
  textPart.state = "done";
1229
1307
  this._broadcastTextEvent(streamId, {
@@ -1251,11 +1329,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
1251
1329
  }, continuation);
1252
1330
  }
1253
1331
  }
1332
+ if (!streamCompleted.value) {
1333
+ console.warn("[AIChatAgent] Stream was still active when cancel was received. Pass options.abortSignal to streamText() in your onChatMessage() to cancel the upstream LLM call and avoid wasted work.");
1334
+ textPart.state = "done";
1335
+ this._broadcastTextEvent(streamId, {
1336
+ type: "text-end",
1337
+ id
1338
+ }, continuation);
1339
+ this._completeStream(streamId);
1340
+ streamCompleted.value = true;
1341
+ this._broadcastChatMessage({
1342
+ body: "",
1343
+ done: true,
1344
+ id,
1345
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1346
+ ...continuation && { continuation: true }
1347
+ });
1348
+ }
1254
1349
  }
1255
1350
  /**
1256
1351
  * Applies a tool approval response from the client, updating the persisted message.
1257
1352
  * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
1258
- * Updates the tool part state from input-available/approval-requested to approval-responded.
1353
+ *
1354
+ * - approved=true transitions to approval-responded
1355
+ * - approved=false transitions to output-denied so convertToModelMessages
1356
+ * emits a tool_result for providers (e.g. Anthropic) that require it.
1259
1357
  *
1260
1358
  * @param toolCallId - The tool call ID this approval is for
1261
1359
  * @param approved - Whether the tool execution was approved
@@ -1264,7 +1362,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1264
1362
  async _applyToolApproval(toolCallId, approved) {
1265
1363
  return this._findAndUpdateToolPart(toolCallId, "_applyToolApproval", ["input-available", "approval-requested"], (part) => ({
1266
1364
  ...part,
1267
- state: "approval-responded",
1365
+ state: approved ? "approval-responded" : "output-denied",
1268
1366
  approval: {
1269
1367
  ...part.approval,
1270
1368
  approved
@@ -1273,6 +1371,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1273
1371
  }
1274
1372
  async _reply(id, response, excludeBroadcastIds = [], options = {}) {
1275
1373
  const { continuation = false, chatMessageId } = options;
1374
+ const abortSignal = chatMessageId ? this._chatMessageAbortControllers.get(chatMessageId)?.signal : void 0;
1276
1375
  return this._tryCatchChat(async () => {
1277
1376
  if (!response.body) {
1278
1377
  this._broadcastChatMessage({
@@ -1299,8 +1398,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1299
1398
  const streamCompleted = { value: false };
1300
1399
  let earlyPersistedId = null;
1301
1400
  try {
1302
- if (isSSE) await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation);
1303
- else await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation);
1401
+ if (isSSE) await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
1402
+ else await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
1304
1403
  } catch (error) {
1305
1404
  if (!streamCompleted.value) {
1306
1405
  this._markStreamError(streamId);