@cloudflare/ai-chat 0.2.2 → 0.2.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.
@@ -1,4 +1,4 @@
1
- import { t as AIChatAgent } from "../index-qqP10Pcu.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;
@@ -291,11 +291,31 @@ declare class AIChatAgent<
291
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;
294
300
  /**
295
301
  * Connection that initiated the pending auto-continuation.
296
302
  * Only this connection should wait for the continuation stream to start.
297
303
  */
298
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;
299
319
  /**
300
320
  * Client tool schemas from the most recent chat request.
301
321
  * Stored so they can be passed to onChatMessage during tool continuations.
@@ -317,6 +337,11 @@ declare class AIChatAgent<
317
337
  private _persistedMessageCache;
318
338
  /** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
319
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;
320
345
  /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
321
346
  private static _byteLength;
322
347
  /**
@@ -372,6 +397,11 @@ declare class AIChatAgent<
372
397
  messages: UIMessage[];
373
398
  constructor(ctx: AgentContext, env: Env);
374
399
  private _flushAwaitingStreamStartConnections;
400
+ private _mergeAutoContinuationPrerequisite;
401
+ private _storeDeferredAutoContinuation;
402
+ private _activateDeferredAutoContinuation;
403
+ private _clearDeferredAutoContinuation;
404
+ private _clearAllAutoContinuationState;
375
405
  private _clearPendingAutoContinuation;
376
406
  /**
377
407
  * Notify a connection about an active stream that can be resumed.
@@ -456,6 +486,8 @@ declare class AIChatAgent<
456
486
  * streaming turn.
457
487
  */
458
488
  private _runExclusiveChatTurn;
489
+ private _enqueueAutoContinuation;
490
+ private _awaitPendingAutoContinuationPrerequisite;
459
491
  private _queueAutoContinuation;
460
492
  /**
461
493
  * Handle incoming chat messages and generate a response
@@ -718,4 +750,4 @@ export {
718
750
  OnChatMessageOptions as r,
719
751
  AIChatAgent as t
720
752
  };
721
- //# sourceMappingURL=index-qqP10Pcu.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-qqP10Pcu.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,7 +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;
423
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;
424
435
  this._persistedMessageCache = /* @__PURE__ */ new Map();
425
436
  this.maxPersistedMessages = void 0;
426
437
  this.waitForMcpConnections = { timeout: 1e4 };
@@ -446,7 +457,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
446
457
  this.onClose = async (connection, code, reason, wasClean) => {
447
458
  this._pendingResumeConnections.delete(connection.id);
448
459
  this._awaitingStreamStartConnections.delete(connection.id);
449
- if (this._pendingAutoContinuationConnectionId === connection.id) this._pendingAutoContinuationConnectionId = null;
460
+ if (this._pendingAutoContinuationConnection?.id === connection.id) this._pendingAutoContinuationConnection = null;
461
+ if (this._activeAutoContinuationConnectionId === connection.id) this._activeAutoContinuationConnectionId = null;
450
462
  return _onClose(connection, code, reason, wasClean);
451
463
  };
452
464
  const _onMessage = this.onMessage.bind(this);
@@ -521,7 +533,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
521
533
  this.sql`delete from cf_ai_chat_agent_messages`;
522
534
  this._resumableStream.clearAll();
523
535
  this._pendingResumeConnections.clear();
524
- this._clearPendingAutoContinuation(true);
525
536
  this._lastClientTools = void 0;
526
537
  this._lastBody = void 0;
527
538
  this._persistRequestContext();
@@ -542,7 +553,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
542
553
  return;
543
554
  }
544
555
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
545
- if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(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);
546
558
  else if (this._pendingAutoContinuation && this._pendingAutoContinuationConnectionId === connection.id) this._awaitingStreamStartConnections.set(connection.id, connection);
547
559
  else connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
548
560
  return;
@@ -571,11 +583,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
571
583
  applyPromise.finally(() => {
572
584
  if (this._pendingInteractionPromise === applyPromise) this._pendingInteractionPromise = null;
573
585
  }).catch(() => {});
