@cloudflare/ai-chat 0.8.4 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -194,7 +194,15 @@ declare class AIChatAgent<
194
194
  private _agentToolLastErrors;
195
195
  private _agentToolPreTurnAssistantIds;
196
196
  private _agentToolLiveSequences;
197
- private _agentToolActiveRunId;
197
+ /**
198
+ * Request id → run id for in-flight agent-tool turns (null = resolved as
199
+ * not an agent-tool turn, cached so unrelated turns don't re-query SQLite
200
+ * per frame). Drives frame attribution in {@link broadcast}: a frame
201
+ * belongs to a run iff it carries that run's turn request id, so an error
202
+ * in a user-driven turn or a concurrent run can never leak into another
203
+ * run's state (#1575).
204
+ */
205
+ private _agentToolRunsByRequestId;
198
206
  /**
199
207
  * Client tool schemas from the most recent chat request.
200
208
  * Stored so they can be passed to onChatMessage during tool continuations.
@@ -302,6 +310,13 @@ declare class AIChatAgent<
302
310
  msg: string | ArrayBuffer | ArrayBufferView,
303
311
  without?: string[]
304
312
  ): void;
313
+ /**
314
+ * Resolve the agent-tool run whose turn owns a request id, or null when the
315
+ * request is not an agent-tool turn. Falls back to the persisted run row
316
+ * (written when the turn starts, see `_registerAgentToolTurn`) so
317
+ * attribution survives a DO restart mid-run; either outcome is cached.
318
+ */
319
+ private _agentToolRunForRequest;
305
320
  constructor(ctx: AgentContext, env: Env);
306
321
  private _ensureAgentToolTables;
307
322
  private _flushAwaitingStreamStartConnections;
@@ -313,6 +328,16 @@ declare class AIChatAgent<
313
328
  /**
314
329
  * Notify a connection about an active stream that can be resumed.
315
330
  * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
331
+ *
332
+ * A connection can legitimately be notified more than once for the same
333
+ * request — proactively from onConnect AND in response to its
334
+ * CF_AGENT_STREAM_RESUME_REQUEST (#1733). This is intentional and must NOT
335
+ * be deduped here: an explicit resume request always deserves a response
336
+ * (the client's reconnectToStream would otherwise hang until its safety
337
+ * timeout, with no replay), and the proactive notify is required for
338
+ * clients that never send a resume request. The notify itself is a single
339
+ * tiny frame; clients are responsible for deduping the ACK so the full
340
+ * chunk buffer is not replayed twice.
316
341
  * @param connection - The WebSocket connection to notify
317
342
  */
318
343
  private _notifyStreamResuming;
@@ -325,10 +350,34 @@ declare class AIChatAgent<
325
350
  requestId: string,
326
351
  options?: {
327
352
  messageId?: string;
353
+ continuation?: boolean;
328
354
  }
329
355
  ): string;
330
356
  /** @internal Delegate to _resumableStream */
331
357
  protected _completeStream(streamId: string): void;
