@cloudflare/ai-chat 0.1.9 → 0.2.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/README.md +13 -10
- package/dist/experimental/forever.d.ts +1 -1
- package/dist/{index-BLQX_nE0.d.ts → index-BbdbMsrQ.d.ts} +130 -12
- package/dist/index.d.ts +1 -1
- package/dist/index.js +346 -154
- package/dist/index.js.map +1 -1
- package/dist/react.js +131 -10
- package/dist/react.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -335,6 +335,13 @@ var ResumableStream = class ResumableStream {
|
|
|
335
335
|
//#region src/index.ts
|
|
336
336
|
/** Shared encoder for UTF-8 byte length measurement */
|
|
337
337
|
const textEncoder = new TextEncoder();
|
|
338
|
+
const TIMED_OUT = Symbol("timed-out");
|
|
339
|
+
/**
|
|
340
|
+
* Max string length preserved in `input`/`output` of provider-executed tool
|
|
341
|
+
* parts (e.g. Anthropic code_execution / text_editor). Strings exceeding this
|
|
342
|
+
* limit are truncated with a marker so persisted messages stay small.
|
|
343
|
+
*/
|
|
344
|
+
const PROVIDER_TOOL_MAX_STRING_LENGTH = 500;
|
|
338
345
|
/**
|
|
339
346
|
* Validates that a parsed message has the minimum required structure.
|
|
340
347
|
* Returns false for messages that would cause runtime errors downstream
|
|
@@ -405,10 +412,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
405
412
|
constructor(ctx, env) {
|
|
406
413
|
super(ctx, env);
|
|
407
414
|
this._streamingMessage = null;
|
|
415
|
+
this._pendingInteractionPromise = null;
|
|
408
416
|
this._approvalPersistedMessageId = null;
|
|
409
|
-
this.
|
|
410
|
-
this.
|
|
417
|
+
this._chatTurnQueue = Promise.resolve();
|
|
418
|
+
this._activeChatTurnRequestId = null;
|
|
419
|
+
this._chatEpoch = 0;
|
|
411
420
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
421
|
+
this._awaitingStreamStartConnections = /* @__PURE__ */ new Map();
|
|
422
|
+
this._pendingAutoContinuation = false;
|
|
412
423
|
this._persistedMessageCache = /* @__PURE__ */ new Map();
|
|
413
424
|
this.maxPersistedMessages = void 0;
|
|
414
425
|
this.waitForMcpConnections = { timeout: 1e4 };
|
|
@@ -433,11 +444,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
433
444
|
const _onClose = this.onClose.bind(this);
|
|
434
445
|
this.onClose = async (connection, code, reason, wasClean) => {
|
|
435
446
|
this._pendingResumeConnections.delete(connection.id);
|
|
447
|
+
this._awaitingStreamStartConnections.delete(connection.id);
|
|
436
448
|
return _onClose(connection, code, reason, wasClean);
|
|
437
449
|
};
|
|
438
450
|
const _onMessage = this.onMessage.bind(this);
|
|
439
451
|
this.onMessage = async (connection, message) => {
|
|
440
|
-
await this.mcp.ensureJsonSchema();
|
|
441
452
|
if (typeof message === "string") {
|
|
442
453
|
let data;
|
|
443
454
|
try {
|
|
@@ -446,10 +457,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
446
457
|
return _onMessage(connection, message);
|
|
447
458
|
}
|
|
448
459
|
if (data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST && data.init.method === "POST") {
|
|
449
|
-
if (this.waitForMcpConnections) {
|
|
450
|
-
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
|
|
451
|
-
await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
|
|
452
|
-
}
|
|
453
460
|
const { body } = data.init;
|
|
454
461
|
if (!body) {
|
|
455
462
|
console.warn("[AIChatAgent] Received chat request with empty body, ignoring");
|
|
@@ -463,49 +470,56 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
463
470
|
return;
|
|
464
471
|
}
|
|
465
472
|
const { messages, clientTools, trigger: _trigger, ...customBody } = parsed;
|
|
466
|
-
this._lastClientTools = clientTools?.length ? clientTools : void 0;
|
|
467
|
-
this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
468
|
-
this._persistRequestContext();
|
|
469
|
-
const transformedMessages = autoTransformMessages(messages);
|
|
470
|
-
this._broadcastChatMessage({
|
|
471
|
-
messages: transformedMessages,
|
|
472
|
-
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
473
|
-
}, [connection.id]);
|
|
474
|
-
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
475
|
-
this._emit("message:request");
|
|
476
473
|
const chatMessageId = data.id;
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
474
|
+
return this._runExclusiveChatTurn(chatMessageId, async () => {
|
|
475
|
+
if (this.waitForMcpConnections) {
|
|
476
|
+
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
|
|
477
|
+
await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
|
|
478
|
+
}
|
|
479
|
+
this._lastClientTools = clientTools?.length ? clientTools : void 0;
|
|
480
|
+
this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
481
|
+
this._persistRequestContext();
|
|
482
|
+
const transformedMessages = autoTransformMessages(messages);
|
|
483
|
+
this._broadcastChatMessage({
|
|
484
|
+
messages: transformedMessages,
|
|
485
|
+
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
486
|
+
}, [connection.id]);
|
|
487
|
+
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
488
|
+
this._emit("message:request");
|
|
489
|
+
const abortSignal = this._getAbortSignal(chatMessageId);
|
|
490
|
+
return this._tryCatchChat(async () => {
|
|
491
|
+
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
492
|
+
agent: this,
|
|
493
|
+
connection,
|
|
494
|
+
request: void 0,
|
|
495
|
+
email: void 0
|
|
496
|
+
}, async () => {
|
|
497
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
498
|
+
requestId: chatMessageId,
|
|
499
|
+
abortSignal,
|
|
500
|
+
clientTools,
|
|
501
|
+
body: this._lastBody
|
|
502
|
+
});
|
|
503
|
+
if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
|
|
504
|
+
else {
|
|
505
|
+
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
506
|
+
this._broadcastChatMessage({
|
|
507
|
+
body: "No response was generated by the agent.",
|
|
508
|
+
done: true,
|
|
509
|
+
id: chatMessageId,
|
|
510
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
511
|
+
}, [connection.id]);
|
|
512
|
+
}
|
|
490
513
|
});
|
|
491
|
-
if (response) await this._reply(data.id, response, [connection.id], { chatMessageId });
|
|
492
|
-
else {
|
|
493
|
-
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
494
|
-
this._broadcastChatMessage({
|
|
495
|
-
body: "No response was generated by the agent.",
|
|
496
|
-
done: true,
|
|
497
|
-
id: data.id,
|
|
498
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
499
|
-
}, [connection.id]);
|
|
500
|
-
}
|
|
501
514
|
});
|
|
502
515
|
});
|
|
503
516
|
}
|
|
504
517
|
if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
|
|
505
|
-
this.
|
|
518
|
+
this.resetTurnState();
|
|
506
519
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
507
520
|
this._resumableStream.clearAll();
|
|
508
521
|
this._pendingResumeConnections.clear();
|
|
522
|
+
this._clearPendingAutoContinuation(true);
|
|
509
523
|
this._lastClientTools = void 0;
|
|
510
524
|
this._lastBody = void 0;
|
|
511
525
|
this._persistRequestContext();
|
|
@@ -527,6 +541,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
527
541
|
}
|
|
528
542
|
if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
|
|
529
543
|
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
544
|
+
else if (this._pendingAutoContinuation) this._awaitingStreamStartConnections.set(connection.id, connection);
|
|
530
545
|
else connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
|
|
531
546
|
return;
|
|
532
547
|
}
|
|
@@ -549,39 +564,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
549
564
|
toolCallId,
|
|
550
565
|
toolName
|
|
551
566
|
});
|
|
552
|
-
this._applyToolResult(toolCallId, toolName, output, overrideState, errorText)
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
return this._tryCatchChat(async () => {
|
|
562
|
-
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
563
|
-
agent: this,
|
|
564
|
-
connection,
|
|
565
|
-
request: void 0,
|
|
566
|
-
email: void 0
|
|
567
|
-
}, async () => {
|
|
568
|
-
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
569
|
-
requestId: continuationId,
|
|
570
|
-
abortSignal,
|
|
571
|
-
clientTools: clientTools ?? this._lastClientTools,
|
|
572
|
-
body: this._lastBody
|
|
573
|
-
});
|
|
574
|
-
if (response) await this._reply(continuationId, response, [], {
|
|
575
|
-
continuation: true,
|
|
576
|
-
chatMessageId: continuationId
|
|
577
|
-
});
|
|
578
|
-
});
|
|
579
|
-
});
|
|
580
|
-
}).catch((error) => {
|
|
581
|
-
console.error("[AIChatAgent] Tool continuation failed:", error);
|
|
582
|
-
});
|
|
583
|
-
}
|
|
584
|
-
});
|
|
567
|
+
const applyPromise = this._applyToolResult(toolCallId, toolName, output, overrideState, errorText);
|
|
568
|
+
this._pendingInteractionPromise = applyPromise;
|
|
569
|
+
applyPromise.finally(() => {
|
|
570
|
+
if (this._pendingInteractionPromise === applyPromise) this._pendingInteractionPromise = null;
|
|
571
|
+
}).catch(() => {});
|
|
572
|
+
if (autoContinue) {
|
|
573
|
+
this._pendingAutoContinuation = true;
|
|
574
|
+
this._queueAutoContinuation(connection, nanoid(), clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
|
|
575
|
+
}
|
|
585
576
|
return;
|
|
586
577
|
}
|
|
587
578
|
if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
|
|
@@ -590,39 +581,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
590
581
|
toolCallId,
|
|
591
582
|
approved
|
|
592
583
|
});
|
|
593
|
-
this._applyToolApproval(toolCallId, approved)
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
return this._tryCatchChat(async () => {
|
|
603
|
-
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
604
|
-
agent: this,
|
|
605
|
-
connection,
|
|
606
|
-
request: void 0,
|
|
607
|
-
email: void 0
|
|
608
|
-
}, async () => {
|
|
609
|
-
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
610
|
-
requestId: continuationId,
|
|
611
|
-
abortSignal,
|
|
612
|
-
clientTools: this._lastClientTools,
|
|
613
|
-
body: this._lastBody
|
|
614
|
-
});
|
|
615
|
-
if (response) await this._reply(continuationId, response, [], {
|
|
616
|
-
continuation: true,
|
|
617
|
-
chatMessageId: continuationId
|
|
618
|
-
});
|
|
619
|
-
});
|
|
620
|
-
});
|
|
621
|
-
}).catch((error) => {
|
|
622
|
-
console.error("[AIChatAgent] Tool approval continuation failed:", error);
|
|
623
|
-
});
|
|
624
|
-
}
|
|
625
|
-
});
|
|
584
|
+
const approvalPromise = this._applyToolApproval(toolCallId, approved);
|
|
585
|
+
this._pendingInteractionPromise = approvalPromise;
|
|
586
|
+
approvalPromise.finally(() => {
|
|
587
|
+
if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
|
|
588
|
+
}).catch(() => {});
|
|
589
|
+
if (autoContinue) {
|
|
590
|
+
this._pendingAutoContinuation = true;
|
|
591
|
+
this._queueAutoContinuation(connection, nanoid(), this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
|
|
592
|
+
}
|
|
626
593
|
return;
|
|
627
594
|
}
|
|
628
595
|
}
|
|
@@ -636,6 +603,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
636
603
|
});
|
|
637
604
|
};
|
|
638
605
|
}
|
|
606
|
+
_flushAwaitingStreamStartConnections() {
|
|
607
|
+
if (!this._resumableStream.hasActiveStream()) return;
|
|
608
|
+
for (const connection of this._awaitingStreamStartConnections.values()) this._notifyStreamResuming(connection);
|
|
609
|
+
this._awaitingStreamStartConnections.clear();
|
|
610
|
+
}
|
|
611
|
+
_clearPendingAutoContinuation(sendNone = false) {
|
|
612
|
+
this._pendingAutoContinuation = false;
|
|
613
|
+
if (sendNone) for (const connection of this._awaitingStreamStartConnections.values()) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
|
|
614
|
+
this._awaitingStreamStartConnections.clear();
|
|
615
|
+
}
|
|
639
616
|
/**
|
|
640
617
|
* Notify a connection about an active stream that can be resumed.
|
|
641
618
|
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
@@ -659,7 +636,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
659
636
|
}
|
|
660
637
|
/** @internal Delegate to _resumableStream */
|
|
661
638
|
_startStream(requestId) {
|
|
662
|
-
|
|
639
|
+
const streamId = this._resumableStream.start(requestId);
|
|
640
|
+
this._pendingAutoContinuation = false;
|
|
641
|
+
this._flushAwaitingStreamStartConnections();
|
|
642
|
+
return streamId;
|
|
663
643
|
}
|
|
664
644
|
/** @internal Delegate to _resumableStream */
|
|
665
645
|
_completeStream(streamId) {
|
|
@@ -794,6 +774,128 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
794
774
|
throw this.onError(e);
|
|
795
775
|
}
|
|
796
776
|
}
|
|
777
|
+
isChatTurnActive() {
|
|
778
|
+
return this._activeChatTurnRequestId !== null;
|
|
779
|
+
}
|
|
780
|
+
async waitForIdle() {
|
|
781
|
+
await this._chatTurnQueue;
|
|
782
|
+
}
|
|
783
|
+
/** `true` when an assistant message is waiting on a client tool result or approval. */
|
|
784
|
+
hasPendingInteraction() {
|
|
785
|
+
if (this._streamingMessage && this._messageHasPendingInteraction(this._streamingMessage)) return true;
|
|
786
|
+
return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message));
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Waits until the conversation is fully stable — no active stream, no
|
|
790
|
+
* pending client-tool interactions, and no queued continuation turns.
|
|
791
|
+
*
|
|
792
|
+
* Returns `true` when stable. Returns `false` if `timeout` expires before
|
|
793
|
+
* a pending interaction resolves. Safe to call at any time; if there is
|
|
794
|
+
* nothing pending it returns immediately.
|
|
795
|
+
*/
|
|
796
|
+
async waitUntilStable(options) {
|
|
797
|
+
const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
|
|
798
|
+
while (true) {
|
|
799
|
+
if (await this._awaitWithDeadline(this._chatTurnQueue, deadline) === TIMED_OUT) return false;
|
|
800
|
+
if (!this.hasPendingInteraction()) return true;
|
|
801
|
+
const pending = this._pendingInteractionPromise;
|
|
802
|
+
if (pending) {
|
|
803
|
+
let result;
|
|
804
|
+
try {
|
|
805
|
+
result = await this._awaitWithDeadline(pending, deadline);
|
|
806
|
+
} catch {
|
|
807
|
+
continue;
|
|
808
|
+
}
|
|
809
|
+
if (result === TIMED_OUT) return false;
|
|
810
|
+
} else if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, 100)), deadline) === TIMED_OUT) return false;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
abortActiveTurn() {
|
|
814
|
+
if (!this._activeChatTurnRequestId) return false;
|
|
815
|
+
this._cancelChatRequest(this._activeChatTurnRequestId);
|
|
816
|
+
return true;
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Aborts the active turn and invalidates queued continuations. Call this
|
|
820
|
+
* when intercepting `CF_AGENT_CHAT_CLEAR` before the SDK sees the message —
|
|
821
|
+
* the built-in handler calls it automatically.
|
|
822
|
+
*/
|
|
823
|
+
resetTurnState() {
|
|
824
|
+
this._chatEpoch++;
|
|
825
|
+
this._destroyAbortControllers();
|
|
826
|
+
this._pendingInteractionPromise = null;
|
|
827
|
+
}
|
|
828
|
+
async _awaitWithDeadline(promise, deadline) {
|
|
829
|
+
if (deadline == null) return promise;
|
|
830
|
+
const remainingMs = Math.max(0, deadline - Date.now());
|
|
831
|
+
let timer;
|
|
832
|
+
const result = await Promise.race([promise, new Promise((resolve) => {
|
|
833
|
+
timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);
|
|
834
|
+
})]);
|
|
835
|
+
clearTimeout(timer);
|
|
836
|
+
return result;
|
|
837
|
+
}
|
|
838
|
+
_messageHasPendingInteraction(message) {
|
|
839
|
+
return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Run a chat turn exclusively so `_reply()` never overlaps with another
|
|
843
|
+
* streaming turn.
|
|
844
|
+
*/
|
|
845
|
+
async _runExclusiveChatTurn(requestId, fn) {
|
|
846
|
+
const previousTurn = this._chatTurnQueue;
|
|
847
|
+
let releaseTurn = () => {};
|
|
848
|
+
this._chatTurnQueue = new Promise((resolve) => {
|
|
849
|
+
releaseTurn = resolve;
|
|
850
|
+
});
|
|
851
|
+
await previousTurn;
|
|
852
|
+
this._activeChatTurnRequestId = requestId;
|
|
853
|
+
try {
|
|
854
|
+
return await fn();
|
|
855
|
+
} finally {
|
|
856
|
+
this._activeChatTurnRequestId = null;
|
|
857
|
+
releaseTurn();
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
_queueAutoContinuation(connection, requestId, clientTools, body, errorPrefix, prerequisite) {
|
|
861
|
+
const epoch = this._chatEpoch;
|
|
862
|
+
this.keepAliveWhile(() => this._runExclusiveChatTurn(requestId, async () => {
|
|
863
|
+
if (this._chatEpoch !== epoch) {
|
|
864
|
+
this._clearPendingAutoContinuation(true);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
if (prerequisite) {
|
|
868
|
+
if (!await prerequisite) {
|
|
869
|
+
this._clearPendingAutoContinuation(true);
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
const abortSignal = this._getAbortSignal(requestId);
|
|
874
|
+
return this._tryCatchChat(async () => {
|
|
875
|
+
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
876
|
+
agent: this,
|
|
877
|
+
connection,
|
|
878
|
+
request: void 0,
|
|
879
|
+
email: void 0
|
|
880
|
+
}, async () => {
|
|
881
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
882
|
+
requestId,
|
|
883
|
+
abortSignal,
|
|
884
|
+
clientTools,
|
|
885
|
+
body
|
|
886
|
+
});
|
|
887
|
+
if (response) await this._reply(requestId, response, [], {
|
|
888
|
+
continuation: true,
|
|
889
|
+
chatMessageId: requestId
|
|
890
|
+
});
|
|
891
|
+
else this._clearPendingAutoContinuation(true);
|
|
892
|
+
});
|
|
893
|
+
});
|
|
894
|
+
})).catch((error) => {
|
|
895
|
+
this._clearPendingAutoContinuation(true);
|
|
896
|
+
console.error(errorPrefix, error);
|
|
897
|
+
});
|
|
898
|
+
}
|
|
797
899
|
/**
|
|
798
900
|
* Handle incoming chat messages and generate a response
|
|
799
901
|
* @param onFinish Callback to be called when the response is finished
|
|
@@ -804,21 +906,61 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
804
906
|
throw new Error("received a chat message, override onChatMessage and return a Response to send to the client");
|
|
805
907
|
}
|
|
806
908
|
/**
|
|
909
|
+
* Override this method to apply custom transformations to messages before
|
|
910
|
+
* they are persisted to storage. This hook runs **after** the built-in
|
|
911
|
+
* sanitization (OpenAI metadata stripping, Anthropic provider-executed tool
|
|
912
|
+
* payload truncation, empty reasoning part filtering).
|
|
913
|
+
*
|
|
914
|
+
* The default implementation returns the message unchanged.
|
|
915
|
+
*
|
|
916
|
+
* @param message - The pre-sanitized message about to be persisted
|
|
917
|
+
* @returns The transformed message to persist
|
|
918
|
+
*
|
|
919
|
+
* @example
|
|
920
|
+
* ```ts
|
|
921
|
+
* class MyAgent extends AIChatAgent<Env> {
|
|
922
|
+
* protected sanitizeMessageForPersistence(
|
|
923
|
+
* message: UIMessage
|
|
924
|
+
* ): UIMessage {
|
|
925
|
+
* return {
|
|
926
|
+
* ...message,
|
|
927
|
+
* parts: message.parts.map(part => {
|
|
928
|
+
* if ("output" in part && typeof part.output === "string"
|
|
929
|
+
* && part.output.length > 1000) {
|
|
930
|
+
* return { ...part, output: "[redacted]" };
|
|
931
|
+
* }
|
|
932
|
+
* return part;
|
|
933
|
+
* })
|
|
934
|
+
* };
|
|
935
|
+
* }
|
|
936
|
+
* }
|
|
937
|
+
* ```
|
|
938
|
+
*/
|
|
939
|
+
sanitizeMessageForPersistence(message) {
|
|
940
|
+
return message;
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
807
943
|
* Save messages on the server side
|
|
808
944
|
* @param messages Chat messages to save
|
|
809
945
|
*/
|
|
810
946
|
async saveMessages(messages) {
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
947
|
+
const requestId = nanoid();
|
|
948
|
+
const clientTools = this._lastClientTools;
|
|
949
|
+
const body = this._lastBody;
|
|
950
|
+
const epoch = this._chatEpoch;
|
|
951
|
+
await this._runExclusiveChatTurn(requestId, async () => {
|
|
952
|
+
if (this._chatEpoch !== epoch) return;
|
|
953
|
+
await this.persistMessages(messages);
|
|
954
|
+
await this._tryCatchChat(async () => {
|
|
955
|
+
const abortSignal = this._getAbortSignal(requestId);
|
|
956
|
+
const response = await this.onChatMessage(() => {}, {
|
|
957
|
+
requestId,
|
|
958
|
+
abortSignal,
|
|
959
|
+
clientTools,
|
|
960
|
+
body
|
|
961
|
+
});
|
|
962
|
+
if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
|
|
820
963
|
});
|
|
821
|
-
if (response) this._reply(requestId, response);
|
|
822
964
|
});
|
|
823
965
|
}
|
|
824
966
|
async persistMessages(messages, excludeBroadcastIds = [], options) {
|
|
@@ -953,17 +1095,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
953
1095
|
}
|
|
954
1096
|
/**
|
|
955
1097
|
* Resolves a message for persistence, handling tool result merging.
|
|
956
|
-
* If the message contains tool parts with
|
|
957
|
-
*
|
|
958
|
-
*
|
|
959
|
-
*
|
|
1098
|
+
* If the message contains tool parts with a toolCallId that already exists
|
|
1099
|
+
* in a server-side message with a different ID, adopts the server's ID.
|
|
1100
|
+
* This prevents duplicate rows when the client sends messages with
|
|
1101
|
+
* client-generated IDs (e.g. nanoid from the AI SDK) that differ from
|
|
1102
|
+
* the server-stamped IDs. Tool call IDs are unique per conversation,
|
|
1103
|
+
* so matching by toolCallId is safe regardless of tool state (#1094).
|
|
960
1104
|
*
|
|
961
1105
|
* @param message - The message to potentially merge
|
|
962
1106
|
* @returns The message with the correct ID (either original or merged)
|
|
963
1107
|
*/
|
|
964
1108
|
_resolveMessageForToolMerge(message) {
|
|
965
1109
|
if (message.role !== "assistant") return message;
|
|
966
|
-
for (const part of message.parts) if ("toolCallId" in part &&
|
|
1110
|
+
for (const part of message.parts) if ("toolCallId" in part && part.toolCallId) {
|
|
967
1111
|
const toolCallId = part.toolCallId;
|
|
968
1112
|
const existingMessage = this._findMessageByToolCallId(toolCallId);
|
|
969
1113
|
if (existingMessage && existingMessage.id !== message.id) return {
|
|
@@ -987,23 +1131,45 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
987
1131
|
for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) return msg;
|
|
988
1132
|
}
|
|
989
1133
|
}
|
|
1134
|
+
_findLastAssistantMessage() {
|
|
1135
|
+
for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") return this.messages[i];
|
|
1136
|
+
}
|
|
1137
|
+
_createStreamingAssistantMessage(continuation) {
|
|
1138
|
+
if (continuation) {
|
|
1139
|
+
const lastAssistant = this._findLastAssistantMessage();
|
|
1140
|
+
if (lastAssistant) return structuredClone(lastAssistant);
|
|
1141
|
+
}
|
|
1142
|
+
return {
|
|
1143
|
+
id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
|
|
1144
|
+
role: "assistant",
|
|
1145
|
+
parts: []
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
990
1148
|
/**
|
|
991
1149
|
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
992
1150
|
* data that should not be stored or sent back in subsequent requests.
|
|
993
1151
|
*
|
|
994
|
-
*
|
|
1152
|
+
* Pipeline:
|
|
995
1153
|
*
|
|
996
1154
|
* 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
|
|
997
1155
|
* (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
|
|
998
1156
|
* itemIds and reasoningEncryptedContent to message parts. When persisted
|
|
999
1157
|
* and sent back, OpenAI rejects duplicate itemIds.
|
|
1000
1158
|
*
|
|
1001
|
-
* 2. **
|
|
1159
|
+
* 2. **Truncate provider-executed tool payloads**: Server-side tool
|
|
1160
|
+
* executions (e.g. Anthropic code_execution, text_editor) can produce
|
|
1161
|
+
* 200KB+ payloads in `input` and `output`. These are truncated since the
|
|
1162
|
+
* model has already consumed the results.
|
|
1163
|
+
*
|
|
1164
|
+
* 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
|
|
1002
1165
|
* with no text and no remaining providerMetadata are removed. Parts that
|
|
1003
1166
|
* still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
|
|
1004
1167
|
* with providerMetadata.anthropic.redactedData) are preserved, as they
|
|
1005
1168
|
* contain data required for round-tripping with the provider API.
|
|
1006
1169
|
*
|
|
1170
|
+
* 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
|
|
1171
|
+
* method, allowing subclasses to apply custom transformations.
|
|
1172
|
+
*
|
|
1007
1173
|
* @param message - The message to sanitize
|
|
1008
1174
|
* @returns A new message with ephemeral provider data removed
|
|
1009
1175
|
*/
|
|
@@ -1012,6 +1178,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1012
1178
|
let sanitizedPart = part;
|
|
1013
1179
|
if ("providerMetadata" in sanitizedPart && sanitizedPart.providerMetadata && typeof sanitizedPart.providerMetadata === "object" && "openai" in sanitizedPart.providerMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "providerMetadata");
|
|
1014
1180
|
if ("callProviderMetadata" in sanitizedPart && sanitizedPart.callProviderMetadata && typeof sanitizedPart.callProviderMetadata === "object" && "openai" in sanitizedPart.callProviderMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "callProviderMetadata");
|
|
1181
|
+
sanitizedPart = AIChatAgent._truncateProviderExecutedToolPayloads(sanitizedPart);
|
|
1015
1182
|
return sanitizedPart;
|
|
1016
1183
|
}).filter((part) => {
|
|
1017
1184
|
if (part.type === "reasoning") {
|
|
@@ -1023,10 +1190,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1023
1190
|
}
|
|
1024
1191
|
return true;
|
|
1025
1192
|
});
|
|
1026
|
-
return {
|
|
1193
|
+
return this.sanitizeMessageForPersistence({
|
|
1027
1194
|
...message,
|
|
1028
1195
|
parts: sanitizedParts
|
|
1029
|
-
};
|
|
1196
|
+
});
|
|
1030
1197
|
}
|
|
1031
1198
|
/**
|
|
1032
1199
|
* Helper to strip OpenAI-specific ephemeral fields from a metadata object.
|
|
@@ -1052,6 +1219,44 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1052
1219
|
return restPart;
|
|
1053
1220
|
}
|
|
1054
1221
|
/**
|
|
1222
|
+
* Truncates large string values in `input` and `output` of tool parts that
|
|
1223
|
+
* were executed server-side by the provider (e.g. Anthropic code_execution,
|
|
1224
|
+
* text_editor). These payloads can be 200KB+ and are dead weight once the
|
|
1225
|
+
* model has consumed the result.
|
|
1226
|
+
*/
|
|
1227
|
+
static _truncateProviderExecutedToolPayloads(part) {
|
|
1228
|
+
const record = part;
|
|
1229
|
+
if (!record.providerExecuted) return part;
|
|
1230
|
+
const result = { ...record };
|
|
1231
|
+
if (result.input !== void 0) result.input = AIChatAgent._truncateLargeStrings(result.input);
|
|
1232
|
+
if (result.output !== void 0) result.output = AIChatAgent._truncateLargeStrings(result.output);
|
|
1233
|
+
return result;
|
|
1234
|
+
}
|
|
1235
|
+
/**
|
|
1236
|
+
* Recursively walks a value and truncates any string exceeding
|
|
1237
|
+
* `PROVIDER_TOOL_MAX_STRING_LENGTH`, appending a size marker.
|
|
1238
|
+
*
|
|
1239
|
+
* The total output (content + marker) is kept within the threshold so
|
|
1240
|
+
* re-running this function on already-truncated data is a no-op.
|
|
1241
|
+
*/
|
|
1242
|
+
static _truncateLargeStrings(value) {
|
|
1243
|
+
if (typeof value === "string") {
|
|
1244
|
+
if (value.length > PROVIDER_TOOL_MAX_STRING_LENGTH) {
|
|
1245
|
+
const marker = `… [truncated, original length: ${value.length}]`;
|
|
1246
|
+
const contentLength = Math.max(0, PROVIDER_TOOL_MAX_STRING_LENGTH - marker.length);
|
|
1247
|
+
return value.slice(0, contentLength) + marker;
|
|
1248
|
+
}
|
|
1249
|
+
return value;
|
|
1250
|
+
}
|
|
1251
|
+
if (Array.isArray(value)) return value.map((v) => AIChatAgent._truncateLargeStrings(v));
|
|
1252
|
+
if (value !== null && typeof value === "object") {
|
|
1253
|
+
const result = {};
|
|
1254
|
+
for (const [k, v] of Object.entries(value)) result[k] = AIChatAgent._truncateLargeStrings(v);
|
|
1255
|
+
return result;
|
|
1256
|
+
}
|
|
1257
|
+
return value;
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1055
1260
|
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
1056
1261
|
* Called after each persist to keep storage bounded.
|
|
1057
1262
|
*/
|
|
@@ -1340,7 +1545,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1340
1545
|
}
|
|
1341
1546
|
if (!handled) switch (data.type) {
|
|
1342
1547
|
case "start":
|
|
1343
|
-
if (data.messageId != null) message.id = data.messageId;
|
|
1548
|
+
if (data.messageId != null && !continuation) message.id = data.messageId;
|
|
1344
1549
|
if (data.messageMetadata != null) message.metadata = message.metadata ? {
|
|
1345
1550
|
...message.metadata,
|
|
1346
1551
|
...data.messageMetadata
|
|
@@ -1492,6 +1697,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1492
1697
|
const abortSignal = chatMessageId ? this._chatMessageAbortControllers.get(chatMessageId)?.signal : void 0;
|
|
1493
1698
|
return this.keepAliveWhile(() => this._tryCatchChat(async () => {
|
|
1494
1699
|
if (!response.body) {
|
|
1700
|
+
this._clearPendingAutoContinuation(true);
|
|
1495
1701
|
this._broadcastChatMessage({
|
|
1496
1702
|
body: "",
|
|
1497
1703
|
done: true,
|
|
@@ -1503,15 +1709,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1503
1709
|
}
|
|
1504
1710
|
const streamId = this._startStream(id);
|
|
1505
1711
|
const reader = response.body.getReader();
|
|
1506
|
-
const message =
|
|
1507
|
-
id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
|
|
1508
|
-
role: "assistant",
|
|
1509
|
-
parts: []
|
|
1510
|
-
};
|
|
1712
|
+
const message = this._createStreamingAssistantMessage(continuation);
|
|
1511
1713
|
this._streamingMessage = message;
|
|
1512
|
-
this._streamCompletionPromise = new Promise((resolve) => {
|
|
1513
|
-
this._streamCompletionResolve = resolve;
|
|
1514
|
-
});
|
|
1515
1714
|
const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
|
|
1516
1715
|
const streamCompleted = { value: false };
|
|
1517
1716
|
let earlyPersistedId = null;
|
|
@@ -1537,33 +1736,26 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1537
1736
|
this._streamingMessage = null;
|
|
1538
1737
|
earlyPersistedId = this._approvalPersistedMessageId;
|
|
1539
1738
|
this._approvalPersistedMessageId = null;
|
|
1540
|
-
if (this._streamCompletionResolve) {
|
|
1541
|
-
this._streamCompletionResolve();
|
|
1542
|
-
this._streamCompletionResolve = null;
|
|
1543
|
-
this._streamCompletionPromise = null;
|
|
1544
|
-
}
|
|
1545
1739
|
if (chatMessageId) {
|
|
1546
1740
|
this._removeAbortController(chatMessageId);
|
|
1547
1741
|
if (streamCompleted.value) this._emit("message:response");
|
|
1548
1742
|
}
|
|
1549
1743
|
}
|
|
1550
1744
|
if (message.parts.length > 0) if (earlyPersistedId) {
|
|
1551
|
-
const
|
|
1745
|
+
const persistedMessage = {
|
|
1746
|
+
...message,
|
|
1747
|
+
id: earlyPersistedId
|
|
1748
|
+
};
|
|
1749
|
+
const existingIdx = this.messages.findIndex((msg) => msg.id === earlyPersistedId);
|
|
1750
|
+
const updatedMessages = [...this.messages];
|
|
1751
|
+
if (existingIdx >= 0) updatedMessages[existingIdx] = persistedMessage;
|
|
1752
|
+
else updatedMessages.push(persistedMessage);
|
|
1552
1753
|
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
1553
1754
|
} else if (continuation) {
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
lastAssistantIdx = i;
|
|
1557
|
-
break;
|
|
1558
|
-
}
|
|
1559
|
-
if (lastAssistantIdx >= 0) {
|
|
1560
|
-
const lastAssistant = this.messages[lastAssistantIdx];
|
|
1561
|
-
const mergedMessage = {
|
|
1562
|
-
...lastAssistant,
|
|
1563
|
-
parts: [...lastAssistant.parts, ...message.parts]
|
|
1564
|
-
};
|
|
1755
|
+
const existingIdx = this.messages.findIndex((msg) => msg.id === message.id);
|
|
1756
|
+
if (existingIdx >= 0) {
|
|
1565
1757
|
const updatedMessages = [...this.messages];
|
|
1566
|
-
updatedMessages[
|
|
1758
|
+
updatedMessages[existingIdx] = message;
|
|
1567
1759
|
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
1568
1760
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|
|
1569
1761
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|