@cloudflare/ai-chat 0.5.1 → 0.5.2

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
@@ -132,22 +132,8 @@ declare class AIChatAgent<
132
132
  chatRecovery: boolean;
133
133
  /** First queued overlap message index for merge strategy, keyed by epoch. */
134
134
  private _mergeQueuedUserStartIndexByEpoch;
135
- /** Monotonic sequence for overlapping submit-message requests. */
136
- private _submitSequence;
137
- /** Latest overlapping submit-message sequence kept for latest/debounce. */
138
- private _latestOverlappingSubmitSequence;
139
- /**
140
- * Tracks requests that have passed concurrency decision but haven't
141
- * yet been enqueued into `_turnQueue`. Bridges the gap caused by
142
- * `await persistMessages()` between the decision and the enqueue,
143
- * preventing a race where a subsequent message sees `queuedCount()=0`
144
- * and skips concurrency handling.
145
- */
146
- private _pendingEnqueueCount;
147
- /** Active debounce timer handle, cleared on resetTurnState. */
148
- private _activeDebounceTimer;
149
- /** Resolve callback for the active debounce promise. */
150
- private _activeDebounceResolve;
135
+ /** Shared admission policy state for overlapping submit-message requests. */
136
+ private _submitConcurrency;
151
137
  /**
152
138
  * Set of connection IDs that are pending stream resume.
153
139
  * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
@@ -338,11 +324,7 @@ declare class AIChatAgent<
338
324
  * `waitForIdle()` (tests, `waitUntilStable`, recovery code).
339
325
  */
340
326
  private waitForIdle;
341
- private _normalizeMessageConcurrency;
342
327
  private _getSubmitConcurrencyDecision;
343
- private _isSupersededSubmit;
344
- private _waitForTimestamp;
345
- private _cancelActiveDebounce;
346
328
  private _mergeQueuedUserMessages;
347
329
  private _getMergedQueuedUserMessages;
348
330
  private static _mergeUserMessages;
package/dist/index.js CHANGED
@@ -1,119 +1,8 @@
1
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
- import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, sanitizeMessage } from "agents/chat";
4
+ import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, reconcileMessages, resolveToolMergeId, sanitizeMessage } from "agents/chat";
5
5
  import { nanoid } from "nanoid";
