@cloudflare/ai-chat 0.1.9 → 0.2.0
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-B09l5oPB.d.ts} +113 -12
- package/dist/index.d.ts +1 -1
- package/dist/index.js +285 -134
- package/dist/index.js.map +1 -1
- package/dist/react.js +8 -5
- 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,9 +412,11 @@ 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();
|
|
412
421
|
this._persistedMessageCache = /* @__PURE__ */ new Map();
|
|
413
422
|
this.maxPersistedMessages = void 0;
|
|
@@ -437,7 +446,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
437
446
|
};
|
|
438
447
|
const _onMessage = this.onMessage.bind(this);
|
|
439
448
|
this.onMessage = async (connection, message) => {
|
|
440
|
-
await this.mcp.ensureJsonSchema();
|
|
441
449
|
if (typeof message === "string") {
|
|
442
450
|
let data;
|
|
443
451
|
try {
|
|
@@ -446,10 +454,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
446
454
|
return _onMessage(connection, message);
|
|
447
455
|
}
|
|
448
456
|
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
457
|
const { body } = data.init;
|
|
454
458
|
if (!body) {
|
|
455
459
|
console.warn("[AIChatAgent] Received chat request with empty body, ignoring");
|
|
@@ -463,46 +467,52 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
463
467
|
return;
|
|
464
468
|
}
|
|
465
469
|
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
470
|
const chatMessageId = data.id;
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
471
|
+
return this._runExclusiveChatTurn(chatMessageId, async () => {
|
|
472
|
+
if (this.waitForMcpConnections) {
|
|
473
|
+
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
|
|
474
|
+
await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
|
|
475
|
+
}
|
|
476
|
+
this._lastClientTools = clientTools?.length ? clientTools : void 0;
|
|
477
|
+
this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
478
|
+
this._persistRequestContext();
|
|
479
|
+
const transformedMessages = autoTransformMessages(messages);
|
|
480
|
+
this._broadcastChatMessage({
|
|
481
|
+
messages: transformedMessages,
|
|
482
|
+
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
483
|
+
}, [connection.id]);
|
|
484
|
+
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
485
|
+
this._emit("message:request");
|
|
486
|
+
const abortSignal = this._getAbortSignal(chatMessageId);
|
|
487
|
+
return this._tryCatchChat(async () => {
|
|
488
|
+
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
489
|
+
agent: this,
|
|
490
|
+
connection,
|
|
491
|
+
request: void 0,
|
|
492
|
+
email: void 0
|
|
493
|
+
}, async () => {
|
|
494
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
495
|
+
requestId: chatMessageId,
|
|
496
|
+
abortSignal,
|
|
497
|
+
clientTools,
|
|
498
|
+
body: this._lastBody
|
|
499
|
+
});
|
|
500
|
+
if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
|
|
501
|
+
else {
|
|
502
|
+
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
503
|
+
this._broadcastChatMessage({
|
|
504
|
+
body: "No response was generated by the agent.",
|
|
505
|
+
done: true,
|
|
506
|
+
id: chatMessageId,
|
|
507
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
508
|
+
}, [connection.id]);
|
|
509
|
+
}
|
|
490
510
|
});
|
|
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
511
|
});
|
|
502
512
|
});
|
|
503
513
|
}
|
|
504
514
|
if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
|
|
505
|
-
this.
|
|
515
|
+
this.resetTurnState();
|
|
506
516
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
507
517
|
this._resumableStream.clearAll();
|
|
508
518
|
this._pendingResumeConnections.clear();
|
|
@@ -549,39 +559,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
549
559
|
toolCallId,
|
|
550
560
|
toolName
|
|
551
561
|
});
|
|
552
|
-
this._applyToolResult(toolCallId, toolName, output, overrideState, errorText)
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
waitForStream().then(() => {
|
|
559
|
-
const continuationId = nanoid();
|
|
560
|
-
const abortSignal = this._getAbortSignal(continuationId);
|
|
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
|
-
});
|
|
562
|
+
const applyPromise = this._applyToolResult(toolCallId, toolName, output, overrideState, errorText);
|
|
563
|
+
this._pendingInteractionPromise = applyPromise;
|
|
564
|
+
applyPromise.finally(() => {
|
|
565
|
+
if (this._pendingInteractionPromise === applyPromise) this._pendingInteractionPromise = null;
|
|
566
|
+
}).catch(() => {});
|
|
567
|
+
if (autoContinue) this._queueAutoContinuation(connection, nanoid(), clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
|
|
585
568
|
return;
|
|
586
569
|
}
|
|
587
570
|
if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
|
|
@@ -590,39 +573,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
590
573
|
toolCallId,
|
|
591
574
|
approved
|
|
592
575
|
});
|
|
593
|
-
this._applyToolApproval(toolCallId, approved)
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
waitForStream().then(() => {
|
|
600
|
-
const continuationId = nanoid();
|
|
601
|
-
const abortSignal = this._getAbortSignal(continuationId);
|
|
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
|
-
});
|
|
576
|
+
const approvalPromise = this._applyToolApproval(toolCallId, approved);
|
|
577
|
+
this._pendingInteractionPromise = approvalPromise;
|
|
578
|
+
approvalPromise.finally(() => {
|
|
579
|
+
if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
|
|
580
|
+
}).catch(() => {});
|
|
581
|
+
if (autoContinue) this._queueAutoContinuation(connection, nanoid(), this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
|
|
626
582
|
return;
|
|
627
583
|
}
|
|
628
584
|
}
|
|
@@ -794,6 +750,120 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
794
750
|
throw this.onError(e);
|
|
795
751
|
}
|
|
796
752
|
}
|
|
753
|
+
isChatTurnActive() {
|
|
754
|
+
return this._activeChatTurnRequestId !== null;
|
|
755
|
+
}
|
|
756
|
+
async waitForIdle() {
|
|
757
|
+
await this._chatTurnQueue;
|
|
758
|
+
}
|
|
759
|
+
/** `true` when an assistant message is waiting on a client tool result or approval. */
|
|
760
|
+
hasPendingInteraction() {
|
|
761
|
+
if (this._streamingMessage && this._messageHasPendingInteraction(this._streamingMessage)) return true;
|
|
762
|
+
return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message));
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Waits until the conversation is fully stable — no active stream, no
|
|
766
|
+
* pending client-tool interactions, and no queued continuation turns.
|
|
767
|
+
*
|
|
768
|
+
* Returns `true` when stable. Returns `false` if `timeout` expires before
|
|
769
|
+
* a pending interaction resolves. Safe to call at any time; if there is
|
|
770
|
+
* nothing pending it returns immediately.
|
|
771
|
+
*/
|
|
772
|
+
async waitUntilStable(options) {
|
|
773
|
+
const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
|
|
774
|
+
while (true) {
|
|
775
|
+
if (await this._awaitWithDeadline(this._chatTurnQueue, deadline) === TIMED_OUT) return false;
|
|
776
|
+
if (!this.hasPendingInteraction()) return true;
|
|
777
|
+
const pending = this._pendingInteractionPromise;
|
|
778
|
+
if (pending) {
|
|
779
|
+
let result;
|
|
780
|
+
try {
|
|
781
|
+
result = await this._awaitWithDeadline(pending, deadline);
|
|
782
|
+
} catch {
|
|
783
|
+
continue;
|
|
784
|
+
}
|
|
785
|
+
if (result === TIMED_OUT) return false;
|
|
786
|
+
} else if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, 100)), deadline) === TIMED_OUT) return false;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
abortActiveTurn() {
|
|
790
|
+
if (!this._activeChatTurnRequestId) return false;
|
|
791
|
+
this._cancelChatRequest(this._activeChatTurnRequestId);
|
|
792
|
+
return true;
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* Aborts the active turn and invalidates queued continuations. Call this
|
|
796
|
+
* when intercepting `CF_AGENT_CHAT_CLEAR` before the SDK sees the message —
|
|
797
|
+
* the built-in handler calls it automatically.
|
|
798
|
+
*/
|
|
799
|
+
resetTurnState() {
|
|
800
|
+
this._chatEpoch++;
|
|
801
|
+
this._destroyAbortControllers();
|
|
802
|
+
this._pendingInteractionPromise = null;
|
|
803
|
+
}
|
|
804
|
+
async _awaitWithDeadline(promise, deadline) {
|
|
805
|
+
if (deadline == null) return promise;
|
|
806
|
+
const remainingMs = Math.max(0, deadline - Date.now());
|
|
807
|
+
let timer;
|
|
808
|
+
const result = await Promise.race([promise, new Promise((resolve) => {
|
|
809
|
+
timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);
|
|
810
|
+
})]);
|
|
811
|
+
clearTimeout(timer);
|
|
812
|
+
return result;
|
|
813
|
+
}
|
|
814
|
+
_messageHasPendingInteraction(message) {
|
|
815
|
+
return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Run a chat turn exclusively so `_reply()` never overlaps with another
|
|
819
|
+
* streaming turn.
|
|
820
|
+
*/
|
|
821
|
+
async _runExclusiveChatTurn(requestId, fn) {
|
|
822
|
+
const previousTurn = this._chatTurnQueue;
|
|
823
|
+
let releaseTurn = () => {};
|
|
824
|
+
this._chatTurnQueue = new Promise((resolve) => {
|
|
825
|
+
releaseTurn = resolve;
|
|
826
|
+
});
|
|
827
|
+
await previousTurn;
|
|
828
|
+
this._activeChatTurnRequestId = requestId;
|
|
829
|
+
try {
|
|
830
|
+
return await fn();
|
|
831
|
+
} finally {
|
|
832
|
+
this._activeChatTurnRequestId = null;
|
|
833
|
+
releaseTurn();
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
_queueAutoContinuation(connection, requestId, clientTools, body, errorPrefix, prerequisite) {
|
|
837
|
+
const epoch = this._chatEpoch;
|
|
838
|
+
this._runExclusiveChatTurn(requestId, async () => {
|
|
839
|
+
if (this._chatEpoch !== epoch) return;
|
|
840
|
+
if (prerequisite) {
|
|
841
|
+
if (!await prerequisite) return;
|
|
842
|
+
}
|
|
843
|
+
const abortSignal = this._getAbortSignal(requestId);
|
|
844
|
+
return this._tryCatchChat(async () => {
|
|
845
|
+
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
846
|
+
agent: this,
|
|
847
|
+
connection,
|
|
848
|
+
request: void 0,
|
|
849
|
+
email: void 0
|
|
850
|
+
}, async () => {
|
|
851
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
852
|
+
requestId,
|
|
853
|
+
abortSignal,
|
|
854
|
+
clientTools,
|
|
855
|
+
body
|
|
856
|
+
});
|
|
857
|
+
if (response) await this._reply(requestId, response, [], {
|
|
858
|
+
continuation: true,
|
|
859
|
+
chatMessageId: requestId
|
|
860
|
+
});
|
|
861
|
+
});
|
|
862
|
+
});
|
|
863
|
+
}).catch((error) => {
|
|
864
|
+
console.error(errorPrefix, error);
|
|
865
|
+
});
|
|
866
|
+
}
|
|
797
867
|
/**
|
|
798
868
|
* Handle incoming chat messages and generate a response
|
|
799
869
|
* @param onFinish Callback to be called when the response is finished
|
|
@@ -804,21 +874,61 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
804
874
|
throw new Error("received a chat message, override onChatMessage and return a Response to send to the client");
|
|
805
875
|
}
|
|
806
876
|
/**
|
|
877
|
+
* Override this method to apply custom transformations to messages before
|
|
878
|
+
* they are persisted to storage. This hook runs **after** the built-in
|
|
879
|
+
* sanitization (OpenAI metadata stripping, Anthropic provider-executed tool
|
|
880
|
+
* payload truncation, empty reasoning part filtering).
|
|
881
|
+
*
|
|
882
|
+
* The default implementation returns the message unchanged.
|
|
883
|
+
*
|
|
884
|
+
* @param message - The pre-sanitized message about to be persisted
|
|
885
|
+
* @returns The transformed message to persist
|
|
886
|
+
*
|
|
887
|
+
* @example
|
|
888
|
+
* ```ts
|
|
889
|
+
* class MyAgent extends AIChatAgent<Env> {
|
|
890
|
+
* protected sanitizeMessageForPersistence(
|
|
891
|
+
* message: UIMessage
|
|
892
|
+
* ): UIMessage {
|
|
893
|
+
* return {
|
|
894
|
+
* ...message,
|
|
895
|
+
* parts: message.parts.map(part => {
|
|
896
|
+
* if ("output" in part && typeof part.output === "string"
|
|
897
|
+
* && part.output.length > 1000) {
|
|
898
|
+
* return { ...part, output: "[redacted]" };
|
|
899
|
+
* }
|
|
900
|
+
* return part;
|
|
901
|
+
* })
|
|
902
|
+
* };
|
|
903
|
+
* }
|
|
904
|
+
* }
|
|
905
|
+
* ```
|
|
906
|
+
*/
|
|
907
|
+
sanitizeMessageForPersistence(message) {
|
|
908
|
+
return message;
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
807
911
|
* Save messages on the server side
|
|
808
912
|
* @param messages Chat messages to save
|
|
809
913
|
*/
|
|
810
914
|
async saveMessages(messages) {
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
915
|
+
const requestId = nanoid();
|
|
916
|
+
const clientTools = this._lastClientTools;
|
|
917
|
+
const body = this._lastBody;
|
|
918
|
+
const epoch = this._chatEpoch;
|
|
919
|
+
await this._runExclusiveChatTurn(requestId, async () => {
|
|
920
|
+
if (this._chatEpoch !== epoch) return;
|
|
921
|
+
await this.persistMessages(messages);
|
|
922
|
+
await this._tryCatchChat(async () => {
|
|
923
|
+
const abortSignal = this._getAbortSignal(requestId);
|
|
924
|
+
const response = await this.onChatMessage(() => {}, {
|
|
925
|
+
requestId,
|
|
926
|
+
abortSignal,
|
|
927
|
+
clientTools,
|
|
928
|
+
body
|
|
929
|
+
});
|
|
930
|
+
if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
|
|
820
931
|
});
|
|
821
|
-
if (response) this._reply(requestId, response);
|
|
822
932
|
});
|
|
823
933
|
}
|
|
824
934
|
async persistMessages(messages, excludeBroadcastIds = [], options) {
|
|
@@ -953,17 +1063,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
953
1063
|
}
|
|
954
1064
|
/**
|
|
955
1065
|
* Resolves a message for persistence, handling tool result merging.
|
|
956
|
-
* If the message contains tool parts with
|
|
957
|
-
*
|
|
958
|
-
*
|
|
959
|
-
*
|
|
1066
|
+
* If the message contains tool parts with a toolCallId that already exists
|
|
1067
|
+
* in a server-side message with a different ID, adopts the server's ID.
|
|
1068
|
+
* This prevents duplicate rows when the client sends messages with
|
|
1069
|
+
* client-generated IDs (e.g. nanoid from the AI SDK) that differ from
|
|
1070
|
+
* the server-stamped IDs. Tool call IDs are unique per conversation,
|
|
1071
|
+
* so matching by toolCallId is safe regardless of tool state (#1094).
|
|
960
1072
|
*
|
|
961
1073
|
* @param message - The message to potentially merge
|
|
962
1074
|
* @returns The message with the correct ID (either original or merged)
|
|
963
1075
|
*/
|
|
964
1076
|
_resolveMessageForToolMerge(message) {
|
|
965
1077
|
if (message.role !== "assistant") return message;
|
|
966
|
-
for (const part of message.parts) if ("toolCallId" in part &&
|
|
1078
|
+
for (const part of message.parts) if ("toolCallId" in part && part.toolCallId) {
|
|
967
1079
|
const toolCallId = part.toolCallId;
|
|
968
1080
|
const existingMessage = this._findMessageByToolCallId(toolCallId);
|
|
969
1081
|
if (existingMessage && existingMessage.id !== message.id) return {
|
|
@@ -991,19 +1103,27 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
991
1103
|
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
992
1104
|
* data that should not be stored or sent back in subsequent requests.
|
|
993
1105
|
*
|
|
994
|
-
*
|
|
1106
|
+
* Pipeline:
|
|
995
1107
|
*
|
|
996
1108
|
* 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
|
|
997
1109
|
* (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
|
|
998
1110
|
* itemIds and reasoningEncryptedContent to message parts. When persisted
|
|
999
1111
|
* and sent back, OpenAI rejects duplicate itemIds.
|
|
1000
1112
|
*
|
|
1001
|
-
* 2. **
|
|
1113
|
+
* 2. **Truncate provider-executed tool payloads**: Server-side tool
|
|
1114
|
+
* executions (e.g. Anthropic code_execution, text_editor) can produce
|
|
1115
|
+
* 200KB+ payloads in `input` and `output`. These are truncated since the
|
|
1116
|
+
* model has already consumed the results.
|
|
1117
|
+
*
|
|
1118
|
+
* 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
|
|
1002
1119
|
* with no text and no remaining providerMetadata are removed. Parts that
|
|
1003
1120
|
* still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
|
|
1004
1121
|
* with providerMetadata.anthropic.redactedData) are preserved, as they
|
|
1005
1122
|
* contain data required for round-tripping with the provider API.
|
|
1006
1123
|
*
|
|
1124
|
+
* 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
|
|
1125
|
+
* method, allowing subclasses to apply custom transformations.
|
|
1126
|
+
*
|
|
1007
1127
|
* @param message - The message to sanitize
|
|
1008
1128
|
* @returns A new message with ephemeral provider data removed
|
|
1009
1129
|
*/
|
|
@@ -1012,6 +1132,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1012
1132
|
let sanitizedPart = part;
|
|
1013
1133
|
if ("providerMetadata" in sanitizedPart && sanitizedPart.providerMetadata && typeof sanitizedPart.providerMetadata === "object" && "openai" in sanitizedPart.providerMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "providerMetadata");
|
|
1014
1134
|
if ("callProviderMetadata" in sanitizedPart && sanitizedPart.callProviderMetadata && typeof sanitizedPart.callProviderMetadata === "object" && "openai" in sanitizedPart.callProviderMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "callProviderMetadata");
|
|
1135
|
+
sanitizedPart = AIChatAgent._truncateProviderExecutedToolPayloads(sanitizedPart);
|
|
1015
1136
|
return sanitizedPart;
|
|
1016
1137
|
}).filter((part) => {
|
|
1017
1138
|
if (part.type === "reasoning") {
|
|
@@ -1023,10 +1144,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1023
1144
|
}
|
|
1024
1145
|
return true;
|
|
1025
1146
|
});
|
|
1026
|
-
return {
|
|
1147
|
+
return this.sanitizeMessageForPersistence({
|
|
1027
1148
|
...message,
|
|
1028
1149
|
parts: sanitizedParts
|
|
1029
|
-
};
|
|
1150
|
+
});
|
|
1030
1151
|
}
|
|
1031
1152
|
/**
|
|
1032
1153
|
* Helper to strip OpenAI-specific ephemeral fields from a metadata object.
|
|
@@ -1052,6 +1173,44 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1052
1173
|
return restPart;
|
|
1053
1174
|
}
|
|
1054
1175
|
/**
|
|
1176
|
+
* Truncates large string values in `input` and `output` of tool parts that
|
|
1177
|
+
* were executed server-side by the provider (e.g. Anthropic code_execution,
|
|
1178
|
+
* text_editor). These payloads can be 200KB+ and are dead weight once the
|
|
1179
|
+
* model has consumed the result.
|
|
1180
|
+
*/
|
|
1181
|
+
static _truncateProviderExecutedToolPayloads(part) {
|
|
1182
|
+
const record = part;
|
|
1183
|
+
if (!record.providerExecuted) return part;
|
|
1184
|
+
const result = { ...record };
|
|
1185
|
+
if (result.input !== void 0) result.input = AIChatAgent._truncateLargeStrings(result.input);
|
|
1186
|
+
if (result.output !== void 0) result.output = AIChatAgent._truncateLargeStrings(result.output);
|
|
1187
|
+
return result;
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* Recursively walks a value and truncates any string exceeding
|
|
1191
|
+
* `PROVIDER_TOOL_MAX_STRING_LENGTH`, appending a size marker.
|
|
1192
|
+
*
|
|
1193
|
+
* The total output (content + marker) is kept within the threshold so
|
|
1194
|
+
* re-running this function on already-truncated data is a no-op.
|
|
1195
|
+
*/
|
|
1196
|
+
static _truncateLargeStrings(value) {
|
|
1197
|
+
if (typeof value === "string") {
|
|
1198
|
+
if (value.length > PROVIDER_TOOL_MAX_STRING_LENGTH) {
|
|
1199
|
+
const marker = `… [truncated, original length: ${value.length}]`;
|
|
1200
|
+
const contentLength = Math.max(0, PROVIDER_TOOL_MAX_STRING_LENGTH - marker.length);
|
|
1201
|
+
return value.slice(0, contentLength) + marker;
|
|
1202
|
+
}
|
|
1203
|
+
return value;
|
|
1204
|
+
}
|
|
1205
|
+
if (Array.isArray(value)) return value.map((v) => AIChatAgent._truncateLargeStrings(v));
|
|
1206
|
+
if (value !== null && typeof value === "object") {
|
|
1207
|
+
const result = {};
|
|
1208
|
+
for (const [k, v] of Object.entries(value)) result[k] = AIChatAgent._truncateLargeStrings(v);
|
|
1209
|
+
return result;
|
|
1210
|
+
}
|
|
1211
|
+
return value;
|
|
1212
|
+
}
|
|
1213
|
+
/**
|
|
1055
1214
|
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
1056
1215
|
* Called after each persist to keep storage bounded.
|
|
1057
1216
|
*/
|
|
@@ -1509,9 +1668,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1509
1668
|
parts: []
|
|
1510
1669
|
};
|
|
1511
1670
|
this._streamingMessage = message;
|
|
1512
|
-
this._streamCompletionPromise = new Promise((resolve) => {
|
|
1513
|
-
this._streamCompletionResolve = resolve;
|
|
1514
|
-
});
|
|
1515
1671
|
const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
|
|
1516
1672
|
const streamCompleted = { value: false };
|
|
1517
1673
|
let earlyPersistedId = null;
|
|
@@ -1537,11 +1693,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1537
1693
|
this._streamingMessage = null;
|
|
1538
1694
|
earlyPersistedId = this._approvalPersistedMessageId;
|
|
1539
1695
|
this._approvalPersistedMessageId = null;
|
|
1540
|
-
if (this._streamCompletionResolve) {
|
|
1541
|
-
this._streamCompletionResolve();
|
|
1542
|
-
this._streamCompletionResolve = null;
|
|
1543
|
-
this._streamCompletionPromise = null;
|
|
1544
|
-
}
|
|
1545
1696
|
if (chatMessageId) {
|
|
1546
1697
|
this._removeAbortController(chatMessageId);
|
|
1547
1698
|
if (streamCompleted.value) this._emit("message:response");
|