@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/src/index.ts CHANGED
@@ -58,27 +58,20 @@ function isValidMessageStructure(msg: unknown): msg is ChatMessage {
58
58
  return true;
59
59
  }
60
60
 
61
- /**
62
- * One-shot deprecation warnings (warns once per key per session).
63
- */
64
- const _deprecationWarnings = new Set<string>();
65
- function warnDeprecated(id: string, message: string) {
66
- if (!_deprecationWarnings.has(id)) {
67
- _deprecationWarnings.add(id);
68
- console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
69
- }
70
- }
71
-
72
61
  /**
73
62
  * Schema for a client-defined tool sent from the browser.
74
63
  * These tools are executed on the client, not the server.
75
64
  *
76
- * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema` (FlexibleSchema)
77
- * because this is the wire format. Zod schemas cannot be serialized.
65
+ * **For most apps**, define tools on the server with `tool()` from `"ai"` —
66
+ * you get full Zod type safety, server-side execution, and simpler code.
67
+ * Use `onToolCall` in `useAgentChat` for tools that need client-side execution.
78
68
  *
79
- * @deprecated Define tools on the server using `tool()` from "ai" instead.
80
- * For tools that need client-side execution, omit the `execute` function
81
- * and handle them via the `onToolCall` callback in `useAgentChat`.
69
+ * **For SDKs and platforms** where the tool surface is determined dynamically
70
+ * by the embedding application at runtime, client tool schemas let the
71
+ * client register tools the server does not know about at deploy time.
72
+ *
73
+ * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema`
74
+ * because this is the wire format. Zod schemas cannot be serialized.
82
75
  */