6
- //#region src/message-reconciler.ts
7
- /**
8
- * Reconcile incoming client messages against server state.
9
- *
10
- * 1. Merges server-known tool outputs into incoming messages that still
11
- * show stale states (input-available, approval-requested, approval-responded)
12
- * 2. Reconciles assistant IDs: exact match → content-key match → toolCallId match
13
- *
14
- * @param incoming - Messages from the client
15
- * @param serverMessages - Current server-side messages (source of truth)
16
- * @param sanitizeForContentKey - Function to sanitize a message before computing
17
- * its content key (typically strips ephemeral provider metadata)
18
- * @returns Reconciled messages ready for persistence
19
- */
20
- function reconcileMessages(incoming, serverMessages, sanitizeForContentKey) {
21
- return reconcileAssistantIds(mergeServerToolOutputs(incoming, serverMessages), serverMessages, sanitizeForContentKey);
22
- }
23
- /**
24
- * For a single message, resolve its ID by matching toolCallId against server state.
25
- * Prevents duplicate DB rows when client IDs differ from server IDs.
26
- * Tool call IDs are unique per conversation, so matching is safe regardless of state.
27
- */
28
- function resolveToolMergeId(message, serverMessages) {
29
- if (message.role !== "assistant") return message;
30
- for (const part of message.parts) if ("toolCallId" in part && part.toolCallId) {
31
- const toolCallId = part.toolCallId;
32
- const existing = findMessageByToolCallId(serverMessages, toolCallId);
33
- if (existing && existing.id !== message.id) return {
34
- ...message,
35
- id: existing.id
36
- };
37
- }
38
- return message;
39
- }
40
- /**
41
- * Content key for assistant messages used for dedup of identical short replies.
42
- * Returns JSON of sanitized parts, or undefined for non-assistant messages.
43
- */
44
- function assistantContentKey(message, sanitize) {
45
- if (message.role !== "assistant") return;
46
- const sanitized = sanitize ? sanitize(message) : message;
47
- return JSON.stringify(sanitized.parts);
48
- }
49
- function mergeServerToolOutputs(incoming, serverMessages) {
50
- const serverToolOutputs = /* @__PURE__ */ new Map();
51
- for (const msg of serverMessages) {
52
- if (msg.role !== "assistant") continue;
53
- for (const part of msg.parts) if ("toolCallId" in part && "state" in part && part.state === "output-available" && "output" in part) serverToolOutputs.set(part.toolCallId, part.output);
54
- }
55
- if (serverToolOutputs.size === 0) return incoming;
56
- return incoming.map((msg) => {
57
- if (msg.role !== "assistant") return msg;
58
- let hasChanges = false;
59
- const updatedParts = msg.parts.map((part) => {
60
- if ("toolCallId" in part && "state" in part && (part.state === "input-available" || part.state === "approval-requested" || part.state === "approval-responded") && serverToolOutputs.has(part.toolCallId)) {
61
- hasChanges = true;
62
- return {
63
- ...part,
64
- state: "output-available",
65
- output: serverToolOutputs.get(part.toolCallId)
66
- };
67
- }
68
- return part;
69
- });
70
- return hasChanges ? {
71
- ...msg,
72
- parts: updatedParts
73
- } : msg;
74
- });
75
- }
76
- function reconcileAssistantIds(incoming, serverMessages, sanitize) {
77
- if (serverMessages.length === 0) return incoming;
78
- const claimedServerIndices = /* @__PURE__ */ new Set();
79
- const exactMatchMap = /* @__PURE__ */ new Map();
80
- for (let i = 0; i < incoming.length; i++) {
81
- const serverIdx = serverMessages.findIndex((sm, si) => !claimedServerIndices.has(si) && sm.id === incoming[i].id);
82
- if (serverIdx !== -1) {
83
- claimedServerIndices.add(serverIdx);
84
- exactMatchMap.set(i, serverIdx);
85
- }
86
- }
87
- return incoming.map((incomingMessage, incomingIdx) => {
88
- if (exactMatchMap.has(incomingIdx)) return incomingMessage;
89
- if (incomingMessage.role !== "assistant" || hasToolCallPart(incomingMessage)) return incomingMessage;
90
- const incomingKey = assistantContentKey(incomingMessage, sanitize);
91
- if (!incomingKey) return incomingMessage;
92
- for (let i = 0; i < serverMessages.length; i++) {
93
- if (claimedServerIndices.has(i)) continue;
94
- const serverMessage = serverMessages[i];
95
- if (serverMessage.role !== "assistant" || hasToolCallPart(serverMessage)) continue;
96
- if (assistantContentKey(serverMessage, sanitize) === incomingKey) {
97
- claimedServerIndices.add(i);
98
- return {
99
- ...incomingMessage,
100
- id: serverMessage.id
101
- };
102
- }
103
- }
104
- return incomingMessage;
105
- });
106
- }
107
- function hasToolCallPart(message) {
108
- return message.parts.some((part) => "toolCallId" in part);
109
- }
110
- function findMessageByToolCallId(messages, toolCallId) {
111
- for (const msg of messages) {
112
- if (msg.role !== "assistant") continue;
113
- for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) return msg;
114
- }
115
- }
116
- //#endregion
117
6
  //#region src/index.ts
118
7
  const TIMED_OUT = Symbol("timed-out");
119
8
  /**
@@ -168,11 +57,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
168
57
  this._turnQueue = new TurnQueue();
169
58
  this.chatRecovery = false;
170
59
  this._mergeQueuedUserStartIndexByEpoch = /* @__PURE__ */ new Map();
