Skip to content

Commit 6f5b640

Browse files
committed
fix: keep inbound metadata in runtime context
1 parent 2173d1b commit 6f5b640

4 files changed

Lines changed: 129 additions & 32 deletions

File tree

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

Lines changed: 49 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,6 +1197,7 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
11971197

11981198
it("adds current-turn context to the current model input without exposing internal runtime context", async () => {
11991199
let seenPrompt: string | undefined;
1200+
let seenMessages: unknown[] | undefined;
12001201

12011202
const result = await createContextEngineAttemptRunner({
12021203
contextEngine: createContextEngineBootstrapAndAssemble(),
@@ -1230,23 +1231,34 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
12301231
},
12311232
sessionPrompt: async (session, prompt) => {
12321233
seenPrompt = prompt;
1234+
seenMessages = [...session.messages];
12331235
session.messages = [
12341236
...session.messages,
12351237
{ role: "assistant", content: "done", timestamp: 2 },
12361238
];
12371239
},
12381240
});
12391241

1240-
expect(seenPrompt).toContain("what does this mean?");
1241-
expect(seenPrompt).toContain("Reply target of current user message (untrusted, for context):");
1242-
expect(seenPrompt).toContain('"sender_label": "Mike"');
1243-
expect(seenPrompt).toContain("WT daily plan - Sat May 2");
1244-
expect(seenPrompt).toContain("./quoted-secret.png");
1245-
expect(seenPrompt).toContain("media://inbound/quoted.png");
1242+
expect(seenPrompt).toBe("what does this mean?");
1243+
expect(seenPrompt).not.toContain(
1244+
"Reply target of current user message (untrusted, for context):",
1245+
);
12461246
expect(seenPrompt).not.toContain("OPENCLAW_INTERNAL_CONTEXT");
12471247
expect(seenPrompt).not.toContain("secret runtime context");
1248-
expect(seenPrompt?.trim().startsWith("Reply target of current user message")).toBe(true);
12491248
expect(result.finalPromptText).toBe(seenPrompt);
1249+
const runtimeContext = findRecord(
1250+
requireRecords(seenMessages, "seen messages"),
1251+
(message) => message.customType === "openclaw.runtime-context",
1252+
"runtime context message",
1253+
);
1254+
expect(runtimeContext.content).toContain(
1255+
"Reply target of current user message (untrusted, for context):",
1256+
);
1257+
expect(runtimeContext.content).toContain('"sender_label": "Mike"');
1258+
expect(runtimeContext.content).toContain("WT daily plan - Sat May 2");
1259+
expect(runtimeContext.content).toContain("./quoted-secret.png");
1260+
expect(runtimeContext.content).toContain("media://inbound/quoted.png");
1261+
expect(runtimeContext.content).toContain("secret runtime context");
12501262
expect(hoisted.detectAndLoadPromptImagesMock).toHaveBeenCalledTimes(1);
12511263
expect(mockParams(hoisted.detectAndLoadPromptImagesMock, 0, "prompt image params").prompt).toBe(
12521264
"what does this mean?",
@@ -1259,7 +1271,7 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
12591271
.map((line) => JSON.parse(line) as TrajectoryEvent);
12601272
const promptSubmitted = trajectoryEvents.find((event) => event.type === "prompt.submitted");
12611273
expect(promptSubmitted?.data?.prompt).toBe(seenPrompt);
1262-
expect(promptSubmitted?.data?.prompt).toContain("WT daily plan - Sat May 2");
1274+
expect(promptSubmitted?.data?.prompt).not.toContain("WT daily plan - Sat May 2");
12631275
expect(promptSubmitted?.data?.prompt).not.toContain("secret runtime context");
12641276
});
12651277

@@ -1459,6 +1471,7 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
14591471