358
+ /**
359
+ * Ensure a single cleanup alarm is pending for this DO's resumable-stream
360
+ * buffers. Armed whenever a stream finishes (completes or errors) so that
361
+ * idle/one-off chat DOs still reclaim their buffers — the lazy sweep in
362
+ * {@link ResumableStream} only fires when a *subsequent* stream completes,
363
+ * which never happens for a chat that receives a single turn (#1706).
364
+ *
365
+ * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
366
+ * collapse onto one pending alarm rather than stacking.
367
+ * @internal
368
+ */
369
+ protected _ensureStreamCleanupScheduled({
370
+ idempotent
371
+ }?: {
372
+ idempotent?: boolean;
373
+ }): Promise<void>;
374
+ /**
375
+ * Alarm callback: sweep aged stream buffers, then re-arm only while rows
376
+ * remain so a fully-swept DO stops waking itself. Public so it is reachable
377
+ * as a schedule callback.
378
+ * @internal
379
+ */
380
+ _cleanupStreamBuffers(): Promise<void>;
332
381
  /** @internal Delegate to _resumableStream. Also advances the recovery
333
382
  * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
334
383
  protected _storeStreamChunk(streamId: string, body: string): Promise<void>;
@@ -623,6 +672,15 @@ declare class AIChatAgent<
623
672
  output: unknown,
624
673
  messagesAfterStart: readonly UIMessage[]
625
674
  ): string;
675
+ /**
676
+ * Bind the child turn that is about to stream to its agent-tool run, at
677
+ * the moment the turn's request id is first knowable (inside the turn,
678
+ * before any frame is broadcast). The in-memory mapping drives frame
679
+ * attribution in {@link broadcast}; the run row's `request_id` is
680
+ * persisted here rather than at terminal so attribution also survives a
681
+ * DO restart mid-run (#1575).
682
+ */
683
+ private _registerAgentToolTurn;
626
684
  startAgentToolRun(
627
685
  input: unknown,
628
686
  options: {
@@ -914,9 +972,10 @@ declare class AIChatAgent<
914
972
  * Exactly-once terminalization here rests SOLELY on the
915
973
  * `stored?.status === "exhausted"` re-entry guard below — unlike
916
974
  * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer
917
- * to short-circuit a duplicate alarm earlier. The sealed incident is
918
- * re-persisted even when the record was found missing, so a swept record is
919
- * re-armed for the guard on the next alarm.
975
+ * to short-circuit a duplicate alarm earlier. The incident read/write are
976
+ * best-effort because they back only that guard, not the terminal UX: a
977
+ * failed read synthesizes the incident and a failed seal write costs at most
978
+ * a re-delivered banner on a duplicate alarm.
920
979
  *
921
980
  * Two residual at-least-once edges, both deliberately accepted as "deliver a
922
981
  * second banner" ≫ "silently drop the turn":
package/dist/index.js CHANGED
@@ -20,6 +20,7 @@ const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
20
20
  const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
21
21
  const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
22
22
  const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
23
+ const STREAM_CLEANUP_DELAY_SECONDS = 600;
23
24
  function sendIfOpen(connection, message) {
24
25
  try {
25
26
  connection.send(message);
@@ -92,28 +93,44 @@ var AIChatAgent = class AIChatAgent extends Agent {
92
93
  });
93
94
  }
94
95
  broadcast(msg, without) {
95
- if (this._agentToolForwarders.size > 0 && typeof msg === "string") try {
96
+ if ((this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0) && typeof msg === "string") try {
96
97
  const parsed = JSON.parse(msg);
97
- if (parsed.type === "cf_agent_use_chat_response") {
98
- if (parsed.error === true && typeof parsed.body === "string") {
99
- const runIds = this._agentToolActiveRunId !== null ? [this._agentToolActiveRunId] : [...this._agentToolForwarders.keys()];
100
- for (const runId of runIds) this._agentToolLastErrors.set(runId, parsed.body);
101
- } else if (typeof parsed.body === "string" && parsed.body.length > 0) {
102
- const entries = this._agentToolActiveRunId !== null ? [[this._agentToolActiveRunId, this._agentToolForwarders.get(this._agentToolActiveRunId) ?? /* @__PURE__ */ new Set()]] : [...this._agentToolForwarders.entries()];
103
- for (const [runId, forwarders] of entries) {
98
+ if (parsed.type === "cf_agent_use_chat_response" && typeof parsed.id === "string") {
99
+ const runId = this._agentToolRunForRequest(parsed.id);
100
+ if (runId !== null) {
101
+ if (parsed.error === true && typeof parsed.body === "string") this._agentToolLastErrors.set(runId, parsed.body);
102
+ else if (typeof parsed.body === "string" && parsed.body.length > 0) {
104
103
  const sequence = this._agentToolLiveSequences.get(runId) ?? 0;
105
104
  this._agentToolLiveSequences.set(runId, sequence + 1);
106
105
  const chunk = {
107
106
  sequence,
108
107
  body: parsed.body
109
108
  };
110
- for (const forward of forwarders) forward(chunk);
109
+ const forwarders = this._agentToolForwarders.get(runId);
110
+ if (forwarders) for (const forward of forwarders) forward(chunk);
111
111
  }
112
112
  }
113
113
  }
114
114
  } catch {}
115
115
  super.broadcast(msg, without);
116
116
  }
117
+ /**
118
+ * Resolve the agent-tool run whose turn owns a request id, or null when the
119
+ * request is not an agent-tool turn. Falls back to the persisted run row
120
+ * (written when the turn starts, see `_registerAgentToolTurn`) so
121
+ * attribution survives a DO restart mid-run; either outcome is cached.
122
+ */
123
+ _agentToolRunForRequest(requestId) {
124
+ const cached = this._agentToolRunsByRequestId.get(requestId);
125
+ if (cached !== void 0) return cached;
126
+ const runId = this.sql`
127
+ select run_id from cf_ai_chat_agent_tool_runs
128
+ where request_id = ${requestId} and status = 'running'
129
+ limit 1
130
+ `?.[0]?.run_id ?? null;
131
+ this._agentToolRunsByRequestId.set(requestId, runId);
132
+ return runId;
133
+ }
117
134
  constructor(ctx, env) {
118
135
  super(ctx, env);
119
136
  this._streamingMessage = null;
@@ -134,7 +151,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
134
151
  this._agentToolLastErrors = /* @__PURE__ */ new Map();
135
152
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
136
153
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
137
- this._agentToolActiveRunId = null;
154
+ this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
138
155
  this._persistedMessageCache = /* @__PURE__ */ new Map();
139
156
  this.maxPersistedMessages = void 0;
140
157
  this.messageConcurrency = "queue";
@@ -434,6 +451,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
434
451
  /**
435
452
  * Notify a connection about an active stream that can be resumed.
436
453
  * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
454
+ *
455
+ * A connection can legitimately be notified more than once for the same
456
+ * request — proactively from onConnect AND in response to its
457
+ * CF_AGENT_STREAM_RESUME_REQUEST (#1733). This is intentional and must NOT
458
+ * be deduped here: an explicit resume request always deserves a response
459
+ * (the client's reconnectToStream would otherwise hang until its safety
460
+ * timeout, with no replay), and the proactive notify is required for
461
+ * clients that never send a resume request. The notify itself is a single
462
+ * tiny frame; clients are responsible for deduping the ACK so the full
463
+ * chunk buffer is not replayed twice.
437
464
  * @param connection - The WebSocket connection to notify
438
465
  */
439
466
  _notifyStreamResuming(connection) {
@@ -459,6 +486,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
459
486
  this._flushAwaitingStreamStartConnections();
460
487
  this._activateDeferredAutoContinuation();
461
488
  }
489
+ this._ensureStreamCleanupScheduled();
462
490
  return streamId;
463
491
  }
464
492
  /** @internal Delegate to _resumableStream */
@@ -470,6 +498,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
470
498
  this._continuation.activeRequestId = null;
471
499
  this._continuation.activeConnectionId = null;
472
500
  }
501
+ this._ensureStreamCleanupScheduled();
502
+ }
503
+ /**
504
+ * Ensure a single cleanup alarm is pending for this DO's resumable-stream
505
+ * buffers. Armed whenever a stream finishes (completes or errors) so that
506
+ * idle/one-off chat DOs still reclaim their buffers — the lazy sweep in
507
+ * {@link ResumableStream} only fires when a *subsequent* stream completes,
508
+ * which never happens for a chat that receives a single turn (#1706).
509
+ *
510
+ * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
511
+ * collapse onto one pending alarm rather than stacking.
512
+ * @internal
513
+ */
514
+ async _ensureStreamCleanupScheduled({ idempotent = true } = {}) {
515
+ await this.schedule(STREAM_CLEANUP_DELAY_SECONDS, "_cleanupStreamBuffers", void 0, { idempotent });
516
+ }
517
+ /**
518
+ * Alarm callback: sweep aged stream buffers, then re-arm only while rows
519
+ * remain so a fully-swept DO stops waking itself. Public so it is reachable
520
+ * as a schedule callback.
521
+ * @internal
522
+ */
523
+ async _cleanupStreamBuffers() {
524
+ this._resumableStream.cleanup();
525
+ if (this._resumableStream.hasReclaimableStreams()) await this._ensureStreamCleanupScheduled({ idempotent: false });
473
526
  }
474
527
  /** @internal Delegate to _resumableStream. Also advances the recovery
475
528
  * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
@@ -508,6 +561,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
508
561
  this._continuation.activeRequestId = null;
509
562
  this._continuation.activeConnectionId = null;
510
563
  }
564
+ this._ensureStreamCleanupScheduled();
511
565
  }
512
566
  /**
513
567
  * Reconstruct and persist a partial assistant message from an orphaned
@@ -1265,6 +1319,27 @@ var AIChatAgent = class AIChatAgent extends Agent {
1265
1319
  return String(output);
1266
1320
  }
1267
1321
  }
1322
+ /**
1323
+ * Bind the child turn that is about to stream to its agent-tool run, at
1324
+ * the moment the turn's request id is first knowable (inside the turn,
1325
+ * before any frame is broadcast). The in-memory mapping drives frame
1326
+ * attribution in {@link broadcast}; the run row's `request_id` is
1327
+ * persisted here rather than at terminal so attribution also survives a
1328
+ * DO restart mid-run (#1575).
1329
+ */
1330
+ _registerAgentToolTurn(runId) {
1331
+ const requestId = this._turnQueue.activeRequestId;
1332
+ if (requestId === null) {
1333
+ console.warn(`[AIChatAgent] agent-tool run ${runId} has no active request id at turn start; frame attribution will be skipped`);
1334
+ return;
1335
+ }
1336
+ this._agentToolRunsByRequestId.set(requestId, runId);
1337
+ this.sql`
1338
+ update cf_ai_chat_agent_tool_runs
1339
+ set request_id = ${requestId}
1340
+ where run_id = ${runId}
1341
+ `;
1342
+ }
1268
1343
  async startAgentToolRun(input, options) {
1269
1344
  const existing = await this.inspectAgentToolRun(options.runId);
1270
1345
  if (existing) return existing;
@@ -1289,7 +1364,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1289
1364
  const previousBody = this._lastBody;
1290
1365
  this._setRequestContext(void 0, { agentToolInput: input });
1291
1366
  const result = await this.saveMessages(async (messages) => {
1292
- this._agentToolActiveRunId = options.runId;
1367
+ this._registerAgentToolTurn(options.runId);
1293
1368
  return [...messages, this.formatAgentToolInput(input, { runId: options.runId })];
1294
1369
  }, { signal: controller.signal }).finally(() => {
1295
1370
  this._setRequestContext(previousClientTools, previousBody);
@@ -1364,7 +1439,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1364
1439
  options.signal?.removeEventListener("abort", abortFromParent);
1365
1440
  this._agentToolAbortControllers.delete(options.runId);
1366
1441
  this._agentToolLiveSequences.delete(options.runId);
1367
- if (this._agentToolActiveRunId === options.runId) this._agentToolActiveRunId = null;
1442
+ if (this._agentToolAbortControllers.size === 0) this._agentToolRunsByRequestId.clear();
1443
+ else for (const [reqId, runId] of this._agentToolRunsByRequestId) if (runId === options.runId) this._agentToolRunsByRequestId.delete(reqId);
1368
1444
  this._agentToolLastErrors.delete(options.runId);
1369
1445
  this._agentToolPreTurnAssistantIds.delete(options.runId);
1370
1446
  this._closeAgentToolTailers(options.runId);
@@ -2045,6 +2121,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2045
2121
  async _replayTerminalOnAck(connection, requestId) {
2046
2122
  const pending = await this._pendingChatTerminal();
2047
2123
  if (!pending || pending.requestId !== requestId) return false;
2124
+ if (!this._resumableStream.replayErroredChunksByRequestId(connection, pending.requestId)) return true;
2048
2125
  sendIfOpen(connection, JSON.stringify({
2049
2126
  body: pending.body,
2050
2127
  done: true,
@@ -2135,7 +2212,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2135
2212
  createdAt: ctx.createdAt
2136
2213
  }) ?? {};
2137
2214
  if (streamStillActive && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
2138
- if (streamStillActive) this._resumableStream.complete(streamId);
2215
+ if (streamStillActive) {
2216
+ this._resumableStream.complete(streamId);
2217
+ this._ensureStreamCleanupScheduled();
2218
+ }
2139
2219
  const leaf = this.messages.length > 0 ? this.messages[this.messages.length - 1] : void 0;
2140
2220
  const lostPartialUserId = recoverySnapshot?.continuation === false && recoverySnapshot.latestUserMessageId && leaf?.role === "user" && leaf.id === recoverySnapshot.latestUserMessageId ? recoverySnapshot.latestUserMessageId : void 0;
2141
2221
  const targetId = shouldRetryPreStream || lostPartialUserId !== void 0 ? void 0 : this._findLastAssistantMessage()?.id;
@@ -2325,9 +2405,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2325
2405
  * Exactly-once terminalization here rests SOLELY on the
2326
2406
  * `stored?.status === "exhausted"` re-entry guard below — unlike
2327
2407
  * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer
2328
- * to short-circuit a duplicate alarm earlier. The sealed incident is
2329
- * re-persisted even when the record was found missing, so a swept record is
2330
- * re-armed for the guard on the next alarm.
2408
+ * to short-circuit a duplicate alarm earlier. The incident read/write are
2409
+ * best-effort because they back only that guard, not the terminal UX: a
2410
+ * failed read synthesizes the incident and a failed seal write costs at most
2411
+ * a re-delivered banner on a duplicate alarm.
2331
2412
  *
2332
2413
  * Two residual at-least-once edges, both deliberately accepted as "deliver a
2333
2414
  * second banner" ≫ "silently drop the turn":
@@ -2341,7 +2422,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
2341
2422
  async _exhaustRecoveryAfterStableTimeout(callback, data) {
2342
2423
  const config = this._resolveChatRecoveryConfig();
2343
2424
  const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
2344
- const stored = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
2425
+ let stored = null;
2426
+ if (incidentKey) try {
2427
+ stored = await this.ctx.storage.get(incidentKey) ?? null;
2428
+ } catch (readError) {
2429
+ console.error("[AIChatAgent] failed to read recovery incident during give-up; synthesizing", readError);
2430
+ }
2345
2431
  if (stored?.status === "exhausted") return;
2346
2432
  const rootRequestId = data?.originalRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
2347
2433
  const incident = stored ? {
@@ -2360,13 +2446,17 @@ var AIChatAgent = class AIChatAgent extends Agent {
2360
2446
  lastAttemptAt: Date.now(),
2361
2447
  reason: "stable_timeout"
2362
2448
  };
2363
- if (incidentKey) await this.ctx.storage.put(incidentKey, incident);
2364
2449
  const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
2365
2450
  const partial = streamId ? this._getPartialStreamText(streamId) : {
2366
2451
  text: "",
2367
2452
  parts: []
2368
2453
  };
2369
2454
  await this._exhaustChatRecovery(incident, config, partial, streamId, incident.firstSeenAt);
2455
+ if (incidentKey) try {
2456
+ await this.ctx.storage.put(incidentKey, incident);
2457
+ } catch (writeError) {
2458
+ console.error("[AIChatAgent] failed to persist sealed recovery incident during give-up", writeError);
2459
+ }
2370
2460
  }
2371
2461
  _shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
2372
2462
  if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
@@ -3181,7 +3271,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3181
3271
  return { status: "completed" };
3182
3272
  }
3183
3273
  const message = this._createStreamingAssistantMessage(continuation);
3184
- const streamId = this._startStream(id, { messageId: message.id });
3274
+ const streamId = this._startStream(id, {
3275
+ messageId: message.id,
3276
+ continuation
3277
+ });
3185
3278
  const reader = response.body.getReader();
3186
3279
  this._streamingMessage = message;
3187
3280
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");