@cloudflare/ai-chat 0.2.0 → 0.2.1
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/dist/experimental/forever.d.ts +1 -1
- package/dist/{index-B09l5oPB.d.ts → index-BbdbMsrQ.d.ts} +18 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +67 -26
- package/dist/index.js.map +1 -1
- package/dist/react.js +123 -5
- package/dist/react.js.map +1 -1
- package/package.json +1 -1
|
@@ -278,6 +278,19 @@ declare class AIChatAgent<
|
|
|
278
278
|
* @internal
|
|
279
279
|
*/
|
|
280
280
|
private _pendingResumeConnections;
|
|
281
|
+
/**
|
|
282
|
+
* Connections waiting for a stream to start after requesting resume.
|
|
283
|
+
* Used for client-side tool auto-continuations where the client asks to
|
|
284
|
+
* resume immediately after submitting tool output, before the server has
|
|
285
|
+
* started streaming the continuation turn.
|
|
286
|
+
*/
|
|
287
|
+
private _awaitingStreamStartConnections;
|
|
288
|
+
/**
|
|
289
|
+
* True while an auto-continuation turn has been queued but has not yet
|
|
290
|
+
* started streaming. This suppresses immediate STREAM_RESUME_NONE replies
|
|
291
|
+
* so clients can attach to the upcoming continuation stream.
|
|
292
|
+
*/
|
|
293
|
+
private _pendingAutoContinuation;
|
|
281
294
|
/**
|
|
282
295
|
* Client tool schemas from the most recent chat request.
|
|
283
296
|
* Stored so they can be passed to onChatMessage during tool continuations.
|
|
@@ -353,6 +366,8 @@ declare class AIChatAgent<
|
|
|
353
366
|
/** Array of chat messages for the current conversation */
|
|
354
367
|
messages: UIMessage[];
|
|
355
368
|
constructor(ctx: AgentContext, env: Env);
|
|
369
|
+
private _flushAwaitingStreamStartConnections;
|
|
370
|
+
private _clearPendingAutoContinuation;
|
|
356
371
|
/**
|
|
357
372
|
* Notify a connection about an active stream that can be resumed.
|
|
358
373
|
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
@@ -544,6 +559,8 @@ declare class AIChatAgent<
|
|
|
544
559
|
* @returns The existing message if found, undefined otherwise
|
|
545
560
|
*/
|
|
546
561
|
private _findMessageByToolCallId;
|
|
562
|
+
private _findLastAssistantMessage;
|
|
563
|
+
private _createStreamingAssistantMessage;
|
|
547
564
|
/**
|
|
548
565
|
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
549
566
|
* data that should not be stored or sent back in subsequent requests.
|
|
@@ -696,4 +713,4 @@ export {
|
|
|
696
713
|
OnChatMessageOptions as r,
|
|
697
714
|
AIChatAgent as t
|
|
698
715
|
};
|
|
699
|
-
//# sourceMappingURL=index-
|
|
716
|
+
//# sourceMappingURL=index-BbdbMsrQ.d.ts.map
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -418,6 +418,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
418
418
|
this._activeChatTurnRequestId = null;
|
|
419
419
|
this._chatEpoch = 0;
|
|
420
420
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
421
|
+
this._awaitingStreamStartConnections = /* @__PURE__ */ new Map();
|
|
422
|
+
this._pendingAutoContinuation = false;
|
|
421
423
|
this._persistedMessageCache = /* @__PURE__ */ new Map();
|
|
422
424
|
this.maxPersistedMessages = void 0;
|
|
423
425
|
this.waitForMcpConnections = { timeout: 1e4 };
|
|
@@ -442,6 +444,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
442
444
|
const _onClose = this.onClose.bind(this);
|
|
443
445
|
this.onClose = async (connection, code, reason, wasClean) => {
|
|
444
446
|
this._pendingResumeConnections.delete(connection.id);
|
|
447
|
+
this._awaitingStreamStartConnections.delete(connection.id);
|
|
445
448
|
return _onClose(connection, code, reason, wasClean);
|
|
446
449
|
};
|
|
447
450
|
const _onMessage = this.onMessage.bind(this);
|
|
@@ -516,6 +519,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
516
519
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
517
520
|
this._resumableStream.clearAll();
|
|
518
521
|
this._pendingResumeConnections.clear();
|
|
522
|
+
this._clearPendingAutoContinuation(true);
|
|
519
523
|
this._lastClientTools = void 0;
|
|
520
524
|
this._lastBody = void 0;
|
|
521
525
|
this._persistRequestContext();
|
|
@@ -537,6 +541,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
537
541
|
}
|
|
538
542
|
if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
|
|
539
543
|
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
544
|
+
else if (this._pendingAutoContinuation) this._awaitingStreamStartConnections.set(connection.id, connection);
|
|
540
545
|
else connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
|
|
541
546
|
return;
|
|
542
547
|
}
|
|
@@ -564,7 +569,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
564
569
|
applyPromise.finally(() => {
|
|
565
570
|
if (this._pendingInteractionPromise === applyPromise) this._pendingInteractionPromise = null;
|
|
566
571
|
}).catch(() => {});
|
|
567
|
-
if (autoContinue)
|
|
572
|
+
if (autoContinue) {
|
|
573
|
+
this._pendingAutoContinuation = true;
|
|
574
|
+
this._queueAutoContinuation(connection, nanoid(), clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
|
|
575
|
+
}
|
|
568
576
|
return;
|
|
569
577
|
}
|
|
570
578
|
if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
|
|
@@ -578,7 +586,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
578
586
|
approvalPromise.finally(() => {
|
|
579
587
|
if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
|
|
580
588
|
}).catch(() => {});
|
|
581
|
-
if (autoContinue)
|
|
589
|
+
if (autoContinue) {
|
|
590
|
+
this._pendingAutoContinuation = true;
|
|
591
|
+
this._queueAutoContinuation(connection, nanoid(), this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
|
|
592
|
+
}
|
|
582
593
|
return;
|
|
583
594
|
}
|
|
584
595
|
}
|
|
@@ -592,6 +603,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
592
603
|
});
|
|
593
604
|
};
|
|
594
605
|
}
|
|
606
|
+
_flushAwaitingStreamStartConnections() {
|
|
607
|
+
if (!this._resumableStream.hasActiveStream()) return;
|
|
608
|
+
for (const connection of this._awaitingStreamStartConnections.values()) this._notifyStreamResuming(connection);
|
|
609
|
+
this._awaitingStreamStartConnections.clear();
|
|
610
|
+
}
|
|
611
|
+
_clearPendingAutoContinuation(sendNone = false) {
|
|
612
|
+
this._pendingAutoContinuation = false;
|
|
613
|
+
if (sendNone) for (const connection of this._awaitingStreamStartConnections.values()) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
|
|
614
|
+
this._awaitingStreamStartConnections.clear();
|
|
615
|
+
}
|
|
595
616
|
/**
|
|
596
617
|
* Notify a connection about an active stream that can be resumed.
|
|
597
618
|
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
@@ -615,7 +636,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
615
636
|
}
|
|
616
637
|
/** @internal Delegate to _resumableStream */
|
|
617
638
|
_startStream(requestId) {
|
|
618
|
-
|
|
639
|
+
const streamId = this._resumableStream.start(requestId);
|
|
640
|
+
this._pendingAutoContinuation = false;
|
|
641
|
+
this._flushAwaitingStreamStartConnections();
|
|
642
|
+
return streamId;
|
|
619
643
|
}
|
|
620
644
|
/** @internal Delegate to _resumableStream */
|
|
621
645
|
_completeStream(streamId) {
|
|
@@ -835,10 +859,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
835
859
|
}
|
|
836
860
|
_queueAutoContinuation(connection, requestId, clientTools, body, errorPrefix, prerequisite) {
|
|
837
861
|
const epoch = this._chatEpoch;
|
|
838
|
-
this._runExclusiveChatTurn(requestId, async () => {
|
|
839
|
-
if (this._chatEpoch !== epoch)
|
|
862
|
+
this.keepAliveWhile(() => this._runExclusiveChatTurn(requestId, async () => {
|
|
863
|
+
if (this._chatEpoch !== epoch) {
|
|
864
|
+
this._clearPendingAutoContinuation(true);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
840
867
|
if (prerequisite) {
|
|
841
|
-
if (!await prerequisite)
|
|
868
|
+
if (!await prerequisite) {
|
|
869
|
+
this._clearPendingAutoContinuation(true);
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
842
872
|
}
|
|
843
873
|
const abortSignal = this._getAbortSignal(requestId);
|
|
844
874
|
return this._tryCatchChat(async () => {
|
|
@@ -858,9 +888,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
858
888
|
continuation: true,
|
|
859
889
|
chatMessageId: requestId
|
|
860
890
|
});
|
|
891
|
+
else this._clearPendingAutoContinuation(true);
|
|
861
892
|
});
|
|
862
893
|
});
|
|
863
|
-
}).catch((error) => {
|
|
894
|
+
})).catch((error) => {
|
|
895
|
+
this._clearPendingAutoContinuation(true);
|
|
864
896
|
console.error(errorPrefix, error);
|
|
865
897
|
});
|
|
866
898
|
}
|
|
@@ -1099,6 +1131,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1099
1131
|
for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) return msg;
|
|
1100
1132
|
}
|
|
1101
1133
|
}
|
|
1134
|
+
_findLastAssistantMessage() {
|
|
1135
|
+
for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") return this.messages[i];
|
|
1136
|
+
}
|
|
1137
|
+
_createStreamingAssistantMessage(continuation) {
|
|
1138
|
+
if (continuation) {
|
|
1139
|
+
const lastAssistant = this._findLastAssistantMessage();
|
|
1140
|
+
if (lastAssistant) return structuredClone(lastAssistant);
|
|
1141
|
+
}
|
|
1142
|
+
return {
|
|
1143
|
+
id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
|
|
1144
|
+
role: "assistant",
|
|
1145
|
+
parts: []
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1102
1148
|
/**
|
|
1103
1149
|
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
1104
1150
|
* data that should not be stored or sent back in subsequent requests.
|
|
@@ -1499,7 +1545,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1499
1545
|
}
|
|
1500
1546
|
if (!handled) switch (data.type) {
|
|
1501
1547
|
case "start":
|
|
1502
|
-
if (data.messageId != null) message.id = data.messageId;
|
|
1548
|
+
if (data.messageId != null && !continuation) message.id = data.messageId;
|
|
1503
1549
|
if (data.messageMetadata != null) message.metadata = message.metadata ? {
|
|
1504
1550
|
...message.metadata,
|
|
1505
1551
|
...data.messageMetadata
|
|
@@ -1651,6 +1697,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1651
1697
|
const abortSignal = chatMessageId ? this._chatMessageAbortControllers.get(chatMessageId)?.signal : void 0;
|
|
1652
1698
|
return this.keepAliveWhile(() => this._tryCatchChat(async () => {
|
|
1653
1699
|
if (!response.body) {
|
|
1700
|
+
this._clearPendingAutoContinuation(true);
|
|
1654
1701
|
this._broadcastChatMessage({
|
|
1655
1702
|
body: "",
|
|
1656
1703
|
done: true,
|
|
@@ -1662,11 +1709,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1662
1709
|
}
|
|
1663
1710
|
const streamId = this._startStream(id);
|
|
1664
1711
|
const reader = response.body.getReader();
|
|
1665
|
-
const message =
|
|
1666
|
-
id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
|
|
1667
|
-
role: "assistant",
|
|
1668
|
-
parts: []
|
|
1669
|
-
};
|
|
1712
|
+
const message = this._createStreamingAssistantMessage(continuation);
|
|
1670
1713
|
this._streamingMessage = message;
|
|
1671
1714
|
const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
|
|
1672
1715
|
const streamCompleted = { value: false };
|
|
@@ -1699,22 +1742,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1699
1742
|
}
|
|
1700
1743
|
}
|
|
1701
1744
|
if (message.parts.length > 0) if (earlyPersistedId) {
|
|
1702
|
-
const
|
|
1745
|
+
const persistedMessage = {
|
|
1746
|
+
...message,
|
|
1747
|
+
id: earlyPersistedId
|
|
1748
|
+
};
|
|
1749
|
+
const existingIdx = this.messages.findIndex((msg) => msg.id === earlyPersistedId);
|
|
1750
|
+
const updatedMessages = [...this.messages];
|
|
1751
|
+
if (existingIdx >= 0) updatedMessages[existingIdx] = persistedMessage;
|
|
1752
|
+
else updatedMessages.push(persistedMessage);
|
|
1703
1753
|
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
1704
1754
|
} else if (continuation) {
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
lastAssistantIdx = i;
|
|
1708
|
-
break;
|
|
1709
|
-
}
|
|
1710
|
-
if (lastAssistantIdx >= 0) {
|
|
1711
|
-
const lastAssistant = this.messages[lastAssistantIdx];
|
|
1712
|
-
const mergedMessage = {
|
|
1713
|
-
...lastAssistant,
|
|
1714
|
-
parts: [...lastAssistant.parts, ...message.parts]
|
|
1715
|
-
};
|
|
1755
|
+
const existingIdx = this.messages.findIndex((msg) => msg.id === message.id);
|
|
1756
|
+
if (existingIdx >= 0) {
|
|
1716
1757
|
const updatedMessages = [...this.messages];
|
|
1717
|
-
updatedMessages[
|
|
1758
|
+
updatedMessages[existingIdx] = message;
|
|
1718
1759
|
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
1719
1760
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|
|
1720
1761
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|