@cloudflare/ai-chat 0.2.1 → 0.2.3

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.
@@ -1,4 +1,4 @@
1
- import { t as AIChatAgent } from "../index-BbdbMsrQ.js";
1
+ import { t as AIChatAgent } from "../index-Cd0kBa7e.js";
2
2
 
3
3
  //#region src/experimental/forever.d.ts
4
4
  declare function withDurableChat<TBase extends typeof AIChatAgent>(Base: TBase): TBase;
@@ -280,17 +280,42 @@ declare class AIChatAgent<
280
280
  private _pendingResumeConnections;
281
281
  /**
282
282
  * Connections waiting for a stream to start after requesting resume.
283
- * Used for client-side tool auto-continuations where the client asks to
284
- * resume immediately after submitting tool output, before the server has
285
- * started streaming the continuation turn.
283
+ * Used for client-side tool auto-continuations where the originating client
284
+ * asks to resume immediately after submitting tool output, before the server
285
+ * has started streaming the continuation turn.
286
286
  */
287
287
  private _awaitingStreamStartConnections;
288
288
  /**
289
289
  * True while an auto-continuation turn has been queued but has not yet
290
290
  * started streaming. This suppresses immediate STREAM_RESUME_NONE replies
291
- * so clients can attach to the upcoming continuation stream.
291
+ * so the originating client can attach to the upcoming continuation stream.
292
292
  */
293
293
  private _pendingAutoContinuation;
294
+ /**
295
+ * The latest connection/context to use for a queued auto-continuation.
296
+ * Multiple rapid tool results are coalesced into a single turn, so we keep
297
+ * the newest values here until that turn starts.
298
+ */
299
+ private _pendingAutoContinuationConnection;
300
+ /**
301
+ * Connection that initiated the pending auto-continuation.
302
+ * Only this connection should wait for the continuation stream to start.
303
+ */
304
+ private _pendingAutoContinuationConnectionId;
305
+ private _activeAutoContinuationConnectionId;
306
+ private _activeAutoContinuationRequestId;
307
+ private _pendingAutoContinuationPastCoalesce;
308
+ private _pendingAutoContinuationClientTools;
309
+ private _pendingAutoContinuationBody;
310
+ private _pendingAutoContinuationErrorPrefix;
311
+ private _pendingAutoContinuationRequestId;
312
+ /**
313
+ * Aggregate prerequisite for a queued auto-continuation.
314
+ * Each new tool result/approval extends this promise so the single queued
315
+ * continuation waits for every rapid-fire apply operation to finish.
316
+ */
317
+ private _pendingAutoContinuationPrerequisite;
318
+ private _deferredAutoContinuation;
294
319
  /**
295
320
  * Client tool schemas from the most recent chat request.
296
321
  * Stored so they can be passed to onChatMessage during tool continuations.
@@ -312,6 +337,11 @@ declare class AIChatAgent<
312
337
  private _persistedMessageCache;
313
338
  /** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
314
339
  private static ROW_MAX_BYTES;
340
+ /**
341
+ * Small debounce window to batch adjacent client-side tool results/approvals
342
+ * into a single server continuation turn.
343
+ */
344
+ private static AUTO_CONTINUATION_COALESCE_MS;
315
345
  /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
316
346
  private static _byteLength;
317
347
  /**
@@ -367,6 +397,11 @@ declare class AIChatAgent<
367
397
  messages: UIMessage[];
368
398
  constructor(ctx: AgentContext, env: Env);
369
399
  private _flushAwaitingStreamStartConnections;
400
+ private _mergeAutoContinuationPrerequisite;
401
+ private _storeDeferredAutoContinuation;
402
+ private _activateDeferredAutoContinuation;
403
+ private _clearDeferredAutoContinuation;
404
+ private _clearAllAutoContinuationState;
370
405
  private _clearPendingAutoContinuation;
371
406
  /**
372
407
  * Notify a connection about an active stream that can be resumed.
@@ -451,6 +486,8 @@ declare class AIChatAgent<
451
486
  * streaming turn.
452
487
  */
453
488
  private _runExclusiveChatTurn;
