@cloudflare/ai-chat 0.5.1 → 0.5.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.
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,13 +684,44 @@ 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();
878
691
  this._pendingChatResponseResults.length = 0;
879
692
  }
693
+ /**
694
+ * Abort a single in-flight chat turn by request id.
695
+ *
696
+ * Equivalent to the cancel path that fires when a client sends a
697
+ * `chat-request-cancel` WebSocket message — the inference loop's
698
+ * signal aborts and the turn's `ChatResponseResult` reports
699
+ * `status: "aborted"`. No-op if no controller exists for `requestId`.
700
+ *
701
+ * Most callers don't have the request id and want
702
+ * {@link abortAllRequests} instead. Prefer
703
+ * {@link SaveMessagesOptions.signal} when driving a turn
704
+ * programmatically — it threads the abort intent in from the start
705
+ * without requiring the caller to know the id.
706
+ */
707
+ abortRequest(requestId, reason) {
708
+ this._abortRegistry.cancel(requestId, reason);
709
+ }
710
+ /**
711
+ * Abort every in-flight chat turn on this agent.
712
+ *
713
+ * Aborts all controllers in the registry and clears it. Used by
714
+ * subclasses that drive single-purpose turns (e.g. an RPC-driven
715
+ * sub-agent helper that runs one turn at a time) and want a coarse
716
+ * "cancel whatever is running" handle without tracking request ids.
717
+ *
718
+ * Does NOT reset queued turns, continuation timers, or submit
719
+ * concurrency state — use {@link resetTurnState} for the full
720
+ * teardown that runs on `chat-clear`.
721
+ */
722
+ abortAllRequests() {
723
+ this._abortRegistry.destroyAll();
724
+ }
880
725
  async _awaitWithDeadline(promise, deadline) {
881
726
  if (deadline == null) return promise;
882
727
  const remainingMs = Math.max(0, deadline - Date.now());
@@ -1030,8 +875,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
1030
875
  console.error(errorPrefix, error);
1031
876
  });
1032
877
  }
1033
- async _runProgrammaticChatTurn(requestId, clientTools, body) {
878
+ /**
879
+ * @returns `true` if the registry's controller for `requestId` was
880
+ * aborted during the turn (so the caller can surface
881
+ * `status: "aborted"` to the public API). Returns `false` for
882
+ * successful or errored completion.
883
+ */
884
+ async _runProgrammaticChatTurn(requestId, clientTools, body, externalSignal) {
1034
885
  this._setRequestContext(clientTools, body);
886
+ let wasAborted = false;
1035
887
  await this._tryCatchChat(async () => {
1036
888
  return __DO_NOT_USE_WILL_BREAK__agentContext.run({
1037
889
  agent: this,
@@ -1040,8 +892,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1040
892
  email: void 0
1041
893
  }, async () => {
1042
894
  const abortSignal = this._abortRegistry.getSignal(requestId);
1043
- const programmaticBody = async () => {
1044
- try {
895
+ const detachExternal = this._abortRegistry.linkExternal(requestId, externalSignal);
896
+ try {
897
+ const programmaticBody = async () => {
1045
898
  const response = await this.onChatMessage(() => {}, {
1046
899
  requestId,
1047
900
  abortSignal,
@@ -1050,16 +903,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
1050
903
  continuation: false
1051
904
  });
1052
905
  if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
1053
- } finally {
1054
- this._abortRegistry.remove(requestId);
1055
- }
1056
- };
1057
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1058
- await programmaticBody();
1059
- });
1060
- else await programmaticBody();
906
+ };
907
+ if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
908
+ await programmaticBody();
909
+ });
910
+ else await programmaticBody();
911
+ } finally {
912
+ if (abortSignal?.aborted) wasAborted = true;
913
+ detachExternal();
914
+ this._abortRegistry.remove(requestId);
915
+ }
1061
916
  });
1062
917
  });
918
+ return wasAborted;
1063
919
  }
