@cloudflare/ai-chat 0.4.5 → 0.5.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.
- package/README.md +12 -12
- package/dist/index.d.ts +48 -75
- package/dist/index.js +57 -34
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js +69 -33
- package/dist/react.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
22
22
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
23
23
|
|
|
24
24
|
const result = streamText({
|
|
25
|
-
model: workersai("@cf/moonshotai/kimi-k2.
|
|
25
|
+
model: workersai("@cf/moonshotai/kimi-k2.6"),
|
|
26
26
|
messages: await convertToModelMessages(this.messages)
|
|
27
27
|
});
|
|
28
28
|
|
|
@@ -110,7 +110,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
110
110
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
111
111
|
|
|
112
112
|
const result = streamText({
|
|
113
|
-
model: workersai("@cf/moonshotai/kimi-k2.
|
|
113
|
+
model: workersai("@cf/moonshotai/kimi-k2.6"),
|
|
114
114
|
messages: await convertToModelMessages(this.messages),
|
|
115
115
|
tools: {
|
|
116
116
|
getWeather: tool({
|
|
@@ -289,7 +289,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
289
289
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
290
290
|
|
|
291
291
|
const result = streamText({
|
|
292
|
-
model: workersai("@cf/moonshotai/kimi-k2.
|
|
292
|
+
model: workersai("@cf/moonshotai/kimi-k2.6"),
|
|
293
293
|
messages: pruneMessages({
|
|
294
294
|
messages: await convertToModelMessages(this.messages),
|
|
295
295
|
reasoning: "before-last-message",
|
|
@@ -333,13 +333,13 @@ async onChatMessage(onFinish, options) {
|
|
|
333
333
|
|
|
334
334
|
## API Reference
|
|
335
335
|
|
|
336
|
-
### `AIChatAgent<Env, State>`
|
|
336
|
+
### `AIChatAgent<Env, State, Props>`
|
|
337
337
|
|
|
338
338
|
Extends `Agent` from the `agents` package.
|
|
339
339
|
|
|
340
340
|
| Property / Method | Type | Description |
|
|
341
341
|
| ------------------------------------ | ----------------------------- | ------------------------------------------------------------------------------------------------- |
|
|
342
|
-
| `messages` | `
|
|
342
|
+
| `messages` | `ChatMessage[]` | Current conversation messages (loaded from SQLite) |
|
|
343
343
|
| `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
|
|
344
344
|
| `messageConcurrency` | `MessageConcurrency` | Concurrency strategy for `sendMessage()` submits. Default: `"queue"` |
|
|
345
345
|
| `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
|
|
@@ -364,13 +364,13 @@ React hook for chat interactions. Wraps the AI SDK's `useChat` with WebSocket tr
|
|
|
364
364
|
| `resume` | `boolean` | Enable stream resumption. Default: `true` |
|
|
365
365
|
| `body` | `object \| () => object` | Custom data sent with every request (see below) |
|
|
366
366
|
| `prepareSendMessagesRequest` | `(options) => { body?, headers? }` | Advanced per-request customization |
|
|
367
|
-
| `getInitialMessages` | `(options) => Promise<
|
|
367
|
+
| `getInitialMessages` | `(options) => Promise<ChatMessage[]>` | Custom initial message loader |
|
|
368
368
|
|
|
369
369
|
**Returns:**
|
|
370
370
|
|
|
371
371
|
| Property | Type | Description |
|
|
372
372
|
| ------------------------- | ---------------------------------- | ------------------------------------------------------- |
|
|
373
|
-
| `messages` | `
|
|
373
|
+
| `messages` | `ChatMessage[]` | Chat messages |
|
|
374
374
|
| `sendMessage` | `(message) => void` | Send a message |
|
|
375
375
|
| `clearHistory` | `() => void` | Clear conversation |
|
|
376
376
|
| `addToolOutput` | `({ toolCallId, output }) => void` | Provide tool output |
|
|
@@ -380,11 +380,11 @@ React hook for chat interactions. Wraps the AI SDK's `useChat` with WebSocket tr
|
|
|
380
380
|
|
|
381
381
|
### Exports
|
|
382
382
|
|
|
383
|
-
| Import path | What it provides
|
|
384
|
-
| --------------------------- |
|
|
385
|
-
| `@cloudflare/ai-chat` | `AIChatAgent`, `createToolsFromClientSchemas`
|
|
386
|
-
| `@cloudflare/ai-chat/react` | `useAgentChat`
|
|
387
|
-
| `@cloudflare/ai-chat/types` | `MessageType`, `OutgoingMessage`, `IncomingMessage`
|
|
383
|
+
| Import path | What it provides |
|
|
384
|
+
| --------------------------- | ------------------------------------------------------------ |
|
|
385
|
+
| `@cloudflare/ai-chat` | `AIChatAgent`, `ChatMessage`, `createToolsFromClientSchemas` |
|
|
386
|
+
| `@cloudflare/ai-chat/react` | `useAgentChat` |
|
|
387
|
+
| `@cloudflare/ai-chat/types` | `MessageType`, `OutgoingMessage`, `IncomingMessage` |
|
|
388
388
|
|
|
389
389
|
## Examples
|
|
390
390
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,66 +1,24 @@
|
|
|
1
1
|
import { Agent, AgentContext, FiberRecoveryContext } from "agents";
|
|
2
2
|
import {
|
|
3
|
+
ChatRecoveryContext,
|
|
4
|
+
ChatRecoveryContext as ChatRecoveryContext$1,
|
|
5
|
+
ChatRecoveryOptions,
|
|
6
|
+
ChatRecoveryOptions as ChatRecoveryOptions$1,
|
|
7
|
+
ChatResponseResult,
|
|
8
|
+
ChatResponseResult as ChatResponseResult$1,
|
|
3
9
|
ClientToolSchema,
|
|
4
10
|
ClientToolSchema as ClientToolSchema$1,
|
|
5
|
-
|
|
11
|
+
MessageConcurrency,
|
|
12
|
+
MessageConcurrency as MessageConcurrency$1,
|
|
6
13
|
ResumableStream,
|
|
14
|
+
SaveMessagesResult,
|
|
15
|
+
SaveMessagesResult as SaveMessagesResult$1,
|
|
7
16
|
createToolsFromClientSchemas
|
|
8
17
|
} from "agents/chat";
|
|
9
18
|
import { StreamTextOnFinishCallback, ToolSet, UIMessage } from "ai";
|
|
10
19
|
|
|
11
20
|
//#region src/index.d.ts
|
|
12
|
-
|
|
13
|
-
* Context passed to `onChatRecovery` when an interrupted chat stream
|
|
14
|
-
* is detected after DO restart.
|
|
15
|
-
*/
|
|
16
|
-
type ChatRecoveryContext = {
|
|
17
|
-
/** Stream ID from the interrupted stream. */ streamId: string /** Request ID from the interrupted stream. */;
|
|
18
|
-
requestId: string /** Partial text extracted from stored chunks. */;
|
|
19
|
-
partialText: string /** Partial message parts reconstructed from chunks. */;
|
|
20
|
-
partialParts: MessagePart[] /** Checkpoint data from `this.stash()` during the interrupted stream. */;
|
|
21
|
-
recoveryData: unknown | null /** Current persisted messages. */;
|
|
22
|
-
messages: UIMessage[] /** Custom body from the last chat request. */;
|
|
23
|
-
lastBody?: Record<
|
|
24
|
-
string,
|
|
25
|
-
unknown
|
|
26
|
-
> /** Client tool schemas from the last chat request. */;
|
|
27
|
-
lastClientTools?: ClientToolSchema$1[];
|
|
28
|
-
/**
|
|
29
|
-
* Epoch milliseconds when the underlying fiber was started. Compare against
|
|
30
|
-
* `Date.now()` to suppress continuations for turns that have been orphaned
|
|
31
|
-
* too long to safely replay.
|
|
32
|
-
*/
|
|
33
|
-
createdAt: number;
|
|
34
|
-
};
|
|
35
|
-
/**
|
|
36
|
-
* Options returned from `onChatRecovery` to control recovery behavior.
|
|
37
|
-
*/
|
|
38
|
-
type ChatRecoveryOptions = {
|
|
39
|
-
/** Save the partial response from stored chunks. Default: true. */ persist?: boolean /** Schedule a continuation via continueLastTurn(). Default: true. */;
|
|
40
|
-
continue?: boolean;
|
|
41
|
-
};
|
|
42
|
-
type MessageConcurrency =
|
|
43
|
-
| "queue"
|
|
44
|
-
| "latest"
|
|
45
|
-
| "merge"
|
|
46
|
-
| "drop"
|
|
47
|
-
| {
|
|
48
|
-
strategy: "debounce";
|
|
49
|
-
debounceMs?: number;
|
|
50
|
-
};
|
|
51
|
-
/**
|
|
52
|
-
* Result passed to the `onChatResponse` lifecycle hook after a chat turn completes.
|
|
53
|
-
*/
|
|
54
|
-
type ChatResponseResult = {
|
|
55
|
-
/** The finalized assistant message from this turn. */ message: UIMessage /** The request ID associated with this turn. */;
|
|
56
|
-
requestId: string /** Whether this turn was a continuation of a previous assistant turn. */;
|
|
57
|
-
continuation: boolean /** How the turn ended. */;
|
|
58
|
-
status:
|
|
59
|
-
| "completed"
|
|
60
|
-
| "error"
|
|
61
|
-
| "aborted" /** Error message when `status` is `"error"`. */;
|
|
62
|
-
error?: string;
|
|
63
|
-
};
|
|
21
|
+
type ChatMessage = UIMessage;
|
|
64
22
|
/**
|
|
65
23
|
* Options passed to the onChatMessage handler.
|
|
66
24
|
*/
|
|
@@ -110,21 +68,15 @@ type OnChatMessageOptions = {
|
|
|
110
68
|
*/
|
|
111
69
|
continuation?: boolean;
|
|
112
70
|
};
|
|
113
|
-
/**
|
|
114
|
-
* Result returned by `saveMessages()`.
|
|
115
|
-
*/
|
|
116
|
-
type SaveMessagesResult = {
|
|
117
|
-
/** Server-generated request ID for the chat turn. */ requestId: string /** Whether the turn ran or was skipped (e.g. because the chat was cleared). */;
|
|
118
|
-
status: "completed" | "skipped";
|
|
119
|
-
};
|
|
120
71
|
/**
|
|
121
72
|
* Extension of Agent with built-in chat capabilities
|
|
122
73
|
* @template Env Environment type containing bindings
|
|
123
74
|
*/
|
|
124
75
|
declare class AIChatAgent<
|
|
125
76
|
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
126
|
-
State = unknown
|
|
127
|
-
|
|
77
|
+
State = unknown,
|
|
78
|
+
Props extends Record<string, unknown> = Record<string, unknown>
|
|
79
|
+
> extends Agent<Env, State, Props> {
|
|
128
80
|
/**
|
|
129
81
|
* Registry of per-request AbortControllers.
|
|
130
82
|
* Used to propagate cancellation signals for any external calls made by the agent.
|
|
@@ -268,7 +220,7 @@ declare class AIChatAgent<
|
|
|
268
220
|
* programmatic `saveMessages()` calls keep their existing serialized
|
|
269
221
|
* behavior.
|
|
270
222
|
*/
|
|
271
|
-
messageConcurrency: MessageConcurrency;
|
|
223
|
+
messageConcurrency: MessageConcurrency$1;
|
|
272
224
|
/**
|
|
273
225
|
* When enabled, waits for all MCP server connections to be ready before
|
|
274
226
|
* calling `onChatMessage`. This prevents the race condition where
|
|
@@ -301,7 +253,14 @@ declare class AIChatAgent<
|
|
|
301
253
|
| {
|
|
302
254
|
timeout: number;
|
|
303
255
|
};
|
|
304
|
-
/**
|
|
256
|
+
/**
|
|
257
|
+
* Array of chat messages for the current conversation.
|
|
258
|
+
*
|
|
259
|
+
* Public and mutable for backwards compatibility. Framework code
|
|
260
|
+
* generally writes through `saveMessages` / `persistMessages`, but
|
|
261
|
+
* existing subclasses may still assign `this.messages = [...]` or
|
|
262
|
+
* mutate the array directly.
|
|
263
|
+
*/
|
|
305
264
|
messages: UIMessage[];
|
|
306
265
|
constructor(ctx: AgentContext, env: Env);
|
|
307
266
|
private _flushAwaitingStreamStartConnections;
|
|
@@ -367,6 +326,17 @@ declare class AIChatAgent<
|
|
|
367
326
|
private _loadMessagesFromDb;
|
|
368
327
|
private _tryCatchChat;
|
|
369
328
|
private isChatTurnActive;
|
|
329
|
+
/**
|
|
330
|
+
* Wait until the agent is fully idle — both the turn queue is drained
|
|
331
|
+
* AND no submits are in flight between the concurrency decision and
|
|
332
|
+
* `_runExclusiveChatTurn` (mid-`persistMessages` etc.).
|
|
333
|
+
*
|
|
334
|
+
* Just awaiting `_turnQueue.waitForIdle()` would miss submits whose
|
|
335
|
+
* handlers have bumped `_latestOverlappingSubmitSequence` and
|
|
336
|
+
* incremented `_pendingEnqueueCount` but haven't yet reached
|
|
337
|
+
* `_runExclusiveChatTurn` — those would race with anything calling
|
|
338
|
+
* `waitForIdle()` (tests, `waitUntilStable`, recovery code).
|
|
339
|
+
*/
|
|
370
340
|
private waitForIdle;
|
|
371
341
|
private _normalizeMessageConcurrency;
|
|
372
342
|
private _getSubmitConcurrencyDecision;
|
|
@@ -449,7 +419,7 @@ declare class AIChatAgent<
|
|
|
449
419
|
* }
|
|
450
420
|
* ```
|
|
451
421
|
*/
|
|
452
|
-
protected onChatResponse(_result: ChatResponseResult): void | Promise<void>;
|
|
422
|
+
protected onChatResponse(_result: ChatResponseResult$1): void | Promise<void>;
|
|
453
423
|
/**
|
|
454
424
|
* Override this method to apply custom transformations to messages before
|
|
455
425
|
* they are persisted to storage. This hook runs **after** the built-in
|
|
@@ -504,8 +474,10 @@ declare class AIChatAgent<
|
|
|
504
474
|
saveMessages(
|
|
505
475
|
messages:
|
|
506
476
|
| UIMessage[]
|
|
507
|
-
| ((
|
|
508
|
-
|
|
477
|
+
| ((
|
|
478
|
+
currentMessages: readonly UIMessage[]
|
|
479
|
+
) => UIMessage[] | Promise<UIMessage[]>)
|
|
480
|
+
): Promise<SaveMessagesResult$1>;
|
|
509
481
|
/**
|
|
510
482
|
* Trigger a continuation of the last assistant message without inserting
|
|
511
483
|
* a new user message. The LLM sees the full conversation (including the
|
|
@@ -520,7 +492,7 @@ declare class AIChatAgent<
|
|
|
520
492
|
*/
|
|
521
493
|
protected continueLastTurn(
|
|
522
494
|
body?: Record<string, unknown>
|
|
523
|
-
): Promise<SaveMessagesResult>;
|
|
495
|
+
): Promise<SaveMessagesResult$1>;
|
|
524
496
|
/**
|
|
525
497
|
* Context passed to `onChatRecovery` when an interrupted chat stream
|
|
526
498
|
* is detected after DO restart.
|
|
@@ -546,8 +518,8 @@ declare class AIChatAgent<
|
|
|
546
518
|
* during streaming (e.g., OpenAI `responseId`).
|
|
547
519
|
*/
|
|
548
520
|
protected onChatRecovery(
|
|
549
|
-
_ctx: ChatRecoveryContext
|
|
550
|
-
): Promise<ChatRecoveryOptions>;
|
|
521
|
+
_ctx: ChatRecoveryContext$1
|
|
522
|
+
): Promise<ChatRecoveryOptions$1>;
|
|
551
523
|
_chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
|
|
552
524
|
/**
|
|
553
525
|
* Extract partial text and parts from stored stream chunks.
|
|
@@ -703,13 +675,14 @@ declare class AIChatAgent<
|
|
|
703
675
|
//#endregion
|
|
704
676
|
export {
|
|
705
677
|
AIChatAgent,
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
678
|
+
ChatMessage,
|
|
679
|
+
type ChatRecoveryContext,
|
|
680
|
+
type ChatRecoveryOptions,
|
|
681
|
+
type ChatResponseResult,
|
|
709
682
|
type ClientToolSchema,
|
|
710
|
-
MessageConcurrency,
|
|
683
|
+
type MessageConcurrency,
|
|
711
684
|
OnChatMessageOptions,
|
|
712
|
-
SaveMessagesResult,
|
|
685
|
+
type SaveMessagesResult,
|
|
713
686
|
createToolsFromClientSchemas
|
|
714
687
|
};
|
|
715
688
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "./types.js";
|
|
2
2
|
import { autoTransformMessages } from "./ai-chat-v5-migration.js";
|
|
3
3
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
4
4
|
import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, sanitizeMessage } from "agents/chat";
|
|
@@ -179,6 +179,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
179
179
|
this.maxPersistedMessages = void 0;
|
|
180
180
|
this.messageConcurrency = "queue";
|
|
181
181
|
this.waitForMcpConnections = { timeout: 1e4 };
|
|
182
|
+
this.messages = [];
|
|
182
183
|
this.sql`create table if not exists cf_ai_chat_agent_messages (
|
|
183
184
|
id text primary key,
|
|
184
185
|
message text not null,
|
|
@@ -190,7 +191,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
190
191
|
)`;
|
|
191
192
|
this._restoreRequestContext();
|
|
192
193
|
this._resumableStream = new ResumableStream(this.sql.bind(this));
|
|
193
|
-
|
|
194
|
+
const rawMessages = this._loadMessagesFromDb();
|
|
195
|
+
this.messages = autoTransformMessages(rawMessages);
|
|
194
196
|
this._abortRegistry = new AbortRegistry();
|
|
195
197
|
const _onConnect = this.onConnect.bind(this);
|
|
196
198
|
this.onConnect = async (connection, ctx) => {
|
|
@@ -214,7 +216,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
214
216
|
} catch (_error) {
|
|
215
217
|
return _onMessage(connection, message);
|
|
216
218
|
}
|
|
217
|
-
if (data.type ===
|
|
219
|
+
if (data.type === "cf_agent_use_chat_request" && data.init.method === "POST") {
|
|
218
220
|
const { body } = data.init;
|
|
219
221
|
if (!body) {
|
|
220
222
|
console.warn("[AIChatAgent] Received chat request with empty body, ignoring");
|
|
@@ -244,7 +246,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
244
246
|
try {
|
|
245
247
|
this._broadcastChatMessage({
|
|
246
248
|
messages: transformedMessages,
|
|
247
|
-
type:
|
|
249
|
+
type: "cf_agent_chat_messages"
|
|
248
250
|
}, [connection.id]);
|
|
249
251
|
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
250
252
|
if (concurrencyDecision.mergeQueuedMessages) await this._mergeQueuedUserMessages(epoch);
|
|
@@ -308,7 +310,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
308
310
|
body: "No response was generated by the agent.",
|
|
309
311
|
done: true,
|
|
310
312
|
id: chatMessageId,
|
|
311
|
-
type:
|
|
313
|
+
type: "cf_agent_use_chat_response"
|
|
312
314
|
}, [connection.id]);
|
|
313
315
|
}
|
|
314
316
|
} finally {
|
|
@@ -326,7 +328,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
326
328
|
onStale: () => this._completeSkippedRequest(connection, chatMessageId)
|
|
327
329
|
});
|
|
328
330
|
}
|
|
329
|
-
if (data.type ===
|
|
331
|
+
if (data.type === "cf_agent_chat_clear") {
|
|
330
332
|
this.resetTurnState();
|
|
331
333
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
332
334
|
this._resumableStream.clearAll();
|
|
@@ -336,28 +338,28 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
336
338
|
this._persistRequestContext();
|
|
337
339
|
this._persistedMessageCache.clear();
|
|
338
340
|
this.messages = [];
|
|
339
|
-
this._broadcastChatMessage({ type:
|
|
341
|
+
this._broadcastChatMessage({ type: "cf_agent_chat_clear" }, [connection.id]);
|
|
340
342
|
this._emit("message:clear");
|
|
341
343
|
return;
|
|
342
344
|
}
|
|
343
|
-
if (data.type ===
|
|
345
|
+
if (data.type === "cf_agent_chat_messages") {
|
|
344
346
|
const transformedMessages = autoTransformMessages(data.messages);
|
|
345
347
|
await this.persistMessages(transformedMessages, [connection.id]);
|
|
346
348
|
return;
|
|
347
349
|
}
|
|
348
|
-
if (data.type ===
|
|
350
|
+
if (data.type === "cf_agent_chat_request_cancel") {
|
|
349
351
|
this._abortRegistry.cancel(data.id);
|
|
350
352
|
this._emit("message:cancel", { requestId: data.id });
|
|
351
353
|
return;
|
|
352
354
|
}
|
|
353
|
-
if (data.type ===
|
|
354
|
-
if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) connection.send(JSON.stringify({ type:
|
|
355
|
+
if (data.type === "cf_agent_stream_resume_request") {
|
|
356
|
+
if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) connection.send(JSON.stringify({ type: "cf_agent_stream_resume_none" }));
|
|
355
357
|
else this._notifyStreamResuming(connection);
|
|
356
358
|
else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
|
|
357
|
-
else connection.send(JSON.stringify({ type:
|
|
359
|
+
else connection.send(JSON.stringify({ type: "cf_agent_stream_resume_none" }));
|
|
358
360
|
return;
|
|
359
361
|
}
|
|
360
|
-
if (data.type ===
|
|
362
|
+
if (data.type === "cf_agent_stream_resume_ack") {
|
|
361
363
|
this._pendingResumeConnections.delete(connection.id);
|
|
362
364
|
if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
|
|
363
365
|
const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
|
|
@@ -365,7 +367,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
365
367
|
}
|
|
366
368
|
return;
|
|
367
369
|
}
|
|
368
|
-
if (data.type ===
|
|
370
|
+
if (data.type === "cf_agent_tool_result") {
|
|
369
371
|
const { toolCallId, toolName, output, state, errorText, autoContinue, clientTools } = data;
|
|
370
372
|
if (clientTools?.length) {
|
|
371
373
|
this._lastClientTools = clientTools;
|
|
@@ -384,7 +386,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
384
386
|
if (autoContinue) this._enqueueAutoContinuation(connection, clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
|
|
385
387
|
return;
|
|
386
388
|
}
|
|
387
|
-
if (data.type ===
|
|
389
|
+
if (data.type === "cf_agent_tool_approval") {
|
|
388
390
|
const { toolCallId, approved, autoContinue } = data;
|
|
389
391
|
this._emit("tool:approval", {
|
|
390
392
|
toolCallId,
|
|
@@ -453,7 +455,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
453
455
|
if (!this._resumableStream.hasActiveStream()) return;
|
|
454
456
|
this._pendingResumeConnections.add(connection.id);
|
|
455
457
|
connection.send(JSON.stringify({
|
|
456
|
-
type:
|
|
458
|
+
type: "cf_agent_stream_resuming",
|
|
457
459
|
id: this._resumableStream.activeRequestId
|
|
458
460
|
}));
|
|
459
461
|
}
|
|
@@ -599,7 +601,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
599
601
|
body,
|
|
600
602
|
done: false,
|
|
601
603
|
id: event.id,
|
|
602
|
-
type:
|
|
604
|
+
type: "cf_agent_use_chat_response",
|
|
603
605
|
...continuation && { continuation: true }
|
|
604
606
|
});
|
|
605
607
|
}
|
|
@@ -632,8 +634,23 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
632
634
|
isChatTurnActive() {
|
|
633
635
|
return this._turnQueue.isActive;
|
|
634
636
|
}
|
|
637
|
+
/**
|
|
638
|
+
* Wait until the agent is fully idle — both the turn queue is drained
|
|
639
|
+
* AND no submits are in flight between the concurrency decision and
|
|
640
|
+
* `_runExclusiveChatTurn` (mid-`persistMessages` etc.).
|
|
641
|
+
*
|
|
642
|
+
* Just awaiting `_turnQueue.waitForIdle()` would miss submits whose
|
|
643
|
+
* handlers have bumped `_latestOverlappingSubmitSequence` and
|
|
644
|
+
* incremented `_pendingEnqueueCount` but haven't yet reached
|
|
645
|
+
* `_runExclusiveChatTurn` — those would race with anything calling
|
|
646
|
+
* `waitForIdle()` (tests, `waitUntilStable`, recovery code).
|
|
647
|
+
*/
|
|
635
648
|
async waitForIdle() {
|
|
636
|
-
|
|
649
|
+
while (true) {
|
|
650
|
+
await this._turnQueue.waitForIdle();
|
|
651
|
+
if (this._pendingEnqueueCount === 0) return;
|
|
652
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
653
|
+
}
|
|
637
654
|
}
|
|
638
655
|
_normalizeMessageConcurrency() {
|
|
639
656
|
if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
|
|
@@ -796,13 +813,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
796
813
|
body: "",
|
|
797
814
|
done: true,
|
|
798
815
|
id: requestId,
|
|
799
|
-
type:
|
|
816
|
+
type: "cf_agent_use_chat_response"
|
|
800
817
|
});
|
|
801
818
|
}
|
|
802
819
|
_rollbackDroppedSubmit(connection) {
|
|
803
820
|
this._sendDirectMessage(connection, {
|
|
804
821
|
messages: this._messagesForClientSync(),
|
|
805
|
-
type:
|
|
822
|
+
type: "cf_agent_chat_messages"
|
|
806
823
|
});
|
|
807
824
|
}
|
|
808
825
|
/** `true` when an assistant message is waiting on a client tool result or approval. */
|
|
@@ -821,7 +838,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
821
838
|
async waitUntilStable(options) {
|
|
822
839
|
const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
|
|
823
840
|
while (true) {
|
|
824
|
-
|
|
841
|
+
while (true) {
|
|
842
|
+
if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
|
|
843
|
+
if (this._pendingEnqueueCount === 0) break;
|
|
844
|
+
if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, 5)), deadline) === TIMED_OUT) return false;
|
|
845
|
+
}
|
|
825
846
|
if (!this.hasPendingInteraction()) return true;
|
|
826
847
|
const pending = this._pendingInteractionPromise;
|
|
827
848
|
if (pending) {
|
|
@@ -1333,10 +1354,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1333
1354
|
}
|
|
1334
1355
|
}
|
|
1335
1356
|
if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
|
|
1336
|
-
|
|
1357
|
+
const persisted = this._loadMessagesFromDb();
|
|
1358
|
+
this.messages = autoTransformMessages(persisted);
|
|
1337
1359
|
this._broadcastChatMessage({
|
|
1338
1360
|
messages: mergedMessages,
|
|
1339
|
-
type:
|
|
1361
|
+
type: "cf_agent_chat_messages"
|
|
1340
1362
|
}, excludeBroadcastIds);
|
|
1341
1363
|
}
|
|
1342
1364
|
/**
|
|
@@ -1629,7 +1651,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1629
1651
|
where id = ${message.id}
|
|
1630
1652
|
`;
|
|
1631
1653
|
this._persistedMessageCache.set(message.id, json);
|
|
1632
|
-
|
|
1654
|
+
const persisted = this._loadMessagesFromDb();
|
|
1655
|
+
this.messages = autoTransformMessages(persisted);
|
|
1633
1656
|
}
|
|
1634
1657
|
}
|
|
1635
1658
|
if (!updated) {
|
|
@@ -1637,13 +1660,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1637
1660
|
return false;
|
|
1638
1661
|
}
|
|
1639
1662
|
if (isStreamingMessage) this._broadcastChatMessage({
|
|
1640
|
-
type:
|
|
1663
|
+
type: "cf_agent_message_updated",
|
|
1641
1664
|
message
|
|
1642
1665
|
});
|
|
1643
1666
|
else {
|
|
1644
1667
|
const broadcastMessage = this._findMessageByToolCallId(toolCallId);
|
|
1645
1668
|
if (broadcastMessage) this._broadcastChatMessage({
|
|
1646
|
-
type:
|
|
1669
|
+
type: "cf_agent_message_updated",
|
|
1647
1670
|
message: broadcastMessage
|
|
1648
1671
|
});
|
|
1649
1672
|
}
|
|
@@ -1704,7 +1727,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1704
1727
|
body: "",
|
|
1705
1728
|
done: true,
|
|
1706
1729
|
id,
|
|
1707
|
-
type:
|
|
1730
|
+
type: "cf_agent_use_chat_response",
|
|
1708
1731
|
...continuation && { continuation: true }
|
|
1709
1732
|
});
|
|
1710
1733
|
return "completed";
|
|
@@ -1791,7 +1814,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1791
1814
|
body: data.errorText ?? JSON.stringify(data),
|
|
1792
1815
|
done: false,
|
|
1793
1816
|
id,
|
|
1794
|
-
type:
|
|
1817
|
+
type: "cf_agent_use_chat_response"
|
|
1795
1818
|
});
|
|
1796
1819
|
break;
|
|
1797
1820
|
}
|
|
@@ -1814,7 +1837,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1814
1837
|
body: chunkBody,
|
|
1815
1838
|
done: false,
|
|
1816
1839
|
id,
|
|
1817
|
-
type:
|
|
1840
|
+
type: "cf_agent_use_chat_response",
|
|
1818
1841
|
...continuation && { continuation: true }
|
|
1819
1842
|
});
|
|
1820
1843
|
} catch (_error) {}
|
|
@@ -1826,7 +1849,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1826
1849
|
body: "",
|
|
1827
1850
|
done: true,
|
|
1828
1851
|
id,
|
|
1829
|
-
type:
|
|
1852
|
+
type: "cf_agent_use_chat_response",
|
|
1830
1853
|
...continuation && { continuation: true }
|
|
1831
1854
|
});
|
|
1832
1855
|
return "aborted";
|
|
@@ -1880,7 +1903,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1880
1903
|
body: "",
|
|
1881
1904
|
done: true,
|
|
1882
1905
|
id,
|
|
1883
|
-
type:
|
|
1906
|
+
type: "cf_agent_use_chat_response",
|
|
1884
1907
|
...continuation && { continuation: true }
|
|
1885
1908
|
});
|
|
1886
1909
|
return "completed";
|
|
@@ -1907,7 +1930,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1907
1930
|
body: "",
|
|
1908
1931
|
done: true,
|
|
1909
1932
|
id,
|
|
1910
|
-
type:
|
|
1933
|
+
type: "cf_agent_use_chat_response",
|
|
1911
1934
|
...continuation && { continuation: true }
|
|
1912
1935
|
});
|
|
1913
1936
|
return "aborted";
|
|
@@ -1946,7 +1969,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1946
1969
|
body: "",
|
|
1947
1970
|
done: true,
|
|
1948
1971
|
id,
|
|
1949
|
-
type:
|
|
1972
|
+
type: "cf_agent_use_chat_response",
|
|
1950
1973
|
...continuation && { continuation: true }
|
|
1951
1974
|
});
|
|
1952
1975
|
this._activateDeferredAutoContinuation();
|
|
@@ -1971,7 +1994,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1971
1994
|
done: true,
|
|
1972
1995
|
error: true,
|
|
1973
1996
|
id,
|
|
1974
|
-
type:
|
|
1997
|
+
type: "cf_agent_use_chat_response",
|
|
1975
1998
|
...continuation && { continuation: true }
|
|
1976
1999
|
});
|
|
1977
2000
|
this._emit("message:error", { error: error instanceof Error ? error.message : String(error) });
|