489
+ private _enqueueAutoContinuation;
490
+ private _awaitPendingAutoContinuationPrerequisite;
454
491
  private _queueAutoContinuation;
455
492
  /**
456
493
  * Handle incoming chat messages and generate a response
@@ -713,4 +750,4 @@ export {
713
750
  OnChatMessageOptions as r,
714
751
  AIChatAgent as t
715
752
  };
716
- //# sourceMappingURL=index-BbdbMsrQ.d.ts.map
753
+ //# sourceMappingURL=index-Cd0kBa7e.d.ts.map
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  n as ClientToolSchema,
4
4
  r as OnChatMessageOptions,
5
5
  t as AIChatAgent
6
- } from "./index-BbdbMsrQ.js";
6
+ } from "./index-Cd0kBa7e.js";
7
7
  export {
8
8
  AIChatAgent,
9
9
  ClientToolSchema,
package/dist/index.js CHANGED
@@ -405,6 +405,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
405
405
  static {
406
406
  this.ROW_MAX_BYTES = 18e5;
407
407
  }
408
+ static {
409
+ this.AUTO_CONTINUATION_COALESCE_MS = 10;
410
+ }
408
411
  /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
409
412
  static _byteLength(s) {
410
413
  return textEncoder.encode(s).byteLength;
@@ -420,6 +423,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
420
423
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
421
424
  this._awaitingStreamStartConnections = /* @__PURE__ */ new Map();
422
425
  this._pendingAutoContinuation = false;
426
+ this._pendingAutoContinuationConnection = null;
427
+ this._pendingAutoContinuationConnectionId = null;
428
+ this._activeAutoContinuationConnectionId = null;
429
+ this._activeAutoContinuationRequestId = null;
430
+ this._pendingAutoContinuationPastCoalesce = false;
431
+ this._pendingAutoContinuationErrorPrefix = null;
432
+ this._pendingAutoContinuationRequestId = null;
433
+ this._pendingAutoContinuationPrerequisite = null;
434
+ this._deferredAutoContinuation = null;
423
435
  this._persistedMessageCache = /* @__PURE__ */ new Map();
424
436
  this.maxPersistedMessages = void 0;
425
437
  this.waitForMcpConnections = { timeout: 1e4 };
@@ -445,6 +457,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
445
457
  this.onClose = async (connection, code, reason, wasClean) => {
446
458
  this._pendingResumeConnections.delete(connection.id);
447
459
  this._awaitingStreamStartConnections.delete(connection.id);
460
+ if (this._pendingAutoContinuationConnection?.id === connection.id) this._pendingAutoContinuationConnection = null;
461
+ if (this._activeAutoContinuationConnectionId === connection.id) this._activeAutoContinuationConnectionId = null;
448
462
  return _onClose(connection, code, reason, wasClean);
449
463
  };
450
464
  const _onMessage = this.onMessage.bind(this);
@@ -519,7 +533,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
519
533
  this.sql`delete from cf_ai_chat_agent_messages`;
520
534
  this._resumableStream.clearAll();
521
535
  this._pendingResumeConnections.clear();
522
- this._clearPendingAutoContinuation(true);
523
536
  this._lastClientTools = void 0;
524
537
  this._lastBody = void 0;
525
538
  this._persistRequestContext();
@@ -540,8 +553,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
540
553
  return;
541
554
  }
542
555
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
543
- if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
544
- else if (this._pendingAutoContinuation) this._awaitingStreamStartConnections.set(connection.id, connection);
556
+ if (this._resumableStream.hasActiveStream()) if (this._activeAutoContinuationRequestId === this._resumableStream.activeRequestId && this._activeAutoContinuationConnectionId !== null && this._activeAutoContinuationConnectionId !== connection.id) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
557
+ else this._notifyStreamResuming(connection);
558
+ else if (this._pendingAutoContinuation && this._pendingAutoContinuationConnectionId === connection.id) this._awaitingStreamStartConnections.set(connection.id, connection);
545
559
  else connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
546
560
  return;
547
561
  }
@@ -569,10 +583,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
569
583
  applyPromise.finally(() => {
570
584
  if (this._pendingInteractionPromise === applyPromise) this._pendingInteractionPromise = null;
571
585
  }).catch(() => {});
