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): resolve wrapped directory changes

Chris284d3b99df2e
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 f3f51cd590..8f337562b7 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -266,6 +266,9 @@ describe('cindy-bridge extension source', () => {
const cdPathRoot = path.join(tempRoot, 'cdpath-root');
const cdPathSubDir = path.join(cdPathRoot, 'sub');
const cdPathSecretLink = path.join(cdPathSubDir, 'link');
+ const cwdSwitchName = 'cwd-switch-link';
+ const rootCwdSwitchOrdinaryLink = path.join(tempRoot, cwdSwitchName);
+ const nestedCwdSwitchSecretLink = path.join(nestedDir, cwdSwitchName);
mkdirSync(path.dirname(secretPath), { recursive: true });
mkdirSync(nestedDir, { recursive: true });
mkdirSync(dashDir, { recursive: true });
@@ -283,6 +286,8 @@ describe('cindy-bridge extension source', () => {
symlinkSync(ordinaryPath, nestedCdRedirectOrdinaryLink);
symlinkSync(ordinaryPath, nestedOrdinaryReadLink);
symlinkSync(secretPath, cdPathSecretLink);
+ symlinkSync(ordinaryPath, rootCwdSwitchOrdinaryLink);
+ symlinkSync(secretPath, nestedCwdSwitchSecretLink);
symlinkSync(ordinaryPath, ordinaryLink);
expect(context.collectResolvedCredentialPaths?.({ path: secretLink })).toEqual([
@@ -417,6 +422,47 @@ describe('cindy-bridge extension source', () => {
context.bashInputReadTargets?.({ command: redirectedCommand }),
), redirectedCommand).toEqual([realpathSync(secretPath)]);
}
+ for (const command of [
+ `2>/dev/null cd ${nestedDir} && cat <${cwdSwitchName}`,
+ `>/dev/null builtin cd ${nestedDir} && cat <${cwdSwitchName}`,
+ `builtin 2>/dev/null cd ${nestedDir} && cat <${cwdSwitchName}`,
+ `command -p 2>/dev/null cd ${nestedDir} && cat <${cwdSwitchName}`,
+ `command -- cd ${nestedDir} && cat <${cwdSwitchName}`,
+ `builtin command cd ${nestedDir} && cat <${cwdSwitchName}`,
+ `command builtin 2>/dev/null pushd ${nestedDir} && cat <${cwdSwitchName}`,
+ `{saved}>/dev/null builtin cd ${nestedDir} && cat <${cwdSwitchName}`,
+ `(2>/dev/null builtin cd ${nestedDir} && cat <${cwdSwitchName})`,
+ ]) {
+ const evidence = context.bashInputReadEvidence?.({ command });
+ expect(evidence, command).toEqual({ targets: [nestedCwdSwitchSecretLink], unresolved: false });
+ expect(context.collectResolvedCredentialPaths?.(evidence?.targets), command)
+ .toEqual([realpathSync(secretPath)]);
+ }
+ expect(context.bashInputReadEvidence?.({
+ command: `true && 2>/dev/null builtin pushd ${nestedDir} && cat <${cwdSwitchName}`,
+ })).toEqual({
+ targets: [rootCwdSwitchOrdinaryLink, nestedCwdSwitchSecretLink],
+ unresolved: false,
+ });
+ expect(context.bashInputReadEvidence?.({
+ command: `2>/missing builtin cd ${nestedDir}; cat <${cwdSwitchName}`,
+ })).toEqual({
+ targets: [rootCwdSwitchOrdinaryLink, nestedCwdSwitchSecretLink],
+ unresolved: false,
+ });
+ const dynamicPrefixedEvidence = context.bashInputReadEvidence?.({
+ command: `>$(printf out) builtin cd ${nestedDir} && cat <ordinary-link.txt`,
+ });
+ expect(dynamicPrefixedEvidence?.unresolved).toBe(true);
+ expect(context.collectResolvedCredentialPaths?.(dynamicPrefixedEvidence?.targets)).toEqual([]);
+ expect(context.bashInputReadEvidence?.({
+ command: '>$(printf cd) cat <ordinary-link.txt',
+ })).toEqual({ targets: [ordinaryLink], unresolved: false });
+ const ordinaryPrefixedCommand = `2>/dev/null builtin cd ${nestedDir} && cat <${nestedOrdinaryReadName}`;
+ const ordinaryPrefixedEvidence = context.bashInputReadEvidence?.({ command: ordinaryPrefixedCommand });
+ expect(ordinaryPrefixedEvidence).toEqual({ targets: [nestedOrdinaryReadLink], unresolved: false });
+ expect(context.collectResolvedCredentialPaths?.(ordinaryPrefixedEvidence?.targets)).toEqual([]);
+
expect(context.bashInputReadEvidence?.({
command: `cd ${nestedDir} >/dev/null && cat <${scopedLinkName}`,
})).toEqual({ targets: [nestedScopedOrdinaryLink], unresolved: false });
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 fa82a64105..d5732a7674 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
@@ -2120,6 +2120,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
writeFileSync(secretPath, 'FAKE_REDIRECT_DOTENV_SECRET=must-not-leak');
writeFileSync(ordinaryPath, 'ordinary-content');
symlinkSync('../secrets/.env', postCdLink);
+ symlinkSync(ordinaryPath, path.join(workingDir, 'link'));
symlinkSync(secretPath, path.join(workingDir, escapedLinkName));
symlinkSync(secretPath, path.join(workingDir, cdRedirectLinkName));
symlinkSync(ordinaryPath, path.join(subDir, cdRedirectLinkName));
@@ -2127,6 +2128,10 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
for (const [sessionId, command] of [
['perm-auto-bash-symlink-dotenv-post-cd', 'cd sub >/dev/null && cat<link'],
+ ['perm-auto-bash-symlink-dotenv-leading-redirect', '2>/dev/null cd sub && cat<link'],
+ ['perm-auto-bash-symlink-dotenv-builtin-cd', 'builtin cd sub && cat<link'],
+ ['perm-auto-bash-symlink-dotenv-leading-builtin', '2>/dev/null builtin cd sub && cat<link'],
+ ['perm-auto-bash-symlink-dotenv-builtin-pushd', 'builtin pushd sub >/dev/null && cat<link'],
['perm-auto-bash-symlink-dotenv-backslash', `cat <"${escapedLinkName}"`],
['perm-auto-bash-symlink-dotenv-cd-redirect', `cd sub <>${cdRedirectLinkName} && cat <ordinary`],
] as const) {
@@ -2147,6 +2152,24 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
expect(followUp.some((b) => b.includes('FAKE_REDIRECT_DOTENV_SECRET')), command).toBe(false);
expect(followUp.some((b) => b.includes('User denied this tool call via Cindy.')), command).toBe(true);
}
+
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('bash', { command: '2>/dev/null builtin cd sub && cat<link' }),
+ anthropicStreamBody('bash Full Access prefixed cd turn finished'),
+ );
+ const fullAccessReqBefore = seenRequests.length;
+ const fullAccessTurn = await runPermissionTurn({
+ sessionId: 'perm-full-access-bash-prefixed-builtin-cd',
+ workingDir,
+ permissionMode: 'bypassPermissions',
+ resolverBehavior: 'allow',
+ });
+ expect(fullAccessTurn.resolverTools).toEqual([]);
+ const fullAccessFollowUp = seenRequests.slice(fullAccessReqBefore).map((request) => request.body);
+ expect(fullAccessFollowUp.some((body) => body.includes('FAKE_REDIRECT_DOTENV_SECRET'))).toBe(false);
+ expect(fullAccessFollowUp.some((body) => body.includes('Cindy blocks reading credential or key paths')))
+ .toBe(true);
} finally {
rmSync(workingDir, { recursive: true, force: true });
scriptedResponses.length = 0;
@@ -2228,7 +2251,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
);
it.skipIf(!canSymlink)(
- 'auto mode keeps ordinary bash input redirect symlinks on the readonly fast path',
+ 'ordinary bash input redirect symlinks keep their existing permission behavior',
{ timeout: 60_000 },
async () => {
const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-perm-auto-bash-symlink-plain-'));
@@ -2246,15 +2269,15 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
scriptedResponses.length = 0;
scriptedResponses.push(
anthropicToolUseBody('bash', {
- command: `cd sub <${redirectLinkName} && cat<link`,
+ command: `2>/dev/null builtin cd sub <${redirectLinkName} && cat<link`,
}),
anthropicStreamBody('bash ordinary symlink turn finished'),
);
const reqBefore = seenRequests.length;
const { resolverTools } = await runPermissionTurn({
- sessionId: 'perm-auto-bash-symlink-plain',
+ sessionId: 'perm-full-access-bash-prefixed-symlink-plain',
workingDir,
- permissionMode: 'auto',
+ permissionMode: 'bypassPermissions',
resolverBehavior: 'deny',
});
expect(resolverTools).toEqual([]);
@@ -2264,7 +2287,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
scriptedResponses.length = 0;
scriptedResponses.push(
anthropicToolUseBody('bash', {
- command: `cd sub <>${redirectLinkName} && cat<link`,
+ command: `2>/dev/null command -- cd sub <>${redirectLinkName} && cat<link`,
}),
anthropicStreamBody('bash ordinary read-write symlink turn finished'),
);
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 c87e1f7c5e..66560a8fee 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -316,26 +316,165 @@ function bashInheritedDirectoryChangeIsUncertain(target: string): boolean {
return cdPath.split(':').some((entry) => entry.length > 0 && path.normalize(entry) !== '.');
}
+type BashLeadingRedirection = { end: number; unresolved: boolean };
+type BashDirectoryChangeHead = {
+ cursor: number;
+ hadRedirection: boolean;
+ unresolved: boolean;
+};
+
+function bashInlinePaddingEnd(command: string, start: number): number {
+ let cursor = start;
+ while (cursor < command.length) {
+ while (/[ \t\r]/.test(command[cursor] ?? '')) cursor += 1;
+ if (command[cursor] !== '\\' || command[cursor + 1] !== '\n') break;
+ cursor += 2;
+ }
+ return cursor;
+}
+
+function bashLeadingRedirectionAt(command: string, start: number): BashLeadingRedirection | null {
+ let redirect = start;
+ const namedFd = /^\{[A-Za-z_][A-Za-z0-9_]*\}/.exec(command.slice(redirect));
+ if (namedFd) redirect += namedFd[0].length;
+ else while (/\d/.test(command[redirect] ?? '')) redirect += 1;
+ let operator = '';
+ if (command.startsWith('&>>', redirect)) operator = '&>>';
+ else if (command.startsWith('&>', redirect)) operator = '&>';
+ else {
+ for (const candidate of ['<<<', '<>', '<&', '>&', '>>', '>|', '<', '>']) {
+ if (command.startsWith(candidate, redirect)) {
+ operator = candidate;
+ break;
+ }
+ }
+ }
+ if (!operator) return null;
+ if (command.startsWith('<<', redirect) && !command.startsWith('<<<', redirect)) {
+ return { end: redirect + 2, unresolved: true };
+ }
+ const targetStart = bashInlinePaddingEnd(command, redirect + operator.length);
+ const target = readShellRedirectionTarget(command, targetStart);
+ return {
+ end: target.end,
+ unresolved: !target.target || target.unresolved,
+ };
+}
+
+function bashUnresolvedHeadHasDirectoryChange(codeMask: string, start: number): boolean {
+ let visible = '';
+ let depth = 0;
+ for (let index = start; index < codeMask.length; index += 1) {
+ const char = codeMask.charAt(index);
+ if (char === '(') {
+ depth += 1;
+ visible += ' ';
+ continue;
+ }
+ if (char === ')') {
+ if (depth === 0) break;
+ depth -= 1;
+ visible += ' ';
+ continue;
+ }
+ if (depth > 0) {
+ visible += /\s/.test(char) ? char : ' ';
+ continue;
+ }
+ if (/[;&|\n]/.test(char)) break;
+ visible += char;
+ }
+ return /\b(?:(?:command|builtin)\s+)*(?:cd|pushd)(?:\s|$)/.test(visible);
+}
+
+function bashDirectoryChangeHead(
+ command: string,
+ codeMask: string,
+ start: number,
+): BashDirectoryChangeHead | null {
+ let cursor = bashInlinePaddingEnd(command, start);
+ let hadRedirection = false;
+ let unresolved = false;
+ while (true) {
+ const redirection = bashLeadingRedirectionAt(command, cursor);
+ if (!redirection) break;
+ hadRedirection = true;
+ unresolved ||= redirection.unresolved;
+ cursor = bashInlinePaddingEnd(command, redirection.end);
+ }
+
+ let word = readShellRedirectionTarget(command, cursor);
+ if (!word.target || word.unresolved) {
+ if (unresolved && bashUnresolvedHeadHasDirectoryChange(codeMask, cursor)) {
+ return { cursor, hadRedirection, unresolved: true };
+ }
+ return null;
+ }
+ while (word.target === 'command' || word.target === 'builtin') {
+ const wrapper = word.target;
+ cursor = bashInlinePaddingEnd(command, word.end);
+ while (true) {
+ const redirection = bashLeadingRedirectionAt(command, cursor);
+ if (redirection) {
+ hadRedirection = true;
+ unresolved ||= redirection.unresolved;
+ cursor = bashInlinePaddingEnd(command, redirection.end);
+ continue;
+ }
+ word = readShellRedirectionTarget(command, cursor);
+ if (wrapper !== 'command' || (word.target !== '--' && !/^-p+$/.test(word.target))) break;
+ cursor = bashInlinePaddingEnd(command, word.end);
+ }
+ if (!word.target || word.unresolved) return unresolved
+ ? { cursor, hadRedirection, unresolved: true }
+ : null;
+ }
+
+ if ((word.target !== 'cd' && word.target !== 'pushd') || word.unresolved) {
+ if (unresolved && bashUnresolvedHeadHasDirectoryChange(codeMask, cursor)) {
+ return { cursor, hadRedirection, unresolved: true };
+ }
+ return null;
+ }
+ return { cursor: word.end, hadRedirection, unresolved };
+}
+
function bashWorkingDirectoryCandidates(command: string): BashPathCandidates {
let candidates = [process.cwd()];
let unresolved = false;
const codeMask = bashShellCodeMask(command);
- 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)) {
+ const commandStart = /(?:^(?=[^;&|(){}\n])|[;&|(){}\n])\s*(?:(?:if|then|elif|else|while|until|do)\s+)?/g;
+ for (const match of codeMask.matchAll(commandStart)) {
const matchIndex = match.index ?? 0;
- let cursor = matchIndex + match[0].length;
+ const head = bashDirectoryChangeHead(command, codeMask, matchIndex + match[0].length);
+ if (!head) continue;
+ if (head.unresolved) {
+ unresolved = true;
+ continue;
+ }
+ let cursor = head.cursor;
+ let hadRedirection = head.hadRedirection;
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 parsed = readShellRedirectionTarget(command, bashInlinePaddingEnd(command, cursor));
let optionsEnded = false;
- while (parsed.target === '--' || /^-[LPen]+$/.test(parsed.target)) {
+ while (true) {
+ cursor = bashInlinePaddingEnd(command, cursor);
+ const redirection = bashLeadingRedirectionAt(command, cursor);
+ if (redirection) {
+ hadRedirection = true;
+ unresolved ||= redirection.unresolved;
+ cursor = redirection.end;
+ parsed = readShellRedirectionTarget(command, bashInlinePaddingEnd(command, cursor));
+ continue;
+ }
+ if (parsed.target !== '--' && !/^-[LPen]+$/.test(parsed.target)) break;
if (parsed.target === '--') optionsEnded = true;
cursor = parsed.end;
- while (/\s/.test(command[cursor] ?? '')) cursor += 1;
- parsed = readShellRedirectionTarget(command, cursor);
+ parsed = readShellRedirectionTarget(command, bashInlinePaddingEnd(command, cursor));
}
if (!parsed.target || parsed.unresolved || (!optionsEnded && parsed.target.startsWith('-'))) {
unresolved = true;
@@ -369,7 +508,7 @@ function bashWorkingDirectoryCandidates(command: string): BashPathCandidates {
codeMask.slice(operatorEvidence.end),
);
if (operator === '||' || branchMayHaveBeenSkipped || precededByConditionalOperator
- || (operatorEvidence.hadRedirection && (operator === ';' || operator === '\n'))) {
+ || ((hadRedirection || operatorEvidence.hadRedirection) && (operator === ';' || operator === '\n'))) {
candidates = [...new Set([...candidates, ...changed])];
} else if (changed.length > 0) {
candidates = [...new Set(changed)];