@cloudflare/ai-chat 0.1.8 → 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/ai-chat-v5-migration.js +1 -1
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/experimental/forever.d.ts +2 -16
- package/dist/experimental/forever.js +1 -1
- package/dist/experimental/forever.js.map +1 -1
- package/dist/index-B09l5oPB.d.ts +699 -0
- package/dist/index.d.ts +5 -470
- package/dist/index.js +287 -138
- package/dist/index.js.map +1 -1
- package/dist/{message-builder-uSvexDl2.js → message-builder-BAgcFJMf.js} +2 -2
- package/dist/{message-builder-uSvexDl2.js.map → message-builder-BAgcFJMf.js.map} +1 -1
- package/dist/react.js +21 -12
- package/dist/react.js.map +1 -1
- package/dist/types.js +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +5 -5
- package/dist/resumable-stream-DTLAk9XC.d.ts +0 -126
package/dist/index.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { MessageType } from "./types.js";
|
|
2
2
|
import { autoTransformMessages } from "./ai-chat-v5-migration.js";
|
|
3
|
-
import { t as applyChunkToParts } from "./message-builder-
|
|
3
|
+
import { t as applyChunkToParts } from "./message-builder-BAgcFJMf.js";
|
|
4
4
|
import { jsonSchema, tool } from "ai";
|
|
5
5
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
6
6
|
import { nanoid } from "nanoid";
|
|
7
|
-
|
|
8
7
|
//#region src/resumable-stream.ts
|
|
9
8
|
/**
|
|
10
9
|
* ResumableStream: Standalone class for buffering, persisting, and replaying
|
|
@@ -332,11 +331,17 @@ var ResumableStream = class ResumableStream {
|
|
|
332
331
|
`;
|
|
333
332
|
}
|
|
334
333
|
};
|
|
335
|
-
|
|
336
334
|
//#endregion
|
|
337
335
|
//#region src/index.ts
|
|
338
336
|
/** Shared encoder for UTF-8 byte length measurement */
|
|
339
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;
|
|
340
345
|
/**
|
|
341
346
|
* Validates that a parsed message has the minimum required structure.
|
|
342
347
|
* Returns false for messages that would cause runtime errors downstream
|
|
@@ -407,9 +412,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
407
412
|
constructor(ctx, env) {
|
|
408
413
|
super(ctx, env);
|
|
409
414
|
this._streamingMessage = null;
|
|
415
|
+
this._pendingInteractionPromise = null;
|
|
410
416
|
this._approvalPersistedMessageId = null;
|
|
411
|
-
this.
|
|
412
|
-
this.
|
|
417
|
+
this._chatTurnQueue = Promise.resolve();
|
|
418
|
+
this._activeChatTurnRequestId = null;
|
|
419
|
+
this._chatEpoch = 0;
|
|
413
420
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
414
421
|
this._persistedMessageCache = /* @__PURE__ */ new Map();
|
|
415
422
|
this.maxPersistedMessages = void 0;
|
|
@@ -439,7 +446,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
439
446
|
};
|
|
440
447
|
const _onMessage = this.onMessage.bind(this);
|
|
441
448
|
this.onMessage = async (connection, message) => {
|
|
442
|
-
await this.mcp.ensureJsonSchema();
|
|
443
449
|
if (typeof message === "string") {
|
|
444
450
|
let data;
|
|
445
451
|
try {
|
|
@@ -448,10 +454,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
448
454
|
return _onMessage(connection, message);
|
|
449
455
|
}
|
|
450
456
|
if (data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST && data.init.method === "POST") {
|
|
451
|
-
if (this.waitForMcpConnections) {
|
|
452
|
-
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
|
|
453
|
-
await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
|
|
454
|
-
}
|
|
455
457
|
const { body } = data.init;
|
|
456
458
|
if (!body) {
|
|
457
459
|
console.warn("[AIChatAgent] Received chat request with empty body, ignoring");
|
|
@@ -465,46 +467,52 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
465
467
|
return;
|
|
466
468
|
}
|
|
467
469
|
const { messages, clientTools, trigger: _trigger, ...customBody } = parsed;
|
|
468
|
-
this._lastClientTools = clientTools?.length ? clientTools : void 0;
|
|
469
|
-
this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
470
|
-
this._persistRequestContext();
|
|
471
|
-
const transformedMessages = autoTransformMessages(messages);
|
|
472
|
-
this._broadcastChatMessage({
|
|
473
|
-
messages: transformedMessages,
|
|
474
|
-
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
475
|
-
}, [connection.id]);
|
|
476
|
-
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
477
|
-
this._emit("message:request");
|
|
478
470
|
const chatMessageId = data.id;
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
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
|
+
}
|
|
492
510
|
});
|
|
493
|
-
if (response) await this._reply(data.id, response, [connection.id], { chatMessageId });
|
|
494
|
-
else {
|
|
495
|
-
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
496
|
-
this._broadcastChatMessage({
|
|
497
|
-
body: "No response was generated by the agent.",
|
|
498
|
-
done: true,
|
|
499
|
-
id: data.id,
|
|
500
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
501
|
-
}, [connection.id]);
|
|
502
|
-
}
|
|
503
511
|
});
|
|
504
512
|
});
|
|
505
513
|
}
|
|
506
514
|
if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
|
|
507
|
-
this.
|
|
515
|
+
this.resetTurnState();
|
|
508
516
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
509
517
|
this._resumableStream.clearAll();
|
|
510
518
|
this._pendingResumeConnections.clear();
|
|
@@ -551,39 +559,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
551
559
|
toolCallId,
|
|
552
560
|
toolName
|
|
553
561
|
});
|
|
554
|
-
this._applyToolResult(toolCallId, toolName, output, overrideState, errorText)
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
waitForStream().then(() => {
|
|
561
|
-
const continuationId = nanoid();
|
|
562
|
-
const abortSignal = this._getAbortSignal(continuationId);
|
|
563
|
-
return this._tryCatchChat(async () => {
|
|
564
|
-
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
565
|
-
agent: this,
|
|
566
|
-
connection,
|
|
567
|
-
request: void 0,
|
|
568
|
-
email: void 0
|
|
569
|
-
}, async () => {
|
|
570
|
-
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
571
|
-
requestId: continuationId,
|
|
572
|
-
abortSignal,
|
|
573
|
-
clientTools: clientTools ?? this._lastClientTools,
|
|
574
|
-
body: this._lastBody
|
|
575
|
-
});
|
|
576
|
-
if (response) await this._reply(continuationId, response, [], {
|
|
577
|
-
continuation: true,
|
|
578
|
-
chatMessageId: continuationId
|
|
579
|
-
});
|
|
580
|
-
});
|
|
581
|
-
});
|
|
582
|
-
}).catch((error) => {
|
|
583
|
-
console.error("[AIChatAgent] Tool continuation failed:", error);
|
|
584
|
-
});
|
|
585
|
-
}
|
|
586
|
-
});
|
|
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);
|
|
587
568
|
return;
|
|
588
569
|
}
|
|
589
570
|
if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
|
|
@@ -592,39 +573,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
592
573
|
toolCallId,
|
|
593
574
|
approved
|
|
594
575
|
});
|
|
595
|
-
this._applyToolApproval(toolCallId, approved)
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
waitForStream().then(() => {
|
|
602
|
-
const continuationId = nanoid();
|
|
603
|
-
const abortSignal = this._getAbortSignal(continuationId);
|
|
604
|
-
return this._tryCatchChat(async () => {
|
|
605
|
-
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
606
|
-
agent: this,
|
|
607
|
-
connection,
|
|
608
|
-
request: void 0,
|
|
609
|
-
email: void 0
|
|
610
|
-
}, async () => {
|
|
611
|
-
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
612
|
-
requestId: continuationId,
|
|
613
|
-
abortSignal,
|
|
614
|
-
clientTools: this._lastClientTools,
|
|
615
|
-
body: this._lastBody
|
|
616
|
-
});
|
|
617
|
-
if (response) await this._reply(continuationId, response, [], {
|
|
618
|
-
continuation: true,
|
|
619
|
-
chatMessageId: continuationId
|
|
620
|
-
});
|
|
621
|
-
});
|
|
622
|
-
});
|
|
623
|
-
}).catch((error) => {
|
|
624
|
-
console.error("[AIChatAgent] Tool approval continuation failed:", error);
|
|
625
|
-
});
|
|
626
|
-
}
|
|
627
|
-
});
|
|
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);
|
|
628
582
|
return;
|
|
629
583
|
}
|
|
630
584
|
}
|
|
@@ -796,6 +750,120 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
796
750
|
throw this.onError(e);
|
|
797
751
|
}
|
|
798
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
|
+
}
|
|
799
867
|
/**
|
|
800
868
|
* Handle incoming chat messages and generate a response
|
|
801
869
|
* @param onFinish Callback to be called when the response is finished
|
|
@@ -806,21 +874,61 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
806
874
|
throw new Error("received a chat message, override onChatMessage and return a Response to send to the client");
|
|
807
875
|
}
|
|
808
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
|
+
/**
|
|
809
911
|
* Save messages on the server side
|
|
810
912
|
* @param messages Chat messages to save
|
|
811
913
|
*/
|
|
812
914
|
async saveMessages(messages) {
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
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 });
|
|
822
931
|
});
|
|
823
|
-
if (response) this._reply(requestId, response);
|
|
824
932
|
});
|
|
825
933
|
}
|
|
826
934
|
async persistMessages(messages, excludeBroadcastIds = [], options) {
|
|
@@ -955,17 +1063,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
955
1063
|
}
|
|
956
1064
|
/**
|
|
957
1065
|
* Resolves a message for persistence, handling tool result merging.
|
|
958
|
-
* If the message contains tool parts with
|
|
959
|
-
*
|
|
960
|
-
*
|
|
961
|
-
*
|
|
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).
|
|
962
1072
|
*
|
|
963
1073
|
* @param message - The message to potentially merge
|
|
964
1074
|
* @returns The message with the correct ID (either original or merged)
|
|
965
1075
|
*/
|
|
966
1076
|
_resolveMessageForToolMerge(message) {
|
|
967
1077
|
if (message.role !== "assistant") return message;
|
|
968
|
-
for (const part of message.parts) if ("toolCallId" in part &&
|
|
1078
|
+
for (const part of message.parts) if ("toolCallId" in part && part.toolCallId) {
|
|
969
1079
|
const toolCallId = part.toolCallId;
|
|
970
1080
|
const existingMessage = this._findMessageByToolCallId(toolCallId);
|
|
971
1081
|
if (existingMessage && existingMessage.id !== message.id) return {
|
|
@@ -993,19 +1103,27 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
993
1103
|
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
994
1104
|
* data that should not be stored or sent back in subsequent requests.
|
|
995
1105
|
*
|
|
996
|
-
*
|
|
1106
|
+
* Pipeline:
|
|
997
1107
|
*
|
|
998
1108
|
* 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
|
|
999
1109
|
* (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
|
|
1000
1110
|
* itemIds and reasoningEncryptedContent to message parts. When persisted
|
|
1001
1111
|
* and sent back, OpenAI rejects duplicate itemIds.
|
|
1002
1112
|
*
|
|
1003
|
-
* 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
|
|
1004
1119
|
* with no text and no remaining providerMetadata are removed. Parts that
|
|
1005
1120
|
* still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
|
|
1006
1121
|
* with providerMetadata.anthropic.redactedData) are preserved, as they
|
|
1007
1122
|
* contain data required for round-tripping with the provider API.
|
|
1008
1123
|
*
|
|
1124
|
+
* 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
|
|
1125
|
+
* method, allowing subclasses to apply custom transformations.
|
|
1126
|
+
*
|
|
1009
1127
|
* @param message - The message to sanitize
|
|
1010
1128
|
* @returns A new message with ephemeral provider data removed
|
|
1011
1129
|
*/
|
|
@@ -1014,6 +1132,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1014
1132
|
let sanitizedPart = part;
|
|
1015
1133
|
if ("providerMetadata" in sanitizedPart && sanitizedPart.providerMetadata && typeof sanitizedPart.providerMetadata === "object" && "openai" in sanitizedPart.providerMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "providerMetadata");
|
|
1016
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);
|
|
1017
1136
|
return sanitizedPart;
|
|
1018
1137
|
}).filter((part) => {
|
|
1019
1138
|
if (part.type === "reasoning") {
|
|
@@ -1025,10 +1144,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1025
1144
|
}
|
|
1026
1145
|
return true;
|
|
1027
1146
|
});
|
|
1028
|
-
return {
|
|
1147
|
+
return this.sanitizeMessageForPersistence({
|
|
1029
1148
|
...message,
|
|
1030
1149
|
parts: sanitizedParts
|
|
1031
|
-
};
|
|
1150
|
+
});
|
|
1032
1151
|
}
|
|
1033
1152
|
/**
|
|
1034
1153
|
* Helper to strip OpenAI-specific ephemeral fields from a metadata object.
|
|
@@ -1054,6 +1173,44 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1054
1173
|
return restPart;
|
|
1055
1174
|
}
|
|
1056
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
|
+
/**
|
|
1057
1214
|
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
1058
1215
|
* Called after each persist to keep storage bounded.
|
|
1059
1216
|
*/
|
|
@@ -1511,9 +1668,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1511
1668
|
parts: []
|
|
1512
1669
|
};
|
|
1513
1670
|
this._streamingMessage = message;
|
|
1514
|
-
this._streamCompletionPromise = new Promise((resolve) => {
|
|
1515
|
-
this._streamCompletionResolve = resolve;
|
|
1516
|
-
});
|
|
1517
1671
|
const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
|
|
1518
1672
|
const streamCompleted = { value: false };
|
|
1519
1673
|
let earlyPersistedId = null;
|
|
@@ -1539,11 +1693,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1539
1693
|
this._streamingMessage = null;
|
|
1540
1694
|
earlyPersistedId = this._approvalPersistedMessageId;
|
|
1541
1695
|
this._approvalPersistedMessageId = null;
|
|
1542
|
-
if (this._streamCompletionResolve) {
|
|
1543
|
-
this._streamCompletionResolve();
|
|
1544
|
-
this._streamCompletionResolve = null;
|
|
1545
|
-
this._streamCompletionPromise = null;
|
|
1546
|
-
}
|
|
1547
1696
|
if (chatMessageId) {
|
|
1548
1697
|
this._removeAbortController(chatMessageId);
|
|
1549
1698
|
if (streamCompleted.value) this._emit("message:response");
|
|
@@ -1610,7 +1759,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1610
1759
|
await super.destroy();
|
|
1611
1760
|
}
|
|
1612
1761
|
};
|
|
1613
|
-
|
|
1614
1762
|
//#endregion
|
|
1615
1763
|
export { AIChatAgent, createToolsFromClientSchemas };
|
|
1764
|
+
|
|
1616
1765
|
//# sourceMappingURL=index.js.map
|