@cloudflare/ai-chat 0.11.0 → 0.12.0
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 +155 -116
- package/dist/index.js +446 -240
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { MessageType } from "./types.js";
|
|
2
2
|
import { autoTransformMessages } from "./ai-chat-v5-migration.js";
|
|
3
3
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, isDurableObjectMemoryLimitReset } from "agents";
|
|
4
|
-
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState,
|
|
4
|
+
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, PreStreamTurns, ResumableStream, ResumeHandshake, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyChunkToParts, awaitWithDeadline, buildChatRecoveringFrame, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, dispatchChatRecoveryToHandoff, drainInteractionApplies, hasIncompleteToolBatch, interceptAgentToolBroadcast, isReplayChunk, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, parseProtocolMessage, partAwaitsClientInteraction, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sendIfOpen, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
5
|
+
import { Sessions } from "agents/sessions";
|
|
5
6
|
import { nanoid } from "nanoid";
|
|
6
7
|
//#region src/index.ts
|
|
7
8
|
function withAgentSpan(host, operation, storagePhase, attributes, run) {
|
|
@@ -43,10 +44,67 @@ const agentToolChunkEncoder = new TextEncoder();
|
|
|
43
44
|
* Extension of Agent with built-in chat capabilities
|
|
44
45
|
* @template Env Environment type containing bindings
|
|
45
46
|
*/
|
|
47
|
+
/** Bounds for one window of the legacy lift: rows and their summed bytes. */
|
|
48
|
+
const LEGACY_LIFT_WINDOW_ROWS = 25;
|
|
49
|
+
const LEGACY_LIFT_WINDOW_BYTES = 4 * 1024 * 1024;
|
|
46
50
|
var AIChatAgent = class AIChatAgent extends Agent {
|
|
51
|
+
/** The default linear conversation handle. */
|
|
52
|
+
#session;
|
|
47
53
|
static {
|
|
48
54
|
this.MESSAGE_DEBOUNCE_MS = 750;
|
|
49
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* Register the shared chat-turn Task definition (see
|
|
58
|
+
* `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
|
|
59
|
+
* host wires its protected internals through the hooks.
|
|
60
|
+
*/
|
|
61
|
+
_registerChatTurnTaskDefinition() {
|
|
62
|
+
const chatFiberName = this.constructor.CHAT_FIBER_NAME;
|
|
63
|
+
this.tasks.register(chatFiberName, createChatTurnTaskDefinition({
|
|
64
|
+
definitionName: chatFiberName,
|
|
65
|
+
storage: this.ctx.storage,
|
|
66
|
+
getRunCreatedAt: async (runId) => (await this.tasks.get(runId))?.createdAt ?? null,
|
|
67
|
+
getLiveClosure: (nonce) => this._liveChatTurnClosures.get(nonce),
|
|
68
|
+
keepAliveWhile: (fn) => this.keepAliveWhile(fn),
|
|
69
|
+
withStash: (context, fn) => this._withFiberStash(context, fn),
|
|
70
|
+
handleRecovery: (ctx) => this._handleInternalFiberRecovery(ctx)
|
|
71
|
+
}));
|
|
72
|
+
}
|
|
73
|
+
/** Register the shared Tasks transport for recovery continuations. */
|
|
74
|
+
_registerChatRecoveryTaskDefinition() {
|
|
75
|
+
this.tasks.register(CHAT_RECOVERY_TASK_NAME, createChatRecoveryTaskDefinition({
|
|
76
|
+
_chatRecoveryContinue: (data) => this._chatRecoveryContinue(data),
|
|
77
|
+
_chatRecoveryRetry: (data) => this._chatRecoveryRetry(data)
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Run a queue-driven recovery callback to its model handoff and return;
|
|
82
|
+
* the turn continues as tracked alarm work, and a detached platform
|
|
83
|
+
* failure enqueues one replacement attempt through the same transport.
|
|
84
|
+
*/
|
|
85
|
+
_dispatchChatRecovery(callback, data, detached) {
|
|
86
|
+
return dispatchChatRecoveryToHandoff({
|
|
87
|
+
detached,
|
|
88
|
+
track: (turn) => this.lifecycle.trackAlarmWork(turn),
|
|
89
|
+
redefer: (dedupeKey) => this._enqueueChatRecovery(callback, data ?? {}, "redefer", CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, dedupeKey),
|
|
90
|
+
onDetachedError: (error) => console.error(`[AIChatAgent] ${callback} dispatch failed`, error)
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Enqueue one recovery attempt on the shared Tasks transport. Tasks
|
|
95
|
+
* mirrors a routed dynamic agent's wake to the root's alarm; the run
|
|
96
|
+
* itself, and this continuation's replay, still execute here. `dedupeKey`
|
|
97
|
+
* keys a retried enqueue so it joins its own prior attempt instead of
|
|
98
|
+
* duplicating it — see {@link chatRecoveryTaskRunOptions}.
|
|
99
|
+
*/
|
|
100
|
+
async _enqueueChatRecovery(callback, data, reason, delaySeconds, dedupeKey) {
|
|
101
|
+
const input = {
|
|
102
|
+
callback,
|
|
103
|
+
data,
|
|
104
|
+
delaySeconds
|
|
105
|
+
};
|
|
106
|
+
await this.tasks.__DO_NOT_USE_WILL_BREAK__enqueue(CHAT_RECOVERY_TASK_NAME, input, chatRecoveryTaskRunOptions(input, reason, dedupeKey));
|
|
107
|
+
}
|
|
50
108
|
async _runChatRecoveryFiber(requestId, continuation, fn) {
|
|
51
109
|
const snapshot = createChatFiberSnapshot({
|
|
52
110
|
kind: "ai-chat-turn",
|
|
@@ -57,10 +115,43 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
57
115
|
lastBody: this._lastBody,
|
|
58
116
|
lastClientTools: this._lastClientTools
|
|
59
117
|
});
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
118
|
+
const wrap = (data) => wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, data);
|
|
119
|
+
if (this.parentPath.length > 0) return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
|
|
120
|
+
initialSnapshot: wrap(null),
|
|
121
|
+
wrapStash: wrap
|
|
122
|
+
});
|
|
123
|
+
const nonce = nanoid();
|
|
124
|
+
let resolveOutcome;
|
|
125
|
+
let rejectOutcome;
|
|
126
|
+
const outcome = new Promise((resolve, reject) => {
|
|
127
|
+
resolveOutcome = resolve;
|
|
128
|
+
rejectOutcome = reject;
|
|
129
|
+
});
|
|
130
|
+
outcome.catch(() => {});
|
|
131
|
+
const ambient = __DO_NOT_USE_WILL_BREAK__agentContext.getStore();
|
|
132
|
+
this._liveChatTurnClosures.set(nonce, {
|
|
133
|
+
initial: wrap(null),
|
|
134
|
+
wrap,
|
|
135
|
+
run: ambient ? () => __DO_NOT_USE_WILL_BREAK__agentContext.run(ambient, fn) : fn,
|
|
136
|
+
settle: {
|
|
137
|
+
resolve: resolveOutcome,
|
|
138
|
+
reject: rejectOutcome
|
|
139
|
+
}
|
|
63
140
|
});
|
|
141
|
+
try {
|
|
142
|
+
await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(this.constructor.CHAT_FIBER_NAME, {
|
|
143
|
+
requestId,
|
|
144
|
+
continuation,
|
|
145
|
+
nonce
|
|
146
|
+
}, {
|
|
147
|
+
runId: `chat_${nonce}`,
|
|
148
|
+
retain: false,
|
|
149
|
+
metadata: { requestId }
|
|
150
|
+
});
|
|
151
|
+
return await outcome;
|
|
152
|
+
} finally {
|
|
153
|
+
this._liveChatTurnClosures.delete(nonce);
|
|
154
|
+
}
|
|
64
155
|
}
|
|
65
156
|
broadcast(msg, without) {
|
|
66
157
|
if (this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0) interceptAgentToolBroadcast(msg, {
|
|
@@ -139,6 +230,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
139
230
|
}
|
|
140
231
|
constructor(ctx, env) {
|
|
141
232
|
super(ctx, env);
|
|
233
|
+
this.sessions = new Sessions();
|
|
234
|
+
this.hydrationByteBudget = 32 * 1024 * 1024;
|
|
235
|
+
this.#session = this.sessions.session();
|
|
236
|
+
this.streams = createChatStreams();
|
|
142
237
|
this._streamingMessage = null;
|
|
143
238
|
this._pendingChatResponseResults = [];
|
|
144
239
|
this._insideResponseHook = false;
|
|
@@ -161,7 +256,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
161
256
|
this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
|
|
162
257
|
this._agentToolLiveSequences = /* @__PURE__ */ new Map();
|
|
163
258
|
this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
|
|
164
|
-
this._persistedMessageCache = /* @__PURE__ */ new Map();
|
|
165
259
|
this._autoContinuation = new AutoContinuationController({
|
|
166
260
|
continuation: this._continuation,
|
|
167
261
|
generateRequestId: () => nanoid(),
|
|
@@ -176,19 +270,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
176
270
|
this.maxPersistedMessages = void 0;
|
|
177
271
|
this.messageConcurrency = "queue";
|
|
178
272
|
this.waitForMcpConnections = { timeout: 1e4 };
|
|
273
|
+
this._liveChatTurnClosures = /* @__PURE__ */ new Map();
|
|
179
274
|
this.messages = [];
|
|
180
|
-
this._streamProgressCredit = new StreamProgressCreditThrottle();
|
|
181
275
|
this._agentToolProgressEmitterInstance = null;
|
|
182
276
|
this._inSerializedDetachedDeliverySlot = false;
|
|
183
277
|
this._inFlightDetachedNotifications = /* @__PURE__ */ new Set();
|
|
278
|
+
this._progressSeed = null;
|
|
184
279
|
this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
|
|
280
|
+
this.#pendingCutover = null;
|
|
281
|
+
this.lifecycle.use(this.sessions);
|
|
282
|
+
this.lifecycle.use(this.streams);
|
|
283
|
+
this._registerChatTurnTaskDefinition();
|
|
284
|
+
this._registerChatRecoveryTaskDefinition();
|
|
185
285
|
withAgentSpan(this, "chat_initialization", "initialization", { "cloudflare.agents.component": "ai_chat" }, (update) => {
|
|
186
286
|
withAgentSpan(this, "initialize_chat_storage", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => {
|
|
187
|
-
this.sql`create table if not exists cf_ai_chat_agent_messages (
|
|
188
|
-
id text primary key,
|
|
189
|
-
message text not null,
|
|
190
|
-
created_at datetime default current_timestamp
|
|
191
|
-
)`;
|
|
192
287
|
this.sql`create table if not exists cf_ai_chat_request_context (
|
|
193
288
|
key text primary key,
|
|
194
289
|
value text not null
|
|
@@ -197,15 +292,22 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
197
292
|
});
|
|
198
293
|
withAgentSpan(this, "restore_chat_request_context", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => this._restoreRequestContext());
|
|
199
294
|
withAgentSpan(this, "initialize_resumable_stream", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => {
|
|
200
|
-
this._resumableStream = new ResumableStream(this.sql.bind(this))
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
this.messages = autoTransformMessages(rawMessages);
|
|
204
|
-
update({
|
|
205
|
-
"cloudflare.agents.chat.messages.loaded": rawMessages.length,
|
|
206
|
-
"cloudflare.agents.chat.active_stream.restored": this._resumableStream.hasActiveStream()
|
|
295
|
+
this._resumableStream = new ResumableStream(this.streams, this.sql.bind(this), { onProgress: (durable) => {
|
|
296
|
+
this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, durable).catch(() => {});
|
|
297
|
+
} });
|
|
207
298
|
});
|
|
299
|
+
update({ "cloudflare.agents.chat.active_stream.restored": this._resumableStream.hasActiveStream() });
|
|
208
300
|
});
|
|
301
|
+
this.#subscribeToSessionChanges();
|
|
302
|
+
const _onStart = this.onStart.bind(this);
|
|
303
|
+
this.onStart = async (props) => {
|
|
304
|
+
await withAgentSpan(this, "load_chat_messages", "startup", { "cloudflare.agents.component": "ai_chat" }, async (update) => {
|
|
305
|
+
await this._migrateLegacyMessages();
|
|
306
|
+
await this._hydrateMessages();
|
|
307
|
+
update({ "cloudflare.agents.chat.messages.loaded": this.messages.length });
|
|
308
|
+
});
|
|
309
|
+
return _onStart(props);
|
|
310
|
+
};
|
|
209
311
|
this._abortRegistry = new AbortRegistry();
|
|
210
312
|
const _onConnect = this.onConnect.bind(this);
|
|
211
313
|
this.onConnect = async (connection, ctx) => {
|
|
@@ -386,7 +488,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
386
488
|
}
|
|
387
489
|
if (event.type === "clear") {
|
|
388
490
|
this.resetTurnState();
|
|
389
|
-
this.
|
|
491
|
+
await this.#session.clearMessages();
|
|
390
492
|
await this._clearChatTerminal();
|
|
391
493
|
this._resumableStream.clearAll();
|
|
392
494
|
this._pendingResumeConnections.clear();
|
|
@@ -395,8 +497,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
395
497
|
this._lastClientTools = void 0;
|
|
396
498
|
this._lastBody = void 0;
|
|
397
499
|
this._persistRequestContext();
|
|
398
|
-
this._persistedMessageCache.clear();
|
|
399
|
-
this.messages = [];
|
|
400
500
|
this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
|
|
401
501
|
this._emit("message:clear");
|
|
402
502
|
return;
|
|
@@ -460,7 +560,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
460
560
|
const _onRequest = this.onRequest.bind(this);
|
|
461
561
|
this.onRequest = async (request) => {
|
|
462
562
|
return this._tryCatchChat(async () => {
|
|
463
|
-
if (new URL(request.url).pathname.split("/").pop() === "get-messages") return Response
|
|
563
|
+
if (new URL(request.url).pathname.split("/").pop() === "get-messages") return new Response(this.#streamMessagesAsJson(), { headers: { "content-type": "application/json" } });
|
|
464
564
|
return _onRequest(request);
|
|
465
565
|
});
|
|
466
566
|
};
|
|
@@ -590,70 +690,60 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
590
690
|
this._flushAwaitingStreamStartConnections();
|
|
591
691
|
this._activateDeferredAutoContinuation();
|
|
592
692
|
}
|
|
593
|
-
this._ensureStreamCleanupScheduled();
|
|
594
693
|
return streamId;
|
|
595
694
|
}
|
|
596
695
|
/** @internal Delegate to _resumableStream */
|
|
597
696
|
_completeStream(streamId) {
|
|
598
697
|
const completedRequestId = this._resumableStream.activeRequestId;
|
|
599
698
|
this._resumableStream.complete(streamId);
|
|
699
|
+
this._afterStreamFinished(completedRequestId);
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* @internal The producer finished; leave the row for the cutover that
|
|
703
|
+
* persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s
|
|
704
|
+
* finally settles it if no persist follows.
|
|
705
|
+
*/
|
|
706
|
+
_finishStream(streamId) {
|
|
707
|
+
const finishedRequestId = this._resumableStream.activeRequestId;
|
|
708
|
+
this._resumableStream.finish(streamId);
|
|
709
|
+
this._afterStreamFinished(finishedRequestId);
|
|
710
|
+
}
|
|
711
|
+
_afterStreamFinished(requestId) {
|
|
600
712
|
this._pendingResumeConnections.clear();
|
|
601
|
-
if (
|
|
713
|
+
if (requestId === this._continuation.activeRequestId) {
|
|
602
714
|
this._continuation.activeRequestId = null;
|
|
603
715
|
this._continuation.activeConnectionId = null;
|
|
604
716
|
}
|
|
605
|
-
this._ensureStreamCleanupScheduled();
|
|
606
717
|
}
|
|
607
718
|
/**
|
|
608
|
-
*
|
|
609
|
-
*
|
|
610
|
-
*
|
|
611
|
-
* {@link ResumableStream} only fires when a *subsequent* stream completes,
|
|
612
|
-
* which never happens for a chat that receives a single turn (#1706).
|
|
613
|
-
*
|
|
614
|
-
* `idempotent` dedupes on (callback, payload, owner) so repeated finishes
|
|
615
|
-
* collapse onto one pending alarm rather than stacking.
|
|
719
|
+
* @deprecated Streams are reclaimed at cutover and on the next stream
|
|
720
|
+
* start; no alarm is armed any more. Kept so a cleanup alarm persisted
|
|
721
|
+
* by an earlier version still resolves to a callback when it fires.
|
|
616
722
|
* @internal
|
|
617
723
|
*/
|
|
618
|
-
async
|
|
619
|
-
|
|
724
|
+
async _cleanupStreamBuffers() {
|
|
725
|
+
this._resumableStream.reclaim();
|
|
620
726
|
}
|
|
621
727
|
/**
|
|
622
|
-
*
|
|
623
|
-
*
|
|
624
|
-
*
|
|
625
|
-
*
|
|
728
|
+
* @internal Delegate to _resumableStream.
|
|
729
|
+
*
|
|
730
|
+
* A settled tool result (`tool-output-available` / `-error` / `-denied`)
|
|
731
|
+
* is flushed to SQLite immediately rather than waiting for the packed
|
|
732
|
+
* segment to fill: it captures a completed, often non-idempotent side
|
|
733
|
+
* effect (or a user's denial), and an isolate eviction before the next
|
|
734
|
+
* batch flush would lose it — recovery would re-anchor without it and
|
|
735
|
+
* re-run the tool. The flush is also what the recovery progress marker is
|
|
736
|
+
* derived from (`_chatRecoveryProgressMarker`), so a settled result counts
|
|
737
|
+
* as forward progress the moment it lands, as it did under the old
|
|
738
|
+
* per-chunk counter. Streaming deltas keep the buffer's own packing.
|
|
626
739
|
*/
|
|
627
|
-
async _cleanupStreamBuffers() {
|
|
628
|
-
await cleanupStreamBuffers(this._resumableStream, () => this._ensureStreamCleanupScheduled({ idempotent: false }));
|
|
629
|
-
}
|
|
630
|
-
/** @internal Delegate to _resumableStream. Also advances the recovery
|
|
631
|
-
* progress counter at production time (see `_maybeBumpRecoveryProgress`). */
|
|
632
740
|
async _storeStreamChunk(streamId, body) {
|
|
633
741
|
this._resumableStream.storeChunk(streamId, body);
|
|
634
742
|
let type;
|
|
635
743
|
try {
|
|
636
744
|
type = JSON.parse(body).type;
|
|
637
745
|
} catch {}
|
|
638
|
-
|
|
639
|
-
}
|
|
640
|
-
/** Advance the recovery-progress counter when a chunk represents genuinely
|
|
641
|
-
* new produced content. Uses the shared host-agnostic rule
|
|
642
|
-
* ({@link shouldCreditStreamProgress}): a milestone (started segment / settled
|
|
643
|
-
* tool) always credits, and a long single segment's streaming deltas credit
|
|
644
|
-
* through a time throttle so the no-progress window doesn't false-fire while
|
|
645
|
-
* content streams across crashes. Bumped at production time, so it reflects
|
|
646
|
-
* real forward progress and is immune to client reconnects / recovery
|
|
647
|
-
* re-persists (which replay or re-materialize stored chunks rather than flow
|
|
648
|
-
* through here). This is what the recovery no-progress window keys off
|
|
649
|
-
* (#1637), and stays compaction-proof (#1628). */
|
|
650
|
-
async _maybeBumpRecoveryProgress(type) {
|
|
651
|
-
if (shouldCreditStreamProgress({
|
|
652
|
-
codec: aiSdkRecoveryCodec,
|
|
653
|
-
type,
|
|
654
|
-
throttle: this._streamProgressCredit,
|
|
655
|
-
now: Date.now()
|
|
656
|
-
})) await this._bumpChatRecoveryProgress();
|
|
746
|
+
if (type === "tool-output-available" || type === "tool-output-error" || type === "tool-output-denied") this._resumableStream.flushBuffer();
|
|
657
747
|
}
|
|
658
748
|
/** @internal Delegate to _resumableStream */
|
|
659
749
|
_flushChunkBuffer() {
|
|
@@ -672,7 +762,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
672
762
|
this._continuation.activeRequestId = null;
|
|
673
763
|
this._continuation.activeConnectionId = null;
|
|
674
764
|
}
|
|
675
|
-
this._ensureStreamCleanupScheduled();
|
|
676
765
|
}
|
|
677
766
|
/**
|
|
678
767
|
* Reconstruct and persist a partial assistant message from an orphaned
|
|
@@ -686,9 +775,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
686
775
|
* `Think` and the client reducer use), replacing a hand-rolled chunk
|
|
687
776
|
* switch; it owns the `start` / `finish` / `message-metadata` handling;
|
|
688
777
|
* - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);
|
|
689
|
-
* - (c)+(d) upsert-by-id
|
|
690
|
-
*
|
|
691
|
-
* that `Think._upsertMessageInHistory` implements over a Session tree.
|
|
778
|
+
* - (c)+(d) upsert-by-id through the shared `OrphanPersistStore` shape
|
|
779
|
+
* (`getMessage` → `updateMessage` / `appendMessage`).
|
|
692
780
|
* When a row already owns the id, the shared `reconcileOrphanPartial`
|
|
693
781
|
* merge preserves an in-place tool result rather than letting a replayed
|
|
694
782
|
* chunk re-advance it (ai-chat has an early tool-approval persist; hosts
|
|
@@ -737,9 +825,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
737
825
|
return reconstructedId;
|
|
738
826
|
}
|
|
739
827
|
/**
|
|
740
|
-
* The orphan-persist store adapter
|
|
741
|
-
*
|
|
742
|
-
* `
|
|
828
|
+
* The orphan-persist store adapter. Orphan-persist steps **(c)/(d)** route
|
|
829
|
+
* through the shared `OrphanPersistStore` seam, backed by ai-chat's
|
|
830
|
+
* `this.messages`
|
|
743
831
|
* array + the existing `persistMessages` whole-array write path, so
|
|
744
832
|
* reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call
|
|
745
833
|
* is exactly one `persistMessages` invocation; `parentId` is unused (a flat
|
|
@@ -879,24 +967,172 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
879
967
|
...continuation && { continuation: true }
|
|
880
968
|
});
|
|
881
969
|
}
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
970
|
+
/**
|
|
971
|
+
* Lift ai-chat's legacy flat table into the default Sessions chain.
|
|
972
|
+
*
|
|
973
|
+
* Runs in `onStart` (before hydration), not in the constructor: the lift is
|
|
974
|
+
* an async import through Sessions, and the constructor does no session
|
|
975
|
+
* storage work at all.
|
|
976
|
+
*
|
|
977
|
+
* Order is read first as ids alone, then message bodies are fetched in
|
|
978
|
+
* windows bounded by row count and bytes, so a large transcript never sits
|
|
979
|
+
* in the isolate at once. Once every readable row has a copy the legacy
|
|
980
|
+
* table is DROPPED rather than renamed: keeping it would leave the object
|
|
981
|
+
* holding its history twice.
|
|
982
|
+
*/
|
|
983
|
+
async _migrateLegacyMessages() {
|
|
984
|
+
if (!(this.ctx.storage.sql.exec(`SELECT name FROM sqlite_master
|
|
985
|
+
WHERE type = 'table' AND name = 'cf_ai_chat_agent_messages'`).toArray().length > 0)) return;
|
|
986
|
+
const order = this.sql`
|
|
987
|
+
SELECT id, LENGTH(CAST(message AS BLOB)) AS bytes, created_at
|
|
988
|
+
FROM cf_ai_chat_agent_messages
|
|
989
|
+
ORDER BY created_at ASC, rowid ASC
|
|
990
|
+
`;
|
|
991
|
+
let parentId = null;
|
|
992
|
+
let imported = 0;
|
|
993
|
+
let skipped = 0;
|
|
994
|
+
let index = 0;
|
|
995
|
+
while (index < order.length) {
|
|
996
|
+
const window = [];
|
|
997
|
+
let bytes = 0;
|
|
998
|
+
while (index < order.length && window.length < LEGACY_LIFT_WINDOW_ROWS && (window.length === 0 || bytes + order[index].bytes <= LEGACY_LIFT_WINDOW_BYTES)) {
|
|
999
|
+
bytes += order[index].bytes;
|
|
1000
|
+
window.push(order[index]);
|
|
1001
|
+
index++;
|
|
1002
|
+
}
|
|
1003
|
+
const ids = JSON.stringify(window.map((row) => row.id));
|
|
1004
|
+
const bodies = new Map(this.sql`
|
|
1005
|
+
SELECT id, message FROM cf_ai_chat_agent_messages
|
|
1006
|
+
WHERE id IN (SELECT value FROM json_each(${ids}))
|
|
1007
|
+
`.map((row) => [row.id, row.message]));
|
|
1008
|
+
for (const row of window) {
|
|
1009
|
+
const body = bodies.get(row.id);
|
|
1010
|
+
if (body === void 0) {
|
|
1011
|
+
skipped++;
|
|
1012
|
+
continue;
|
|
1013
|
+
}
|
|
1014
|
+
try {
|
|
1015
|
+
const message = autoTransformMessages([JSON.parse(body)])[0];
|
|
1016
|
+
if (!message || !isValidMessageStructure(message)) {
|
|
1017
|
+
console.warn(`[AIChatAgent] Skipping invalid legacy message ${row.id}: missing or malformed id, role, or parts`);
|
|
1018
|
+
skipped++;
|
|
1019
|
+
continue;
|
|
1020
|
+
}
|
|
1021
|
+
const parsedTime = typeof row.created_at === "number" ? row.created_at : Date.parse(String(row.created_at ?? ""));
|
|
1022
|
+
await this.#session.importMessage(message, {
|
|
1023
|
+
parentId,
|
|
1024
|
+
createdAt: Number.isFinite(parsedTime) ? parsedTime : imported
|
|
1025
|
+
});
|
|
1026
|
+
parentId = message.id;
|
|
1027
|
+
imported++;
|
|
1028
|
+
} catch (error) {
|
|
1029
|
+
console.error(`Failed to migrate message ${row.id}:`, error);
|
|
1030
|
+
skipped++;
|
|
892
1031
|
}
|
|
893
|
-
this._persistedMessageCache.set(parsed.id, messageStr);
|
|
894
|
-
return parsed;
|
|
895
|
-
} catch (error) {
|
|
896
|
-
console.error(`Failed to parse message ${row.id}:`, error);
|
|
897
|
-
return null;
|
|
898
1032
|
}
|
|
899
|
-
}
|
|
1033
|
+
}
|
|
1034
|
+
if (skipped === 0 && imported === order.length) {
|
|
1035
|
+
this.ctx.storage.sql.exec("DROP TABLE cf_ai_chat_agent_messages");
|
|
1036
|
+
return;
|
|
1037
|
+
}
|
|
1038
|
+
console.error(`[AIChatAgent] Legacy lift imported ${imported} of ${order.length} rows (${skipped} skipped); leaving cf_ai_chat_agent_messages in place so they remain recoverable.`);
|
|
1039
|
+
}
|
|
1040
|
+
/**
|
|
1041
|
+
* Hydrate `this.messages` once per wake, bounded by
|
|
1042
|
+
* {@link hydrationByteBudget}. This is the only transcript read on the
|
|
1043
|
+
* startup path; every later change arrives through the Sessions change
|
|
1044
|
+
* feed.
|
|
1045
|
+
*/
|
|
1046
|
+
async _hydrateMessages() {
|
|
1047
|
+
const budget = this.hydrationByteBudget;
|
|
1048
|
+
const stored = Number.isFinite(budget) && budget > 0 ? (await this.#session.getRecentHistory(budget)).messages : await this.#session.getHistory();
|
|
1049
|
+
const messages = [];
|
|
1050
|
+
for (const message of stored) {
|
|
1051
|
+
if (!isValidMessageStructure(message)) {
|
|
1052
|
+
console.warn(`[AIChatAgent] Skipping invalid message ${message?.id}: missing or malformed id, role, or parts`);
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
messages.push(message);
|
|
1056
|
+
}
|
|
1057
|
+
this.messages = autoTransformMessages(messages);
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Mirror `this.messages` from the Sessions change feed. Every durable write
|
|
1061
|
+
* dispatches here synchronously, so write sites never hand-patch the
|
|
1062
|
+
* cache.
|
|
1063
|
+
*/
|
|
1064
|
+
#subscribeToSessionChanges() {
|
|
1065
|
+
this.sessions.subscribe(async (event) => {
|
|
1066
|
+
if (event.sessionId !== this.#session.sessionId) return;
|
|
1067
|
+
switch (event.type) {
|
|
1068
|
+
case "append": {
|
|
1069
|
+
if (!event.inserted) return;
|
|
1070
|
+
const message = this.#messageForCache(event.message);
|
|
1071
|
+
const index = this.messages.findIndex((m) => m.id === message.id);
|
|
1072
|
+
if (index === -1) this.messages.push(message);
|
|
1073
|
+
else this.messages[index] = message;
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
case "update": {
|
|
1077
|
+
const index = this.messages.findIndex((m) => m.id === event.message.id);
|
|
1078
|
+
if (index === -1) return;
|
|
1079
|
+
this.messages[index] = this.#messageForCache(event.message);
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
case "delete": {
|
|
1083
|
+
const removed = new Set(event.messageIds);
|
|
1084
|
+
this.messages = this.messages.filter((m) => !removed.has(m.id));
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
case "clear":
|
|
1088
|
+
this.messages = [];
|
|
1089
|
+
return;
|
|
1090
|
+
default: return;
|
|
1091
|
+
}
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Turn a stored row into its in-memory form. A stored row is exactly what
|
|
1096
|
+
* the write returned, so this never costs a re-read.
|
|
1097
|
+
*/
|
|
1098
|
+
#messageForCache(message) {
|
|
1099
|
+
const stored = message;
|
|
1100
|
+
return autoTransformMessages([stored])[0] ?? stored;
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Serialize the whole transcript as a JSON array of messages without ever
|
|
1104
|
+
* holding it in one string: `historyBatches()` yields bounded batches and
|
|
1105
|
+
* each batch is encoded straight into the response body.
|
|
1106
|
+
*/
|
|
1107
|
+
#streamMessagesAsJson() {
|
|
1108
|
+
const encoder = new TextEncoder();
|
|
1109
|
+
const batches = this.#session.historyBatches();
|
|
1110
|
+
let opened = false;
|
|
1111
|
+
let first = true;
|
|
1112
|
+
return new ReadableStream({
|
|
1113
|
+
pull: async (controller) => {
|
|
1114
|
+
if (!opened) {
|
|
1115
|
+
opened = true;
|
|
1116
|
+
controller.enqueue(encoder.encode("["));
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
const next = await batches.next();
|
|
1120
|
+
if (next.done) {
|
|
1121
|
+
controller.enqueue(encoder.encode("]"));
|
|
1122
|
+
controller.close();
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
let chunk = "";
|
|
1126
|
+
for (const message of autoTransformMessages(next.value)) {
|
|
1127
|
+
chunk += `${first ? "" : ","}${JSON.stringify(message)}`;
|
|
1128
|
+
first = false;
|
|
1129
|
+
}
|
|
1130
|
+
if (chunk.length > 0) controller.enqueue(encoder.encode(chunk));
|
|
1131
|
+
},
|
|
1132
|
+
cancel: async () => {
|
|
1133
|
+
await batches.return?.(void 0);
|
|
1134
|
+
}
|
|
1135
|
+
});
|
|
900
1136
|
}
|
|
901
1137
|
async _tryCatchChat(fn) {
|
|
902
1138
|
try {
|
|
@@ -2094,13 +2330,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2094
2330
|
`[0] ?? null;
|
|
2095
2331
|
}
|
|
2096
2332
|
_getAgentToolStreamId(requestId) {
|
|
2097
|
-
return this.
|
|
2098
|
-
select id, status, request_id
|
|
2099
|
-
from cf_ai_chat_stream_metadata
|
|
2100
|
-
where request_id = ${requestId}
|
|
2101
|
-
order by rowid desc
|
|
2102
|
-
limit 1
|
|
2103
|
-
`[0]?.id;
|
|
2333
|
+
return this._resumableStream.latestStreamInfoForRequest(requestId)?.id;
|
|
2104
2334
|
}
|
|
2105
2335
|
_getAgentToolStoredChunks(requestId, afterSequence = -1) {
|
|
2106
2336
|
const streamId = this._getAgentToolStreamId(requestId);
|
|
@@ -2320,34 +2550,38 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2320
2550
|
* recomputed from the live, mutable transcript. Compaction collapses older
|
|
2321
2551
|
* assistant messages into a summary, lowering the count — so a turn that had
|
|
2322
2552
|
* genuinely advanced could read as "no progress" between attempts and exhaust
|
|
2323
|
-
* its budget prematurely (#1628).
|
|
2324
|
-
*
|
|
2325
|
-
*
|
|
2326
|
-
*
|
|
2327
|
-
* re-
|
|
2328
|
-
*
|
|
2553
|
+
* its budget prematurely (#1628). It then became a KV counter bumped per
|
|
2554
|
+
* credited chunk. It is now derived from the stream log the chunks were
|
|
2555
|
+
* already flushed to (`ResumableStream.progressMarker`): the log only grows
|
|
2556
|
+
* when new content lands durably, a reconnect replay or a recovery
|
|
2557
|
+
* re-persist reads it without appending (#1637), and compaction rewrites
|
|
2558
|
+
* the transcript, not the log. Nothing is written per chunk.
|
|
2559
|
+
*
|
|
2560
|
+
* The pre-derivation KV counter is folded in once per isolate, so a marker
|
|
2561
|
+
* an in-flight incident already recorded is never read lower after the
|
|
2562
|
+
* upgrade.
|
|
2329
2563
|
*/
|
|
2330
2564
|
async _chatRecoveryProgressMarker() {
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
async _bumpChatRecoveryProgress() {
|
|
2338
|
-
return bumpChatRecoveryProgress(this.ctx.storage);
|
|
2565
|
+
this._progressSeed ??= readChatRecoveryProgress(this.ctx.storage).then((legacy) => this._resumableStream.seedProgress(legacy), (error) => {
|
|
2566
|
+
this._progressSeed = null;
|
|
2567
|
+
throw error;
|
|
2568
|
+
});
|
|
2569
|
+
await this._progressSeed;
|
|
2570
|
+
return this._resumableStream.progressMarker();
|
|
2339
2571
|
}
|
|
2340
2572
|
/**
|
|
2341
2573
|
* N9: forwarding a sub-agent's chunks IS forward progress for this parent
|
|
2342
2574
|
* turn, so credit the parent's recovery progress marker — otherwise a parent
|
|
2343
2575
|
* whose turn merely `await`s a child banks no progress of its own and its
|
|
2344
|
-
* no-progress window exhausts while the child is healthily streaming.
|
|
2576
|
+
* no-progress window exhausts while the child is healthily streaming. The
|
|
2577
|
+
* child's output goes to clients, not to this object's stream log, so the
|
|
2578
|
+
* derived marker cannot see it; this is the one explicit credit left. Only
|
|
2345
2579
|
* invoked after a child actually produced output (see
|
|
2346
2580
|
* `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
|
|
2347
2581
|
* Throttled (and reset per isolate) so we never write storage per token.
|
|
2348
2582
|
*/
|
|
2349
2583
|
async _onAgentToolStreamProgress() {
|
|
2350
|
-
if (this._agentToolStreamProgress.shouldCredit(Date.now()))
|
|
2584
|
+
if (this._agentToolStreamProgress.shouldCredit(Date.now())) this._resumableStream.creditProgress();
|
|
2351
2585
|
}
|
|
2352
2586
|
_chatRecoveryEngine() {
|
|
2353
2587
|
return this._chatRecoveryEngineInstance ??= new ChatRecoveryEngine({
|
|
@@ -2369,9 +2603,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2369
2603
|
recoveryKind: event.recoveryKind,
|
|
2370
2604
|
...event.reason ? { reason: event.reason } : {}
|
|
2371
2605
|
}),
|
|
2372
|
-
scheduleRecovery:
|
|
2373
|
-
await this.schedule(delaySeconds, callback, data, chatRecoverySchedulePolicy(reason));
|
|
2374
|
-
},
|
|
2606
|
+
scheduleRecovery: (callback, data, reason, delaySeconds) => this._enqueueChatRecovery(callback, data, reason, delaySeconds),
|
|
2375
2607
|
setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
|
|
2376
2608
|
onShouldKeepRecoveringError: (error) => console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error),
|
|
2377
2609
|
exhaustChatRecovery: (incident, config, partial, streamId, createdAt) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt),
|
|
@@ -2486,7 +2718,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2486
2718
|
persistOrphanedStream: (streamId) => this._persistOrphanedStream(streamId),
|
|
2487
2719
|
completeRecoveredStream: (streamId) => {
|
|
2488
2720
|
this._resumableStream.complete(streamId);
|
|
2489
|
-
this._ensureStreamCleanupScheduled();
|
|
2490
2721
|
},
|
|
2491
2722
|
dispatchRecoveredTurn: (input) => this._dispatchRecoveredChatTurn(input)
|
|
2492
2723
|
});
|
|
@@ -2503,14 +2734,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2503
2734
|
*/
|
|
2504
2735
|
_resolveAIChatRecoveryStream(requestId) {
|
|
2505
2736
|
let streamId = "";
|
|
2506
|
-
if (requestId)
|
|
2507
|
-
const rows = this.sql`
|
|
2508
|
-
SELECT id FROM cf_ai_chat_stream_metadata
|
|
2509
|
-
WHERE request_id = ${requestId}
|
|
2510
|
-
ORDER BY created_at DESC LIMIT 1
|
|
2511
|
-
`;
|
|
2512
|
-
if (rows.length > 0) streamId = rows[0].id;
|
|
2513
|
-
}
|
|
2737
|
+
if (requestId) streamId = this._resumableStream.latestStreamInfoForRequest(requestId)?.id ?? "";
|
|
2514
2738
|
if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
|
|
2515
2739
|
const streamStillActive = Boolean(streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId);
|
|
2516
2740
|
return {
|
|
@@ -2606,6 +2830,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2606
2830
|
return {};
|
|
2607
2831
|
}
|
|
2608
2832
|
async _chatRecoveryContinue(data) {
|
|
2833
|
+
await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryContinueDetached(data, onTurnStarted));
|
|
2834
|
+
}
|
|
2835
|
+
async _chatRecoveryContinueDetached(data, onTurnStarted) {
|
|
2609
2836
|
const previousRootRequestId = this._activeChatRecoveryRootRequestId;
|
|
2610
2837
|
this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
|
|
2611
2838
|
try {
|
|
@@ -2626,6 +2853,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2626
2853
|
return;
|
|
2627
2854
|
}
|
|
2628
2855
|
this._applyRecoveredRequestContext(data);
|
|
2856
|
+
onTurnStarted?.();
|
|
2629
2857
|
const result = await this.continueLastTurn();
|
|
2630
2858
|
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
2631
2859
|
} catch (error) {
|
|
@@ -2754,25 +2982,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2754
2982
|
* Two residual at-least-once edges, both deliberately accepted as "deliver a
|
|
2755
2983
|
* second banner" ≫ "silently drop the turn":
|
|
2756
2984
|
* • No `incidentId` at all in the payload (only reachable via a direct/test
|
|
2757
|
-
* invocation — every production
|
|
2758
|
-
* incident can't be persisted (no key), so the guard can't
|
|
2985
|
+
* invocation — every production recovery enqueue carries one): the
|
|
2986
|
+
* synthesized incident can't be persisted (no key), so the guard can't
|
|
2987
|
+
* arm.
|
|
2759
2988
|
* • The record is swept AGAIN between two alarms (the guard re-persists on
|
|
2760
2989
|
* the first, so this needs a second independent sweep) — vanishingly
|
|
2761
2990
|
* unlikely.
|
|
2762
2991
|
*/
|
|
2763
2992
|
/**
|
|
2764
|
-
*
|
|
2765
|
-
*
|
|
2993
|
+
* Host memory-limit policy hook (#1825), dispatched structurally by
|
|
2994
|
+
* Lifecycle's circuit breaker — protected because it is framework
|
|
2995
|
+
* machinery, not part of the public chat API. Tasks applies the breaker to
|
|
2996
|
+
* root recovery runs; the routed dynamic-agent fallback applies it to
|
|
2997
|
+
* `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
|
|
2998
|
+
* strike budget this hook seals active incidents via
|
|
2999
|
+
* {@link _cf_sealMemoryLimitedRecovery}.
|
|
2766
3000
|
*/
|
|
2767
|
-
|
|
2768
|
-
|
|
3001
|
+
async onAlarmMemoryLimit(context) {
|
|
3002
|
+
if (!context.sealed) return;
|
|
3003
|
+
await this._cf_sealMemoryLimitedRecovery();
|
|
2769
3004
|
}
|
|
2770
3005
|
/**
|
|
2771
|
-
* Seal any still-live recovery incident as an out-of-memory exhaustion
|
|
2772
|
-
* the alarm circuit breaker trips at its strike budget (#1825). Runs
|
|
2773
|
-
* outermost alarm frame (post-unwind), so the terminal banner /
|
|
2774
|
-
* and the sealed-incident write can land where mid-turn
|
|
2775
|
-
* the shared give-up spine via the recovery engine.
|
|
3006
|
+
* Seal any still-live recovery incident as an out-of-memory exhaustion
|
|
3007
|
+
* when the alarm circuit breaker trips at its strike budget (#1825). Runs
|
|
3008
|
+
* at the outermost alarm frame (post-unwind), so the terminal banner /
|
|
3009
|
+
* `onExhausted` and the sealed-incident write can land where mid-turn
|
|
3010
|
+
* writes OOMed. Reuses the shared give-up spine via the recovery engine.
|
|
2776
3011
|
*/
|
|
2777
3012
|
async _cf_sealMemoryLimitedRecovery() {
|
|
2778
3013
|
const active = await listActiveChatRecoveryIncidents(this.ctx.storage);
|
|
@@ -2840,6 +3075,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2840
3075
|
return lastMessage?.role === "user" && lastMessage.id === snapshot.latestUserMessageId;
|
|
2841
3076
|
}
|
|
2842
3077
|
async _chatRecoveryRetry(data) {
|
|
3078
|
+
await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryRetryDetached(data, onTurnStarted));
|
|
3079
|
+
}
|
|
3080
|
+
async _chatRecoveryRetryDetached(data, onTurnStarted) {
|
|
2843
3081
|
const previousRootRequestId = this._activeChatRecoveryRootRequestId;
|
|
2844
3082
|
this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
|
|
2845
3083
|
try {
|
|
@@ -2864,6 +3102,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2864
3102
|
return;
|
|
2865
3103
|
}
|
|
2866
3104
|
this._applyRecoveredRequestContext(data);
|
|
3105
|
+
onTurnStarted?.();
|
|
2867
3106
|
const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
|
|
2868
3107
|
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
2869
3108
|
} catch (error) {
|
|
@@ -2880,33 +3119,53 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2880
3119
|
_getPartialStreamText(streamId) {
|
|
2881
3120
|
return aiSdkRecoveryCodec.toRecoveryPartial(this._resumableStream.getStreamChunks(streamId).map((chunk) => chunk.body));
|
|
2882
3121
|
}
|
|
3122
|
+
/**
|
|
3123
|
+
* The turn whose finished stream is waiting for its message write: the
|
|
3124
|
+
* cutover rides on the instance, not on an argument, so a subclass that
|
|
3125
|
+
* overrides {@link persistMessages} and calls `super` with only the
|
|
3126
|
+
* messages still lands the message, the stream's settlement and the
|
|
3127
|
+
* deletion of its rows in one transaction. Consumed by the first persist
|
|
3128
|
+
* that carries the turn's message; cleared when the turn ends.
|
|
3129
|
+
*/
|
|
3130
|
+
#pendingCutover;
|
|
2883
3131
|
async persistMessages(messages, excludeBroadcastIds = [], options) {
|
|
2884
|
-
const
|
|
3132
|
+
const priorMessages = [...this.messages];
|
|
3133
|
+
const priorById = new Map(priorMessages.map((m) => [m.id, m]));
|
|
3134
|
+
const mergedMessages = reconcileMessages(messages, priorMessages, (msg) => this._sanitizeMessageForPersistence(msg));
|
|
3135
|
+
const toWrite = [];
|
|
2885
3136
|
for (const message of mergedMessages) {
|
|
2886
|
-
const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message),
|
|
2887
|
-
const
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
this.sql`
|
|
2891
|
-
insert into cf_ai_chat_agent_messages (id, message)
|
|
2892
|
-
values (${safe.id}, ${json})
|
|
2893
|
-
on conflict(id) do update set message = excluded.message
|
|
2894
|
-
`;
|
|
2895
|
-
this._persistedMessageCache.set(safe.id, json);
|
|
3137
|
+
const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message), priorMessages);
|
|
3138
|
+
const prior = priorById.get(resolved.id);
|
|
3139
|
+
if (prior && JSON.stringify(prior) === JSON.stringify(resolved)) continue;
|
|
3140
|
+
toWrite.push(resolved);
|
|
2896
3141
|
}
|
|
3142
|
+
const cutover = this.#pendingCutover;
|
|
3143
|
+
if (cutover && mergedMessages.some((message) => message.id === cutover.messageId)) {
|
|
3144
|
+
this.#pendingCutover = null;
|
|
3145
|
+
const sync = this.#session.__DO_NOT_USE_WILL_BREAK__sync();
|
|
3146
|
+
const afters = [];
|
|
3147
|
+
try {
|
|
3148
|
+
this._resumableStream.cutover(cutover.streamId, () => {
|
|
3149
|
+
for (const message of toWrite) afters.push(sync.upsert(message).after);
|
|
3150
|
+
}, { discard: cutover.discard });
|
|
3151
|
+
} catch (error) {
|
|
3152
|
+
sync.abandon();
|
|
3153
|
+
throw error;
|
|
3154
|
+
}
|
|
3155
|
+
for (const after of afters) await after();
|
|
3156
|
+
} else for (const message of toWrite) await this.#session.upsertMessage(message);
|
|
2897
3157
|
if (options?._deleteStaleRows) {
|
|
2898
|
-
const serverIds = new Set(
|
|
2899
|
-
if (mergedMessages.every((
|
|
2900
|
-
const keepIds = new Set(mergedMessages.map((
|
|
2901
|
-
|
|
2902
|
-
select id from cf_ai_chat_agent_messages
|
|
2903
|
-
` || []).map((row) => row.id).filter((id) => !keepIds.has(id));
|
|
2904
|
-
this._deleteMessagesByIds(staleIds);
|
|
3158
|
+
const serverIds = new Set(priorMessages.map((message) => message.id));
|
|
3159
|
+
if (mergedMessages.every((message) => serverIds.has(message.id))) {
|
|
3160
|
+
const keepIds = new Set(mergedMessages.map((message) => message.id));
|
|
3161
|
+
await this._deleteMessagesByIds(this.messages.map((message) => message.id).filter((id) => !keepIds.has(id)));
|
|
2905
3162
|
}
|
|
2906
3163
|
}
|
|
2907
|
-
if (this.maxPersistedMessages != null)
|
|
2908
|
-
|
|
2909
|
-
|
|
3164
|
+
if (this.maxPersistedMessages != null) {
|
|
3165
|
+
const stored = await this.#session.getHistoryRowStats();
|
|
3166
|
+
const excess = stored.length - this.maxPersistedMessages;
|
|
3167
|
+
if (excess > 0) await this._deleteMessagesByIds(stored.slice(0, excess).map((row) => row.id));
|
|
3168
|
+
}
|
|
2910
3169
|
this._broadcastChatMessage({
|
|
2911
3170
|
messages: mergedMessages,
|
|
2912
3171
|
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
@@ -2941,38 +3200,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2941
3200
|
};
|
|
2942
3201
|
}
|
|
2943
3202
|
/**
|
|
2944
|
-
*
|
|
2945
|
-
* data that should not be stored or sent back in subsequent requests.
|
|
3203
|
+
* Applies the ai-chat-specific normalization Sessions does not do.
|
|
2946
3204
|
*
|
|
2947
|
-
*
|
|
3205
|
+
* Sessions already strips OpenAI ephemeral fields (itemId,
|
|
3206
|
+
* reasoningEncryptedContent) and drops truly empty reasoning parts on every
|
|
3207
|
+
* write, so those steps are not repeated here.
|
|
2948
3208
|
*
|
|
2949
|
-
*
|
|
2950
|
-
* (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
|
|
2951
|
-
* itemIds and reasoningEncryptedContent to message parts. When persisted
|
|
2952
|
-
* and sent back, OpenAI rejects duplicate itemIds.
|
|
3209
|
+
* Pipeline:
|
|
2953
3210
|
*
|
|
2954
|
-
*
|
|
3211
|
+
* 1. **Truncate provider-executed tool payloads**: Server-side tool
|
|
2955
3212
|
* executions (e.g. Anthropic code_execution, text_editor) can produce
|
|
2956
3213
|
* 200KB+ payloads in `input` and `output`. These are truncated since the
|
|
2957
3214
|
* model has already consumed the results.
|
|
2958
3215
|
*
|
|
2959
|
-
*
|
|
2960
|
-
* with no text and no remaining providerMetadata are removed. Parts that
|
|
2961
|
-
* still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
|
|
2962
|
-
* with providerMetadata.anthropic.redactedData) are preserved, as they
|
|
2963
|
-
* contain data required for round-tripping with the provider API.
|
|
2964
|
-
*
|
|
2965
|
-
* 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
|
|
3216
|
+
* 2. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
|
|
2966
3217
|
* method, allowing subclasses to apply custom transformations.
|
|
2967
3218
|
*
|
|
2968
3219
|
* @param message - The message to sanitize
|
|
2969
|
-
* @returns A new message with
|
|
3220
|
+
* @returns A new message with ai-chat's normalization applied
|
|
2970
3221
|
*/
|
|
2971
3222
|
_sanitizeMessageForPersistence(message) {
|
|
2972
|
-
const
|
|
2973
|
-
const parts = baseSanitized.parts.map((part) => AIChatAgent._truncateProviderExecutedToolPayloads(part));
|
|
3223
|
+
const parts = message.parts.map((part) => AIChatAgent._truncateProviderExecutedToolPayloads(part));
|
|
2974
3224
|
return this.sanitizeMessageForPersistence({
|
|
2975
|
-
...
|
|
3225
|
+
...message,
|
|
2976
3226
|
parts
|
|
2977
3227
|
});
|
|
2978
3228
|
}
|
|
@@ -3033,54 +3283,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3033
3283
|
return key.startsWith(PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX);
|
|
3034
3284
|
}
|
|
3035
3285
|
/**
|
|
3036
|
-
* Delete
|
|
3037
|
-
*
|
|
3038
|
-
* 100 bound-parameter limit. No-op for an empty list.
|
|
3039
|
-
* @internal
|
|
3286
|
+
* Delete message rows through Sessions. The change feed removes them from
|
|
3287
|
+
* `this.messages`.
|
|
3040
3288
|
*/
|
|
3041
|
-
_deleteMessagesByIds(ids) {
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
const strings = buildInClauseStrings("delete from cf_ai_chat_agent_messages where id in ", batch.length);
|
|
3045
|
-
this.sql(strings, ...batch);
|
|
3046
|
-
for (const id of batch) this._persistedMessageCache.delete(id);
|
|
3047
|
-
}
|
|
3048
|
-
}
|
|
3049
|
-
/**
|
|
3050
|
-
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
3051
|
-
* Called after each persist to keep storage bounded.
|
|
3052
|
-
*/
|
|
3053
|
-
_enforceMaxPersistedMessages() {
|
|
3054
|
-
if (this.maxPersistedMessages == null) return;
|
|
3055
|
-
const count = this.sql`
|
|
3056
|
-
select count(*) as cnt from cf_ai_chat_agent_messages
|
|
3057
|
-
`?.[0]?.cnt ?? 0;
|
|
3058
|
-
if (count <= this.maxPersistedMessages) return;
|
|
3059
|
-
const excess = count - this.maxPersistedMessages;
|
|
3060
|
-
const toDelete = this.sql`
|
|
3061
|
-
select id from cf_ai_chat_agent_messages
|
|
3062
|
-
order by created_at asc
|
|
3063
|
-
limit ${excess}
|
|
3064
|
-
`;
|
|
3065
|
-
if (toDelete && toDelete.length > 0) this._deleteMessagesByIds(toDelete.map((row) => row.id));
|
|
3066
|
-
}
|
|
3067
|
-
/**
|
|
3068
|
-
* Enforces SQLite row size limits by compacting tool outputs and text parts
|
|
3069
|
-
* when a serialized message exceeds the safety threshold (1.8MB).
|
|
3070
|
-
*
|
|
3071
|
-
* Only fires in pathological cases (extremely large tool outputs or text).
|
|
3072
|
-
* Returns the message unchanged if it fits within limits.
|
|
3073
|
-
*
|
|
3074
|
-
* Compaction strategy:
|
|
3075
|
-
* 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
|
|
3076
|
-
* 2. If still too big, truncate text parts from oldest to newest
|
|
3077
|
-
* 3. Add metadata so clients can detect compaction
|
|
3078
|
-
*
|
|
3079
|
-
* @param message - The message to check
|
|
3080
|
-
* @returns The message, compacted if necessary
|
|
3081
|
-
*/
|
|
3082
|
-
_enforceRowSizeLimit(message) {
|
|
3083
|
-
return enforceRowSizeLimit(message, { warn: (m) => console.warn(`[AIChatAgent] ${m}`) });
|
|
3289
|
+
async _deleteMessagesByIds(ids) {
|
|
3290
|
+
if (ids.length === 0) return;
|
|
3291
|
+
await this.#session.deleteMessages(ids);
|
|
3084
3292
|
}
|
|
3085
3293
|
/**
|
|
3086
3294
|
* Shared helper for finding a tool part by toolCallId and applying an update.
|
|
@@ -3148,16 +3356,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3148
3356
|
...message,
|
|
3149
3357
|
parts: updatedParts
|
|
3150
3358
|
});
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
set message = ${json}
|
|
3156
|
-
where id = ${message.id}
|
|
3157
|
-
`;
|
|
3158
|
-
this._persistedMessageCache.set(message.id, json);
|
|
3159
|
-
const persisted = this._loadMessagesFromDb();
|
|
3160
|
-
this.messages = autoTransformMessages(persisted);
|
|
3359
|
+
if (!await this.#session.updateMessage(updatedMessage)) {
|
|
3360
|
+
const index = this.messages.findIndex((candidate) => candidate.id === updatedMessage.id);
|
|
3361
|
+
if (index !== -1) this.messages[index] = autoTransformMessages([updatedMessage])[0];
|
|
3362
|
+
}
|
|
3161
3363
|
}
|
|
3162
3364
|
}
|
|
3163
3365
|
if (!wasFound) {
|
|
@@ -3319,7 +3521,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3319
3521
|
const { done, value } = readResult;
|
|
3320
3522
|
if (done) {
|
|
3321
3523
|
if (abortSignal?.aborted) break;
|
|
3322
|
-
this.
|
|
3524
|
+
this._finishStream(streamId);
|
|
3323
3525
|
streamCompleted.value = true;
|
|
3324
3526
|
this._broadcastChatMessage({
|
|
3325
3527
|
body: "",
|
|
@@ -3368,13 +3570,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3368
3570
|
parts: [...this._streamingMessage.parts]
|
|
3369
3571
|
};
|
|
3370
3572
|
const sanitized = this._sanitizeMessageForPersistence(snapshot);
|
|
3371
|
-
const
|
|
3372
|
-
this.
|
|
3373
|
-
INSERT INTO cf_ai_chat_agent_messages (id, message)
|
|
3374
|
-
VALUES (${sanitized.id}, ${json})
|
|
3375
|
-
ON CONFLICT(id) DO UPDATE SET message = excluded.message
|
|
3376
|
-
`;
|
|
3377
|
-
this._approvalPersistedMessageId = sanitized.id;
|
|
3573
|
+
const stored = await this.#session.upsertMessage(sanitized);
|
|
3574
|
+
this._approvalPersistedMessageId = stored.message.id;
|
|
3378
3575
|
}
|
|
3379
3576
|
if ((data.type === "tool-output-available" || data.type === "tool-output-error") && data.toolCallId) {
|
|
3380
3577
|
if (!message.parts.some((p) => "toolCallId" in p && p.toolCallId === data.toolCallId)) if (data.type === "tool-output-available") this._findAndUpdateToolPart(data.toolCallId, "_streamSSEReply", [
|
|
@@ -3487,7 +3684,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3487
3684
|
} catch (_error) {}
|
|
3488
3685
|
}
|
|
3489
3686
|
if (!streamCompleted.value) {
|
|
3490
|
-
this.
|
|
3687
|
+
this._finishStream(streamId);
|
|
3491
3688
|
streamCompleted.value = true;
|
|
3492
3689
|
this._broadcastChatMessage({
|
|
3493
3690
|
body: "",
|
|
@@ -3541,7 +3738,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3541
3738
|
type: "text-end",
|
|
3542
3739
|
id
|
|
3543
3740
|
}, continuation);
|
|
3544
|
-
this.
|
|
3741
|
+
this._finishStream(streamId);
|
|
3545
3742
|
streamCompleted.value = true;
|
|
3546
3743
|
this._broadcastChatMessage({
|
|
3547
3744
|
body: "",
|
|
@@ -3568,7 +3765,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3568
3765
|
type: "text-end",
|
|
3569
3766
|
id
|
|
3570
3767
|
}, continuation);
|
|
3571
|
-
this.
|
|
3768
|
+
this._finishStream(streamId);
|
|
3572
3769
|
streamCompleted.value = true;
|
|
3573
3770
|
this._broadcastChatMessage({
|
|
3574
3771
|
body: "",
|
|
@@ -3688,6 +3885,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3688
3885
|
if (streamCompleted.value && streamResult.status !== "error" && !stallRouted) this._emit("message:response");
|
|
3689
3886
|
}
|
|
3690
3887
|
}
|
|
3888
|
+
this.#pendingCutover = this._resumableStream.pendingCutoverId === streamId ? {
|
|
3889
|
+
streamId,
|
|
3890
|
+
messageId: earlyPersistedId ?? message.id,
|
|
3891
|
+
discard: !this._agentToolRunsByRequestId.get(id)
|
|
3892
|
+
} : null;
|
|
3691
3893
|
if (message.parts.length > 0) if (earlyPersistedId) {
|
|
3692
3894
|
const persistedMessage = {
|
|
3693
3895
|
...message,
|
|
@@ -3706,6 +3908,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3706
3908
|
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
3707
3909
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|
|
3708
3910
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|
|
3911
|
+
this.#pendingCutover = null;
|
|
3912
|
+
this._resumableStream.finalizePending();
|
|
3709
3913
|
this._pendingChatResponseResults.push({
|
|
3710
3914
|
message,
|
|
3711
3915
|
requestId: id,
|
|
@@ -3715,6 +3919,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3715
3919
|
});
|
|
3716
3920
|
return streamResult;
|
|
3717
3921
|
} finally {
|
|
3922
|
+
this.#pendingCutover = null;
|
|
3923
|
+
this._resumableStream.finalizePending();
|
|
3718
3924
|
this._onStreamingTurnFinalized();
|
|
3719
3925
|
}
|
|
3720
3926
|
}));
|