@cloudflare/ai-chat 0.12.1 → 0.12.3
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/README.md +3 -3
- package/dist/index.d.ts +29 -22
- package/dist/index.js +151 -78
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
28
28
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
29
29
|
|
|
30
30
|
const result = streamText({
|
|
31
|
-
model: workersai("@cf/
|
|
31
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
32
32
|
messages: await convertToModelMessages(this.messages)
|
|
33
33
|
});
|
|
34
34
|
|
|
@@ -116,7 +116,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
116
116
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
117
117
|
|
|
118
118
|
const result = streamText({
|
|
119
|
-
model: workersai("@cf/
|
|
119
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
120
120
|
messages: await convertToModelMessages(this.messages),
|
|
121
121
|
tools: {
|
|
122
122
|
getWeather: tool({
|
|
@@ -417,7 +417,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
417
417
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
418
418
|
|
|
419
419
|
const result = streamText({
|
|
420
|
-
model: workersai("@cf/
|
|
420
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
421
421
|
messages: pruneMessages({
|
|
422
422
|
messages: await convertToModelMessages(this.messages),
|
|
423
423
|
reasoning: "before-last-message",
|
package/dist/index.d.ts
CHANGED
|
@@ -113,6 +113,11 @@ declare class AIChatAgent<
|
|
|
113
113
|
> extends Agent<Env, State, Props> {
|
|
114
114
|
#private;
|
|
115
115
|
private _activeChatRecoveryRootRequestId;
|
|
116
|
+
/**
|
|
117
|
+
* The stop signal of each running recovery attempt, keyed by the original
|
|
118
|
+
* request id a client cancels it with.
|
|
119
|
+
*/
|
|
120
|
+
private readonly _recoveryAttemptStops;
|
|
116
121
|
/**
|
|
117
122
|
* The originating user message ids of the active recovery chain (#2280),
|
|
118
123
|
* carried in the recovery payload because the successor turn runs under a
|
|
@@ -921,6 +926,12 @@ declare class AIChatAgent<
|
|
|
921
926
|
*/
|
|
922
927
|
private _hasIncompleteToolBatch;
|
|
923
928
|
private _fireAutoContinuation;
|
|
929
|
+
/**
|
|
930
|
+
* Report a chat request whose turn failed before it streamed: an error
|
|
931
|
+
* frame for the request and a durable terminal record, so a client that
|
|
932
|
+
* reconnects learns the outcome too.
|
|
933
|
+
*/
|
|
934
|
+
private _reportTurnFailure;
|
|
924
935
|
/**
|
|
925
936
|
* Report an auto-continuation that failed before it produced a response,
|
|
926
937
|
* the way a stream error is reported: an error frame, a durable terminal
|
|
@@ -1420,6 +1431,15 @@ declare class AIChatAgent<
|
|
|
1420
1431
|
data?: ChatRecoveryContinueData,
|
|
1421
1432
|
onTurnStarted?: () => void
|
|
1422
1433
|
): Promise<void>;
|
|
1434
|
+
/** Register a running recovery attempt so a cancel by `rootRequestId` stops it. */
|
|
1435
|
+
private _beginRecoveryAttempt;
|
|
1436
|
+
private _endRecoveryAttempt;
|
|
1437
|
+
/**
|
|
1438
|
+
* Whether a client stopped this attempt. The cancel already marked the
|
|
1439
|
+
* incident when it was still scheduled; record it here otherwise, so the
|
|
1440
|
+
* attempt's own outcome does not overwrite the user's stop.
|
|
1441
|
+
*/
|
|
1442
|
+
private _recoveryAttemptStopped;
|
|
1423
1443
|
private _applyRecoveredRequestContext;
|
|
1424
1444
|
/**
|
|
1425
1445
|
* Route a live stream stall (the {@link chatStreamStallTimeoutMs} watchdog
|
|
@@ -1531,28 +1551,6 @@ declare class AIChatAgent<
|
|
|
1531
1551
|
*/
|
|
1532
1552
|
private _cf_sealMemoryLimitedRecovery;
|
|
1533
1553
|
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
1554
|
private _shouldRetryRecoveredPreStreamTurn;
|
|
1557
1555
|
_chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
|
|
1558
1556
|
protected _chatRecoveryRetryDetached(
|
|
@@ -1651,6 +1649,11 @@ declare class AIChatAgent<
|
|
|
1651
1649
|
* no-op), false if no matching part was found
|
|
1652
1650
|
*/
|
|
1653
1651
|
private _findAndUpdateToolPart;
|
|
1652
|
+
/**
|
|
1653
|
+
* {@link _findAndUpdateToolPart}, reporting whether the update changed the
|
|
1654
|
+
* part, was an idempotent no-op, or found no part to update.
|
|
1655
|
+
*/
|
|
1656
|
+
private _updateToolPart;
|
|
1654
1657
|
/**
|
|
1655
1658
|
* Returns true if `applied` is the same reference as `original`, or if
|
|
1656
1659
|
* the two have identical state-relevant fields. Used by
|
|
@@ -1701,6 +1704,8 @@ declare class AIChatAgent<
|
|
|
1701
1704
|
* @returns true if the result was applied, false if the message was not found
|
|
1702
1705
|
*/
|
|
1703
1706
|
private _applyToolResult;
|
|
1707
|
+
/** {@link _applyToolResult}, reporting what the apply did to the part. */
|
|
1708
|
+
private _settleToolResult;
|
|
1704
1709
|
private _streamSSEReply;
|
|
1705
1710
|
private _sendPlaintextReply;
|
|
1706
1711
|
/**
|
|
@@ -1716,6 +1721,8 @@ declare class AIChatAgent<
|
|
|
1716
1721
|
* @returns true if the approval was applied, false if the message was not found
|
|
1717
1722
|
*/
|
|
1718
1723
|
private _applyToolApproval;
|
|
1724
|
+
/** {@link _applyToolApproval}, reporting what the apply did to the part. */
|
|
1725
|
+
private _settleToolApproval;
|
|
1719
1726
|
private _reply;
|
|
1720
1727
|
/**
|
|
1721
1728
|
* When the DO is destroyed, cancel all pending requests and clean up resources
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
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,
|
|
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";
|
|
4
|
+
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, isPlatformTransientError } from "agents";
|
|
5
|
+
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_RECOVERY_CANCELLED_REASON, 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";
|
|
8
8
|
//#region src/index.ts
|
|
@@ -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)
|
|
@@ -283,6 +287,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
283
287
|
}
|
|
284
288
|
constructor(ctx, env) {
|
|
285
289
|
super(ctx, env);
|
|
290
|
+
this._recoveryAttemptStops = /* @__PURE__ */ new Map();
|
|
286
291
|
this._chatRecoveryOriginIdsScope = new AsyncLocalStorage();
|
|
287
292
|
this.sessions = new Sessions();
|
|
288
293
|
this.hydrationByteBudget = 32 * 1024 * 1024;
|
|
@@ -412,6 +417,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
412
417
|
const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
413
418
|
const epoch = this._turnQueue.generation;
|
|
414
419
|
const requestOriginIds = originMessageIds(messages);
|
|
420
|
+
const storedAtAdmission = requestTrigger === "regenerate-message" ? new Set(this.messages.map((message) => message.id)) : null;
|
|
415
421
|
if (requestOriginIds) this._requestOriginMessageIds.set(chatMessageId, requestOriginIds);
|
|
416
422
|
const concurrencyDecision = this._getSubmitConcurrencyDecision(requestTrigger);
|
|
417
423
|
if (concurrencyDecision.action === "drop") {
|
|
@@ -426,6 +432,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
426
432
|
"cloudflare.agents.turn.trigger": requestTrigger
|
|
427
433
|
}, () => this._clearChatTerminal());
|
|
428
434
|
this._preStream.begin(chatMessageId);
|
|
435
|
+
const abortSignal = this._abortRegistry.getSignal(chatMessageId);
|
|
429
436
|
try {
|
|
430
437
|
const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
|
|
431
438
|
try {
|
|
@@ -438,7 +445,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
438
445
|
messages: transformedMessages,
|
|
439
446
|
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
440
447
|
}, [connection.id]);
|
|
441
|
-
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows:
|
|
448
|
+
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: requestTrigger !== "regenerate-message" });
|
|
442
449
|
if (concurrencyDecision.strategy === "merge") await this._mergeQueuedUserMessages(epoch);
|
|
443
450
|
});
|
|
444
451
|
} finally {
|
|
@@ -477,7 +484,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
477
484
|
return;
|
|
478
485
|
}
|
|
479
486
|
}
|
|
480
|
-
await withAgentSpan(this, "prepare_chat_context", "turn", {
|
|
487
|
+
if (await withAgentSpan(this, "prepare_chat_context", "turn", {
|
|
481
488
|
"cloudflare.agents.component": "ai_chat",
|
|
482
489
|
"cloudflare.agents.turn.request_id": chatMessageId,
|
|
483
490
|
"cloudflare.agents.turn.trigger": requestTrigger,
|
|
@@ -488,10 +495,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
488
495
|
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
|
|
489
496
|
await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
|
|
490
497
|
}
|
|
498
|
+
if (abortSignal?.aborted) return true;
|
|
491
499
|
this._setRequestContext(requestClientTools, requestBody);
|
|
492
|
-
|
|
500
|
+
return false;
|
|
501
|
+
})) {
|
|
502
|
+
this._broadcastChatMessage({
|
|
503
|
+
body: "",
|
|
504
|
+
done: true,
|
|
505
|
+
id: chatMessageId,
|
|
506
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
507
|
+
outcome: "aborted"
|
|
508
|
+
});
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
if (storedAtAdmission) {
|
|
512
|
+
const keep = new Set(transformedMessages.map((message) => message.id));
|
|
513
|
+
const stale = this.messages.filter((message) => !keep.has(message.id));
|
|
514
|
+
if (stale.some((message) => message.role === "user" && !storedAtAdmission.has(message.id))) {
|
|
515
|
+
this._completeSkippedRequest(connection, chatMessageId);
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
if (stale.length > 0) await this.persistMessages(transformedMessages, [], { _deleteStaleRows: true });
|
|
519
|
+
}
|
|
493
520
|
this._emit("message:request");
|
|
494
|
-
const abortSignal = this._abortRegistry.getSignal(chatMessageId);
|
|
495
521
|
return this._tryCatchChat(async () => {
|
|
496
522
|
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
497
523
|
agent: this,
|
|
@@ -500,6 +526,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
500
526
|
email: void 0
|
|
501
527
|
}, async () => {
|
|
502
528
|
const chatTurnBody = async () => {
|
|
529
|
+
let replying = false;
|
|
503
530
|
try {
|
|
504
531
|
await withAgentSpan(this, "repair_interrupted_tools", "turn", {
|
|
505
532
|
"cloudflare.agents.component": "ai_chat",
|
|
@@ -521,7 +548,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
521
548
|
"cloudflare.agents.turn.trigger": requestTrigger,
|
|
522
549
|
"cloudflare.agents.turn.admission": "queue",
|
|
523
550
|
"cloudflare.agents.turn.generation": epoch
|
|
524
|
-
}, () => this._reply(chatMessageId, response, [connection.id], {
|
|
551
|
+
}, () => this._reply(chatMessageId, response, [connection.id], {
|
|
552
|
+
chatMessageId,
|
|
553
|
+
onStreamStart: () => {
|
|
554
|
+
replying = true;
|
|
555
|
+
}
|
|
556
|
+
}));
|
|
525
557
|
else {
|
|
526
558
|
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
527
559
|
this._broadcastChatMessage({
|
|
@@ -532,6 +564,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
532
564
|
outcome: "completed"
|
|
533
565
|
});
|
|
534
566
|
}
|
|
567
|
+
} catch (error) {
|
|
568
|
+
if (!replying && !abortSignal?.aborted && !isDurableObjectResetError(error)) await this._reportTurnFailure(chatMessageId, error);
|
|
569
|
+
throw error;
|
|
535
570
|
} finally {
|
|
536
571
|
this._abortRegistry.remove(chatMessageId);
|
|
537
572
|
this._settlePreStreamTurn(chatMessageId);
|
|
@@ -545,6 +580,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
545
580
|
onStale: () => this._completeSkippedRequest(connection, chatMessageId)
|
|
546
581
|
});
|
|
547
582
|
} finally {
|
|
583
|
+
this._abortRegistry.remove(chatMessageId);
|
|
548
584
|
this._settlePreStreamTurn(chatMessageId);
|
|
549
585
|
this._requestOriginMessageIds.delete(chatMessageId);
|
|
550
586
|
}
|
|
@@ -572,6 +608,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
572
608
|
}
|
|
573
609
|
if (event.type === "cancel") {
|
|
574
610
|
this._abortRegistry.cancel(event.id);
|
|
611
|
+
this._recoveryAttemptStops.get(event.id)?.abort();
|
|
575
612
|
await this._cancelScheduledRecovery(event.id);
|
|
576
613
|
this._emit("message:cancel", { requestId: event.id });
|
|
577
614
|
return;
|
|
@@ -595,9 +632,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
595
632
|
toolCallId,
|
|
596
633
|
toolName
|
|
597
634
|
});
|
|
598
|
-
this._enqueueInteractionApply(() =>
|
|
599
|
-
|
|
600
|
-
|
|
635
|
+
this._enqueueInteractionApply(async () => {
|
|
636
|
+
const outcome = await this._settleToolResult(toolCallId, toolName, output, overrideState, errorText);
|
|
637
|
+
if (autoContinue && outcome === "changed") this._scheduleAutoContinuation(connection, clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:");
|
|
638
|
+
return outcome !== "missing";
|
|
639
|
+
});
|
|
640
|
+
if (!autoContinue) this._rearmPendingAutoContinuationForBatch();
|
|
601
641
|
return;
|
|
602
642
|
}
|
|
603
643
|
if (event.type === "tool-approval") {
|
|
@@ -606,9 +646,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
606
646
|
toolCallId,
|
|
607
647
|
approved
|
|
608
648
|
});
|
|
609
|
-
this._enqueueInteractionApply(() =>
|
|
610
|
-
|
|
611
|
-
|
|
649
|
+
this._enqueueInteractionApply(async () => {
|
|
650
|
+
const outcome = await this._settleToolApproval(toolCallId, approved);
|
|
651
|
+
if (autoContinue && outcome === "changed") this._scheduleAutoContinuation(connection, this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:");
|
|
652
|
+
return outcome !== "missing";
|
|
653
|
+
});
|
|
654
|
+
if (!autoContinue) this._rearmPendingAutoContinuationForBatch();
|
|
612
655
|
return;
|
|
613
656
|
}
|
|
614
657
|
}
|
|
@@ -1221,7 +1264,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1221
1264
|
try {
|
|
1222
1265
|
return await fn();
|
|
1223
1266
|
} catch (e) {
|
|
1224
|
-
|
|
1267
|
+
await this.onError(e);
|
|
1268
|
+
throw e;
|
|
1225
1269
|
}
|
|
1226
1270
|
}
|
|
1227
1271
|
isChatTurnActive() {
|
|
@@ -1730,6 +1774,23 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1730
1774
|
});
|
|
1731
1775
|
}
|
|
1732
1776
|
/**
|
|
1777
|
+
* Report a chat request whose turn failed before it streamed: an error
|
|
1778
|
+
* frame for the request and a durable terminal record, so a client that
|
|
1779
|
+
* reconnects learns the outcome too.
|
|
1780
|
+
*/
|
|
1781
|
+
async _reportTurnFailure(requestId, error) {
|
|
1782
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1783
|
+
this._broadcastChatMessage({
|
|
1784
|
+
body: errorMessage,
|
|
1785
|
+
done: true,
|
|
1786
|
+
error: true,
|
|
1787
|
+
id: requestId,
|
|
1788
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
1789
|
+
});
|
|
1790
|
+
this._emit("message:error", { error: errorMessage });
|
|
1791
|
+
await this._recordChatTerminal(requestId, errorMessage);
|
|
1792
|
+
}
|
|
1793
|
+
/**
|
|
1733
1794
|
* Report an auto-continuation that failed before it produced a response,
|
|
1734
1795
|
* the way a stream error is reported: an error frame, a durable terminal
|
|
1735
1796
|
* record, and `onChatResponse` with `status: "error"` for the assistant
|
|
@@ -2763,6 +2824,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2763
2824
|
readProgress: () => this._chatRecoveryProgressMarker(),
|
|
2764
2825
|
isAwaitingClientInteraction: () => this.hasPendingClientInteraction(),
|
|
2765
2826
|
putIncident: (key, incident) => this.ctx.storage.put(key, incident),
|
|
2827
|
+
syncStorage: () => this.ctx.storage.sync(),
|
|
2766
2828
|
deleteIncident: async (key) => {
|
|
2767
2829
|
await this.ctx.storage.delete(key);
|
|
2768
2830
|
},
|
|
@@ -3013,12 +3075,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3013
3075
|
if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
|
|
3014
3076
|
const previousRootRequestId = this._activeChatRecoveryRootRequestId;
|
|
3015
3077
|
this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
|
|
3078
|
+
const stop = this._beginRecoveryAttempt(data?.originalRequestId);
|
|
3016
3079
|
try {
|
|
3017
3080
|
const recoveryConfig = this._resolveChatRecoveryConfig();
|
|
3018
|
-
|
|
3081
|
+
const ready = await this.waitUntilStable({
|
|
3019
3082
|
timeout: recoveryConfig.stableTimeoutMs,
|
|
3020
3083
|
pendingInteraction: () => this.hasPendingClientInteraction()
|
|
3021
|
-
})
|
|
3084
|
+
});
|
|
3085
|
+
if (await this._recoveryAttemptStopped(stop, data?.incidentId)) return;
|
|
3086
|
+
if (!ready) {
|
|
3022
3087
|
if (await this._parkRecoveryForPendingInteraction(data)) return;
|
|
3023
3088
|
console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state");
|
|
3024
3089
|
if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
|
|
@@ -3026,24 +3091,42 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3026
3091
|
return;
|
|
3027
3092
|
}
|
|
3028
3093
|
const targetId = data?.targetAssistantId;
|
|
3029
|
-
if (targetId && this.
|
|
3094
|
+
if (targetId && this.messages.at(-1)?.id !== targetId) {
|
|
3030
3095
|
await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
|
|
3031
3096
|
return;
|
|
3032
3097
|
}
|
|
3033
3098
|
this._applyRecoveredRequestContext(data);
|
|
3034
3099
|
onTurnStarted?.();
|
|
3035
3100
|
this._takeRecoveryReschedule(data?.incidentId);
|
|
3036
|
-
const result = await this.continueLastTurn();
|
|
3101
|
+
const result = await this.continueLastTurn(void 0, { signal: stop.signal });
|
|
3102
|
+
if (await this._recoveryAttemptStopped(stop, data?.incidentId)) return;
|
|
3037
3103
|
if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
|
|
3038
3104
|
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
3105
|
} finally {
|
|
3106
|
+
this._endRecoveryAttempt(data?.originalRequestId, stop);
|
|
3043
3107
|
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
3044
3108
|
await this._reconcileOwnStaleAgentToolChildRuns();
|
|
3045
3109
|
}
|
|
3046
3110
|
}
|
|
3111
|
+
/** Register a running recovery attempt so a cancel by `rootRequestId` stops it. */
|
|
3112
|
+
_beginRecoveryAttempt(rootRequestId) {
|
|
3113
|
+
const stop = new AbortController();
|
|
3114
|
+
if (rootRequestId) this._recoveryAttemptStops.set(rootRequestId, stop);
|
|
3115
|
+
return stop;
|
|
3116
|
+
}
|
|
3117
|
+
_endRecoveryAttempt(rootRequestId, stop) {
|
|
3118
|
+
if (rootRequestId && this._recoveryAttemptStops.get(rootRequestId) === stop) this._recoveryAttemptStops.delete(rootRequestId);
|
|
3119
|
+
}
|
|
3120
|
+
/**
|
|
3121
|
+
* Whether a client stopped this attempt. The cancel already marked the
|
|
3122
|
+
* incident when it was still scheduled; record it here otherwise, so the
|
|
3123
|
+
* attempt's own outcome does not overwrite the user's stop.
|
|
3124
|
+
*/
|
|
3125
|
+
async _recoveryAttemptStopped(stop, incidentId) {
|
|
3126
|
+
if (!stop.signal.aborted) return false;
|
|
3127
|
+
if (!await this._chatRecoveryEngine().isRecoveryCancelled(incidentId)) await this._updateChatRecoveryIncident(incidentId, "skipped", CHAT_RECOVERY_CANCELLED_REASON);
|
|
3128
|
+
return true;
|
|
3129
|
+
}
|
|
3047
3130
|
_applyRecoveredRequestContext(data) {
|
|
3048
3131
|
if (!data) return;
|
|
3049
3132
|
if ("lastClientTools" in data) this._lastClientTools = data.lastClientTools ?? void 0;
|
|
@@ -3076,7 +3159,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3076
3159
|
requestId: input.requestId,
|
|
3077
3160
|
recoveryRootRequestId,
|
|
3078
3161
|
latestUserMessageId,
|
|
3079
|
-
recoveryKind
|
|
3162
|
+
recoveryKind,
|
|
3163
|
+
trigger: "stalled"
|
|
3080
3164
|
});
|
|
3081
3165
|
const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
|
|
3082
3166
|
if (exhausted) {
|
|
@@ -3287,48 +3371,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3287
3371
|
reason: "stable_timeout"
|
|
3288
3372
|
});
|
|
3289
3373
|
}
|
|
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
3374
|
_shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
|
|
3333
3375
|
if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
|
|
3334
3376
|
const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
|
|
@@ -3341,12 +3383,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3341
3383
|
if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
|
|
3342
3384
|
const previousRootRequestId = this._activeChatRecoveryRootRequestId;
|
|
3343
3385
|
this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
|
|
3386
|
+
const stop = this._beginRecoveryAttempt(data?.originalRequestId);
|
|
3344
3387
|
try {
|
|
3345
3388
|
const recoveryConfig = this._resolveChatRecoveryConfig();
|
|
3346
|
-
|
|
3389
|
+
const ready = await this.waitUntilStable({
|
|
3347
3390
|
timeout: recoveryConfig.stableTimeoutMs,
|
|
3348
3391
|
pendingInteraction: () => this.hasPendingClientInteraction()
|
|
3349
|
-
})
|
|
3392
|
+
});
|
|
3393
|
+
if (await this._recoveryAttemptStopped(stop, data?.incidentId)) return;
|
|
3394
|
+
if (!ready) {
|
|
3350
3395
|
if (await this._parkRecoveryForPendingInteraction(data)) return;
|
|
3351
3396
|
console.warn("[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state");
|
|
3352
3397
|
if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
|
|
@@ -3365,13 +3410,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3365
3410
|
this._applyRecoveredRequestContext(data);
|
|
3366
3411
|
onTurnStarted?.();
|
|
3367
3412
|
this._takeRecoveryReschedule(data?.incidentId);
|
|
3368
|
-
const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
|
|
3413
|
+
const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody, { signal: stop.signal });
|
|
3414
|
+
if (await this._recoveryAttemptStopped(stop, data?.incidentId)) return;
|
|
3369
3415
|
if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
|
|
3370
3416
|
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
3417
|
} finally {
|
|
3418
|
+
this._endRecoveryAttempt(data?.originalRequestId, stop);
|
|
3375
3419
|
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
3376
3420
|
await this._reconcileOwnStaleAgentToolChildRuns();
|
|
3377
3421
|
}
|
|
@@ -3574,6 +3618,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3574
3618
|
* no-op), false if no matching part was found
|
|
3575
3619
|
*/
|
|
3576
3620
|
async _findAndUpdateToolPart(toolCallId, callerName, matchStates, applyUpdate) {
|
|
3621
|
+
return await this._updateToolPart(toolCallId, callerName, matchStates, applyUpdate) !== "missing";
|
|
3622
|
+
}
|
|
3623
|
+
/**
|
|
3624
|
+
* {@link _findAndUpdateToolPart}, reporting whether the update changed the
|
|
3625
|
+
* part, was an idempotent no-op, or found no part to update.
|
|
3626
|
+
*/
|
|
3627
|
+
async _updateToolPart(toolCallId, callerName, matchStates, applyUpdate) {
|
|
3577
3628
|
let message;
|
|
3578
3629
|
if (this._streamingMessage) {
|
|
3579
3630
|
for (const part of this._streamingMessage.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) {
|
|
@@ -3588,7 +3639,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3588
3639
|
}
|
|
3589
3640
|
if (!message) {
|
|
3590
3641
|
console.warn(`[AIChatAgent] ${callerName}: Could not find message with toolCallId ${toolCallId} after retries`);
|
|
3591
|
-
return
|
|
3642
|
+
return "missing";
|
|
3592
3643
|
}
|
|
3593
3644
|
const isStreamingMessage = message === this._streamingMessage;
|
|
3594
3645
|
let wasFound = false;
|
|
@@ -3627,9 +3678,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3627
3678
|
}
|
|
3628
3679
|
if (!wasFound) {
|
|
3629
3680
|
console.warn(`[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join("|")})`);
|
|
3630
|
-
return
|
|
3681
|
+
return "missing";
|
|
3631
3682
|
}
|
|
3632
|
-
if (!hasRealChange) return
|
|
3683
|
+
if (!hasRealChange) return "unchanged";
|
|
3633
3684
|
if (isStreamingMessage) this._broadcastChatMessage({
|
|
3634
3685
|
type: MessageType.CF_AGENT_MESSAGE_UPDATED,
|
|
3635
3686
|
message
|
|
@@ -3641,7 +3692,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3641
3692
|
message: broadcastMessage
|
|
3642
3693
|
});
|
|
3643
3694
|
}
|
|
3644
|
-
return
|
|
3695
|
+
return "changed";
|
|
3645
3696
|
}
|
|
3646
3697
|
/**
|
|
3647
3698
|
* Returns true if `applied` is the same reference as `original`, or if
|
|
@@ -3706,7 +3757,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3706
3757
|
* @returns true if the result was applied, false if the message was not found
|
|
3707
3758
|
*/
|
|
3708
3759
|
async _applyToolResult(toolCallId, _toolName, output, overrideState, errorText) {
|
|
3709
|
-
return this.
|
|
3760
|
+
return await this._settleToolResult(toolCallId, _toolName, output, overrideState, errorText) !== "missing";
|
|
3761
|
+
}
|
|
3762
|
+
/** {@link _applyToolResult}, reporting what the apply did to the part. */
|
|
3763
|
+
async _settleToolResult(toolCallId, _toolName, output, overrideState, errorText) {
|
|
3764
|
+
return this._updateToolPart(toolCallId, "_applyToolResult", [
|
|
3710
3765
|
"input-available",
|
|
3711
3766
|
"approval-requested",
|
|
3712
3767
|
"approval-responded",
|
|
@@ -4084,13 +4139,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
4084
4139
|
* @returns true if the approval was applied, false if the message was not found
|
|
4085
4140
|
*/
|
|
4086
4141
|
async _applyToolApproval(toolCallId, approved) {
|
|
4142
|
+
return await this._settleToolApproval(toolCallId, approved) !== "missing";
|
|
4143
|
+
}
|
|
4144
|
+
/** {@link _applyToolApproval}, reporting what the apply did to the part. */
|
|
4145
|
+
async _settleToolApproval(toolCallId, approved) {
|
|
4087
4146
|
const update = toolApprovalUpdate(toolCallId, approved);
|
|
4088
|
-
return this.
|
|
4147
|
+
return this._updateToolPart(toolCallId, "_applyToolApproval", update.matchStates, update.apply);
|
|
4089
4148
|
}
|
|
4090
4149
|
async _reply(id, response, excludeBroadcastIds = [], options = {}) {
|
|
4091
4150
|
const { continuation = false, chatMessageId, onStreamStart } = options;
|
|
4092
4151
|
const abortSignal = chatMessageId ? this._abortRegistry.getExistingSignal(chatMessageId) : void 0;
|
|
4152
|
+
const turnGeneration = this._turnQueue.activeGeneration;
|
|
4153
|
+
const resetSinceTurnStarted = () => turnGeneration !== null && this._turnQueue.generation !== turnGeneration;
|
|
4093
4154
|
return this.keepAliveWhile(() => this._tryCatchChat(async () => {
|
|
4155
|
+
if (resetSinceTurnStarted()) {
|
|
4156
|
+
response.body?.cancel().catch(() => {});
|
|
4157
|
+
this._broadcastChatMessage({
|
|
4158
|
+
body: "",
|
|
4159
|
+
done: true,
|
|
4160
|
+
id,
|
|
4161
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
4162
|
+
outcome: "aborted",
|
|
4163
|
+
...continuation && { continuation: true }
|
|
4164
|
+
});
|
|
4165
|
+
return { status: "aborted" };
|
|
4166
|
+
}
|
|
4094
4167
|
if (!response.body) {
|
|
4095
4168
|
this._clearPendingAutoContinuation(true);
|
|
4096
4169
|
this._broadcastChatMessage({
|
|
@@ -4208,7 +4281,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
4208
4281
|
messageId: earlyPersistedId ?? message.id,
|
|
4209
4282
|
discard: !this._agentToolRunsByRequestId.get(id)
|
|
4210
4283
|
} : null;
|
|
4211
|
-
if (message.parts.length > 0 && !discardPartial) if (earlyPersistedId) {
|
|
4284
|
+
if (message.parts.length > 0 && !discardPartial && !resetSinceTurnStarted()) if (earlyPersistedId) {
|
|
4212
4285
|
const persistedMessage = {
|
|
4213
4286
|
...message,
|
|
4214
4287
|
id: earlyPersistedId
|