@cloudflare/ai-chat 0.2.0 → 0.2.2
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-qqP10Pcu.d.ts} +23 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +73 -26
- package/dist/index.js.map +1 -1
- package/dist/react.js +123 -5
- package/dist/react.js.map +1 -1
- package/package.json +3 -3
|
@@ -278,6 +278,24 @@ 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 originating client
|
|
284
|
+
* asks to resume immediately after submitting tool output, before the server
|
|
285
|
+
* has 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 the originating client can attach to the upcoming continuation stream.
|
|
292
|
+
*/
|
|
293
|
+
private _pendingAutoContinuation;
|
|
294
|
+
/**
|
|
295
|
+
* Connection that initiated the pending auto-continuation.
|
|
296
|
+
* Only this connection should wait for the continuation stream to start.
|
|
297
|
+
*/
|
|
298
|
+
private _pendingAutoContinuationConnectionId;
|
|
281
299
|
/**
|
|
282
300
|
* Client tool schemas from the most recent chat request.
|
|
283
301
|
* Stored so they can be passed to onChatMessage during tool continuations.
|
|
@@ -353,6 +371,8 @@ declare class AIChatAgent<
|
|
|
353
371
|
/** Array of chat messages for the current conversation */
|
|
354
372
|
messages: UIMessage[];
|
|
355
373
|
constructor(ctx: AgentContext, env: Env);
|
|
374
|
+
private _flushAwaitingStreamStartConnections;
|
|
375
|
+
private _clearPendingAutoContinuation;
|
|
356
376
|
/**
|
|
357
377
|
* Notify a connection about an active stream that can be resumed.
|
|
358
378
|
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
@@ -544,6 +564,8 @@ declare class AIChatAgent<
|
|
|
544
564
|
* @returns The existing message if found, undefined otherwise
|
|
545
565
|
*/
|
|
546
566
|
private _findMessageByToolCallId;
|
|
567
|
+
private _findLastAssistantMessage;
|
|
568
|
+
private _createStreamingAssistantMessage;
|
|
547
569
|
/**
|
|
548
570
|
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
549
571
|
* data that should not be stored or sent back in subsequent requests.
|
|
@@ -696,4 +718,4 @@ export {
|
|
|
696
718
|
OnChatMessageOptions as r,
|
|
697
719
|
AIChatAgent as t
|
|
698
720
|
};
|
|
699
|
-
//# sourceMappingURL=index-
|
|
721
|
+
//# sourceMappingURL=index-qqP10Pcu.d.ts.map
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -418,6 +418,9 @@ 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;
|
|
423
|
+
this._pendingAutoContinuationConnectionId = null;
|
|
421
424
|
this._persistedMessageCache = /* @__PURE__ */ new Map();
|
|
422
425
|
this.maxPersistedMessages = void 0;
|
|
423
426
|
this.waitForMcpConnections = { timeout: 1e4 };
|
|
@@ -442,6 +445,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
442
445
|
const _onClose = this.onClose.bind(this);
|
|
443
446
|
this.onClose = async (connection, code, reason, wasClean) => {
|
|
444
447
|
this._pendingResumeConnections.delete(connection.id);
|
|
448
|
+
this._awaitingStreamStartConnections.delete(connection.id);
|
|
449
|
+
if (this._pendingAutoContinuationConnectionId === connection.id) this._pendingAutoContinuationConnectionId = null;
|
|
445
450
|
return _onClose(connection, code, reason, wasClean);
|
|
446
451
|
};
|
|
447
452
|
const _onMessage = this.onMessage.bind(this);
|
|
@@ -516,6 +521,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
516
521
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
517
522
|
this._resumableStream.clearAll();
|
|
518
523
|
this._pendingResumeConnections.clear();
|
|
524
|
+
this._clearPendingAutoContinuation(true);
|
|
519
525
|
this._lastClientTools = void 0;
|
|
520
526
|
this._lastBody = void 0;
|
|
521
527
|
this._persistRequestContext();
|
|
@@ -537,6 +543,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
537
543
|
}
|
|
538
544
|
if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
|
|
539
545
|
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
546
|
+
else if (this._pendingAutoContinuation && this._pendingAutoContinuationConnectionId === connection.id) this._awaitingStreamStartConnections.set(connection.id, connection);
|
|
540
547
|
else connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
|
|
541
548
|
return;
|
|
542
549
|
}
|
|
@@ -564,7 +571,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
564
571
|
applyPromise.finally(() => {
|
|
565
572
|
if (this._pendingInteractionPromise === applyPromise) this._pendingInteractionPromise = null;
|
|
566
573
|
}).catch(() => {});
|
|
567
|
-
if (autoContinue)
|
|
574
|
+
if (autoContinue) {
|
|
575
|
+
this._pendingAutoContinuation = true;
|
|
576
|
+
this._pendingAutoContinuationConnectionId = connection.id;
|
|
577
|
+
this._queueAutoContinuation(connection, nanoid(), clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
|
|
578
|
+
}
|
|
568
579
|
return;
|
|
569
580
|
}
|
|
570
581
|
if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
|
|
@@ -578,7 +589,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
578
589
|
approvalPromise.finally(() => {
|
|
579
590
|
if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
|
|
580
591
|
}).catch(() => {});
|
|
581
|
-
if (autoContinue)
|
|
592
|
+
if (autoContinue) {
|
|
593
|
+
this._pendingAutoContinuation = true;
|
|
594
|
+
this._pendingAutoContinuationConnectionId = connection.id;
|
|
595
|
+
this._queueAutoContinuation(connection, nanoid(), this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
|
|
596
|
+
}
|
|
582
597
|
return;
|
|
583
598
|
}
|
|
584
599
|
}
|
|
@@ -592,6 +607,17 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
592
607
|
});
|
|
593
608
|
};
|
|
594
609
|
}
|
|
610
|
+
_flushAwaitingStreamStartConnections() {
|
|
611
|
+
if (!this._resumableStream.hasActiveStream()) return;
|
|
612
|
+
for (const connection of this._awaitingStreamStartConnections.values()) this._notifyStreamResuming(connection);
|
|
613
|
+
this._awaitingStreamStartConnections.clear();
|
|
614
|
+
}
|
|
615
|
+
_clearPendingAutoContinuation(sendNone = false) {
|
|
616
|
+
this._pendingAutoContinuation = false;
|
|
617
|
+
this._pendingAutoContinuationConnectionId = null;
|
|
618
|
+
if (sendNone) for (const connection of this._awaitingStreamStartConnections.values()) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
|
|
619
|
+
this._awaitingStreamStartConnections.clear();
|
|
620
|
+
}
|
|
595
621
|
/**
|
|
596
622
|
* Notify a connection about an active stream that can be resumed.
|
|
597
623
|
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
@@ -615,7 +641,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
615
641
|
}
|
|
616
642
|
/** @internal Delegate to _resumableStream */
|
|
617
643
|
_startStream(requestId) {
|
|
618
|
-
|
|
644
|
+
const streamId = this._resumableStream.start(requestId);
|
|
645
|
+
this._pendingAutoContinuation = false;
|
|
646
|
+
this._pendingAutoContinuationConnectionId = null;
|
|
647
|
+
this._flushAwaitingStreamStartConnections();
|
|
648
|
+
return streamId;
|
|
619
649
|
}
|
|
620
650
|
/** @internal Delegate to _resumableStream */
|
|
621
651
|
_completeStream(streamId) {
|
|
@@ -835,10 +865,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
835
865
|
}
|
|
836
866
|
_queueAutoContinuation(connection, requestId, clientTools, body, errorPrefix, prerequisite) {
|
|
837
867
|
const epoch = this._chatEpoch;
|
|
838
|
-
this._runExclusiveChatTurn(requestId, async () => {
|
|
839
|
-
if (this._chatEpoch !== epoch)
|
|
868
|
+
this.keepAliveWhile(() => this._runExclusiveChatTurn(requestId, async () => {
|
|
869
|
+
if (this._chatEpoch !== epoch) {
|
|
870
|
+
this._clearPendingAutoContinuation(true);
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
840
873
|
if (prerequisite) {
|
|
841
|
-
if (!await prerequisite)
|
|
874
|
+
if (!await prerequisite) {
|
|
875
|
+
this._clearPendingAutoContinuation(true);
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
842
878
|
}
|
|
843
879
|
const abortSignal = this._getAbortSignal(requestId);
|
|
844
880
|
return this._tryCatchChat(async () => {
|
|
@@ -858,9 +894,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
858
894
|
continuation: true,
|
|
859
895
|
chatMessageId: requestId
|
|
860
896
|
});
|
|
897
|
+
else this._clearPendingAutoContinuation(true);
|
|
861
898
|
});
|
|
862
899
|
});
|
|
863
|
-
}).catch((error) => {
|
|
900
|
+
})).catch((error) => {
|
|
901
|
+
this._clearPendingAutoContinuation(true);
|
|
864
902
|
console.error(errorPrefix, error);
|
|
865
903
|
});
|
|
866
904
|
}
|
|
@@ -1099,6 +1137,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1099
1137
|
for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) return msg;
|
|
1100
1138
|
}
|
|
1101
1139
|
}
|
|
1140
|
+
_findLastAssistantMessage() {
|
|
1141
|
+
for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") return this.messages[i];
|
|
1142
|
+
}
|
|
1143
|
+
_createStreamingAssistantMessage(continuation) {
|
|
1144
|
+
if (continuation) {
|
|
1145
|
+
const lastAssistant = this._findLastAssistantMessage();
|
|
1146
|
+
if (lastAssistant) return structuredClone(lastAssistant);
|
|
1147
|
+
}
|
|
1148
|
+
return {
|
|
1149
|
+
id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
|
|
1150
|
+
role: "assistant",
|
|
1151
|
+
parts: []
|
|
1152
|
+
};
|
|
1153
|
+
}
|
|
1102
1154
|
/**
|
|
1103
1155
|
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
1104
1156
|
* data that should not be stored or sent back in subsequent requests.
|
|
@@ -1499,7 +1551,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1499
1551
|
}
|
|
1500
1552
|
if (!handled) switch (data.type) {
|
|
1501
1553
|
case "start":
|
|
1502
|
-
if (data.messageId != null) message.id = data.messageId;
|
|
1554
|
+
if (data.messageId != null && !continuation) message.id = data.messageId;
|
|
1503
1555
|
if (data.messageMetadata != null) message.metadata = message.metadata ? {
|
|
1504
1556
|
...message.metadata,
|
|
1505
1557
|
...data.messageMetadata
|
|
@@ -1651,6 +1703,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1651
1703
|
const abortSignal = chatMessageId ? this._chatMessageAbortControllers.get(chatMessageId)?.signal : void 0;
|
|
1652
1704
|
return this.keepAliveWhile(() => this._tryCatchChat(async () => {
|
|
1653
1705
|
if (!response.body) {
|
|
1706
|
+
this._clearPendingAutoContinuation(true);
|
|
1654
1707
|
this._broadcastChatMessage({
|
|
1655
1708
|
body: "",
|
|
1656
1709
|
done: true,
|
|
@@ -1662,11 +1715,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1662
1715
|
}
|
|
1663
1716
|
const streamId = this._startStream(id);
|
|
1664
1717
|
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
|
-
};
|
|
1718
|
+
const message = this._createStreamingAssistantMessage(continuation);
|
|
1670
1719
|
this._streamingMessage = message;
|
|
1671
1720
|
const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
|
|
1672
1721
|
const streamCompleted = { value: false };
|
|
@@ -1699,22 +1748,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1699
1748
|
}
|
|
1700
1749
|
}
|
|
1701
1750
|
if (message.parts.length > 0) if (earlyPersistedId) {
|
|
1702
|
-
const
|
|
1751
|
+
const persistedMessage = {
|
|
1752
|
+
...message,
|
|
1753
|
+
id: earlyPersistedId
|
|
1754
|
+
};
|
|
1755
|
+
const existingIdx = this.messages.findIndex((msg) => msg.id === earlyPersistedId);
|
|
1756
|
+
const updatedMessages = [...this.messages];
|
|
1757
|
+
if (existingIdx >= 0) updatedMessages[existingIdx] = persistedMessage;
|
|
1758
|
+
else updatedMessages.push(persistedMessage);
|
|
1703
1759
|
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
1704
1760
|
} 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
|
-
};
|
|
1761
|
+
const existingIdx = this.messages.findIndex((msg) => msg.id === message.id);
|
|
1762
|
+
if (existingIdx >= 0) {
|
|
1716
1763
|
const updatedMessages = [...this.messages];
|
|
1717
|
-
updatedMessages[
|
|
1764
|
+
updatedMessages[existingIdx] = message;
|
|
1718
1765
|
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
1719
1766
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|
|
1720
1767
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|