1064
920
  /**
1065
921
  * Handle incoming chat messages and generate a response
@@ -1146,16 +1002,23 @@ var AIChatAgent = class AIChatAgent extends Agent {
1146
1002
  * await this.saveMessages((messages) => [...messages, syntheticMessage]);
1147
1003
  * ```
1148
1004
  *
1149
- * Returns `{ requestId, status }` so callers can detect whether the turn
1150
- * ran (`"completed"`) or was skipped because the chat was cleared
1151
- * (`"skipped"`).
1005
+ * Pass `options.signal` to cancel the turn from outside without knowing
1006
+ * the internally-generated request id. The signal is linked to the
1007
+ * registry's controller for this turn — when it aborts, the inference
1008
+ * loop's signal aborts and the result reports `status: "aborted"`.
1009
+ * Pre-aborted signals short-circuit before any model work runs.
1010
+ *
1011
+ * Returns `{ requestId, status }` where `status` is `"completed"` when
1012
+ * the turn ran, `"skipped"` when the chat was cleared, or `"aborted"`
1013
+ * when an external signal cancelled it mid-stream.
1152
1014
  */
1153
- async saveMessages(messages) {
1015
+ async saveMessages(messages, options) {
1154
1016
  const requestId = nanoid();
1155
1017
  const clientTools = this._lastClientTools;
1156
1018
  const body = this._lastBody;
1157
1019
  const epoch = this._turnQueue.generation;
1158
1020
  let status = "completed";
1021
+ let wasAborted = false;
1159
1022
  await this._runExclusiveChatTurn(requestId, async () => {
1160
1023
  const resolvedMessages = typeof messages === "function" ? await messages(this.messages) : messages;
1161
1024
  if (this._turnQueue.generation !== epoch) {
@@ -1167,9 +1030,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
1167
1030
  status = "skipped";
1168
1031
  return;
1169
1032
  }
1170
- await this._runProgrammaticChatTurn(requestId, clientTools, body);
1033
+ wasAborted = await this._runProgrammaticChatTurn(requestId, clientTools, body, options?.signal);
1171
1034
  }, { epoch });
1172
1035
  if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1036
+ else if (wasAborted && status === "completed") status = "aborted";
1173
1037
  return {
1174
1038
  requestId,
1175
1039
  status
@@ -1186,8 +1050,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
1186
1050
  * used by tool auto-continuation.
1187
1051
  *
1188
1052
  * Returns early if there is no assistant message to continue from.
1053
+ *
1054
+ * Pass `options.signal` to cancel the continuation from outside —
1055
+ * matches the {@link saveMessages} contract.
1189
1056
  */
1190
- async continueLastTurn(body) {
1057
+ async continueLastTurn(body, options) {
1191
1058
  if (!this._findLastAssistantMessage()) return {
1192
1059
  requestId: "",
1193
1060
  status: "skipped"
@@ -1197,6 +1064,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1197
1064
  const resolvedBody = body ?? this._lastBody;
1198
1065
  const epoch = this._turnQueue.generation;
1199
1066
  let status = "completed";
1067
+ let wasAborted = false;
1200
1068
  await this._runExclusiveChatTurn(requestId, async () => {
1201
1069
  if (this._turnQueue.generation !== epoch) {
1202
1070
  status = "skipped";
@@ -1212,6 +1080,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1212
1080
  email: void 0
1213
1081
  }, async () => {
1214
1082
  const abortSignal = this._abortRegistry.getSignal(requestId);
1083
+ const detachExternal = this._abortRegistry.linkExternal(requestId, options?.signal);
1215
1084
  try {
1216
1085
  const response = await this.onChatMessage(() => {}, {
1217
1086
  requestId,
@@ -1225,6 +1094,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1225
1094
  chatMessageId: requestId
1226
1095
  });
1227
1096
  } finally {
1097
+ if (abortSignal?.aborted) wasAborted = true;
1098
+ detachExternal();
1228
1099
  this._abortRegistry.remove(requestId);
1229
1100
  }
1230
1101
  });
@@ -1236,6 +1107,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1236
1107
  else await turnBody();
1237
1108
  }, { epoch });
1238
1109
  if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1110
+ else if (wasAborted && status === "completed") status = "aborted";
1239
1111
  return {
1240
1112
  requestId,
1241
1113
  status