Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/vscode-extension/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
- Subagents fly a little lower than the main agent, so several UFOs never overlap; they are born from the main UFO and fly back to it when done.
- The UFO dresses for what it is doing: the action's colour plus an accessory. Reading glasses on a read, a magnifying glass on a search, a hard hat on an edit (green on a new file), a beacon on a run (red if it fails), thought orbs while thinking, an hourglass while waiting for permission, antennas on a delegate. The rim ring and its lights change with it; the name tag keeps the agent's colour.
- Each leg of the flight path is drawn in the colour of the action the UFO flew there to do.
- A search the agent runs in the terminal (`grep -rn`, `rg`, `git grep`, `find`) lights the beacons on the files it found, as the Grep tool does; the pattern is no longer taken for a file (#457).
- The UFO keeps flying smoothly when the scene drops to low-performance mode (for example a laptop on battery); only the system's reduced-motion setting turns the flight off. Legends and rings follow a growing building a few times a second instead of every frame.
- Legends above the city: the building card, and the function card beside it when you point at a floor, float above the tallest building with a line down to what they describe, so they no longer hide the buildings around them.
- Click a building to pin its card; it stays while you look at others and follows the playhead. Click it again to remove it.
Expand Down
15 changes: 11 additions & 4 deletions apps/vscode-extension/src/core/agent-flow/claudeCodeTranscript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@
* first characters of each prompt (the turn label). Pure: no fs.
*/
import { MAIN_ACTOR_ID, type AgentStepKind, type AgentTraceEvent, type AgentTraceLineTouch, type AgentTraceLocation } from './agentFlowModels';
import { classifyShellCommand } from './shellCommandClassifier';
import { classifyShellCommand, grepLinePaths, searchHitsFromOutput } from './shellCommandClassifier';
import { touchFromCreatedContent, touchFromPatch, touchFromReadWindow } from './lineTouches';

const PROMPT_LABEL_MAX = 160;

interface ToolUse {
name: string;
kind: AgentStepKind;
/** The shell command, for a Bash call (its output names a search's hits). */
command?: string;
}

type Json = Record<string, unknown>;
Expand Down Expand Up @@ -91,7 +93,9 @@ function blocksOf(message: Json, type: string): Json[] {

/** A search's hits, as the result lists them (at most 200). */
function searchHits(result: Json): AgentTraceLocation[] {
const hits = Array.isArray(result.filenames) ? result.filenames.filter((f): f is string => typeof f === 'string') : [];
let hits = Array.isArray(result.filenames) ? result.filenames.filter((f): f is string => typeof f === 'string') : [];
// Grep in content mode lists no filenames: its lines name them.
if (hits.length === 0 && result.mode === 'content' && typeof result.content === 'string') { hits = grepLinePaths(result.content); }
return hits.slice(0, 200).map((path) => ({ path }));
}

Expand All @@ -109,7 +113,10 @@ function applyExecuteResult(update: StepEvent, result: Json): void {
/** What a tool_result adds to its step, from the entry's `toolUseResult`. */
function applyToolResult(update: StepEvent, tool: ToolUse, result: Json): void {
if (tool.kind === 'search') {
const hits = searchHits(result);
// Grep/Glob list their hits; a `grep -rn` or `rg` run through Bash prints them.
const hits = tool.command
? searchHitsFromOutput(tool.command, String(result.stdout ?? '')).slice(0, 200).map((path) => ({ path }))
: searchHits(result);
if (hits.length > 0) { update.locations = hits; }
}
if (tool.name === 'Write' && result.type === 'create' && str(result.filePath)) {
Expand Down Expand Up @@ -366,7 +373,7 @@ export class ClaudeCodeTranscriptParser {
private toolStep(id: string, name: string, input: Json, at: number, subagent: boolean): AgentTraceEvent {
const { kind, locations, title, command, created, deleted } = toolCallShape(name, input);
const { added, removed } = editLineCounts(name, input);
this.tools.set(id, { name, kind });
this.tools.set(id, { name, kind, command });
const step: StepEvent = {
type: 'step', at, id, kind, tool: name, title, status: 'running', subagent,
};
Expand Down
18 changes: 16 additions & 2 deletions apps/vscode-extension/src/core/agent-flow/codexRollout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* patch headers name the files it edits, creates and deletes. Pure: no fs.
*/
import type { AgentTraceEvent } from './agentFlowModels';
import { classifyShellCommand, parseApplyPatch, unwrapShell } from './shellCommandClassifier';
import { classifyShellCommand, parseApplyPatch, searchHitsFromOutput, unwrapShell } from './shellCommandClassifier';

type Json = Record<string, unknown>;

Expand Down Expand Up @@ -107,6 +107,8 @@ function shellStep(id: string, at: number, name: string, command: string): StepE

export class CodexRolloutParser {
private readonly calls = new Map<string, CallKind>();
/** A search's command, until its output names the hits. */
private readonly searchCommands = new Map<string, string>();
private turnOpen = false;
private lastAt = 0;
public sessionId: string | null = null;
Expand Down Expand Up @@ -206,15 +208,26 @@ export class CodexRolloutParser {
return [];
}
this.calls.delete(id);
const exitCode = outputExitCode(parseJson(item.output));
const parsedOutput = parseJson(item.output);
const exitCode = outputExitCode(parsedOutput);
const failed = exitCode !== undefined ? exitCode !== 0 : /^(error|failed)/i.test(String(item.output ?? ''));
const step: StepEvent = {
type: 'step', at, id, kind: stepKind, status: failed ? 'failed' : 'done',
};
if (exitCode !== undefined) { step.exitCode = exitCode; }
this.addSearchHits(step, id, parsedOutput, item.output);
return [step];
}

/** A shell search's output names the files it found. */
private addSearchHits(step: StepEvent, id: string, parsed: Json | null, raw: unknown): void {
const searched = this.searchCommands.get(id);
if (searched === undefined) { return; }
this.searchCommands.delete(id);
const hits = searchHitsFromOutput(searched, str(parsed?.output) ?? str(raw) ?? '');
if (hits.length > 0) { step.locations = hits.map((path) => ({ path })); }
}

private callStep(id: string, name: string, args: Json, at: number): AgentTraceEvent {
const command = commandText(args.command) ?? commandText(args.cmd);
const patch = patchOf(name, args, command);
Expand All @@ -225,6 +238,7 @@ export class CodexRolloutParser {
if (command) {
const step = shellStep(id, at, name, command);
this.calls.set(id, CALL_KINDS.has(step.kind) ? step.kind as CallKind : 'execute');
if (step.kind === 'search') { this.searchCommands.set(id, command); }
return step;
}
this.calls.set(id, 'execute');
Expand Down
123 changes: 122 additions & 1 deletion apps/vscode-extension/src/core/agent-flow/shellCommandClassifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,125 @@ export interface ClassifiedCommand {
const READ_COMMANDS = new Set(['cat', 'head', 'tail', 'less', 'more', 'nl', 'bat', 'wc', 'sed', 'awk', 'type', 'get-content']);
const SEARCH_COMMANDS = new Set(['rg', 'grep', 'egrep', 'fgrep', 'ag', 'ack', 'find', 'fd', 'ls', 'tree', 'dir', 'git-grep', 'select-string']);

/** Searches whose output is `path:line:text` (or just the line when they search one file). */
const GREP_COMMANDS = new Set(['rg', 'grep', 'egrep', 'fgrep', 'ag', 'ack', 'git-grep']);
/** Searches that print one path per line. */
const LISTING_COMMANDS = new Set(['find', 'fd']);
/** grep / rg options that take the next word as their value. */
const GREP_VALUE_OPTIONS = new Set([
'-e', '--regexp', '-f', '--file', '-m', '--max-count', '-A', '-B', '-C', '--after-context', '--before-context', '--context',
'-g', '--glob', '-t', '--type', '-T', '--type-not', '--include', '--exclude', '--exclude-dir', '-d', '--directories',
'-D', '--devices', '--color', '--colour', '-M', '--max-columns', '-j', '--threads', '--label', '--max-depth',
]);
const MAX_SEARCH_HITS = 200;

interface GrepOperands { paths: string[]; listsFiles: boolean; recursive: boolean; counts: boolean; withNames: boolean }

/** A short-flag cluster (`-rnl`) or a long flag contains one of these. */
function hasFlag(flag: string, short: string, long: string[]): boolean {
if (flag.startsWith('--')) { return long.includes(flag); }
return new RegExp(`^-[a-zA-Z]*[${short}]`).test(flag);
}

/** What one option of a grep says about its output. */
function readGrepFlag(flag: string, found: GrepOperands): void {
found.listsFiles ||= hasFlag(flag, 'lL', ['--files-with-matches', '--files', '--files-without-match']);
found.recursive ||= hasFlag(flag, 'rR', ['--recursive', '--dereference-recursive']);
found.counts ||= hasFlag(flag, 'c', ['--count', '--count-matches']);
found.withNames ||= hasFlag(flag, 'H', ['--with-filename']);
}

/**
* A grep's operands without its options: the pattern (the first operand,
* unless `-e`/`-f` gave it) and the files or folders it searched.
*/
function grepOperands(args: string[]): GrepOperands {
const found: GrepOperands = { paths: [], listsFiles: false, recursive: false, counts: false, withNames: false };
let patternGiven = false;
const end = args.indexOf('--');
const options = end < 0 ? args : args.slice(0, end);
for (let i = 0; i < options.length; i += 1) {
const word = options[i];
if (!word.startsWith('-') || word.length < 2) { found.paths.push(word); continue; }
const flag = word.split('=')[0];
patternGiven ||= ['-e', '--regexp', '-f', '--file'].includes(flag);
readGrepFlag(flag, found);
if (GREP_VALUE_OPTIONS.has(flag) && !word.includes('=')) { i += 1; }
}
if (end >= 0) { found.paths.push(...args.slice(end + 1)); }
if (!patternGiven) { found.paths = found.paths.slice(1); }
return found;
}

/** `C:\x\y.ts:12:text` -> `C:\x\y.ts`; `src/a.ts:12:text` -> `src/a.ts`; null when the line names no file. */
function hitPathOf(line: string, listsFiles: boolean): string | null {
const text = line.trim();
if (!text) { return null; }
if (listsFiles) { return looksLikePath(text) ? text : null; }
const match = /^((?:[A-Za-z]:[\\/])?[^:]+?):\d+[:-]/.exec(text) ?? /^((?:[A-Za-z]:[\\/])?[^:]+?):/.exec(text);
return match && looksLikePath(match[1]) ? match[1] : null;
}

/** The distinct paths an output names, line by line (at most MAX_SEARCH_HITS). */
function outputPaths(output: string, pathOf: (line: string) => string | null): string[] {
const paths: string[] = [];
for (const line of String(output || '').split(/\r?\n/)) {
const hit = pathOf(line);
if (hit && !paths.includes(hit)) { paths.push(hit); }
if (paths.length >= MAX_SEARCH_HITS) { break; }
}
return paths;
}

/** The files named by `path:line:text` lines (a Grep tool's content mode prints those too). */
export function grepLinePaths(output: string): string[] {
return outputPaths(output, (line) => hitPathOf(line, false));
}

/** The search of a command line and the folder it ran in (`cd x && grep ...`); null when a pipe reshapes its output. */
function searchSegment(command: string): { words: string[]; dir: string } | null {
const segments = allSegments(command);
let dir = '';
const index = segments.findIndex((segment) => {
if (segment[0] === 'cd' && segment[1]) { dir = segment[1]; return false; }
return segment[0] !== 'export' && segment[0] !== 'set';
});
if (index < 0) { return null; }
// Piped into a count or anything else, the output names no paths.
const reshaped = segments.slice(index + 1).some((next) => !['head', 'tail', 'sort', 'uniq'].includes(commandName(next).name));
return reshaped ? null : { words: segments[index], dir };
}

/** A grep's hits: one file searched prints only the lines, otherwise each line names its file. */
function grepHits(args: string[], output: string): string[] {
const parsed = grepOperands(args);
if (parsed.counts) { return []; }
const files = parsed.paths.filter((p) => !p.includes('*'));
const oneFile = files.length === 1 && /\.[A-Za-z0-9]+$/.test(files[0]) && looksLikePath(files[0]);
if (oneFile && !parsed.recursive && !parsed.listsFiles && !parsed.withNames) { return [files[0]]; }
return outputPaths(output, (line) => hitPathOf(line, parsed.listsFiles));
}

/**
* The files a shell search found, read from what it printed: `grep -rn`,
* `rg`, `git grep` (`path:line:text`), `grep -l` / `rg -l` / `find` / `fd`
* (one path per line), and a grep over one file (just the matching lines).
* Paths are relative to where the command ran (`cd x &&` included), as the
* other shell operands are. Empty for any other command or when nothing matched.
*/
export function searchHitsFromOutput(command: string, output: string): string[] {
const search = output?.trim() ? searchSegment(command) : null;
if (!search) { return []; }
const { name, args } = commandName(search.words);
let paths: string[] = [];
if (GREP_COMMANDS.has(name)) { paths = grepHits(args, output); }
if (LISTING_COMMANDS.has(name)) { paths = outputPaths(output, (line) => (looksLikePath(line.trim()) ? line.trim() : null)); }
return paths.map((path) => {
const clean = path.replace(/^\.[\\/]/, '');
return search.dir && !/^([A-Za-z]:)?[\\/]/.test(clean) ? joinPath(search.dir, clean) : clean;
});
}

/** Splits a command line into words, honouring simple quotes. Not a full shell parser. */
export function splitShellWords(command: string): string[] {
const words: string[] = [];
Expand Down Expand Up @@ -107,7 +226,9 @@ export function classifyShellCommand(command: string): ClassifiedCommand {
return { kind: 'read', paths: args.filter(looksLikePath) };
}
if (SEARCH_COMMANDS.has(name)) {
return { kind: 'search', paths: args.filter(looksLikePath) };
// A grep's pattern (`backend\.utils\.validation`) is not a path.
const operands = GREP_COMMANDS.has(name) ? grepOperands(args).paths : args;
return { kind: 'search', paths: operands.filter(looksLikePath) };
}
return { kind: 'execute', paths: [] };
}
Expand Down
47 changes: 46 additions & 1 deletion apps/vscode-extension/test/analysis/agentFlowCore.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const path = require('path');
const projectRoot = path.resolve(__dirname, '..', '..');
const out = (...parts) => require(path.join(projectRoot, 'out', 'core', 'agent-flow', ...parts));

const { classifyShellCommand, parseApplyPatch, splitShellWords } = out('shellCommandClassifier.js');
const { classifyShellCommand, parseApplyPatch, searchHitsFromOutput, splitShellWords } = out('shellCommandClassifier.js');
const { parseClaudeCodeTranscript, encodeClaudeProjectDir, claudeToolKind } = out('claudeCodeTranscript.js');
const { parseCodexRollout } = out('codexRollout.js');
const { AcpSessionEventMapper } = out('acpSessionEvents.js');
Expand Down Expand Up @@ -45,6 +45,51 @@ test('shell commands are read as the step they really are', () => {
assert.deepEqual(splitShellWords(`echo "a b" 'c'`), ['echo', 'a b', 'c']);
});

test('a shell search: the pattern is not a path, and its output names the hits (#323)', () => {
// Adrián's IDE test: the pattern was taken for a file and the hits were never read.
assert.deepEqual(classifyShellCommand('grep -rn "backend\\.utils\\.validation|from" backend'), { kind: 'search', paths: [] });
assert.deepEqual(classifyShellCommand('grep -n "x\\.y" src/a.py'), { kind: 'search', paths: ['src/a.py'] });
assert.deepEqual(classifyShellCommand('rg -e "a.b" -g "*.ts" src/b.ts'), { kind: 'search', paths: ['src/b.ts'] });
const grepOut = ['backend/utils/validation.py:3:from x import y', 'backend/api/routes.py:12:import backend.utils.validation', 'backend/api/routes.py:40:validation()', ''].join('\n');
assert.deepEqual(searchHitsFromOutput('grep -rn "backend\\.utils\\.validation" backend', grepOut), ['backend/utils/validation.py', 'backend/api/routes.py']);
assert.deepEqual(searchHitsFromOutput('rg -n validation', './a.ts:1:x\r\n./b/c.ts:2:y'), ['a.ts', 'b/c.ts']);
assert.deepEqual(searchHitsFromOutput('cd backend && grep -rln validation .', './api/routes.py\n./utils/v.py'), ['backend/api/routes.py', 'backend/utils/v.py']);
assert.deepEqual(searchHitsFromOutput('grep -n "x" src/a.py', '12:x = 1\n40:x()'), ['src/a.py'], 'one file: grep prints no filename');
assert.deepEqual(searchHitsFromOutput('git grep -n foo', 'src/a.ts:3:foo'), ['src/a.ts']);
assert.deepEqual(searchHitsFromOutput('find . -name "*.py"', './a/b.py\n./c.py'), ['a/b.py', 'c.py']);
assert.deepEqual(searchHitsFromOutput('grep -rn x C:\\repo', 'C:\\repo\\src\\a.ts:3:x'), ['C:\\repo\\src\\a.ts'], 'Windows paths keep their drive');
assert.deepEqual(searchHitsFromOutput('grep -rc x src', 'src/a.ts:3'), [], 'a count names no hit');
assert.deepEqual(searchHitsFromOutput('grep -rn x src | wc -l', '3'), [], 'piped into a count');
assert.deepEqual(searchHitsFromOutput('grep -rn x src', ''), [], 'nothing matched');
assert.deepEqual(searchHitsFromOutput('npm test', 'src/a.ts:3:x'), [], 'not a search');
});

test('a Bash grep in a Claude Code transcript and a shell rg in Codex carry their hits (#323)', () => {
const claude = [
claudeLine({ type: 'user', message: { role: 'user', content: 'Where is it used?' } }),
claudeLine({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'tool_use', id: 'b1', name: 'Bash', input: { command: 'grep -rn "backend\\.utils\\.validation" backend' } }] } }),
claudeLine({ type: 'user', toolUseResult: { stdout: 'backend/api/routes.py:12:import backend.utils.validation\nbackend/jobs/run.py:4:from backend.utils.validation import x', stderr: '', interrupted: false }, message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'b1', content: '...' }] } }),
].join('\n');
const grepContent = [
claudeLine({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'tool_use', id: 'g1', name: 'Grep', input: { pattern: 'validation', output_mode: 'content', '-n': true } }] } }),
claudeLine({ type: 'user', toolUseResult: { mode: 'content', numFiles: 0, filenames: [], content: `${ROOT}/backend/a.py:3:validation\n${ROOT}/backend/b.py:9:validation` }, message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'g1', content: '...' }] } }),
];
const steps = parseClaudeCodeTranscript([claude, ...grepContent].join('\n')).events.filter((e) => e.type === 'step');
assert.deepEqual(steps[3].locations, [{ path: `${ROOT}/backend/a.py` }, { path: `${ROOT}/backend/b.py` }], 'Grep in content mode: the lines name the files');
assert.equal(steps[0].kind, 'search');
assert.equal(steps[0].locations, undefined, 'the pattern is not taken for a file');
assert.deepEqual(steps[1].locations, [{ path: 'backend/api/routes.py' }, { path: 'backend/jobs/run.py' }]);
const line = (type, payload) => JSON.stringify({ timestamp: '2026-11-28T10:00:00Z', type, payload });
const codex = [
line('session_meta', { id: 'cx2', cwd: ROOT }),
line('response_item', { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Find it' }] }),
line('response_item', { type: 'function_call', name: 'shell', call_id: 'r1', arguments: JSON.stringify({ command: ['bash', '-lc', 'rg -n flag src'] }) }),
line('response_item', { type: 'function_call_output', call_id: 'r1', output: JSON.stringify({ output: 'src/cli.ts:3:flag\nsrc/flag.ts:1:flag', metadata: { exit_code: 0 } }) }),
].join('\n');
const done = parseCodexRollout(codex).events.filter((e) => e.type === 'step' && e.status === 'done');
assert.deepEqual(done[0].locations, [{ path: 'src/cli.ts' }, { path: 'src/flag.ts' }]);
});

test('apply_patch headers name the edited, added and deleted files', () => {
const patch = ['*** Begin Patch', '*** Update File: src/a.ts', '@@', '-old', '+new', '+more', '*** Add File: src/b.ts', '+x', '*** Delete File: src/c.ts', '*** End Patch'].join('\n');
assert.deepEqual(parseApplyPatch(patch), { updated: ['src/a.ts'], added: ['src/b.ts'], deleted: ['src/c.ts'], plus: 3, minus: 1 });
Expand Down
Loading
Loading