Skip to content

Commit a1c689e

Browse files
authored
fix(outbound): preserve fenced tool call examples (#117089)
1 parent 8ea6c43 commit a1c689e

19 files changed

Lines changed: 743 additions & 46 deletions

‎extensions/discord/src/monitor/reply-safety.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-pay
44
import {
55
sanitizeAssistantVisibleText,
66
sanitizeAssistantVisibleTextWithProfile,
7+
findCodeRegions,
78
} from "openclaw/plugin-sdk/text-chunking";
89
import { stripPlainTextToolCallBlocks } from "openclaw/plugin-sdk/tool-payload";
910

@@ -58,9 +59,13 @@ function stripDiscordInternalChannelLines(text: string): string {
5859
}
5960

6061
function sanitizeDiscordFrontChannelText(text: string): string {
61-
const withoutToolCallBlocks = stripPlainTextToolCallBlocks(text);
62+
const withoutToolCallBlocks = stripPlainTextToolCallBlocks(text, {
63+
resolveProtectedRanges: findCodeRegions,
64+
});
6265
const withoutAssistantScaffolding = sanitizeAssistantVisibleText(withoutToolCallBlocks);
63-
const withoutResidualToolCallBlocks = stripPlainTextToolCallBlocks(withoutAssistantScaffolding);
66+
const withoutResidualToolCallBlocks = stripPlainTextToolCallBlocks(withoutAssistantScaffolding, {
67+
resolveProtectedRanges: findCodeRegions,
68+
});
6469
const withoutChannelLines = stripDiscordInternalChannelLines(withoutResidualToolCallBlocks);
6570
return collapseExcessBlankLines(withoutChannelLines).trim();
6671
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/** Parser limits and allowlist options for plain-text tool-call repair. */
2+
export type PlainTextToolCallParseOptions = {
3+
/** Optional allowlist of tool names that may be repaired. */
4+
allowedToolNames?: Iterable<string>;
5+
/** Maximum serialized payload size accepted for one repaired call. */
6+
maxPayloadBytes?: number;
7+
};
8+
9+
export type PlainTextToolCallNameMatcher = {
10+
hasExactName(name: string): boolean;
11+
hasNamePrefix(prefix: string): boolean;
12+
};
13+
14+
/** Source range that must remain literal user-visible text. */
15+
export type PlainTextToolCallProtectedRange = { end: number; start: number };
16+
17+
/** Resolves protected ranges against the exact text about to be scanned. */
18+
export type PlainTextToolCallProtectedRangeResolver = (
19+
text: string,
20+
) => readonly PlainTextToolCallProtectedRange[];
21+
22+
export function isOffsetInProtectedRanges(
23+
offset: number,
24+
ranges: readonly PlainTextToolCallProtectedRange[],
25+
): boolean {
26+
return ranges.some((range) => offset >= range.start && offset < range.end);
27+
}

‎packages/tool-call-repair/src/index.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,17 @@ export {
33
parseStandalonePlainTextToolCallBlocks,
44
stripPlainTextToolCallBlocks,
55
type PlainTextToolCallBlock,
6-
type PlainTextToolCallParseOptions,
76
} from "./payload.js";
7+
export {
8+
type PlainTextToolCallNameMatcher,
9+
type PlainTextToolCallParseOptions,
10+
type PlainTextToolCallProtectedRange,
11+
type PlainTextToolCallProtectedRangeResolver,
12+
} from "./contracts.js";
813
export {
914
normalizePlainTextToolCallStreamEvents,
1015
projectScrubbedPlainTextToolCallMessage,
1116
type PlainTextToolCallMessageNormalization,
12-
type PlainTextToolCallNameMatcher,
1317
type PlainTextToolCallStreamNormalizerOptions,
1418
} from "./stream-normalizer.js";
1519
export {

‎packages/tool-call-repair/src/payload.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,32 @@ describe("scanPlainTextJsonToolCall", () => {
146146
});
147147

148148
describe("stripPlainTextToolCallBlocks", () => {
149+
it("preserves protected candidates while stripping adjacent unprotected calls", () => {
150+
const protectedCall = '[read]\n{"path":"example.txt"}\n[/read]';
151+
const unprotectedCall = '[read]\n{"path":"secret.txt"}\n[/read]';
152+
const raw = [protectedCall, unprotectedCall].join("\n");
153+
154+
expect(
155+
stripPlainTextToolCallBlocks(raw, {
156+
resolveProtectedRanges: () => [{ start: 0, end: protectedCall.length }],
157+
}),
158+
).toBe(`${protectedCall}\n`);
159+
expect(stripPlainTextToolCallBlocks(raw)).toBe("");
160+
});
161+
162+
it("checks protection for every adjacent candidate", () => {
163+
const first = '[read]\n{"path":"secret.txt"}\n[/read]';
164+
const second = '[server]\n{"host":"example.test"}\n[/server]';
165+
const raw = `${first}\n${second}`;
166+
const secondStart = raw.indexOf(second);
167+
168+
expect(
169+
stripPlainTextToolCallBlocks(raw, {
170+
resolveProtectedRanges: () => [{ start: secondStart, end: raw.length }],
171+
}),
172+
).toBe(second);
173+
});
174+
149175
it("preserves a balanced tool block whose JSON is invalid", () => {
150176
const raw = '[read]\n{"path":}\n[/read]';
151177

‎packages/tool-call-repair/src/payload.ts‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
import {
2+
isOffsetInProtectedRanges,
3+
type PlainTextToolCallNameMatcher,
4+
type PlainTextToolCallParseOptions,
5+
type PlainTextToolCallProtectedRangeResolver,
6+
} from "./contracts.js";
17
// Tool Call Repair module implements payload behavior.
28
import {
39
consumeLineBreak,
@@ -29,14 +35,6 @@ export type PlainTextToolCallBlock = {
2935
start: number;
3036
};
3137

32-
/** Parser limits and allowlist options for plain-text tool-call repair. */
33-
export type PlainTextToolCallParseOptions = {
34-
/** Optional allowlist of tool names that may be repaired. */
35-
allowedToolNames?: Iterable<string>;
36-
/** Maximum serialized payload size accepted for one repaired call. */
37-
maxPayloadBytes?: number;
38-
};
39-
4038
type NormalizedPlainTextToolCallParseOptions = Omit<
4139
PlainTextToolCallParseOptions,
4240
"allowedToolNames"
@@ -70,11 +68,6 @@ export type PlainTextJsonToolCallScan =
7068
payload: PlainTextJsonToolCallSpan;
7169
});
7270

73-
export type PlainTextToolCallNameMatcher = {
74-
hasExactName(name: string): boolean;
75-
hasNamePrefix(prefix: string): boolean;
76-
};
77-
7871
type PlainTextToolCallScanBranches = {
7972
json: PlainTextJsonToolCallScan;
8073
matches: { json: boolean; xmlish: boolean };
@@ -681,7 +674,10 @@ export function parseStandalonePlainTextToolCallBlocks(
681674
}
682675

683676
/** Removes full-line standalone plain-text tool-call blocks from user-visible text. */
684-
export function stripPlainTextToolCallBlocks(text: string): string {
677+
export function stripPlainTextToolCallBlocks(
678+
text: string,
679+
options: { resolveProtectedRanges?: PlainTextToolCallProtectedRangeResolver } = {},
680+
): string {
685681
if (
686682
!text ||
687683
(!/\[(?:tool:)?[A-Za-z0-9_-]+\]/.test(text) &&
@@ -692,6 +688,7 @@ export function stripPlainTextToolCallBlocks(text: string): string {
692688
) {
693689
return text;
694690
}
691+
const protectedRanges = options.resolveProtectedRanges?.(text) ?? [];
695692
let result = "";
696693
let cursor = 0;
697694
let index = 0;
@@ -702,6 +699,10 @@ export function stripPlainTextToolCallBlocks(text: string): string {
702699
continue;
703700
}
704701
const blockStart = skipLineIndentation(text, index);
702+
if (isOffsetInProtectedRanges(blockStart, protectedRanges)) {
703+
index += 1;
704+
continue;
705+
}
705706
const scan = scanPlainTextToolCall(text, blockStart);
706707
if (scan.kind === "prefix" && scan.completeEnd === undefined) {
707708
return result + text.slice(cursor);
@@ -719,6 +720,9 @@ export function stripPlainTextToolCallBlocks(text: string): string {
719720
result += text.slice(cursor, index);
720721
while (true) {
721722
const adjacentStart = skipLineIndentation(text, blockEnd);
723+
if (isOffsetInProtectedRanges(adjacentStart, protectedRanges)) {
724+
break;
725+
}
722726
const adjacent = scanPlainTextToolCall(text, adjacentStart);
723727
const adjacentEnd =
724728
adjacent.kind === "complete"

‎packages/tool-call-repair/src/promote.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { PlainTextToolCallProtectedRangeResolver } from "./contracts.js";
12
// Tool Call Repair module implements promote behavior.
23
import { parseStandalonePlainTextToolCallBlocks, type PlainTextToolCallBlock } from "./payload.js";
34

@@ -21,6 +22,7 @@ export type PlainTextToolCallPromotionOptions = {
2122
isRetainableNonTextBlock?: (block: Record<string, unknown>) => boolean;
2223
message: unknown;
2324
requireAssistantRole?: boolean;
25+
resolveProtectedRanges?: PlainTextToolCallProtectedRangeResolver;
2426
resolveToolName?: ToolCallRepairNameResolver;
2527
};
2628

@@ -87,6 +89,14 @@ function createPromotedToolCallBlocks(
8789
if (!parsedBlocks) {
8890
return undefined;
8991
}
92+
const protectedRanges = options.resolveProtectedRanges?.(text) ?? [];
93+
if (
94+
parsedBlocks.some((block) =>
95+
protectedRanges.some((range) => block.start >= range.start && block.start < range.end),
96+
)
97+
) {
98+
return undefined;
99+
}
90100

91101
const resolveToolName = options.resolveToolName ?? resolveExactToolName;
92102
const toolCalls: Record<string, unknown>[] = [];
@@ -137,7 +147,7 @@ export function projectStandalonePlainTextToolCallMessage(
137147

138148
const originalContent = messageRecord.content;
139149
if (typeof originalContent === "string") {
140-
const toolCalls = createPromotedToolCallBlocks(originalContent.trim(), options);
150+
const toolCalls = createPromotedToolCallBlocks(originalContent, options);
141151
if (!toolCalls) {
142152
return undefined;
143153
}

0 commit comments

Comments
 (0)