Skip to content

Commit 153e3ad

Browse files
frankekntermtek
andauthored
fix(auto-reply): strip leading NO_REPLY tokens to prevent silent-reply leak (#63068)
* fix(auto-reply): strip leading NO_REPLY tokens to prevent silent-reply leak * fix(auto-reply): preserve substantive NO_REPLY leading text * fix(agents): preserve ACP silent-prefix cumulative deltas * fix(auto-reply): harden silent-token streaming paths * fix(auto-reply): normalize glued silent tokens consistently --------- Co-authored-by: termtek <[email protected]>
1 parent 21d0f7c commit 153e3ad

13 files changed

Lines changed: 343 additions & 23 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Docs: https://docs.openclaw.ai
1919
- npm packaging: derive required root runtime mirrors from bundled plugin manifests and built root chunks, then install packed release tarballs without the repo `node_modules` so release checks catch missing plugin deps before publish.
2020
- Reply/doctor: resolve reply-run SecretRefs before preflight helpers touch config, surface gateway OAuth reauth failures to users, and make `openclaw doctor` call out exact reauth commands.
2121
- Android/pairing: clear stale setup-code auth on new QR scans, bootstrap operator and node sessions from fresh pairing, prefer stored device tokens after bootstrap handoff, and pause pairing auto-retry while the app is backgrounded so scan-once Android pairing recovers reliably again. (#63199) Thanks @obviyus.
22+
- Auto-reply/NO_REPLY: strip glued leading `NO_REPLY` tokens before reply normalization and ACP-visible streaming so silent sentinel text no longer leaks into user-visible replies while preserving substantive `NO_REPLY ...` text. Thanks @frankekn.
2223

2324
## 2026.4.8
2425

‎src/agents/command/attempt-execution.test.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@ import fs from "node:fs/promises";
22
import os from "node:os";
33
import path from "node:path";
44
import { afterEach, beforeEach, describe, expect, it } from "vitest";
5-
import { resolveFallbackRetryPrompt, sessionFileHasContent } from "./attempt-execution.js";
5+
import {
6+
createAcpVisibleTextAccumulator,
7+
resolveFallbackRetryPrompt,
8+
sessionFileHasContent,
9+
} from "./attempt-execution.js";
610

711
describe("resolveFallbackRetryPrompt", () => {
812
const originalBody = "Summarize the quarterly earnings report and highlight key trends.";
@@ -157,3 +161,47 @@ describe("sessionFileHasContent", () => {
157161
expect(await sessionFileHasContent(link)).toBe(false);
158162
});
159163
});
164+
165+
describe("createAcpVisibleTextAccumulator", () => {
166+
it("preserves cumulative raw snapshots after stripping a glued NO_REPLY prefix", () => {
167+
const acc = createAcpVisibleTextAccumulator();
168+
169+
expect(acc.consume("NO_REPLYThe user")).toEqual({
170+
text: "The user",
171+
delta: "The user",
172+
});
173+
174+
expect(acc.consume("NO_REPLYThe user is saying")).toEqual({
175+
text: "The user is saying",
176+
delta: " is saying",
177+
});
178+
179+
expect(acc.finalize()).toBe("The user is saying");
180+
expect(acc.finalizeRaw()).toBe("The user is saying");
181+
});
182+
183+
it("keeps append-only deltas working after stripping a glued NO_REPLY prefix", () => {
184+
const acc = createAcpVisibleTextAccumulator();
185+
186+
expect(acc.consume("NO_REPLYThe user")).toEqual({
187+
text: "The user",
188+
delta: "The user",
189+
});
190+
191+
expect(acc.consume(" is saying")).toEqual({
192+
text: "The user is saying",
193+
delta: " is saying",
194+
});
195+
});
196+
197+
it("preserves punctuation-start text that begins with NO_REPLY-like content", () => {
198+
const acc = createAcpVisibleTextAccumulator();
199+
200+
expect(acc.consume("NO_REPLY: explanation")).toEqual({
201+
text: "NO_REPLY: explanation",
202+
delta: "NO_REPLY: explanation",
203+
});
204+
205+
expect(acc.finalize()).toBe("NO_REPLY: explanation");
206+
});
207+
});

‎src/agents/command/attempt-execution.ts‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import {
77
isSilentReplyPrefixText,
88
isSilentReplyText,
99
SILENT_REPLY_TOKEN,
10+
startsWithSilentToken,
11+
stripLeadingSilentToken,
1012
} from "../../auto-reply/tokens.js";
1113
import { loadConfig } from "../../config/config.js";
1214
import { mergeSessionEntry, type SessionEntry, updateSessionStore } from "../../config/sessions.js";
@@ -150,6 +152,7 @@ export function prependInternalEventContext(
150152
export function createAcpVisibleTextAccumulator() {
151153
let pendingSilentPrefix = "";
152154
let visibleText = "";
155+
let rawVisibleText = "";
153156
const startsWithWordChar = (chunk: string): boolean => /^[\p{L}\p{N}]/u.test(chunk);
154157

155158
const resolveNextCandidate = (base: string, chunk: string): string => {
@@ -169,16 +172,16 @@ export function createAcpVisibleTextAccumulator() {
169172
return `${base}${chunk}`;
170173
};
171174

172-
const mergeVisibleChunk = (base: string, chunk: string): { text: string; delta: string } => {
175+
const mergeVisibleChunk = (base: string, chunk: string): { rawText: string; delta: string } => {
173176
if (!base) {
174-
return { text: chunk, delta: chunk };
177+
return { rawText: chunk, delta: chunk };
175178
}
176179
if (chunk.startsWith(base) && chunk.length > base.length) {
177180
const delta = chunk.slice(base.length);
178-
return { text: chunk, delta };
181+
return { rawText: chunk, delta };
179182
}
180183
return {
181-
text: `${base}${chunk}`,
184+
rawText: `${base}${chunk}`,
182185
delta: chunk,
183186
};
184187
};
@@ -199,8 +202,22 @@ export function createAcpVisibleTextAccumulator() {
199202
pendingSilentPrefix = leadCandidate;
200203
return null;
201204
}
205+
// Strip leading NO_REPLY token when it is glued to visible text
206+
// (e.g. "NO_REPLYThe user is saying...") so the token never leaks.
207+
if (startsWithSilentToken(trimmedLeadCandidate, SILENT_REPLY_TOKEN)) {
208+
const stripped = stripLeadingSilentToken(leadCandidate, SILENT_REPLY_TOKEN);
209+
if (stripped) {
210+
pendingSilentPrefix = "";
211+
rawVisibleText = leadCandidate;
212+
visibleText = stripped;
213+
return { text: stripped, delta: stripped };
214+
}
215+
pendingSilentPrefix = leadCandidate;
216+
return null;
217+
}
202218
if (pendingSilentPrefix) {
203219
pendingSilentPrefix = "";
220+
rawVisibleText = leadCandidate;
204221
visibleText = leadCandidate;
205222
return {
206223
text: visibleText,
@@ -209,9 +226,13 @@ export function createAcpVisibleTextAccumulator() {
209226
}
210227
}
211228

212-
const nextVisible = mergeVisibleChunk(visibleText, chunk);
213-
visibleText = nextVisible.text;
214-
return nextVisible.delta ? nextVisible : null;
229+
const nextVisible = mergeVisibleChunk(rawVisibleText, chunk);
230+
rawVisibleText = nextVisible.rawText;
231+
if (!nextVisible.delta) {
232+
return null;
233+
}
234+
visibleText = `${visibleText}${nextVisible.delta}`;
235+
return { text: visibleText, delta: nextVisible.delta };
215236
},
216237
finalize(): string {
217238
return visibleText.trim();

‎src/auto-reply/reply/agent-runner-execution.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,49 @@ describe("runAgentTurnWithFallback", () => {
290290
expect(onToolResult.mock.calls[0]?.[0]?.text).toBeUndefined();
291291
});
292292

293+
it("strips a glued leading NO_REPLY token from streamed tool results", async () => {
294+
const onToolResult = vi.fn();
295+
state.runEmbeddedPiAgentMock.mockImplementationOnce(async (params: EmbeddedAgentParams) => {
296+
await params.onToolResult?.({ text: "NO_REPLYThe user is saying hello" });
297+
return { payloads: [{ text: "final" }], meta: {} };
298+
});
299+
300+
const runAgentTurnWithFallback = await getRunAgentTurnWithFallback();
301+
const pendingToolTasks = new Set<Promise<void>>();
302+
const typingSignals = createMockTypingSignaler();
303+
const result = await runAgentTurnWithFallback({
304+
commandBody: "hello",
305+
followupRun: createFollowupRun(),
306+
sessionCtx: {
307+
Provider: "whatsapp",
308+
MessageSid: "msg",
309+
} as unknown as TemplateContext,
310+
opts: {
311+
onToolResult,
312+
} satisfies GetReplyOptions,
313+
typingSignals,
314+
blockReplyPipeline: null,
315+
blockStreamingEnabled: false,
316+
resolvedBlockStreamingBreak: "message_end",
317+
applyReplyToMode: (payload) => payload,
318+
shouldEmitToolResult: () => true,
319+
shouldEmitToolOutput: () => false,
320+
pendingToolTasks,
321+
resetSessionAfterCompactionFailure: async () => false,
322+
resetSessionAfterRoleOrderingConflict: async () => false,
323+
isHeartbeat: false,
324+
sessionKey: "main",
325+
getActiveSessionEntry: () => undefined,
326+
resolvedVerboseLevel: "off",
327+
});
328+
329+
await Promise.all(pendingToolTasks);
330+
331+
expect(result.kind).toBe("success");
332+
expect(typingSignals.signalTextDelta).toHaveBeenCalledWith("The user is saying hello");
333+
expect(onToolResult).toHaveBeenCalledWith({ text: "The user is saying hello" });
334+
});
335+
293336
it("forwards item lifecycle events to reply options", async () => {
294337
const onItemEvent = vi.fn();
295338
state.runEmbeddedPiAgentMock.mockImplementationOnce(async (params: EmbeddedAgentParams) => {

‎src/auto-reply/reply/agent-runner-execution.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ import {
5858
isSilentReplyPrefixText,
5959
isSilentReplyText,
6060
SILENT_REPLY_TOKEN,
61+
startsWithSilentToken,
62+
stripLeadingSilentToken,
6163
} from "../tokens.js";
6264
import type { GetReplyOptions, ReplyPayload } from "../types.js";
6365
import { resolveRunAuthProfile } from "./agent-runner-auth-profile.js";
@@ -681,6 +683,9 @@ export async function runAgentTurnWithFallback(params: {
681683
) {
682684
return { skip: true };
683685
}
686+
if (text && startsWithSilentToken(text, SILENT_REPLY_TOKEN)) {
687+
text = stripLeadingSilentToken(text, SILENT_REPLY_TOKEN);
688+
}
684689
if (!text) {
685690
// Allow media-only payloads (e.g. tool result screenshots) through.
686691
if (reply.hasMedia) {

‎src/auto-reply/reply/agent-runner.runreplyagent.e2e.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,12 @@ describe("runReplyAgent typing (heartbeat)", () => {
452452
expectedForwarded: ["No", "No, that is valid"],
453453
shouldType: true,
454454
},
455+
{
456+
partials: ["NO_REPLYThe user is saying hello"],
457+
finalText: "NO_REPLYThe user is saying hello",
458+
expectedForwarded: ["The user is saying hello"],
459+
shouldType: true,
460+
},
455461
] as const;
456462

457463
for (const testCase of cases) {

‎src/auto-reply/reply/normalize-reply.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import {
77
isSilentReplyPayloadText,
88
isSilentReplyText,
99
SILENT_REPLY_TOKEN,
10+
startsWithSilentToken,
11+
stripLeadingSilentToken,
1012
stripSilentToken,
1113
} from "../tokens.js";
1214
import type { ReplyPayload } from "../types.js";
@@ -62,11 +64,17 @@ export function normalizeReplyPayload(
6264
// Strip NO_REPLY from mixed-content messages (e.g. "😄 NO_REPLY") so the
6365
// token never leaks to end users. If stripping leaves nothing, treat it as
6466
// silent just like the exact-match path above. (#30916, #30955)
65-
if (text && text.includes(silentToken) && !isSilentReplyText(text, silentToken)) {
66-
text = stripSilentToken(text, silentToken);
67-
if (!hasContent(text)) {
68-
opts.onSkip?.("silent");
69-
return null;
67+
if (text && !isSilentReplyText(text, silentToken)) {
68+
const hasLeadingSilentToken = startsWithSilentToken(text, silentToken);
69+
if (hasLeadingSilentToken) {
70+
text = stripLeadingSilentToken(text, silentToken);
71+
}
72+
if (hasLeadingSilentToken || text.includes(silentToken)) {
73+
text = stripSilentToken(text, silentToken);
74+
if (!hasContent(text)) {
75+
opts.onSkip?.("silent");
76+
return null;
77+
}
7078
}
7179
}
7280
if (text && !trimmed) {

‎src/auto-reply/reply/reply-utils.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,38 @@ describe("normalizeReplyPayload", () => {
125125
expect(result!.text).not.toContain("NO_REPLY");
126126
});
127127

128+
it("strips glued leading NO_REPLY text without leaking the token", () => {
129+
const result = normalizeReplyPayload({
130+
text: "NO_REPLYThe user is saying hello",
131+
});
132+
expect(result).not.toBeNull();
133+
expect(result!.text).toBe("The user is saying hello");
134+
});
135+
136+
it("strips glued leading NO_REPLY text case-insensitively", () => {
137+
const result = normalizeReplyPayload({
138+
text: "no_replyThe user is saying hello",
139+
});
140+
expect(result).not.toBeNull();
141+
expect(result!.text).toBe("The user is saying hello");
142+
});
143+
128144
it("keeps NO_REPLY when used as leading substantive text", () => {
129145
const result = normalizeReplyPayload({ text: "NO_REPLY -- nope" });
130146
expect(result).not.toBeNull();
131147
expect(result!.text).toBe("NO_REPLY -- nope");
132148
});
133149

150+
it("keeps punctuation-start content after a leading NO_REPLY token", () => {
151+
const colonResult = normalizeReplyPayload({ text: "NO_REPLY: explanation" });
152+
expect(colonResult).not.toBeNull();
153+
expect(colonResult!.text).toBe("NO_REPLY: explanation");
154+
155+
const dashResult = normalizeReplyPayload({ text: "NO_REPLY—note" });
156+
expect(dashResult).not.toBeNull();
157+
expect(dashResult!.text).toBe("NO_REPLY—note");
158+
});
159+
134160
it("suppresses message when stripping NO_REPLY leaves nothing", () => {
135161
const reasons: string[] = [];
136162
const result = normalizeReplyPayload(
@@ -968,6 +994,22 @@ describe("createStreamingDirectiveAccumulator", () => {
968994
expect(afterReset?.replyToTag).toBe(false);
969995
expect(afterReset?.replyToId).toBeUndefined();
970996
});
997+
998+
it("strips a glued leading NO_REPLY token from streamed text", () => {
999+
const accumulator = createStreamingDirectiveAccumulator();
1000+
1001+
const result = accumulator.consume("NO_REPLYThe user is saying hello");
1002+
1003+
expect(result?.text).toBe("The user is saying hello");
1004+
});
1005+
1006+
it("keeps punctuation-start text after a leading NO_REPLY token", () => {
1007+
const accumulator = createStreamingDirectiveAccumulator();
1008+
1009+
const result = accumulator.consume("NO_REPLY: explanation");
1010+
1011+
expect(result?.text).toBe("NO_REPLY: explanation");
1012+
});
9711013
});
9721014

9731015
describe("extractShortModelName", () => {

‎src/auto-reply/reply/streaming-directives.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import { hasOutboundReplyContent } from "openclaw/plugin-sdk/reply-payload";
22
import { splitMediaFromOutput } from "../../media/parse.js";
33
import { parseInlineDirectives } from "../../utils/directive-tags.js";
4-
import { isSilentReplyPrefixText, isSilentReplyText, SILENT_REPLY_TOKEN } from "../tokens.js";
4+
import {
5+
isSilentReplyPrefixText,
6+
isSilentReplyText,
7+
SILENT_REPLY_TOKEN,
8+
startsWithSilentToken,
9+
stripLeadingSilentToken,
10+
} from "../tokens.js";
511
import type { ReplyDirectiveParseResult } from "./reply-directives.js";
612

713
type PendingReplyState = {
@@ -52,6 +58,8 @@ const parseChunk = (raw: string, options?: { silentToken?: string }): ParsedChun
5258
isSilentReplyText(text, silentToken) || isSilentReplyPrefixText(text, silentToken);
5359
if (isSilent) {
5460
text = "";
61+
} else if (startsWithSilentToken(text, silentToken)) {
62+
text = stripLeadingSilentToken(text, silentToken);
5563
}
5664

5765
return {

‎src/auto-reply/tokens.test.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { describe, it, expect } from "vitest";
2-
import { isSilentReplyPrefixText, isSilentReplyText, stripSilentToken } from "./tokens.js";
2+
import {
3+
isSilentReplyPrefixText,
4+
isSilentReplyText,
5+
startsWithSilentToken,
6+
stripLeadingSilentToken,
7+
stripSilentToken,
8+
} from "./tokens.js";
39

410
describe("isSilentReplyText", () => {
511
it("returns true for exact token", () => {
@@ -78,6 +84,28 @@ describe("stripSilentToken", () => {
7884
});
7985
});
8086

87+
describe("stripLeadingSilentToken", () => {
88+
it("strips glued leading token text", () => {
89+
expect(stripLeadingSilentToken("NO_REPLYThe user is saying")).toBe("The user is saying");
90+
});
91+
});
92+
93+
describe("startsWithSilentToken", () => {
94+
it("matches leading glued silent tokens case-insensitively", () => {
95+
expect(startsWithSilentToken("NO_REPLYThe user is saying")).toBe(true);
96+
expect(startsWithSilentToken("No_RePlYThe user is saying")).toBe(true);
97+
expect(startsWithSilentToken("no_replyThe user is saying")).toBe(true);
98+
});
99+
100+
it("rejects separated substantive prefixes and exact-token-only text", () => {
101+
expect(startsWithSilentToken("NO_REPLY -- nope")).toBe(false);
102+
expect(startsWithSilentToken("NO_REPLY: explanation")).toBe(false);
103+
expect(startsWithSilentToken("NO_REPLY—note")).toBe(false);
104+
expect(startsWithSilentToken("NO_REPLY")).toBe(false);
105+
expect(startsWithSilentToken(" NO_REPLY ")).toBe(false);
106+
});
107+
});
108+
81109
describe("isSilentReplyPrefixText", () => {
82110
it("matches uppercase token lead fragments", () => {
83111
expect(isSilentReplyPrefixText("NO")).toBe(true);

0 commit comments

Comments
 (0)