Skip to content

Commit b6de8d5

Browse files
authored
improve(agents): reduce per-turn conversation metadata tokens (#113616)
* perf(agents): trim per-turn conversation metadata tokens * test(agents): expect compact supplemental metadata * test(agents): cover compact persisted sender metadata
1 parent 7e80f36 commit b6de8d5

13 files changed

Lines changed: 139 additions & 151 deletions

‎src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ describe("prepareEmbeddedAttemptPromptContext", () => {
170170

171171
const result = prepareEmbeddedAttemptPromptContext(fixture.input);
172172

173-
expect(result.llmBoundaryPromptForPrecheck).toContain('"name": "Alice"');
173+
expect(result.llmBoundaryPromptForPrecheck).toContain('"name":"Alice"');
174174
expect(result.llmBoundaryPromptForPrecheck).toContain("Visible request");
175175
});
176176

‎src/agents/embedded-agent-runner/run/attempt-session-boundary.test.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ describe("prepareEmbeddedAttemptSessionBoundary", () => {
162162

163163
const converted = await activeSession.agent.convertToLlm([runtimeMessage]);
164164

165-
expect((converted[0] as { content?: unknown }).content).toContain('"name": "Alice"');
165+
expect((converted[0] as { content?: unknown }).content).toContain('"name":"Alice"');
166166
});
167167

168168
it("retains sender projection for earlier in-memory turns after a queued turn", async () => {
@@ -208,8 +208,8 @@ describe("prepareEmbeddedAttemptSessionBoundary", () => {
208208

209209
const converted = await activeSession.agent.convertToLlm([initialRuntime, queuedRuntime]);
210210

211-
expect((converted[0] as { content?: unknown }).content).toContain('"name": "Alice"');
212-
expect((converted[1] as { content?: unknown }).content).toContain('"name": "Bob"');
211+
expect((converted[0] as { content?: unknown }).content).toContain('"name":"Alice"');
212+
expect((converted[1] as { content?: unknown }).content).toContain('"name":"Bob"');
213213
});
214214

215215
it("reserves exact pairings before matching duplicate timestamp and text", async () => {
@@ -255,8 +255,8 @@ describe("prepareEmbeddedAttemptSessionBoundary", () => {
255255

256256
const converted = await activeSession.agent.convertToLlm([firstRuntime, secondRuntime]);
257257

258-
expect((converted[0] as { content?: unknown }).content).toContain('"name": "Alice"');
259-
expect((converted[1] as { content?: unknown }).content).toContain('"name": "Bob"');
258+
expect((converted[0] as { content?: unknown }).content).toContain('"name":"Alice"');
259+
expect((converted[1] as { content?: unknown }).content).toContain('"name":"Bob"');
260260
});
261261

262262
it("repairs an orphaned user leaf before rebuilding active session messages", () => {

‎src/agents/embedded-agent-runner/run/attempt.llm-boundary.cache-stability.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -640,7 +640,7 @@ describe("prompt-cache tail carrier for current-turn metadata (issue #100271)",
640640
const historicalContent = (asHistorical[0] as { content?: unknown } | undefined)?.content;
641641
expect(JSON.stringify(currentContent)).toBe(JSON.stringify(historicalContent));
642642
expect(typeof currentContent).toBe("string");
643-
expect(currentContent).toContain('"name": "Alice"');
643+
expect(currentContent).toContain('"name":"Alice"');
644644
expect(
645645
normalizeMessagesForLlmBoundary(asCurrent, {
646646
timezone: TZ,

‎src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ describe("normalizeMessagesForLlmBoundary", () => {
112112
[
113113
"Conversation info (untrusted metadata):",
114114
"```json",
115-
'{\n "sender": {\n "id": "alice-id",\n "name": "Alice",\n "username": "alice"\n }\n}',
115+
'{"sender":{"id":"alice-id","name":"Alice","username":"alice"}}',
116116
"```",
117117
"",
118118
"The launch is Friday",
@@ -122,7 +122,7 @@ describe("normalizeMessagesForLlmBoundary", () => {
122122
[
123123
"Conversation info (untrusted metadata):",
124124
"```json",
125-
'{\n "sender": {\n "id": "bob-id",\n "name": "Bob"\n }\n}',
125+
'{"sender":{"id":"bob-id","name":"Bob"}}',
126126
"```",
127127
"",
128128
"Who said the launch is Friday?",
@@ -648,8 +648,8 @@ describe("normalizeMessagesForLlmBoundary", () => {
648648
const content = output[0]?.content ?? "";
649649

650650
expect(content.match(/Conversation info \(untrusted metadata\):/g)).toHaveLength(1);
651-
expect(content).toContain('"channel": "discord"');
652-
expect(content).toContain('"name": "Alice"');
651+
expect(content).toContain('"channel":"discord"');
652+
expect(content).toContain('"name":"Alice"');
653653
expect(content).toContain("Current ask");
654654
});
655655

‎src/agents/embedded-agent-runner/run/attempt.spawn-workspace.context-engine.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3576,7 +3576,7 @@ describe("runEmbeddedAttempt tool-result guard budget wiring", () => {
35763576

35773577
expect(submittedMessages.filter((message) => message.role === "user")).toEqual([
35783578
expect.objectContaining({
3579-
content: expect.stringContaining('"name": "Alice"'),
3579+
content: expect.stringContaining('"name":"Alice"'),
35803580
role: "user",
35813581
}),
35823582
]);

‎src/agents/prompt-composition.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ describe("prompt composition invariants", () => {
121121
const inboundBody = "Please summarize the deploy log.";
122122

123123
expect(turn.bodyPrompt).toContain("Discord channel metadata (untrusted metadata):");
124-
expect(turn.bodyPrompt).toContain('"topic": "Deploy coordination"');
124+
expect(turn.bodyPrompt).toContain('"topic":"Deploy coordination"');
125125
expect(turn.bodyPrompt).not.toContain("EXTERNAL_UNTRUSTED_CONTENT");
126126
expect(countOccurrences(turn.bodyPrompt, inboundBody)).toBe(1);
127127
expect(turn.systemPrompt).not.toContain(inboundBody);

‎src/auto-reply/reply/inbound-meta.test.ts‎

Lines changed: 69 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ describe("buildInboundMetaSystemPrompt", () => {
219219
expect(payload["flags"]).toBeUndefined();
220220
});
221221

222-
it("keeps explicit bot mentions out of the system metadata", () => {
222+
it("keeps bot usernames out of the system metadata and includes standing mention guidance", () => {
223223
const prompt = buildInboundMetaSystemPrompt(
224224
{
225225
OriginatingTo: "telegram:-1001249586642",
@@ -236,7 +236,9 @@ describe("buildInboundMetaSystemPrompt", () => {
236236
const payload = parseInboundMetaPayload(prompt);
237237
expect(payload["flags"]).toBeUndefined();
238238
expect(prompt).not.toContain("SirPinchALotBot");
239-
expect(prompt).not.toContain("explicitly mentions your channel identity");
239+
expect(prompt).toContain(
240+
"When explicitly_mentioned_bot is true, the incoming message mentions your channel identity; treat it as addressed to you even if your persona name differs.",
241+
);
240242
});
241243

242244
it("omits sender_id when blank", () => {
@@ -605,7 +607,7 @@ describe("buildInboundUserContextPrefix", () => {
605607
} as TemplateContext);
606608

607609
expect(text).toContain("Conversation info (untrusted metadata):");
608-
expect(text).toContain('"conversation_label": "ops-room"');
610+
expect(text).toContain('"conversation_label":"ops-room"');
609611
});
610612

611613
it("renders group subject and participants as untrusted metadata", () => {
@@ -779,52 +781,58 @@ describe("buildInboundUserContextPrefix", () => {
779781
});
780782

781783
it("renders hydrated reply chain instead of duplicate one-hop reply target", () => {
782-
const text = buildInboundUserContextPrefix({
783-
ReplyToSender: "Blair",
784-
ReplyToBody: "The cache warmer is the piece I meant.",
785-
ReplyChain: [
786-
{
787-
messageId: "3001",
788-
sender: "Blair",
789-
senderId: "700002",
790-
timestamp: 1778216405000,
791-
body: "The cache warmer is the piece I meant.",
792-
replyToId: "3000",
793-
},
794-
{
795-
messageId: "3000",
796-
sender: "Avery",
797-
senderId: "700001",
798-
timestamp: 1778216400000,
799-
body: "Architecture sketch for the cache warmer",
800-
mediaType: "image",
801-
mediaRef: "telegram:file/proof-photo-small",
802-
},
803-
],
804-
} as TemplateContext);
784+
const text = buildInboundUserContextPrefix(
785+
{
786+
ReplyToSender: "Blair",
787+
ReplyToBody: "The cache warmer is the piece I meant.",
788+
ReplyChain: [
789+
{
790+
messageId: "3001",
791+
sender: "Blair",
792+
senderId: "700002",
793+
timestamp: 1778216405000,
794+
body: "The cache warmer is the piece I meant.",
795+
replyToId: "3000",
796+
forwardedFrom: "Morgan",
797+
forwardedDate: 1778212800000,
798+
},
799+
{
800+
messageId: "3000",
801+
sender: "Avery",
802+
senderId: "700001",
803+
timestamp: 1778216400000,
804+
body: "Architecture sketch for the cache warmer",
805+
mediaType: "image",
806+
mediaRef: "telegram:file/proof-photo-small",
807+
},
808+
],
809+
} as TemplateContext,
810+
{ timezone: "UTC" },
811+
);
805812

806813
const replyChain = parseReplyChainPayload(text);
807814
expect(replyChain).toEqual([
808815
{
809816
message_id: "3001",
810817
sender: "Blair",
811818
sender_id: "700002",
812-
timestamp_ms: 1778216405000,
819+
timestamp: "2026-05-08T05:00:05Z",
813820
body: "The cache warmer is the piece I meant.",
814821
reply_to_id: "3000",
822+
forwarded_from: "Morgan",
823+
forwarded_date: "2026-05-08T04:00:00Z",
815824
},
816825
{
817826
message_id: "3000",
818827
sender: "Avery",
819828
sender_id: "700001",
820-
timestamp_ms: 1778216400000,
829+
timestamp: "2026-05-08T05:00:00Z",
821830
body: "Architecture sketch for the cache warmer",
822831
media_type: "image",
823832
media_ref: "telegram:file/proof-photo-small",
824833
},
825834
]);
826835
expect(text).not.toContain("Reply target of current user message");
827-
expect(parseConversationInfoPayload(text)["has_reply_context"]).toBe(true);
828836
});
829837

830838
it("renders Telegram replies as an inline current-message quote", () => {
@@ -940,6 +948,29 @@ describe("buildInboundUserContextPrefix", () => {
940948
expect(conversationInfo["sender"]).toEqual({ e164: "+15551234567" });
941949
});
942950

951+
it("omits e164 when it repeats the sender id digits", () => {
952+
const text = buildInboundUserContextPrefix({
953+
ChatType: "group",
954+
SenderId: "15551234567",
955+
SenderE164: "+1 (555) 123-4567",
956+
} as TemplateContext);
957+
958+
expect(parseConversationInfoPayload(text)["sender"]).toEqual({ id: "15551234567" });
959+
});
960+
961+
it("keeps e164 when it differs from the sender id digits", () => {
962+
const text = buildInboundUserContextPrefix({
963+
ChatType: "group",
964+
SenderId: "15550001111",
965+
SenderE164: "+15551234567",
966+
} as TemplateContext);
967+
968+
expect(parseConversationInfoPayload(text)["sender"]).toEqual({
969+
id: "15550001111",
970+
e164: "+15551234567",
971+
});
972+
});
973+
943974
it("includes dynamic per-turn flags in conversation info", () => {
944975
const text = buildInboundUserContextPrefix({
945976
ChatType: "group",
@@ -965,9 +996,6 @@ describe("buildInboundUserContextPrefix", () => {
965996
expect(conversationInfo["mentioned_subteam_ids"]).toEqual(["S_ONCALL"]);
966997
expect(conversationInfo["implicit_mention_kinds"]).toEqual(["bot_thread_participant"]);
967998
expect(conversationInfo["mention_source"]).toBe("implicit_thread");
968-
expect(conversationInfo["has_reply_context"]).toBe(true);
969-
expect(conversationInfo["has_forwarded_context"]).toBe(true);
970-
expect(conversationInfo["has_thread_starter"]).toBe(true);
971999
expect(conversationInfo["history_count"]).toBe(1);
9721000
});
9731001

@@ -980,8 +1008,7 @@ describe("buildInboundUserContextPrefix", () => {
9801008

9811009
const conversationInfo = parseConversationInfoPayload(text);
9821010
expect(conversationInfo["explicitly_mentioned_bot"]).toBe(true);
983-
expect(text).toContain("explicitly mentions your channel identity @SirPinchALotBot");
984-
expect(text).toContain("Treat that mention as addressed to you");
1011+
expect(text).not.toContain("SirPinchALotBot");
9851012
});
9861013

9871014
it("trims sender_id in conversation info", () => {
@@ -1034,11 +1061,11 @@ describe("buildInboundUserContextPrefix", () => {
10341061
});
10351062
expect(conversationInfo["topic_id"]).toBe("thread--1");
10361063

1037-
expect(text).toContain('"body": "thread starter"');
1038-
expect(text).toContain('"sender_label": "Quoter"');
1039-
expect(text).toContain('"body": "quoted body"');
1040-
expect(text).toContain('"from": "forwarder"');
1041-
expect(text).toContain('"title": "title"');
1064+
expect(text).toContain('"body":"thread starter"');
1065+
expect(text).toContain('"sender_label":"Quoter"');
1066+
expect(text).toContain('"body":"quoted body"');
1067+
expect(text).toContain('"from":"forwarder"');
1068+
expect(text).toContain('"title":"title"');
10421069
expect(text).toContain("history: body text");
10431070
});
10441071

@@ -1179,7 +1206,7 @@ describe("buildInboundUserContextPrefix", () => {
11791206
expect(text).not.toContain("telegram:file/old-provider-ref");
11801207
expect(text).not.toContain("/home/user/.openclaw/media/inbound/sticker.webp");
11811208
expect(text).not.toContain("Current local chat window (untrusted metadata):");
1182-
expect(text).not.toContain('"message_id": "34273"');
1209+
expect(text).not.toContain('"message_id":"34273"');
11831210
});
11841211

11851212
it("honors timestamp suppression for chat window structured context", () => {
@@ -1366,7 +1393,7 @@ describe("buildInboundUserContextPrefix", () => {
13661393
} as TemplateContext);
13671394

13681395
expect(withForwardedFrom).toContain("Forwarded message context (untrusted metadata):");
1369-
expect(withForwardedFrom).toContain('"from": "source"');
1396+
expect(withForwardedFrom).toContain('"from":"source"');
13701397
});
13711398

13721399
it("truncates oversized untrusted strings before serializing them into prompt context", () => {
@@ -1378,7 +1405,7 @@ describe("buildInboundUserContextPrefix", () => {
13781405

13791406
expect(text).not.toContain(oversized);
13801407
expect(text).toContain("…[truncated]");
1381-
expect(text).toContain('"body": "');
1408+
expect(text).toContain('"body":"');
13821409
});
13831410

13841411
it("preserves tail content in ReplyChain body via head+tail truncation", () => {
@@ -1508,9 +1535,6 @@ describe("buildInboundUserContextPrefix", () => {
15081535
],
15091536
} as TemplateContext);
15101537

1511-
const conversationInfo = parseConversationInfoPayload(text);
1512-
expect(conversationInfo["history_media_count"]).toBe(1);
1513-
15141538
expect(text).toContain("#m-1");
15151539
expect(text).toContain("Alice: <media:image> (1 image) [image/png]");
15161540
expect(text).not.toContain("/tmp/openclaw-secret-image.png");
@@ -1546,9 +1570,6 @@ describe("buildInboundUserContextPrefix", () => {
15461570
],
15471571
} as TemplateContext);
15481572

1549-
const conversationInfo = parseConversationInfoPayload(text);
1550-
expect(conversationInfo["history_media_count"]).toBe(2);
1551-
15521573
expect(text).toContain("#m-2");
15531574
expect(text).toContain("Alice: <media:image> (2 images) [image/png, image/jpeg]");
15541575
expect(text).not.toContain("/tmp/openclaw-secret-image-1.png");

0 commit comments

Comments
 (0)