@cloudflare/ai-chat 0.12.1 → 0.12.2

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
@@ -1531,28 +1531,6 @@ declare class AIChatAgent<
1531
1531
  */
1532
1532
  private _cf_sealMemoryLimitedRecovery;
1533
1533
  private _exhaustRecoveryAfterStableTimeout;
1534
- /**
1535
- * Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with
1536
- * `@cloudflare/think`'s `_handleRecoveryOom`: invoked from the narrow OOM-only
1537
- * `catch` in `_chatRecoveryContinue` / `_chatRecoveryRetry`, i.e. for an OOM
1538
- * that is *thrown* out of a recovery turn (e.g. storage/SQL ops rejecting with
1539
- * the memory-limit-reset message after an isolate reset). An OOM caught inside
1540
- * `continueLastTurn` that surfaces as a returned `error` result is NOT routed
1541
- * here — that turn was already terminalized, so re-driving it would be wasteful
1542
- * and risk a second terminal signal.
1543
- *
1544
- * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
1545
- * which seals once `oomAttempts` exceeds the budget, running before the
1546
- * memory-heavy turn in the low-memory window where writes succeed. This method
1547
- * persists `oomAttempts` (small writes) for the begin path to act on, and
1548
- * schedules a delayed re-run while under budget.
1549
- *
1550
- * Returns `true` when the error was an OOM and this method owns the outcome
1551
- * (rescheduled a delayed re-run while under budget, or terminalized with
1552
- * `reason="out_of_memory"` once over budget / untrackable / bookkeeping
1553
- * failed), `false` for non-OOM errors so the caller proceeds normally.
1554
- */
1555
- private _handleRecoveryOom;
1556
1534
  private _shouldRetryRecoveredPreStreamTurn;
1557
1535
  _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
1558
1536
  protected _chatRecoveryRetryDetached(
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { MessageType } from "./types.js";
2
2
  import { autoTransformMessages } from "./ai-chat-v5-migration.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
- import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, isDurableObjectMemoryLimitReset, isPlatformTransientError } from "agents";
4
+ import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, isPlatformTransientError } from "agents";
5
5
  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, applyLateToolInput, awaitWithDeadline, buildChatRecoveringFrame, chatRecoveryBackoffSeconds, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, dispatchChatRecoveryToHandoff, drainInteractionApplies, hasIncompleteToolBatch, interceptAgentToolBroadcast, isDurableObjectResetError, isPositionlessAgentToolChunk, isReplayChunk, iterateWithStallWatchdog, lateToolInputForwardChunks, listActiveChatRecoveryIncidents, originMessageIds, parseProtocolMessage, partAwaitsClientInteraction, partialHasSettledToolResults, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, runChatRecoveryExhaustion, sendIfOpen, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, withOriginMessageIds, wrapChatFiberSnapshot } from "agents/chat";
6
6
  import { Sessions } from "agents/sessions";
7
7
  import { nanoid } from "nanoid";
@@ -96,7 +96,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
96
96
  */
97
97
  _dispatchChatRecovery(callback, data, detached) {
98
98
  return dispatchChatRecoveryToHandoff({
99
- detached,
99
+ detached: (onTurnStarted) => this._chatRecoveryEngine().runRecoveryAttempt({
100
+ callback,
101
+ data,
102
+ run: () => detached(onTurnStarted)
103
+ }),
100
104
  track: (turn) => this.lifecycle.trackAlarmWork(turn),
101
105
  redefer: (dedupeKey) => this._enqueueChatRecovery(callback, data ?? {}, "redefer", CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, dedupeKey),
102
106
  onDetachedError: (error) => console.error(`[AIChatAgent] ${callback} dispatch failed`, error)
@@ -2763,6 +2767,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2763
2767
  readProgress: () => this._chatRecoveryProgressMarker(),
2764
2768
  isAwaitingClientInteraction: () => this.hasPendingClientInteraction(),
2765
2769
  putIncident: (key, incident) => this.ctx.storage.put(key, incident),
2770
+ syncStorage: () => this.ctx.storage.sync(),
2766
2771
  deleteIncident: async (key) => {
2767
2772
  await this.ctx.storage.delete(key);
2768
2773
  },
@@ -3036,9 +3041,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
3036
3041
  const result = await this.continueLastTurn();
3037
3042
  if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
3038
3043
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
3039
- } catch (error) {
3040
- if (await this._handleRecoveryOom("_chatRecoveryContinue", data, error)) return;
3041
- throw error;
3042
3044
  } finally {
3043
3045
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
3044
3046
  await this._reconcileOwnStaleAgentToolChildRuns();
@@ -3076,7 +3078,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3076
3078
  requestId: input.requestId,
3077
3079
  recoveryRootRequestId,
3078
3080
  latestUserMessageId,
3079
- recoveryKind
3081
+ recoveryKind,
3082
+ trigger: "stalled"
3080
3083
  });
3081
3084
  const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
3082
3085
  if (exhausted) {
@@ -3287,48 +3290,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
3287
3290
  reason: "stable_timeout"
3288
3291
  });
3289
3292
  }
3290
- /**
3291
- * Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with
3292
- * `@cloudflare/think`'s `_handleRecoveryOom`: invoked from the narrow OOM-only
3293
- * `catch` in `_chatRecoveryContinue` / `_chatRecoveryRetry`, i.e. for an OOM
3294
- * that is *thrown* out of a recovery turn (e.g. storage/SQL ops rejecting with
3295
- * the memory-limit-reset message after an isolate reset). An OOM caught inside
3296
- * `continueLastTurn` that surfaces as a returned `error` result is NOT routed
3297
- * here — that turn was already terminalized, so re-driving it would be wasteful
3298
- * and risk a second terminal signal.
3299
- *
3300
- * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
3301
- * which seals once `oomAttempts` exceeds the budget, running before the
3302
- * memory-heavy turn in the low-memory window where writes succeed. This method
3303
- * persists `oomAttempts` (small writes) for the begin path to act on, and
3304
- * schedules a delayed re-run while under budget.
3305
- *
3306
- * Returns `true` when the error was an OOM and this method owns the outcome
3307
- * (rescheduled a delayed re-run while under budget, or terminalized with
3308
- * `reason="out_of_memory"` once over budget / untrackable / bookkeeping
3309
- * failed), `false` for non-OOM errors so the caller proceeds normally.
3310
- */
3311
- async _handleRecoveryOom(callback, data, error) {
3312
- if (!isDurableObjectMemoryLimitReset(error)) return false;
3313
- let decision = "exhausted";
3314
- try {
3315
- decision = await this._chatRecoveryEngine().recordOomAndDecide({
3316
- incidentId: data?.incidentId,
3317
- callback,
3318
- data,
3319
- maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries
3320
- });
3321
- } catch (bookkeepingError) {
3322
- console.error("[AIChatAgent] failed to record OOM recovery attempt; terminalizing", bookkeepingError);
3323
- decision = "exhausted";
3324
- }
3325
- if (decision === "exhausted") await this._chatRecoveryEngine().exhaustRecoveryGiveUp({
3326
- callback,
3327
- data,
3328
- reason: "out_of_memory"
3329
- });
3330
- return true;
3331
- }
3332
3293
  _shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
3333
3294
  if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
3334
3295
  const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
@@ -3368,9 +3329,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
3368
3329
  const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
3369
3330
  if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
3370
3331
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
3371
- } catch (error) {
3372
- if (await this._handleRecoveryOom("_chatRecoveryRetry", data, error)) return;
3373
- throw error;
3374
3332
  } finally {
3375
3333
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
3376
3334
  await this._reconcileOwnStaleAgentToolChildRuns();