@cloudflare/ai-chat 0.2.6 → 0.3.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/README.md +68 -10
- package/dist/experimental/forever.d.ts +1 -1
- package/dist/{index-C2k3fmRr.d.ts → index-BZiT3pOq.d.ts} +147 -7
- package/dist/index.d.ts +10 -4
- package/dist/index.js +397 -38
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +13 -0
- package/dist/react.js +140 -7
- package/dist/react.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -413,6 +413,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
413
413
|
static {
|
|
414
414
|
this.AUTO_CONTINUATION_COALESCE_MS = 10;
|
|
415
415
|
}
|
|
416
|
+
static {
|
|
417
|
+
this.MESSAGE_DEBOUNCE_MS = 750;
|
|
418
|
+
}
|
|
416
419
|
/** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
|
|
417
420
|
static _byteLength(s) {
|
|
418
421
|
return textEncoder.encode(s).byteLength;
|
|
@@ -420,11 +423,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
420
423
|
constructor(ctx, env) {
|
|
421
424
|
super(ctx, env);
|
|
422
425
|
this._streamingMessage = null;
|
|
426
|
+
this._pendingChatResponseResults = [];
|
|
427
|
+
this._insideResponseHook = false;
|
|
423
428
|
this._pendingInteractionPromise = null;
|
|
424
429
|
this._approvalPersistedMessageId = null;
|
|
425
430
|
this._chatTurnQueue = Promise.resolve();
|
|
426
431
|
this._activeChatTurnRequestId = null;
|
|
427
432
|
this._chatEpoch = 0;
|
|
433
|
+
this._queuedChatTurnCountsByEpoch = /* @__PURE__ */ new Map();
|
|
434
|
+
this._mergeQueuedUserStartIndexByEpoch = /* @__PURE__ */ new Map();
|
|
435
|
+
this._submitSequence = 0;
|
|
436
|
+
this._latestOverlappingSubmitSequence = 0;
|
|
437
|
+
this._activeDebounceTimer = null;
|
|
438
|
+
this._activeDebounceResolve = null;
|
|
428
439
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
429
440
|
this._awaitingStreamStartConnections = /* @__PURE__ */ new Map();
|
|
430
441
|
this._pendingAutoContinuation = false;
|
|
@@ -439,6 +450,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
439
450
|
this._deferredAutoContinuation = null;
|
|
440
451
|
this._persistedMessageCache = /* @__PURE__ */ new Map();
|
|
441
452
|
this.maxPersistedMessages = void 0;
|
|
453
|
+
this.messageConcurrency = "queue";
|
|
442
454
|
this.waitForMcpConnections = { timeout: 1e4 };
|
|
443
455
|
this.sql`create table if not exists cf_ai_chat_agent_messages (
|
|
444
456
|
id text primary key,
|
|
@@ -490,20 +502,59 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
490
502
|
}
|
|
491
503
|
const { messages, clientTools, trigger: _trigger, ...customBody } = parsed;
|
|
492
504
|
const chatMessageId = data.id;
|
|
505
|
+
const transformedMessages = autoTransformMessages(messages);
|
|
506
|
+
const requestTrigger = _trigger === "regenerate-message" ? "regenerate-message" : "submit-message";
|
|
507
|
+
const requestClientTools = clientTools?.length ? clientTools : void 0;
|
|
508
|
+
const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
509
|
+
const epoch = this._chatEpoch;
|
|
510
|
+
const concurrencyDecision = this._getSubmitConcurrencyDecision(requestTrigger);
|
|
511
|
+
if (concurrencyDecision.action === "drop") {
|
|
512
|
+
this._rollbackDroppedSubmit(connection);
|
|
513
|
+
this._completeSkippedRequest(connection, chatMessageId);
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
this._broadcastChatMessage({
|
|
517
|
+
messages: transformedMessages,
|
|
518
|
+
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
519
|
+
}, [connection.id]);
|
|
520
|
+
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
521
|
+
if (concurrencyDecision.mergeQueuedMessages) await this._mergeQueuedUserMessages(epoch);
|
|
493
522
|
return this._runExclusiveChatTurn(chatMessageId, async () => {
|
|
523
|
+
if (this._chatEpoch !== epoch) {
|
|
524
|
+
this._completeSkippedRequest(connection, chatMessageId);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
|
|
528
|
+
this._completeSkippedRequest(connection, chatMessageId);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (concurrencyDecision.debounceUntilMs !== null) {
|
|
532
|
+
await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
|
|
533
|
+
if (this._chatEpoch !== epoch) {
|
|
534
|
+
this._completeSkippedRequest(connection, chatMessageId);
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
|
|
538
|
+
this._completeSkippedRequest(connection, chatMessageId);
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
if (concurrencyDecision.mergeQueuedMessages) {
|
|
543
|
+
await this._mergeQueuedUserMessages(epoch);
|
|
544
|
+
if (this._chatEpoch !== epoch) {
|
|
545
|
+
this._completeSkippedRequest(connection, chatMessageId);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
|
|
549
|
+
this._completeSkippedRequest(connection, chatMessageId);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
494
553
|
if (this.waitForMcpConnections) {
|
|
495
554
|
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
|
|
496
555
|
await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
|
|
497
556
|
}
|
|
498
|
-
this.
|
|
499
|
-
this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
500
|
-
this._persistRequestContext();
|
|
501
|
-
const transformedMessages = autoTransformMessages(messages);
|
|
502
|
-
this._broadcastChatMessage({
|
|
503
|
-
messages: transformedMessages,
|
|
504
|
-
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
505
|
-
}, [connection.id]);
|
|
506
|
-
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
557
|
+
this._setRequestContext(requestClientTools, requestBody);
|
|
507
558
|
this._emit("message:request");
|
|
508
559
|
const abortSignal = this._getAbortSignal(chatMessageId);
|
|
509
560
|
return this._tryCatchChat(async () => {
|
|
@@ -516,8 +567,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
516
567
|
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
517
568
|
requestId: chatMessageId,
|
|
518
569
|
abortSignal,
|
|
519
|
-
clientTools,
|
|
520
|
-
body:
|
|
570
|
+
clientTools: requestClientTools,
|
|
571
|
+
body: requestBody
|
|
521
572
|
});
|
|
522
573
|
if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
|
|
523
574
|
else {
|
|
@@ -531,7 +582,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
531
582
|
}
|
|
532
583
|
});
|
|
533
584
|
});
|
|
534
|
-
});
|
|
585
|
+
}, { epoch });
|
|
535
586
|
}
|
|
536
587
|
if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
|
|
537
588
|
this.resetTurnState();
|
|
@@ -756,8 +807,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
756
807
|
_persistOrphanedStream(streamId) {
|
|
757
808
|
const chunks = this._resumableStream.getStreamChunks(streamId);
|
|
758
809
|
if (!chunks.length) return;
|
|
810
|
+
const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
|
|
759
811
|
const message = {
|
|
760
|
-
id:
|
|
812
|
+
id: fallbackId,
|
|
761
813
|
role: "assistant",
|
|
762
814
|
parts: []
|
|
763
815
|
};
|
|
@@ -771,7 +823,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
771
823
|
applyChunkToParts(message.parts, data);
|
|
772
824
|
} catch {}
|
|
773
825
|
if (message.parts.length > 0) {
|
|
826
|
+
if (message.id === fallbackId) {
|
|
827
|
+
for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") {
|
|
828
|
+
message.id = this.messages[i].id;
|
|
829
|
+
break;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
774
832
|
const existingIdx = this.messages.findIndex((m) => m.id === message.id);
|
|
833
|
+
if (existingIdx >= 0) {
|
|
834
|
+
const existing = this.messages[existingIdx];
|
|
835
|
+
message.parts = [...existing.parts, ...message.parts];
|
|
836
|
+
if (existing.metadata) message.metadata = message.metadata ? {
|
|
837
|
+
...existing.metadata,
|
|
838
|
+
...message.metadata
|
|
839
|
+
} : existing.metadata;
|
|
840
|
+
}
|
|
775
841
|
const updatedMessages = existingIdx >= 0 ? this.messages.map((m, i) => i === existingIdx ? message : m) : [...this.messages, message];
|
|
776
842
|
this.persistMessages(updatedMessages);
|
|
777
843
|
}
|
|
@@ -866,6 +932,176 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
866
932
|
await queue;
|
|
867
933
|
} while (this._chatTurnQueue !== queue);
|
|
868
934
|
}
|
|
935
|
+
_normalizeMessageConcurrency() {
|
|
936
|
+
if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
|
|
937
|
+
const debounceMs = this.messageConcurrency.debounceMs;
|
|
938
|
+
return {
|
|
939
|
+
strategy: "debounce",
|
|
940
|
+
debounceMs: typeof debounceMs === "number" && Number.isFinite(debounceMs) && debounceMs >= 0 ? debounceMs : AIChatAgent.MESSAGE_DEBOUNCE_MS
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
_getSubmitConcurrencyDecision(trigger) {
|
|
944
|
+
const queuedTurnsInCurrentEpoch = this._queuedChatTurnCountsByEpoch.get(this._chatEpoch) ?? 0;
|
|
945
|
+
if (trigger !== "submit-message" || queuedTurnsInCurrentEpoch === 0) return {
|
|
946
|
+
action: "execute",
|
|
947
|
+
submitSequence: null,
|
|
948
|
+
debounceUntilMs: null,
|
|
949
|
+
mergeQueuedMessages: false
|
|
950
|
+
};
|
|
951
|
+
const concurrency = this._normalizeMessageConcurrency();
|
|
952
|
+
if (concurrency === "drop") return {
|
|
953
|
+
action: "drop",
|
|
954
|
+
submitSequence: null,
|
|
955
|
+
debounceUntilMs: null,
|
|
956
|
+
mergeQueuedMessages: false
|
|
957
|
+
};
|
|
958
|
+
if (concurrency === "queue") return {
|
|
959
|
+
action: "execute",
|
|
960
|
+
submitSequence: null,
|
|
961
|
+
debounceUntilMs: null,
|
|
962
|
+
mergeQueuedMessages: false
|
|
963
|
+
};
|
|
964
|
+
const submitSequence = ++this._submitSequence;
|
|
965
|
+
this._latestOverlappingSubmitSequence = submitSequence;
|
|
966
|
+
if (concurrency === "latest") return {
|
|
967
|
+
action: "execute",
|
|
968
|
+
submitSequence,
|
|
969
|
+
debounceUntilMs: null,
|
|
970
|
+
mergeQueuedMessages: false
|
|
971
|
+
};
|
|
972
|
+
if (concurrency === "merge") {
|
|
973
|
+
if (!this._mergeQueuedUserStartIndexByEpoch.has(this._chatEpoch)) this._mergeQueuedUserStartIndexByEpoch.set(this._chatEpoch, this.messages.length);
|
|
974
|
+
return {
|
|
975
|
+
action: "execute",
|
|
976
|
+
submitSequence,
|
|
977
|
+
debounceUntilMs: null,
|
|
978
|
+
mergeQueuedMessages: true
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
return {
|
|
982
|
+
action: "execute",
|
|
983
|
+
submitSequence,
|
|
984
|
+
debounceUntilMs: Date.now() + concurrency.debounceMs,
|
|
985
|
+
mergeQueuedMessages: false
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
_isSupersededSubmit(submitSequence) {
|
|
989
|
+
return submitSequence !== null && submitSequence < this._latestOverlappingSubmitSequence;
|
|
990
|
+
}
|
|
991
|
+
async _waitForTimestamp(timestampMs) {
|
|
992
|
+
const remainingMs = timestampMs - Date.now();
|
|
993
|
+
if (remainingMs <= 0) return;
|
|
994
|
+
await new Promise((resolve) => {
|
|
995
|
+
this._activeDebounceResolve = resolve;
|
|
996
|
+
this._activeDebounceTimer = setTimeout(() => {
|
|
997
|
+
this._activeDebounceTimer = null;
|
|
998
|
+
this._activeDebounceResolve = null;
|
|
999
|
+
resolve();
|
|
1000
|
+
}, remainingMs);
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
_cancelActiveDebounce() {
|
|
1004
|
+
if (this._activeDebounceTimer !== null) {
|
|
1005
|
+
clearTimeout(this._activeDebounceTimer);
|
|
1006
|
+
this._activeDebounceTimer = null;
|
|
1007
|
+
}
|
|
1008
|
+
if (this._activeDebounceResolve !== null) {
|
|
1009
|
+
this._activeDebounceResolve();
|
|
1010
|
+
this._activeDebounceResolve = null;
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
async _mergeQueuedUserMessages(epoch = this._chatEpoch) {
|
|
1014
|
+
const mergedMessages = this._getMergedQueuedUserMessages(epoch);
|
|
1015
|
+
if (!mergedMessages) return;
|
|
1016
|
+
await this.persistMessages(mergedMessages, [], { _deleteStaleRows: true });
|
|
1017
|
+
}
|
|
1018
|
+
_getMergedQueuedUserMessages(epoch) {
|
|
1019
|
+
const queuedUserStart = this._mergeQueuedUserStartIndexByEpoch.get(epoch);
|
|
1020
|
+
if (queuedUserStart === void 0) return null;
|
|
1021
|
+
let queuedUserEnd = queuedUserStart;
|
|
1022
|
+
while (this.messages[queuedUserEnd]?.role === "user") queuedUserEnd++;
|
|
1023
|
+
if (queuedUserEnd === queuedUserStart && queuedUserStart < this.messages.length) console.warn(`[AIChatAgent] merge: expected user messages at index ${queuedUserStart} but found role="${this.messages[queuedUserStart]?.role}"; skipping merge`);
|
|
1024
|
+
const queuedUserMessages = this.messages.slice(queuedUserStart, queuedUserEnd);
|
|
1025
|
+
if (queuedUserMessages.length < 2) return null;
|
|
1026
|
+
return [
|
|
1027
|
+
...this.messages.slice(0, queuedUserStart),
|
|
1028
|
+
AIChatAgent._mergeUserMessages(queuedUserMessages),
|
|
1029
|
+
...this.messages.slice(queuedUserEnd)
|
|
1030
|
+
];
|
|
1031
|
+
}
|
|
1032
|
+
static _mergeUserMessages(messages) {
|
|
1033
|
+
const [firstMessage, ...remainingMessages] = messages;
|
|
1034
|
+
if (!firstMessage) throw new Error("cannot merge an empty message list");
|
|
1035
|
+
let mergedParts = AIChatAgent._cloneMessageParts(firstMessage.parts);
|
|
1036
|
+
for (const message of remainingMessages) {
|
|
1037
|
+
AIChatAgent._appendMergedText(mergedParts, "\n\n");
|
|
1038
|
+
mergedParts = AIChatAgent._mergeMessageParts(mergedParts, message.parts);
|
|
1039
|
+
}
|
|
1040
|
+
return {
|
|
1041
|
+
...messages[messages.length - 1] ?? firstMessage,
|
|
1042
|
+
parts: mergedParts
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
static _mergeMessageParts(currentParts, nextParts) {
|
|
1046
|
+
const mergedParts = AIChatAgent._cloneMessageParts(currentParts);
|
|
1047
|
+
for (const part of nextParts) {
|
|
1048
|
+
if (part.type === "text") {
|
|
1049
|
+
AIChatAgent._appendMergedText(mergedParts, part.text);
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
mergedParts.push(part);
|
|
1053
|
+
}
|
|
1054
|
+
return mergedParts;
|
|
1055
|
+
}
|
|
1056
|
+
static _cloneMessageParts(parts) {
|
|
1057
|
+
return [...parts];
|
|
1058
|
+
}
|
|
1059
|
+
static _appendMergedText(parts, text) {
|
|
1060
|
+
if (text.length === 0) return;
|
|
1061
|
+
const lastPart = parts[parts.length - 1];
|
|
1062
|
+
if (lastPart?.type === "text") {
|
|
1063
|
+
parts[parts.length - 1] = {
|
|
1064
|
+
...lastPart,
|
|
1065
|
+
text: lastPart.text + text
|
|
1066
|
+
};
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
const textPart = {
|
|
1070
|
+
type: "text",
|
|
1071
|
+
text
|
|
1072
|
+
};
|
|
1073
|
+
parts.push(textPart);
|
|
1074
|
+
}
|
|
1075
|
+
_setRequestContext(clientTools, body) {
|
|
1076
|
+
this._lastClientTools = clientTools?.length ? clientTools : void 0;
|
|
1077
|
+
this._lastBody = body && Object.keys(body).length > 0 ? body : void 0;
|
|
1078
|
+
this._persistRequestContext();
|
|
1079
|
+
}
|
|
1080
|
+
_messagesForClientSync() {
|
|
1081
|
+
if (!this._streamingMessage || this._streamingMessage.parts.length === 0) return this.messages;
|
|
1082
|
+
const existingIdx = this.messages.findIndex((message) => message.id === this._streamingMessage?.id);
|
|
1083
|
+
if (existingIdx >= 0) return this.messages.map((message, idx) => idx === existingIdx && this._streamingMessage ? this._streamingMessage : message);
|
|
1084
|
+
return [...this.messages, this._streamingMessage];
|
|
1085
|
+
}
|
|
1086
|
+
_sendDirectMessage(connection, message) {
|
|
1087
|
+
try {
|
|
1088
|
+
connection.send(JSON.stringify(message));
|
|
1089
|
+
} catch {}
|
|
1090
|
+
}
|
|
1091
|
+
_completeSkippedRequest(connection, requestId) {
|
|
1092
|
+
this._sendDirectMessage(connection, {
|
|
1093
|
+
body: "",
|
|
1094
|
+
done: true,
|
|
1095
|
+
id: requestId,
|
|
1096
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
_rollbackDroppedSubmit(connection) {
|
|
1100
|
+
this._sendDirectMessage(connection, {
|
|
1101
|
+
messages: this._messagesForClientSync(),
|
|
1102
|
+
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
1103
|
+
});
|
|
1104
|
+
}
|
|
869
1105
|
/** `true` when an assistant message is waiting on a client tool result or approval. */
|
|
870
1106
|
hasPendingInteraction() {
|
|
871
1107
|
if (this._streamingMessage && this._messageHasPendingInteraction(this._streamingMessage)) return true;
|
|
@@ -907,12 +1143,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
907
1143
|
* the built-in handler calls it automatically.
|
|
908
1144
|
*/
|
|
909
1145
|
resetTurnState() {
|
|
1146
|
+
this._mergeQueuedUserStartIndexByEpoch.delete(this._chatEpoch);
|
|
910
1147
|
this._chatEpoch++;
|
|
911
1148
|
this._destroyAbortControllers();
|
|
1149
|
+
this._cancelActiveDebounce();
|
|
912
1150
|
this._pendingInteractionPromise = null;
|
|
913
1151
|
this._activeAutoContinuationRequestId = null;
|
|
914
1152
|
this._activeAutoContinuationConnectionId = null;
|
|
915
1153
|
this._clearAllAutoContinuationState(true);
|
|
1154
|
+
this._pendingChatResponseResults.length = 0;
|
|
916
1155
|
}
|
|
917
1156
|
async _awaitWithDeadline(promise, deadline) {
|
|
918
1157
|
if (deadline == null) return promise;
|
|
@@ -931,9 +1170,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
931
1170
|
* Run a chat turn exclusively so `_reply()` never overlaps with another
|
|
932
1171
|
* streaming turn.
|
|
933
1172
|
*/
|
|
934
|
-
async _runExclusiveChatTurn(requestId, fn) {
|
|
1173
|
+
async _runExclusiveChatTurn(requestId, fn, options) {
|
|
935
1174
|
const previousTurn = this._chatTurnQueue;
|
|
936
1175
|
let releaseTurn = () => {};
|
|
1176
|
+
const epoch = options?.epoch ?? this._chatEpoch;
|
|
1177
|
+
this._queuedChatTurnCountsByEpoch.set(epoch, (this._queuedChatTurnCountsByEpoch.get(epoch) ?? 0) + 1);
|
|
937
1178
|
this._chatTurnQueue = new Promise((resolve) => {
|
|
938
1179
|
releaseTurn = resolve;
|
|
939
1180
|
});
|
|
@@ -943,7 +1184,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
943
1184
|
return await fn();
|
|
944
1185
|
} finally {
|
|
945
1186
|
this._activeChatTurnRequestId = null;
|
|
1187
|
+
const nextCount = (this._queuedChatTurnCountsByEpoch.get(epoch) ?? 1) - 1;
|
|
1188
|
+
if (nextCount <= 0) {
|
|
1189
|
+
this._queuedChatTurnCountsByEpoch.delete(epoch);
|
|
1190
|
+
this._mergeQueuedUserStartIndexByEpoch.delete(epoch);
|
|
1191
|
+
} else this._queuedChatTurnCountsByEpoch.set(epoch, nextCount);
|
|
946
1192
|
releaseTurn();
|
|
1193
|
+
if (this._pendingChatResponseResults.length > 0 && !this._insideResponseHook) {
|
|
1194
|
+
this._insideResponseHook = true;
|
|
1195
|
+
try {
|
|
1196
|
+
await this.keepAliveWhile(async () => {
|
|
1197
|
+
while (this._pendingChatResponseResults.length > 0) {
|
|
1198
|
+
const result = this._pendingChatResponseResults.shift();
|
|
1199
|
+
try {
|
|
1200
|
+
await this.onChatResponse(result);
|
|
1201
|
+
} catch (hookError) {
|
|
1202
|
+
console.error("[AIChatAgent] onChatResponse threw:", hookError);
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
});
|
|
1206
|
+
} finally {
|
|
1207
|
+
this._insideResponseHook = false;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
947
1210
|
}
|
|
948
1211
|
}
|
|
949
1212
|
_enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
|
|
@@ -1033,12 +1296,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1033
1296
|
} finally {
|
|
1034
1297
|
dispose();
|
|
1035
1298
|
}
|
|
1036
|
-
}).catch((error) => {
|
|
1299
|
+
}, { epoch }).catch((error) => {
|
|
1037
1300
|
const errorPrefix = this._pendingAutoContinuationErrorPrefix ?? "[AIChatAgent] Auto-continuation failed:";
|
|
1038
1301
|
this._clearAllAutoContinuationState(true);
|
|
1039
1302
|
console.error(errorPrefix, error);
|
|
1040
1303
|
});
|
|
1041
1304
|
}
|
|
1305
|
+
async _runProgrammaticChatTurn(requestId, clientTools, body) {
|
|
1306
|
+
this._setRequestContext(clientTools, body);
|
|
1307
|
+
await this._tryCatchChat(async () => {
|
|
1308
|
+
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
1309
|
+
agent: this,
|
|
1310
|
+
connection: void 0,
|
|
1311
|
+
request: void 0,
|
|
1312
|
+
email: void 0
|
|
1313
|
+
}, async () => {
|
|
1314
|
+
const abortSignal = this._getAbortSignal(requestId);
|
|
1315
|
+
const response = await this.onChatMessage(() => {}, {
|
|
1316
|
+
requestId,
|
|
1317
|
+
abortSignal,
|
|
1318
|
+
clientTools,
|
|
1319
|
+
body
|
|
1320
|
+
});
|
|
1321
|
+
if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
|
|
1322
|
+
});
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1042
1325
|
/**
|
|
1043
1326
|
* Handle incoming chat messages and generate a response
|
|
1044
1327
|
* @param onFinish Callback to be called when the response is finished
|
|
@@ -1049,6 +1332,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1049
1332
|
throw new Error("received a chat message, override onChatMessage and return a Response to send to the client");
|
|
1050
1333
|
}
|
|
1051
1334
|
/**
|
|
1335
|
+
* Called after a chat turn completes and the assistant message has been
|
|
1336
|
+
* persisted. The turn lock is released before this hook runs, so it is
|
|
1337
|
+
* safe to call `saveMessages` from inside.
|
|
1338
|
+
*
|
|
1339
|
+
* Fires for all turn completion paths: WebSocket chat requests,
|
|
1340
|
+
* `saveMessages`, and auto-continuation.
|
|
1341
|
+
*
|
|
1342
|
+
* Responses triggered from inside `onChatResponse` (e.g. via `saveMessages`)
|
|
1343
|
+
* do not fire `onChatResponse` recursively.
|
|
1344
|
+
*
|
|
1345
|
+
* The default implementation is a no-op.
|
|
1346
|
+
*
|
|
1347
|
+
* @param result - Information about the completed turn
|
|
1348
|
+
*
|
|
1349
|
+
* @example
|
|
1350
|
+
* ```ts
|
|
1351
|
+
* class MyAgent extends AIChatAgent<Env> {
|
|
1352
|
+
* protected async onChatResponse(result: ChatResponseResult) {
|
|
1353
|
+
* if (result.status === "completed") {
|
|
1354
|
+
* this.broadcast(JSON.stringify({ streaming: false }));
|
|
1355
|
+
* }
|
|
1356
|
+
* }
|
|
1357
|
+
* }
|
|
1358
|
+
* ```
|
|
1359
|
+
*/
|
|
1360
|
+
onChatResponse(_result) {}
|
|
1361
|
+
/**
|
|
1052
1362
|
* Override this method to apply custom transformations to messages before
|
|
1053
1363
|
* they are persisted to storage. This hook runs **after** the built-in
|
|
1054
1364
|
* sanitization (OpenAI metadata stripping, Anthropic provider-executed tool
|
|
@@ -1083,28 +1393,51 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1083
1393
|
return message;
|
|
1084
1394
|
}
|
|
1085
1395
|
/**
|
|
1086
|
-
*
|
|
1087
|
-
*
|
|
1396
|
+
* Persist messages and trigger `onChatMessage()` for a new response.
|
|
1397
|
+
*
|
|
1398
|
+
* Waits for any active chat turn to finish before starting, so scheduled
|
|
1399
|
+
* or programmatic messages never overlap an in-flight stream.
|
|
1400
|
+
*
|
|
1401
|
+
* Pass a function to derive the next message list from the latest
|
|
1402
|
+
* persisted `this.messages` when the turn actually starts. This avoids
|
|
1403
|
+
* stale baselines when multiple `saveMessages()` calls queue up behind
|
|
1404
|
+
* active work:
|
|
1405
|
+
*
|
|
1406
|
+
* ```ts
|
|
1407
|
+
* await this.saveMessages((messages) => [...messages, syntheticMessage]);
|
|
1408
|
+
* ```
|
|
1409
|
+
*
|
|
1410
|
+
* Returns `{ requestId, status }` so callers can detect whether the turn
|
|
1411
|
+
* ran (`"completed"`) or was skipped because the chat was cleared
|
|
1412
|
+
* (`"skipped"`).
|
|
1088
1413
|
*/
|
|
1089
1414
|
async saveMessages(messages) {
|
|
1090
1415
|
const requestId = nanoid();
|
|
1091
1416
|
const clientTools = this._lastClientTools;
|
|
1092
1417
|
const body = this._lastBody;
|
|
1093
1418
|
const epoch = this._chatEpoch;
|
|
1419
|
+
let status = "completed";
|
|
1094
1420
|
await this._runExclusiveChatTurn(requestId, async () => {
|
|
1095
|
-
if (this._chatEpoch !== epoch)
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1421
|
+
if (this._chatEpoch !== epoch) {
|
|
1422
|
+
status = "skipped";
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
const resolvedMessages = typeof messages === "function" ? await messages(this.messages) : messages;
|
|
1426
|
+
if (this._chatEpoch !== epoch) {
|
|
1427
|
+
status = "skipped";
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
await this.persistMessages(resolvedMessages);
|
|
1431
|
+
if (this._chatEpoch !== epoch) {
|
|
1432
|
+
status = "skipped";
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
await this._runProgrammaticChatTurn(requestId, clientTools, body);
|
|
1436
|
+
}, { epoch });
|
|
1437
|
+
return {
|
|
1438
|
+
requestId,
|
|
1439
|
+
status
|
|
1440
|
+
};
|
|
1108
1441
|
}
|
|
1109
1442
|
async persistMessages(messages, excludeBroadcastIds = [], options) {
|
|
1110
1443
|
const mergedMessages = this._mergeIncomingWithServerState(messages);
|
|
@@ -1647,11 +1980,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1647
1980
|
let readResult;
|
|
1648
1981
|
try {
|
|
1649
1982
|
readResult = await reader.read();
|
|
1650
|
-
} catch {
|
|
1651
|
-
break;
|
|
1983
|
+
} catch (readError) {
|
|
1984
|
+
if (abortSignal?.aborted) break;
|
|
1985
|
+
throw readError;
|
|
1652
1986
|
}
|
|
1653
1987
|
const { done, value } = readResult;
|
|
1654
1988
|
if (done) {
|
|
1989
|
+
if (abortSignal?.aborted) break;
|
|
1655
1990
|
this._completeStream(streamId);
|
|
1656
1991
|
streamCompleted.value = true;
|
|
1657
1992
|
this._broadcastChatMessage({
|
|
@@ -1661,7 +1996,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1661
1996
|
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
1662
1997
|
...continuation && { continuation: true }
|
|
1663
1998
|
});
|
|
1664
|
-
|
|
1999
|
+
return "completed";
|
|
1665
2000
|
}
|
|
1666
2001
|
const lines = decoder.decode(value).split("\n");
|
|
1667
2002
|
for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
|
|
@@ -1731,6 +2066,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1731
2066
|
break;
|
|
1732
2067
|
}
|
|
1733
2068
|
let eventToSend = data;
|
|
2069
|
+
if (continuation && data.type === "start" && "messageId" in data) {
|
|
2070
|
+
const { messageId: _, ...rest } = data;
|
|
2071
|
+
eventToSend = rest;
|
|
2072
|
+
}
|
|
1734
2073
|
if (data.type === "finish" && "finishReason" in data) {
|
|
1735
2074
|
const { finishReason, ...rest } = data;
|
|
1736
2075
|
eventToSend = {
|
|
@@ -1761,7 +2100,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1761
2100
|
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
1762
2101
|
...continuation && { continuation: true }
|
|
1763
2102
|
});
|
|
2103
|
+
return "aborted";
|
|
1764
2104
|
}
|
|
2105
|
+
return "completed";
|
|
1765
2106
|
}
|
|
1766
2107
|
async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
|
|
1767
2108
|
this._broadcastTextEvent(streamId, {
|
|
@@ -1782,11 +2123,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1782
2123
|
let readResult;
|
|
1783
2124
|
try {
|
|
1784
2125
|
readResult = await reader.read();
|
|
1785
|
-
} catch {
|
|
1786
|
-
break;
|
|
2126
|
+
} catch (readError) {
|
|
2127
|
+
if (abortSignal?.aborted) break;
|
|
2128
|
+
throw readError;
|
|
1787
2129
|
}
|
|
1788
2130
|
const { done, value } = readResult;
|
|
1789
2131
|
if (done) {
|
|
2132
|
+
if (abortSignal?.aborted) break;
|
|
1790
2133
|
textPart.state = "done";
|
|
1791
2134
|
this._broadcastTextEvent(streamId, {
|
|
1792
2135
|
type: "text-end",
|
|
@@ -1801,7 +2144,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1801
2144
|
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
1802
2145
|
...continuation && { continuation: true }
|
|
1803
2146
|
});
|
|
1804
|
-
|
|
2147
|
+
return "completed";
|
|
1805
2148
|
}
|
|
1806
2149
|
const chunk = decoder.decode(value);
|
|
1807
2150
|
if (chunk.length > 0) {
|
|
@@ -1829,7 +2172,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1829
2172
|
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
1830
2173
|
...continuation && { continuation: true }
|
|
1831
2174
|
});
|
|
2175
|
+
return "aborted";
|
|
1832
2176
|
}
|
|
2177
|
+
return "completed";
|
|
1833
2178
|
}
|
|
1834
2179
|
/**
|
|
1835
2180
|
* Applies a tool approval response from the client, updating the persisted message.
|
|
@@ -1875,10 +2220,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1875
2220
|
this._streamingMessage = message;
|
|
1876
2221
|
const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
|
|
1877
2222
|
const streamCompleted = { value: false };
|
|
2223
|
+
let streamEndStatus = "completed";
|
|
1878
2224
|
let earlyPersistedId = null;
|
|
1879
2225
|
try {
|
|
1880
|
-
if (isSSE) await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
|
|
1881
|
-
else await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
|
|
2226
|
+
if (isSSE) streamEndStatus = await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
|
|
2227
|
+
else streamEndStatus = await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
|
|
1882
2228
|
} catch (error) {
|
|
1883
2229
|
if (!streamCompleted.value) {
|
|
1884
2230
|
this._markStreamError(streamId);
|
|
@@ -1891,6 +2237,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1891
2237
|
...continuation && { continuation: true }
|
|
1892
2238
|
});
|
|
1893
2239
|
this._emit("message:error", { error: error instanceof Error ? error.message : String(error) });
|
|
2240
|
+
this._pendingChatResponseResults.push({
|
|
2241
|
+
message,
|
|
2242
|
+
requestId: id,
|
|
2243
|
+
continuation,
|
|
2244
|
+
status: "error",
|
|
2245
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2246
|
+
});
|
|
1894
2247
|
}
|
|
1895
2248
|
throw error;
|
|
1896
2249
|
} finally {
|
|
@@ -1921,6 +2274,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1921
2274
|
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
1922
2275
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|
|
1923
2276
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|
|
2277
|
+
this._pendingChatResponseResults.push({
|
|
2278
|
+
message,
|
|
2279
|
+
requestId: id,
|
|
2280
|
+
continuation,
|
|
2281
|
+
status: streamEndStatus
|
|
2282
|
+
});
|
|
1924
2283
|
}));
|
|
1925
2284
|
}
|
|
1926
2285
|
/**
|