@cloudflare/ai-chat 0.4.4 → 0.4.6

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 CHANGED
@@ -25,6 +25,12 @@ type ChatRecoveryContext = {
25
25
  unknown
26
26
  > /** Client tool schemas from the last chat request. */;
27
27
  lastClientTools?: ClientToolSchema$1[];
28
+ /**
29
+ * Epoch milliseconds when the underlying fiber was started. Compare against
30
+ * `Date.now()` to suppress continuations for turns that have been orphaned
31
+ * too long to safely replay.
32
+ */
33
+ createdAt: number;
28
34
  };
29
35
  /**
30
36
  * Options returned from `onChatRecovery` to control recovery behavior.
@@ -361,6 +367,17 @@ declare class AIChatAgent<
361
367
  private _loadMessagesFromDb;
362
368
  private _tryCatchChat;
363
369
  private isChatTurnActive;
370
+ /**
371
+ * Wait until the agent is fully idle — both the turn queue is drained
372
+ * AND no submits are in flight between the concurrency decision and
373
+ * `_runExclusiveChatTurn` (mid-`persistMessages` etc.).
374
+ *
375
+ * Just awaiting `_turnQueue.waitForIdle()` would miss submits whose
376
+ * handlers have bumped `_latestOverlappingSubmitSequence` and
377
+ * incremented `_pendingEnqueueCount` but haven't yet reached
378
+ * `_runExclusiveChatTurn` — those would race with anything calling
379
+ * `waitForIdle()` (tests, `waitUntilStable`, recovery code).
380
+ */
364
381
  private waitForIdle;
365
382
  private _normalizeMessageConcurrency;
366
383
  private _getSubmitConcurrencyDecision;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { MessageType } from "./types.js";
1
+ import "./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
4
  import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, sanitizeMessage } from "agents/chat";