574
- if (autoContinue) {
575
- this._pendingAutoContinuation = true;
576
- this._pendingAutoContinuationConnectionId = connection.id;
577
- this._queueAutoContinuation(connection, nanoid(), clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
578
- }
586
+ if (autoContinue) this._enqueueAutoContinuation(connection, clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
579
587
  return;
580
588
  }
581
589
  if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
@@ -589,11 +597,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
589
597
  approvalPromise.finally(() => {
590
598
  if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
591
599
  }).catch(() => {});
592
- if (autoContinue) {
593
- this._pendingAutoContinuation = true;
594
- this._pendingAutoContinuationConnectionId = connection.id;
595
- this._queueAutoContinuation(connection, nanoid(), this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
596
- }
600
+ if (autoContinue) this._enqueueAutoContinuation(connection, this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
597
601
  return;
598
602
  }
599
603
  }
@@ -612,9 +616,58 @@ var AIChatAgent = class AIChatAgent extends Agent {
612
616
  for (const connection of this._awaitingStreamStartConnections.values()) this._notifyStreamResuming(connection);
613
617
  this._awaitingStreamStartConnections.clear();
614
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
+ }
615
661
  _clearPendingAutoContinuation(sendNone = false) {
616
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;
617
669
  this._pendingAutoContinuationConnectionId = null;
670
+ this._pendingAutoContinuationPastCoalesce = false;
618
671
  if (sendNone) for (const connection of this._awaitingStreamStartConnections.values()) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
619
672
  this._awaitingStreamStartConnections.clear();
620
673
  }
@@ -642,15 +695,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
642
695
  /** @internal Delegate to _resumableStream */
643
696
  _startStream(requestId) {
644
697
  const streamId = this._resumableStream.start(requestId);
645
- this._pendingAutoContinuation = false;
646
- this._pendingAutoContinuationConnectionId = null;
647
- 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
+ }
648
713
  return streamId;
649
714
  }
650
715
  /** @internal Delegate to _resumableStream */
651
716
  _completeStream(streamId) {
717
+ const completedRequestId = this._resumableStream.activeRequestId;
652
718
  this._resumableStream.complete(streamId);
653
719
  this._pendingResumeConnections.clear();
720
+ if (completedRequestId === this._activeAutoContinuationRequestId) {
721
+ this._activeAutoContinuationRequestId = null;
722
+ this._activeAutoContinuationConnectionId = null;
723
+ }
654
724
  }
655
725
  /** @internal Delegate to _resumableStream */
656
726
  _storeStreamChunk(streamId, body) {
@@ -784,7 +854,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
784
854
  return this._activeChatTurnRequestId !== null;
785
855
  }
786
856
  async waitForIdle() {
787
- await this._chatTurnQueue;
857
+ let queue;
858
+ do {
859
+ queue = this._chatTurnQueue;
860
+ await queue;
861
+ } while (this._chatTurnQueue !== queue);
788
862
  }
789
863
  /** `true` when an assistant message is waiting on a client tool result or approval. */
790
864
  hasPendingInteraction() {
@@ -830,6 +904,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
830
904
  this._chatEpoch++;
831
905
  this._destroyAbortControllers();
832
906
  this._pendingInteractionPromise = null;
907
+ this._activeAutoContinuationRequestId = null;
908
+ this._activeAutoContinuationConnectionId = null;
909
+ this._clearAllAutoContinuationState(true);
833
910
  }
834
911
  async _awaitWithDeadline(promise, deadline) {
835
912
  if (deadline == null) return promise;
@@ -863,42 +940,96 @@ var AIChatAgent = class AIChatAgent extends Agent {
863
940
  releaseTurn();
864
941
  }
865
942
  }
