@cloudflare/ai-chat 0.1.3 → 0.1.5
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 +51 -0
- package/dist/index.d.ts +62 -39
- package/dist/index.js +176 -77
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +40 -25
- package/dist/react.js +48 -35
- package/dist/react.js.map +1 -1
- package/dist/types.d.ts +5 -1
- package/dist/types.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +402 -184
- package/src/react-tests/vitest.config.ts +1 -0
- package/src/react.tsx +98 -57
- package/src/tests/cancel-request.test.ts +280 -0
- package/src/tests/client-tool-duplicate-message.test.ts +666 -9
- package/src/tests/get-messages-endpoint.test.ts +74 -0
- package/src/tests/merge-server-state.test.ts +237 -0
- package/src/tests/request-id.test.ts +312 -0
- package/src/tests/sanitize-messages.test.ts +110 -0
- package/src/tests/vitest.config.ts +1 -0
- package/src/tests/worker.ts +113 -1
- package/src/tests/wrangler.jsonc +24 -0
- package/src/tests/ws-transport-abort.test.ts +198 -0
- package/src/types.ts +4 -0
- package/src/ws-chat-transport.ts +50 -26
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,56 @@
|
|
|
1
1
|
# @cloudflare/ai-chat
|
|
2
2
|
|
|
3
|
+
## 0.1.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#986](https://github.com/cloudflare/agents/pull/986) [`e0d7a75`](https://github.com/cloudflare/agents/commit/e0d7a75b9c8ef484f7d5fc26f821e575b7a567cb) Thanks [@threepointone](https://github.com/threepointone)! - Terminate the WebSocket chat transport stream when the abort signal fires so
|
|
8
|
+
clients exit the "streaming" state after stop/cancel.
|
|
9
|
+
|
|
10
|
+
## 0.1.4
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- [#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).
|
|
15
|
+
|
|
16
|
+
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).
|
|
17
|
+
|
|
18
|
+
This enables the Vercel AI SDK recommended pattern for client-side tool denial:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
addToolOutput({
|
|
22
|
+
toolCallId: invocation.toolCallId,
|
|
23
|
+
state: "output-error",
|
|
24
|
+
errorText: "User declined: insufficient permissions",
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
- [#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.
|
|
29
|
+
|
|
30
|
+
`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.
|
|
31
|
+
|
|
32
|
+
- [#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.
|
|
33
|
+
|
|
34
|
+
Also fix `saveMessages()` to pass the full options object (`requestId`, `abortSignal`, `clientTools`, `body`) to `onChatMessage` and use a consistent request ID for `_reply`.
|
|
35
|
+
|
|
36
|
+
- [#973](https://github.com/cloudflare/agents/pull/973) [`969fbff`](https://github.com/cloudflare/agents/commit/969fbff702d5702c1f0ea6faaecb3dfd0431a01b) Thanks [@threepointone](https://github.com/threepointone)! - Update dependencies
|
|
37
|
+
|
|
38
|
+
- [#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.
|
|
39
|
+
|
|
40
|
+
- [#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
|
|
41
|
+
|
|
42
|
+
- [#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.
|
|
43
|
+
|
|
44
|
+
- [#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()`.
|
|
45
|
+
|
|
46
|
+
- [#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`.
|
|
47
|
+
|
|
48
|
+
This ensures `convertToModelMessages` emits a `tool_result` for denied approvals, which is required by providers like Anthropic.
|
|
49
|
+
|
|
50
|
+
Also adds regression tests for denied approval behavior, including rejection from `approval-requested` state.
|
|
51
|
+
|
|
52
|
+
- [#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.
|
|
53
|
+
|
|
3
54
|
## 0.1.3
|
|
4
55
|
|
|
5
56
|
### 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
|
-
*
|
|
17
|
-
*
|
|
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
|
-
*
|
|
20
|
-
*
|
|
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
|
-
/**
|
|
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
|
-
*
|
|
39
|
-
*
|
|
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
|
|
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
|
-
* //
|
|
88
|
+
* // In onChatMessage:
|
|
72
89
|
* const tools = {
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
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
|
-
*
|
|
297
|
+
* Two-step process:
|
|
282
298
|
*
|
|
283
|
-
* 1. **
|
|
284
|
-
* defaults to using OpenAI's Responses API which assigns unique
|
|
285
|
-
* to
|
|
286
|
-
* OpenAI rejects
|
|
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. **
|
|
289
|
-
* text and
|
|
290
|
-
*
|
|
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
|
-
*
|
|
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
|