83
76
  export type ClientToolSchema = {
84
77
  /** Unique name for the tool */
@@ -93,6 +86,15 @@ export type ClientToolSchema = {
93
86
  * Options passed to the onChatMessage handler.
94
87
  */
95
88
  export type OnChatMessageOptions = {
89
+ /**
90
+ * Unique ID for this chat message exchange.
91
+ *
92
+ * For initial user messages this is the client-generated ID from the
93
+ * `CF_AGENT_USE_CHAT_REQUEST` WebSocket frame. For tool continuations
94
+ * (auto-continue after client tool results or approvals) this is a
95
+ * server-generated ID.
96
+ */
97
+ requestId: string;
96
98
  /** AbortSignal for cancelling the request */
97
99
  abortSignal?: AbortSignal;
98
100
  /**
@@ -100,8 +102,12 @@ export type OnChatMessageOptions = {
100
102
  * These represent tools that will be executed on the client side.
101
103
  * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
102
104
  *
103
- * @deprecated Define tools on the server instead. Use `onToolCall` callback
104
- * in `useAgentChat` for client-side execution.
105
+ * **For most apps**, you do not need this — define tools on the server with
106
+ * `tool()` from `"ai"` and use `onToolCall` for client-side execution.
107
+ *
108
+ * **For SDKs and platforms** where tools are defined dynamically by the
109
+ * client at runtime and the server does not know the tool surface ahead
110
+ * of time, this field carries the client-provided tool schemas.
105
111
  */
106
112
  clientTools?: ClientToolSchema[];
107
113
  /**
@@ -122,46 +128,29 @@ export type OnChatMessageOptions = {
122
128
  /**
123
129
  * Converts client tool schemas to AI SDK tool format.
124
130
  *
125
- * These tools have no `execute` function - when the AI model calls them,
131
+ * These tools have no `execute` function — when the AI model calls them,
126
132
  * the tool call is sent back to the client for execution.
127
133
  *
134
+ * **For most apps**, define tools on the server with `tool()` from `"ai"`
135
+ * for full Zod type safety. This helper is intended for SDK/platform use
136
+ * cases where the tool surface is determined dynamically by the client.
137
+ *
128
138
  * @param clientTools - Array of tool schemas from the client
129
139
  * @returns Record of AI SDK tools that can be spread into your tools object
130
140
  *
131
- * @deprecated Define tools on the server using `tool()` from "ai" instead.
132
- * For tools that need client-side execution, omit the `execute` function
133
- * and handle them via the `onToolCall` callback in `useAgentChat`.
134
- *
135
141
  * @example
136
142
  * ```typescript
137
- * // Server: Define tool without execute
143
+ * // In onChatMessage:
138
144
  * const tools = {
139
- * getLocation: tool({
140
- * description: "Get user's location",
141
- * inputSchema: z.object({})
142
- * // No execute = client must handle
143
- * })
145
+ * ...createToolsFromClientSchemas(options.clientTools),
146
+ * // server-defined tools with execute:
147
+ * myServerTool: tool({ ... }),
144
148
  * };
145
- *
146
- * // Client: Handle in onToolCall
147
- * useAgentChat({
148
- * onToolCall: async ({ toolCall, addToolOutput }) => {
149
- * if (toolCall.toolName === 'getLocation') {
150
- * const pos = await navigator.geolocation.getCurrentPosition();
151
- * addToolOutput({ toolCallId: toolCall.toolCallId, output: pos });
152
- * }
153
- * }
154
- * });
155
149
  * ```
156
150
  */
157
151
  export function createToolsFromClientSchemas(
158
152
  clientTools?: ClientToolSchema[]
159
153
  ): ToolSet {
160
- warnDeprecated(
161
- "createToolsFromClientSchemas",
162
- "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."
163
- );
164
-
165
154
  if (!clientTools || clientTools.length === 0) {
166
155
  return {};
167
156
  }
@@ -353,6 +342,9 @@ export class AIChatAgent<
353
342
  // Wrap onMessage
354
343
  const _onMessage = this.onMessage.bind(this);
355
344
  this.onMessage = async (connection: Connection, message: WSMessage) => {
345
+ // Ensure jsonSchema is initialized for getAITools() (matches base Agent pattern)
346
+ await this.mcp.ensureJsonSchema();
347
+
356
348
  // Handle AIChatAgent's internal messages first
357
349
  if (typeof message === "string") {
358
350
  let data: IncomingMessage;
@@ -437,6 +429,7 @@ export class AIChatAgent<
437
429
  // so this is optional for the user to pass to streamText.
438
430
  },
439
431
  {
432
+ requestId: chatMessageId,
440
433
  abortSignal,
441
434
  clientTools,
442
435
  body: this._lastBody
@@ -526,8 +519,15 @@ export class AIChatAgent<
526
519
 
527
520
  // Handle client-side tool result
528
521
  if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
529
- const { toolCallId, toolName, output, autoContinue, clientTools } =
530
- data;
522
+ const {
523
+ toolCallId,
524
+ toolName,
525
+ output,
526
+ state,
527
+ errorText,
528
+ autoContinue,
529
+ clientTools
530
+ } = data;
531
531
 
532
532
  // Update cached client tools so subsequent continuations use the latest schemas
533
533
  if (clientTools?.length) {
@@ -535,81 +535,89 @@ export class AIChatAgent<
535
535
  this._persistRequestContext();
536
536
  }
537
537
 
538
+ const overrideState =
539
+ state === "output-error" ? "output-error" : undefined;
540
+
538
541
  // Apply the tool result
539
- this._applyToolResult(toolCallId, toolName, output).then(
540
- (applied) => {
541
- // Only auto-continue if client requested it (opt-in behavior)
542
- // This mimics server-executed tool behavior where the LLM
543
- // automatically continues after seeing tool results
544
- if (applied && autoContinue) {
545
- // Wait for the original stream to complete and message to be persisted
546
- // before calling onChatMessage, so this.messages includes the tool result
547
- const waitForStream = async () => {
548
- if (this._streamCompletionPromise) {
549
- await this._streamCompletionPromise;
550
- } else {
551
- // TODO: The completion promise can be null if the stream finished
552
- // before the tool result arrived (race between stream end and tool
553
- // apply). The 500ms fallback is a pragmatic workaround — consider
554
- // a more deterministic signal (e.g. always setting the promise).
555
- await new Promise((resolve) => setTimeout(resolve, 500));
556
- }
557
- };
542
+ this._applyToolResult(
543
+ toolCallId,
544
+ toolName,
545
+ output,
546
+ overrideState,
547
+ errorText
548
+ ).then((applied) => {
549
+ // Only auto-continue if client requested it (opt-in behavior)
550
+ // This mimics server-executed tool behavior where the LLM
551
+ // automatically continues after seeing tool results
552
+ if (applied && autoContinue) {
553
+ // Wait for the original stream to complete and message to be persisted
554
+ // before calling onChatMessage, so this.messages includes the tool result
555
+ const waitForStream = async () => {
556
+ if (this._streamCompletionPromise) {
557
+ await this._streamCompletionPromise;
558
+ } else {
559
+ // TODO: The completion promise can be null if the stream finished
560
+ // before the tool result arrived (race between stream end and tool
561
+ // apply). The 500ms fallback is a pragmatic workaround — consider
562
+ // a more deterministic signal (e.g. always setting the promise).
563
+ await new Promise((resolve) => setTimeout(resolve, 500));
564
+ }
565
+ };
566
+
567
+ waitForStream()
568
+ .then(() => {
569
+ const continuationId = nanoid();
570
+ const abortSignal = this._getAbortSignal(continuationId);
558
571
 
559
- waitForStream()
560
- .then(() => {
561
- const continuationId = nanoid();
562
- const abortSignal = this._getAbortSignal(continuationId);
563
-
564
- return this._tryCatchChat(async () => {
565
- return agentContext.run(
566
- {
567
- agent: this,
568
- connection,
569
- request: undefined,
570
- email: undefined
571
- },
572
- async () => {
573
- const response = await this.onChatMessage(
574
- async (_finishResult) => {
575
- // User-provided hook. Cleanup handled by _reply.
576
- },
572
+ return this._tryCatchChat(async () => {
573
+ return agentContext.run(
574
+ {
575
+ agent: this,
576
+ connection,
577
+ request: undefined,
578
+ email: undefined
579
+ },
580
+ async () => {
581
+ const response = await this.onChatMessage(
582
+ async (_finishResult) => {
583
+ // User-provided hook. Cleanup handled by _reply.
584
+ },
585
+ {
586
+ requestId: continuationId,
587
+ abortSignal,
588
+ clientTools: clientTools ?? this._lastClientTools,
589
+ body: this._lastBody
590
+ }
591
+ );
592
+
593
+ if (response) {
594
+ // Pass continuation flag to merge parts into last assistant message
595
+ // Note: We pass an empty excludeBroadcastIds array because the sender
596
+ // NEEDS to receive the continuation stream. Unlike regular chat requests
597
+ // where aiFetch handles the response, tool continuations have no listener
598
+ // waiting - the client relies on the broadcast.
599
+ await this._reply(
600
+ continuationId,
601
+ response,
602
+ [], // Don't exclude sender - they need the continuation
577
603
  {
578
- abortSignal,
579
- clientTools: clientTools ?? this._lastClientTools,
580
- body: this._lastBody
604
+ continuation: true,
605
+ chatMessageId: continuationId
581
606
  }
582
607
  );
583
-
584
- if (response) {
585
- // Pass continuation flag to merge parts into last assistant message
586
- // Note: We pass an empty excludeBroadcastIds array because the sender
587
- // NEEDS to receive the continuation stream. Unlike regular chat requests
588
- // where aiFetch handles the response, tool continuations have no listener
589
- // waiting - the client relies on the broadcast.
590
- await this._reply(
591
- continuationId,
592
- response,
593
- [], // Don't exclude sender - they need the continuation
594
- {
595
- continuation: true,
596
- chatMessageId: continuationId
597
- }
598
- );
599
- }
600
608
  }
601
- );
602
- });
603
- })
604
- .catch((error) => {
605
- console.error(
606
- "[AIChatAgent] Tool continuation failed:",
607
- error
609
+ }
608
610
  );
609
611
  });
610
- }
612
+ })
613
+ .catch((error) => {
614
+ console.error(
615
+ "[AIChatAgent] Tool continuation failed:",
616
+ error
617
+ );
618
+ });
611
619
  }
612
- );
620
+ });
613
621
  return;
614
622
  }
615
623
 
@@ -617,8 +625,9 @@ export class AIChatAgent<
617
625
  if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
618
626
  const { toolCallId, approved, autoContinue } = data;
619
627
  this._applyToolApproval(toolCallId, approved).then((applied) => {
620
- // Only auto-continue if approved AND client requested it
621
- if (applied && approved && autoContinue) {
628
+ // Auto-continue for both approvals and rejections so the LLM
629
+ // sees the tool_result and can respond accordingly.
630
+ if (applied && autoContinue) {
622
631
  const waitForStream = async () => {
623
632
  if (this._streamCompletionPromise) {
624
633
  await this._streamCompletionPromise;
@@ -644,6 +653,7 @@ export class AIChatAgent<
644
653
  const response = await this.onChatMessage(
645
654
  async (_finishResult) => {},
646
655
  {
656
+ requestId: continuationId,
647
657
  abortSignal,
648
658
  clientTools: this._lastClientTools,
649
659
  body: this._lastBody
@@ -675,6 +685,17 @@ export class AIChatAgent<
675
685
  // Forward unhandled messages to consumer's onMessage
676
686
  return _onMessage(connection, message);
677
687
  };
688
+
689
+ const _onRequest = this.onRequest.bind(this);
690
+ this.onRequest = async (request: Request) => {
691
+ return this._tryCatchChat(async () => {
692
+ const url = new URL(request.url);
693
+ if (url.pathname.split("/").pop() === "get-messages") {
694
+ return Response.json(this._loadMessagesFromDb());
695
+ }
696
+ return _onRequest(request);
697
+ });
698
+ };
678
699
  }
679
700
 
680
701
  /**
@@ -871,19 +892,6 @@ export class AIChatAgent<
871
892
  .filter((msg): msg is ChatMessage => msg !== null);
872
893
  }
873
894
 
874
- override async onRequest(request: Request): Promise<Response> {
875
- return this._tryCatchChat(async () => {
876
- const url = new URL(request.url);
877
-
878
- if (url.pathname.endsWith("/get-messages")) {
879
- const messages = this._loadMessagesFromDb();
880
- return Response.json(messages);
881
- }
882
-
883
- return super.onRequest(request);
884
- });
885
- }
886
-
887
895
  private async _tryCatchChat<T>(fn: () => T | Promise<T>) {
888
896
  try {
889
897
  return await fn();
@@ -916,8 +924,15 @@ export class AIChatAgent<
916
924
  async saveMessages(messages: ChatMessage[]) {
917
925
  await this.persistMessages(messages);
918
926
  await this._tryCatchChat(async () => {
919
- const response = await this.onChatMessage(() => {});
920
- if (response) this._reply(crypto.randomUUID(), response);
927
+ const requestId = nanoid();
928
+ const abortSignal = this._getAbortSignal(requestId);
929
+ const response = await this.onChatMessage(() => {}, {
930
+ requestId,
931
+ abortSignal,
932
+ clientTools: this._lastClientTools,
933
+ body: this._lastBody
934
+ });
935
+ if (response) this._reply(requestId, response);
921
936
  });
922
937
  }
923
938
 
@@ -998,38 +1013,125 @@ export class AIChatAgent<
998
1013
  }
999
1014
  }
1000
1015
 
1001
- // If server has no tool outputs, return incoming messages as-is
1002
- if (serverToolOutputs.size === 0) {
1016
+ // Merge server's tool outputs into incoming messages.
1017
+ const withMergedToolOutputs =
1018
+ serverToolOutputs.size === 0
1019
+ ? incomingMessages
1020
+ : incomingMessages.map((msg) => {
1021
+ if (msg.role !== "assistant") return msg;
1022
+
1023
+ let hasChanges = false;
1024
+ const updatedParts = msg.parts.map((part) => {
1025
+ // If this is a tool part in input-available state and server has the output
1026
+ if (
1027
+ "toolCallId" in part &&
1028
+ "state" in part &&
1029
+ part.state === "input-available" &&
1030
+ serverToolOutputs.has(part.toolCallId as string)
1031
+ ) {
1032
+ hasChanges = true;
1033
+ return {
1034
+ ...part,
1035
+ state: "output-available" as const,
1036
+ output: serverToolOutputs.get(part.toolCallId as string)
1037
+ };
1038
+ }
1039
+ return part;
1040
+ }) as ChatMessage["parts"];
1041
+
1042
+ return hasChanges ? { ...msg, parts: updatedParts } : msg;
1043
+ });
1044
+
1045
+ return this._reconcileAssistantIdsWithServerState(withMergedToolOutputs);
1046
+ }
1047
+
1048
+ /**
1049
+ * Reconciles assistant message IDs between incoming client state and server state.
1050
+ *
1051
+ * The client can keep a different local ID for an assistant message than the one
1052
+ * persisted on the server (e.g. optimistic/local IDs). When that full history is
1053
+ * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
1054
+ * this, we reuse the server ID for assistant messages that match by content and
1055
+ * order, while leaving tool-call messages to _resolveMessageForToolMerge.
1056
+ */
1057
+ private _reconcileAssistantIdsWithServerState(
1058
+ incomingMessages: ChatMessage[]
1059
+ ): ChatMessage[] {
1060
+ if (this.messages.length === 0) {
1003
1061
  return incomingMessages;
1004
1062
  }
1005
1063
 
1006
- // Merge server's tool outputs into incoming messages
1007
- return incomingMessages.map((msg) => {
1008
- if (msg.role !== "assistant") return msg;
1064
+ // Tracks the earliest server index we should consider for subsequent matches.
1065
+ // This preserves ordering and prevents one server message from being reused for
1066
+ // multiple incoming messages with identical content.
1067
+ let serverCursor = 0;
1068
+
1069
+ return incomingMessages.map((incomingMessage) => {
1070
+ // Fast path: exact ID already exists in server history.
1071
+ // This applies to any role (user/assistant/system/tool), so in-order
1072
+ // round-trips naturally advance the cursor even when assistant content
1073
+ // reconciliation is skipped.
1074
+ const exactMatchIndex = this.messages.findIndex(
1075
+ (serverMessage, index) =>
1076
+ index >= serverCursor && serverMessage.id === incomingMessage.id
1077
+ );
1078
+ if (exactMatchIndex !== -1) {
1079
+ serverCursor = exactMatchIndex + 1;
1080
+ return incomingMessage;
1081
+ }
1082
+
1083
+ if (
1084
+ incomingMessage.role !== "assistant" ||
1085
+ this._hasToolCallPart(incomingMessage)
1086
+ ) {
1087
+ // Content-based reconciliation is only for non-tool assistant messages.
1088
+ // Tool-bearing assistant messages are reconciled by _resolveMessageForToolMerge.
1089
+ return incomingMessage;
1090
+ }
1009
1091
 
1010
- let hasChanges = false;
1011
- const updatedParts = msg.parts.map((part) => {
1012
- // If this is a tool part in input-available state and server has the output
1092
+ const incomingKey = this._assistantMessageContentKey(incomingMessage);
1093
+ if (!incomingKey) {
1094
+ return incomingMessage;
1095
+ }
1096
+
1097
+ for (let i = serverCursor; i < this.messages.length; i++) {
1098
+ const serverMessage = this.messages[i];
1013
1099
  if (
1014
- "toolCallId" in part &&
1015
- "state" in part &&
1016
- part.state === "input-available" &&
1017
- serverToolOutputs.has(part.toolCallId as string)
1100
+ serverMessage.role !== "assistant" ||
1101
+ this._hasToolCallPart(serverMessage)
1018
1102
  ) {
1019
- hasChanges = true;
1103
+ continue;
1104
+ }
1105
+
1106
+ if (this._assistantMessageContentKey(serverMessage) === incomingKey) {
1107
+ serverCursor = i + 1;
1108
+
1020
1109
  return {
1021
- ...part,
1022
- state: "output-available" as const,
1023
- output: serverToolOutputs.get(part.toolCallId as string)
1110
+ ...incomingMessage,
1111
+ id: serverMessage.id
1024
1112
  };
1025
1113
  }
1026
- return part;
1027
- }) as ChatMessage["parts"];
1114
+ }
1028
1115
 
1029
- return hasChanges ? { ...msg, parts: updatedParts } : msg;
1116
+ return incomingMessage;
1030
1117
  });
1031
1118
  }
1032
1119
 
1120
+ private _hasToolCallPart(message: ChatMessage): boolean {
1121
+ return message.parts.some((part) => "toolCallId" in part);
1122
+ }
1123
+
1124
+ private _assistantMessageContentKey(
1125
+ message: ChatMessage
1126
+ ): string | undefined {
1127
+ if (message.role !== "assistant") {
1128
+ return undefined;
1129
+ }
1130
+
1131
+ const sanitized = this._sanitizeMessageForPersistence(message);
1132
+ return JSON.stringify(sanitized.parts);
1133
+ }
1134
+
1033
1135
  /**
1034
1136
  * Resolves a message for persistence, handling tool result merging.
1035
1137
  * If the message contains tool parts with output-available state, checks if there's
@@ -1051,6 +1153,7 @@ export class AIChatAgent<
1051
1153
  "toolCallId" in part &&
1052
1154
  "state" in part &&
1053
1155
  (part.state === "output-available" ||
1156
+ part.state === "output-error" ||
1054
1157
  part.state === "approval-responded" ||
1055
1158
  part.state === "approval-requested")
1056
1159
  ) {
@@ -1099,36 +1202,25 @@ export class AIChatAgent<
1099
1202
  * Sanitizes a message for persistence by removing ephemeral provider-specific
1100
1203
  * data that should not be stored or sent back in subsequent requests.
1101
1204
  *
1102
- * This handles two issues with the OpenAI Responses API:
1205
+ * Two-step process:
1103
1206
  *
1104
- * 1. **Duplicate item IDs**: The AI SDK's @ai-sdk/openai provider (v2.0.x+)
1105
- * defaults to using OpenAI's Responses API which assigns unique itemIds
1106
- * to each message part. When these IDs are persisted and sent back,
1107
- * OpenAI rejects them as duplicates.
1207
+ * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
1208
+ * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
1209
+ * itemIds and reasoningEncryptedContent to message parts. When persisted
1210
+ * and sent back, OpenAI rejects duplicate itemIds.
1108
1211
  *
1109
- * 2. **Empty reasoning parts**: OpenAI may return reasoning parts with empty
1110
- * text and encrypted content. These cause "Non-OpenAI reasoning parts are
1111
- * not supported" warnings when sent back via convertToModelMessages().
1212
+ * 2. **Filter truly empty reasoning parts**: After stripping, reasoning parts
1213
+ * with no text and no remaining providerMetadata are removed. Parts that
1214
+ * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
1215
+ * with providerMetadata.anthropic.redactedData) are preserved, as they
1216
+ * contain data required for round-tripping with the provider API.
1112
1217
  *
1113
1218
  * @param message - The message to sanitize
1114
1219
  * @returns A new message with ephemeral provider data removed
1115
1220
  */
1116
1221
  private _sanitizeMessageForPersistence(message: ChatMessage): ChatMessage {
1117
- // First, filter out empty reasoning parts (they have no useful content)
1118
- const filteredParts = message.parts.filter((part) => {
1119
- if (part.type === "reasoning") {
1120
- const reasoningPart = part as ReasoningUIPart;
1121
- // Remove reasoning parts that have no text content
1122
- // These are typically placeholders with only encrypted content
1123
- if (!reasoningPart.text || reasoningPart.text.trim() === "") {
1124
- return false;
1125
- }
1126
- }
1127
- return true;
1128
- });
1129
-
1130
- // Then sanitize remaining parts by stripping OpenAI-specific ephemeral data
1131
- const sanitizedParts = filteredParts.map((part) => {
1222
+ // First, strip OpenAI-specific ephemeral data from all parts
1223
+ const strippedParts = message.parts.map((part) => {
1132
1224
  let sanitizedPart = part;
1133
1225
 
1134
1226
  // Strip providerMetadata.openai.itemId and reasoningEncryptedContent
@@ -1160,6 +1252,28 @@ export class AIChatAgent<
1160
1252
  return sanitizedPart;
1161
1253
  }) as ChatMessage["parts"];
1162
1254
 
1255
+ // Then filter out reasoning parts that are truly empty (no text and no
1256
+ // remaining providerMetadata). This removes OpenAI placeholders whose
1257
+ // metadata was just stripped, while preserving provider-specific blocks
1258
+ // like Anthropic's redacted_thinking that carry data in providerMetadata.
1259
+ const sanitizedParts = strippedParts.filter((part) => {
1260
+ if (part.type === "reasoning") {
1261
+ const reasoningPart = part as ReasoningUIPart;
1262
+ if (!reasoningPart.text || reasoningPart.text.trim() === "") {
1263
+ if (
1264
+ "providerMetadata" in reasoningPart &&
1265
+ reasoningPart.providerMetadata &&
1266
+ typeof reasoningPart.providerMetadata === "object" &&
1267
+ Object.keys(reasoningPart.providerMetadata).length > 0
1268
+ ) {
1269
+ return true;
1270
+ }
1271
+ return false;
1272
+ }
1273
+ }
1274
+ return true;
1275
+ });
1276
+
1163
1277
  return { ...message, parts: sanitizedParts };
1164
1278
  }
1165
1279
 
@@ -1513,22 +1627,29 @@ export class AIChatAgent<
1513
1627
  * @param toolCallId - The tool call ID this result is for
1514
1628
  * @param _toolName - The name of the tool (unused, kept for API compat)
1515
1629
  * @param output - The output from the tool execution
1630
+ * @param overrideState - Optional state override ("output-error" to signal denial/failure)
1631
+ * @param errorText - Error message when overrideState is "output-error"
1516
1632
  * @returns true if the result was applied, false if the message was not found
1517
1633
  */
1518
1634
  private async _applyToolResult(
1519
1635
  toolCallId: string,
1520
1636
  _toolName: string,
1521
- output: unknown
1637
+ output: unknown,
1638
+ overrideState?: "output-error",
1639
+ errorText?: string
1522
1640
  ): Promise<boolean> {
1523
1641
  return this._findAndUpdateToolPart(
1524
1642
  toolCallId,
1525
1643
  "_applyToolResult",
1526
- ["input-available"],
1644
+ ["input-available", "approval-requested", "approval-responded"],
1527
1645
  (part) => ({
1528
1646
  ...part,
1529
- state: "output-available",
1530
- output,
1531
- preliminary: false
1647
+ ...(overrideState === "output-error"
1648
+ ? {
1649
+ state: "output-error",
1650
+ errorText: errorText ?? "Tool execution denied by user"
1651
+ }
1652
+ : { state: "output-available", output, preliminary: false })
1532
1653
  })
1533
1654
  );
1534
1655
  }
@@ -1539,11 +1660,35 @@ export class AIChatAgent<
1539
1660
  reader: ReadableStreamDefaultReader<Uint8Array>,
1540
1661
  message: ChatMessage,
1541
1662
  streamCompleted: { value: boolean },
1542
- continuation = false
1663
+ continuation = false,
1664
+ abortSignal?: AbortSignal
1543
1665
  ) {
1544
1666
  streamCompleted.value = false;
1667
+
1668
+ // Cancel the reader when the abort signal fires (e.g. client pressed stop).
1669
+ // This ensures we stop broadcasting chunks even if the underlying stream
1670
+ // hasn't been connected to the abort signal (e.g. user forgot to pass it
1671
+ // to streamText).
1672
+ if (abortSignal && !abortSignal.aborted) {
1673
+ abortSignal.addEventListener(
1674
+ "abort",
1675
+ () => {
1676
+ reader.cancel().catch(() => {});
1677
+ },
1678
+ { once: true }
1679
+ );
1680
+ }
1681
+
1545
1682
  while (true) {
1546
- const { done, value } = await reader.read();
1683
+ if (abortSignal?.aborted) break;
1684
+ let readResult: ReadableStreamReadResult<Uint8Array>;
1685
+ try {
1686
+ readResult = await reader.read();
1687
+ } catch {
1688
+ // reader.read() throws after cancel() — treat as abort
1689
+ break;
1690
+ }
1691
+ const { done, value } = readResult;
1547
1692
  if (done) {
1548
1693
  this._completeStream(streamId);
1549
1694
  streamCompleted.value = true;
@@ -1731,6 +1876,24 @@ export class AIChatAgent<
1731
1876
  }
1732
1877
  }
1733
1878
  }
1879
+
1880
+ // If we exited due to abort, send a done signal so clients know the stream ended
1881
+ if (!streamCompleted.value) {
1882
+ console.warn(
1883
+ "[AIChatAgent] Stream was still active when cancel was received. " +
1884
+ "Pass options.abortSignal to streamText() in your onChatMessage() " +
1885
+ "to cancel the upstream LLM call and avoid wasted work."
1886
+ );
1887
+ this._completeStream(streamId);
1888
+ streamCompleted.value = true;
1889
+ this._broadcastChatMessage({
1890
+ body: "",
1891
+ done: true,
1892
+ id,
1893
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1894
+ ...(continuation && { continuation: true })
1895
+ });
1896
+ }
1734
1897
  }
1735
1898
 
1736
1899
  // Handle plain text responses (e.g., from generateText)
@@ -1740,7 +1903,8 @@ export class AIChatAgent<
1740
1903
  reader: ReadableStreamDefaultReader<Uint8Array>,
1741
1904
  message: ChatMessage,
1742
1905
  streamCompleted: { value: boolean },
1743
- continuation = false
1906
+ continuation = false,
1907
+ abortSignal?: AbortSignal
1744
1908
  ) {
1745
1909
  // if not AI SDK SSE format, we need to inject text-start and text-end events ourselves
1746
1910
  this._broadcastTextEvent(
@@ -1754,8 +1918,27 @@ export class AIChatAgent<
1754
1918
  const textPart: TextUIPart = { type: "text", text: "", state: "streaming" };
1755
1919
  message.parts.push(textPart);
1756
1920
 
1921
+ // Cancel the reader when the abort signal fires
1922
+ if (abortSignal && !abortSignal.aborted) {
1923
+ abortSignal.addEventListener(
1924
+ "abort",
1925
+ () => {
1926
+ reader.cancel().catch(() => {});
1927
+ },
1928
+ { once: true }
1929
+ );
1930
+ }
1931
+
1757
1932
  while (true) {
1758
- const { done, value } = await reader.read();
1933
+ if (abortSignal?.aborted) break;
1934
+ let readResult: ReadableStreamReadResult<Uint8Array>;
1935
+ try {
1936
+ readResult = await reader.read();
1937
+ } catch {
1938
+ // reader.read() throws after cancel() — treat as abort
1939
+ break;
1940
+ }
1941
+ const { done, value } = readResult;
1759
1942
  if (done) {
1760
1943
  textPart.state = "done";
1761
1944
 
@@ -1791,12 +1974,39 @@ export class AIChatAgent<
1791
1974
  );
1792
1975
  }
1793
1976
  }
1977
+
1978
+ // If we exited due to abort, send a done signal so clients know the stream ended
1979
+ if (!streamCompleted.value) {
1980
+ console.warn(
1981
+ "[AIChatAgent] Stream was still active when cancel was received. " +
1982
+ "Pass options.abortSignal to streamText() in your onChatMessage() " +
1983
+ "to cancel the upstream LLM call and avoid wasted work."
1984
+ );
1985
+ textPart.state = "done";
1986
+ this._broadcastTextEvent(
1987
+ streamId,
1988
+ { type: "text-end", id },
1989
+ continuation
1990
+ );
1991
+ this._completeStream(streamId);
1992
+ streamCompleted.value = true;
1993
+ this._broadcastChatMessage({
1994
+ body: "",
1995
+ done: true,
1996
+ id,
1997
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1998
+ ...(continuation && { continuation: true })
1999
+ });
2000
+ }
1794
2001
  }
1795
2002
 
1796
2003
  /**
1797
2004
  * Applies a tool approval response from the client, updating the persisted message.
1798
2005
  * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
1799
- * Updates the tool part state from input-available/approval-requested to approval-responded.
2006
+ *
2007
+ * - approved=true transitions to approval-responded
2008
+ * - approved=false transitions to output-denied so convertToModelMessages
2009
+ * emits a tool_result for providers (e.g. Anthropic) that require it.
1800
2010
  *
1801
2011
  * @param toolCallId - The tool call ID this approval is for
1802
2012
  * @param approved - Whether the tool execution was approved
@@ -1812,7 +2022,7 @@ export class AIChatAgent<
1812
2022
  ["input-available", "approval-requested"],
1813
2023
  (part) => ({
1814
2024
  ...part,
1815
- state: "approval-responded",
2025
+ state: approved ? "approval-responded" : "output-denied",
1816
2026
  // Merge with existing approval data to preserve the id field.
1817
2027
  // convertToModelMessages needs approval.id to produce a valid
1818
2028
  // tool-approval-request content part with approvalId.
@@ -1831,6 +2041,12 @@ export class AIChatAgent<
1831
2041
  options: { continuation?: boolean; chatMessageId?: string } = {}
1832
2042
  ) {
1833
2043
  const { continuation = false, chatMessageId } = options;
2044
+ // Look up the abort signal for this request so we can cancel the reader
2045
+ // loop if the client sends a cancel message. This is a safety net —
2046
+ // users should also pass abortSignal to streamText for proper cancellation.
2047
+ const abortSignal = chatMessageId
2048
+ ? this._chatMessageAbortControllers.get(chatMessageId)?.signal
2049
+ : undefined;
1834
2050
 
1835
2051
  return this._tryCatchChat(async () => {
1836
2052
  if (!response.body) {
@@ -1882,7 +2098,8 @@ export class AIChatAgent<
1882
2098
  reader,
1883
2099
  message,
1884
2100
  streamCompleted,
1885
- continuation
2101
+ continuation,
2102
+ abortSignal
1886
2103
  );
1887
2104
  } else {
1888
2105
  await this._sendPlaintextReply(
@@ -1891,7 +2108,8 @@ export class AIChatAgent<
1891
2108
  reader,
1892
2109
  message,
1893
2110
  streamCompleted,
1894
- continuation
2111
+ continuation,
2112
+ abortSignal
1895
2113
  );
1896
2114
  }
1897
2115
  } catch (error) {