@cloudflare/ai-chat 0.8.3 → 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/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(requestId: string): string;
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: AIChatAgent does not yet replay this on connect (no idle-connect
804
- * hydration; tracked in #1645) — this is the live signal only.
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(
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ 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;
17
18
  const KV_DELETE_MAX_KEYS = 128;
18
19
  const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
@@ -203,6 +204,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
203
204
  this._completeSkippedRequest(connection, chatMessageId);
204
205
  return;
205
206
  }
207
+ await this._clearChatTerminal();
206
208
  const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
207
209
  try {
208
210
  this._broadcastChatMessage({
@@ -290,6 +292,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
290
292
  if (data.type === "cf_agent_chat_clear") {
291
293
  this.resetTurnState();
292
294
  this.sql`delete from cf_ai_chat_agent_messages`;
295
+ await this._clearChatTerminal();
293
296
  this._resumableStream.clearAll();
294
297
  this._pendingResumeConnections.clear();
295
298
  this._lastClientTools = void 0;
@@ -315,7 +318,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
315
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" }));
316
319
  else this._notifyStreamResuming(connection);
317
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);
318
- 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" }));
319
322
  return;
320
323
  }
321
324
  if (data.type === "cf_agent_stream_resume_ack") {
@@ -323,7 +326,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
323
326
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
324
327
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
325
328
  if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
326
- } 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({
327
330
  body: "",
328
331
  done: true,
329
332
  id: data.id,
@@ -449,8 +452,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
449
452
  return this._resumableStream?.activeRequestId ?? null;
450
453
  }
451
454
  /** @internal Delegate to _resumableStream */
452
- _startStream(requestId) {
453
- const streamId = this._resumableStream.start(requestId);
455
+ _startStream(requestId, options = {}) {
456
+ const streamId = this._resumableStream.start(requestId, options);
454
457
  if (this._continuation.pending?.requestId === requestId) {
455
458
  this._continuation.activatePending();
456
459
  this._flushAwaitingStreamStartConnections();
@@ -535,7 +538,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
535
538
  } catch {}
536
539
  if (message.parts.length > 0) {
537
540
  if (message.id === fallbackId) {
538
- for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") {
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") {
539
544
  message.id = this.messages[i].id;
540
545
  break;
541
546
  }
@@ -543,7 +548,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
543
548
  const existingIdx = this.messages.findIndex((m) => m.id === message.id);
544
549
  if (existingIdx >= 0) {
545
550
  const existing = this.messages[existingIdx];
546
- message.parts = [...existing.parts, ...message.parts];
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];
547
554
  if (existing.metadata) message.metadata = message.metadata ? {
548
555
  ...existing.metadata,
549
556
  ...message.metadata
@@ -926,6 +933,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
926
933
  await this.keepAliveWhile(async () => {
927
934
  while (this._pendingChatResponseResults.length > 0) {
928
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.");
929
938
  try {
930
939
  await this.onChatResponse(chatResult);
931
940
  } catch (hookError) {
@@ -1980,6 +1989,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1980
1989
  } catch (error) {
1981
1990
  console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error);
1982
1991
  }
1992
+ await this._recordChatTerminal(incident.requestId, config.terminalMessage);
1983
1993
  this._broadcastChatMessage({
1984
1994
  body: config.terminalMessage,
1985
1995
  done: true,
@@ -1990,11 +2000,66 @@ var AIChatAgent = class AIChatAgent extends Agent {
1990
2000
  await this._setChatRecovering(false);
1991
2001
  }
1992
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
+ /**
1993
2058
  * Set or clear the live "recovering…" status (#1620). Persists a durable
1994
2059
  * record (so set/clear stay consistent across the isolates a recovery spans)
1995
2060
  * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
1996
- * NOTE: AIChatAgent does not yet replay this on connect (no idle-connect
1997
- * hydration; tracked in #1645) — this is the live signal only.
2061
+ * NOTE: the live "recovering…" signal is still not replayed on connect — only
2062
+ * the terminal outcome is (#1645, via the resume handshake).
1998
2063
  */
1999
2064
  async _setChatRecovering(active, requestId) {
2000
2065
  const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
@@ -2037,7 +2102,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
2037
2102
  };
2038
2103
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2039
2104
  const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(recoverySnapshot, streamId ?? "", partial);
2040
- const recoveryKind = shouldRetryPreStream ? "retry" : "continue";
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";
2041
2108
  const recoveryRootRequestId = recoverySnapshot?.recoveryRootRequestId ?? requestId;
2042
2109
  const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
2043
2110
  requestId,
@@ -2069,7 +2136,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
2069
2136
  }) ?? {};
2070
2137
  if (streamStillActive && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
2071
2138
  if (streamStillActive) this._resumableStream.complete(streamId);
2072
- const targetId = shouldRetryPreStream ? void 0 : this._findLastAssistantMessage()?.id;
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;
2073
2142
  if (shouldRetryPreStream && options.continue !== false) {
2074
2143
  await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
2075
2144
  this._emit("chat:recovery:scheduled", {
@@ -2086,6 +2155,22 @@ var AIChatAgent = class AIChatAgent extends Agent {
2086
2155
  lastBody: recoverySnapshot.lastBody ?? null,
2087
2156
  lastClientTools: recoverySnapshot.lastClientTools ?? null
2088
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 });
2089
2174
  } else if (options.continue !== false) {
2090
2175
  await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
2091
2176
  this._emit("chat:recovery:scheduled", {
@@ -3095,9 +3180,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
3095
3180
  this._activateDeferredAutoContinuation();
3096
3181
  return { status: "completed" };
3097
3182
  }
3098
- const streamId = this._startStream(id);
3099
- const reader = response.body.getReader();
3100
3183
  const message = this._createStreamingAssistantMessage(continuation);
3184
+ const streamId = this._startStream(id, { messageId: message.id });
3185
+ const reader = response.body.getReader();
3101
3186
  this._streamingMessage = message;
3102
3187
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
3103
3188
  const streamCompleted = { value: false };