Skip to content

Commit b48e2db

Browse files
darioandyoshi-techclaudesteipete
authored
fix(tool-display): don't render shell redirects or rg --files as search targets (#133783)
* fix(tool-display): don't render shell redirects or `rg --files` as search targets `rg --files` takes no pattern, so every positional is a path, but the exec summary read `positional[0]` as the pattern. `positionalArgs` also keeps shell redirect tokens, and the summary uses the LAST positional as the target. Together those made rg --files autonomy .openclaw 2>/dev/null render as `search "autonomy" in 2>/dev/null`, naming a redirect as the path that was searched. The same shape appeared in an agent failure notification, where it read as though a file called `2>/dev/null` had been searched and sent debugging down the wrong path. Redirect filtering is deliberately applied only inside the grep/rg branch rather than in `positionalArgs`. Other summaries already render redirect operators -- `cat > file <<EOF` renders as `show >` and is covered by an existing test -- so filtering globally would change long-standing unrelated output. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01YbWMfBs2sgfwzkDkmnLSEB * fix(agents): parse shell redirects before display arguments Retain quote provenance while excluding complete redirections, and use one option parser for value-taking flags and positional boundaries. Correct ripgrep file-list mode and inherited cat/head/tail/copy summaries without changing execution or command-text privacy. Co-authored-by: darioandyoshi-tech <[email protected]> --------- Co-authored-by: darioandyoshi-tech <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent 3b758df commit b48e2db

4 files changed

Lines changed: 291 additions & 113 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { describe, expect, it } from "vitest";
2+
import { formatToolDetail, resolveToolDisplay } from "./tool-display.js";
3+
4+
const cases = [
5+
["rg --files autonomy .openclaw 2>/dev/null", "list files in .openclaw"],
6+
["rg --files -g '*.ts'", "list files"],
7+
["rg --files -t ts src", "list files in src"],
8+
["rg --files --glob=*.ts src", "list files in src"],
9+
["rg -- --files src", 'search "--files" in src'],
10+
["rg -e --files src", 'search "--files" in src'],
11+
["rg needle src 2>/dev/null", 'search "needle" in src'],
12+
["rg needle src 2> /dev/null", 'search "needle" in src'],
13+
["rg needle src>/dev/null", 'search "needle" in src'],
14+
["rg needle src 2>&1", 'search "needle" in src'],
15+
["rg needle src >|out", 'search "needle" in src'],
16+
["rg '2>/dev/null' README.md", 'search "2>/dev/null" in README.md'],
17+
[String.raw`rg 2\>literal README.md`, 'search "2>literal" in README.md'],
18+
["rg -e needle src", 'search "needle" in src'],
19+
["rg -ne'needle' src", 'search "needle" in src'],
20+
["rg -f patterns src", "search text in src"],
21+
["grep -E -e needle src", 'search "needle" in src'],
22+
["rg -E utf8 needle src", 'search "needle" in src'],
23+
["cat >out <<EOF\nsynthetic body\nEOF", "show output"],
24+
["head -n 2 source > out", "show first 2 lines of source"],
25+
["cp 2>err source destination", "copy source to destination"],
26+
["tail source 2>&1", "show source"],
27+
] as const;
28+
29+
describe("exec search and redirect display", () => {
30+
it.each(cases)("summarizes %s", (command, expected) => {
31+
expect(
32+
formatToolDetail(
33+
resolveToolDisplay({ name: "exec", args: { command }, detailMode: "explain" }),
34+
),
35+
).toBe(expected);
36+
});
37+
it("preserves the original command in raw detail mode", () => {
38+
const command = "rg needle src 2> /dev/null";
39+
const detail = formatToolDetail(
40+
resolveToolDisplay({ name: "bash", args: { command }, detailMode: "raw" }),
41+
);
42+
expect(detail).toContain('search "needle" in src');
43+
expect(detail).toContain(command);
44+
});
45+
});

‎src/agents/tool-display-exec-shell.ts‎

Lines changed: 158 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -26,61 +26,130 @@ export function stripOuterQuotes(value: string | undefined): string | undefined
2626
return trimmed;
2727
}
2828

