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): assemble approved project skills safely

nanaf3ebdd8105be
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index b5936a1e64..1d1bdc9a7e 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -196,6 +196,8 @@ export interface BuildPiAgentOpts {
resolvePiRuntimeModelDescriptor?: AgentDeps['resolvePiRuntimeModelDescriptor'];
resolvePiGatewayModelDescriptor?: AgentDeps['resolvePiGatewayModelDescriptor'];
getGhostRosterPrompt?: AgentDeps['getGhostRosterPrompt'];
+ /** Trusted project-approval authority; omitted until the host has one, which fails closed. */
+ resolvePiProjectTrustInput?: AgentDeps['resolvePiProjectTrustInput'];
}
/** Cindy wire protocol → pi models.json api 形态。 */
@@ -380,5 +382,6 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {
resolvePiRuntimeModelDescriptor: opts.resolvePiRuntimeModelDescriptor,
resolvePiGatewayModelDescriptor: opts.resolvePiGatewayModelDescriptor,
getGhostRosterPrompt: opts.getGhostRosterPrompt,
+ resolvePiProjectTrustInput: opts.resolvePiProjectTrustInput,
});
}
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index a07adf3677..3c989108ff 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -90,6 +90,14 @@ Cindy 显式设置:models.json、`--append-system-prompt`、`--session-dir`、
7. **统一会话树真相**:Cindy `parentSessionId` 是外层独立会话分叉;Pi JSONL entry tree 是当前
Pi 会话内分支。Pi 导航后必须通过 `session.treeRehydrate` 原子替换 SQLite 可见投影,旧行仅
soft-hide;切换只改对话上下文,不得声称或尝试回滚工作区文件。
+8. **项目资源显式装配**:root、只读 subagent 与离线 fork 启动 Pi 时都必须显式传
+ `--no-approve --no-extensions`;root 仅用重复 `--extension` 回装 Cindy 自有 bridge/subagent
+ 与 pinned plan-mode,并仅用重复 `--skill` 装配 host 从 PR3 approval snapshot 判定 eligible
+ 的 canonical 项目 skill 路径。不得读取/复制项目 `.pi/settings.json`,不得传 `--approve`,
+ 不得依赖 `PI_OFFLINE=1` 代替 packages/extensions 硬门。root 不传 `--no-skills`,以保留现有
+ user/global skill 行为;项目 skill 的 `loaded` 只能由当前会话 `get_commands` 的 exact
+ temporary/local provenance 证明。approval 真源缺失、异常、撤销、失效或路径消失时,新会话
+ 一律不带项目 `--skill`,并在 per-session runtime manifest 记录诊断原因。
## 5. 已交付(2026-07 里程碑)
@@ -99,6 +107,9 @@ Cindy 显式设置:models.json、`--append-system-prompt`、`--session-dir`、
- 自动化安全网:maker-core PI 定向 + 端到端集成(真 pi 二进制 + 真 bridge + 假模型工具调用)
覆盖安全命令静默执行 / 危险命令升级并 deny 拦截 / 区内写落盘 / 凭证读升级 / 普通读直通 /
斜杠转义 / models.json 计费透传。
+- PR4 项目资源桥:只装配 Cindy 明确批准的 `.pi/skills` 与 cwd→git root 范围内
+ `.agents/skills`;真实 pinned Pi RPC 夹具覆盖未批准/显式 skills、重复名、并发隔离,以及
+ 项目声明 npm/git/local packages 与 extensions 时零 install/clone/第三方执行。
## 6. 上线门禁
@@ -138,8 +149,9 @@ Cindy 显式设置:models.json、`--append-system-prompt`、`--session-dir`、
## 7. 上线后路线图(已与 Chris 对齐)
-项目 trust 的输入/输出契约见 [`pi-project-trust.md`](pi-project-trust.md)。该契约不改变本节
-所述运行时默认,也不授权 `--approve`、trust.json 或用户 Pi home 复用;这些属于后续装配 PR。
+项目 trust 的输入/输出契约见 [`pi-project-trust.md`](pi-project-trust.md)。PR4 已按该契约
+收缩为 skills-only 显式装配;它不授权 `--approve`、trust.json、项目原始 settings 或用户
+Pi home 复用。settings/packages/extensions 仍属于后续独立安全评审范围。
> 续做指南(每项怎么接着做 + file:line 锚点 + 坑)见 `docs/dev-rules/pi-remaining-work.md`。
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 3fd0e6b0e4..c4ca153f93 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -70,6 +70,7 @@ import type {
ListCustomizationsResult,
} from '../types/customizations.js';
import type { PiRuntimeCapabilityManifest } from '../types/pi-runtime-capabilities.js';
+import type { PiProjectTrustInputSnapshot } from '../types/pi-project-trust.js';
import { scanWorkspaceFileResources } from './shared/palette-scanner.js';
import type { AutoReviewDelegate } from './shared/auto-review-decision.js';
@@ -357,6 +358,17 @@ export interface AgentDeps {
*/
resolvePiAgentHome?: () => string | undefined;
+ /**
+ * Pi-only: resolve the immutable Cindy project-approval input for one new
+ * runtime. The host owns identity canonicalization, approval audit/revocation,
+ * and discovered-resource provenance. Missing/throwing resolvers fail closed.
+ */
+ resolvePiProjectTrustInput?: (ctx: {
+ sessionId?: string;
+ workingDir: string;
+ remoteHostId?: string;
+ }) => Promise<PiProjectTrustInputSnapshot | null>;
+
/**
* pi 专用钩子:把 mcpProviders 转成 pi 子进程可消费的 MCP 桥配置。
*
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts
index 8b16835b55..f8bbc52b23 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts
@@ -57,8 +57,12 @@ describe('cindy-subagent extension source', () => {
expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toMatch(/TASK_TIMEOUT_MS\s*=/);
// 子代理不写会话文件,不污染 Cindy 的会话 JSONL。
expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("'--no-session'");
- // 必须**不**传 --no-extensions:否则子进程不加载 cindy-bridge,权限门对子代理失效。
- expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain('--no-extensions');
+ // 子 Pi 与父 Pi 使用同一条 project hard gate;权限门只经显式 bridge 回装。
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("'--no-approve'");
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("'--no-extensions'");
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(
+ "'--extension', join(configHome, 'extensions', 'cindy-bridge.ts')",
+ );
});
it('reads model and provider from the runtime snapshot file, not from spawn-time env', () => {
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
index 38ab97f614..24f7e56a78 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
@@ -114,6 +114,11 @@ interface RunOptions {
configHome: string;
sessionDir: string;
approve: boolean;
+ /** Additional CLI resource gates/explicit paths under test. */
+ extraArgs?: string[];
+ /** The hard-gate probe disables offline mode so it cannot mask install attempts. */
+ offline?: boolean;
+ extraEnv?: NodeJS.ProcessEnv;
beforeRpcRequest?: () => Promise<void>;
spawnProcess?: typeof spawn;
startupTimeoutMs?: number;
@@ -132,7 +137,11 @@ afterEach(() => {
for (const root of fixtureRoots.splice(0)) rmSync(root, { recursive: true, force: true });
});
-function createSafeEnv(root: string, configHome: string): NodeJS.ProcessEnv {
+function createSafeEnv(
+ root: string,
+ configHome: string,
+ options: Pick<RunOptions, 'offline' | 'extraEnv'> = {},
+): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {};
for (const key of SAFE_ENV_KEYS) {
if (process.env[key] !== undefined) env[key] = process.env[key];
@@ -146,10 +155,10 @@ function createSafeEnv(root: string, configHome: string): NodeJS.ProcessEnv {
env.USERPROFILE = home;
env.XDG_CONFIG_HOME = xdg;
env.PI_CODING_AGENT_DIR = configHome;
- env.PI_OFFLINE = '1';
+ if (options.offline !== false) env.PI_OFFLINE = '1';
env.PI_TELEMETRY = '0';
env.NO_COLOR = '1';
- return env;
+ return { ...env, ...options.extraEnv };
}
function writeSkill(dir: string, name: string): void {
@@ -258,7 +267,7 @@ function normalizeSkills(commands: PiCommand[], fixture: Fixture): NormalizedSki
.sort((a, b) => a.name.localeCompare(b.name));
}
-function piArgs(options: Pick<RunOptions, 'sessionDir' | 'approve'>): string[] {
+function piArgs(options: Pick<RunOptions, 'sessionDir' | 'approve' | 'extraArgs'>): string[] {
return [
'--mode', 'rpc',
'--provider', 'dummy',
@@ -266,6 +275,7 @@ function piArgs(options: Pick<RunOptions, 'sessionDir' | 'approve'>): string[] {
'--session-dir', options.sessionDir,
'--no-context-files',
options.approve ? '--approve' : '--no-approve',
+ ...(options.extraArgs ?? []),
];
}
@@ -330,7 +340,7 @@ async function runGetCommands(options: RunOptions): Promise<RunResult> {
[...(options.binaryPrefixArgs ?? []), ...piArgs(options)],
{
cwd: options.cwd,
- env: createSafeEnv(path.dirname(options.configHome), options.configHome),
+ env: createSafeEnv(path.dirname(options.configHome), options.configHome, options),
stdio: ['pipe', 'pipe', 'pipe'],
},
);
@@ -718,7 +728,11 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts
const loadedProjectBaseDirs = new Map(
result.commands.flatMap((command) => {
const baseDir = command.sourceInfo?.baseDir;
- if (command.source !== 'skill' || command.sourceInfo?.scope !== 'project' || !baseDir) {
+ if (
+ command.source !== 'skill'
+ || command.sourceInfo?.scope !== 'project'
+ || typeof baseDir !== 'string'
+ ) {
return [];
}
return [[command.name, canonicalPath(baseDir)] as const];
@@ -800,4 +814,164 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts
expect(secondNames).toContain('skill:only-second');
expect(secondNames).not.toContain('skill:only-first');
});
+
+ it('loads repeated explicit project skills under no-approve and no-skills', async () => {
+ const fixture = await createFixture('pi-rpc-explicit-skills-only-');
+ const explicitSkills = [
+ path.join(fixture.workingDir, '.pi', 'skills', 'project-pi-skill'),
+ path.join(fixture.repoRoot, '.agents', 'skills', 'ancestor-agents-skill'),
+ ];
+ const result = await runGetCommands({
+ binaryPath: PI_BINARY,
+ cwd: fixture.workingDir,
+ configHome: fixture.configHome,
+ sessionDir: fixture.sessionDir,
+ approve: false,
+ extraArgs: [
+ '--no-skills',
+ '--no-extensions',
+ ...explicitSkills.flatMap((skillPath) => ['--skill', skillPath]),
+ ],
+ });
+
+ expect(normalizeSkills(result.commands, fixture).map((skill) => skill.name)).toEqual([
+ 'skill:ancestor-agents-skill',
+ 'skill:project-pi-skill',
+ ]);
+ });
+
+ it('keeps global discovery while explicit project skills bypass only the project trust gate', async () => {
+ const fixture = await createFixture('pi-rpc-explicit-skills-additive-');
+ const explicitSkill = path.join(
+ fixture.workingDir,
+ '.pi',
+ 'skills',
+ 'project-pi-skill',
+ );
+ const result = await runGetCommands({
+ binaryPath: PI_BINARY,
+ cwd: fixture.workingDir,
+ configHome: fixture.configHome,
+ sessionDir: fixture.sessionDir,
+ approve: false,
+ extraArgs: ['--no-extensions', '--skill', explicitSkill],
+ });
+
+ expect(normalizeSkills(result.commands, fixture).map((skill) => skill.name)).toEqual([
+ 'skill:global-skill',
+ 'skill:project-pi-skill',
+ ]);
+ expect(result.commands).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ name: 'skill:project-pi-skill',
+ source: 'skill',
+ sourceInfo: expect.objectContaining({
+ path: path.join(explicitSkill, 'SKILL.md'),
+ source: 'local',
+ scope: 'temporary',
+ }),
+ }),
+ ]));
+ });
+
+ it('reports one deterministic runtime command when explicit approved paths share a skill name', async () => {
+ const fixture = await createFixture('pi-rpc-explicit-duplicate-name-');
+ const first = path.join(fixture.workingDir, '.pi', 'skills', 'duplicate-first');
+ const second = path.join(fixture.repoRoot, '.agents', 'skills', 'duplicate-second');
+ writeSkill(first, 'duplicate-name');
+ writeSkill(second, 'duplicate-name');
+
+ const result = await runGetCommands({
+ binaryPath: PI_BINARY,
+ cwd: fixture.workingDir,
+ configHome: fixture.configHome,
+ sessionDir: fixture.sessionDir,
+ approve: false,
+ extraArgs: [
+ '--no-extensions',
+ '--skill', first,
+ '--skill', second,
+ ],
+ });
+
+ const duplicates = result.commands.filter((command) => command.name === 'skill:duplicate-name');
+ expect(duplicates).toHaveLength(1);
+ expect(duplicates[0]).toMatchObject({
+ source: 'skill',
+ sourceInfo: { baseDir: first, source: 'local', scope: 'temporary' },
+ });
+ });
+
+ it('executes only explicit host extensions and never installs or executes project packages/extensions', async () => {
+ const fixture = await createFixture('pi-rpc-resource-hard-gates-');
+ const trustedExtensionMarker = path.join(fixture.root, 'trusted-extension-loaded');
+ const projectExtensionMarker = path.join(fixture.root, 'project-extension-loaded');
+ const packageExtensionMarker = path.join(fixture.root, 'package-extension-loaded');
+ const npmMarker = path.join(fixture.root, 'npm-invoked');
+ const gitTrace = path.join(fixture.root, 'git-trace.log');
+ const trustedExtension = path.join(fixture.configHome, 'trusted-extension.ts');
+ const projectExtension = path.join(fixture.workingDir, '.pi', 'extensions', 'project.ts');
+ const localPackage = path.join(fixture.root, 'local-package');
+ const packageExtension = path.join(localPackage, 'extensions', 'package.ts');
+ const npmProbe = path.join(fixture.root, 'npm-probe.mjs');
+
+ mkdirSync(path.dirname(projectExtension), { recursive: true });
+ mkdirSync(path.dirname(packageExtension), { recursive: true });
+ const markerExtension = (marker: string) => [
+ "import { writeFileSync } from 'node:fs';",
+ `writeFileSync(${JSON.stringify(marker)}, 'loaded');`,
+ 'export default function () {}',
+ ].join('\n');
+ writeFileSync(trustedExtension, markerExtension(trustedExtensionMarker));
+ writeFileSync(projectExtension, markerExtension(projectExtensionMarker));
+ writeFileSync(packageExtension, markerExtension(packageExtensionMarker));
+ writeFileSync(path.join(localPackage, 'package.json'), JSON.stringify({
+ name: 'fixture-local-package',
+ version: '1.0.0',
+ pi: { extensions: ['./extensions/package.ts'] },
+ }));
+ writeFileSync(
+ npmProbe,
+ `import { writeFileSync } from 'node:fs'; writeFileSync(${JSON.stringify(npmMarker)}, 'called'); process.exit(17);\n`,
+ );
+ writeFileSync(path.join(fixture.workingDir, '.pi', 'settings.json'), JSON.stringify({
+ npmCommand: [process.execPath, npmProbe],
+ packages: [
+ 'npm:fixture-must-not-install',
+ 'git:http://127.0.0.1:9/fixture-must-not-clone',
+ localPackage,
+ ],
+ extensions: [projectExtension],
+ }));
+
+ const result = await runGetCommands({
+ binaryPath: PI_BINARY,
+ cwd: fixture.workingDir,
+ configHome: fixture.configHome,
+ sessionDir: fixture.sessionDir,
+ approve: false,
+ offline: false,
+ extraEnv: {
+ GIT_TRACE: gitTrace,
+ GIT_TERMINAL_PROMPT: '0',
+ },
+ extraArgs: [
+ '--no-extensions',
+ '--extension', trustedExtension,
+ '--skill', path.join(fixture.workingDir, '.pi', 'skills', 'project-pi-skill'),
+ ],
+ });
+
+ expect(normalizeSkills(result.commands, fixture).map((skill) => skill.name)).toEqual([
+ 'skill:global-skill',
+ 'skill:project-pi-skill',
+ ]);
+ expect(existsSync(trustedExtensionMarker)).toBe(true);
+ expect(existsSync(projectExtensionMarker)).toBe(false);
+ expect(existsSync(packageExtensionMarker)).toBe(false);
+ expect(existsSync(npmMarker)).toBe(false);
+ expect(existsSync(path.join(fixture.workingDir, '.pi', 'npm'))).toBe(false);
+ expect(existsSync(path.join(fixture.workingDir, '.pi', 'git'))).toBe(false);
+ expect(existsSync(gitTrace) ? readFileSync(gitTrace, 'utf8') : '').not.toMatch(/\bclone\b/i);
+ });
});
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-runtime-capabilities.lifecycle.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-runtime-capabilities.lifecycle.test.ts
index 9c5723d8b0..f2f4644709 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-runtime-capabilities.lifecycle.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-runtime-capabilities.lifecycle.test.ts
@@ -7,6 +7,7 @@ const captured = vi.hoisted(() => ({
instances: [] as Array<{
sessionId: string;
sdkSessionId: string;
+ args: string[];
requests: Array<Record<string, unknown>>;
closed: boolean;
onExit?: (info: { code: number | null; signal: string | null }) => void;
@@ -23,6 +24,7 @@ vi.mock('../rpc-client.js', () => ({
private readonly state: (typeof captured.instances)[number];
isClosed = false;
constructor(opts: {
+ args: string[];
env: Record<string, string | undefined>;
onEvent: (event: unknown) => void;
onExit?: (info: { code: number | null; signal: string | null }) => void;
@@ -30,6 +32,7 @@ vi.mock('../rpc-client.js', () => ({
this.state = {
sessionId: opts.env.CINDY_PI_SESSION_ID ?? '',
sdkSessionId: `/mock/${opts.env.CINDY_PI_SESSION_ID || 'fork'}.jsonl`,
+ args: [...opts.args],
requests: [],
closed: false,
onExit: opts.onExit,
@@ -261,6 +264,9 @@ describe('Pi runtime capability lifecycle', () => {
sourceSdkSessionId: '/mock/source.jsonl', upToMessageId: undefined, workingDir: cwd,
});
expect(fork.runtimeCapabilities).toBeUndefined();
+ expect(captured.instances.at(-1)?.args).toEqual(expect.arrayContaining([
+ '--no-approve', '--no-extensions',
+ ]));
expect(captured.instances.at(-1)?.requests.filter((request) => request.type === 'get_commands')).toHaveLength(0);
const forkedHandle = await new PiAgent(deps()).startSession({
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index d766035ebd..87241dff88 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -12,7 +12,7 @@
* resume 路径、启动 RPC 也不会即时拒),控制流本身才是被测对象。
*/
-import { mkdtempSync, rmSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -67,6 +67,7 @@ vi.mock('../rpc-client.js', () => ({
import { PiAgent } from '../index.js';
import type { AgentDeps } from '../../base-agent.js';
import type { Logger } from '../../../interfaces/logger.js';
+import type { PiProjectTrustInputSnapshot } from '../../../types/pi-project-trust.js';
const noopLogger: Logger = {
trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},
@@ -92,7 +93,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
proxyDisposed = 0;
preparedMcpContext = undefined;
agentHome = mkdtempSync(path.join(tmpdir(), 'pi-cleanup-home-'));
- cwd = mkdtempSync(path.join(tmpdir(), 'pi-cleanup-cwd-'));
+ cwd = realpathSync(mkdtempSync(path.join(tmpdir(), 'pi-cleanup-cwd-')));
});
afterEach(() => {
@@ -101,7 +102,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
rmSync(cwd, { recursive: true, force: true });
});
- function buildDeps(): AgentDeps {
+ function buildDeps(overrides: Partial<AgentDeps> = {}): AgentDeps {
return {
auth: {
getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
@@ -141,9 +142,49 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
disposeSessionCtx: () => { disposed++; },
};
},
+ ...overrides,
};
}
+ function approvedInput(
+ workingDir: string,
+ revision: string,
+ skills: readonly string[],
+ ): PiProjectTrustInputSnapshot {
+ return {
+ identity: {
+ workingDir,
+ canonicalWorkingDir: workingDir,
+ canonicalRepoRoot: workingDir,
+ repoRootStatus: 'resolved',
+ platform: 'posix',
+ canonicalPathEncoding: 'utf8-lossless',
+ },
+ approval: {
+ status: 'approved',
+ scope: 'working-dir',
+ scopeKey: `${workingDir}\0${workingDir}`,
+ revision,
+ },
+ discovered: {
+ skills,
+ canonicalSkillEvidence: skills.map((skillPath) => ({
+ discoveredPath: skillPath,
+ canonicalPath: skillPath,
+ })),
+ settings: [],
+ packages: [],
+ extensions: [],
+ },
+ };
+ }
+
+ function repeatedArgValues(args: readonly string[], flag: string): string[] {
+ return args.flatMap((value, index) => value === flag && args[index + 1]
+ ? [args[index + 1]!]
+ : []);
+ }
+
const opts = () => ({
sessionId: 's1',
sessionInstanceId: 'pi-instance-1',
@@ -189,6 +230,59 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(proxyDisposed).toBe(1);
});
+ it('always disables project trust and implicit extensions while explicitly restoring only Cindy extensions', async () => {
+ const handle = await new PiAgent(buildDeps()).startSession(opts());
+ const args = knobs.spawnedArgs[0]!;
+ const configHome = knobs.spawnedEnvs[0]!.PI_CODING_AGENT_DIR!;
+
+ expect(args).toEqual(expect.arrayContaining(['--no-approve', '--no-extensions']));
+ expect(args).not.toContain('--approve');
+ expect(args).not.toContain('--no-skills');
+ expect(args).not.toContain('--skill');
+ expect(repeatedArgValues(args, '--extension')).toEqual([
+ path.join(configHome, 'extensions', 'cindy-bridge.ts'),
+ path.join(configHome, 'extensions', 'cindy-subagent.ts'),
+ ]);
+ await vi.waitFor(() => {
+ expect(handle.getRuntimeCapabilities?.()?.projectResources).toEqual({
+ status: 'unavailable',
+ reason: 'approval-resolver-unavailable',
+ approvalRevision: null,
+ requestedSkillCount: 0,
+ });
+ });
+ await handle.close();
+ });
+
+ it('freezes approval per new session and fails closed after revocation', async () => {
+ const skillPath = path.join(cwd, '.pi', 'skills', 'approved-skill');
+ mkdirSync(skillPath, { recursive: true });
+ writeFileSync(path.join(skillPath, 'SKILL.md'), '# approved\n');
+ const deps = buildDeps({
+ resolvePiProjectTrustInput: async ({ sessionId, workingDir }) => sessionId === 'approved'
+ ? approvedInput(workingDir, 'rev-approved', [skillPath])
+ : {
+ ...approvedInput(workingDir, 'rev-unused', [skillPath]),
+ approval: { status: 'revoked', revision: 'rev-revoked', reason: 'user-revoked' },
+ },
+ });
+ const agent = new PiAgent(deps);
+ const approvedHandle = await agent.startSession({ sessionId: 'approved', workingDir: cwd, model: 'm' });
+ const revokedHandle = await agent.startSession({ sessionId: 'revoked', workingDir: cwd, model: 'm' });
+
+ expect(repeatedArgValues(knobs.spawnedArgs[0]!, '--skill')).toEqual([skillPath]);
+ expect(repeatedArgValues(knobs.spawnedArgs[1]!, '--skill')).toEqual([]);
+ await vi.waitFor(() => {
+ expect(approvedHandle.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
+ status: 'approved', approvalRevision: 'rev-approved', requestedSkillCount: 1,
+ });
+ expect(revokedHandle.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
+ status: 'revoked', reason: 'user-revoked', approvalRevision: 'rev-revoked', requestedSkillCount: 0,
+ });
+ });
+ await Promise.all([approvedHandle.close(), revokedHandle.close()]);
+ });
+
it('injects remote MCP secrets only through env and marks them for bash-child stripping', async () => {
const agent = new PiAgent(buildDeps());
const handle = await agent.startSession(opts());
@@ -250,12 +344,31 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
// (PI_CODING_AGENT_DIR = agentHome/run-tmp/<hex>)承载 models.json,close/退出时清理。
it('isolates each session config home under run-tmp and keeps concurrent sessions independent', async () => {
const { existsSync } = await import('node:fs');
- const agent = new PiAgent(buildDeps());
- const h1 = await agent.startSession({ sessionId: 's1', workingDir: cwd, model: 'm' });
- const h2 = await agent.startSession({ sessionId: 's2', workingDir: cwd, model: 'm' });
+ const skillOne = path.join(cwd, '.pi', 'skills', 'one');
+ const skillTwo = path.join(cwd, '.agents', 'skills', 'two');
+ for (const skillPath of [skillOne, skillTwo]) {
+ mkdirSync(skillPath, { recursive: true });
+ writeFileSync(path.join(skillPath, 'SKILL.md'), '# isolated\n');
+ }
+ const agent = new PiAgent(buildDeps({
+ resolvePiProjectTrustInput: async ({ sessionId, workingDir }) => approvedInput(
+ workingDir,
+ `rev-${sessionId}`,
+ [sessionId === 's1' ? skillOne : skillTwo],
+ ),
+ }));
+ const [h1, h2] = await Promise.all([
+ agent.startSession({ sessionId: 's1', workingDir: cwd, model: 'm' }),
+ agent.startSession({ sessionId: 's2', workingDir: cwd, model: 'm' }),
+ ]);
- const home1 = knobs.spawnedEnvs[0].PI_CODING_AGENT_DIR as string;
- const home2 = knobs.spawnedEnvs[1].PI_CODING_AGENT_DIR as string;
+ const indexForSession = (sessionId: string) => knobs.spawnedEnvs.findIndex(
+ (env) => env.CINDY_PI_SESSION_ID === sessionId,
+ );
+ const s1Index = indexForSession('s1');
+ const s2Index = indexForSession('s2');
+ const home1 = knobs.spawnedEnvs[s1Index].PI_CODING_AGENT_DIR as string;
+ const home2 = knobs.spawnedEnvs[s2Index].PI_CODING_AGENT_DIR as string;
const runTmp = path.join(agentHome, 'run-tmp');
// 两个会话各自独立的 configHome(都在 run-tmp 下,hex 不同),各有自己的 models.json。
expect(home1).not.toBe(home2);
@@ -263,6 +376,16 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(home2.startsWith(runTmp)).toBe(true);
expect(existsSync(path.join(home1, 'models.json'))).toBe(true);
expect(existsSync(path.join(home2, 'models.json'))).toBe(true);
+ expect(repeatedArgValues(knobs.spawnedArgs[s1Index]!, '--skill')).toEqual([skillOne]);
+ expect(repeatedArgValues(knobs.spawnedArgs[s2Index]!, '--skill')).toEqual([skillTwo]);
+ await vi.waitFor(() => {
+ expect(h1.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
+ approvalRevision: 'rev-s1', requestedSkillCount: 1,
+ });
+ expect(h2.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
+ approvalRevision: 'rev-s2', requestedSkillCount: 1,
+ });
+ });
// close 一个会话清理它的 configHome,另一个不受影响(cleanup 是 fire-and-forget,轮询等)。
await h1.close();
diff --git a/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts b/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
new file mode 100644
index 0000000000..012debe1f0
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
@@ -0,0 +1,276 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ assembleApprovedPiProjectResources,
+ reconcilePiProjectResourceRuntime,
+ unavailablePiProjectResourceAssembly,
+} from '../project-resource-assembly.js';
+import type {
+ PiProjectApprovalSnapshot,
+ PiProjectTrustInputSnapshot,
+} from '../../../types/pi-project-trust.js';
+
+function inputFor(
+ workingDir: string,
+ approval: PiProjectApprovalSnapshot | null,
+ skills = [`${workingDir}/.pi/skills/demo`],
+): PiProjectTrustInputSnapshot {
+ const repoRoot = workingDir.split('/').slice(0, 3).join('/');
+ return {
+ identity: {
+ workingDir,
+ canonicalWorkingDir: workingDir,
+ canonicalRepoRoot: repoRoot,
+ repoRootStatus: 'resolved',
+ platform: 'posix',
+ canonicalPathEncoding: 'utf8-lossless',
+ },
+ approval,
+ discovered: {
+ skills,
+ canonicalSkillEvidence: skills.map((skillPath) => ({
+ discoveredPath: skillPath,
+ canonicalPath: skillPath,
+ })),
+ settings: [`${workingDir}/.pi/settings.json`],
+ packages: [`${workingDir}/.pi/settings.json#packages`],
+ extensions: [`${workingDir}/.pi/extensions/project.ts`],
+ },
+ };
+}
+
+const approved = (workingDir: string, revision: string): PiProjectApprovalSnapshot => ({
+ status: 'approved',
+ scope: 'working-dir',
+ scopeKey: `${workingDir.split('/').slice(0, 3).join('/')}\0${workingDir}`,
+ revision,
+});
+
+const available = {
+ stat: async () => ({ isDirectory: () => true, isFile: () => false }),
+ realpath: async (skillPath: string) => skillPath,
+};
+
+describe('Pi approved project resource assembly', () => {
+ it('freezes only explicitly eligible project skill paths', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const result = await assembleApprovedPiProjectResources(input, available);
+
+ expect(result.skillPaths).toEqual(input.discovered.skills);
+ expect(result.diagnostic).toEqual({
+ status: 'approved',
+ reason: 'approval-matched',
+ approvalRevision: 'rev-a',
+ requestedSkillCount: 1,
+ });
+ expect(result.decision?.launch).toEqual({
+ approve: false,
+ writeTrustJson: false,
+ inheritUserPiHome: false,
+ allowPackages: false,
+ allowExtensions: false,
+ });
+ expect(result.decision?.eligibleSettingsPaths).toEqual([]);
+ expect(result.decision?.settingsProjection).toBeNull();
+ expect(Object.isFrozen(result.skillPaths)).toBe(true);
+ expect(Object.isFrozen(result.diagnostic)).toBe(true);
+ expect(Object.isFrozen(result)).toBe(true);
+ });
+
+ it.each([
+ ['missing', null, 'approval-missing'],
+ ['unapproved', { status: 'unapproved', reason: 'user-denied' }, 'user-denied'],
+ ['revoked', { status: 'revoked', revision: 'revoked-2', reason: 'user-revoked' }, 'user-revoked'],
+ ['stale', { status: 'stale', revision: 'stale-2', reason: 'repo-moved' }, 'repo-moved'],
+ ['unavailable', { status: 'unavailable', reason: 'authority-offline' }, 'authority-offline'],
+ ] as const)('keeps %s approval discovered and fail-closed', async (_label, approval, reason) => {
+ const workingDir = '/repo-a/packages/app';
+ const result = await assembleApprovedPiProjectResources(
+ inputFor(workingDir, approval),
+ available,
+ );
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe(reason);
+ expect(result.decision?.resources.skills).toBe('discovered');
+ });
+
+ it('diagnoses a missing authority without manufacturing trust input', () => {
+ expect(unavailablePiProjectResourceAssembly('approval-resolver-unavailable')).toEqual({
+ decision: null,
+ skillPaths: [],
+ diagnostic: {
+ status: 'unavailable',
+ reason: 'approval-resolver-unavailable',
+ approvalRevision: null,
+ requestedSkillCount: 0,
+ },
+ });
+ });
+
+ it('invalidates the entire approved set when one path disappeared before launch', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const first = `${workingDir}/.pi/skills/first`;
+ const missing = `${workingDir}/.agents/skills/missing`;
+ const stat = vi.fn(async (skillPath: string) => {
+ if (skillPath === missing) throw new Error('ENOENT');
+ return { isDirectory: () => true, isFile: () => false };
+ });
+ const result = await assembleApprovedPiProjectResources(
+ inputFor(workingDir, approved(workingDir, 'rev-a'), [first, missing]),
+ { stat, realpath: available.realpath },
+ );
+
+ expect(stat).toHaveBeenCalledTimes(2);
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-skill-path-unavailable');
+ expect(result.decision?.resources.skills).toBe('eligible');
+ });
+
+ it('diagnoses canonical evidence changes without partially loading the remaining skill', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ input.discovered.canonicalSkillEvidence = [{
+ discoveredPath: input.discovered.skills[0]!,
+ canonicalPath: '/outside/retargeted-skill',
+ }];
+ const result = await assembleApprovedPiProjectResources(input, available);
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-skills-ineligible');
+ expect(result.decision?.resources.skills).toBe('discovered');
+ });
+
+ it('keeps concurrent workingDir approval snapshots isolated', async () => {
+ const firstDir = '/repo-a/packages/app';
+ const secondDir = '/repo-b/packages/app';
+ const [first, second] = await Promise.all([
+ assembleApprovedPiProjectResources(
+ inputFor(firstDir, approved(firstDir, 'rev-a')),
+ available,
+ ),
+ assembleApprovedPiProjectResources(
+ inputFor(secondDir, { status: 'revoked', revision: 'rev-b', reason: 'user-revoked' }),
+ available,
+ ),
+ ]);
+
+ expect(first.skillPaths).toEqual([`${firstDir}/.pi/skills/demo`]);
+ expect(first.diagnostic.approvalRevision).toBe('rev-a');
+ expect(second.skillPaths).toEqual([]);
+ expect(second.diagnostic).toMatchObject({
+ status: 'revoked',
+ reason: 'user-revoked',
+ approvalRevision: 'rev-b',
+ });
+ });
+
+ it('invalidates the whole set when a canonical skill path is retargeted after approval', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const result = await assembleApprovedPiProjectResources(input, {
+ stat: available.stat,
+ realpath: async (candidate) => candidate === input.discovered.skills[0]
+ ? '/outside/retargeted-skill'
+ : candidate,
+ });
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-skill-path-changed');
+ });
+
+ it('invalidates approved skills when the lexical workingDir is retargeted', async () => {
+ const workingDir = '/repo-a/packages/app-link';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const result = await assembleApprovedPiProjectResources(input, {
+ stat: available.stat,
+ realpath: async (candidate) => candidate === input.identity.workingDir
+ ? '/outside/retargeted-working-dir'
+ : candidate,
+ });
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-project-path-changed');
+ });
+
+ it('reports loaded only when this get_commands catalog confirms every explicit path', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const assembly = await assembleApprovedPiProjectResources(
+ inputFor(workingDir, approved(workingDir, 'rev-a')),
+ available,
+ );
+ const skillPath = assembly.skillPaths[0]!;
+ const baseManifest = {
+ capturedAt: '2026-08-10T00:00:00.000Z',
+ generation: 1,
+ status: 'loaded' as const,
+ source: 'pi:get_commands' as const,
+ };
+
+ expect(reconcilePiProjectResourceRuntime(assembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: {
+ scope: 'temporary',
+ source: 'local',
+ baseDir: skillPath,
+ path: `${skillPath}/SKILL.md`,
+ },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-confirmed',
+ requestedSkillCount: 1,
+ loadedSkillCount: 1,
+ });
+
+ expect(reconcilePiProjectResourceRuntime(assembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: { scope: 'user', source: 'auto', baseDir: skillPath },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-missing',
+ requestedSkillCount: 1,
+ loadedSkillCount: 0,
+ });
+
+ expect(reconcilePiProjectResourceRuntime(assembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: {
+ scope: 'temporary',
+ source: 'local',
+ baseDir: skillPath,
+ path: '/other/SKILL.md',
+ },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-missing',
+ loadedSkillCount: 0,
+ });
+
+ expect(reconcilePiProjectResourceRuntime(assembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: {
+ scope: 'temporary',
+ source: 'local',
+ baseDir: skillPath,
+ path: `${skillPath}/skill.md`,
+ },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-missing',
+ loadedSkillCount: 0,
+ });
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/__tests__/project-trust.test.ts b/packages/maker-core/src/agents/pi/__tests__/project-trust.test.ts
index 8b6714a64d..8759c885fd 100644
--- a/packages/maker-core/src/agents/pi/__tests__/project-trust.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/project-trust.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { evaluatePiProjectTrust, piProjectKey } from '../project-trust.js';
+import {
+ evaluatePiProjectTrust,
+ piCanonicalPathsEqual,
+ piProjectKey,
+} from '../project-trust.js';
import type {
PiProjectApprovalSnapshot,
PiProjectDiscoveredResources,
@@ -50,6 +54,15 @@ function expectSettingsDiscovered(result: ReturnType<typeof evaluatePiProjectTru
}
describe('Pi project trust contract', () => {
+ it('compares launch-time realpaths with the approval platform identity', () => {
+ expect(piCanonicalPathsEqual(identity, '/repo/Skill', '/repo/Skill')).toBe(true);
+ expect(piCanonicalPathsEqual(identity, '/repo/Skill', '/repo/skill')).toBe(false);
+ expect(piCanonicalPathsEqual({
+ platform: 'win32',
+ windowsCaseComparison: 'ordinal-insensitive',
+ }, 'C:\\Repo\\Skill', 'c:/repo/skill')).toBe(true);
+ });
+
it('uses canonical repo root + workingDir and isolates sibling workingDirs', () => {
expect(piProjectKey(identity)).toBe('/repo\0/repo/packages/app');
expect(evaluatePiProjectTrust({ identity, approval: approval(), discovered }).status).toBe('approved');
diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
index dc0af6bd3d..655c16b89e 100644
--- a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
@@ -13,8 +13,9 @@
* 否则 `${...}` 会被外层 String.raw 插值 —— 一律用字符串拼接。
*
* 安全形态(重要,别当冗余删掉):
- * - 子进程**继承 `PI_CODING_AGENT_DIR`**,因此同样加载 cindy-bridge → 权限门(`tool_call`
- * 拦截 + 凭证路径硬拦)对子代理照样生效。不传 `--no-extensions` 正是为了保住这条。
+ * - 子进程**继承 `PI_CODING_AGENT_DIR`**,但显式 `--no-extensions` 关闭隐式发现,再只用
+ * `--extension <configHome>/extensions/cindy-bridge.ts` 回装权限门。这样 project extension
+ * 永远不会执行,bridge 的 tool_call 拦截 + 凭证路径硬拦仍对子代理生效。
* - 第一期只给**只读**工具白名单(read/grep/find/ls)。这不只是保守:ask 档下非只读工具
* 要走 `ctx.ui.confirm`,而 headless 子进程没有 UI 承接、bridge 的 catch 分支按 deny
* 收口(fail-closed)。只读工具在门里直接放行,因此只读子代理开箱可用;写权限子代理需
@@ -113,12 +114,14 @@ const CINDY_SUBAGENT_EXTENSION_BODY = String.raw`/**
*/
import { spawn } from 'node:child_process';
import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
const TOOL_NAME = 'subagent';
const MARKER = '__cindySubagent';
const BINARY_ENV = 'CINDY_PI_SUBAGENT_BINARY';
const DEPTH_ENV = 'CINDY_PI_SUBAGENT_DEPTH';
const RUNTIME_FILE_ENV = 'CINDY_PI_SUBAGENT_RUNTIME_FILE';
+const CONFIG_HOME_ENV = 'PI_CODING_AGENT_DIR';
// cindy-bridge 用它决定要不要连 MCP server;子代理不需要,spawn 时剥掉(见 runTask)。
const MCP_BRIDGE_ENV = 'CINDY_PI_MCP_BRIDGE';
// PARENT_PID_ENV 与 PARENT_WATCHDOG_INTERVAL_MS 由末尾追加的看门狗段声明(那段要能独立
@@ -350,8 +353,16 @@ function runTask(binary, task, runtime, signal, onProgress) {
return;
}
const profile = PROFILES[task.agent];
+ const configHome = process.env[CONFIG_HOME_ENV];
+ if (typeof configHome !== 'string' || configHome.trim().length === 0) {
+ resolve({ text: 'subagent configuration is unavailable.', isError: true, toolUses: 0, tokens: 0, usage: emptyUsage() });
+ return;
+ }
const args = [
'--mode', 'json',
+ '--no-approve',
+ '--no-extensions',
+ '--extension', join(configHome, 'extensions', 'cindy-bridge.ts'),
'--no-session',
'--tools', profile.tools,
'--append-system-prompt', profile.prompt,
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index aed02fb1a1..e5a1d84663 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -82,6 +82,11 @@ import { resolveMcpToolTarget } from '../shared/mcp-tool-target.js';
import { resolveAgentCredentialMode } from '../credential-mode.js';
import { PiRpcProcess, type PiRpcEvent } from './rpc-client.js';
import { capturePiRuntimeCapabilityManifest } from './runtime-capabilities.js';
+import {
+ assembleApprovedPiProjectResources,
+ reconcilePiProjectResourceRuntime,
+ unavailablePiProjectResourceAssembly,
+} from './project-resource-assembly.js';
import {
createPiTranslateContext,
disposePiTranslateContext,
@@ -749,17 +754,13 @@ export class PiAgent extends BaseAgent {
// 与 models.json 同放隔离 configHome(Pi 从 PI_CODING_AGENT_DIR/extensions 扫描)。
const extensionsDir = path.join(configHome, 'extensions');
await fs.mkdir(extensionsDir, { recursive: true });
- await fs.writeFile(
- path.join(extensionsDir, CINDY_BRIDGE_EXTENSION_FILENAME),
- CINDY_BRIDGE_EXTENSION_SOURCE,
- );
+ const bridgeExtensionPath = path.join(extensionsDir, CINDY_BRIDGE_EXTENSION_FILENAME);
+ await fs.writeFile(bridgeExtensionPath, CINDY_BRIDGE_EXTENSION_SOURCE);
// cindy-subagent extension:与 bridge 并列的独立扩展(职责分离 —— bridge 管权限门与
// MCP 桥,这个只管子代理)。子进程继承 PI_CODING_AGENT_DIR,因此同样加载 bridge,
// 权限门对子代理照样生效;递归由扩展内的 depth env 自己截断。
- await fs.writeFile(
- path.join(extensionsDir, CINDY_SUBAGENT_EXTENSION_FILENAME),
- CINDY_SUBAGENT_EXTENSION_SOURCE,
- );
+ const subagentExtensionPath = path.join(extensionsDir, CINDY_SUBAGENT_EXTENSION_FILENAME);
+ await fs.writeFile(subagentExtensionPath, CINDY_SUBAGENT_EXTENSION_SOURCE);
// 权限档文件:extension 每次 tool_call 现读(热切换);读不到按 ask fail-closed。
const runtimeDir = path.join(agentHome, 'runtime');
@@ -1044,13 +1045,53 @@ export class PiAgent extends BaseAgent {
/* 缺失 → 不挂载 plan-mode */
}
+ // Project resources have exactly one authority: the host-owned PR3 trust
+ // snapshot. Freeze it once per new runtime, then assemble only its eligible
+ // skills. Missing/throwing authorities and paths fail closed; never infer
+ // approval from permission mode, MCP/plugin state, or caller vendor options.
+ let projectResourceAssembly = unavailablePiProjectResourceAssembly(
+ 'approval-resolver-unavailable',
+ );
+ if (this.deps.resolvePiProjectTrustInput) {
+ try {
+ const trustInput = await this.deps.resolvePiProjectTrustInput({
+ ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),
+ workingDir: opts.workingDir,
+ ...(opts.remoteHostId ? { remoteHostId: opts.remoteHostId } : {}),
+ });
+ projectResourceAssembly = await assembleApprovedPiProjectResources(trustInput);
+ } catch {
+ projectResourceAssembly = unavailablePiProjectResourceAssembly(
+ 'approval-resolver-failed',
+ );
+ this.deps.logger.warn('pi project approval resolver failed closed', {
+ sessionId: opts.sessionId ?? null,
+ });
+ }
+ }
+ this.deps.logger.debug('pi project resource assembly snapshot', {
+ sessionId: opts.sessionId ?? null,
+ status: projectResourceAssembly.diagnostic.status,
+ reason: projectResourceAssembly.diagnostic.reason,
+ approvalRevision: projectResourceAssembly.diagnostic.approvalRevision,
+ requestedSkillCount: projectResourceAssembly.diagnostic.requestedSkillCount,
+ });
+
const args = [
'--mode', 'rpc',
+ // Keep Pi's project trust and implicit extension discovery disabled even
+ // when project settings declare packages/extensions. Cindy-owned/pinned
+ // extensions and approved skills are the only explicit additions below.
+ '--no-approve',
+ '--no-extensions',
'--session-dir', sessionDir,
'--provider', initialProvider,
'--model', opts.model,
...(appendSystemPrompt.length > 0 ? ['--append-system-prompt', appendSystemPrompt] : []),
+ '--extension', bridgeExtensionPath,
+ '--extension', subagentExtensionPath,
...(planModeExtAvailable ? ['--extension', planModeExtPath] : []),
+ ...projectResourceAssembly.skillPaths.flatMap((skillPath) => ['--skill', skillPath]),
];
const queue: AsyncQueue<AgentEvent> = createAsyncQueue<AgentEvent>();
@@ -1455,7 +1496,7 @@ export class PiAgent extends BaseAgent {
stage: 'ready' | 'switch_session' | 'fork',
): Promise<void> => {
const generation = ++runtimeCapabilityGeneration;
- const manifest = await capturePiRuntimeCapabilityManifest(
+ const capturedManifest = await capturePiRuntimeCapabilityManifest(
proc,
{
...(opts.sessionId ? { sessionId: opts.sessionId } : {}),
@@ -1464,6 +1505,13 @@ export class PiAgent extends BaseAgent {
generation,
stage,
);
+ const manifest = {
+ ...capturedManifest,
+ projectResources: reconcilePiProjectResourceRuntime(
+ projectResourceAssembly,
+ capturedManifest,
+ ),
+ };
if (!closed && generation === runtimeCapabilityGeneration) publishRuntimeCapabilities(manifest);
};
let runtimeCaptureStage: 'ready' | 'switch_session' = 'ready';
@@ -2261,6 +2309,8 @@ export class PiAgent extends BaseAgent {
binaryPath: this.deps.binaryPath,
args: [
'--mode', 'rpc',
+ '--no-approve',
+ '--no-extensions',
'--session-dir', sessionDir,
'--session', opts.sourceSdkSessionId,
'--provider', PI_PROVIDER_ID,
diff --git a/packages/maker-core/src/agents/pi/project-resource-assembly.ts b/packages/maker-core/src/agents/pi/project-resource-assembly.ts
new file mode 100644
index 0000000000..9adda57df6
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/project-resource-assembly.ts
@@ -0,0 +1,174 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+import type {
+ PiProjectTrustDecision,
+ PiProjectTrustInputSnapshot,
+ PiProjectTrustStatus,
+} from '../../types/pi-project-trust.js';
+import { evaluatePiProjectTrust, piCanonicalPathsEqual } from './project-trust.js';
+import type {
+ PiProjectResourceRuntimeDiagnostic,
+ PiRuntimeCapabilityManifest,
+} from '../../types/pi-runtime-capabilities.js';
+import { piExplicitSkillRuntimePath } from './skill-runtime-provenance.js';
+
+export interface PiProjectResourceAssemblyDiagnostic {
+ readonly status: PiProjectTrustStatus;
+ readonly reason: string;
+ readonly approvalRevision: string | null;
+ readonly requestedSkillCount: number;
+}
+
+export interface PiProjectResourceAssemblySnapshot {
+ readonly decision: PiProjectTrustDecision | null;
+ readonly skillPaths: readonly string[];
+ readonly diagnostic: PiProjectResourceAssemblyDiagnostic;
+}
+
+const unavailableDiagnostic = (
+ reason: string,
+): PiProjectResourceAssemblyDiagnostic => Object.freeze({
+ status: 'unavailable',
+ reason,
+ approvalRevision: null,
+ requestedSkillCount: 0,
+});
+
+export function unavailablePiProjectResourceAssembly(
+ reason: string,
+): PiProjectResourceAssemblySnapshot {
+ return Object.freeze({
+ decision: null,
+ skillPaths: Object.freeze([]),
+ diagnostic: unavailableDiagnostic(reason),
+ });
+}
+
+async function validateSkillPathsImmediatelyBeforeLaunch(
+ skillPaths: readonly string[],
+ stat: (path: string) => Promise<{ isDirectory(): boolean; isFile(): boolean }>,
+ realpath: (path: string) => Promise<string>,
+ identity: PiProjectTrustInputSnapshot['identity'],
+): Promise<'available' | 'unavailable' | 'project-changed' | 'skill-changed'> {
+ try {
+ const canonicalWorkingDir = identity.canonicalWorkingDir;
+ const canonicalRepoRoot = identity.canonicalRepoRoot;
+ if (!canonicalWorkingDir || !canonicalRepoRoot) return 'unavailable';
+ const [resolvedWorkingDir, resolvedRepoRoot, entries] = await Promise.all([
+ realpath(identity.workingDir),
+ realpath(canonicalRepoRoot),
+ Promise.all(skillPaths.map(async (skillPath) => ({
+ skillPath,
+ stats: await stat(skillPath),
+ resolvedPath: await realpath(skillPath),
+ }))),
+ ]);
+ if (
+ !piCanonicalPathsEqual(identity, canonicalWorkingDir, resolvedWorkingDir)
+ || !piCanonicalPathsEqual(identity, canonicalRepoRoot, resolvedRepoRoot)
+ ) return 'project-changed';
+ if (entries.some(({ stats }) => !stats.isDirectory() && !stats.isFile())) return 'unavailable';
+ return entries.every(({ skillPath, resolvedPath }) =>
+ piCanonicalPathsEqual(identity, skillPath, resolvedPath))
+ ? 'available'
+ : 'skill-changed';
+ } catch {
+ return 'unavailable';
+ }
+}
+
+/**
+ * Convert one host-owned approval snapshot into a frozen, skills-only launch
+ * snapshot. A missing/changed path invalidates the whole approved set so a
+ * partial launch cannot silently diverge from the audited evidence.
+ */
+export async function assembleApprovedPiProjectResources(
+ input: PiProjectTrustInputSnapshot | null,
+ options: {
+ stat?: (path: string) => Promise<{ isDirectory(): boolean; isFile(): boolean }>;
+ realpath?: (path: string) => Promise<string>;
+ } = {},
+): Promise<PiProjectResourceAssemblySnapshot> {
+ if (!input) return unavailablePiProjectResourceAssembly('approval-snapshot-unavailable');
+
+ const decision = evaluatePiProjectTrust({
+ identity: input.identity,
+ approval: input.approval,
+ discovered: input.discovered,
+ capabilities: { explicitSkills: true },
+ });
+ const eligibleSkillPaths = [...decision.eligibleSkillPaths];
+ let reason = decision.reason;
+ let skillPaths: readonly string[] = eligibleSkillPaths;
+
+ if (
+ decision.status === 'approved' &&
+ input.discovered.skills.length > 0 &&
+ eligibleSkillPaths.length === 0
+ ) {
+ reason = 'approved-skills-ineligible';
+ } else if (eligibleSkillPaths.length > 0) {
+ const pathStatus = await validateSkillPathsImmediatelyBeforeLaunch(
+ eligibleSkillPaths,
+ options.stat ?? fs.stat,
+ options.realpath ?? fs.realpath,
+ input.identity,
+ );
+ if (pathStatus !== 'available') {
+ reason = pathStatus === 'project-changed'
+ ? 'approved-project-path-changed'
+ : pathStatus === 'skill-changed'
+ ? 'approved-skill-path-changed'
+ : 'approved-skill-path-unavailable';
+ skillPaths = [];
+ }
+ }
+
+ const frozenSkillPaths = Object.freeze([...skillPaths]);
+ return Object.freeze({
+ decision,
+ skillPaths: frozenSkillPaths,
+ diagnostic: Object.freeze({
+ status: decision.status,
+ reason,
+ approvalRevision: decision.approvalRevision,
+ requestedSkillCount: frozenSkillPaths.length,
+ }),
+ });
+}
+
+function comparableRuntimePath(value: string): string {
+ // Explicit --skill provenance normally echoes the canonical argv path. Keep
+ // comparison case-sensitive here: a conservative false-negative is safer
+ // than claiming loaded on a case-sensitive Windows directory.
+ return path.resolve(value);
+}
+
+/**
+ * Reconcile the approved launch snapshot with this runtime's exact command
+ * catalog. Approval alone never upgrades a skill to loaded; missing commands
+ * remain diagnosable even when get_commands itself succeeded.
+ */
+export function reconcilePiProjectResourceRuntime(
+ assembly: PiProjectResourceAssemblySnapshot,
+ manifest: PiRuntimeCapabilityManifest,
+): PiProjectResourceRuntimeDiagnostic {
+ if (manifest.status !== 'loaded' || assembly.skillPaths.length === 0) {
+ return assembly.diagnostic;
+ }
+
+ const expectedPaths = new Set(assembly.skillPaths.map(comparableRuntimePath));
+ const loadedPaths = new Set(manifest.commands.flatMap((command) => {
+ const skillPath = piExplicitSkillRuntimePath(command);
+ return skillPath ? [comparableRuntimePath(skillPath)] : [];
+ }));
+ const loadedSkillCount = [...expectedPaths].filter((skillPath) => loadedPaths.has(skillPath)).length;
+ return Object.freeze({
+ ...assembly.diagnostic,
+ reason: loadedSkillCount === expectedPaths.size
+ ? 'runtime-skills-confirmed'
+ : 'runtime-skills-missing',
+ loadedSkillCount,
+ });
+}
diff --git a/packages/maker-core/src/agents/pi/project-trust.ts b/packages/maker-core/src/agents/pi/project-trust.ts
index be1ea4e585..122e810dd7 100644
--- a/packages/maker-core/src/agents/pi/project-trust.ts
+++ b/packages/maker-core/src/agents/pi/project-trust.ts
@@ -59,6 +59,17 @@ function normalizePath(
return null;
}
+/** Compare two host canonical paths with the exact platform identity used by approval keys. */
+export function piCanonicalPathsEqual(
+ identity: Pick<PiProjectIdentityResolution, 'platform' | 'windowsCaseComparison'>,
+ first: string,
+ second: string,
+): boolean {
+ const left = normalizePath(first, identity.platform, identity.windowsCaseComparison);
+ const right = normalizePath(second, identity.platform, identity.windowsCaseComparison);
+ return left !== null && right !== null && left === right;
+}
+
function hasLosslessCanonicalEncoding(
identity: Pick<PiProjectIdentityResolution, 'platform' | 'canonicalPathEncoding' | 'windowsCaseComparison'>,
): boolean {
diff --git a/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts b/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts
new file mode 100644
index 0000000000..58884254d6
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts
@@ -0,0 +1,23 @@
+import path from 'node:path';
+
+import type { PiRuntimeCommand } from '../../types/pi-runtime-capabilities.js';
+
+/**
+ * Return the exact explicit --skill directory proven by pinned Pi provenance.
+ * Both fields must agree; accepting either independently lets malformed runtime
+ * data mark the wrong discovered project skill loaded.
+ */
+export function piExplicitSkillRuntimePath(command: PiRuntimeCommand): string | null {
+ const baseDir = command.sourceInfo.baseDir;
+ const skillFile = command.sourceInfo.path;
+ if (
+ command.source !== 'skill'
+ || command.sourceInfo.scope !== 'temporary'
+ || command.sourceInfo.source !== 'local'
+ || typeof baseDir !== 'string'
+ || typeof skillFile !== 'string'
+ || path.basename(skillFile) !== 'SKILL.md'
+ || path.resolve(path.dirname(skillFile)) !== path.resolve(baseDir)
+ ) return null;
+ return baseDir;
+}
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index 63ceed26f7..b9bbfeb38e 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -922,15 +922,30 @@ describe('Maker Pi runtime skill status', () => {
source: 'pi:get_commands',
commands: [
{
- name: `skill:${opts.sessionId}-skill`,
+ name: `skill:${opts.sessionId}-frontmatter-name`,
source: 'skill',
- sourceInfo: { source: 'auto', scope: 'project', baseDir: '/repo/.pi' },
+ sourceInfo: {
+ source: 'local',
+ scope: 'temporary',
+ baseDir: `/repo/.pi/skills/${opts.sessionId}-skill`,
+ path: `/repo/.pi/skills/${opts.sessionId}-skill/SKILL.md`,
+ },
},
{
name: 'skill:user-collision',
source: 'skill',
sourceInfo: { source: 'auto', scope: 'user', baseDir: '/home/.agents/skills' },
},
+ {
+ name: 'skill:malformed-collision',
+ source: 'skill',
+ sourceInfo: {
+ source: 'local',
+ scope: 'temporary',
+ baseDir: '/repo/.pi/skills/malformed-collision',
+ path: '/other/SKILL.md',
+ },
+ },
],
});
return handle;
@@ -949,6 +964,7 @@ describe('Maker Pi runtime skill status', () => {
projectSkill('one-skill', '/repo/.agents/skills/one-skill'),
projectSkill('two-skill', '/repo/.pi/skills/two-skill'),
projectSkill('user-collision', '/repo/.pi/skills/user-collision'),
+ projectSkill('malformed-collision', '/repo/.pi/skills/malformed-collision'),
],
}));
const maker = new Maker({
@@ -982,17 +998,19 @@ describe('Maker Pi runtime skill status', () => {
['one-skill', 'discovered'],
['two-skill', 'discovered'],
['user-collision', 'discovered'],
+ ['malformed-collision', 'discovered'],
]);
expect(one.skills[0]).toMatchObject({
name: 'one-skill',
runtimeStatus: 'loaded',
- runtimeCommandName: 'skill:one-skill',
+ runtimeCommandName: 'skill:one-frontmatter-name',
});
expect(two.skills.map((skill) => [skill.name, skill.runtimeStatus])).toEqual([
['one-skill', 'discovered'],
['one-skill', 'discovered'],
['two-skill', 'loaded'],
['user-collision', 'discovered'],
+ ['malformed-collision', 'discovered'],
]);
expect(preview.skills.every((skill) => skill.runtimeStatus === 'discovered')).toBe(true);
expect(wrongProject.skills.every((skill) => skill.runtimeStatus === 'discovered')).toBe(true);
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index 54a180d045..ca65ff4b21 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -34,6 +34,7 @@ import type {
ListCustomizationsResult,
} from './types/customizations.js';
import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilities.js';
+import { piExplicitSkillRuntimePath } from './agents/pi/skill-runtime-provenance.js';
import { Session, generateSessionId } from './session.js';
import type {
AgentSessionHandle,
@@ -164,30 +165,39 @@ function mergePiRuntimeSkillStatuses(
manifest: PiRuntimeCapabilityManifest | undefined,
): ListAgentSkillsResult {
if (manifest?.status !== 'loaded') return result;
- const loadedProjectSkills = new Map(
- manifest.commands.flatMap((command) => {
- const baseDir = command.sourceInfo.baseDir;
- if (
- command.source !== 'skill'
- || command.sourceInfo.scope !== 'project'
- || typeof baseDir !== 'string'
- || !command.name.startsWith('skill:')
- ) return [];
- return [[[
- command.name.slice('skill:'.length),
- canonicalPiRuntimePath(baseDir),
- ].join('\0'), command.name] as const];
- }),
- );
- if (loadedProjectSkills.size === 0) return result;
+ const loadedExplicitSkills = new Map<string, string>();
+ const loadedLegacyProjectSkills = new Map<string, string>();
+ for (const command of manifest.commands) {
+ const baseDir = command.sourceInfo.baseDir;
+ if (command.source !== 'skill' || !command.name.startsWith('skill:')) continue;
+ const skillName = command.name.slice('skill:'.length);
+ if (command.sourceInfo.scope === 'project' && typeof baseDir === 'string') {
+ loadedLegacyProjectSkills.set(
+ [skillName, canonicalPiRuntimePath(baseDir)].join('\0'),
+ command.name,
+ );
+ continue;
+ }
+ // Pinned Pi reports explicit --skill with a paired baseDir + SKILL.md path.
+ // The shared helper rejects partial/mismatched provenance before a
+ // user/global collision can mark a project scanner result loaded. Match
+ // explicit resources by path because frontmatter names need not equal
+ // their containing folder names.
+ const explicitPath = piExplicitSkillRuntimePath(command);
+ if (explicitPath) {
+ loadedExplicitSkills.set(canonicalPiRuntimePath(explicitPath), command.name);
+ }
+ }
+ if (loadedExplicitSkills.size === 0 && loadedLegacyProjectSkills.size === 0) return result;
return {
...result,
skills: result.skills.map((skill) => {
const runtimeCommandName = skill.scope === 'repo' && skill.path
- ? loadedProjectSkills.get([
- skill.name,
- canonicalPiRuntimePath(path.dirname(path.dirname(skill.path))),
- ].join('\0'))
+ ? loadedExplicitSkills.get(canonicalPiRuntimePath(skill.path))
+ ?? [skill.path, path.dirname(path.dirname(skill.path))]
+ .map(canonicalPiRuntimePath)
+ .map((skillPath) => loadedLegacyProjectSkills.get([skill.name, skillPath].join('\0')))
+ .find((commandName) => commandName !== undefined)
: undefined;
return runtimeCommandName
? { ...skill, runtimeStatus: 'loaded' as const, runtimeCommandName }
diff --git a/packages/maker-core/src/types/pi-project-trust.ts b/packages/maker-core/src/types/pi-project-trust.ts
index c996351b6b..cad8c273ba 100644
--- a/packages/maker-core/src/types/pi-project-trust.ts
+++ b/packages/maker-core/src/types/pi-project-trust.ts
@@ -117,6 +117,13 @@ export interface PiProjectSettingsProjection {
readonly revision?: string;
}
+/** Immutable startup input supplied by the host's project-approval authority. */
+export interface PiProjectTrustInputSnapshot {
+ readonly identity: PiProjectIdentityResolution;
+ readonly approval: PiProjectApprovalSnapshot | null;
+ readonly discovered: PiProjectDiscoveredResources;
+}
+
export interface PiProjectTrustDecision {
status: PiProjectTrustStatus;
/** `${canonicalRepoRoot}\0${canonicalWorkingDir}`; null when unavailable. */
diff --git a/packages/maker-core/src/types/pi-runtime-capabilities.ts b/packages/maker-core/src/types/pi-runtime-capabilities.ts
index 61f0c72740..cd4fe250c1 100644
--- a/packages/maker-core/src/types/pi-runtime-capabilities.ts
+++ b/packages/maker-core/src/types/pi-runtime-capabilities.ts
@@ -45,6 +45,16 @@ export interface PiRuntimeCommand {
sourceInfo: PiRuntimeCommandSourceInfo;
}
+/** Startup-only Cindy approval/assembly fact for this isolated Pi runtime. */
+export interface PiProjectResourceRuntimeDiagnostic {
+ status: import('./pi-project-trust.js').PiProjectTrustStatus;
+ reason: string;
+ approvalRevision: string | null;
+ requestedSkillCount: number;
+ /** Present only when this session's get_commands returned a valid catalog. */
+ loadedSkillCount?: number;
+}
+
/**
* Per-session runtime catalog snapshot. All fields are optional at call sites
* through the AgentSessionHandle contract, so old consumers remain compatible.
@@ -60,4 +70,6 @@ export interface PiRuntimeCapabilityManifest {
source: PiRuntimeCapabilitySource;
commands: readonly PiRuntimeCommand[];
error?: PiRuntimeCapabilityError;
+ /** Does not imply loaded; only `commands` from this session's get_commands can do that. */
+ projectResources?: PiProjectResourceRuntimeDiagnostic;
}