14601472
it("keeps current inbound context visible on runtime-only turns", async () => {
14611473
let seenPrompt: string | undefined;
1474+
let seenSystemPrompt: string | undefined;
14621475

14631476
const result = await createContextEngineAttemptRunner({
14641477
contextEngine: createContextEngineBootstrapAndAssemble(),
@@ -1483,16 +1496,19 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
14831496
},
14841497
sessionPrompt: async (session, prompt) => {
14851498
seenPrompt = prompt;
1499+
seenSystemPrompt = session.agent.state.systemPrompt;
14861500
session.messages = [
14871501
...session.messages,
14881502
{ role: "assistant", content: "done", timestamp: 2 },
14891503
];
14901504
},
14911505
});
14921506

1493-
expect(seenPrompt).toContain("Reply target of current user message (untrusted, for context):");
1494-
expect(seenPrompt).toContain("Hello from the replied message");
1495-
expect(seenPrompt).toContain("Continue the OpenClaw runtime event.");
1507+
expect(seenPrompt).toBe("Continue the OpenClaw runtime event.");
1508+
expect(seenSystemPrompt).toContain(
1509+
"Reply target of current user message (untrusted, for context):",
1510+
);
1511+
expect(seenSystemPrompt).toContain("Hello from the replied message");
14961512
expect(result.finalPromptText).toBe(seenPrompt);
14971513
const trajectoryEvents = (
14981514
await fs.readFile(path.join(tempPaths[0] ?? "", "session.trajectory.jsonl"), "utf8")
@@ -1501,12 +1517,14 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
15011517
.split("\n")
15021518
.map((line) => JSON.parse(line) as TrajectoryEvent);
15031519
const contextCompiled = trajectoryEvents.find((event) => event.type === "context.compiled");
1504-
expect(contextCompiled?.data?.prompt).toContain("Hello from the replied message");
1520+
expect(contextCompiled?.data?.prompt).toBe("Continue the OpenClaw runtime event.");
15051521
expect(contextCompiled?.data?.systemPrompt).toContain("runtime bare mention event");
1522+
expect(contextCompiled?.data?.systemPrompt).toContain("Hello from the replied message");
15061523
});
15071524

