@cloudflare/ai-chat 0.9.0 → 0.9.1
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 +35 -0
- package/dist/index.js +75 -2
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1364,7 +1364,42 @@ declare class AIChatAgent<
|
|
|
1364
1364
|
* the first, so this needs a second independent sweep) — vanishingly
|
|
1365
1365
|
* unlikely.
|
|
1366
1366
|
*/
|
|
1367
|
+
/**
|
|
1368
|
+
* Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
|
|
1369
|
+
* back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
|
|
1370
|
+
*/
|
|
1371
|
+
protected _cf_recoveryAlarmCallbacks(): string[];
|
|
1372
|
+
/**
|
|
1373
|
+
* Seal any still-live recovery incident as an out-of-memory exhaustion when
|
|
1374
|
+
* the alarm circuit breaker trips at its strike budget (#1825). Runs at the
|
|
1375
|
+
* outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
|
|
1376
|
+
* and the sealed-incident write can land where mid-turn writes OOMed. Reuses
|
|
1377
|
+
* the shared give-up spine via the recovery engine.
|
|
1378
|
+
*/
|
|
1379
|
+
protected _cf_sealMemoryLimitedRecovery(): Promise<void>;
|
|
1367
1380
|
private _exhaustRecoveryAfterStableTimeout;
|
|
1381
|
+
/**
|
|
1382
|
+
* Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with
|
|
1383
|
+
* `@cloudflare/think`'s `_handleRecoveryOom`: invoked from the narrow OOM-only
|
|
1384
|
+
* `catch` in `_chatRecoveryContinue` / `_chatRecoveryRetry`, i.e. for an OOM
|
|
1385
|
+
* that is *thrown* out of a recovery turn (e.g. storage/SQL ops rejecting with
|
|
1386
|
+
* the memory-limit-reset message after an isolate reset). An OOM caught inside
|
|
1387
|
+
* `continueLastTurn` that surfaces as a returned `error` result is NOT routed
|
|
1388
|
+
* here — that turn was already terminalized, so re-driving it would be wasteful
|
|
1389
|
+
* and risk a second terminal signal.
|
|
1390
|
+
*
|
|
1391
|
+
* The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
|
|
1392
|
+
* which seals once `oomAttempts` exceeds the budget, running before the
|
|
1393
|
+
* memory-heavy turn in the low-memory window where writes succeed. This method
|
|
1394
|
+
* persists `oomAttempts` (small writes) for the begin path to act on, and
|
|
1395
|
+
* schedules a delayed re-run while under budget.
|
|
1396
|
+
*
|
|
1397
|
+
* Returns `true` when the error was an OOM and this method owns the outcome
|
|
1398
|
+
* (rescheduled a delayed re-run while under budget, or terminalized with
|
|
1399
|
+
* `reason="out_of_memory"` once over budget / untrackable / bookkeeping
|
|
1400
|
+
* failed), `false` for non-OOM errors so the caller proceeds normally.
|
|
1401
|
+
*/
|
|
1402
|
+
private _handleRecoveryOom;
|
|
1368
1403
|
private _shouldRetryRecoveredPreStreamTurn;
|
|
1369
1404
|
_chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
|
|
1370
1405
|
/**
|
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
|
-
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
4
|
-
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, STREAM_CLEANUP_DELAY_SECONDS, StreamProgressCreditThrottle, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyChunkToParts, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, bumpChatRecoveryProgress, chatRecoverySchedulePolicy, classifyAgentToolChildRecovery, cleanupStreamBuffers, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createToolsFromClientSchemas, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, isReplayChunk, iterateWithStallWatchdog, parseProtocolMessage, partAwaitsClientInteraction, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, sendIfOpen, setChatRecovering, shouldCreditStreamProgress, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
3
|
+
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, isDurableObjectMemoryLimitReset } from "agents";
|
|
4
|
+
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, STREAM_CLEANUP_DELAY_SECONDS, StreamProgressCreditThrottle, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyChunkToParts, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, bumpChatRecoveryProgress, chatRecoverySchedulePolicy, classifyAgentToolChildRecovery, cleanupStreamBuffers, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createToolsFromClientSchemas, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, isReplayChunk, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, parseProtocolMessage, partAwaitsClientInteraction, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, sendIfOpen, setChatRecovering, shouldCreditStreamProgress, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
5
5
|
import { nanoid } from "nanoid";
|
|
6
6
|
//#region src/index.ts
|
|
7
7
|
/**
|
|
@@ -2533,6 +2533,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2533
2533
|
this._applyRecoveredRequestContext(data);
|
|
2534
2534
|
const result = await this.continueLastTurn();
|
|
2535
2535
|
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
2536
|
+
} catch (error) {
|
|
2537
|
+
if (await this._handleRecoveryOom("_chatRecoveryContinue", data, error)) return;
|
|
2538
|
+
throw error;
|
|
2536
2539
|
} finally {
|
|
2537
2540
|
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
2538
2541
|
await this._reconcileOwnStaleAgentToolChildRuns();
|
|
@@ -2665,6 +2668,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2665
2668
|
* the first, so this needs a second independent sweep) — vanishingly
|
|
2666
2669
|
* unlikely.
|
|
2667
2670
|
*/
|
|
2671
|
+
/**
|
|
2672
|
+
* Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
|
|
2673
|
+
* back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
|
|
2674
|
+
*/
|
|
2675
|
+
_cf_recoveryAlarmCallbacks() {
|
|
2676
|
+
return ["_chatRecoveryContinue", "_chatRecoveryRetry"];
|
|
2677
|
+
}
|
|
2678
|
+
/**
|
|
2679
|
+
* Seal any still-live recovery incident as an out-of-memory exhaustion when
|
|
2680
|
+
* the alarm circuit breaker trips at its strike budget (#1825). Runs at the
|
|
2681
|
+
* outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
|
|
2682
|
+
* and the sealed-incident write can land where mid-turn writes OOMed. Reuses
|
|
2683
|
+
* the shared give-up spine via the recovery engine.
|
|
2684
|
+
*/
|
|
2685
|
+
async _cf_sealMemoryLimitedRecovery() {
|
|
2686
|
+
const active = await listActiveChatRecoveryIncidents(this.ctx.storage);
|
|
2687
|
+
for (const { incident } of active) {
|
|
2688
|
+
const callback = incident.recoveryKind === "retry" ? "_chatRecoveryRetry" : "_chatRecoveryContinue";
|
|
2689
|
+
await this._chatRecoveryEngine().exhaustRecoveryGiveUp({
|
|
2690
|
+
callback,
|
|
2691
|
+
data: { incidentId: incident.incidentId },
|
|
2692
|
+
reason: "out_of_memory"
|
|
2693
|
+
});
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2668
2696
|
_exhaustRecoveryAfterStableTimeout(callback, data) {
|
|
2669
2697
|
return this._chatRecoveryEngine().exhaustRecoveryGiveUp({
|
|
2670
2698
|
callback,
|
|
@@ -2672,6 +2700,48 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2672
2700
|
reason: "stable_timeout"
|
|
2673
2701
|
});
|
|
2674
2702
|
}
|
|
2703
|
+
/**
|
|
2704
|
+
* Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with
|
|
2705
|
+
* `@cloudflare/think`'s `_handleRecoveryOom`: invoked from the narrow OOM-only
|
|
2706
|
+
* `catch` in `_chatRecoveryContinue` / `_chatRecoveryRetry`, i.e. for an OOM
|
|
2707
|
+
* that is *thrown* out of a recovery turn (e.g. storage/SQL ops rejecting with
|
|
2708
|
+
* the memory-limit-reset message after an isolate reset). An OOM caught inside
|
|
2709
|
+
* `continueLastTurn` that surfaces as a returned `error` result is NOT routed
|
|
2710
|
+
* here — that turn was already terminalized, so re-driving it would be wasteful
|
|
2711
|
+
* and risk a second terminal signal.
|
|
2712
|
+
*
|
|
2713
|
+
* The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
|
|
2714
|
+
* which seals once `oomAttempts` exceeds the budget, running before the
|
|
2715
|
+
* memory-heavy turn in the low-memory window where writes succeed. This method
|
|
2716
|
+
* persists `oomAttempts` (small writes) for the begin path to act on, and
|
|
2717
|
+
* schedules a delayed re-run while under budget.
|
|
2718
|
+
*
|
|
2719
|
+
* Returns `true` when the error was an OOM and this method owns the outcome
|
|
2720
|
+
* (rescheduled a delayed re-run while under budget, or terminalized with
|
|
2721
|
+
* `reason="out_of_memory"` once over budget / untrackable / bookkeeping
|
|
2722
|
+
* failed), `false` for non-OOM errors so the caller proceeds normally.
|
|
2723
|
+
*/
|
|
2724
|
+
async _handleRecoveryOom(callback, data, error) {
|
|
2725
|
+
if (!isDurableObjectMemoryLimitReset(error)) return false;
|
|
2726
|
+
let decision = "exhausted";
|
|
2727
|
+
try {
|
|
2728
|
+
decision = await this._chatRecoveryEngine().recordOomAndDecide({
|
|
2729
|
+
incidentId: data?.incidentId,
|
|
2730
|
+
callback,
|
|
2731
|
+
data,
|
|
2732
|
+
maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries
|
|
2733
|
+
});
|
|
2734
|
+
} catch (bookkeepingError) {
|
|
2735
|
+
console.error("[AIChatAgent] failed to record OOM recovery attempt; terminalizing", bookkeepingError);
|
|
2736
|
+
decision = "exhausted";
|
|
2737
|
+
}
|
|
2738
|
+
if (decision === "exhausted") await this._chatRecoveryEngine().exhaustRecoveryGiveUp({
|
|
2739
|
+
callback,
|
|
2740
|
+
data,
|
|
2741
|
+
reason: "out_of_memory"
|
|
2742
|
+
});
|
|
2743
|
+
return true;
|
|
2744
|
+
}
|
|
2675
2745
|
_shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
|
|
2676
2746
|
if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
|
|
2677
2747
|
const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
|
|
@@ -2704,6 +2774,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2704
2774
|
this._applyRecoveredRequestContext(data);
|
|
2705
2775
|
const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
|
|
2706
2776
|
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
2777
|
+
} catch (error) {
|
|
2778
|
+
if (await this._handleRecoveryOom("_chatRecoveryRetry", data, error)) return;
|
|
2779
|
+
throw error;
|
|
2707
2780
|
} finally {
|
|
2708
2781
|
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
2709
2782
|
await this._reconcileOwnStaleAgentToolChildRuns();
|