@cloudflare/ai-chat 0.3.2 → 0.4.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/index.d.ts +103 -26
- package/dist/index.js +284 -94
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +113 -5
- package/dist/react.js +98 -2
- package/dist/react.js.map +1 -1
- package/package.json +6 -11
- package/dist/experimental/forever.d.ts +0 -7
- package/dist/experimental/forever.js +0 -10
- package/dist/experimental/forever.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { MessageType } from "./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
|
-
import { ContinuationState, ROW_MAX_BYTES, ResumableStream, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, sanitizeMessage } from "agents/chat";
|
|
4
|
+
import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, sanitizeMessage } from "agents/chat";
|
|
5
5
|
import { nanoid } from "nanoid";
|
|
6
6
|
//#region src/message-reconciler.ts
|
|
7
7
|
/**
|
|
@@ -166,9 +166,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
166
166
|
this._pendingInteractionPromise = null;
|
|
167
167
|
this._approvalPersistedMessageId = null;
|
|
168
168
|
this._turnQueue = new TurnQueue();
|
|
169
|
+
this.unstable_chatRecovery = false;
|
|
169
170
|
this._mergeQueuedUserStartIndexByEpoch = /* @__PURE__ */ new Map();
|
|
170
171
|
this._submitSequence = 0;
|
|
171
172
|
this._latestOverlappingSubmitSequence = 0;
|
|
173
|
+
this._pendingEnqueueCount = 0;
|
|
172
174
|
this._activeDebounceTimer = null;
|
|
173
175
|
this._activeDebounceResolve = null;
|
|
174
176
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
@@ -189,7 +191,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
189
191
|
this._restoreRequestContext();
|
|
190
192
|
this._resumableStream = new ResumableStream(this.sql.bind(this));
|
|
191
193
|
this.messages = autoTransformMessages(this._loadMessagesFromDb());
|
|
192
|
-
this.
|
|
194
|
+
this._abortRegistry = new AbortRegistry();
|
|
193
195
|
const _onConnect = this.onConnect.bind(this);
|
|
194
196
|
this.onConnect = async (connection, ctx) => {
|
|
195
197
|
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
@@ -238,12 +240,17 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
238
240
|
this._completeSkippedRequest(connection, chatMessageId);
|
|
239
241
|
return;
|
|
240
242
|
}
|
|
241
|
-
this.
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
243
|
+
this._pendingEnqueueCount++;
|
|
244
|
+
try {
|
|
245
|
+
this._broadcastChatMessage({
|
|
246
|
+
messages: transformedMessages,
|
|
247
|
+
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
248
|
+
}, [connection.id]);
|
|
249
|
+
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
250
|
+
if (concurrencyDecision.mergeQueuedMessages) await this._mergeQueuedUserMessages(epoch);
|
|
251
|
+
} finally {
|
|
252
|
+
this._pendingEnqueueCount = Math.max(0, this._pendingEnqueueCount - 1);
|
|
253
|
+
}
|
|
247
254
|
return this._runExclusiveChatTurn(chatMessageId, async () => {
|
|
248
255
|
if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
|
|
249
256
|
this._completeSkippedRequest(connection, chatMessageId);
|
|
@@ -277,7 +284,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
277
284
|
}
|
|
278
285
|
this._setRequestContext(requestClientTools, requestBody);
|
|
279
286
|
this._emit("message:request");
|
|
280
|
-
const abortSignal = this.
|
|
287
|
+
const abortSignal = this._abortRegistry.getSignal(chatMessageId);
|
|
281
288
|
return this._tryCatchChat(async () => {
|
|
282
289
|
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
283
290
|
agent: this,
|
|
@@ -285,22 +292,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
285
292
|
request: void 0,
|
|
286
293
|
email: void 0
|
|
287
294
|
}, async () => {
|
|
288
|
-
const
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
295
|
+
const chatTurnBody = async () => {
|
|
296
|
+
try {
|
|
297
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
298
|
+
requestId: chatMessageId,
|
|
299
|
+
abortSignal,
|
|
300
|
+
clientTools: requestClientTools,
|
|
301
|
+
body: requestBody,
|
|
302
|
+
continuation: false
|
|
303
|
+
});
|
|
304
|
+
if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
|
|
305
|
+
else {
|
|
306
|
+
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
307
|
+
this._broadcastChatMessage({
|
|
308
|
+
body: "No response was generated by the agent.",
|
|
309
|
+
done: true,
|
|
310
|
+
id: chatMessageId,
|
|
311
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
312
|
+
}, [connection.id]);
|
|
313
|
+
}
|
|
314
|
+
} finally {
|
|
315
|
+
this._abortRegistry.remove(chatMessageId);
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${chatMessageId}`, async () => {
|
|
319
|
+
await chatTurnBody();
|
|
293
320
|
});
|
|
294
|
-
|
|
295
|
-
else {
|
|
296
|
-
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
297
|
-
this._broadcastChatMessage({
|
|
298
|
-
body: "No response was generated by the agent.",
|
|
299
|
-
done: true,
|
|
300
|
-
id: chatMessageId,
|
|
301
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
302
|
-
}, [connection.id]);
|
|
303
|
-
}
|
|
321
|
+
else await chatTurnBody();
|
|
304
322
|
});
|
|
305
323
|
});
|
|
306
324
|
}, {
|
|
@@ -328,7 +346,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
328
346
|
return;
|
|
329
347
|
}
|
|
330
348
|
if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {
|
|
331
|
-
this.
|
|
349
|
+
this._abortRegistry.cancel(data.id);
|
|
332
350
|
this._emit("message:cancel", { requestId: data.id });
|
|
333
351
|
return;
|
|
334
352
|
}
|
|
@@ -626,7 +644,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
626
644
|
};
|
|
627
645
|
}
|
|
628
646
|
_getSubmitConcurrencyDecision(trigger) {
|
|
629
|
-
const queuedTurnsInCurrentEpoch = this._turnQueue.queuedCount();
|
|
647
|
+
const queuedTurnsInCurrentEpoch = this._turnQueue.queuedCount() + this._pendingEnqueueCount;
|
|
630
648
|
if (trigger !== "submit-message" || queuedTurnsInCurrentEpoch === 0) return {
|
|
631
649
|
action: "execute",
|
|
632
650
|
submitSequence: null,
|
|
@@ -819,7 +837,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
819
837
|
}
|
|
820
838
|
abortActiveTurn() {
|
|
821
839
|
if (!this._turnQueue.activeRequestId) return false;
|
|
822
|
-
this.
|
|
840
|
+
this._abortRegistry.cancel(this._turnQueue.activeRequestId);
|
|
823
841
|
return true;
|
|
824
842
|
}
|
|
825
843
|
/**
|
|
@@ -830,8 +848,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
830
848
|
resetTurnState() {
|
|
831
849
|
this._mergeQueuedUserStartIndexByEpoch.delete(this._turnQueue.generation);
|
|
832
850
|
this._turnQueue.reset();
|
|
833
|
-
this.
|
|
851
|
+
this._abortRegistry.destroyAll();
|
|
834
852
|
this._cancelActiveDebounce();
|
|
853
|
+
this._pendingEnqueueCount = 0;
|
|
835
854
|
this._pendingInteractionPromise = null;
|
|
836
855
|
this._continuation.sendResumeNone();
|
|
837
856
|
this._continuation.clearAll();
|
|
@@ -941,7 +960,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
941
960
|
const clientTools = this._continuation.pending?.clientTools;
|
|
942
961
|
const body = this._continuation.pending?.body;
|
|
943
962
|
if (this._continuation.pending) this._continuation.pending.pastCoalesce = true;
|
|
944
|
-
const abortSignal = this.
|
|
963
|
+
const abortSignal = this._abortRegistry.getSignal(requestId);
|
|
945
964
|
return this._tryCatchChat(async () => {
|
|
946
965
|
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
947
966
|
agent: this,
|
|
@@ -949,22 +968,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
949
968
|
request: void 0,
|
|
950
969
|
email: void 0
|
|
951
970
|
}, async () => {
|
|
952
|
-
const
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
971
|
+
const autoContinuationBody = async () => {
|
|
972
|
+
try {
|
|
973
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
974
|
+
requestId,
|
|
975
|
+
abortSignal,
|
|
976
|
+
clientTools,
|
|
977
|
+
body,
|
|
978
|
+
continuation: true
|
|
979
|
+
});
|
|
980
|
+
if (response) {
|
|
981
|
+
await this._reply(requestId, response, [], {
|
|
982
|
+
continuation: true,
|
|
983
|
+
chatMessageId: requestId
|
|
984
|
+
});
|
|
985
|
+
this._activateDeferredAutoContinuation();
|
|
986
|
+
} else {
|
|
987
|
+
this._clearPendingAutoContinuation(true);
|
|
988
|
+
this._activateDeferredAutoContinuation();
|
|
989
|
+
}
|
|
990
|
+
} finally {
|
|
991
|
+
this._abortRegistry.remove(requestId);
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
995
|
+
await autoContinuationBody();
|
|
957
996
|
});
|
|
958
|
-
|
|
959
|
-
await this._reply(requestId, response, [], {
|
|
960
|
-
continuation: true,
|
|
961
|
-
chatMessageId: requestId
|
|
962
|
-
});
|
|
963
|
-
this._activateDeferredAutoContinuation();
|
|
964
|
-
} else {
|
|
965
|
-
this._clearPendingAutoContinuation(true);
|
|
966
|
-
this._activateDeferredAutoContinuation();
|
|
967
|
-
}
|
|
997
|
+
else await autoContinuationBody();
|
|
968
998
|
});
|
|
969
999
|
});
|
|
970
1000
|
} finally {
|
|
@@ -988,14 +1018,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
988
1018
|
request: void 0,
|
|
989
1019
|
email: void 0
|
|
990
1020
|
}, async () => {
|
|
991
|
-
const abortSignal = this.
|
|
992
|
-
const
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
1021
|
+
const abortSignal = this._abortRegistry.getSignal(requestId);
|
|
1022
|
+
const programmaticBody = async () => {
|
|
1023
|
+
try {
|
|
1024
|
+
const response = await this.onChatMessage(() => {}, {
|
|
1025
|
+
requestId,
|
|
1026
|
+
abortSignal,
|
|
1027
|
+
clientTools,
|
|
1028
|
+
body,
|
|
1029
|
+
continuation: false
|
|
1030
|
+
});
|
|
1031
|
+
if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
|
|
1032
|
+
} finally {
|
|
1033
|
+
this._abortRegistry.remove(requestId);
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
1037
|
+
await programmaticBody();
|
|
997
1038
|
});
|
|
998
|
-
|
|
1039
|
+
else await programmaticBody();
|
|
999
1040
|
});
|
|
1000
1041
|
});
|
|
1001
1042
|
}
|
|
@@ -1113,6 +1154,154 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1113
1154
|
status
|
|
1114
1155
|
};
|
|
1115
1156
|
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Trigger a continuation of the last assistant message without inserting
|
|
1159
|
+
* a new user message. The LLM sees the full conversation (including the
|
|
1160
|
+
* partial assistant response) and generates a continuation that appends
|
|
1161
|
+
* to the same message.
|
|
1162
|
+
*
|
|
1163
|
+
* This uses `continuation: true` in `_reply`, which clones the last
|
|
1164
|
+
* assistant message and appends new parts to it — the same mechanism
|
|
1165
|
+
* used by tool auto-continuation.
|
|
1166
|
+
*
|
|
1167
|
+
* Returns early if there is no assistant message to continue from.
|
|
1168
|
+
*/
|
|
1169
|
+
async continueLastTurn(body) {
|
|
1170
|
+
if (!this._findLastAssistantMessage()) return {
|
|
1171
|
+
requestId: "",
|
|
1172
|
+
status: "skipped"
|
|
1173
|
+
};
|
|
1174
|
+
const requestId = nanoid();
|
|
1175
|
+
const clientTools = this._lastClientTools;
|
|
1176
|
+
const resolvedBody = body ?? this._lastBody;
|
|
1177
|
+
const epoch = this._turnQueue.generation;
|
|
1178
|
+
let status = "completed";
|
|
1179
|
+
await this._runExclusiveChatTurn(requestId, async () => {
|
|
1180
|
+
if (this._turnQueue.generation !== epoch) {
|
|
1181
|
+
status = "skipped";
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1184
|
+
this._setRequestContext(clientTools, resolvedBody);
|
|
1185
|
+
const turnBody = async () => {
|
|
1186
|
+
await this._tryCatchChat(async () => {
|
|
1187
|
+
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
1188
|
+
agent: this,
|
|
1189
|
+
connection: void 0,
|
|
1190
|
+
request: void 0,
|
|
1191
|
+
email: void 0
|
|
1192
|
+
}, async () => {
|
|
1193
|
+
const abortSignal = this._abortRegistry.getSignal(requestId);
|
|
1194
|
+
try {
|
|
1195
|
+
const response = await this.onChatMessage(() => {}, {
|
|
1196
|
+
requestId,
|
|
1197
|
+
abortSignal,
|
|
1198
|
+
clientTools,
|
|
1199
|
+
body: resolvedBody,
|
|
1200
|
+
continuation: true
|
|
1201
|
+
});
|
|
1202
|
+
if (response) await this._reply(requestId, response, [], {
|
|
1203
|
+
continuation: true,
|
|
1204
|
+
chatMessageId: requestId
|
|
1205
|
+
});
|
|
1206
|
+
} finally {
|
|
1207
|
+
this._abortRegistry.remove(requestId);
|
|
1208
|
+
}
|
|
1209
|
+
});
|
|
1210
|
+
});
|
|
1211
|
+
};
|
|
1212
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
1213
|
+
await turnBody();
|
|
1214
|
+
});
|
|
1215
|
+
else await turnBody();
|
|
1216
|
+
}, { epoch });
|
|
1217
|
+
if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
|
|
1218
|
+
return {
|
|
1219
|
+
requestId,
|
|
1220
|
+
status
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
static {
|
|
1224
|
+
this.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* Intercept internal chat fibers before they reach the user's
|
|
1228
|
+
* `onFiberRecovered` hook. Maps to `onChatRecovery`.
|
|
1229
|
+
* @internal
|
|
1230
|
+
*/
|
|
1231
|
+
async _handleInternalFiberRecovery(ctx) {
|
|
1232
|
+
const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
|
|
1233
|
+
if (!ctx.name.startsWith(chatPrefix)) return false;
|
|
1234
|
+
const requestId = ctx.name.slice(chatPrefix.length);
|
|
1235
|
+
let streamId = "";
|
|
1236
|
+
if (requestId) {
|
|
1237
|
+
const rows = this.sql`
|
|
1238
|
+
SELECT id FROM cf_ai_chat_stream_metadata
|
|
1239
|
+
WHERE request_id = ${requestId}
|
|
1240
|
+
ORDER BY created_at DESC LIMIT 1
|
|
1241
|
+
`;
|
|
1242
|
+
if (rows.length > 0) streamId = rows[0].id;
|
|
1243
|
+
}
|
|
1244
|
+
if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
|
|
1245
|
+
const partial = streamId ? this._getPartialStreamText(streamId) : {
|
|
1246
|
+
text: "",
|
|
1247
|
+
parts: []
|
|
1248
|
+
};
|
|
1249
|
+
const options = await this.onChatRecovery({
|
|
1250
|
+
streamId: streamId ?? "",
|
|
1251
|
+
requestId,
|
|
1252
|
+
partialText: partial.text,
|
|
1253
|
+
partialParts: partial.parts,
|
|
1254
|
+
recoveryData: ctx.snapshot,
|
|
1255
|
+
messages: [...this.messages],
|
|
1256
|
+
lastBody: this._lastBody,
|
|
1257
|
+
lastClientTools: this._lastClientTools
|
|
1258
|
+
});
|
|
1259
|
+
const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
|
|
1260
|
+
if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
|
|
1261
|
+
if (streamStillActive) this._resumableStream.complete(streamId);
|
|
1262
|
+
if (options.continue !== false) {
|
|
1263
|
+
const targetId = this._findLastAssistantMessage()?.id;
|
|
1264
|
+
await this.schedule(0, "_chatRecoveryContinue", targetId ? { targetAssistantId: targetId } : void 0, { idempotent: true });
|
|
1265
|
+
}
|
|
1266
|
+
return true;
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Called when an interrupted chat stream is detected after restart.
|
|
1270
|
+
* Return options to control recovery:
|
|
1271
|
+
*
|
|
1272
|
+
* - `{}` (default): persist partial response + schedule continuation
|
|
1273
|
+
* - `{ continue: false }`: persist but don't continue
|
|
1274
|
+
* - `{ persist: false, continue: false }`: handle everything yourself
|
|
1275
|
+
*
|
|
1276
|
+
* `ctx.recoveryData` contains any data checkpointed via `this.stash()`
|
|
1277
|
+
* during streaming (e.g., OpenAI `responseId`).
|
|
1278
|
+
*/
|
|
1279
|
+
async onChatRecovery(_ctx) {
|
|
1280
|
+
return {};
|
|
1281
|
+
}
|
|
1282
|
+
async _chatRecoveryContinue(data) {
|
|
1283
|
+
if (!await this.waitUntilStable({ timeout: 1e4 })) {
|
|
1284
|
+
console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
|
|
1285
|
+
return;
|
|
1286
|
+
}
|
|
1287
|
+
const targetId = data?.targetAssistantId;
|
|
1288
|
+
if (targetId && this._findLastAssistantMessage()?.id !== targetId) return;
|
|
1289
|
+
await this.continueLastTurn();
|
|
1290
|
+
}
|
|
1291
|
+
/**
|
|
1292
|
+
* Extract partial text and parts from stored stream chunks.
|
|
1293
|
+
*/
|
|
1294
|
+
_getPartialStreamText(streamId) {
|
|
1295
|
+
const chunks = this._resumableStream.getStreamChunks(streamId);
|
|
1296
|
+
const parts = [];
|
|
1297
|
+
for (const chunk of chunks) try {
|
|
1298
|
+
applyChunkToParts(parts, JSON.parse(chunk.body));
|
|
1299
|
+
} catch {}
|
|
1300
|
+
return {
|
|
1301
|
+
text: parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join(""),
|
|
1302
|
+
parts
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1116
1305
|
async persistMessages(messages, excludeBroadcastIds = [], options) {
|
|
1117
1306
|
const mergedMessages = reconcileMessages(messages, this.messages, (msg) => this._sanitizeMessageForPersistence(msg));
|
|
1118
1307
|
for (const message of mergedMessages) {
|
|
@@ -1491,6 +1680,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1491
1680
|
}
|
|
1492
1681
|
async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
|
|
1493
1682
|
streamCompleted.value = false;
|
|
1683
|
+
let continuationTextResumed = false;
|
|
1684
|
+
let continuationReasoningResumed = false;
|
|
1494
1685
|
if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
|
|
1495
1686
|
reader.cancel().catch(() => {});
|
|
1496
1687
|
}, { once: true });
|
|
@@ -1520,6 +1711,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1520
1711
|
const lines = decoder.decode(value).split("\n");
|
|
1521
1712
|
for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
|
|
1522
1713
|
const data = JSON.parse(line.slice(6));
|
|
1714
|
+
if (continuation) {
|
|
1715
|
+
if (!continuationTextResumed && data.type === "text-start") {
|
|
1716
|
+
for (let k = message.parts.length - 1; k >= 0; k--) {
|
|
1717
|
+
const part = message.parts[k];
|
|
1718
|
+
if (part.type === "text") {
|
|
1719
|
+
if ("state" in part && part.state === "streaming") continuationTextResumed = true;
|
|
1720
|
+
break;
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
if (continuationTextResumed) continue;
|
|
1724
|
+
}
|
|
1725
|
+
if (!continuationReasoningResumed && data.type === "reasoning-start") {
|
|
1726
|
+
for (let k = message.parts.length - 1; k >= 0; k--) if (message.parts[k].type === "reasoning") {
|
|
1727
|
+
continuationReasoningResumed = true;
|
|
1728
|
+
break;
|
|
1729
|
+
}
|
|
1730
|
+
if (continuationReasoningResumed) continue;
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1523
1733
|
const handled = applyChunkToParts(message.parts, data);
|
|
1524
1734
|
if (data.type === "tool-approval-request" && this._streamingMessage) {
|
|
1525
1735
|
const snapshot = {
|
|
@@ -1624,16 +1834,26 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1624
1834
|
return "completed";
|
|
1625
1835
|
}
|
|
1626
1836
|
async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
}
|
|
1636
|
-
|
|
1837
|
+
let textPart;
|
|
1838
|
+
if (continuation) for (let k = message.parts.length - 1; k >= 0; k--) {
|
|
1839
|
+
const part = message.parts[k];
|
|
1840
|
+
if (part.type === "text") {
|
|
1841
|
+
if ("state" in part && part.state === "streaming") textPart = part;
|
|
1842
|
+
break;
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
if (textPart) {} else {
|
|
1846
|
+
this._broadcastTextEvent(streamId, {
|
|
1847
|
+
type: "text-start",
|
|
1848
|
+
id
|
|
1849
|
+
}, continuation);
|
|
1850
|
+
textPart = {
|
|
1851
|
+
type: "text",
|
|
1852
|
+
text: "",
|
|
1853
|
+
state: "streaming"
|
|
1854
|
+
};
|
|
1855
|
+
message.parts.push(textPart);
|
|
1856
|
+
}
|
|
1637
1857
|
if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
|
|
1638
1858
|
reader.cancel().catch(() => {});
|
|
1639
1859
|
}, { once: true });
|
|
@@ -1719,7 +1939,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1719
1939
|
}
|
|
1720
1940
|
async _reply(id, response, excludeBroadcastIds = [], options = {}) {
|
|
1721
1941
|
const { continuation = false, chatMessageId } = options;
|
|
1722
|
-
const abortSignal = chatMessageId ? this.
|
|
1942
|
+
const abortSignal = chatMessageId ? this._abortRegistry.getExistingSignal(chatMessageId) : void 0;
|
|
1723
1943
|
return this.keepAliveWhile(() => this._tryCatchChat(async () => {
|
|
1724
1944
|
if (!response.body) {
|
|
1725
1945
|
this._clearPendingAutoContinuation(true);
|
|
@@ -1771,7 +1991,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1771
1991
|
earlyPersistedId = this._approvalPersistedMessageId;
|
|
1772
1992
|
this._approvalPersistedMessageId = null;
|
|
1773
1993
|
if (chatMessageId) {
|
|
1774
|
-
this.
|
|
1994
|
+
this._abortRegistry.remove(chatMessageId);
|
|
1775
1995
|
if (streamCompleted.value) this._emit("message:response");
|
|
1776
1996
|
}
|
|
1777
1997
|
}
|
|
@@ -1802,40 +2022,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1802
2022
|
}));
|
|
1803
2023
|
}
|
|
1804
2024
|
/**
|
|
1805
|
-
* For the given message id, look up its associated AbortController
|
|
1806
|
-
* If the AbortController does not exist, create and store one in memory
|
|
1807
|
-
*
|
|
1808
|
-
* returns the AbortSignal associated with the AbortController
|
|
1809
|
-
*/
|
|
1810
|
-
_getAbortSignal(id) {
|
|
1811
|
-
if (typeof id !== "string") return;
|
|
1812
|
-
if (!this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.set(id, new AbortController());
|
|
1813
|
-
return this._chatMessageAbortControllers.get(id)?.signal;
|
|
1814
|
-
}
|
|
1815
|
-
/**
|
|
1816
|
-
* Remove an abort controller from the cache of pending message responses
|
|
1817
|
-
*/
|
|
1818
|
-
_removeAbortController(id) {
|
|
1819
|
-
this._chatMessageAbortControllers.delete(id);
|
|
1820
|
-
}
|
|
1821
|
-
/**
|
|
1822
|
-
* Propagate an abort signal for any requests associated with the given message id
|
|
1823
|
-
*/
|
|
1824
|
-
_cancelChatRequest(id) {
|
|
1825
|
-
if (this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.get(id)?.abort();
|
|
1826
|
-
}
|
|
1827
|
-
/**
|
|
1828
|
-
* Abort all pending requests and clear the cache of AbortControllers
|
|
1829
|
-
*/
|
|
1830
|
-
_destroyAbortControllers() {
|
|
1831
|
-
for (const controller of this._chatMessageAbortControllers.values()) controller?.abort();
|
|
1832
|
-
this._chatMessageAbortControllers.clear();
|
|
1833
|
-
}
|
|
1834
|
-
/**
|
|
1835
2025
|
* When the DO is destroyed, cancel all pending requests and clean up resources
|
|
1836
2026
|
*/
|
|
1837
2027
|
async destroy() {
|
|
1838
|
-
this.
|
|
2028
|
+
this._abortRegistry.destroyAll();
|
|
1839
2029
|
this._resumableStream.destroy();
|
|
1840
2030
|
await super.destroy();
|
|
1841
2031
|
}
|