Skip to content

Commit 11e6928

Browse files
committed
fix: keep runtime context out of user turns
1 parent b9fd13e commit 11e6928

12 files changed

Lines changed: 265 additions & 44 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Docs: https://docs.openclaw.ai
1818

1919
- Channels/sessions: prevent guarded inbound session recording from creating route-only phantom sessions while still allowing last-route updates for sessions that already exist. Carries forward #73009. Thanks @jzakirov.
2020
- Plugins/runtime deps: stage bundled plugin dependencies imported by mirrored root dist chunks, so packaged memory and status commands do not miss `chokidar` or similar root-chunk dependencies after update. Fixes #72882 and #72970; carries forward #72992. Thanks @shrimpy8, @colin-chang, and @Schnup03.
21+
- Agents/runtime context: deliver hidden runtime context through prompt-local system context while keeping the transcript-only custom entry out of provider user turns, and strip stale copied runtime-context prefaces from user-facing replies. Fixes #72386; carries forward #72969. Thanks @jhsmith409.
2122
- Channels/Telegram: skip the optional webhook-info API call during polling-mode status checks and startup bot-label probes so long-polling setups avoid an unnecessary Telegram round trip. Carries forward #72990. Thanks @danielgruneberg.
2223
- CLI/message: resolve targeted `openclaw message` channels to their owning plugin before loading the registry, and fall back to configured channel plugins when the channel must be inferred, so scripted sends avoid full bundled plugin registry scans without assuming channel ids match plugin ids. Fixes #73006. Thanks @jasonftl.
2324
- CLI/models: keep route-first `models status --json` stdout reserved for the JSON payload by routing auth-profile and startup diagnostics to stderr. Fixes #72962. Thanks @vishutdhar.

‎src/agents/compaction.tool-result-details.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,38 @@ describe("compaction toolResult details stripping", () => {
8282
expect(serialized).not.toContain('"details"');
8383
});
8484

