@cloudflare/ai-chat 0.9.3 → 0.9.4
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.js +94 -32
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -4,6 +4,9 @@ import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, isDurableObjectMemoryLimi
|
|
|
4
4
|
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, STREAM_CLEANUP_DELAY_SECONDS, StreamProgressCreditThrottle, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyChunkToParts, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, bumpChatRecoveryProgress, chatRecoverySchedulePolicy, classifyAgentToolChildRecovery, cleanupStreamBuffers, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createToolsFromClientSchemas, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, isReplayChunk, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, parseProtocolMessage, partAwaitsClientInteraction, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, sendIfOpen, setChatRecovering, shouldCreditStreamProgress, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
5
5
|
import { nanoid } from "nanoid";
|
|
6
6
|
//#region src/index.ts
|
|
7
|
+
function withAgentSpan(host, operation, storagePhase, attributes, run) {
|
|
8
|
+
return host._withAgentSpan(operation, storagePhase, attributes, run);
|
|
9
|
+
}
|
|
7
10
|
/**
|
|
8
11
|
* Provider-executed tool fields that contain opaque replay tokens and must be
|
|
9
12
|
* persisted exactly as returned by the provider.
|
|
@@ -179,20 +182,30 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
179
182
|
this._inSerializedDetachedDeliverySlot = false;
|
|
180
183
|
this._inFlightDetachedNotifications = /* @__PURE__ */ new Set();
|
|
181
184
|
this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
|
|
182
|
-
this
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
185
|
+
withAgentSpan(this, "chat_initialization", "initialization", { "cloudflare.agents.component": "ai_chat" }, (update) => {
|
|
186
|
+
withAgentSpan(this, "initialize_chat_storage", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => {
|
|
187
|
+
this.sql`create table if not exists cf_ai_chat_agent_messages (
|
|
188
|
+
id text primary key,
|
|
189
|
+
message text not null,
|
|
190
|
+
created_at datetime default current_timestamp
|
|
191
|
+
)`;
|
|
192
|
+
this.sql`create table if not exists cf_ai_chat_request_context (
|
|
193
|
+
key text primary key,
|
|
194
|
+
value text not null
|
|
195
|
+
)`;
|
|
196
|
+
this._ensureAgentToolTables();
|
|
197
|
+
});
|
|
198
|
+
withAgentSpan(this, "restore_chat_request_context", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => this._restoreRequestContext());
|
|
199
|
+
withAgentSpan(this, "initialize_resumable_stream", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => {
|
|
200
|
+
this._resumableStream = new ResumableStream(this.sql.bind(this));
|
|
201
|
+
});
|
|
202
|
+
const rawMessages = withAgentSpan(this, "load_chat_messages", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => this._loadMessagesFromDb());
|
|
203
|
+
this.messages = autoTransformMessages(rawMessages);
|
|
204
|
+
update({
|
|
205
|
+
"cloudflare.agents.chat.messages.loaded": rawMessages.length,
|
|
206
|
+
"cloudflare.agents.chat.active_stream.restored": this._resumableStream.hasActiveStream()
|
|
207
|
+
});
|
|
208
|
+
});
|
|
196
209
|
this._abortRegistry = new AbortRegistry();
|
|
197
210
|
const _onConnect = this.onConnect.bind(this);
|
|
198
211
|
this.onConnect = async (connection, ctx) => {
|
|
@@ -212,7 +225,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
212
225
|
return _onClose(connection, code, reason, wasClean);
|
|
213
226
|
};
|
|
214
227
|
const _onMessage = this.onMessage.bind(this);
|
|
215
|
-
|
|
228
|
+
const handleMessage = async (connection, message) => {
|
|
216
229
|
if (this._cf_connectionTargetsSubAgent(connection)) return _onMessage(connection, message);
|
|
217
230
|
if (typeof message === "string") {
|
|
218
231
|
const event = parseProtocolMessage(message);
|
|
@@ -243,17 +256,27 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
243
256
|
this._completeSkippedRequest(connection, chatMessageId);
|
|
244
257
|
return;
|
|
245
258
|
}
|
|
246
|
-
await this
|
|
259
|
+
await withAgentSpan(this, "clear_previous_chat_state", "interaction", {
|
|
260
|
+
"cloudflare.agents.component": "ai_chat",
|
|
261
|
+
"cloudflare.agents.turn.request_id": chatMessageId,
|
|
262
|
+
"cloudflare.agents.turn.trigger": requestTrigger
|
|
263
|
+
}, () => this._clearChatTerminal());
|
|
247
264
|
this._preStream.begin(chatMessageId);
|
|
248
265
|
try {
|
|
249
266
|
const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
|
|
250
267
|
try {
|
|
251
|
-
this
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
268
|
+
await withAgentSpan(this, "persist_incoming_messages", "interaction", {
|
|
269
|
+
"cloudflare.agents.component": "ai_chat",
|
|
270
|
+
"cloudflare.agents.turn.request_id": chatMessageId,
|
|
271
|
+
"cloudflare.agents.turn.trigger": requestTrigger
|
|
272
|
+
}, async () => {
|
|
273
|
+
this._broadcastChatMessage({
|
|
274
|
+
messages: transformedMessages,
|
|
275
|
+
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
276
|
+
}, [connection.id]);
|
|
277
|
+
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
278
|
+
if (concurrencyDecision.strategy === "merge") await this._mergeQueuedUserMessages(epoch);
|
|
279
|
+
});
|
|
257
280
|
} finally {
|
|
258
281
|
releasePendingEnqueue();
|
|
259
282
|
}
|
|
@@ -274,7 +297,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
274
297
|
}
|
|
275
298
|
}
|
|
276
299
|
if (concurrencyDecision.strategy === "merge") {
|
|
277
|
-
await this
|
|
300
|
+
await withAgentSpan(this, "merge_queued_messages", "turn", {
|
|
301
|
+
"cloudflare.agents.component": "ai_chat",
|
|
302
|
+
"cloudflare.agents.turn.request_id": chatMessageId,
|
|
303
|
+
"cloudflare.agents.turn.trigger": requestTrigger,
|
|
304
|
+
"cloudflare.agents.turn.admission": "queue",
|
|
305
|
+
"cloudflare.agents.turn.generation": epoch
|
|
306
|
+
}, () => this._mergeQueuedUserMessages(epoch));
|
|
278
307
|
if (this._turnQueue.generation !== epoch) {
|
|
279
308
|
this._completeSkippedRequest(connection, chatMessageId);
|
|
280
309
|
return;
|
|
@@ -284,11 +313,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
284
313
|
return;
|
|
285
314
|
}
|
|
286
315
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
316
|
+
await withAgentSpan(this, "prepare_chat_context", "turn", {
|
|
317
|
+
"cloudflare.agents.component": "ai_chat",
|
|
318
|
+
"cloudflare.agents.turn.request_id": chatMessageId,
|
|
319
|
+
"cloudflare.agents.turn.trigger": requestTrigger,
|
|
320
|
+
"cloudflare.agents.turn.admission": "queue",
|
|
321
|
+
"cloudflare.agents.turn.generation": epoch
|
|
322
|
+
}, async () => {
|
|
323
|
+
if (this.waitForMcpConnections) {
|
|
324
|
+
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
|
|
325
|
+
await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
|
|
326
|
+
}
|
|
327
|
+
this._setRequestContext(requestClientTools, requestBody);
|
|
328
|
+
});
|
|
292
329
|
this._emit("message:request");
|
|
293
330
|
const abortSignal = this._abortRegistry.getSignal(chatMessageId);
|
|
294
331
|
return this._tryCatchChat(async () => {
|
|
@@ -300,7 +337,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
300
337
|
}, async () => {
|
|
301
338
|
const chatTurnBody = async () => {
|
|
302
339
|
try {
|
|
303
|
-
await this
|
|
340
|
+
await withAgentSpan(this, "repair_interrupted_tools", "turn", {
|
|
341
|
+
"cloudflare.agents.component": "ai_chat",
|
|
342
|
+
"cloudflare.agents.turn.request_id": chatMessageId,
|
|
343
|
+
"cloudflare.agents.turn.trigger": requestTrigger,
|
|
344
|
+
"cloudflare.agents.turn.admission": "queue",
|
|
345
|
+
"cloudflare.agents.turn.generation": epoch
|
|
346
|
+
}, () => this._repairInterruptedToolsBeforeTurn());
|
|
304
347
|
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
305
348
|
requestId: chatMessageId,
|
|
306
349
|
abortSignal,
|
|
@@ -308,7 +351,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
308
351
|
body: requestBody,
|
|
309
352
|
continuation: false
|
|
310
353
|
});
|
|
311
|
-
if (response) await this
|
|
354
|
+
if (response) await withAgentSpan(this, "persist_chat_result", "turn", {
|
|
355
|
+
"cloudflare.agents.component": "ai_chat",
|
|
356
|
+
"cloudflare.agents.turn.request_id": chatMessageId,
|
|
357
|
+
"cloudflare.agents.turn.trigger": requestTrigger,
|
|
358
|
+
"cloudflare.agents.turn.admission": "queue",
|
|
359
|
+
"cloudflare.agents.turn.generation": epoch
|
|
360
|
+
}, () => this._reply(chatMessageId, response, [connection.id], { chatMessageId }));
|
|
312
361
|
else {
|
|
313
362
|
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
314
363
|
this._broadcastChatMessage({
|
|
@@ -364,7 +413,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
364
413
|
return;
|
|
365
414
|
}
|
|
366
415
|
if (event.type === "stream-resume-request") {
|
|
367
|
-
await this._resumeHandshake().handleResumeRequest(connection);
|
|
416
|
+
await this._resumeHandshake().handleResumeRequest(connection, event.probeId);
|
|
368
417
|
return;
|
|
369
418
|
}
|
|
370
419
|
if (event.type === "stream-resume-ack") {
|
|
@@ -401,6 +450,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
401
450
|
}
|
|
402
451
|
return _onMessage(connection, message);
|
|
403
452
|
};
|
|
453
|
+
this.onMessage = (connection, message) => {
|
|
454
|
+
const event = typeof message === "string" ? parseProtocolMessage(message) : null;
|
|
455
|
+
if (event?.type === "chat-request") return withAgentSpan(this, "chat_interaction", "interaction", {
|
|
456
|
+
"cloudflare.agents.component": "ai_chat",
|
|
457
|
+
"cloudflare.agents.turn.request_id": event.id
|
|
458
|
+
}, () => handleMessage(connection, message));
|
|
459
|
+
return handleMessage(connection, message);
|
|
460
|
+
};
|
|
404
461
|
const _onRequest = this.onRequest.bind(this);
|
|
405
462
|
this.onRequest = async (request) => {
|
|
406
463
|
return this._tryCatchChat(async () => {
|
|
@@ -1166,7 +1223,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1166
1223
|
const generation = options?.epoch;
|
|
1167
1224
|
let result;
|
|
1168
1225
|
try {
|
|
1169
|
-
result = await this._turnQueue.enqueue(requestId,
|
|
1226
|
+
result = await this._turnQueue.enqueue(requestId, () => withAgentSpan(this, "chat_turn", "turn", {
|
|
1227
|
+
"cloudflare.agents.component": "ai_chat",
|
|
1228
|
+
"cloudflare.agents.turn.request_id": requestId,
|
|
1229
|
+
"cloudflare.agents.turn.admission": "queue",
|
|
1230
|
+
"cloudflare.agents.turn.generation": generation
|
|
1231
|
+
}, fn), { generation });
|
|
1170
1232
|
} finally {
|
|
1171
1233
|
const gen = generation ?? this._turnQueue.generation;
|
|
1172
1234
|
if (this._turnQueue.queuedCount(gen) === 0) this._mergeQueuedUserStartIndexByEpoch.delete(gen);
|