29-
/** Splits a command string into shell-ish words while respecting simple quotes and escapes. */
30-
export function splitShellWords(input: string | undefined, maxWords = 48): string[] {
31-
if (!input) {
32-
return [];
33-
}
29+
export type ShellWords = {
30+
words: string[];
31+
hereInput?: "heredoc" | "here-string";
32+
unsupported: boolean;
33+
};
3434

35-
const words: string[] = [];
35+
/** Separates command arguments from unquoted shell redirects before quote removal. */
36+
export function parseShellWords(input: string | undefined, maxWords = 48): ShellWords {
37+
const source = input ?? "";
38+
const result: ShellWords = { words: [], unsupported: false };
3639
let current = "";
37-
let quote: '"' | "'" | undefined;
38-
let escaped = false;
40+
let quote: '"' | "'" | "ansi-c" | undefined;
41+
let previousUnquotedDollar = false;
42+
let started = false;
43+
let protectedWord = false;
44+
let redirectOperand = false;
45+
const flush = () => {
46+
if (started) {
47+
if (!redirectOperand) {
48+
result.words.push(current);
49+
}
50+
redirectOperand = false;
51+
}
52+
current = "";
53+
started = false;
54+
protectedWord = false;
55+
};
3956

40-
for (const char of input) {
41-
if (escaped) {
42-
current += char;
43-
escaped = false;
57+
for (let index = 0; index < source.length; index += 1) {
58+
const char = source.charAt(index);
59+
const next = source.charAt(index + 1);
60+
const wasUnquotedDollar: boolean = previousUnquotedDollar;
61+
previousUnquotedDollar = false;
62+
if (quote === "'") {
63+
if (char === quote) {
64+
quote = undefined;
65+
} else {
66+
current += char;
67+
}
4468
continue;
4569
}
46-
if (char === "\\") {
47-
escaped = true;
70+
if (char === "\\" && (!quote || quote === "ansi-c" || /[$`"\\\n]/u.test(next))) {
71+
if (!next) {
72+
result.unsupported = true;
73+
break;
74+
}
75+
index += 1;
76+
if (next !== "\n") {
77+
current += next;
78+
started = protectedWord = true;
79+
} else {
80+
previousUnquotedDollar = wasUnquotedDollar;
81+
}
4882
continue;
4983
}
50-
5184
if (quote) {
52-
if (char === quote) {
85+
if (char === (quote === "ansi-c" ? "'" : quote)) {
5386
quote = undefined;
5487
} else {
5588
current += char;
5689
}
5790
continue;
5891
}
59-
6092
if (char === '"' || char === "'") {
61-
quote = char;
93+
quote = char === "'" && wasUnquotedDollar ? "ansi-c" : char;
94+
started = protectedWord = true;
6295
continue;
6396
}
64-
65-
if (/\s/.test(char)) {
66-
if (!current) {
67-
continue;
97+
if (/\s/u.test(char)) {
98+
flush();
99+
if (result.words.length >= maxWords) {
100+
return result;
101+
}
102+
continue;
103+
}
104+
if (char === "#" && !started) {
105+
break;
106+
}
107+
if (char === "<" || char === ">" || (char === "&" && next === ">")) {
108+
if (next === "(") {
109+
result.unsupported = true;
68110
}
69-
words.push(current);
70-
if (words.length >= maxWords) {
71-
return words;
111+
// Only unquoted adjacent digits or {name} belong to the redirect's fd prefix.
112+
if (!protectedWord && /^(?:\d+|\{[A-Za-z_][A-Za-z0-9_]*\})$/u.test(current)) {
113+
current = "";
114+
started = false;
72115
}
73-
current = "";
116+
flush();
117+
let operator = char;
118+
if (char === "&") {
119+
operator += next;
120+
index += 1;
121+
if (source.charAt(index + 1) === ">") {
122+
operator += ">";
123+
index += 1;
124+
}
125+
} else if (
126+
next === char ||
127+
next === "&" ||
128+
(char === "<" && next === ">") ||
129+
(char === ">" && next === "|")
130+
) {
131+
operator += next;
132+
index += 1;
133+
if (
134+
operator === "<<" &&
135+
(source.charAt(index + 1) === "-" || source.charAt(index + 1) === "<")
136+
) {
137+
operator += source.charAt(++index);
138+
}
139+
}
140+
if (operator.startsWith("<<")) {
141+
result.hereInput = operator === "<<<" ? "here-string" : "heredoc";
142+
}
143+
redirectOperand = true;
74144
continue;
75145
}
76-
77146
current += char;
147+
started = true;
148+
previousUnquotedDollar = char === "$";
78149
}
79-
80-
if (current) {
81-
words.push(current);
82-
}
83-
return words;
150+
flush();
151+
result.unsupported ||= quote !== undefined || redirectOperand;
152+
return result;
84153
}
85154

86155
/** Returns a normalized basename for a command token. */
@@ -93,80 +162,67 @@ export function binaryName(token: string | undefined): string | undefined {
93162
return normalizeLowercaseStringOrEmpty(segment);
94163
}
95164

96-
/** Reads the value for any matching short or long option name. */
97-
export function optionValue(words: string[], names: string[]): string | undefined {
98-
const lookup = new Set(names);
99-
100-
for (let i = 0; i < words.length; i += 1) {
101-
const token = words[i];
102-
if (!token) {
103-
continue;
165+
/** Parses option boundaries once; callers supply the command's value-taking options. */
166+
export function parseShellOptions(words: string[], from = 1, optionsWithValue: string[] = []) {
167+
const positional: string[] = [];
168+
const options = new Map<string, string | undefined>();
169+
const takesValue = new Set(optionsWithValue);
170+
const record = (name: string, value?: string) => {
171+
if (!options.has(name)) {
172+
options.set(name, value);
173+
}
174+
};
175+
for (let index = from; index < words.length; index += 1) {
176+
const token = words[index];
177+
if (token === undefined) {
178+
break;
104179
}
105-
106-
if (lookup.has(token)) {
107-
const value = words[i + 1];
108-
if (value && !value.startsWith("-")) {
109-
return value;
110-
}
111-
continue;
180+
if (token === "--") {
181+
positional.push(...words.slice(index + 1));
182+
break;
112183
}
113-
114-
for (const name of names) {
115-
if (name.startsWith("--") && token.startsWith(`${name}=`)) {
116-
return token.slice(name.length + 1);
184+
if (takesValue.has(token)) {
185+
record(token, words[++index]);
186+
} else if (token.startsWith("--")) {
187+
const equals = token.indexOf("=");
188+
record(
189+
equals < 0 ? token : token.slice(0, equals),
190+
equals < 0 ? undefined : token.slice(equals + 1),
191+
);
192+
} else if (token.startsWith("-") && token.length > 1) {
193+
for (let offset = 1; offset < token.length; offset += 1) {
194+
const name = `-${token[offset]}`;
195+
if (takesValue.has(name)) {
196+
record(name, token.slice(offset + 1) || words[++index]);
197+
break;
198+
}
199+
record(name);
117200
}
201+
} else {
202+
positional.push(token);
118203
}
119204
}
205+
return { positional, options };
206+
}
120207

208+
/** Reads the first occurrence of any matching short or long option. */
209+
export function optionValue(words: string[], names: string[]): string | undefined {
210+
const { options } = parseShellOptions(words, 1, names);
211+
for (const [name, value] of options) {
212+
if (names.includes(name)) {
213+
return value;
214+
}
215+
}
121216
return undefined;
122217
}
123218

124-
/** Returns positional args after skipping options and configured option values. */
219+
/** Returns positional args after consuming options and their values. */
125220
export function positionalArgs(
126221
words: string[],
127222
from = 1,
128223
optionsWithValue: string[] = [],
129224
): string[] {
130-
const args: string[] = [];
131-
const takesValue = new Set(optionsWithValue);
132-
133-
for (let i = from; i < words.length; i += 1) {
134-
const token = words[i];
135-
if (!token) {
136-
continue;
137-
}
138-
139-
if (token === "--") {
140-
for (let j = i + 1; j < words.length; j += 1) {
141-
const candidate = words[j];
142-
if (candidate) {
143-
args.push(candidate);
144-
}
145-
}
146-
break;
147-
}
148-
149-
if (token.startsWith("--")) {
150-
if (token.includes("=")) {
151-
continue;
152-
}
153-
if (takesValue.has(token)) {
154-
i += 1;
155-
}
156-
continue;
157-
}
158-
159-
if (token.startsWith("-")) {
160-
if (takesValue.has(token)) {
161-
i += 1;
162-
}
163-
continue;
164-
}
165-
166-
args.push(token);
167-
}
168-
169-
return args;
225+
return parseShellOptions(words, from, optionsWithValue).positional;
170226
}
171227

172228
/** Returns the first positional arg after skipping options and configured option values. */
@@ -213,7 +269,7 @@ export function trimLeadingEnv(words: string[]): string[] {
213269

214270
/** Unwraps common `sh -c`/`bash -lc` command wrappers for display parsing. */
215271
export function unwrapShellWrapper(command: string): string {
216-
const words = splitShellWords(command, 10);
272+
const { words } = parseShellWords(command, 10);
217273
if (words.length < 3) {
218274
return command;
219275
}
@@ -594,15 +650,20 @@ export function splitTopLevelStages(command: string): string[] {
594650
/** Splits a command on top-level single pipes without splitting `||`. */
595651
export function splitTopLevelPipes(command: string): string[] {
596652
return splitTopLevel(command, (char, index) => {
597-
if (char === "|" && command[index - 1] !== "|" && command[index + 1] !== "|") {
653+
if (
654+
char === "|" &&
655+
command[index - 1] !== "|" &&
656+
command[index - 1] !== ">" &&
657+
command[index + 1] !== "|"
658+
) {
598659
return 1;
599660
}
600661
return 0;
601662
});
602663
}
603664

604665
function parseChdirTarget(head: string): string | undefined {
605-
const words = splitShellWords(head, 3);
666+
const { words } = parseShellWords(head, 3);
606667
const bin = binaryName(words[0]);
607668
if (bin === "cd" || bin === "pushd") {
608669
return words[1] || undefined;
@@ -611,12 +672,12 @@ function parseChdirTarget(head: string): string | undefined {
611672
}
612673

613674
function isChdirCommand(head: string): boolean {
614-
const bin = binaryName(splitShellWords(head, 2)[0]);
675+
const bin = binaryName(parseShellWords(head, 2).words[0]);
615676
return bin === "cd" || bin === "pushd" || bin === "popd";
616677
}
617678

618679
function isPopdCommand(head: string): boolean {
619-
return binaryName(splitShellWords(head, 2)[0]) === "popd";
680+
return binaryName(parseShellWords(head, 2).words[0]) === "popd";
620681
}
621682

622683
/** Removes leading setup commands such as exports and cwd changes from display summaries. */

0 commit comments

Comments
 (0)