@cloudflare/ai-chat 0.8.2 → 0.8.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.
- package/LICENSE +21 -0
- package/dist/index.d.ts +42 -3
- package/dist/index.js +121 -34
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License Copyright (c) 2025 Cloudflare, Inc.
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of
|
|
4
|
+
charge, to any person obtaining a copy of this software and associated
|
|
5
|
+
documentation files (the "Software"), to deal in the Software without
|
|
6
|
+
restriction, including without limitation the rights to use, copy, modify, merge,
|
|
7
|
+
publish, distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to the
|
|
9
|
+
following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice
|
|
12
|
+
(including the next paragraph) shall be included in all copies or substantial
|
|
13
|
+
portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
|
16
|
+
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
17
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
18
|
+
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
|
19
|
+
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
20
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
package/dist/index.d.ts
CHANGED
|
@@ -321,7 +321,12 @@ declare class AIChatAgent<
|
|
|
321
321
|
/** @internal Delegate to _resumableStream */
|
|
322
322
|
protected get _activeRequestId(): string | null;
|
|
323
323
|
/** @internal Delegate to _resumableStream */
|
|
324
|
-
protected _startStream(
|
|
324
|
+
protected _startStream(
|
|
325
|
+
requestId: string,
|
|
326
|
+
options?: {
|
|
327
|
+
messageId?: string;
|
|
328
|
+
}
|
|
329
|
+
): string;
|
|
325
330
|
/** @internal Delegate to _resumableStream */
|
|
326
331
|
protected _completeStream(streamId: string): void;
|
|
327
332
|
/** @internal Delegate to _resumableStream. Also advances the recovery
|
|
@@ -796,12 +801,39 @@ declare class AIChatAgent<
|
|
|
796
801
|
private _beginChatRecoveryIncident;
|
|
797
802
|
private _updateChatRecoveryIncident;
|
|
798
803
|
private _exhaustChatRecovery;
|
|
804
|
+
/**
|
|
805
|
+
* Persist a durable record of the last terminal turn so a client that
|
|
806
|
+
* (re)connects after the turn ended still learns its outcome (#1645). Kept
|
|
807
|
+
* until a later turn supersedes it (`_clearChatTerminal`); a single record is
|
|
808
|
+
* sufficient because only the most recent terminal is relevant.
|
|
809
|
+
*/
|
|
810
|
+
private _recordChatTerminal;
|
|
811
|
+
/** Clear the durable terminal record once a later turn supersedes it (#1645). */
|
|
812
|
+
private _clearChatTerminal;
|
|
813
|
+
private _pendingChatTerminal;
|
|
814
|
+
/**
|
|
815
|
+
* Replay a pending terminal outcome (#1645) over the resume handshake so a
|
|
816
|
+
* reconnecting client surfaces it exactly like a live exhaustion. The bare
|
|
817
|
+
* terminal frame is dropped by the client unless it arrives on a resumed
|
|
818
|
+
* stream — the only path that reaches the transport's stream reader and
|
|
819
|
+
* becomes `useChat.error` — so we drive `STREAM_RESUMING` here and deliver
|
|
820
|
+
* the error frame once the client ACKs (see `_replayTerminalOnAck`).
|
|
821
|
+
* Returns true if a terminal was pending (and `STREAM_RESUMING` was sent).
|
|
822
|
+
*/
|
|
823
|
+
private _replayTerminalOnResume;
|
|
824
|
+
/**
|
|
825
|
+
* Deliver the pending terminal error frame on the resumed stream the client
|
|
826
|
+
* ACKed (#1645). The record is retained (not cleared) so concurrent
|
|
827
|
+
* reconnects (e.g. multiple tabs) each learn the outcome; it is cleared when
|
|
828
|
+
* a later turn supersedes it.
|
|
829
|
+
*/
|
|
830
|
+
private _replayTerminalOnAck;
|
|
799
831
|
/**
|
|
800
832
|
* Set or clear the live "recovering…" status (#1620). Persists a durable
|
|
801
833
|
* record (so set/clear stay consistent across the isolates a recovery spans)
|
|
802
834
|
* and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
|
|
803
|
-
* NOTE:
|
|
804
|
-
*
|
|
835
|
+
* NOTE: the live "recovering…" signal is still not replayed on connect — only
|
|
836
|
+
* the terminal outcome is (#1645, via the resume handshake).
|
|
805
837
|
*/
|
|
806
838
|
private _setChatRecovering;
|
|
807
839
|
protected _handleInternalFiberRecovery(
|
|
@@ -972,6 +1004,13 @@ declare class AIChatAgent<
|
|
|
972
1004
|
private static _shouldPreserveProviderToolPayload;
|
|
973
1005
|
private static _getToolNameFromPart;
|
|
974
1006
|
private static _isOpaqueReplayFieldKey;
|
|
1007
|
+
/**
|
|
1008
|
+
* Delete the given message rows from SQLite in batched `IN (...)` queries
|
|
1009
|
+
* and evict them from the persistence cache. Batches stay within the SQLite
|
|
1010
|
+
* 100 bound-parameter limit. No-op for an empty list.
|
|
1011
|
+
* @internal
|
|
1012
|
+
*/
|
|
1013
|
+
private _deleteMessagesByIds;
|
|
975
1014
|
/**
|
|
976
1015
|
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
977
1016
|
* Called after each persist to keep storage bounded.
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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, SubmitConcurrencyController, TurnQueue, applyChunkToParts, byteLength, createChatFiberSnapshot, createToolsFromClientSchemas, isReplayChunk, reconcileMessages, resolveToolMergeId, sanitizeMessage, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
4
|
+
import { AbortRegistry, ContinuationState, MAX_BOUND_PARAMS, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, buildInClauseStrings, byteLength, createChatFiberSnapshot, createToolsFromClientSchemas, isReplayChunk, reconcileMessages, resolveToolMergeId, sanitizeMessage, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
5
5
|
import { nanoid } from "nanoid";
|
|
6
6
|
//#region src/index.ts
|
|
7
7
|
const CHAT_RECOVERY_INCIDENT_KEY_PREFIX = "cf:chat-recovery:incident:";
|
|
@@ -13,7 +13,9 @@ const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
|
|
|
13
13
|
const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
|
|
14
14
|
const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
|
|
15
15
|
const CHAT_RECOVERING_KEY = "cf:chat:recovering";
|
|
16
|
+
const CHAT_LAST_TERMINAL_KEY = "cf:chat:last-terminal";
|
|
16
17
|
const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
|
|
18
|
+
const KV_DELETE_MAX_KEYS = 128;
|
|
17
19
|
const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
|
|
18
20
|
const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
|
|
19
21
|
const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
|
|
@@ -202,6 +204,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
202
204
|
this._completeSkippedRequest(connection, chatMessageId);
|
|
203
205
|
return;
|
|
204
206
|
}
|
|
207
|
+
await this._clearChatTerminal();
|
|
205
208
|
const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
|
|
206
209
|
try {
|
|
207
210
|
this._broadcastChatMessage({
|
|
@@ -289,6 +292,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
289
292
|
if (data.type === "cf_agent_chat_clear") {
|
|
290
293
|
this.resetTurnState();
|
|
291
294
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
295
|
+
await this._clearChatTerminal();
|
|
292
296
|
this._resumableStream.clearAll();
|
|
293
297
|
this._pendingResumeConnections.clear();
|
|
294
298
|
this._lastClientTools = void 0;
|
|
@@ -314,7 +318,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
314
318
|
if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
|
|
315
319
|
else this._notifyStreamResuming(connection);
|
|
316
320
|
else if (this._continuation.pending !== null && (this._continuation.pending.connectionId === null || this._continuation.pending.connectionId === connection.id)) this._continuation.awaitingConnections.set(connection.id, connection);
|
|
317
|
-
else sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
|
|
321
|
+
else if (await this._replayTerminalOnResume(connection)) {} else sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
|
|
318
322
|
return;
|
|
319
323
|
}
|
|
320
324
|
if (data.type === "cf_agent_stream_resume_ack") {
|
|
@@ -322,7 +326,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
322
326
|
if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
|
|
323
327
|
const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
|
|
324
328
|
if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
|
|
325
|
-
} else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, data.id)) sendIfOpen(connection, JSON.stringify({
|
|
329
|
+
} else if (this._resumableStream.hasActiveStream()) {} else if (await this._replayTerminalOnAck(connection, data.id)) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, data.id)) sendIfOpen(connection, JSON.stringify({
|
|
326
330
|
body: "",
|
|
327
331
|
done: true,
|
|
328
332
|
id: data.id,
|
|
@@ -448,8 +452,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
448
452
|
return this._resumableStream?.activeRequestId ?? null;
|
|
449
453
|
}
|
|
450
454
|
/** @internal Delegate to _resumableStream */
|
|
451
|
-
_startStream(requestId) {
|
|
452
|
-
const streamId = this._resumableStream.start(requestId);
|
|
455
|
+
_startStream(requestId, options = {}) {
|
|
456
|
+
const streamId = this._resumableStream.start(requestId, options);
|
|
453
457
|
if (this._continuation.pending?.requestId === requestId) {
|
|
454
458
|
this._continuation.activatePending();
|
|
455
459
|
this._flushAwaitingStreamStartConnections();
|
|
@@ -534,7 +538,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
534
538
|
} catch {}
|
|
535
539
|
if (message.parts.length > 0) {
|
|
536
540
|
if (message.id === fallbackId) {
|
|
537
|
-
|
|
541
|
+
const storedId = this._resumableStream.getStreamMessageId(streamId);
|
|
542
|
+
if (storedId != null) message.id = storedId;
|
|
543
|
+
else for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") {
|
|
538
544
|
message.id = this.messages[i].id;
|
|
539
545
|
break;
|
|
540
546
|
}
|
|
@@ -542,7 +548,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
542
548
|
const existingIdx = this.messages.findIndex((m) => m.id === message.id);
|
|
543
549
|
if (existingIdx >= 0) {
|
|
544
550
|
const existing = this.messages[existingIdx];
|
|
545
|
-
|
|
551
|
+
const existingToolCallIds = new Set(existing.parts.filter((p) => "toolCallId" in p).map((p) => p.toolCallId));
|
|
552
|
+
const newParts = message.parts.filter((p) => !("toolCallId" in p && existingToolCallIds.has(p.toolCallId)));
|
|
553
|
+
message.parts = [...existing.parts, ...newParts];
|
|
546
554
|
if (existing.metadata) message.metadata = message.metadata ? {
|
|
547
555
|
...existing.metadata,
|
|
548
556
|
...message.metadata
|
|
@@ -925,6 +933,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
925
933
|
await this.keepAliveWhile(async () => {
|
|
926
934
|
while (this._pendingChatResponseResults.length > 0) {
|
|
927
935
|
const chatResult = this._pendingChatResponseResults.shift();
|
|
936
|
+
if (chatResult.status === "completed" || chatResult.status === "aborted") await this._clearChatTerminal();
|
|
937
|
+
else if (chatResult.status === "error") await this._recordChatTerminal(chatResult.requestId, chatResult.error ?? "The assistant encountered an error.");
|
|
928
938
|
try {
|
|
929
939
|
await this.onChatResponse(chatResult);
|
|
930
940
|
} catch (hookError) {
|
|
@@ -1577,14 +1587,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1577
1587
|
_getAgentToolStoredChunks(requestId, afterSequence = -1) {
|
|
1578
1588
|
const streamId = this._getAgentToolStreamId(requestId);
|
|
1579
1589
|
if (!streamId) return [];
|
|
1580
|
-
return this.
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
where stream_id = ${streamId} and chunk_index > ${afterSequence}
|
|
1584
|
-
order by chunk_index asc
|
|
1585
|
-
`.map((row) => ({
|
|
1586
|
-
sequence: row.chunk_index,
|
|
1587
|
-
body: row.body
|
|
1590
|
+
return this._resumableStream.getStreamChunks(streamId).filter((chunk) => chunk.chunk_index > afterSequence).map((chunk) => ({
|
|
1591
|
+
sequence: chunk.chunk_index,
|
|
1592
|
+
body: chunk.body
|
|
1588
1593
|
}));
|
|
1589
1594
|
}
|
|
1590
1595
|
_getAgentToolMessagesAfterStart(runId) {
|
|
@@ -1864,7 +1869,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1864
1869
|
const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
|
|
1865
1870
|
const staleKeys = [];
|
|
1866
1871
|
for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
|
|
1867
|
-
for (
|
|
1872
|
+
for (let i = 0; i < staleKeys.length; i += KV_DELETE_MAX_KEYS) await this.ctx.storage.delete(staleKeys.slice(i, i + KV_DELETE_MAX_KEYS));
|
|
1868
1873
|
}
|
|
1869
1874
|
async _beginChatRecoveryIncident(input) {
|
|
1870
1875
|
const config = this._resolveChatRecoveryConfig();
|
|
@@ -1984,6 +1989,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1984
1989
|
} catch (error) {
|
|
1985
1990
|
console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error);
|
|
1986
1991
|
}
|
|
1992
|
+
await this._recordChatTerminal(incident.requestId, config.terminalMessage);
|
|
1987
1993
|
this._broadcastChatMessage({
|
|
1988
1994
|
body: config.terminalMessage,
|
|
1989
1995
|
done: true,
|
|
@@ -1994,11 +2000,66 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1994
2000
|
await this._setChatRecovering(false);
|
|
1995
2001
|
}
|
|
1996
2002
|
/**
|
|
2003
|
+
* Persist a durable record of the last terminal turn so a client that
|
|
2004
|
+
* (re)connects after the turn ended still learns its outcome (#1645). Kept
|
|
2005
|
+
* until a later turn supersedes it (`_clearChatTerminal`); a single record is
|
|
2006
|
+
* sufficient because only the most recent terminal is relevant.
|
|
2007
|
+
*/
|
|
2008
|
+
async _recordChatTerminal(requestId, body) {
|
|
2009
|
+
await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, {
|
|
2010
|
+
requestId,
|
|
2011
|
+
body
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
/** Clear the durable terminal record once a later turn supersedes it (#1645). */
|
|
2015
|
+
async _clearChatTerminal() {
|
|
2016
|
+
await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
|
|
2017
|
+
}
|
|
2018
|
+
async _pendingChatTerminal() {
|
|
2019
|
+
return await this.ctx.storage.get(CHAT_LAST_TERMINAL_KEY) ?? null;
|
|
2020
|
+
}
|
|
2021
|
+
/**
|
|
2022
|
+
* Replay a pending terminal outcome (#1645) over the resume handshake so a
|
|
2023
|
+
* reconnecting client surfaces it exactly like a live exhaustion. The bare
|
|
2024
|
+
* terminal frame is dropped by the client unless it arrives on a resumed
|
|
2025
|
+
* stream — the only path that reaches the transport's stream reader and
|
|
2026
|
+
* becomes `useChat.error` — so we drive `STREAM_RESUMING` here and deliver
|
|
2027
|
+
* the error frame once the client ACKs (see `_replayTerminalOnAck`).
|
|
2028
|
+
* Returns true if a terminal was pending (and `STREAM_RESUMING` was sent).
|
|
2029
|
+
*/
|
|
2030
|
+
async _replayTerminalOnResume(connection) {
|
|
2031
|
+
const pending = await this._pendingChatTerminal();
|
|
2032
|
+
if (!pending) return false;
|
|
2033
|
+
sendIfOpen(connection, JSON.stringify({
|
|
2034
|
+
type: "cf_agent_stream_resuming",
|
|
2035
|
+
id: pending.requestId
|
|
2036
|
+
}));
|
|
2037
|
+
return true;
|
|
2038
|
+
}
|
|
2039
|
+
/**
|
|
2040
|
+
* Deliver the pending terminal error frame on the resumed stream the client
|
|
2041
|
+
* ACKed (#1645). The record is retained (not cleared) so concurrent
|
|
2042
|
+
* reconnects (e.g. multiple tabs) each learn the outcome; it is cleared when
|
|
2043
|
+
* a later turn supersedes it.
|
|
2044
|
+
*/
|
|
2045
|
+
async _replayTerminalOnAck(connection, requestId) {
|
|
2046
|
+
const pending = await this._pendingChatTerminal();
|
|
2047
|
+
if (!pending || pending.requestId !== requestId) return false;
|
|
2048
|
+
sendIfOpen(connection, JSON.stringify({
|
|
2049
|
+
body: pending.body,
|
|
2050
|
+
done: true,
|
|
2051
|
+
error: true,
|
|
2052
|
+
id: pending.requestId,
|
|
2053
|
+
type: "cf_agent_use_chat_response"
|
|
2054
|
+
}));
|
|
2055
|
+
return true;
|
|
2056
|
+
}
|
|
2057
|
+
/**
|
|
1997
2058
|
* Set or clear the live "recovering…" status (#1620). Persists a durable
|
|
1998
2059
|
* record (so set/clear stay consistent across the isolates a recovery spans)
|
|
1999
2060
|
* and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
|
|
2000
|
-
* NOTE:
|
|
2001
|
-
*
|
|
2061
|
+
* NOTE: the live "recovering…" signal is still not replayed on connect — only
|
|
2062
|
+
* the terminal outcome is (#1645, via the resume handshake).
|
|
2002
2063
|
*/
|
|
2003
2064
|
async _setChatRecovering(active, requestId) {
|
|
2004
2065
|
const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
|
|
@@ -2041,7 +2102,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2041
2102
|
};
|
|
2042
2103
|
const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
|
|
2043
2104
|
const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(recoverySnapshot, streamId ?? "", partial);
|
|
2044
|
-
const
|
|
2105
|
+
const preStreamLeaf = this.messages.length > 0 ? this.messages[this.messages.length - 1] : void 0;
|
|
2106
|
+
const emptyPartialNewTurn = !!streamId && recoverySnapshot?.continuation === false && !!recoverySnapshot.latestUserMessageId && partial.text === "" && partial.parts.length === 0 && preStreamLeaf?.role === "user" && preStreamLeaf.id === recoverySnapshot.latestUserMessageId;
|
|
2107
|
+
const recoveryKind = shouldRetryPreStream || emptyPartialNewTurn ? "retry" : "continue";
|
|
2045
2108
|
const recoveryRootRequestId = recoverySnapshot?.recoveryRootRequestId ?? requestId;
|
|
2046
2109
|
const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
|
|
2047
2110
|
requestId,
|
|
@@ -2073,7 +2136,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2073
2136
|
}) ?? {};
|
|
2074
2137
|
if (streamStillActive && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
|
|
2075
2138
|
if (streamStillActive) this._resumableStream.complete(streamId);
|
|
2076
|
-
const
|
|
2139
|
+
const leaf = this.messages.length > 0 ? this.messages[this.messages.length - 1] : void 0;
|
|
2140
|
+
const lostPartialUserId = recoverySnapshot?.continuation === false && recoverySnapshot.latestUserMessageId && leaf?.role === "user" && leaf.id === recoverySnapshot.latestUserMessageId ? recoverySnapshot.latestUserMessageId : void 0;
|
|
2141
|
+
const targetId = shouldRetryPreStream || lostPartialUserId !== void 0 ? void 0 : this._findLastAssistantMessage()?.id;
|
|
2077
2142
|
if (shouldRetryPreStream && options.continue !== false) {
|
|
2078
2143
|
await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
|
|
2079
2144
|
this._emit("chat:recovery:scheduled", {
|
|
@@ -2090,6 +2155,22 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2090
2155
|
lastBody: recoverySnapshot.lastBody ?? null,
|
|
2091
2156
|
lastClientTools: recoverySnapshot.lastClientTools ?? null
|
|
2092
2157
|
}, { idempotent: true });
|
|
2158
|
+
} else if (lostPartialUserId !== void 0 && options.continue !== false) {
|
|
2159
|
+
await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
|
|
2160
|
+
this._emit("chat:recovery:scheduled", {
|
|
2161
|
+
incidentId: incident.incidentId,
|
|
2162
|
+
requestId,
|
|
2163
|
+
attempt: incident.attempt,
|
|
2164
|
+
maxAttempts: incident.maxAttempts,
|
|
2165
|
+
recoveryKind: "retry"
|
|
2166
|
+
});
|
|
2167
|
+
await this.schedule(0, "_chatRecoveryRetry", {
|
|
2168
|
+
targetUserId: lostPartialUserId,
|
|
2169
|
+
originalRequestId: recoveryRootRequestId,
|
|
2170
|
+
incidentId: incident.incidentId,
|
|
2171
|
+
lastBody: recoverySnapshot?.lastBody ?? null,
|
|
2172
|
+
lastClientTools: recoverySnapshot?.lastClientTools ?? null
|
|
2173
|
+
}, { idempotent: true });
|
|
2093
2174
|
} else if (options.continue !== false) {
|
|
2094
2175
|
await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
|
|
2095
2176
|
this._emit("chat:recovery:scheduled", {
|
|
@@ -2353,15 +2434,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2353
2434
|
const serverIds = new Set(this.messages.map((m) => m.id));
|
|
2354
2435
|
if (mergedMessages.every((m) => serverIds.has(m.id))) {
|
|
2355
2436
|
const keepIds = new Set(mergedMessages.map((m) => m.id));
|
|
2356
|
-
const
|
|
2437
|
+
const staleIds = (this.sql`
|
|
2357
2438
|
select id from cf_ai_chat_agent_messages
|
|
2358
|
-
` || [];
|
|
2359
|
-
|
|
2360
|
-
this.sql`
|
|
2361
|
-
delete from cf_ai_chat_agent_messages where id = ${row.id}
|
|
2362
|
-
`;
|
|
2363
|
-
this._persistedMessageCache.delete(row.id);
|
|
2364
|
-
}
|
|
2439
|
+
` || []).map((row) => row.id).filter((id) => !keepIds.has(id));
|
|
2440
|
+
this._deleteMessagesByIds(staleIds);
|
|
2365
2441
|
}
|
|
2366
2442
|
}
|
|
2367
2443
|
if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
|
|
@@ -2493,6 +2569,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2493
2569
|
return key.startsWith(PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX);
|
|
2494
2570
|
}
|
|
2495
2571
|
/**
|
|
2572
|
+
* Delete the given message rows from SQLite in batched `IN (...)` queries
|
|
2573
|
+
* and evict them from the persistence cache. Batches stay within the SQLite
|
|
2574
|
+
* 100 bound-parameter limit. No-op for an empty list.
|
|
2575
|
+
* @internal
|
|
2576
|
+
*/
|
|
2577
|
+
_deleteMessagesByIds(ids) {
|
|
2578
|
+
for (let i = 0; i < ids.length; i += MAX_BOUND_PARAMS) {
|
|
2579
|
+
const batch = ids.slice(i, i + MAX_BOUND_PARAMS);
|
|
2580
|
+
const strings = buildInClauseStrings("delete from cf_ai_chat_agent_messages where id in ", batch.length);
|
|
2581
|
+
this.sql(strings, ...batch);
|
|
2582
|
+
for (const id of batch) this._persistedMessageCache.delete(id);
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
/**
|
|
2496
2586
|
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
2497
2587
|
* Called after each persist to keep storage bounded.
|
|
2498
2588
|
*/
|
|
@@ -2508,10 +2598,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2508
2598
|
order by created_at asc
|
|
2509
2599
|
limit ${excess}
|
|
2510
2600
|
`;
|
|
2511
|
-
if (toDelete && toDelete.length > 0)
|
|
2512
|
-
this.sql`delete from cf_ai_chat_agent_messages where id = ${row.id}`;
|
|
2513
|
-
this._persistedMessageCache.delete(row.id);
|
|
2514
|
-
}
|
|
2601
|
+
if (toDelete && toDelete.length > 0) this._deleteMessagesByIds(toDelete.map((row) => row.id));
|
|
2515
2602
|
}
|
|
2516
2603
|
/**
|
|
2517
2604
|
* Enforces SQLite row size limits by compacting tool outputs and text parts
|
|
@@ -3093,9 +3180,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3093
3180
|
this._activateDeferredAutoContinuation();
|
|
3094
3181
|
return { status: "completed" };
|
|
3095
3182
|
}
|
|
3096
|
-
const streamId = this._startStream(id);
|
|
3097
|
-
const reader = response.body.getReader();
|
|
3098
3183
|
const message = this._createStreamingAssistantMessage(continuation);
|
|
3184
|
+
const streamId = this._startStream(id, { messageId: message.id });
|
|
3185
|
+
const reader = response.body.getReader();
|
|
3099
3186
|
this._streamingMessage = message;
|
|
3100
3187
|
const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
|
|
3101
3188
|
const streamCompleted = { value: false };
|