@cloudflare/ai-chat 0.2.2 → 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-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) {
@@ -830,6 +900,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
830
900
  this._chatEpoch++;
831
901
  this._destroyAbortControllers();
832
902
  this._pendingInteractionPromise = null;
903
+ this._activeAutoContinuationRequestId = null;
904
+ this._activeAutoContinuationConnectionId = null;
905
+ this._clearAllAutoContinuationState(true);
833
906
  }
834
907
  async _awaitWithDeadline(promise, deadline) {
835
908
  if (deadline == null) return promise;
@@ -863,42 +936,96 @@ var AIChatAgent = class AIChatAgent extends Agent {
863
936
  releaseTurn();
864
937
  }
865
938
  }
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);
939
+ _enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
940
+ if (this._pendingAutoContinuation) {
941
+ if (this._pendingAutoContinuationPastCoalesce) {
942
+ this._storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite);
871
943
  return;
872
944
  }
873
- if (prerequisite) {
874
- if (!await prerequisite) {
875
- 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);
876
983
  return;
877
984
  }
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
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
+ }
896
1021
  });
897
- else this._clearPendingAutoContinuation(true);
898
1022
  });
899
- });
900
- })).catch((error) => {
901
- this._clearPendingAutoContinuation(true);
1023
+ } finally {
1024
+ dispose();
1025
+ }
1026
+ }).catch((error) => {
1027
+ const errorPrefix = this._pendingAutoContinuationErrorPrefix ?? "[AIChatAgent] Auto-continuation failed:";
1028
+ this._clearAllAutoContinuationState(true);
902
1029
  console.error(errorPrefix, error);
903
1030
  });
904
1031
  }
@@ -1711,6 +1838,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1711
1838
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1712
1839
  ...continuation && { continuation: true }
1713
1840
  });
1841
+ this._activateDeferredAutoContinuation();
1714
1842
  return;
1715
1843
  }
1716
1844
  const streamId = this._startStream(id);