171
- this._submitSequence = 0;
172
- this._latestOverlappingSubmitSequence = 0;
173
- this._pendingEnqueueCount = 0;
174
- this._activeDebounceTimer = null;
175
- this._activeDebounceResolve = null;
60
+ this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: AIChatAgent.MESSAGE_DEBOUNCE_MS });
176
61
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
177
62
  this._continuation = new ContinuationState();
178
63
  this._persistedMessageCache = /* @__PURE__ */ new Map();
@@ -242,40 +127,40 @@ var AIChatAgent = class AIChatAgent extends Agent {
242
127
  this._completeSkippedRequest(connection, chatMessageId);
243
128
  return;
244
129
  }
245
- this._pendingEnqueueCount++;
130
+ const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
246
131
  try {
247
132
  this._broadcastChatMessage({
248
133
  messages: transformedMessages,
249
134
  type: "cf_agent_chat_messages"
250
135
  }, [connection.id]);
251
136
  await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
252
- if (concurrencyDecision.mergeQueuedMessages) await this._mergeQueuedUserMessages(epoch);
137
+ if (concurrencyDecision.strategy === "merge") await this._mergeQueuedUserMessages(epoch);
253
138
  } finally {
254
- this._pendingEnqueueCount = Math.max(0, this._pendingEnqueueCount - 1);
139
+ releasePendingEnqueue();
255
140
  }
256
141
  return this._runExclusiveChatTurn(chatMessageId, async () => {
257
- if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
142
+ if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
258
143
  this._completeSkippedRequest(connection, chatMessageId);
259
144
  return;
260
145
  }
261
146
  if (concurrencyDecision.debounceUntilMs !== null) {
262
- await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
147
+ await this._submitConcurrency.waitForTimestamp(concurrencyDecision.debounceUntilMs);
263
148
  if (this._turnQueue.generation !== epoch) {
264
149
  this._completeSkippedRequest(connection, chatMessageId);
265
150
  return;
266
151
  }
267
- if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
152
+ if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
268
153
  this._completeSkippedRequest(connection, chatMessageId);
269
154
  return;
270
155
  }
271
156
  }
