Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): gate read-write credential redirects

Chrisf9cb99fd99a5
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
index 94cf9e4aeb..e43d95f785 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -1,4 +1,5 @@
import {
+ globSync,
linkSync,
lstatSync,
mkdtempSync,
@@ -172,6 +173,7 @@ describe('cindy-bridge extension source', () => {
source.slice(helperStart, helperEnd),
'(globalThis as any).collectResolvedCredentialPaths = collectResolvedCredentialPaths;',
'(globalThis as any).bashInputReadTargets = bashInputReadTargets;',
+ '(globalThis as any).bashInputReadEvidence = bashInputReadEvidence;',
'(globalThis as any).parseShellInputRedirections = parseShellInputRedirections;',
].join('\n');
const compiled = ts.transpileModule(executableSource, {
@@ -182,19 +184,28 @@ describe('cindy-bridge extension source', () => {
}).outputText;
const tempRoot = mkdtempSync(path.join(tmpdir(), 'cindy-pi-credential-link-'));
const context: {
+ globSync: typeof globSync;
realpathSync: typeof realpathSync;
statSync: typeof statSync;
path: typeof path;
- process: { cwd: () => string };
+ process: { cwd: () => string; env: NodeJS.ProcessEnv };
collectResolvedCredentialPaths?: (input: unknown) => string[];
bashInputReadTargets?: (input: unknown) => string[];
+ bashInputReadEvidence?: (input: unknown) => { targets: string[]; unresolved: boolean };
parseShellInputRedirections?: (command: string) => {
command: string;
targets: string[];
targetPrefixes: string[];
+ targetMayExpand: boolean[];
hasUnresolvedTarget: boolean;
};
- } = { realpathSync, statSync, path, process: { cwd: () => tempRoot } };
+ } = {
+ globSync,
+ realpathSync,
+ statSync,
+ path,
+ process: { cwd: () => tempRoot, env: { ...process.env, HOME: tempRoot } },
+ };
runInNewContext(compiled, context);
try {
@@ -207,6 +218,9 @@ describe('cindy-bridge extension source', () => {
const nestedSecretLink = path.join(nestedDir, 'nested-innocent.txt');
const dashSecretLink = path.join(dashDir, 'innocent.txt');
const lateSecretLink = path.join(nestedDir, 'late-only-secret-link');
+ const scopedLinkName = 'scoped-innocent.txt';
+ const rootScopedSecretLink = path.join(tempRoot, scopedLinkName);
+ const nestedScopedOrdinaryLink = path.join(nestedDir, scopedLinkName);
mkdirSync(path.dirname(secretPath), { recursive: true });
mkdirSync(nestedDir, { recursive: true });
mkdirSync(dashDir, { recursive: true });
@@ -216,6 +230,8 @@ describe('cindy-bridge extension source', () => {
symlinkSync(secretPath, nestedSecretLink);
symlinkSync(secretPath, dashSecretLink);
symlinkSync(secretPath, lateSecretLink);
+ symlinkSync(secretPath, rootScopedSecretLink);
+ symlinkSync(ordinaryPath, nestedScopedOrdinaryLink);
symlinkSync(ordinaryPath, ordinaryLink);
expect(context.collectResolvedCredentialPaths?.({ path: secretLink })).toEqual([
@@ -233,10 +249,55 @@ describe('cindy-bridge extension source', () => {
expect(context.collectResolvedCredentialPaths?.(
context.bashInputReadTargets?.({ command: ordinaryCommand }),
)).toEqual([]);
+ const readWriteSecretCommand = `cat 3<>${secretLink}`;
+ expect(context.parseShellInputRedirections?.(readWriteSecretCommand)).toEqual({
+ command: readWriteSecretCommand,
+ targets: [secretLink],
+ targetPrefixes: ['cat 3'],
+ targetMayExpand: [false],
+ hasUnresolvedTarget: false,
+ });
+ expect(context.collectResolvedCredentialPaths?.(
+ context.bashInputReadTargets?.({ command: readWriteSecretCommand }),
+ )).toEqual([realpathSync(secretPath)]);
+ for (const expandedCommand of [
+ `cat <>${path.join(tempRoot, 'innocent.*')}`,
+ 'cat <>~/innocent.*',
+ ]) {
+ expect(context.collectResolvedCredentialPaths?.(
+ context.bashInputReadTargets?.({ command: expandedCommand }),
+ ), expandedCommand).toEqual([realpathSync(secretPath)]);
+ }
+ expect(context.collectResolvedCredentialPaths?.(
+ context.bashInputReadTargets?.({ command: "cat <>'innocent.*'" }),
+ )).toEqual([]);
const nestedCommand = `cd ${nestedDir} && cat <nested-innocent.txt`;
expect(context.collectResolvedCredentialPaths?.(
context.bashInputReadTargets?.({ command: nestedCommand }),
)).toEqual([realpathSync(secretPath)]);
+ for (const groupedCommand of [
+ `(cd ${nestedDir} && cat <>nested-innocent.txt)`,
+ `{ cd ${nestedDir} && cat 3<>nested-innocent.txt; }`,
+ `if cd ${nestedDir}; then cat 7<>nested-innocent.txt; fi`,
+ 'cd ~/nested && cat 8<>nested-innocent.txt',
+ 'cd nest* && cat 9<>nested-innocent.txt',
+ ]) {
+ expect(context.collectResolvedCredentialPaths?.(
+ context.bashInputReadTargets?.({ command: groupedCommand }),
+ ), groupedCommand).toEqual([realpathSync(secretPath)]);
+ }
+ for (const scopedCommand of [
+ `(cd ${nestedDir} && true); cat <>${scopedLinkName}`,
+ `if false; then cd ${nestedDir}; fi; cat 3<>${scopedLinkName}`,
+ `false && cd ${nestedDir}; cat 4<>${scopedLinkName}`,
+ `true || cd ${nestedDir}; cat 5<>${scopedLinkName}`,
+ `cd ${path.join(tempRoot, 'missing')} && :; cat 6<>${scopedLinkName}`,
+ `case x in y) cd ${nestedDir};; esac; cat 7<>${scopedLinkName}`,
+ ]) {
+ expect(context.collectResolvedCredentialPaths?.(
+ context.bashInputReadTargets?.({ command: scopedCommand }),
+ ), scopedCommand).toEqual([realpathSync(secretPath)]);
+ }
const optionTerminatedCdCommand = 'cd -- -credential-dir && cat <innocent.txt';
expect(context.collectResolvedCredentialPaths?.(
context.bashInputReadTargets?.({ command: optionTerminatedCdCommand }),
@@ -258,16 +319,25 @@ describe('cindy-bridge extension source', () => {
command: dynamicCommand,
targets: [],
targetPrefixes: [],
+ targetMayExpand: [],
hasUnresolvedTarget: true,
});
expect(context.bashInputReadTargets?.({ command: dynamicCommand })).toEqual([]);
+ expect(context.bashInputReadEvidence?.({ command: dynamicCommand })).toEqual({
+ targets: [],
+ unresolved: true,
+ });
+ expect(context.bashInputReadEvidence?.({ command: 'cat <>~cindy-no-such-user/innocent.txt' }))
+ .toEqual({ targets: [], unresolved: true });
expect(context.parseShellInputRedirections?.('cat <>created')).toEqual({
command: 'cat <>created',
- targets: [],
- targetPrefixes: [],
+ targets: ['created'],
+ targetPrefixes: ['cat '],
+ targetMayExpand: [false],
hasUnresolvedTarget: false,
});
- expect(source).toContain("event.toolName === 'bash' ? bashInputReadTargets(event.input) : []");
+ expect(source).toContain("event.toolName === 'bash'\n ? bashInputReadEvidence(event.input)");
+ expect(source).toContain('bashReadEvidence.unresolved || touchesCredentialPath(bashReadTargets)');
expect(source).toContain('resolvedCredentialPaths: resolvedCredentialReadPaths');
} finally {
rmSync(tempRoot, { recursive: true, force: true });
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index 3fb0a4004a..789a330fcb 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -37,7 +37,7 @@ export const CINDY_BRIDGE_EXTENSION_FILENAME = "cindy-bridge.ts";
export const CINDY_BRIDGE_EXTENSION_SOURCE = String.raw`/**
* cindy-bridge (generated by Cindy — do not edit; overwritten on session start)
*/
-import { lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
+import { globSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
import { stat } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
@@ -118,25 +118,115 @@ const REVIEW_CREDENTIAL_GLOB_PATTERNS = ${JSON.stringify(REVIEW_SENSITIVE_CREDEN
${SHELL_INPUT_REDIRECTION_PARSER_SOURCE}
-function bashInputReadTargets(input: unknown): string[] {
- if (!input || typeof input !== 'object') return [];
+type BashPathCandidates = { paths: string[]; unresolved: boolean };
+type BashInputReadEvidence = { targets: string[]; unresolved: boolean };
+
+function bashTildeCandidates(target: string): BashPathCandidates {
+ if (!target.startsWith('~')) return { paths: [target], unresolved: false };
+ const match = /^~([^/]*)(.*)$/.exec(target);
+ if (!match) return { paths: [], unresolved: true };
+ const user = match[1] ?? '';
+ const suffix = (match[2] ?? '').replace(/^\//, '');
+ if (!user) {
+ const home = process.env.HOME || process.env.USERPROFILE;
+ return home
+ ? { paths: [path.join(home, suffix)], unresolved: false }
+ : { paths: [], unresolved: true };
+ }
+ try {
+ const entry = readFileSync('/etc/passwd', 'utf8')
+ .split(/\r?\n/)
+ .find((line) => line.split(':', 1)[0] === user);
+ const home = entry?.split(':')[5];
+ return home
+ ? { paths: [path.join(home, suffix)], unresolved: false }
+ : { paths: [], unresolved: true };
+ } catch {
+ return { paths: [], unresolved: true };
+ }
+}
+
+function bashExpandedPathCandidates(
+ target: string,
+ cwd: string,
+ mayExpand: boolean,
+): BashPathCandidates {
+ if (!mayExpand) {
+ return { paths: [path.isAbsolute(target) ? target : path.resolve(cwd, target)], unresolved: false };
+ }
+ const tilde = bashTildeCandidates(target);
+ if (tilde.unresolved) return tilde;
+ try {
+ const paths = tilde.paths.flatMap((pattern) => {
+ const matches = globSync(pattern, { cwd });
+ if (matches.length === 0) {
+ return [path.isAbsolute(pattern) ? pattern : path.resolve(cwd, pattern)];
+ }
+ return matches.map((match) => path.isAbsolute(match) ? match : path.resolve(cwd, match));
+ });
+ return { paths: [...new Set(paths)], unresolved: false };
+ } catch {
+ return { paths: [], unresolved: true };
+ }
+}
+
+function bashInputReadEvidence(input: unknown): BashInputReadEvidence {
+ if (!input || typeof input !== 'object') return { targets: [], unresolved: false };
const command = (input as Record<string, unknown>).command;
- if (typeof command !== 'string') return [];
+ if (typeof command !== 'string') return { targets: [], unresolved: false };
const parsed = parseShellInputRedirections(command);
- return [...new Set(parsed.targets.flatMap((target, index) => {
- const cwdCandidates = bashWorkingDirectoryCandidates(parsed.targetPrefixes[index] ?? '');
- return path.isAbsolute(target)
- ? [target]
- : cwdCandidates.map((cwd) => path.resolve(cwd, target));
- }))];
+ let unresolved = parsed.hasUnresolvedTarget;
+ const targets = parsed.targets.flatMap((target, index) => {
+ const cwdEvidence = bashWorkingDirectoryCandidates(parsed.targetPrefixes[index] ?? '');
+ unresolved ||= cwdEvidence.unresolved;
+ return cwdEvidence.paths.flatMap((cwd) => {
+ const expanded = bashExpandedPathCandidates(target, cwd, parsed.targetMayExpand[index] === true);
+ unresolved ||= expanded.unresolved;
+ return expanded.paths;
+ });
+ });
+ return { targets: [...new Set(targets)], unresolved };
}
-function bashWorkingDirectoryCandidates(command: string): string[] {
+function bashInputReadTargets(input: unknown): string[] {
+ return bashInputReadEvidence(input).targets;
+}
+
+function bashSubshellDepthAt(command: string, end: number): number {
+ let depth = 0;
+ for (let index = 0; index < end; index += 1) {
+ if (command[index] === '(') depth += 1;
+ else if (command[index] === ')') depth = Math.max(0, depth - 1);
+ }
+ return depth;
+}
+
+function bashSubshellScopeRemainsOpen(command: string, start: number, depth: number): boolean {
+ if (depth === 0) return true;
+ let currentDepth = depth;
+ for (let index = start; index < command.length; index += 1) {
+ if (command[index] === '(') currentDepth += 1;
+ else if (command[index] === ')') {
+ currentDepth -= 1;
+ if (currentDepth < depth) return false;
+ }
+ }
+ return true;
+}
+
+function bashWorkingDirectoryCandidates(command: string): BashPathCandidates {
let candidates = [process.cwd()];
+ let unresolved = false;
const codeMask = bashShellCodeMask(command);
- const directoryChange = /(?:^|[;&|\n])\s*(?:command\s+)?(?:cd|pushd)\s+/g;
+ const directoryChange = /(?:^|[;&|(){}\n])\s*(?:(?:if|then|elif|else|while|until|do)\s+)?(?:command\s+)?(?:cd|pushd)\s+/g;
for (const match of codeMask.matchAll(directoryChange)) {
- let cursor = (match.index ?? 0) + match[0].length;
+ const matchIndex = match.index ?? 0;
+ let cursor = matchIndex + match[0].length;
+ const precededByConditionalOperator = matchIndex > 0
+ && ((codeMask[matchIndex] === '&' && codeMask[matchIndex - 1] === '&')
+ || (codeMask[matchIndex] === '|' && codeMask[matchIndex - 1] === '|'));
+ const changeDepth = bashSubshellDepthAt(codeMask, cursor);
+ if (!bashSubshellScopeRemainsOpen(codeMask, cursor, changeDepth)) continue;
let parsed = readShellRedirectionTarget(command, cursor);
let optionsEnded = false;
while (parsed.target === '--' || /^-[LPen]+$/.test(parsed.target)) {
@@ -145,28 +235,33 @@ function bashWorkingDirectoryCandidates(command: string): string[] {
while (/\s/.test(command[cursor] ?? '')) cursor += 1;
parsed = readShellRedirectionTarget(command, cursor);
}
- if (!parsed.target || parsed.unresolved || (!optionsEnded && parsed.target.startsWith('-'))) continue;
+ if (!parsed.target || parsed.unresolved || (!optionsEnded && parsed.target.startsWith('-'))) {
+ unresolved = true;
+ continue;
+ }
const operator = /^\s*(&&|\|\||[;\n|&])/.exec(command.slice(parsed.end))?.[1] ?? '';
if (!operator || operator === '|' || operator === '&') continue;
const changed: string[] = [];
for (const cwd of candidates) {
- const candidate = path.resolve(cwd, parsed.target);
- try {
- if (statSync(candidate).isDirectory()) changed.push(candidate);
- } catch {
- // A failed cd leaves cwd unchanged for ;/newline, and skips the RHS of &&.
+ const expanded = bashExpandedPathCandidates(parsed.target, cwd, parsed.mayExpand);
+ unresolved ||= expanded.unresolved;
+ for (const candidate of expanded.paths) {
+ try {
+ if (statSync(candidate).isDirectory()) changed.push(candidate);
+ } catch {
+ // A failed cd leaves cwd unchanged for later ;/newline commands.
+ }
}
}
- if (operator === '||') {
+ const branchMayHaveBeenSkipped = /\b(?:elif|else|fi|done|esac)\b/.test(codeMask.slice(parsed.end));
+ if (operator === '||' || branchMayHaveBeenSkipped || precededByConditionalOperator) {
candidates = [...new Set([...candidates, ...changed])];
} else if (changed.length > 0) {
candidates = [...new Set(changed)];
- } else if (operator === '&&') {
- candidates = [];
}
}
- return candidates;
+ return { paths: candidates, unresolved };
}
function bashShellCodeMask(command: string): string {
@@ -1342,7 +1437,10 @@ export default async function cindyBridge(pi: any) {
// 凭证/密钥路径的内置只读工具与 bash 输入重定向都必须携带 canonical
// 证据。bash 的原始 input 是整条命令,不能直接 realpath;先用与 Host 相同的
// parser 提取真实输入目标,才能识别工作区 symlink 指向的凭证文件。
- const bashReadTargets = event.toolName === 'bash' ? bashInputReadTargets(event.input) : [];
+ const bashReadEvidence = event.toolName === 'bash'
+ ? bashInputReadEvidence(event.input)
+ : { targets: [], unresolved: false };
+ const bashReadTargets = bashReadEvidence.targets;
const readonlyCredentialEvidence = READONLY_BUILTINS.has(event.toolName)
? collectReadonlyCredentialEvidence(event.toolName, event.input)
: null;
@@ -1352,7 +1450,7 @@ export default async function cindyBridge(pi: any) {
? [...new Set(collectResolvedCredentialPaths(bashReadTargets))]
: [];
const credentialRead = readonlyCredentialEvidence?.touchesCredential === true
- || (event.toolName === 'bash' && touchesCredentialPath(bashReadTargets))
+ || (event.toolName === 'bash' && (bashReadEvidence.unresolved || touchesCredentialPath(bashReadTargets)))
|| resolvedCredentialReadPaths.length > 0;
if (credentialRead && permission.mode === 'bypassPermissions') {
return { block: true, reason: 'Cindy blocks reading credential or key paths, even with Full access.' };
diff --git a/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts b/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts
index 2b134988e4..352c653121 100644
--- a/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts
@@ -599,10 +599,26 @@ describe('对抗语料 — dotenv 凭证路径', () => {
}
});
+ it.each([
+ 'cat <>.env',
+ 'cat<>.env.local',
+ 'cat 3<>.env.production',
+ 'cat 7 <> ".env.test"',
+ '<>.env cat',
+ '3<>.env.local cat',
+ 'cat <>ordinary.txt <>.env.local',
+ 'true && cat 9<>./.env',
+ 'cat <>$TARGET',
+ ])('%s 的读写重定向凭证目标必须进入确定性凭证门', (command) => {
+ expect(classifyShellCommand(command, roots, opts)).toBe('prompt-each-time');
+ });
+
it.each([
'cat <>created',
'cat<>created',
'cat 3<>created',
+ 'cat 7 <> "ordinary.txt"',
+ '3<>ordinary.txt cat',
])('%s 保留读写副作用审批', (command) => {
expect(classifyShellCommand(command, roots, opts)).toBe('prompt');
});
diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.ts
index 278e7726a2..4b1894f4a2 100644
--- a/packages/maker-core/src/agents/shared/auto-review.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.ts
@@ -5328,8 +5328,11 @@ function shellCommandReadsDotenv(
const readsCredentialInput = inputRedirections.targets.some(
(target) => shellOperandCouldMatchDotenv(target),
);
+ const inspectionCommand = inputRedirections.targets.length > 0
+ ? parseShellInputRedirections(segment, true).command
+ : inputRedirections.command;
const unwrapped = unwrapCommand(
- stripShellControlTokens(tokenize(inputRedirections.command)),
+ stripShellControlTokens(tokenize(inspectionCommand)),
opts.cwd ?? workspaceRoots[0],
opts.cwdUnknown === true,
);
diff --git a/packages/maker-core/src/agents/shared/shell-input-redirections.test.ts b/packages/maker-core/src/agents/shared/shell-input-redirections.test.ts
index 94178c0312..faab3e5aa4 100644
--- a/packages/maker-core/src/agents/shared/shell-input-redirections.test.ts
+++ b/packages/maker-core/src/agents/shared/shell-input-redirections.test.ts
@@ -16,6 +16,7 @@ describe('parseShellInputRedirections', () => {
expect(parsed.command.trim()).toBe(stripped);
expect(parsed.targets).toEqual([target]);
expect(parsed.targetPrefixes).toHaveLength(1);
+ expect(parsed.targetMayExpand).toEqual([command === 'cat <*.txt']);
expect(parsed.hasUnresolvedTarget).toBe(false);
});
@@ -24,11 +25,14 @@ describe('parseShellInputRedirections', () => {
'cat <$TARGET',
'cat <"${TARGET}"',
'cat <`printf .env`',
+ 'cat <>$TARGET',
+ 'cat 3<>$(printf .env)',
])('preserves dynamic input targets for fail-closed classification: %s', (command) => {
expect(parseShellInputRedirections(command)).toEqual({
command,
targets: [],
targetPrefixes: [],
+ targetMayExpand: [],
hasUnresolvedTarget: true,
});
});
@@ -39,6 +43,7 @@ describe('parseShellInputRedirections', () => {
command: 'cat ',
targets: ['.env'],
targetPrefixes: ['cat '],
+ targetMayExpand: [false],
hasUnresolvedTarget: false,
});
});
@@ -49,6 +54,7 @@ describe('parseShellInputRedirections', () => {
command: 'cat .env',
targets: [],
targetPrefixes: [],
+ targetMayExpand: [],
hasUnresolvedTarget: false,
});
});
@@ -59,6 +65,7 @@ describe('parseShellInputRedirections', () => {
command: 'true \ncat ',
targets: ['.env'],
targetPrefixes: ['true \ncat '],
+ targetMayExpand: [false],
hasUnresolvedTarget: false,
});
});
@@ -69,10 +76,29 @@ describe('parseShellInputRedirections', () => {
command: 'cat README.md ',
targets: [],
targetPrefixes: [],
+ targetMayExpand: [],
hasUnresolvedTarget: false,
});
});
+ it.each([
+ ['cat <>created', 'created', 'cat ', 'cat'],
+ ['cat<>.env', '.env', 'cat', 'cat'],
+ ['cat 3<> ".env.local"', '.env.local', 'cat 3', 'cat'],
+ ['cat 7 <>./.env.production', './.env.production', 'cat 7 ', 'cat 7'],
+ ['3<>.env cat', '.env', '3', 'cat'],
+ ['cat3<>.env.local', '.env.local', 'cat3', 'cat3'],
+ ])('records the read target while preserving read-write syntax: %s', (command, target, prefix, inspection) => {
+ expect(parseShellInputRedirections(command)).toEqual({
+ command,
+ targets: [target],
+ targetPrefixes: [prefix],
+ targetMayExpand: [false],
+ hasUnresolvedTarget: false,
+ });
+ expect(parseShellInputRedirections(command, true).command.trim()).toBe(inspection);
+ });
+
it.each([
"grep '<.env' data.txt",
"cat '<.env'",
@@ -81,13 +107,12 @@ describe('parseShellInputRedirections', () => {
'cat <&0',
'cat <(printf x)',
'cat \\<.env',
- 'cat <>created',
- 'cat 3<>created',
])('does not treat data or non-input-file syntax as a target: %s', (command) => {
expect(parseShellInputRedirections(command)).toEqual({
command,
targets: [],
targetPrefixes: [],
+ targetMayExpand: [],
hasUnresolvedTarget: false,
});
});
diff --git a/packages/maker-core/src/agents/shared/shell-input-redirections.ts b/packages/maker-core/src/agents/shared/shell-input-redirections.ts
index b6f042a2ac..7615b3a24a 100644
--- a/packages/maker-core/src/agents/shared/shell-input-redirections.ts
+++ b/packages/maker-core/src/agents/shared/shell-input-redirections.ts
@@ -2,16 +2,18 @@ export type ParsedShellInputRedirections = {
command: string;
targets: string[];
targetPrefixes: string[];
+ targetMayExpand: boolean[];
hasUnresolvedTarget: boolean;
};
export function readShellRedirectionTarget(
command: string,
start: number,
-): { target: string; end: number; unresolved: boolean } {
+): { target: string; end: number; unresolved: boolean; mayExpand: boolean } {
let target = '';
let quote: "'" | '"' | null = null;
let unresolved = false;
+ let mayExpand = false;
let cursor = start;
while (cursor < command.length) {
const char = command[cursor];
@@ -32,6 +34,8 @@ export function readShellRedirectionTarget(
continue;
}
if (char === '$' || char.charCodeAt(0) === 96) unresolved = true;
+ if (char === '*' || char === '?' || char === '[' || char === '{'
+ || (char === '~' && target.length === 0)) mayExpand = true;
if (char === "'" || char === '"') {
quote = char;
cursor += 1;
@@ -46,12 +50,16 @@ export function readShellRedirectionTarget(
target += char;
cursor += 1;
}
- return { target, end: cursor, unresolved };
+ return { target, end: cursor, unresolved, mayExpand };
}
-export function parseShellInputRedirections(command: string): ParsedShellInputRedirections {
+export function parseShellInputRedirections(
+ command: string,
+ stripReadWriteTargets = false,
+): ParsedShellInputRedirections {
const targets: string[] = [];
const targetPrefixes: string[] = [];
+ const targetMayExpand: boolean[] = [];
let stripped = '';
let quote: "'" | '"' | null = null;
let hasUnresolvedTarget = false;
@@ -103,8 +111,22 @@ export function parseShellInputRedirections(command: string): ParsedShellInputRe
continue;
}
if (next === '>') {
- stripped += '<>';
- index += 2;
+ let cursor = index + 2;
+ while (/\s/.test(command[cursor] ?? '')) cursor += 1;
+ const parsedTarget = readShellRedirectionTarget(command, cursor);
+ if (!parsedTarget.target || parsedTarget.unresolved) {
+ hasUnresolvedTarget = true;
+ } else {
+ targets.push(parsedTarget.target);
+ targetPrefixes.push(stripped);
+ targetMayExpand.push(parsedTarget.mayExpand);
+ }
+ if (stripReadWriteTargets && parsedTarget.target && !parsedTarget.unresolved) {
+ stripped = stripped.replace(/(^|[\s;&|(){}])\d+$/, '$1') + ' ';
+ } else {
+ stripped += command.slice(index, parsedTarget.end);
+ }
+ index = parsedTarget.end;
continue;
}
if (next === '&' || next === '(') {
@@ -122,12 +144,13 @@ export function parseShellInputRedirections(command: string): ParsedShellInputRe
} else {
targets.push(parsedTarget.target);
targetPrefixes.push(stripped);
+ targetMayExpand.push(parsedTarget.mayExpand);
stripped += ' ';
}
index = parsedTarget.end;
}
- return { command: stripped, targets, targetPrefixes, hasUnresolvedTarget };
+ return { command: stripped, targets, targetPrefixes, targetMayExpand, hasUnresolvedTarget };
}
export function shellInputRedirectionParserSource(): string {