@@ -190,7 +190,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
190
190
  )`;
191
191
  this._restoreRequestContext();
192
192
  this._resumableStream = new ResumableStream(this.sql.bind(this));
193
- this.messages = autoTransformMessages(this._loadMessagesFromDb());
193
+ const rawMessages = this._loadMessagesFromDb();
194
+ this.messages = autoTransformMessages(rawMessages);
194
195
  this._abortRegistry = new AbortRegistry();
195
196
  const _onConnect = this.onConnect.bind(this);
196
197
  this.onConnect = async (connection, ctx) => {
@@ -214,7 +215,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
214
215
  } catch (_error) {
215
216
  return _onMessage(connection, message);
216
217
  }
217
- if (data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST && data.init.method === "POST") {
218
+ if (data.type === "cf_agent_use_chat_request" && data.init.method === "POST") {
218
219
  const { body } = data.init;
219
220
  if (!body) {
220
221
  console.warn("[AIChatAgent] Received chat request with empty body, ignoring");
@@ -244,7 +245,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
244
245
  try {
245
246
  this._broadcastChatMessage({
246
247
  messages: transformedMessages,
247
- type: MessageType.CF_AGENT_CHAT_MESSAGES
248
+ type: "cf_agent_chat_messages"
248
249
  }, [connection.id]);
249
250
  await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
250
251
  if (concurrencyDecision.mergeQueuedMessages) await this._mergeQueuedUserMessages(epoch);
@@ -308,7 +309,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
308
309
  body: "No response was generated by the agent.",
309
310
  done: true,
310
311
  id: chatMessageId,
311
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
312
+ type: "cf_agent_use_chat_response"
312
313
  }, [connection.id]);
313
314
  }
314
315
  } finally {
@@ -326,7 +327,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
326
327
  onStale: () => this._completeSkippedRequest(connection, chatMessageId)
327
328
  });
328
329
  }
329
- if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
330
+ if (data.type === "cf_agent_chat_clear") {
330
331
  this.resetTurnState();
331
332
  this.sql`delete from cf_ai_chat_agent_messages`;
332
333
  this._resumableStream.clearAll();
@@ -336,28 +337,28 @@ var AIChatAgent = class AIChatAgent extends Agent {
336
337
  this._persistRequestContext();
337
338
  this._persistedMessageCache.clear();
338
339
  this.messages = [];
339
- this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
340
+ this._broadcastChatMessage({ type: "cf_agent_chat_clear" }, [connection.id]);
340
341
  this._emit("message:clear");
341
342
  return;
342
343
  }
343
- if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {
344
+ if (data.type === "cf_agent_chat_messages") {
344
345
  const transformedMessages = autoTransformMessages(data.messages);
345
346
  await this.persistMessages(transformedMessages, [connection.id]);
346
347
  return;
347
348
  }
348
- if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {
349
+ if (data.type === "cf_agent_chat_request_cancel") {
349
350
  this._abortRegistry.cancel(data.id);
350
351
  this._emit("message:cancel", { requestId: data.id });
351
352
  return;
352
353
  }
353
- if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
354
- if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
354
+ if (data.type === "cf_agent_stream_resume_request") {
355
+ if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) connection.send(JSON.stringify({ type: "cf_agent_stream_resume_none" }));
355
356
  else this._notifyStreamResuming(connection);
356
357
  else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
357
- else connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
358
+ else connection.send(JSON.stringify({ type: "cf_agent_stream_resume_none" }));
358
359
  return;
359
360
  }
360
- if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {
361
+ if (data.type === "cf_agent_stream_resume_ack") {
361
362
  this._pendingResumeConnections.delete(connection.id);
362
363
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
363
364
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
@@ -365,7 +366,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
365
366
  }
366
367
  return;
367
368
  }
368
- if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
369
+ if (data.type === "cf_agent_tool_result") {
369
370
  const { toolCallId, toolName, output, state, errorText, autoContinue, clientTools } = data;
370
371
  if (clientTools?.length) {
371
372
  this._lastClientTools = clientTools;
@@ -384,7 +385,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
384
385
  if (autoContinue) this._enqueueAutoContinuation(connection, clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
385
386
  return;
386
387
  }
387
- if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
388
+ if (data.type === "cf_agent_tool_approval") {
388
389
  const { toolCallId, approved, autoContinue } = data;
389
390
  this._emit("tool:approval", {
390
391
  toolCallId,
@@ -453,7 +454,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
453
454
  if (!this._resumableStream.hasActiveStream()) return;
454
455
  this._pendingResumeConnections.add(connection.id);
455
456
  connection.send(JSON.stringify({
456
- type: MessageType.CF_AGENT_STREAM_RESUMING,
457
+ type: "cf_agent_stream_resuming",
457
458
  id: this._resumableStream.activeRequestId
458
459
  }));
459
460
  }
@@ -599,7 +600,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
599
600
  body,
600
601
  done: false,
601
602
  id: event.id,
602
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
603
+ type: "cf_agent_use_chat_response",
603
604
  ...continuation && { continuation: true }
604
605
  });
605
606
  }
@@ -632,8 +633,23 @@ var AIChatAgent = class AIChatAgent extends Agent {
632
633
  isChatTurnActive() {
633
634
  return this._turnQueue.isActive;
634
635
  }
636
+ /**
637
+ * Wait until the agent is fully idle — both the turn queue is drained
638
+ * AND no submits are in flight between the concurrency decision and
639
+ * `_runExclusiveChatTurn` (mid-`persistMessages` etc.).
640
+ *
641
+ * Just awaiting `_turnQueue.waitForIdle()` would miss submits whose
642
+ * handlers have bumped `_latestOverlappingSubmitSequence` and
643
+ * incremented `_pendingEnqueueCount` but haven't yet reached
644
+ * `_runExclusiveChatTurn` — those would race with anything calling
645
+ * `waitForIdle()` (tests, `waitUntilStable`, recovery code).
646
+ */
635
647
  async waitForIdle() {
636
- await this._turnQueue.waitForIdle();
648
+ while (true) {
649
+ await this._turnQueue.waitForIdle();
650
+ if (this._pendingEnqueueCount === 0) return;
651
+ await new Promise((resolve) => setTimeout(resolve, 5));
652
+ }
637
653
  }
638
654
  _normalizeMessageConcurrency() {
639
655
  if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
@@ -796,13 +812,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
796
812
  body: "",
797
813
  done: true,
798
814
  id: requestId,
799
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
815
+ type: "cf_agent_use_chat_response"
800
816
  });
801
817
  }
802
818
  _rollbackDroppedSubmit(connection) {
803
819
  this._sendDirectMessage(connection, {
804
820
  messages: this._messagesForClientSync(),
805
- type: MessageType.CF_AGENT_CHAT_MESSAGES
821
+ type: "cf_agent_chat_messages"
806
822
  });
807
823
  }
808
824
  /** `true` when an assistant message is waiting on a client tool result or approval. */
@@ -821,7 +837,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
821
837
  async waitUntilStable(options) {
822
838
  const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
823
839
  while (true) {
824
- if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
840
+ while (true) {
841
+ if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
842
+ if (this._pendingEnqueueCount === 0) break;
843
+ if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, 5)), deadline) === TIMED_OUT) return false;
844
+ }
825
845
  if (!this.hasPendingInteraction()) return true;
826
846
  const pending = this._pendingInteractionPromise;
827
847
  if (pending) {
@@ -1254,7 +1274,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1254
1274
  recoveryData: ctx.snapshot,
1255
1275
  messages: [...this.messages],
1256
1276
  lastBody: this._lastBody,
1257
- lastClientTools: this._lastClientTools
1277
+ lastClientTools: this._lastClientTools,
1278
+ createdAt: ctx.createdAt
1258
1279
  });
1259
1280
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
1260
1281
  if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
@@ -1332,10 +1353,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
1332
1353
  }
1333
1354
  }
1334
1355
  if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
1335
- this.messages = autoTransformMessages(this._loadMessagesFromDb());
1356
+ const persisted = this._loadMessagesFromDb();
1357
+ this.messages = autoTransformMessages(persisted);
1336
1358
  this._broadcastChatMessage({
1337
1359
  messages: mergedMessages,
1338
- type: MessageType.CF_AGENT_CHAT_MESSAGES
1360
+ type: "cf_agent_chat_messages"
1339
1361
  }, excludeBroadcastIds);
1340
1362
  }
1341
1363
  /**
@@ -1628,7 +1650,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1628
1650
  where id = ${message.id}
1629
1651
  `;
