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): parse adjacent credential redirects

Chrisd9f1a3b9ff95
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 0014b51c41..ae74c0069e 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -132,6 +132,8 @@ describe('cindy-bridge extension source', () => {
const executableSource = [
source.slice(helperStart, helperEnd),
'(globalThis as any).collectResolvedCredentialPaths = collectResolvedCredentialPaths;',
+ '(globalThis as any).bashInputReadTargets = bashInputReadTargets;',
+ '(globalThis as any).parseShellInputRedirections = parseShellInputRedirections;',
].join('\n');
const compiled = ts.transpileModule(executableSource, {
compilerOptions: {
@@ -142,12 +144,14 @@ describe('cindy-bridge extension source', () => {
const context: {
realpathSync: typeof realpathSync;
collectResolvedCredentialPaths?: (input: unknown) => string[];
+ bashInputReadTargets?: (input: unknown) => string[];
+ parseShellInputRedirections?: (command: string) => { command: string; targets: string[] };
} = { realpathSync };
runInNewContext(compiled, context);
const tempRoot = mkdtempSync(path.join(tmpdir(), 'cindy-pi-credential-link-'));
try {
- const secretPath = path.join(tempRoot, 'secrets', 'id_rsa');
+ const secretPath = path.join(tempRoot, 'secrets', '.env');
const ordinaryPath = path.join(tempRoot, 'ordinary.txt');
const secretLink = path.join(tempRoot, 'innocent.txt');
const ordinaryLink = path.join(tempRoot, 'ordinary-link.txt');
@@ -161,6 +165,18 @@ describe('cindy-bridge extension source', () => {
realpathSync(secretPath),
]);
expect(context.collectResolvedCredentialPaths?.({ path: ordinaryLink })).toEqual([]);
+
+ const secretCommand = `cat<${secretLink}`;
+ const ordinaryCommand = `cat<${ordinaryLink}`;
+ expect(context.parseShellInputRedirections?.(secretCommand).command.trim()).toBe('cat');
+ expect(context.bashInputReadTargets?.({ command: secretCommand })).toEqual([secretLink]);
+ expect(context.collectResolvedCredentialPaths?.(
+ context.bashInputReadTargets?.({ command: secretCommand }),
+ )).toEqual([realpathSync(secretPath)]);
+ expect(context.collectResolvedCredentialPaths?.(
+ context.bashInputReadTargets?.({ command: ordinaryCommand }),
+ )).toEqual([]);
+ expect(source).toContain("event.toolName === 'bash' ? bashInputReadTargets(event.input) : []");
expect(source).toContain('resolvedCredentialPaths: resolvedCredentialReadPaths');
} finally {
rmSync(tempRoot, { recursive: true, force: true });
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index 38324d65e8..b1fbecf6d0 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -1954,6 +1954,74 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it.skipIf(!canSymlink)(
+ 'auto mode escalates bash input redirects reached through a dotenv symlink',
+ { timeout: 60_000 },
+ async () => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-perm-auto-bash-symlink-dotenv-'));
+ try {
+ const secretPath = path.join(workingDir, 'secrets', '.env');
+ const linkPath = path.join(workingDir, 'innocent.txt');
+ mkdirSync(path.dirname(secretPath), { recursive: true });
+ writeFileSync(secretPath, 'FAKE_REDIRECT_DOTENV_SECRET=must-not-leak');
+ symlinkSync(secretPath, linkPath);
+
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('bash', { command: `cat<${linkPath}` }),
+ anthropicStreamBody('bash symlink dotenv turn finished'),
+ );
+ const reqBefore = seenRequests.length;
+ const { resolverTools } = await runPermissionTurn({
+ sessionId: 'perm-auto-bash-symlink-dotenv',
+ workingDir,
+ permissionMode: 'auto',
+ resolverBehavior: 'deny',
+ });
+ expect(resolverTools).toEqual(['bash']);
+ const followUp = seenRequests.slice(reqBefore).map((r) => r.body);
+ expect(followUp.some((b) => b.includes('FAKE_REDIRECT_DOTENV_SECRET'))).toBe(false);
+ expect(followUp.some((b) => b.includes('User denied this tool call via Cindy.'))).toBe(true);
+ } finally {
+ rmSync(workingDir, { recursive: true, force: true });
+ scriptedResponses.length = 0;
+ }
+ },
+ );
+
+ it.skipIf(!canSymlink)(
+ 'auto mode keeps ordinary bash input redirect symlinks on the readonly fast path',
+ { timeout: 60_000 },
+ async () => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-perm-auto-bash-symlink-plain-'));
+ try {
+ const targetPath = path.join(workingDir, 'ordinary-target.txt');
+ const linkPath = path.join(workingDir, 'ordinary-link.txt');
+ writeFileSync(targetPath, 'ordinary-bash-symlink-content');
+ symlinkSync(targetPath, linkPath);
+
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('bash', { command: `cat<${linkPath}` }),
+ anthropicStreamBody('bash ordinary symlink turn finished'),
+ );
+ const reqBefore = seenRequests.length;
+ const { resolverTools } = await runPermissionTurn({
+ sessionId: 'perm-auto-bash-symlink-plain',
+ workingDir,
+ permissionMode: 'auto',
+ resolverBehavior: 'deny',
+ });
+ expect(resolverTools).toEqual([]);
+ const followUp = seenRequests.slice(reqBefore).map((r) => r.body);
+ expect(followUp.some((b) => b.includes('ordinary-bash-symlink-content'))).toBe(true);
+ } finally {
+ rmSync(workingDir, { recursive: true, force: true });
+ scriptedResponses.length = 0;
+ }
+ },
+ );
+
it.skipIf(!canSymlink)(
'full access blocks credential reads reached through a workspace symlink',
{ timeout: 60_000 },
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
index 677adc8092..da1403905d 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
@@ -939,7 +939,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
);
firePermissionRequest('policy-first', 'write', { path: '/tmp/first.txt' });
- firePermissionRequest('policy-continuation', 'bash', { command: 'pnpm test' });
+ firePermissionRequest('policy-continuation', 'bash', { command: 'pnpm test' }, {
+ resolvedCredentialPaths: [],
+ });
expect((await waitForResponse('policy-first')).confirmed).toBe(true);
expect((await waitForResponse('policy-continuation')).confirmed).toBe(true);
expect(forceConfirmToolCall).toHaveBeenCalledTimes(2);
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts
index 74080352ad..1e2ef2018e 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts
@@ -74,14 +74,21 @@ describe('classifyPiToolForAutoReview', () => {
{ path: innocentLink },
['/Users/t/.ssh/id_rsa'],
)).toBe('prompt-each-time');
+ expect(verdict(
+ 'bash',
+ { command: `cat<${innocentLink}` },
+ [`${WS}/secrets/.env`],
+ )).toBe('prompt-each-time');
- // A normal symlink produces no credential evidence and keeps the readonly fast path.
+ // Normal symlinks produce no credential evidence and keep their existing fast paths.
expect(verdict('read', { path: innocentLink }, [])).toBe('auto-approve');
+ expect(verdict('bash', { command: `cat<${innocentLink}` }, [])).toBe('auto-approve');
// Non-empty evidence that no longer matches Host policy indicates protocol drift.
expect(verdict('read', { path: innocentLink }, [`${WS}/ordinary.txt`])).toBe(
'prompt-each-time',
);
expect(verdict('read', { path: innocentLink }, null)).toBe('prompt-each-time');
+ expect(verdict('bash', { command: `cat<${innocentLink}` }, null)).toBe('prompt-each-time');
});
it('catches /proc environ variants including task/<tid> (env dump = credentials)', () => {
diff --git a/packages/maker-core/src/agents/pi/auto-review-policy.ts b/packages/maker-core/src/agents/pi/auto-review-policy.ts
index 271c166dae..2f9c068473 100644
--- a/packages/maker-core/src/agents/pi/auto-review-policy.ts
+++ b/packages/maker-core/src/agents/pi/auto-review-policy.ts
@@ -90,6 +90,27 @@ function findCredentialLeaf(input: unknown, depth = 0): string | undefined {
return undefined;
}
+function canonicalCredentialEvidenceAction(
+ resolvedCredentialPaths: readonly string[] | null | undefined,
+): ReviewableAction | undefined {
+ if (resolvedCredentialPaths === null) {
+ return {
+ kind: 'other',
+ description: 'Pi credential-read evidence was malformed.',
+ requireConsent: true,
+ };
+ }
+ const resolvedCredentialHit = findCredentialLeaf(resolvedCredentialPaths);
+ if ((resolvedCredentialPaths?.length ?? 0) > 0 && !resolvedCredentialHit) {
+ return {
+ kind: 'other',
+ description: 'Pi credential-read evidence did not match the Host policy.',
+ requireConsent: true,
+ };
+ }
+ return resolvedCredentialHit ? { kind: 'read', path: resolvedCredentialHit } : undefined;
+}
+
/**
* Auto-review 下对一个 pi 工具调用给出审查档位。仅在权限档为 `auto` 时调用
* (见 pi/index.ts handleExtensionUiRequest 的 dispatcher)。纯映射,判定逻辑全在 core。
@@ -101,30 +122,19 @@ export function normalizePiToolForAutoReview(ctx: PiAutoReviewContext): Reviewab
// Bridge follows symlinks in its process, so Host must include those canonical
// targets in the same credential decision. A malformed or policy-inconsistent
// evidence payload cannot fall back to the innocent-looking link path.
- if (ctx.resolvedCredentialPaths === null) {
- return {
- kind: 'other',
- description: 'Pi credential-read evidence was malformed.',
- requireConsent: true,
- };
- }
- const resolvedCredentialHit = findCredentialLeaf(ctx.resolvedCredentialPaths);
- if ((ctx.resolvedCredentialPaths?.length ?? 0) > 0 && !resolvedCredentialHit) {
- return {
- kind: 'other',
- description: 'Pi credential-read evidence did not match the Host policy.',
- requireConsent: true,
- };
- }
+ const evidenceAction = canonicalCredentialEvidenceAction(ctx.resolvedCredentialPaths);
+ if (evidenceAction) return evidenceAction;
// 凭证特征可能落在任意字符串入参(grep 的 pattern、find 的表达式等),与 bridge
- // 的 touchesCredentialPath 同口径递归扫全字段;命中的真实路径优先作为 path 交 core 判必问。
- const credentialHit = resolvedCredentialHit ?? findCredentialLeaf(input);
+ // 的 touchesCredentialPath 同口径递归扫全字段。
+ const credentialHit = findCredentialLeaf(input);
return { kind: 'read', path: credentialHit ?? stringField(input, 'path') };
}
if (FILE_WRITE_TOOLS.has(toolName)) {
return { kind: 'file-write', path: stringField(input, 'path') };
}
if (toolName === 'bash') {
+ const evidenceAction = canonicalCredentialEvidenceAction(ctx.resolvedCredentialPaths);
+ if (evidenceAction) return evidenceAction;
return { kind: 'exec', command: stringField(input, 'command') ?? '' };
}
// MCP / 自定义 / 未知工具进入灰区,同时把完整工具名与入参交给轻量 reviewer。
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 a6ad8d3b59..1b5a4851ff 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -28,6 +28,9 @@ import {
REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS,
SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS,
} from "../shared/sensitive-credential-paths.js";
+import { shellInputRedirectionParserSource } from "../shared/shell-input-redirections.js";
+
+const SHELL_INPUT_REDIRECTION_PARSER_SOURCE = shellInputRedirectionParserSource();
export const CINDY_BRIDGE_EXTENSION_FILENAME = "cindy-bridge.ts";
@@ -113,6 +116,14 @@ const REVIEW_CREDENTIAL_PATH_PATTERNS = ${JSON.stringify(REVIEW_SENSITIVE_CREDEN
.map(({ source, flags }) => new RegExp(source, flags));
const REVIEW_CREDENTIAL_GLOB_PATTERNS = ${JSON.stringify(REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS)};
+${SHELL_INPUT_REDIRECTION_PARSER_SOURCE}
+
+function bashInputReadTargets(input: unknown): string[] {
+ if (!input || typeof input !== 'object') return [];
+ const command = (input as Record<string, unknown>).command;
+ return typeof command === 'string' ? parseShellInputRedirections(command).targets : [];
+}
+
// 递归扫全部字符串叶子(含数组 / 嵌套对象),深度上限防环/超大入参。工具入参把路径
// 放进 { paths: [...] } 或 { opts: { path } } 时也能命中,不止顶层 string 字段。
function touchesCredentialPath(input: unknown, depth = 0): boolean {
@@ -1170,16 +1181,19 @@ export default async function cindyBridge(pi: any) {
if (event.toolName === 'bash' && commandReadsProcessEnviron(event.input?.command)) {
return { block: true, reason: 'Cindy blocks reading process environment (/proc/*/environ), even with Full access.' };
}
- // 凭证/密钥路径的内置只读工具(read/grep/find/ls)在 Pi 父进程内执行,而父进程 env
- // 必须保留代理会话 token 与 BYOM keys($ENV 请求期解析、bridge client 使用)。Full
- // access 若放行 read /proc/self/environ 这类路径,模型可直接取 token 调回环代理,
- // 绕过审批盗刷当前会话额度(greptile 报)→ 即使 bypassPermissions 也硬拦。原始路径
- // 命不中时还要跟随符号链接:工作区内的 link 可指向敏感目标,realpath 后再判一次。
+ // 凭证/密钥路径的内置只读工具与 bash 输入重定向都必须携带 canonical
+ // 证据。bash 的原始 input 是整条命令,不能直接 realpath;先用与 Host 相同的
+ // parser 提取真实输入目标,才能识别工作区 symlink 指向的凭证文件。
+ const bashReadTargets = event.toolName === 'bash' ? bashInputReadTargets(event.input) : [];
const resolvedCredentialReadPaths = READONLY_BUILTINS.has(event.toolName)
? [...new Set(collectResolvedCredentialPaths(event.input))]
- : [];
- const credentialRead = READONLY_BUILTINS.has(event.toolName)
- && (touchesCredentialPath(event.input) || resolvedCredentialReadPaths.length > 0);
+ : event.toolName === 'bash'
+ ? [...new Set(collectResolvedCredentialPaths(bashReadTargets))]
+ : [];
+ const credentialRead = (READONLY_BUILTINS.has(event.toolName)
+ && touchesCredentialPath(event.input))
+ || (event.toolName === 'bash' && 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/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index f5e5d9739e..db3520bb8a 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -3443,12 +3443,12 @@ export class PiAgent extends BaseAgent {
/* keep defaults */
}
if (
- (toolName === 'read' || toolName === 'grep' || toolName === 'find' || toolName === 'ls')
+ (toolName === 'read' || toolName === 'grep' || toolName === 'find' || toolName === 'ls' || toolName === 'bash')
&& resolvedCredentialPaths === undefined
) {
- // Readonly calls only reach Host after the bridge identifies credential risk.
- // Missing canonical-path evidence therefore means an old or malformed bridge,
- // not a safe read; require explicit consent instead of trusting the link name.
+ // Readonly calls and bash input redirects only reach Host with bridge-supplied
+ // canonical-path evidence. Missing evidence means an old or malformed bridge,
+ // not a safe read; require explicit consent instead of trusting a link name.
resolvedCredentialPaths = null;
}
const {
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 ff32ee5702..93595f478f 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
@@ -385,6 +385,11 @@ describe('对抗语料 — dotenv 凭证路径', () => {
for (const command of [
'cat .env',
'cat <.env',
+ 'cat<.env',
+ 'cat<"./.env.local"',
+ 'env -- cat<.env.production',
+ 'grep API_KEY<.env.test',
+ 'cat<.e\\nv',
'cat <".env"',
'cat 0<.env.local',
'env -- cat <./.env.production',
@@ -559,6 +564,8 @@ describe('对抗语料 — dotenv 凭证路径', () => {
it.each([
['cat .environment', 'auto-approve'],
['cat <README.md', 'auto-approve'],
+ ['cat<README.md', 'auto-approve'],
+ ['env -- cat<ordinary.txt', 'auto-approve'],
["cat '<.env'", 'auto-approve'],
['cat <<<.env', 'auto-approve'],
['cat 0<README.md', 'auto-approve'],
diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.ts
index 61b393ab1a..3d4696d10f 100644
--- a/packages/maker-core/src/agents/shared/auto-review.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.ts
@@ -42,6 +42,7 @@ import {
isSensitiveCredentialPath,
SENSITIVE_CREDENTIAL_PATH_PATTERNS,
} from './sensitive-credential-paths.js';
+import { parseShellInputRedirections } from './shell-input-redirections.js';
export { isSensitiveCredentialPath } from './sensitive-credential-paths.js';
@@ -4886,16 +4887,6 @@ function shellOperandCouldMatchDotenv(
});
}
-function inputRedirectionTargets(command: string): string[] {
- const targets: string[] = [];
- const re = /(?:^|[\s;&|()])(?:\d*|\{[A-Za-z_][A-Za-z0-9_]*\})?(?:<>|<(?![<&(]))\s*("(?:[^"\\]|\\.)*"|'[^']*'|[^\s;&|<>()]+)/g;
- for (const match of command.matchAll(re)) {
- const target = match[1].replace(/['"]/g, '');
- if (target) targets.push(target);
- }
- return targets;
-}
-
function readerArgumentsReadDotenv(
bin: string,
args: readonly string[],
@@ -5265,8 +5256,9 @@ function shellCommandReadsDotenv(
opts: ShellReviewOptions,
): boolean {
for (const segment of splitTopLevelSegments(command)) {
+ const inputRedirections = parseShellInputRedirections(segment);
const unwrapped = unwrapCommand(
- stripShellControlTokens(tokenize(segment)),
+ stripShellControlTokens(tokenize(inputRedirections.command)),
opts.cwd ?? workspaceRoots[0],
opts.cwdUnknown === true,
);
@@ -5288,7 +5280,7 @@ function shellCommandReadsDotenv(
}
if (!DOTENV_FILE_READER_BINS.has(bin)) continue;
- if (inputRedirectionTargets(segment).some((target) => shellOperandCouldMatchDotenv(target))) return true;
+ if (inputRedirections.targets.some((target) => shellOperandCouldMatchDotenv(target))) return true;
const args = tokens.slice(1);
if (grepRecursesIntoPotentialDotenv(bin, args)) return true;
if (bin === 'rg' && rgSearchesPotentialDotenv(args)) return true;
@@ -5382,7 +5374,8 @@ export function classifyShellCommand(
let trackedCwdUnknown = opts.cwdUnknown === true;
const aliasFirmlinks = (opts.platform ?? process.platform) === 'darwin';
for (const seg of segments) {
- const segTokens = stripShellControlTokens(tokenize(seg));
+ const parsedSegment = parseShellInputRedirections(seg);
+ const segTokens = stripShellControlTokens(tokenize(parsedSegment.command));
const dirChange = directoryChangeTarget(segTokens);
if (dirChange.changesDirectory) {
const segBin = executableName(segTokens[0] ?? '');
@@ -5401,7 +5394,7 @@ export function classifyShellCommand(
needsPrompt = true; // 区外/动态目标、source/popd:与改动前同档(灰区)。
continue;
}
- const v = classifyShellSegment(seg, workspaceRoots, opts);
+ const v = classifyShellSegment(parsedSegment.command, workspaceRoots, opts);
if (v === 'prompt-each-time') return 'prompt-each-time';
if (v === 'prompt') needsPrompt = 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
new file mode 100644
index 0000000000..40324a96f7
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/shell-input-redirections.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseShellInputRedirections } from './shell-input-redirections.js';
+
+describe('parseShellInputRedirections', () => {
+ it.each([
+ ['cat<.env', '.env', 'cat'],
+ ['cat < ".env.local"', '.env.local', 'cat'],
+ ['env -- cat 0<./.env.production', './.env.production', 'env -- cat 0'],
+ ['cat<.e"nv"', '.env', 'cat'],
+ ['cat<.e\\nv', '.env', 'cat'],
+ ['cat<>README.md', 'README.md', 'cat'],
+ ])('extracts the input target from %s', (command, target, stripped) => {
+ const parsed = parseShellInputRedirections(command);
+ expect(parsed.command.trim()).toBe(stripped);
+ expect(parsed.targets).toEqual([target]);
+ });
+
+ it.each([
+ "grep '<.env' data.txt",
+ "cat '<.env'",
+ 'cat <<<.env',
+ 'cat <<EOF',
+ 'cat <&0',
+ 'cat <(printf x)',
+ 'cat \\<.env',
+ ])('does not treat data or non-file input syntax as a target: %s', (command) => {
+ expect(parseShellInputRedirections(command)).toEqual({ command, targets: [] });
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/shell-input-redirections.ts b/packages/maker-core/src/agents/shared/shell-input-redirections.ts
new file mode 100644
index 0000000000..d4eb178a8d
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/shell-input-redirections.ts
@@ -0,0 +1,125 @@
+export type ParsedShellInputRedirections = {
+ command: string;
+ targets: string[];
+};
+
+export function readShellRedirectionTarget(
+ command: string,
+ start: number,
+): { target: string; end: number } {
+ let target = '';
+ let quote: "'" | '"' | null = null;
+ let cursor = start;
+ while (cursor < command.length) {
+ const char = command[cursor];
+ if (quote) {
+ if (char === quote) {
+ quote = null;
+ cursor += 1;
+ continue;
+ }
+ if (char === '\\' && quote === '"' && cursor + 1 < command.length) {
+ target += command[cursor + 1];
+ cursor += 2;
+ continue;
+ }
+ target += char;
+ cursor += 1;
+ continue;
+ }
+ if (char === "'" || char === '"') {
+ quote = char;
+ cursor += 1;
+ continue;
+ }
+ if (char === '\\' && cursor + 1 < command.length) {
+ target += command[cursor + 1];
+ cursor += 2;
+ continue;
+ }
+ if (/\s/.test(char) || /[;&|()<>]/.test(char)) break;
+ target += char;
+ cursor += 1;
+ }
+ return { target, end: cursor };
+}
+
+export function parseShellInputRedirections(command: string): ParsedShellInputRedirections {
+ const targets: string[] = [];
+ let stripped = '';
+ let quote: "'" | '"' | null = null;
+
+ for (let index = 0; index < command.length;) {
+ const char = command[index];
+ if (quote) {
+ stripped += char;
+ if (char === '\\' && quote === '"' && index + 1 < command.length) {
+ stripped += command[index + 1];
+ index += 2;
+ continue;
+ }
+ if (char === quote) quote = null;
+ index += 1;
+ continue;
+ }
+
+ if (char === '\\' && index + 1 < command.length) {
+ stripped += char + command[index + 1];
+ index += 2;
+ continue;
+ }
+ if (char === "'" || char === '"') {
+ quote = char;
+ stripped += char;
+ index += 1;
+ continue;
+ }
+ if (char !== '<') {
+ stripped += char;
+ index += 1;
+ continue;
+ }
+
+ const next = command[index + 1];
+ if (next === '<') {
+ let end = index + 2;
+ while (command[end] === '<') end += 1;
+ stripped += command.slice(index, end);
+ index = end;
+ continue;
+ }
+ if (next === '&' || next === '(') {
+ stripped += char + next;
+ index += 2;
+ continue;
+ }
+
+ let cursor = index + (next === '>' ? 2 : 1);
+ while (/\s/.test(command[cursor] ?? '')) cursor += 1;
+ const parsedTarget = readShellRedirectionTarget(command, cursor);
+ if (parsedTarget.target) targets.push(parsedTarget.target);
+ stripped += ' ';
+ index = parsedTarget.end;
+ }
+
+ return { command: stripped, targets };
+}
+
+export function shellInputRedirectionParserSource(): string {
+ const helperName = readShellRedirectionTarget.name;
+ const parserName = parseShellInputRedirections.name;
+ if (!helperName || !parserName) throw new Error('Shell input redirection parser names are unavailable');
+ const aliases = [
+ helperName === 'readShellRedirectionTarget'
+ ? ''
+ : `const readShellRedirectionTarget = ${helperName};`,
+ parserName === 'parseShellInputRedirections'
+ ? ''
+ : `const parseShellInputRedirections = ${parserName};`,
+ ].filter(Boolean);
+ return [
+ readShellRedirectionTarget.toString(),
+ parseShellInputRedirections.toString(),
+ ...aliases,
+ ].join('\n');
+}