572
- if (autoContinue) {
573
- this._pendingAutoContinuation = true;
574
- this._queueAutoContinuation(connection, nanoid(), clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
575
- }
586
+ if (autoContinue) this._enqueueAutoContinuation(connection, clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
576
587
  return;
577
588
  }
578
589
  if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
@@ -586,10 +597,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
586
597
  approvalPromise.finally(() => {
587
598
  if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
588
599
  }).catch(() => {});
589
- if (autoContinue) {
590
- this._pendingAutoContinuation = true;
591
- this._queueAutoContinuation(connection, nanoid(), this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
592
- }
600
+ if (autoContinue) this._enqueueAutoContinuation(connection, this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
593
601
  return;
594
602
  }
595
603
  }
@@ -608,8 +616,58 @@ var AIChatAgent = class AIChatAgent extends Agent {
608
616
  for (const connection of this._awaitingStreamStartConnections.values()) this._notifyStreamResuming(connection);
609
617
  this._awaitingStreamStartConnections.clear();
610
618
  }
619
+ _mergeAutoContinuationPrerequisite(current, next) {
620
+ if (!next) return current;
621
+ if (!current) return next;
622
+ return Promise.all([current, next]).then(([currentApplied, nextApplied]) => {
623
+ return currentApplied && nextApplied;
624
+ });
625
+ }
626
+ _storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
627
+ const deferred = this._deferredAutoContinuation;
628
+ this._deferredAutoContinuation = {
629
+ connection,
630
+ connectionId: connection.id,
631
+ clientTools,
632
+ body,
633
+ errorPrefix,
634
+ prerequisite: this._mergeAutoContinuationPrerequisite(deferred?.prerequisite ?? null, prerequisite)
635
+ };
636
+ }
637
+ _activateDeferredAutoContinuation() {
638
+ if (this._pendingAutoContinuation || !this._deferredAutoContinuation) return;
639
+ const deferred = this._deferredAutoContinuation;
640
+ this._deferredAutoContinuation = null;
641
+ this._pendingAutoContinuationConnection = deferred.connection;
642
+ this._pendingAutoContinuationConnectionId = deferred.connectionId;
643
+ this._awaitingStreamStartConnections.set(deferred.connectionId, deferred.connection);
644
+ this._pendingAutoContinuationClientTools = deferred.clientTools;
645
+ this._pendingAutoContinuationBody = deferred.body;
646
+ this._pendingAutoContinuationErrorPrefix = deferred.errorPrefix;
647
+ this._pendingAutoContinuationPrerequisite = deferred.prerequisite;
648
+ this._pendingAutoContinuationPastCoalesce = false;
649
+ const requestId = nanoid();
650
+ this._pendingAutoContinuation = true;
651
+ this._pendingAutoContinuationRequestId = requestId;
652
+ this._queueAutoContinuation(requestId);
653
+ }
654
+ _clearDeferredAutoContinuation() {
655
+ this._deferredAutoContinuation = null;
656
+ }
657
+ _clearAllAutoContinuationState(sendNone = false) {
658
+ this._clearPendingAutoContinuation(sendNone);
659
+ this._clearDeferredAutoContinuation();
660
+ }
611
661
  _clearPendingAutoContinuation(sendNone = false) {
612
662
  this._pendingAutoContinuation = false;
663
+ this._pendingAutoContinuationConnection = null;
664
+ this._pendingAutoContinuationClientTools = void 0;
665
+ this._pendingAutoContinuationBody = void 0;
666
+ this._pendingAutoContinuationErrorPrefix = null;
667
+ this._pendingAutoContinuationRequestId = null;
668
+ this._pendingAutoContinuationPrerequisite = null;
669
+ this._pendingAutoContinuationConnectionId = null;
670
+ this._pendingAutoContinuationPastCoalesce = false;
613
671
  if (sendNone) for (const connection of this._awaitingStreamStartConnections.values()) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
614
672
  this._awaitingStreamStartConnections.clear();
615
673
  }
@@ -637,14 +695,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
637
695
  /** @internal Delegate to _resumableStream */