1630
1652
  this._persistedMessageCache.set(message.id, json);
1631
- this.messages = autoTransformMessages(this._loadMessagesFromDb());
1653
+ const persisted = this._loadMessagesFromDb();
1654
+ this.messages = autoTransformMessages(persisted);
1632
1655
  }
1633
1656
  }
1634
1657
  if (!updated) {
@@ -1636,13 +1659,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1636
1659
  return false;
1637
1660
  }
1638
1661
  if (isStreamingMessage) this._broadcastChatMessage({
1639
- type: MessageType.CF_AGENT_MESSAGE_UPDATED,
1662
+ type: "cf_agent_message_updated",
1640
1663
  message
1641
1664
  });
1642
1665
  else {
1643
1666
  const broadcastMessage = this._findMessageByToolCallId(toolCallId);
1644
1667
  if (broadcastMessage) this._broadcastChatMessage({
1645
- type: MessageType.CF_AGENT_MESSAGE_UPDATED,
1668
+ type: "cf_agent_message_updated",
1646
1669
  message: broadcastMessage
1647
1670
  });
1648
1671
  }
@@ -1703,7 +1726,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1703
1726
  body: "",
1704
1727
  done: true,
1705
1728
  id,
1706
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1729
+ type: "cf_agent_use_chat_response",
1707
1730
  ...continuation && { continuation: true }
1708
1731
  });
1709
1732
  return "completed";
@@ -1790,7 +1813,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1790
1813
  body: data.errorText ?? JSON.stringify(data),
1791
1814
  done: false,
1792
1815
  id,
1793
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
1816
+ type: "cf_agent_use_chat_response"
1794
1817
  });
1795
1818
  break;
1796
1819
  }
@@ -1813,7 +1836,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1813
1836
  body: chunkBody,
1814
1837
  done: false,
1815
1838
  id,
1816
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1839
+ type: "cf_agent_use_chat_response",
1817
1840
  ...continuation && { continuation: true }
1818
1841
  });
1819
1842
  } catch (_error) {}
@@ -1825,7 +1848,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1825
1848
  body: "",
1826
1849
  done: true,
1827
1850
  id,
1828
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1851
+ type: "cf_agent_use_chat_response",
1829
1852
  ...continuation && { continuation: true }
1830
1853
  });
1831
1854
  return "aborted";
@@ -1879,7 +1902,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1879
1902
  body: "",
1880
1903
  done: true,
1881
1904
  id,
1882
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1905
+ type: "cf_agent_use_chat_response",
1883
1906
  ...continuation && { continuation: true }
1884
1907
  });
1885
1908
  return "completed";
@@ -1906,7 +1929,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1906
1929
  body: "",
1907
1930
  done: true,
1908
1931
  id,
1909
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1932
+ type: "cf_agent_use_chat_response",
1910
1933
  ...continuation && { continuation: true }
1911
1934
  });
1912
1935
  return "aborted";
@@ -1945,7 +1968,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1945
1968
  body: "",
1946
1969
  done: true,
1947
1970
  id,
1948
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1971
+ type: "cf_agent_use_chat_response",
1949
1972
  ...continuation && { continuation: true }
1950
1973
  });
1951
1974
  this._activateDeferredAutoContinuation();
@@ -1970,7 +1993,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1970
1993
  done: true,
1971
1994
  error: true,
1972
1995
  id,
1973
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1996
+ type: "cf_agent_use_chat_response",
1974
1997
  ...continuation && { continuation: true }
1975
1998
  });
1976
1999
  this._emit("message:error", { error: error instanceof Error ? error.message : String(error) });