866
- _queueAutoContinuation(connection, requestId, clientTools, body, errorPrefix, prerequisite) {
867
- const epoch = this._chatEpoch;
868
- this.keepAliveWhile(() => this._runExclusiveChatTurn(requestId, async () => {
869
- if (this._chatEpoch !== epoch) {
870
- this._clearPendingAutoContinuation(true);
943
+ _enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
944
+ if (this._pendingAutoContinuation) {
945
+ if (this._pendingAutoContinuationPastCoalesce) {
946
+ this._storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite);
871
947
  return;
872
948
  }
873
- if (prerequisite) {
874
- if (!await prerequisite) {
875
- this._clearPendingAutoContinuation(true);
949
+ this._pendingAutoContinuationConnection = connection;
950
+ this._pendingAutoContinuationConnectionId = connection.id;
951
+ this._awaitingStreamStartConnections.set(connection.id, connection);
952
+ this._pendingAutoContinuationClientTools = clientTools;
953
+ this._pendingAutoContinuationBody = body;
954
+ this._pendingAutoContinuationErrorPrefix = errorPrefix;
955
+ this._pendingAutoContinuationPrerequisite = this._mergeAutoContinuationPrerequisite(this._pendingAutoContinuationPrerequisite, prerequisite);
956
+ return;
957
+ }
958
+ this._pendingAutoContinuationConnection = connection;
959
+ this._pendingAutoContinuationConnectionId = connection.id;
960
+ this._awaitingStreamStartConnections.set(connection.id, connection);
961
+ this._pendingAutoContinuationClientTools = clientTools;
962
+ this._pendingAutoContinuationBody = body;
963
+ this._pendingAutoContinuationErrorPrefix = errorPrefix;
964
+ this._pendingAutoContinuationPrerequisite = this._mergeAutoContinuationPrerequisite(this._pendingAutoContinuationPrerequisite, prerequisite);
965
+ this._pendingAutoContinuationPastCoalesce = false;
966
+ const requestId = nanoid();
967
+ this._pendingAutoContinuation = true;
968
+ this._pendingAutoContinuationRequestId = requestId;
969
+ this._queueAutoContinuation(requestId);
970
+ }
971
+ async _awaitPendingAutoContinuationPrerequisite() {
972
+ while (true) {
973
+ const prerequisite = this._pendingAutoContinuationPrerequisite;
974
+ if (!prerequisite) return true;
975
+ if (!await prerequisite) return false;
976
+ await new Promise((resolve) => setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS));
977
+ if (this._pendingAutoContinuationPrerequisite === prerequisite) return true;
978
+ }
979
+ }
980
+ _queueAutoContinuation(requestId) {
981
+ const epoch = this._chatEpoch;
982
+ this._runExclusiveChatTurn(requestId, async () => {
983
+ const dispose = await this.keepAlive();
984
+ try {
985
+ if (this._chatEpoch !== epoch) {
986
+ this._clearAllAutoContinuationState(true);
876
987
  return;
877
988
  }
878
- }
879
- const abortSignal = this._getAbortSignal(requestId);
880
- return this._tryCatchChat(async () => {
881
- return __DO_NOT_USE_WILL_BREAK__agentContext.run({
882
- agent: this,
883
- connection,
884
- request: void 0,
885
- email: void 0
886
- }, async () => {
887
- const response = await this.onChatMessage(async (_finishResult) => {}, {
888
- requestId,
889
- abortSignal,
890
- clientTools,
891
- body
892
- });
893
- if (response) await this._reply(requestId, response, [], {
894
- continuation: true,
895
- chatMessageId: requestId
989
+ if (!await this._awaitPendingAutoContinuationPrerequisite()) {
990
+ this._clearAllAutoContinuationState(true);
991
+ return;
992
+ }
993
+ const connection = this._pendingAutoContinuationConnection;
994
+ if (!connection) {
995
+ this._clearAllAutoContinuationState(true);
996
+ return;
997
+ }
998
+ const clientTools = this._pendingAutoContinuationClientTools;
999
+ const body = this._pendingAutoContinuationBody;
1000
+ this._pendingAutoContinuationPastCoalesce = true;
1001
+ const abortSignal = this._getAbortSignal(requestId);
1002
+ return this._tryCatchChat(async () => {
1003
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
1004
+ agent: this,
1005
+ connection,
1006
+ request: void 0,
1007
+ email: void 0
1008
+ }, async () => {
1009
+ const response = await this.onChatMessage(async (_finishResult) => {}, {
1010
+ requestId,
1011
+ abortSignal,
1012
+ clientTools,
1013
+ body
1014
+ });
1015
+ if (response) {
1016
+ await this._reply(requestId, response, [], {
1017
+ continuation: true,
1018
+ chatMessageId: requestId
1019
+ });
1020
+ this._activateDeferredAutoContinuation();
1021
+ } else {
1022
+ this._clearPendingAutoContinuation(true);
1023
+ this._activateDeferredAutoContinuation();
1024
+ }
896
1025
  });
897
- else this._clearPendingAutoContinuation(true);
898
1026
  });
899
- });
900
- })).catch((error) => {
901
- this._clearPendingAutoContinuation(true);
1027
+ } finally {
1028
+ dispose();
1029
+ }
1030
+ }).catch((error) => {
1031
+ const errorPrefix = this._pendingAutoContinuationErrorPrefix ?? "[AIChatAgent] Auto-continuation failed:";
1032
+ this._clearAllAutoContinuationState(true);
902
1033
  console.error(errorPrefix, error);
903
1034
  });
904
1035
  }
@@ -1711,6 +1842,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1711
1842
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1712
1843
  ...continuation && { continuation: true }
1713
1844
  });
1845
+ this._activateDeferredAutoContinuation();
1714
1846
  return;
1715
1847
  }
1716
1848
  const streamId = this._startStream(id);