@cloudflare/ai-chat 0.9.1 → 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 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.sql`create table if not exists cf_ai_chat_agent_messages (
183
- id text primary key,
184
- message text not null,
185
- created_at datetime default current_timestamp
186
- )`;
187
- this.sql`create table if not exists cf_ai_chat_request_context (
188
- key text primary key,
189
- value text not null
190
- )`;
191
- this._ensureAgentToolTables();
192
- this._restoreRequestContext();
193
- this._resumableStream = new ResumableStream(this.sql.bind(this));
194
- const rawMessages = this._loadMessagesFromDb();
195
- this.messages = autoTransformMessages(rawMessages);
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
- this.onMessage = async (connection, message) => {
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._clearChatTerminal();
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._broadcastChatMessage({
252
- messages: transformedMessages,
253
- type: MessageType.CF_AGENT_CHAT_MESSAGES
254
- }, [connection.id]);
255
- await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
256
- if (concurrencyDecision.strategy === "merge") await this._mergeQueuedUserMessages(epoch);
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._mergeQueuedUserMessages(epoch);
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
- if (this.waitForMcpConnections) {
288
- const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
289
- await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
290
- }
291
- this._setRequestContext(requestClientTools, requestBody);
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._repairInterruptedToolsBeforeTurn();
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._reply(chatMessageId, response, [connection.id], { chatMessageId });
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, fn, { generation });
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);
@@ -1943,13 +2005,47 @@ var AIChatAgent = class AIChatAgent extends Agent {
1943
2005
  return this._getAgentToolStoredChunks(row.request_id, options?.afterSequence);
1944
2006
  }
1945
2007
  async tailAgentToolRun(runId, options) {
2008
+ let closed = false;
2009
+ let forward;
2010
+ const detach = () => {
2011
+ if (forward) {
2012
+ const set = this._agentToolForwarders.get(runId);
2013
+ set?.delete(forward);
2014
+ if (set && set.size === 0) this._agentToolForwarders.delete(runId);
2015
+ forward = void 0;
2016
+ }
2017
+ };
1946
2018
  return new ReadableStream({
1947
2019
  start: async (controller) => {
1948
- let closed = false;
2020
+ let lastEmitted = options?.afterSequence ?? -1;
2021
+ const emit = (chunk) => {
2022
+ if (closed) return;
2023
+ if (chunk.sequence <= lastEmitted) return;
2024
+ lastEmitted = chunk.sequence;
2025
+ try {
2026
+ controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
2027
+ } catch {
2028
+ closed = true;
2029
+ detach();
2030
+ }
2031
+ };
2032
+ let draining = true;
2033
+ const pending = [];
2034
+ forward = (chunk) => {
2035
+ if (closed) return;
2036
+ if (draining) {
2037
+ pending.push(chunk);
2038
+ return;
2039
+ }
2040
+ emit(chunk);
2041
+ };
1949
2042
  const close = () => {
1950
2043
  if (closed) return;
1951
2044
  closed = true;
1952
- controller.close();
2045
+ detach();
2046
+ try {
2047
+ controller.close();
2048
+ } catch {}
1953
2049
  };
1954
2050
  const onAbort = () => close();
1955
2051
  try {
@@ -1958,34 +2054,37 @@ var AIChatAgent = class AIChatAgent extends Agent {
1958
2054
  return;
1959
2055
  }
1960
2056
  options?.signal?.addEventListener("abort", onAbort, { once: true });
2057
+ const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
2058
+ forwarders.add(forward);
2059
+ this._agentToolForwarders.set(runId, forwarders);
2060
+ const closers = this._agentToolClosers.get(runId) ?? /* @__PURE__ */ new Set();
2061
+ closers.add(close);
2062
+ this._agentToolClosers.set(runId, closers);
1961
2063
  for (const chunk of await this.getAgentToolChunks(runId, options)) {
1962
2064
  if (closed) return;
1963
- controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
2065
+ emit(chunk);
1964
2066
  }
2067
+ draining = false;
2068
+ for (const chunk of pending) emit(chunk);
2069
+ pending.length = 0;
1965
2070
  const inspection = await this.inspectAgentToolRun(runId);
1966
2071
  if (!inspection || inspection.status !== "running") {
1967
2072
  close();
1968
2073
  return;
1969
2074
  }
1970
- const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
1971
- const forward = (chunk) => {
1972
- if (closed) return;
1973
- try {
1974
- controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1975
- } catch {
1976
- close();
1977
- }
1978
- };
1979
- forwarders.add(forward);
1980
- this._agentToolForwarders.set(runId, forwarders);
1981
- const closers = this._agentToolClosers.get(runId) ?? /* @__PURE__ */ new Set();
1982
- closers.add(close);
1983
- this._agentToolClosers.set(runId, closers);
2075
+ if (lastEmitted > (options?.afterSequence ?? -1)) this._agentToolLiveSequences.set(runId, lastEmitted + 1);
1984
2076
  } catch (error) {
1985
- controller.error(error);
2077
+ closed = true;
2078
+ detach();
2079
+ try {
2080
+ controller.error(error);
2081
+ } catch {}
1986
2082
  }
1987
2083
  },
1988
- cancel: () => {}
2084
+ cancel: () => {
2085
+ closed = true;
2086
+ detach();
2087
+ }
1989
2088
  });
1990
2089
  }
1991
2090
  _getAgentToolRunRow(runId) {