638
696
  _startStream(requestId) {
639
697
  const streamId = this._resumableStream.start(requestId);
640
- this._pendingAutoContinuation = false;
641
- this._flushAwaitingStreamStartConnections();
698
+ if (this._pendingAutoContinuationRequestId === requestId) {
699
+ this._activeAutoContinuationRequestId = requestId;
700
+ this._activeAutoContinuationConnectionId = this._pendingAutoContinuationConnectionId;
701
+ this._pendingAutoContinuation = false;
702
+ this._pendingAutoContinuationConnection = null;
703
+ this._pendingAutoContinuationConnectionId = null;
704
+ this._pendingAutoContinuationClientTools = void 0;
705
+ this._pendingAutoContinuationBody = void 0;
706
+ this._pendingAutoContinuationErrorPrefix = null;
707
+ this._pendingAutoContinuationRequestId = null;
708
+ this._pendingAutoContinuationPrerequisite = null;
709
+ this._flushAwaitingStreamStartConnections();
710
+ this._pendingAutoContinuationPastCoalesce = false;
711
+ this._activateDeferredAutoContinuation();
712
+ }
642
713
  return streamId;
643
714
  }
644
715
  /** @internal Delegate to _resumableStream */
645
716
  _completeStream(streamId) {
717
+ const completedRequestId = this._resumableStream.activeRequestId;
646
718
  this._resumableStream.complete(streamId);
647
719
  this._pendingResumeConnections.clear();
720
+ if (completedRequestId === this._activeAutoContinuationRequestId) {
721
+ this._activeAutoContinuationRequestId = null;
722
+ this._activeAutoContinuationConnectionId = null;
723
+ }
648
724
  }
649
725
  /** @internal Delegate to _resumableStream */
650
726
  _storeStreamChunk(streamId, body) {
@@ -824,6 +900,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
824
900
  this._chatEpoch++;
825
901
  this._destroyAbortControllers();
826
902
  this._pendingInteractionPromise = null;
903
+ this._activeAutoContinuationRequestId = null;
904
+ this._activeAutoContinuationConnectionId = null;
905
+ this._clearAllAutoContinuationState(true);
827
906
  }
828
907
  async _awaitWithDeadline(promise, deadline) {
829
908
  if (deadline == null) return promise;
@@ -857,42 +936,96 @@ var AIChatAgent = class AIChatAgent extends Agent {
857
936
  releaseTurn();
858
937
  }
859
938
  }