85+
it("does not pass runtime-context custom messages into generateSummary", async () => {
86+
const messages = [
87+
{ role: "user", content: "visible ask", timestamp: 1 },
88+
{
89+
role: "custom",
90+
customType: "openclaw.runtime-context",
91+
content: "secret runtime context",
92+
display: false,
93+
timestamp: 2,
94+
},
95+
{ role: "assistant", content: "visible answer", timestamp: 3 },
96+
] as unknown as AgentMessage[];
97+
98+
await summarizeWithFallback({
99+
messages,
100+
model: { id: "mock", name: "mock", contextWindow: 10000, maxTokens: 1000 } as never,
101+
apiKey: "test", // pragma: allowlist secret
102+
signal: new AbortController().signal,
103+
reserveTokens: 100,
104+
maxChunkTokens: 5000,
105+
contextWindow: 10000,
106+
});
107+
108+
const chunk = (
109+
piCodingAgentMocks.generateSummary.mock.calls as unknown as Array<[unknown]>
110+
)[0]?.[0];
111+
const serialized = JSON.stringify(chunk);
112+
expect(serialized).toContain("visible ask");
113+
expect(serialized).not.toContain("openclaw.runtime-context");
114+
expect(serialized).not.toContain("secret runtime context");
115+
});
116+
85117
it("ignores toolResult.details when evaluating oversized messages", () => {
86118
piCodingAgentMocks.estimateTokens.mockImplementation((message: unknown) => {
87119
const record = message as { details?: unknown };

‎src/agents/compaction.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { isAbortError } from "../infra/unhandled-rejections.js";
1111
import { createSubsystemLogger } from "../logging/subsystem.js";
1212
import { DEFAULT_CONTEXT_TOKENS } from "./defaults.js";
1313
import { isTimeoutError } from "./failover-error.js";
14+
import { stripRuntimeContextCustomMessages } from "./internal-runtime-context.js";
1415
import { repairToolUseResultPairing, stripToolResultDetails } from "./session-transcript-repair.js";
1516
import { extractToolCallsFromAssistant, extractToolResultId } from "./tool-call-id.js";
1617

@@ -101,8 +102,8 @@ export function buildCompactionSummarizationInstructions(
101102
}
102103

103104
export function estimateMessagesTokens(messages: AgentMessage[]): number {
104-
// SECURITY: toolResult.details can contain untrusted/verbose payloads; never include in LLM-facing compaction.
105-
const safe = stripToolResultDetails(messages);
105+
// SECURITY: toolResult.details and runtime-context transcript entries must never enter LLM-facing compaction.
106+
const safe = stripToolResultDetails(stripRuntimeContextCustomMessages(messages));
106107
return safe.reduce((sum, message) => sum + estimateTokens(message), 0);
107108
}
108109

@@ -305,8 +306,8 @@ async function summarizeChunks(params: {
305306
return params.previousSummary ?? DEFAULT_SUMMARY_FALLBACK;
306307
}
307308

308-
// SECURITY: never feed toolResult.details into summarization prompts.
309-
const safeMessages = stripToolResultDetails(params.messages);
309+
// SECURITY: never feed toolResult.details or runtime-context transcript entries into summarization prompts.
310+
const safeMessages = stripToolResultDetails(stripRuntimeContextCustomMessages(params.messages));
310311
const chunks = chunkMessagesByMaxTokens(safeMessages, params.maxChunkTokens);
311312
let summary = params.previousSummary;
312313
const effectiveInstructions = buildCompactionSummarizationInstructions(

‎src/agents/internal-runtime-context.ts‎

Lines changed: 69 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,15 @@ export const INTERNAL_RUNTIME_CONTEXT_END = "<<<END_OPENCLAW_INTERNAL_CONTEXT>>>
44
const ESCAPED_INTERNAL_RUNTIME_CONTEXT_BEGIN = "[[OPENCLAW_INTERNAL_CONTEXT_BEGIN]]";
55
const ESCAPED_INTERNAL_RUNTIME_CONTEXT_END = "[[OPENCLAW_INTERNAL_CONTEXT_END]]";
66

7+
export const OPENCLAW_RUNTIME_CONTEXT_NOTICE =
8+
"This context is runtime-generated, not user-authored. Keep internal details private.";
9+
export const OPENCLAW_NEXT_TURN_RUNTIME_CONTEXT_HEADER =
10+
"OpenClaw runtime context for the immediately preceding user message.";
11+
export const OPENCLAW_RUNTIME_EVENT_HEADER = "OpenClaw runtime event.";
12+
export const OPENCLAW_RUNTIME_CONTEXT_CUSTOM_TYPE = "openclaw.runtime-context";
13+
714
const LEGACY_INTERNAL_CONTEXT_HEADER =
8-
[
9-
"OpenClaw runtime context (internal):",
10-
"This context is runtime-generated, not user-authored. Keep internal details private.",
11-
"",
12-
].join("\n") + "\n";
15+
["OpenClaw runtime context (internal):", OPENCLAW_RUNTIME_CONTEXT_NOTICE, ""].join("\n") + "\n";
1316

1417
const LEGACY_INTERNAL_EVENT_MARKER = "[Internal task completion event]";
1518
const LEGACY_INTERNAL_EVENT_SEPARATOR = "\n\n---\n\n";
@@ -154,6 +157,42 @@ function stripLegacyInternalRuntimeContext(text: string): string {
154157
}
155158
}
156159

160+
function isRuntimeContextPromptHeader(line: string): boolean {
161+
return (
162+
line === OPENCLAW_NEXT_TURN_RUNTIME_CONTEXT_HEADER || line === OPENCLAW_RUNTIME_EVENT_HEADER
163+
);
164+
}
165+
166+
function stripRuntimeContextPromptPreface(text: string): string {
167+
const lines = text.split(/\r?\n/);
168+
let changed = false;
169+
const output: string[] = [];
170+
171+
for (let index = 0; index < lines.length; index += 1) {
172+
const line = lines[index] ?? "";
173+
const nextLine = lines[index + 1] ?? "";
174+
if (
175+
isRuntimeContextPromptHeader(line.trim()) &&
176+
nextLine.trim() === OPENCLAW_RUNTIME_CONTEXT_NOTICE
177+
) {
178+
changed = true;
179+
index += 1;
180+
while (index + 1 < lines.length && (lines[index + 1] ?? "").trim() === "") {
181+
index += 1;
182+
}
183+
continue;
184+
}
185+
output.push(line);
186+
}
187+
188+
return changed
189+
? output
190+
.join("\n")
191+
.replace(/\n{3,}/g, "\n\n")
192+
.trim()
193+
: text;
194+
}
195+
157196
export function stripInternalRuntimeContext(text: string): string {
158197
if (!text) {
159198
return text;
@@ -163,7 +202,9 @@ export function stripInternalRuntimeContext(text: string): string {
163202
INTERNAL_RUNTIME_CONTEXT_BEGIN,
164203
INTERNAL_RUNTIME_CONTEXT_END,
165204
);
166-
return stripLegacyInternalRuntimeContext(withoutDelimitedBlocks);
205+
return stripRuntimeContextPromptPreface(
206+
stripLegacyInternalRuntimeContext(withoutDelimitedBlocks),
207+
);
167208
}
168209

169210
export function hasInternalRuntimeContext(text: string): boolean {
@@ -172,6 +213,27 @@ export function hasInternalRuntimeContext(text: string): boolean {
172213
}
173214
return (
174215
findDelimitedTokenIndex(text, INTERNAL_RUNTIME_CONTEXT_BEGIN, 0) !== -1 ||
175-
text.includes(LEGACY_INTERNAL_CONTEXT_HEADER)
216+
text.includes(LEGACY_INTERNAL_CONTEXT_HEADER) ||
217+
text.includes(
218+
`${OPENCLAW_NEXT_TURN_RUNTIME_CONTEXT_HEADER}\n${OPENCLAW_RUNTIME_CONTEXT_NOTICE}`,
219+
) ||
220+
text.includes(`${OPENCLAW_RUNTIME_EVENT_HEADER}\n${OPENCLAW_RUNTIME_CONTEXT_NOTICE}`)
176221
);
177222
}
223+
224+
export function isOpenClawRuntimeContextCustomMessage(message: unknown): boolean {
225+
if (!message || typeof message !== "object") {
226+
return false;
227+
}
228+
const candidate = message as { role?: unknown; customType?: unknown };
229+
return (
230+
candidate.role === "custom" && candidate.customType === OPENCLAW_RUNTIME_CONTEXT_CUSTOM_TYPE
231+
);
232+
}
233+
234+
export function stripRuntimeContextCustomMessages<T>(messages: T[]): T[] {
235+
if (!messages.some(isOpenClawRuntimeContextCustomMessage)) {
236+
return messages;
237+
}
238+
return messages.filter((message) => !isOpenClawRuntimeContextCustomMessage(message));
239+
}

‎src/agents/pi-embedded-helpers.sanitizeuserfacingtext.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,30 @@ describe("sanitizeUserFacingText", () => {
325325
expect(sanitizeUserFacingText(input)).toBe("Visible intro.\n\nVisible outro.");
326326
});
327327

328+
it("strips copied next-turn runtime context prefaces from user-facing text", () => {
329+
const input = [
330+
"OpenClaw runtime context for the immediately preceding user message.",
331+
"This context is runtime-generated, not user-authored. Keep internal details private.",
332+
"",
333+
"<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>",
334+
"secret runtime context",
335+
"<<<END_OPENCLAW_INTERNAL_CONTEXT>>>",
336+
"",
337+
"Visible reply.",
338+
].join("\n");
339+
340+
expect(sanitizeUserFacingText(input)).toBe("Visible reply.");
341+
});
342+
343+
it("strips copied runtime event prefaces when no visible text remains", () => {
344+
const input = [
345+
"OpenClaw runtime event.",
346+
"This context is runtime-generated, not user-authored. Keep internal details private.",
347+
].join("\n");
348+
349+
expect(sanitizeUserFacingText(input)).toBe("");
350+
});
351+
328352
it("does not strip ordinary text that merely mentions internal marker strings", () => {
329353
const input = [
330354
"The literal header `OpenClaw runtime context (internal):` appears in this note.",

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,10 +164,15 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
164164
role: "custom",
165165
customType: "openclaw.runtime-context",
166166
display: false,
167-
content: expect.stringContaining("secret runtime context"),
167+
content:
168+
"<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>\nsecret runtime context\n<<<END_OPENCLAW_INTERNAL_CONTEXT>>>",
168169
}),
169170
]),
170171
);
172+
expect(JSON.stringify(seen.messages)).not.toContain(
173+
"OpenClaw runtime context for the immediately preceding user message.",
174+
);
175+
expect(JSON.stringify(seen.messages)).not.toContain("not user-authored");
171176
const trajectoryEvents = (
172177
await fs.readFile(path.join(tempPaths[0] ?? "", "session.trajectory.jsonl"), "utf8")
173178
)

‎src/agents/pi-embedded-runner/run/attempt.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,42 @@ describe("normalizeMessagesForLlmBoundary", () => {
9696
expect(output[0]?.content).toEqual([{ type: "text", text: "visible output" }]);
9797
expect(input[0]).toHaveProperty("details");
9898
});
99+
100+
it("keeps runtime-context transcript entries out of the LLM boundary", () => {
101+
const input = [
102+
{
103+
role: "user",
104+
content: [{ type: "text", text: "visible ask" }],
105+
timestamp: 1,
106+
},
107+
{
108+
role: "custom",
109+
customType: "openclaw.runtime-context",
110+
content: "secret runtime context",
111+
display: false,
112+
timestamp: 2,
113+
},
114+
{
115+
role: "custom",
116+
customType: "other-extension-context",
117+
content: "normal custom context",
118+
display: false,
119+
timestamp: 3,
120+
},
121+
];
122+
123+
const output = normalizeMessagesForLlmBoundary(
124+
input as Parameters<typeof normalizeMessagesForLlmBoundary>[0],
125+
) as Array<Record<string, unknown>>;
126+
127+
expect(output).toHaveLength(2);
128+
expect(output).not.toEqual(
129+
expect.arrayContaining([expect.objectContaining({ customType: "openclaw.runtime-context" })]),
130+
);
131+
expect(output).toEqual(
132+
expect.arrayContaining([expect.objectContaining({ customType: "other-extension-context" })]),
133+
);
134+
});
99135
});
100136

101137
describe("shouldCreateBundleMcpRuntimeForAttempt", () => {

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

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ import { resolveOpenClawReferencePaths } from "../../docs-path.js";
7878
import { isTimeoutError } from "../../failover-error.js";
7979
import { resolveHeartbeatPromptForSystemPrompt } from "../../heartbeat-system-prompt.js";
8080
import { resolveImageSanitizationLimits } from "../../image-sanitization.js";
81+
import { stripRuntimeContextCustomMessages } from "../../internal-runtime-context.js";
8182
import { buildModelAliasLines } from "../../model-alias-lines.js";
8283
import { resolveModelAuthMode } from "../../model-auth.js";
8384
import { resolveDefaultModelForAgent } from "../../model-selection.js";
@@ -314,6 +315,7 @@ import {
314315
shouldPreemptivelyCompactBeforePrompt,
315316
} from "./preemptive-compaction.js";
316317
import {
318+
buildRuntimeContextSystemContext,
317319
queueRuntimeContextForNextTurn,
318320
resolveRuntimeContextPromptParts,
319321
} from "./runtime-context-prompt.js";
@@ -480,7 +482,8 @@ export function applyEmbeddedAttemptToolsAllow<T extends { name: string }>(
480482
}
481483

482484
export function normalizeMessagesForLlmBoundary(messages: AgentMessage[]): AgentMessage[] {
483-
return stripToolResultDetails(normalizeAssistantReplayContent(messages));
485+
const normalized = stripToolResultDetails(normalizeAssistantReplayContent(messages));
486+
return stripRuntimeContextCustomMessages(normalized);
484487
}
485488

486489
export function shouldCreateBundleMcpRuntimeForAttempt(params: {
@@ -2657,19 +2660,35 @@ export async function runEmbeddedAttempt(
26572660
if (promptSubmission.runtimeOnly) {
26582661
await abortable(activeSession.prompt(promptSubmission.prompt));
26592662
} else {
2660-
await queueRuntimeContextForNextTurn({
2661-
session: activeSession,
2662-
runtimeContext: promptSubmission.runtimeContext,
2663-
});
2664-
2665-
// Only pass images option if there are actually images to pass
2666-
// This avoids potential issues with models that don't expect the images parameter
2667-
if (imageResult.images.length > 0) {
2668-
await abortable(
2669-
activeSession.prompt(promptSubmission.prompt, { images: imageResult.images }),
2670-
);
2671-
} else {
2672-
await abortable(activeSession.prompt(promptSubmission.prompt));
2663+
const runtimeContext = promptSubmission.runtimeContext?.trim();
2664+
const runtimeSystemPrompt = runtimeContext
2665+
? composeSystemPromptWithHookContext({
2666+
baseSystemPrompt: systemPromptText,
2667+
appendSystemContext: buildRuntimeContextSystemContext(runtimeContext),
2668+
})
2669+
: undefined;
2670+
if (runtimeSystemPrompt) {
2671+
applySystemPromptOverrideToSession(activeSession, runtimeSystemPrompt);
2672+
}
2673+
try {
2674+
await queueRuntimeContextForNextTurn({
2675+
session: activeSession,
2676+
runtimeContext,
2677+
});
2678+
2679+
// Only pass images option if there are actually images to pass
2680+
// This avoids potential issues with models that don't expect the images parameter
2681+
if (imageResult.images.length > 0) {
2682+
await abortable(
2683+
activeSession.prompt(promptSubmission.prompt, { images: imageResult.images }),
2684+
);
2685+
} else {
2686+
await abortable(activeSession.prompt(promptSubmission.prompt));
2687+
}
2688+
} finally {
2689+
if (runtimeSystemPrompt) {
2690+
applySystemPromptOverrideToSession(activeSession, systemPromptText);
2691+
}
26732692
}
26742693
}
26752694
}

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

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, it, vi } from "vitest";
22
import {
3+
buildRuntimeContextSystemContext,
34
queueRuntimeContextForNextTurn,
45
resolveRuntimeContextPromptParts,
56
} from "./runtime-context-prompt.js";
@@ -62,7 +63,10 @@ describe("runtime context prompt submission", () => {
6263
});
6364

6465
it("queues runtime context as a hidden next-turn custom message", async () => {
65-
const sendCustomMessage = vi.fn(async () => {});
66+
const sentMessages: Array<{ content: string }> = [];
67+
const sendCustomMessage = vi.fn(async (message: { content: string }) => {
68+
sentMessages.push(message);
69+
});
6670

6771
await queueRuntimeContextForNextTurn({
6872
session: { sendCustomMessage },
@@ -72,11 +76,25 @@ describe("runtime context prompt submission", () => {
7276
expect(sendCustomMessage).toHaveBeenCalledWith(
7377
expect.objectContaining({
7478
customType: "openclaw.runtime-context",
75-
content: expect.stringContaining("secret runtime context"),
79+
content: "secret runtime context",
7680
display: false,
7781
}),
7882
{ deliverAs: "nextTurn" },
7983
);
84+
expect(sentMessages[0]?.content).not.toContain(
85+
"OpenClaw runtime context for the immediately preceding user message.",
86+
);
87+
expect(sentMessages[0]?.content).not.toContain("not user-authored");
88+
});
89+
90+
it("labels next-turn runtime context only when used as prompt-local system context", () => {
91+
const systemContext = buildRuntimeContextSystemContext("secret runtime context");
92+
93+
expect(systemContext).toContain(
94+
"OpenClaw runtime context for the immediately preceding user message.",
95+
);
96+
expect(systemContext).toContain("not user-authored");
97+
expect(systemContext).toContain("secret runtime context");
8098
});
8199

82100
it("labels runtime-only events as system context", async () => {

0 commit comments

Comments
 (0)