@cloudflare/ai-chat 0.12.2 → 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 -0
- package/dist/index.js +142 -27
- 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
|
|
@@ -1629,6 +1649,11 @@ declare class AIChatAgent<
|
|
|
1629
1649
|
* no-op), false if no matching part was found
|
|
1630
1650
|
*/
|
|
1631
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;
|
|
1632
1657
|
/**
|
|
1633
1658
|
* Returns true if `applied` is the same reference as `original`, or if
|
|
1634
1659
|
* the two have identical state-relevant fields. Used by
|
|
@@ -1679,6 +1704,8 @@ declare class AIChatAgent<
|
|
|
1679
1704
|
* @returns true if the result was applied, false if the message was not found
|
|
1680
1705
|
*/
|
|
1681
1706
|
private _applyToolResult;
|
|
1707
|
+
/** {@link _applyToolResult}, reporting what the apply did to the part. */
|
|
1708
|
+
private _settleToolResult;
|
|
1682
1709
|
private _streamSSEReply;
|
|
1683
1710
|
private _sendPlaintextReply;
|
|
1684
1711
|
/**
|
|
@@ -1694,6 +1721,8 @@ declare class AIChatAgent<
|
|
|
1694
1721
|
* @returns true if the approval was applied, false if the message was not found
|
|
1695
1722
|
*/
|
|
1696
1723
|
private _applyToolApproval;
|
|
1724
|
+
/** {@link _applyToolApproval}, reporting what the apply did to the part. */
|
|
1725
|
+
private _settleToolApproval;
|
|
1697
1726
|
private _reply;
|
|
1698
1727
|
/**
|
|
1699
1728
|
* When the DO is destroyed, cancel all pending requests and clean up resources
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { MessageType } from "./types.js";
|
|
|
2
2
|
import { autoTransformMessages } from "./ai-chat-v5-migration.js";
|
|
3
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
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_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";
|
|
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
|
|
@@ -287,6 +287,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
287
287
|
}
|
|
288
288
|
constructor(ctx, env) {
|
|
289
289
|
super(ctx, env);
|
|
290
|
+
this._recoveryAttemptStops = /* @__PURE__ */ new Map();
|
|
290
291
|
this._chatRecoveryOriginIdsScope = new AsyncLocalStorage();
|
|
291
292
|
this.sessions = new Sessions();
|
|
292
293
|
this.hydrationByteBudget = 32 * 1024 * 1024;
|
|
@@ -416,6 +417,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
416
417
|
const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
417
418
|
const epoch = this._turnQueue.generation;
|
|
418
419
|
const requestOriginIds = originMessageIds(messages);
|
|
420
|
+
const storedAtAdmission = requestTrigger === "regenerate-message" ? new Set(this.messages.map((message) => message.id)) : null;
|
|
419
421
|
if (requestOriginIds) this._requestOriginMessageIds.set(chatMessageId, requestOriginIds);
|
|
420
422
|
const concurrencyDecision = this._getSubmitConcurrencyDecision(requestTrigger);
|
|
421
423
|
if (concurrencyDecision.action === "drop") {
|
|
@@ -430,6 +432,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
430
432
|
"cloudflare.agents.turn.trigger": requestTrigger
|
|
431
433
|
}, () => this._clearChatTerminal());
|
|
432
434
|
this._preStream.begin(chatMessageId);
|
|
435
|
+
const abortSignal = this._abortRegistry.getSignal(chatMessageId);
|
|
433
436
|
try {
|
|
434
437
|
const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
|
|
435
438
|
try {
|
|
@@ -442,7 +445,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
442
445
|
messages: transformedMessages,
|
|
443
446
|
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
444
447
|
}, [connection.id]);
|
|
445
|
-
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows:
|
|
448
|
+
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: requestTrigger !== "regenerate-message" });
|
|
446
449
|
if (concurrencyDecision.strategy === "merge") await this._mergeQueuedUserMessages(epoch);
|
|
447
450
|
});
|
|
448
451
|
} finally {
|
|
@@ -481,7 +484,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
481
484
|
return;
|
|
482
485
|
}
|
|
483
486
|
}
|
|
484
|
-
await withAgentSpan(this, "prepare_chat_context", "turn", {
|
|
487
|
+
if (await withAgentSpan(this, "prepare_chat_context", "turn", {
|
|
485
488
|
"cloudflare.agents.component": "ai_chat",
|
|
486
489
|
"cloudflare.agents.turn.request_id": chatMessageId,
|
|
487
490
|
"cloudflare.agents.turn.trigger": requestTrigger,
|
|
@@ -492,10 +495,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
492
495
|
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
|
|
493
496
|
await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
|
|
494
497
|
}
|
|
498
|
+
if (abortSignal?.aborted) return true;
|
|
495
499
|
this._setRequestContext(requestClientTools, requestBody);
|
|
496
|
-
|
|
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
|
+
}
|
|
497
520
|
this._emit("message:request");
|
|
498
|
-
const abortSignal = this._abortRegistry.getSignal(chatMessageId);
|
|
499
521
|
return this._tryCatchChat(async () => {
|
|
500
522
|
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
501
523
|
agent: this,
|
|
@@ -504,6 +526,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
504
526
|
email: void 0
|
|
505
527
|
}, async () => {
|
|
506
528
|
const chatTurnBody = async () => {
|
|
529
|
+
let replying = false;
|
|
507
530
|
try {
|
|
508
531
|
await withAgentSpan(this, "repair_interrupted_tools", "turn", {
|
|
509
532
|
"cloudflare.agents.component": "ai_chat",
|
|
@@ -525,7 +548,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
525
548
|
"cloudflare.agents.turn.trigger": requestTrigger,
|
|
526
549
|
"cloudflare.agents.turn.admission": "queue",
|
|
527
550
|
"cloudflare.agents.turn.generation": epoch
|
|
528
|
-
}, () => this._reply(chatMessageId, response, [connection.id], {
|
|
551
|
+
}, () => this._reply(chatMessageId, response, [connection.id], {
|
|
552
|
+
chatMessageId,
|
|
553
|
+
onStreamStart: () => {
|
|
554
|
+
replying = true;
|
|
555
|
+
}
|
|
556
|
+
}));
|
|
529
557
|
else {
|
|
530
558
|
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
531
559
|
this._broadcastChatMessage({
|
|
@@ -536,6 +564,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
536
564
|
outcome: "completed"
|
|
537
565
|
});
|
|
538
566
|
}
|
|
567
|
+
} catch (error) {
|
|
568
|
+
if (!replying && !abortSignal?.aborted && !isDurableObjectResetError(error)) await this._reportTurnFailure(chatMessageId, error);
|
|
569
|
+
throw error;
|
|
539
570
|
} finally {
|
|
540
571
|
this._abortRegistry.remove(chatMessageId);
|
|
541
572
|
this._settlePreStreamTurn(chatMessageId);
|
|
@@ -549,6 +580,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
549
580
|
onStale: () => this._completeSkippedRequest(connection, chatMessageId)
|
|
550
581
|
});
|
|
551
582
|
} finally {
|
|
583
|
+
this._abortRegistry.remove(chatMessageId);
|
|
552
584
|
this._settlePreStreamTurn(chatMessageId);
|
|
553
585
|
this._requestOriginMessageIds.delete(chatMessageId);
|
|
554
586
|
}
|
|
@@ -576,6 +608,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
576
608
|
}
|
|
577
609
|
if (event.type === "cancel") {
|
|
578
610
|
this._abortRegistry.cancel(event.id);
|
|
611
|
+
this._recoveryAttemptStops.get(event.id)?.abort();
|
|
579
612
|
await this._cancelScheduledRecovery(event.id);
|
|
580
613
|
this._emit("message:cancel", { requestId: event.id });
|
|
581
614
|
return;
|
|
@@ -599,9 +632,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
599
632
|
toolCallId,
|
|
600
633
|
toolName
|
|
601
634
|
});
|
|
602
|
-
this._enqueueInteractionApply(() =>
|
|
603
|
-
|
|
604
|
-
|
|
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();
|
|
605
641
|
return;
|
|
606
642
|
}
|
|
607
643
|
if (event.type === "tool-approval") {
|
|
@@ -610,9 +646,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
610
646
|
toolCallId,
|
|
611
647
|
approved
|
|
612
648
|
});
|
|
613
|
-
this._enqueueInteractionApply(() =>
|
|
614
|
-
|
|
615
|
-
|
|
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();
|
|
616
655
|
return;
|
|
617
656
|
}
|
|
618
657
|
}
|
|
@@ -1225,7 +1264,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1225
1264
|
try {
|
|
1226
1265
|
return await fn();
|
|
1227
1266
|
} catch (e) {
|
|
1228
|
-
|
|
1267
|
+
await this.onError(e);
|
|
1268
|
+
throw e;
|
|
1229
1269
|
}
|
|
1230
1270
|
}
|
|
1231
1271
|
isChatTurnActive() {
|
|
@@ -1734,6 +1774,23 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1734
1774
|
});
|
|
1735
1775
|
}
|
|
1736
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
|
+
/**
|
|
1737
1794
|
* Report an auto-continuation that failed before it produced a response,
|
|
1738
1795
|
* the way a stream error is reported: an error frame, a durable terminal
|
|
1739
1796
|
* record, and `onChatResponse` with `status: "error"` for the assistant
|
|
@@ -3018,12 +3075,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3018
3075
|
if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
|
|
3019
3076
|
const previousRootRequestId = this._activeChatRecoveryRootRequestId;
|
|
3020
3077
|
this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
|
|
3078
|
+
const stop = this._beginRecoveryAttempt(data?.originalRequestId);
|
|
3021
3079
|
try {
|
|
3022
3080
|
const recoveryConfig = this._resolveChatRecoveryConfig();
|
|
3023
|
-
|
|
3081
|
+
const ready = await this.waitUntilStable({
|
|
3024
3082
|
timeout: recoveryConfig.stableTimeoutMs,
|
|
3025
3083
|
pendingInteraction: () => this.hasPendingClientInteraction()
|
|
3026
|
-
})
|
|
3084
|
+
});
|
|
3085
|
+
if (await this._recoveryAttemptStopped(stop, data?.incidentId)) return;
|
|
3086
|
+
if (!ready) {
|
|
3027
3087
|
if (await this._parkRecoveryForPendingInteraction(data)) return;
|
|
3028
3088
|
console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state");
|
|
3029
3089
|
if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
|
|
@@ -3031,21 +3091,42 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3031
3091
|
return;
|
|
3032
3092
|
}
|
|
3033
3093
|
const targetId = data?.targetAssistantId;
|
|
3034
|
-
if (targetId && this.
|
|
3094
|
+
if (targetId && this.messages.at(-1)?.id !== targetId) {
|
|
3035
3095
|
await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
|
|
3036
3096
|
return;
|
|
3037
3097
|
}
|
|
3038
3098
|
this._applyRecoveredRequestContext(data);
|
|
3039
3099
|
onTurnStarted?.();
|
|
3040
3100
|
this._takeRecoveryReschedule(data?.incidentId);
|
|
3041
|
-
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;
|
|
3042
3103
|
if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
|
|
3043
3104
|
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
3044
3105
|
} finally {
|
|
3106
|
+
this._endRecoveryAttempt(data?.originalRequestId, stop);
|
|
3045
3107
|
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
3046
3108
|
await this._reconcileOwnStaleAgentToolChildRuns();
|
|
3047
3109
|
}
|
|
3048
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
|
+
}
|
|
3049
3130
|
_applyRecoveredRequestContext(data) {
|
|
3050
3131
|
if (!data) return;
|
|
3051
3132
|
if ("lastClientTools" in data) this._lastClientTools = data.lastClientTools ?? void 0;
|
|
@@ -3302,12 +3383,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3302
3383
|
if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
|
|
3303
3384
|
const previousRootRequestId = this._activeChatRecoveryRootRequestId;
|
|
3304
3385
|
this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
|
|
3386
|
+
const stop = this._beginRecoveryAttempt(data?.originalRequestId);
|
|
3305
3387
|
try {
|
|
3306
3388
|
const recoveryConfig = this._resolveChatRecoveryConfig();
|
|
3307
|
-
|
|
3389
|
+
const ready = await this.waitUntilStable({
|
|
3308
3390
|
timeout: recoveryConfig.stableTimeoutMs,
|
|
3309
3391
|
pendingInteraction: () => this.hasPendingClientInteraction()
|
|
3310
|
-
})
|
|
3392
|
+
});
|
|
3393
|
+
if (await this._recoveryAttemptStopped(stop, data?.incidentId)) return;
|
|
3394
|
+
if (!ready) {
|
|
3311
3395
|
if (await this._parkRecoveryForPendingInteraction(data)) return;
|
|
3312
3396
|
console.warn("[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state");
|
|
3313
3397
|
if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
|
|
@@ -3326,10 +3410,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3326
3410
|
this._applyRecoveredRequestContext(data);
|
|
3327
3411
|
onTurnStarted?.();
|
|
3328
3412
|
this._takeRecoveryReschedule(data?.incidentId);
|
|
3329
|
-
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;
|
|
3330
3415
|
if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
|
|
3331
3416
|
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
3332
3417
|
} finally {
|
|
3418
|
+
this._endRecoveryAttempt(data?.originalRequestId, stop);
|
|
3333
3419
|
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
3334
3420
|
await this._reconcileOwnStaleAgentToolChildRuns();
|
|
3335
3421
|
}
|
|
@@ -3532,6 +3618,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3532
3618
|
* no-op), false if no matching part was found
|
|
3533
3619
|
*/
|
|
3534
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) {
|
|
3535
3628
|
let message;
|
|
3536
3629
|
if (this._streamingMessage) {
|
|
3537
3630
|
for (const part of this._streamingMessage.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) {
|
|
@@ -3546,7 +3639,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3546
3639
|
}
|
|
3547
3640
|
if (!message) {
|
|
3548
3641
|
console.warn(`[AIChatAgent] ${callerName}: Could not find message with toolCallId ${toolCallId} after retries`);
|
|
3549
|
-
return
|
|
3642
|
+
return "missing";
|
|
3550
3643
|
}
|
|
3551
3644
|
const isStreamingMessage = message === this._streamingMessage;
|
|
3552
3645
|
let wasFound = false;
|
|
@@ -3585,9 +3678,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3585
3678
|
}
|
|
3586
3679
|
if (!wasFound) {
|
|
3587
3680
|
console.warn(`[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join("|")})`);
|
|
3588
|
-
return
|
|
3681
|
+
return "missing";
|
|
3589
3682
|
}
|
|
3590
|
-
if (!hasRealChange) return
|
|
3683
|
+
if (!hasRealChange) return "unchanged";
|
|
3591
3684
|
if (isStreamingMessage) this._broadcastChatMessage({
|
|
3592
3685
|
type: MessageType.CF_AGENT_MESSAGE_UPDATED,
|
|
3593
3686
|
message
|
|
@@ -3599,7 +3692,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3599
3692
|
message: broadcastMessage
|
|
3600
3693
|
});
|
|
3601
3694
|
}
|
|
3602
|
-
return
|
|
3695
|
+
return "changed";
|
|
3603
3696
|
}
|
|
3604
3697
|
/**
|
|
3605
3698
|
* Returns true if `applied` is the same reference as `original`, or if
|
|
@@ -3664,7 +3757,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
3664
3757
|
* @returns true if the result was applied, false if the message was not found
|
|
3665
3758
|
*/
|
|
3666
3759
|
async _applyToolResult(toolCallId, _toolName, output, overrideState, errorText) {
|
|
3667
|
-
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", [
|
|
3668
3765
|
"input-available",
|
|
3669
3766
|
"approval-requested",
|
|
3670
3767
|
"approval-responded",
|
|
@@ -4042,13 +4139,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
4042
4139
|
* @returns true if the approval was applied, false if the message was not found
|
|
4043
4140
|
*/
|
|
4044
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) {
|
|
4045
4146
|
const update = toolApprovalUpdate(toolCallId, approved);
|
|
4046
|
-
return this.
|
|
4147
|
+
return this._updateToolPart(toolCallId, "_applyToolApproval", update.matchStates, update.apply);
|
|
4047
4148
|
}
|
|
4048
4149
|
async _reply(id, response, excludeBroadcastIds = [], options = {}) {
|
|
4049
4150
|
const { continuation = false, chatMessageId, onStreamStart } = options;
|
|
4050
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;
|
|
4051
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
|
+
}
|
|
4052
4167
|
if (!response.body) {
|
|
4053
4168
|
this._clearPendingAutoContinuation(true);
|
|
4054
4169
|
this._broadcastChatMessage({
|
|
@@ -4166,7 +4281,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
4166
4281
|
messageId: earlyPersistedId ?? message.id,
|
|
4167
4282
|
discard: !this._agentToolRunsByRequestId.get(id)
|
|
4168
4283
|
} : null;
|
|
4169
|
-
if (message.parts.length > 0 && !discardPartial) if (earlyPersistedId) {
|
|
4284
|
+
if (message.parts.length > 0 && !discardPartial && !resetSinceTurnStarted()) if (earlyPersistedId) {
|
|
4170
4285
|
const persistedMessage = {
|
|
4171
4286
|
...message,
|
|
4172
4287
|
id: earlyPersistedId
|