860
- _queueAutoContinuation(connection, requestId, clientTools, body, errorPrefix, prerequisite) {
861
- const epoch = this._chatEpoch;
862
- this.keepAliveWhile(() => this._runExclusiveChatTurn(requestId, async () => {
863
- if (this._chatEpoch !== epoch) {
864
- this._clearPendingAutoContinuation(true);
939
+ _enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
940
+ if (this._pendingAutoContinuation) {
941
+ if (this._pendingAutoContinuationPastCoalesce) {
942
+ this._storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite);
865
943
  return;
866
944
  }
867
- if (prerequisite) {
868
- if (!await prerequisite) {
869
- this._clearPendingAutoContinuation(true);
945
+ this._pendingAutoContinuationConnection = connection;
946
+ this._pendingAutoContinuationConnectionId = connection.id;
947
+ this._awaitingStreamStartConnections.set(connection.id, connection);
948
+ this._pendingAutoContinuationClientTools = clientTools;
949
+ this._pendingAutoContinuationBody = body;
950
+ this._pendingAutoContinuationErrorPrefix = errorPrefix;
951
+ this._pendingAutoContinuationPrerequisite = this._mergeAutoContinuationPrerequisite(this._pendingAutoContinuationPrerequisite, prerequisite);
952
+ return;
953
+ }
954
+ this._pendingAutoContinuationConnection = connection;
955
+ this._pendingAutoContinuationConnectionId = connection.id;
956
+ this._awaitingStreamStartConnections.set(connection.id, connection);
957
+ this._pendingAutoContinuationClientTools = clientTools;
958
+ this._pendingAutoContinuationBody = body;
959
+ this._pendingAutoContinuationErrorPrefix = errorPrefix;
960
+ this._pendingAutoContinuationPrerequisite = this._mergeAutoContinuationPrerequisite(this._pendingAutoContinuationPrerequisite, prerequisite);
961
+ this._pendingAutoContinuationPastCoalesce = false;
962
+ const requestId = nanoid();
963
+ this._pendingAutoContinuation = true;
964
+ this._pendingAutoContinuationRequestId = requestId;
965
+ this._queueAutoContinuation(requestId);
966
+ }
967
+ async _awaitPendingAutoContinuationPrerequisite() {
968
+ while (true) {
969
+ const prerequisite = this._pendingAutoContinuationPrerequisite;
970
+ if (!prerequisite) return true;
971
+ if (!await prerequisite) return false;
972
+ await new Promise((resolve) => setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS));
973
+ if (this._pendingAutoContinuationPrerequisite === prerequisite) return true;
974
+ }
975
+ }
976
+ _queueAutoContinuation(requestId) {
977
+ const epoch = this._chatEpoch;
978
+ this._runExclusiveChatTurn(requestId, async () => {
979
+ const dispose = await this.keepAlive();
980
+ try {
981
+ if (this._chatEpoch !== epoch) {
982
+ this._clearAllAutoContinuationState(true);
870
983
  return;
871
984
  }
872
- }
873
- const abortSignal = this._getAbortSignal(requestId);
874
- return this._tryCatchChat(async () => {
875
- return __DO_NOT_USE_WILL_BREAK__agentContext.run({
876
- agent: this,
877
- connection,
878
- request: void 0,
879
- email: void 0
880
- }, async () => {
881
- const response = await this.onChatMessage(async (_finishResult) => {}, {
882
- requestId,
883
- abortSignal,
884
- clientTools,
885
- body
886
- });
887
- if (response) await this._reply(requestId, response, [], {
888
- continuation: true,
889
- chatMessageId: requestId
985
+ if (!await this._awaitPendingAutoContinuationPrerequisite()) {
986
+ this._clearAllAutoContinuationState(true);
987
+ return;
988
+ }
989
+ const connection = this._pendingAutoContinuationConnection;
990
+ if (!connection) {
991
+ this._clearAllAutoContinuationState(true);
992
+ return;
993
+ }
994
+ const clientTools = this._pendingAutoContinuationClientTools;
995
+ const body = this._pendingAutoContinuationBody;
996
+ this._pendingAutoContinuationPastCoalesce = true;
997
+ const abortSignal = this._getAbortSignal(requestId);
998
+ return this._tryCatchChat(async () => {
999
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
1000
+ agent: this,
1001
+ connection,
1002
+ request: void 0,
1003
+ email: void 0
1004
+ }, async () => {
1005
+ const response = await this.onChatMessage(async (_finishResult) => {}, {
1006
+ requestId,
1007
+ abortSignal,
1008
+ clientTools,
1009
+ body
1010
+ });
1011
+ if (response) {
1012
+ await this._reply(requestId, response, [], {
1013
+ continuation: true,
1014
+ chatMessageId: requestId
1015
+ });
1016
+ this._activateDeferredAutoContinuation();
1017
+ } else {
1018
+ this._clearPendingAutoContinuation(true);
1019
+ this._activateDeferredAutoContinuation();
1020
+ }
890
1021
  });
891
- else this._clearPendingAutoContinuation(true);
892
1022
  });
893
- });
894
- })).catch((error) => {
895
- this._clearPendingAutoContinuation(true);
1023
+ } finally {
1024
+ dispose();
1025
+ }
1026
+ }).catch((error) => {
1027
+ const errorPrefix = this._pendingAutoContinuationErrorPrefix ?? "[AIChatAgent] Auto-continuation failed:";
1028
+ this._clearAllAutoContinuationState(true);
896
1029
  console.error(errorPrefix, error);
897
1030
  });
898
1031
  }
@@ -1705,6 +1838,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1705
1838
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1706
1839
  ...continuation && { continuation: true }
1707
1840
  });
1841
+ this._activateDeferredAutoContinuation();
1708
1842
  return;
1709
1843
  }
1710
1844
  const streamId = this._startStream(id);