272
- if (concurrencyDecision.mergeQueuedMessages) {
157
+ if (concurrencyDecision.strategy === "merge") {
273
158
  await this._mergeQueuedUserMessages(epoch);
274
159
  if (this._turnQueue.generation !== epoch) {
275
160
  this._completeSkippedRequest(connection, chatMessageId);
276
161
  return;
277
162
  }
278
- if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
163
+ if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
279
164
  this._completeSkippedRequest(connection, chatMessageId);
280
165
  return;
281
166
  }
@@ -646,89 +531,18 @@ var AIChatAgent = class AIChatAgent extends Agent {
646
531
  * `waitForIdle()` (tests, `waitUntilStable`, recovery code).
647
532
  */
648
533
  async waitForIdle() {
649
- while (true) {
650
- await this._turnQueue.waitForIdle();
651
- if (this._pendingEnqueueCount === 0) return;
652
- await new Promise((resolve) => setTimeout(resolve, 5));
653
- }
654
- }
655
- _normalizeMessageConcurrency() {
656
- if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
657
- const debounceMs = this.messageConcurrency.debounceMs;
658
- return {
659
- strategy: "debounce",
660
- debounceMs: typeof debounceMs === "number" && Number.isFinite(debounceMs) && debounceMs >= 0 ? debounceMs : AIChatAgent.MESSAGE_DEBOUNCE_MS
661
- };
534
+ await this._submitConcurrency.waitForIdle(() => this._turnQueue.waitForIdle());
662
535
  }
663
536
  _getSubmitConcurrencyDecision(trigger) {
664
- const queuedTurnsInCurrentEpoch = this._turnQueue.queuedCount() + this._pendingEnqueueCount;
665
- if (trigger !== "submit-message" || queuedTurnsInCurrentEpoch === 0) return {
666
- action: "execute",
667
- submitSequence: null,
668
- debounceUntilMs: null,
669
- mergeQueuedMessages: false
670
- };
671
- const concurrency = this._normalizeMessageConcurrency();
672
- if (concurrency === "drop") return {
673
- action: "drop",
674
- submitSequence: null,
675
- debounceUntilMs: null,
676
- mergeQueuedMessages: false
677
- };
678
- if (concurrency === "queue") return {
679
- action: "execute",
680
- submitSequence: null,
681
- debounceUntilMs: null,
682
- mergeQueuedMessages: false
683
- };
684
- const submitSequence = ++this._submitSequence;
685
- this._latestOverlappingSubmitSequence = submitSequence;
686
- if (concurrency === "latest") return {
687
- action: "execute",
688
- submitSequence,
689
- debounceUntilMs: null,
690
- mergeQueuedMessages: false
691
- };
692
- if (concurrency === "merge") {
693
- if (!this._mergeQueuedUserStartIndexByEpoch.has(this._turnQueue.generation)) this._mergeQueuedUserStartIndexByEpoch.set(this._turnQueue.generation, this.messages.length);
694
- return {
695
- action: "execute",
696
- submitSequence,
697
- debounceUntilMs: null,
698
- mergeQueuedMessages: true
699
- };
700
- }
701
- return {
702
- action: "execute",
703
- submitSequence,
704
- debounceUntilMs: Date.now() + concurrency.debounceMs,
705
- mergeQueuedMessages: false
706
- };
707
- }
708
- _isSupersededSubmit(submitSequence) {
709
- return submitSequence !== null && submitSequence < this._latestOverlappingSubmitSequence;
710
- }
711
- async _waitForTimestamp(timestampMs) {
712
- const remainingMs = timestampMs - Date.now();
713
- if (remainingMs <= 0) return;
714
- await new Promise((resolve) => {
715
- this._activeDebounceResolve = resolve;
716
- this._activeDebounceTimer = setTimeout(() => {
717
- this._activeDebounceTimer = null;
718
- this._activeDebounceResolve = null;
719
- resolve();
720
- }, remainingMs);
537
+ const decision = this._submitConcurrency.decide({
538
+ concurrency: this.messageConcurrency,
539
+ isSubmitMessage: trigger === "submit-message",
540
+ queuedTurns: this._turnQueue.queuedCount()
721
541
  });
722
- }
723
- _cancelActiveDebounce() {
724
- if (this._activeDebounceTimer !== null) {
725
- clearTimeout(this._activeDebounceTimer);
726
- this._activeDebounceTimer = null;
727
- }
728
- if (this._activeDebounceResolve !== null) {
729
- this._activeDebounceResolve();
730
- this._activeDebounceResolve = null;
542
+ if (decision.strategy === "merge") {
543
+ if (!this._mergeQueuedUserStartIndexByEpoch.has(this._turnQueue.generation)) this._mergeQueuedUserStartIndexByEpoch.set(this._turnQueue.generation, this.messages.length);
731
544
  }
545
+ return decision;
732
546
  }
733
547
  async _mergeQueuedUserMessages(epoch = this._turnQueue.generation) {
734
548
  const mergedMessages = this._getMergedQueuedUserMessages(epoch);
@@ -840,7 +654,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
840
654
  while (true) {
841
655
  while (true) {
842
656
  if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
843
- if (this._pendingEnqueueCount === 0) break;
657
+ if (this._submitConcurrency.pendingEnqueueCount === 0) break;
844
658
  if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, 5)), deadline) === TIMED_OUT) return false;
845
659
  }
846
660
  if (!this.hasPendingInteraction()) return true;
@@ -870,8 +684,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
870
684
  this._mergeQueuedUserStartIndexByEpoch.delete(this._turnQueue.generation);
871
685
  this._turnQueue.reset();
872
686
  this._abortRegistry.destroyAll();
873
- this._cancelActiveDebounce();
874
- this._pendingEnqueueCount = 0;
687
+ this._submitConcurrency.reset();
875
688
  this._pendingInteractionPromise = null;
876
689
  this._continuation.sendResumeNone();
877
690
  this._continuation.clearAll();