1508-
it("submits suppressed room event context as the model prompt", async () => {
1525+
it("submits suppressed room event context as runtime context", async () => {
15091526
let seenPrompt: string | undefined;
1527+
let seenMessages: unknown[] | undefined;
15101528
let seenModelMessages: unknown[] | undefined;
15111529
const runBeforePromptBuild = vi.fn(async () => ({
15121530
prependContext: "dynamic hook context",
@@ -1541,6 +1559,7 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
15411559
},
15421560
sessionPrompt: async (session, prompt) => {
15431561
seenPrompt = prompt;
1562+
seenMessages = [...session.messages];
15441563
const transformContext = (
15451564
session.agent as {
15461565
transformContext?: (messages: AgentMessage[]) => Promise<AgentMessage[]>;
@@ -1556,14 +1575,23 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
15561575
},
15571576
});
15581577

1559-
expect(seenPrompt).toContain("[OpenClaw room event]");
1560-
expect(seenPrompt).toContain("inbound_event_kind: room_event");
1561-
expect(seenPrompt).toContain("visible_reply_contract: message_tool_only");
1562-
expect(seenPrompt).toContain("Current event:\n#2003 Bob: hey claw summarize the plan");
1563-
expect(seenPrompt?.trim().endsWith("[OpenClaw room event]")).toBe(true);
1578+
expect(seenPrompt).toBe("[OpenClaw room event]");
1579+
expect(seenPrompt).not.toContain("inbound_event_kind: room_event");
1580+
expect(seenPrompt).not.toContain("visible_reply_contract: message_tool_only");
1581+
expect(seenPrompt).not.toContain("Current event:\n#2003 Bob: hey claw summarize the plan");
15641582
expect(seenPrompt).not.toBe("Continue the OpenClaw runtime event.");
15651583
expect(seenPrompt).not.toContain("dynamic hook context");
15661584
expect(seenPrompt).not.toContain("dynamic hook tail");
1585+
const runtimeContext = findRecord(
1586+
requireRecords(seenMessages, "seen messages"),
1587+
(message) => message.customType === "openclaw.runtime-context",
1588+
"runtime context message",
1589+
);
1590+
expect(runtimeContext.content).toContain("inbound_event_kind: room_event");
1591+
expect(runtimeContext.content).toContain("visible_reply_contract: message_tool_only");
1592+
expect(runtimeContext.content).toContain(
1593+
"Current event:\n#2003 Bob: hey claw summarize the plan",
1594+
);
15671595
expect(JSON.stringify(seenModelMessages)).toContain("dynamic hook context");
15681596
expect(JSON.stringify(seenModelMessages)).toContain("dynamic hook tail");
15691597
expect(result.finalPromptText).toBe(seenPrompt);
@@ -1574,8 +1602,10 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
15741602
.split("\n")
15751603
.map((line) => JSON.parse(line) as TrajectoryEvent);
15761604
const contextCompiled = trajectoryEvents.find((event) => event.type === "context.compiled");
1577-
expect(contextCompiled?.data?.prompt).toContain("visible_reply_contract: message_tool_only");
15781605
expect(contextCompiled?.data?.prompt).toContain("[OpenClaw room event]");
1606+
expect(contextCompiled?.data?.prompt).not.toContain(
1607+
"visible_reply_contract: message_tool_only",
1608+
);
15791609
});
15801610

15811611
it("skips blank visible prompts with replay history before provider submission", async () => {

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

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -451,7 +451,6 @@ import {
451451
shouldPreemptivelyCompactBeforePrompt,
452452
} from "./preemptive-compaction.js";
453453
import {
454-
buildCurrentInboundPrompt,
455454
buildRuntimeContextCustomMessage,
456455
resolveRuntimeContextPromptParts,
457456
} from "./runtime-context-prompt.js";
@@ -3813,18 +3812,13 @@ export async function runEmbeddedAttempt(
38133812
modelPrompt: hasPromptBuildContext
38143813
? promptForModelBeforeRuntimeContextSplit
38153814
: undefined,
3815+
currentInboundContext: params.currentInboundContext,
38163816
emptyTranscriptMode: params.suppressNextUserMessagePersistence
38173817
? "model-prompt"
38183818
: "runtime-event",
38193819
});
3820-
const promptForSession = buildCurrentInboundPrompt({
3821-
context: params.currentInboundContext,
3822-
prompt: promptSubmission.prompt,
3823-
});
3824-
const promptForModel = buildCurrentInboundPrompt({
3825-
context: params.currentInboundContext,
3826-
prompt: promptSubmission.modelPrompt ?? promptSubmission.prompt,
3827-
});
3820+
const promptForSession = promptSubmission.prompt;
3821+
const promptForModel = promptSubmission.modelPrompt ?? promptSubmission.prompt;
38283822
const runtimeSystemContext = promptSubmission.runtimeSystemContext?.trim();
38293823
if (promptSubmission.runtimeOnly && runtimeSystemContext) {
38303824
const runtimeSystemPrompt = composeSystemPromptWithHookContext({

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

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,4 +354,62 @@ describe("runtime context prompt submission", () => {
354354
expect(buildRuntimeEventSystemContext("internal event")).toContain("OpenClaw runtime event.");
355355
expect(buildRuntimeEventSystemContext("internal event")).toContain("not user-authored");
356356
});
357+
358+
it("keeps current inbound metadata out of the visible user prompt", () => {
359+
const parts = resolveRuntimeContextPromptParts({
360+
effectivePrompt: "visible ask",
361+
transcriptPrompt: "visible ask",
362+
currentInboundContext: {
363+
text: 'Conversation info (untrusted metadata):\n```json\n{"message_id":"42"}\n```',
364+
},
365+
});
366+
expect(parts.prompt).toBe("visible ask");
367+
expect(parts.prompt).not.toContain("Conversation info");
368+
expect(parts.runtimeContext).toContain("Conversation info (untrusted metadata):");
369+
expect(parts.runtimeContext).toContain('"message_id":"42"');
370+
});
371+
372+
it("keeps current inbound metadata out of the model prompt", () => {
373+
const parts = resolveRuntimeContextPromptParts({
374+
effectivePrompt: "hook context\n\nvisible ask\n\nhook tail",
375+
transcriptPrompt: "visible ask",
376+
modelPrompt: "hook context\n\nvisible ask\n\nhook tail",
377+
currentInboundContext: {
378+
text: 'Sender (untrusted metadata):\n```json\n{"id":"u1"}\n```',
379+
},
380+
});
381+
const modelPrompt = parts.modelPrompt ?? parts.prompt;
382+
expect(modelPrompt).toBe("hook context\n\nvisible ask\n\nhook tail");
383+
expect(modelPrompt).not.toContain("Sender (untrusted metadata)");
384+
expect(parts.runtimeContext).toContain("Sender (untrusted metadata):");
385+
});
386+
387+
it("combines current inbound metadata with extracted hidden runtime context", () => {
388+
const parts = resolveRuntimeContextPromptParts({
389+
effectivePrompt:
390+
"visible ask\n\n__openclaw_runtime_context__\ninternal block\n__/openclaw_runtime_context__",
391+
transcriptPrompt: "visible ask",
392+
currentInboundContext: {
393+
text: "Conversation info (untrusted metadata):\n```json\n{}\n```",
394+
},
395+
});
396+
expect(parts.prompt).toBe("visible ask");
397+
expect(parts.runtimeContext).toContain("Conversation info (untrusted metadata):");
398+
expect(parts.runtimeContext).toContain("internal block");
399+
});
400+
401+
it("preserves current inbound metadata in the empty-transcript model-prompt branch", () => {
402+
const parts = resolveRuntimeContextPromptParts({
403+
effectivePrompt: "[OpenClaw room event]",
404+
transcriptPrompt: "",
405+
emptyTranscriptMode: "model-prompt",
406+
currentInboundContext: {
407+
text: "Room context:\nAlice: hi\n\nCurrent event:\nBob: hi",
408+
},
409+
});
410+
expect(parts.prompt).toBe("[OpenClaw room event]");
411+
expect(parts.prompt).not.toContain("Room context:");
412+
expect(parts.runtimeContext).toContain("Room context:");
413+
expect(parts.runtimeContext).toContain("Current event:\nBob: hi");
414+
});
357415
});

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

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ export function resolveRuntimeContextPromptParts(params: {
8282
effectivePrompt: string;
8383
transcriptPrompt?: string;
8484
modelPrompt?: string;
85+
currentInboundContext?: CurrentInboundPromptContext;
8586
emptyTranscriptMode?: EmptyTranscriptMode;
8687
}): RuntimeContextPromptParts {
8788
const transcriptPrompt = params.transcriptPrompt;
@@ -97,13 +98,20 @@ export function resolveRuntimeContextPromptParts(params: {
9798
: { text: params.modelPrompt };
9899
const modelPromptText = modelPrompt?.text ?? transcriptPrompt ?? extracted.text;
99100
const prompt = transcriptPrompt ?? extracted.text;
101+
const currentInboundContextText = buildCurrentInboundPromptContextPrefix(
102+
params.currentInboundContext,
103+
);
100104
if (!prompt.trim() && params.emptyTranscriptMode === "model-prompt") {
105+
const runtimeContext =
106+
[currentInboundContextText, extracted.runtimeContext]
107+
.filter((value): value is string => Boolean(value?.trim()))
108+
.join("\n\n") || undefined;
101109
return {
102110
prompt: extracted.text,
103111
...(modelPromptText.trim() && modelPromptText !== extracted.text
104112
? { modelPrompt: modelPromptText }
105113
: {}),
106-
...(extracted.runtimeContext ? { runtimeContext: extracted.runtimeContext } : {}),
114+
...(runtimeContext ? { runtimeContext } : {}),
107115
};
108116
}
109117
const hiddenRuntimeContext = modelPrompt
@@ -116,10 +124,17 @@ export function resolveRuntimeContextPromptParts(params: {
116124
: undefined;
117125
// The hidden context is whatever remains after removing the last visible
118126
// prompt occurrence, plus any explicit internal runtime-context block.
127+
const runtimeContextParts = [
128+
currentInboundContextText,
129+
hiddenRuntimeContext,
130+
extracted.runtimeContext,
131+
];
132+
if (!prompt.trim()) {
133+
runtimeContextParts.push(extracted.text);
134+
}
119135
const runtimeContext =
120-
[hiddenRuntimeContext, extracted.runtimeContext]
121-
.filter((value): value is string => Boolean(value?.trim()))
122-
.join("\n\n") || (!prompt.trim() ? extracted.text.trim() : undefined);
136+
runtimeContextParts.filter((value): value is string => Boolean(value?.trim())).join("\n\n") ||
137+
(!prompt.trim() ? extracted.text.trim() : undefined);
123138
if (!prompt.trim()) {
124139
return runtimeContext
125140
? {

0 commit comments

Comments
 (0)