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): 原地加载项目 Skill、prompt 与 extensions (#4437)

Chris Zhang05d5e4209b5d
diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-package-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-package-store.test.ts
index 545a2d012f..b6199b4195 100644
--- a/apps/desktop/src/main/maker-host/__tests__/pi-package-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/pi-package-store.test.ts
@@ -20,6 +20,7 @@ import { evaluatePiRuntimeRequirements } from '../pi-package-compatibility.js';
import {
hasPiPackageCompatibilityWarning,
isRelativeLocalPiPackageSource,
+ listPiRuntimePaletteCommands,
mergePiPackageCommands,
shouldListPiPackageCommands,
} from '../../../shared/piPackages.js';
@@ -150,6 +151,18 @@ describe('Pi package slash command isolation', () => {
const builtin = [{ kind: 'agent-builtin' as const, name: 'compact', description: 'Compact' }];
const prompts = [{ name: 'package-review', description: 'Review with the installed Pi package' }];
+ it('includes authorized project prompt and extension commands in the palette', () => {
+ expect(listPiRuntimePaletteCommands([
+ { name: 'managed-run', description: 'Package command' },
+ { name: 'project-review', description: 'Project prompt' },
+ { name: 'skill:hidden', description: 'Skill stays on the skill list' },
+ { name: 'plan', description: 'Untrusted extension' },
+ ], ['managed-run', 'project-review', 'skill:hidden'])).toEqual([
+ { name: 'managed-run', description: 'Package command' },
+ { name: 'project-review', description: 'Project prompt' },
+ ]);
+ });
+
it('adds package prompts only to Pi', () => {
expect(mergePiPackageCommands('pi', builtin, prompts).map((command) => command.name))
.toEqual(['compact', 'package-review']);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 125d9288c6..10c528df93 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -558,6 +558,7 @@ import { ClaudeOutputLagTimingGuard, type ModelUsageCumulative } from '../usage/
import { type RegionalMoney } from '../../shared/regionalMoney.js';
import { currentLedgerCurrency } from '../usage/ledgerCurrency.js';
import {
+ listPiRuntimePaletteCommands,
mergePiPackageCommands,
shouldListPiPackageCommands,
type PiPackageMutationRequest,
@@ -5926,17 +5927,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
: manifest?.status === 'unknown'
? 'unknown'
: 'pending';
- const managedNames = new Set(manifest?.managedPackageCommandNames ?? []);
if (manifest?.status === 'loaded') {
- packageCommands = manifest.commands.flatMap((command) =>
- managedNames.has(command.name) && !command.name.startsWith('skill:')
- ? [
- {
- name: command.name,
- description: command.description ?? `Pi extension command: ${command.name}`,
- },
- ]
- : [],
+ packageCommands = listPiRuntimePaletteCommands(
+ manifest.commands,
+ manifest.authorizedSlashCommandNames ?? manifest.managedPackageCommandNames,
);
} else if (!manifest) {
// An empty local Pi task may have a persisted session row before its
diff --git a/apps/desktop/src/shared/piPackages.ts b/apps/desktop/src/shared/piPackages.ts
index 45f328974f..089c21c0e2 100644
--- a/apps/desktop/src/shared/piPackages.ts
+++ b/apps/desktop/src/shared/piPackages.ts
@@ -134,6 +134,21 @@ export type PiPackageCommandRuntimeStatus =
| 'failed'
| 'unknown';
+export function listPiRuntimePaletteCommands(
+ commands: ReadonlyArray<{ name: string; description?: string | null }>,
+ authorizedNames: readonly string[] | undefined,
+): Array<{ name: string; description: string }> {
+ const names = new Set(authorizedNames ?? []);
+ return commands.flatMap((command) =>
+ names.has(command.name) && !command.name.startsWith('skill:')
+ ? [{
+ name: command.name,
+ description: command.description ?? `Pi extension command: ${command.name}`,
+ }]
+ : [],
+ );
+}
+
/** Runtime-confirmed Pi package commands belong only to the Pi command palette. */
export function mergePiPackageCommands(
agentKind: 'claude-code' | 'codex' | 'pi',
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index e71f85e2f9..0b605b0734 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -173,9 +173,11 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见
2. **凭证路径判定三处同步**:`shared/auto-review.ts CREDENTIAL_PATH_PATTERNS`、
`cindy-bridge-source.ts touchesCredentialPath`、`auto-review-policy.ts` 只读分支全字段扫描
必须同口径。bridge 自包含不能 import,改一处记得改三处。
-3. **斜杠命令转义**:`escapeLeadingSlashCommand` 对 `/` 开头用户输入前置空格转字面(仅放行
- `/skill:`)—— pi RPC prompt 会执行扩展命令(`/plan` 被 plan-mode 吃掉且不留痕),不转义会让
- Cindy 状态镜像脱同步并暴露未来扩展命令攻击面。
+3. **斜杠命令转义**:`escapeLeadingSlashCommand` 对 `/` 开头用户输入前置空格转字面。仅放行
+ `/skill:`、本次 `get_commands` 证明 provenance 落在 Cindy-managed package 根内的命令,以及
+ 本次显式传入的项目 Skill/prompt/extension 路径所证明的命令。`/` 面板用同一套
+ `authorizedSlashCommandNames`,不单看 managed package。其余扩展命令(如 `/plan`)
+ 转义成字面,避免 Cindy 状态镜像脱同步,也堵住未装配来源的命令攻击面。
4. **auto 档 dispatcher fail-closed**:分类抛错 / 无 resolver 一律不放行。
5. **成本计量**:models.json 的 cost 来自 host 模型目录(`ModelDescriptor.cost`),缺省按 0;
派生链 `catalog-to-descriptors.ts` → `capabilities.availableModels` → `writeModelsJson`。
@@ -187,19 +189,18 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见
8. **项目资源显式装配**:root、只读 subagent 与离线 fork 启动 Pi 时都必须显式传
`--no-approve`;没有 Cindy-managed 本机用户包根时同时传 `--no-extensions`。本机普通 runtime
存在明确安装且未停用的用户包根时,为保留 Pi 原生 package discovery 可以只省略
- `--no-extensions`:包根只能来自 Main 生成的 runtime `settings.json`,`--no-approve` 仍是项目
- `.pi/extensions` / `.pi/settings.json` 的硬门,不得因此传 `--approve` 或读取项目设置。root
- 仅用重复 `--extension` 回装 Cindy 自有 bridge/subagent 与 pinned plan-mode,并仅用重复
- `--skill` 装配 host 从 PR3 approval snapshot 判定 eligible
- 的项目 skill 目录。eligible canonical 目录必须先完整物化到当前会话 `configHome` 的非自动
- 扫描目录,再把隔离快照路径交给 Pi;不得把仍可变化的项目原路径直接放进 argv。复制期间
- 任一越界 symlink、特殊文件或路径替换会使整组 skills fail closed。不得读取/复制项目
- `.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 记录诊断原因。
+ `--no-extensions`:包根只能来自 Main 生成的 runtime `settings.json`,`--no-approve` 仍禁止
+ 读取项目 `.pi/settings.json` 与自动安装项目 packages,不得因此传 `--approve`。
+ 本地非 Review、非 Bot、非 SSH 的 root 任务用重复 `--skill` / `--prompt-template` /
+ `--extension` 把仓库原路径交给 Pi:`.pi/skills` 与 cwd→git root 内 `.agents/skills`
+ 的目录型 Skill、`.pi/prompts/*.md`、`.pi/extensions/*.ts` 与 `*/index.ts`。越界 symlink
+ 不传入。root 仍回装 Cindy 自有 bridge/subagent 与 pinned plan-mode。Review、Bot、子代理、
+ 离线 `forkSdkSession` 克隆进程与远端会话不带这些项目资源。随后以 `resumeSessionId`
+ 恢复的本地根任务(含 fork 之后的恢复)与普通本地任务相同,加载项目资源。
+ 不得读取/复制项目 `.pi/settings.json`,不得传 `--approve`,
+ 不得依赖 `PI_OFFLINE=1` 代替该 settings 硬门。root 不传 `--no-skills`,以保留现有
+ user/global skill 行为;项目 skill 的 `loaded` 由当前会话 `get_commands` 对原路径 provenance
+ 证明。
9. **Pi bash bounded timeout**:Cindy 覆盖的模型可调 `bash` 在 execute 入口强制默认
`300s`、上限 `1800s`。缺省或非正数用默认;大于上限或非有限数字 fail-fast(参数错误,
不是 `Command timed out`);合法秒数原样交给 Pi 原生执行器。不另起 timer / AbortController。
@@ -278,9 +279,9 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见
- 自动化安全网: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/第三方执行。
+- PR4 项目资源桥(2026-07,已废止):当时只装配 Cindy 明确批准的 Skill,项目 packages/extensions
+ 不执行。现行口径见 §8:本地根任务用 `--skill` / `--prompt-template` / `--extension` 原地加载
+ 仓库原路径,不走批准快照;项目 `.pi/extensions` 会进入该会话。项目 packages 仍不自动安装。
### SSH 远端能力(2026-08 里程碑,轮 39 补记)
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 1791d8f843..71d0092fc7 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
@@ -280,10 +280,6 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
: []);
}
- function stagedSkillPath(configHome: string, index: number, sourcePath: string): string {
- return path.join(configHome, 'project-resources', 'skills', String(index), path.basename(sourcePath));
- }
-
const opts = () => ({
sessionId: 's1',
sessionInstanceId: 'pi-instance-1',
@@ -2201,6 +2197,74 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
await handle.close();
});
+ it('passes original project skill, prompt and extension paths without --approve', async () => {
+ const skillDir = path.join(cwd, '.pi', 'skills', 'demo');
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(path.join(skillDir, 'SKILL.md'), '# demo\n');
+ mkdirSync(path.join(cwd, '.pi', 'prompts'), { recursive: true });
+ writeFileSync(path.join(cwd, '.pi', 'prompts', 'review.md'), '# review\n');
+ mkdirSync(path.join(cwd, '.pi', 'extensions'), { recursive: true });
+ writeFileSync(path.join(cwd, '.pi', 'extensions', 'hook.ts'), 'export default () => {};\n');
+
+ const handle = await new PiAgent(buildDeps()).startSession(opts());
+ const args = knobs.spawnedArgs[0]!;
+ const configHome = knobs.spawnedEnvs[0]!.PI_CODING_AGENT_DIR!;
+ expect(args).toContain('--no-approve');
+ expect(args).not.toContain('--approve');
+ expect(repeatedArgValues(args, '--skill')).toEqual([realpathSync(skillDir)]);
+ expect(repeatedArgValues(args, '--prompt-template')).toEqual([
+ realpathSync(path.join(cwd, '.pi', 'prompts', 'review.md')),
+ ]);
+ expect(repeatedArgValues(args, '--extension')).toEqual([
+ path.posix.join(configHome, 'internal-extensions', 'cindy-bridge.ts'),
+ path.posix.join(configHome, 'internal-extensions', 'cindy-subagent.ts'),
+ realpathSync(path.join(cwd, '.pi', 'extensions', 'hook.ts')),
+ ]);
+ await handle.close();
+
+ knobs.spawnedArgs = [];
+ knobs.spawnedEnvs = [];
+ const reviewHandle = await new PiAgent(buildDeps()).startSession({
+ ...opts(),
+ sessionId: 'review-project-resources',
+ reviewMode: true,
+ });
+ const reviewArgs = knobs.spawnedArgs[0]!;
+ expect(repeatedArgValues(reviewArgs, '--skill')).toEqual([]);
+ expect(repeatedArgValues(reviewArgs, '--prompt-template')).toEqual([]);
+ expect(repeatedArgValues(reviewArgs, '--extension')).toEqual([
+ path.posix.join(
+ knobs.spawnedEnvs[0]!.PI_CODING_AGENT_DIR!,
+ 'internal-extensions',
+ 'cindy-bridge.ts',
+ ),
+ ]);
+ await reviewHandle.close();
+ });
+
+ it('still loads project resources when a local root session resumes a fork jsonl', async () => {
+ const skillDir = path.join(cwd, '.pi', 'skills', 'demo');
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(path.join(skillDir, 'SKILL.md'), '# demo\n');
+ mkdirSync(path.join(cwd, '.pi', 'extensions'), { recursive: true });
+ writeFileSync(path.join(cwd, '.pi', 'extensions', 'hook.ts'), 'export default () => {};\n');
+ const resumeFile = path.join(cwd, 'forked.jsonl');
+ writeFileSync(resumeFile, '{}');
+
+ const handle = await new PiAgent(buildDeps()).startSession({
+ ...opts(),
+ sessionId: 'resume-fork',
+ resumeSessionId: resumeFile,
+ });
+ const args = knobs.spawnedArgs[0]!;
+ expect(args).toContain('--no-approve');
+ expect(repeatedArgValues(args, '--skill')).toEqual([realpathSync(skillDir)]);
+ expect(repeatedArgValues(args, '--extension')).toContain(
+ realpathSync(path.join(cwd, '.pi', 'extensions', 'hook.ts')),
+ );
+ 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 });
@@ -2217,10 +2281,10 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
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([
- stagedSkillPath(knobs.spawnedEnvs[0]!.PI_CODING_AGENT_DIR!, 0, skillPath),
- ]);
- expect(repeatedArgValues(knobs.spawnedArgs[1]!, '--skill')).toEqual([]);
+ expect(repeatedArgValues(knobs.spawnedArgs[0]!, '--skill')).toEqual([realpathSync(skillPath)]);
+ expect(repeatedArgValues(knobs.spawnedArgs[1]!, '--skill')).toEqual([realpathSync(skillPath)]);
+ expect(existsSync(path.join(knobs.spawnedEnvs[0]!.PI_CODING_AGENT_DIR!, 'project-resources'))).toBe(false);
+ expect(existsSync(path.join(knobs.spawnedEnvs[1]!.PI_CODING_AGENT_DIR!, 'project-resources'))).toBe(false);
await vi.waitFor(() => {
expect(approvedHandle.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
status: 'approved', approvalRevision: 'rev-approved', requestedSkillCount: 1,
@@ -2447,12 +2511,10 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
writeFileSync(path.join(home3, 'AGENTS.md'), 'runtime edit');
expect(readFileSync(path.join(nativeHome, 'AGENTS.md'), 'utf8')).toBe('global rules v2');
await h3.close();
- expect(repeatedArgValues(knobs.spawnedArgs[s1Index]!, '--skill')).toEqual([
- stagedSkillPath(home1, 0, skillOne),
- ]);
- expect(repeatedArgValues(knobs.spawnedArgs[s2Index]!, '--skill')).toEqual([
- stagedSkillPath(home2, 0, skillTwo),
- ]);
+ const expectedProjectSkills = [realpathSync(skillOne), realpathSync(skillTwo)]
+ .sort((left, right) => left.localeCompare(right));
+ expect(repeatedArgValues(knobs.spawnedArgs[s1Index]!, '--skill')).toEqual(expectedProjectSkills);
+ expect(repeatedArgValues(knobs.spawnedArgs[s2Index]!, '--skill')).toEqual(expectedProjectSkills);
await vi.waitFor(() => {
expect(h1.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
approvalRevision: 'rev-s1', requestedSkillCount: 1,
@@ -2561,7 +2623,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
knobs.spawnedEnvs[reviewIndex]!.CINDY_PI_PERMISSION_FILE,
);
expect(repeatedArgValues(knobs.spawnedArgs[approvedIndex]!, '--skill')).toEqual([
- stagedSkillPath(approvedHome, 0, skillPath),
+ realpathSync(skillPath),
]);
expect(repeatedArgValues(knobs.spawnedArgs[reviewIndex]!, '--skill')).toEqual([]);
expect(repeatedArgValues(knobs.spawnedArgs[approvedIndex]!, '--extension')).toEqual([
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
index 5d34e643c5..8b50457b69 100644
--- 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
@@ -784,6 +784,23 @@ describe('Pi approved project resource assembly', () => {
path: `${skillPath}/skill.md`,
},
}],
+ })).toMatchObject({
+ reason: 'runtime-skills-confirmed',
+ loadedSkillCount: 1,
+ });
+
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: {
+ scope: 'temporary',
+ source: 'local',
+ baseDir: skillPath,
+ path: `${skillPath}/README.md`,
+ },
+ }],
})).toMatchObject({
reason: 'runtime-skills-missing',
loadedSkillCount: 0,
diff --git a/packages/maker-core/src/agents/pi/__tests__/project-resource-cli.test.ts b/packages/maker-core/src/agents/pi/__tests__/project-resource-cli.test.ts
new file mode 100644
index 0000000000..f2f41f8625
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/project-resource-cli.test.ts
@@ -0,0 +1,141 @@
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ assertPiSpawnArgvFitsPlatform,
+ collectPiProjectResourceCliPaths,
+ comparePiResourcePaths,
+ estimateSpawnArgvLength,
+ filterPiProjectCliSkills,
+ PI_POSIX_SPAWN_ARGV_BUDGET,
+ PI_WINDOWS_SPAWN_ARGV_BUDGET,
+ piProjectResourceCliArgs,
+} from '../project-resource-cli.js';
+
+describe('collectPiProjectResourceCliPaths', () => {
+ let root = '';
+
+ afterEach(() => {
+ if (root) rmSync(root, { recursive: true, force: true });
+ });
+
+ function makeRepo(): string {
+ root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-cli-')));
+ mkdirSync(path.join(root, '.git'));
+ return root;
+ }
+
+ it('collects in-repo skills, prompts and extensions', () => {
+ const repo = makeRepo();
+ const skillDir = path.join(repo, '.pi', 'skills', 'demo');
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(path.join(skillDir, 'SKILL.md'), '# demo\n');
+ const agentsSkill = path.join(repo, '.agents', 'skills', 'repo-skill');
+ mkdirSync(agentsSkill, { recursive: true });
+ writeFileSync(path.join(agentsSkill, 'SKILL.md'), '# repo\n');
+ mkdirSync(path.join(repo, '.pi', 'prompts'), { recursive: true });
+ writeFileSync(path.join(repo, '.pi', 'prompts', 'review.md'), '# review\n');
+ mkdirSync(path.join(repo, '.pi', 'extensions'), { recursive: true });
+ writeFileSync(path.join(repo, '.pi', 'extensions', 'hook.ts'), 'export default () => {};\n');
+ mkdirSync(path.join(repo, '.pi', 'extensions', 'nested'));
+ writeFileSync(path.join(repo, '.pi', 'extensions', 'nested', 'index.ts'), 'export default () => {};\n');
+
+ const collected = collectPiProjectResourceCliPaths(repo);
+ expect(collected.skills).toEqual([
+ realpathSync(agentsSkill),
+ realpathSync(skillDir),
+ ].sort((a, b) => a.localeCompare(b)));
+ expect(collected.promptTemplates).toEqual([realpathSync(path.join(repo, '.pi', 'prompts', 'review.md'))]);
+ expect(collected.extensions).toEqual([
+ realpathSync(path.join(repo, '.pi', 'extensions', 'hook.ts')),
+ realpathSync(path.join(repo, '.pi', 'extensions', 'nested', 'index.ts')),
+ ].sort((a, b) => a.localeCompare(b)));
+ expect(piProjectResourceCliArgs(collected)).toEqual([
+ ...collected.skills.flatMap((skillPath) => ['--skill', skillPath]),
+ '--prompt-template', collected.promptTemplates[0],
+ ...collected.extensions.flatMap((extensionPath) => ['--extension', extensionPath]),
+ ]);
+ });
+
+ it('collects skills whose entry file is skill.md', () => {
+ const repo = makeRepo();
+ const skillDir = path.join(repo, '.pi', 'skills', 'lower');
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(path.join(skillDir, 'skill.md'), '# lower\n');
+ expect(collectPiProjectResourceCliPaths(repo).skills).toEqual([realpathSync(skillDir)]);
+ });
+
+ it('skips escaped symlinks and settings files', () => {
+ const repo = makeRepo();
+ const outside = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-cli-out-')));
+ try {
+ mkdirSync(path.join(outside, 'evil-skill'));
+ writeFileSync(path.join(outside, 'evil-skill', 'SKILL.md'), '# evil\n');
+ mkdirSync(path.join(repo, '.pi', 'skills'), { recursive: true });
+ symlinkSync(path.join(outside, 'evil-skill'), path.join(repo, '.pi', 'skills', 'escaped'));
+ mkdirSync(path.join(repo, '.pi'), { recursive: true });
+ writeFileSync(path.join(repo, '.pi', 'settings.json'), '{"compaction":{"enabled":false}}\n');
+
+ const collected = collectPiProjectResourceCliPaths(repo);
+ expect(collected.skills).toEqual([]);
+ expect(collected.promptTemplates).toEqual([]);
+ expect(collected.extensions).toEqual([]);
+ } finally {
+ rmSync(outside, { recursive: true, force: true });
+ }
+ });
+
+ it('does not walk .agents/skills past the nearest git root', () => {
+ const repo = makeRepo();
+ const nested = path.join(repo, 'packages', 'app');
+ mkdirSync(nested, { recursive: true });
+ mkdirSync(path.join(nested, '.git'));
+ const outerSkill = path.join(repo, '.agents', 'skills', 'outer');
+ mkdirSync(outerSkill, { recursive: true });
+ writeFileSync(path.join(outerSkill, 'SKILL.md'), '# outer\n');
+ const innerSkill = path.join(nested, '.pi', 'skills', 'inner');
+ mkdirSync(innerSkill, { recursive: true });
+ writeFileSync(path.join(innerSkill, 'SKILL.md'), '# inner\n');
+
+ expect(collectPiProjectResourceCliPaths(nested).skills).toEqual([realpathSync(innerSkill)]);
+ });
+
+ it('filters disabled skill directories', () => {
+ const repo = makeRepo();
+ const skillDir = path.join(repo, '.pi', 'skills', 'demo');
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(path.join(skillDir, 'SKILL.md'), '# demo\n');
+ const realSkill = realpathSync(skillDir);
+ expect(filterPiProjectCliSkills([realSkill], [path.join(realSkill, 'SKILL.md')])).toEqual([]);
+ expect(filterPiProjectCliSkills([realSkill], [])).toEqual([realSkill]);
+ });
+});
+
+describe('pi project resource path order and spawn argv budget', () => {
+ it('orders paths by code units so locale cannot change Skill precedence', () => {
+ expect(['b', 'A'].sort(comparePiResourcePaths)).toEqual(['A', 'b']);
+ });
+
+ it('rejects an oversized Windows command line before spawn', () => {
+ const args = Array.from(
+ { length: 400 },
+ (_, index) => `C:\\Users\\very\\long\\cindy\\project\\.pi\\skills\\skill-${String(index).padStart(3, '0')}\\with\\nested\\folders`,
+ );
+ expect(estimateSpawnArgvLength(args)).toBeGreaterThan(PI_WINDOWS_SPAWN_ARGV_BUDGET);
+ expect(estimateSpawnArgvLength(args)).toBeLessThan(PI_POSIX_SPAWN_ARGV_BUDGET);
+ expect(() => assertPiSpawnArgvFitsPlatform(args, 'win32')).toThrow(/too many Pi skills/);
+ expect(() => assertPiSpawnArgvFitsPlatform(args, 'darwin')).not.toThrow();
+ });
+
+ it('rejects an oversized POSIX command line before spawn', () => {
+ const args = Array.from(
+ { length: 2_000 },
+ (_, index) => `/Users/very/long/cindy/project/.pi/skills/skill-${String(index).padStart(4, '0')}/with/nested/folders`,
+ );
+ expect(estimateSpawnArgvLength(args)).toBeGreaterThan(PI_POSIX_SPAWN_ARGV_BUDGET);
+ expect(() => assertPiSpawnArgvFitsPlatform(args, 'darwin')).toThrow(/too many Pi skills/);
+ expect(() => assertPiSpawnArgvFitsPlatform(args, 'linux')).toThrow(/too many Pi skills/);
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts b/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts
index 45977a7aa1..594c83c5bf 100644
--- a/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts
@@ -84,6 +84,48 @@ describe('Pi runtime capability parsing', () => {
], ['/private/cindy/pi-packages/sample'])).toEqual([]);
});
+ it('authorizes project prompt and extension commands from explicit launch paths', () => {
+ const promptFile = '/repo/.pi/prompts/review.md';
+ const extensionFile = '/repo/.pi/extensions/hook.ts';
+ expect(identifyManagedPiPackageCommandNames([
+ {
+ ...command,
+ name: 'review',
+ source: 'prompt',
+ sourceInfo: { path: promptFile, source: 'prompt' },
+ },
+ {
+ ...command,
+ name: 'hook-cmd',
+ source: 'extension',
+ sourceInfo: { path: extensionFile, source: 'extension' },
+ },
+ {
+ ...command,
+ name: 'plan',
+ source: 'extension',
+ sourceInfo: { path: '/cindy/internal/plan-mode.ts', source: 'extension' },
+ },
+ ], [promptFile, extensionFile]).sort()).toEqual(['hook-cmd', 'review']);
+ });
+
+ it('authorizes a colliding name when every catalog entry is in package or project roots', () => {
+ expect(identifyManagedPiPackageCommandNames([
+ {
+ ...command,
+ name: 'foo',
+ source: 'extension',
+ sourceInfo: { path: '/private/cindy/pi-packages/sample/index.ts' },
+ },
+ {
+ ...command,
+ name: 'foo',
+ source: 'prompt',
+ sourceInfo: { path: '/repo/.pi/prompts/foo.md' },
+ },
+ ], ['/private/cindy/pi-packages/sample', '/repo/.pi/prompts/foo.md'])).toEqual(['foo']);
+ });
+
it('snapshots managed skills and marks only unambiguous runtime-proven commands loaded', () => {
const packageRoot = path.resolve('managed-package-fixture');
const loadedSkill = path.join(packageRoot, 'skills', 'loaded', 'SKILL.md');
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 671895c3ae..34926974c1 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -195,6 +195,13 @@ import {
unavailablePiProjectResourceAssembly,
} from './project-resource-assembly.js';
import { applyPiBotSkillPolicy } from './bot-skill-policy.js';
+import {
+ assertPiSpawnArgvFitsPlatform,
+ collectPiProjectResourceCliPaths,
+ emptyPiProjectResourceCliPaths,
+ filterPiProjectCliSkills,
+ piProjectResourceCliArgs,
+} from './project-resource-cli.js';
import {
createPiTranslateContext,
disposePiTranslateContext,
@@ -864,11 +871,18 @@ function reconcilePiStartupEffort(requested: Effort | undefined, model: ModelDes
* 有效)—— 防止误触扩展命令让 Cindy 侧状态镜像脱同步(如 /plan),也堵住未来扩展/包
* 新增命令带来的攻击面。内部控制路径(setPlanMode 的 /plan)不走本函数。
*/
+function isAuthorizedPiSlashCommandName(
+ name: string,
+ manifest: PiRuntimeCapabilityManifest | undefined,
+): boolean {
+ if (name.startsWith('skill:')) return true;
+ if (manifest?.status !== 'loaded') return false;
+ return manifest.authorizedSlashCommandNames?.includes(name) === true;
+}
+
function isExecutablePiSlashCommand(text: string, manifest: PiRuntimeCapabilityManifest | undefined): boolean {
const match = text.trimStart().match(/^\/([^\s]+)(?:\s|$)/);
- if (!match?.[1]) return false;
- if (match[1].startsWith('skill:')) return true;
- return manifest?.status === 'loaded' && manifest.managedPackageCommandNames?.includes(match[1]) === true;
+ return Boolean(match?.[1] && isAuthorizedPiSlashCommandName(match[1], manifest));
}
function managedExtensionSlashCommandName(
@@ -877,7 +891,7 @@ function managedExtensionSlashCommandName(
): string | undefined {
const match = text.trimStart().match(/^\/([^\s]+)(?:\s|$)/);
if (!match?.[1] || manifest?.status !== 'loaded') return undefined;
- if (manifest.managedPackageCommandNames?.includes(match[1]) !== true) return undefined;
+ if (!isAuthorizedPiSlashCommandName(match[1], manifest)) return undefined;
if (!manifest.commands.some((command) => command.name === match[1] && command.source === 'extension')) {
return undefined;
}
@@ -3562,6 +3576,7 @@ export class PiAgent extends BaseAgent {
? [] : [...(this.deps.getDisabledSkillPaths?.() ?? [])];
let disabledSkillLaunch = snapshotDisabledSkillLaunch(disabledSkillPaths);
const disabledSkillSnapshot = disabledSkillLaunch.identities;
+ const loadProjectResourcesInPlace = !reviewMode && !opts.botRuntimeProfile && !opts.remoteHostId;
let projectResourceAssembly = unavailablePiProjectResourceAssembly(
reviewMode ? 'review-mode-project-resources-disabled' : 'approval-resolver-unavailable',
);
@@ -3574,7 +3589,11 @@ export class PiAgent extends BaseAgent {
});
projectResourceAssembly = await assembleApprovedPiProjectResources(trustInput, opts.workingDir);
projectResourceAssembly = filterPiDisabledProjectSkills(projectResourceAssembly, currentDisabledSkillLaunchPaths(disabledSkillLaunch));
- projectResourceAssembly = await stageApprovedPiProjectResources(projectResourceAssembly, configHome);
+ // In-place CLI loading uses original repo paths. Staging copies are unused
+ // there and would recopy every Skill asset on each startSession.
+ if (!loadProjectResourcesInPlace) {
+ projectResourceAssembly = await stageApprovedPiProjectResources(projectResourceAssembly, configHome);
+ }
} catch {
projectResourceAssembly = unavailablePiProjectResourceAssembly('approval-resolver-failed');
this.deps.logger.warn('pi project approval resolver failed closed', {
@@ -3669,13 +3688,27 @@ export class PiAgent extends BaseAgent {
typeof entry === 'string' ? entry : entry.source
));
+ // Local root tasks load project skills/prompts/extensions in place via
+ // explicit CLI flags. Keep --no-approve so `.pi/settings.json` is unread.
+ const collectedProjectResources = loadProjectResourcesInPlace
+ ? collectPiProjectResourceCliPaths(opts.workingDir)
+ : emptyPiProjectResourceCliPaths();
+ const projectResourceCli = loadProjectResourcesInPlace
+ ? {
+ ...collectedProjectResources,
+ skills: filterPiProjectCliSkills(
+ collectedProjectResources.skills,
+ currentDisabledSkillLaunchPaths(disabledSkillLaunch),
+ ),
+ }
+ : collectedProjectResources;
+
const args = [
'--mode',
'rpc',
- // --no-approve remains the hard project-resource gate. Only a local
- // runtime with Main-supplied user package roots omits --no-extensions, so
- // Pi can discover those runtime-settings packages without trusting the
- // task's .pi/extensions or .pi/settings.json.
+ // --no-approve remains the hard project-settings gate. Explicit --skill /
+ // --prompt-template / --extension pass original in-repo paths without
+ // trusting `.pi/settings.json` or auto-installing project packages.
'--no-approve',
...(nativePackagePaths.length === 0 ? ['--no-extensions'] : []),
'--session-dir',
@@ -3694,8 +3727,23 @@ export class PiAgent extends BaseAgent {
bridgeExtensionPath,
...(localSubagentSupported ? ['--extension', subagentExtensionPath] : []),
...(!reviewMode && planModeExtAvailable ? ['--extension', planModeExtPath] : []),
- ...botSkillSelection.explicitSkillPaths.flatMap((skillPath) => ['--skill', skillPath]),
+ ...(loadProjectResourcesInPlace
+ ? piProjectResourceCliArgs(projectResourceCli)
+ : botSkillSelection.explicitSkillPaths.flatMap((skillPath) => ['--skill', skillPath])),
];
+ try {
+ assertPiSpawnArgvFitsPlatform(args);
+ } catch (error) {
+ try {
+ disposeSessionCtx?.();
+ } catch {
+ /* best-effort: cleanup failure must not mask argv budget failure */
+ }
+ disposeSessionCtx = undefined;
+ cleanupConfigHome();
+ cleanupRuntimeFiles();
+ throw error;
+ }
const queue: AsyncQueue<AgentEvent> = createAsyncQueue<AgentEvent>();
const ctx: PiTranslateContext = createPiTranslateContext(this.deps.logger);
@@ -5426,13 +5474,24 @@ export class PiAgent extends BaseAgent {
generation,
stage,
);
+ const managedPackageRoots = [...nativePackageRoots, ...managedPackageResources.packageRoots];
const managedPackageCommandNames = identifyManagedPiPackageCommandNames(
capturedManifest.commands,
- [...nativePackageRoots, ...managedPackageResources.packageRoots],
+ managedPackageRoots,
+ );
+ const authorizedSlashCommandNames = identifyManagedPiPackageCommandNames(
+ capturedManifest.commands,
+ [
+ ...managedPackageRoots,
+ ...projectResourceCli.skills,
+ ...projectResourceCli.promptTemplates,
+ ...projectResourceCli.extensions,
+ ],
);
const manifest = {
...capturedManifest,
managedPackageCommandNames,
+ authorizedSlashCommandNames,
managedPackageSkills: snapshotManagedPiPackageSkills(
managedPackageResources.skills,
capturedManifest.commands,
diff --git a/packages/maker-core/src/agents/pi/project-resource-cli.ts b/packages/maker-core/src/agents/pi/project-resource-cli.ts
new file mode 100644
index 0000000000..240081814f
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts
@@ -0,0 +1,208 @@
+/**
+ * Collect project Skill / prompt / extension paths for explicit Pi CLI flags.
+ *
+ * Local root tasks keep `--no-approve` (so `.pi/settings.json` stays unread)
+ * and pass original in-repo paths via `--skill`, `--prompt-template`, and
+ * `--extension`. Review, Bot, fork, and remote sessions do not use this.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+export interface PiProjectResourceCliPaths {
+ readonly skills: readonly string[];
+ readonly promptTemplates: readonly string[];
+ readonly extensions: readonly string[];
+}
+
+export function emptyPiProjectResourceCliPaths(): PiProjectResourceCliPaths {
+ return Object.freeze({
+ skills: Object.freeze([]),
+ promptTemplates: Object.freeze([]),
+ extensions: Object.freeze([]),
+ });
+}
+
+function realpathOrNull(target: string): string | null {
+ try {
+ return fs.realpathSync(target);
+ } catch {
+ return null;
+ }
+}
+
+function isDir(target: string): boolean {
+ try {
+ return fs.statSync(target).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+function isFile(target: string): boolean {
+ try {
+ return fs.statSync(target).isFile();
+ } catch {
+ return false;
+ }
+}
+
+function hasGitMarker(dir: string): boolean {
+ try {
+ const marker = fs.statSync(path.join(dir, '.git'));
+ return marker.isDirectory() || marker.isFile();
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ return code !== 'ENOENT' && code !== 'ENOTDIR';
+ }
+}
+
+function findNearestGitRoot(workingDir: string): string | null {
+ let current = workingDir;
+ while (true) {
+ if (hasGitMarker(current)) return current;
+ const parent = path.dirname(current);
+ if (parent === current) return null;
+ current = parent;
+ }
+}
+
+function isWithinRoot(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
+}
+
+function listDir(dir: string): fs.Dirent[] {
+ try {
+ return fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+}
+
+function collectSkillDirs(repoRoot: string, skillsDir: string, bucket: Set<string>): void {
+ const resolvedDir = realpathOrNull(skillsDir);
+ if (!resolvedDir || !isDir(resolvedDir) || !isWithinRoot(repoRoot, resolvedDir)) return;
+ for (const entry of listDir(resolvedDir)) {
+ if (entry.name.startsWith('.')) continue;
+ const realFolder = realpathOrNull(path.join(resolvedDir, entry.name));
+ if (!realFolder || !isDir(realFolder) || !isWithinRoot(repoRoot, realFolder)) continue;
+ const upper = path.join(realFolder, 'SKILL.md');
+ const lower = path.join(realFolder, 'skill.md');
+ const skillMd = isFile(upper) ? upper : isFile(lower) ? lower : null;
+ if (!skillMd) continue;
+ const realMd = realpathOrNull(skillMd);
+ if (!realMd || !isFile(realMd) || !isWithinRoot(repoRoot, realMd)) continue;
+ bucket.add(realFolder);
+ }
+}
+
+export function collectPiProjectResourceCliPaths(workingDir: string): PiProjectResourceCliPaths {
+ if (!workingDir || !path.isAbsolute(workingDir) || !isDir(workingDir)) {
+ return emptyPiProjectResourceCliPaths();
+ }
+ const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir);
+ const repoRoot = findNearestGitRoot(scanRoot) ?? scanRoot;
+ const skills = new Set<string>();
+ const promptTemplates = new Set<string>();
+ const extensions = new Set<string>();
+
+ collectSkillDirs(repoRoot, path.join(scanRoot, '.pi', 'skills'), skills);
+ let current = scanRoot;
+ while (true) {
+ collectSkillDirs(repoRoot, path.join(current, '.agents', 'skills'), skills);
+ if (current === repoRoot) break;
+ const parent = path.dirname(current);
+ if (parent === current) break;
+ current = parent;
+ }
+
+ const realPrompts = realpathOrNull(path.join(scanRoot, '.pi', 'prompts'));
+ if (realPrompts && isDir(realPrompts) && isWithinRoot(repoRoot, realPrompts)) {
+ for (const entry of listDir(realPrompts)) {
+ if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue;
+ const realFile = realpathOrNull(path.join(realPrompts, entry.name));
+ if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) continue;
+ promptTemplates.add(realFile);
+ }
+ }
+
+ const realExt = realpathOrNull(path.join(scanRoot, '.pi', 'extensions'));
+ if (realExt && isDir(realExt) && isWithinRoot(repoRoot, realExt)) {
+ for (const entry of listDir(realExt)) {
+ if (entry.name.startsWith('.')) continue;
+ const realChild = realpathOrNull(path.join(realExt, entry.name));
+ if (!realChild || !isWithinRoot(repoRoot, realChild)) continue;
+ if (isFile(realChild) && realChild.endsWith('.ts')) {
+ extensions.add(realChild);
+ continue;
+ }
+ if (!isDir(realChild)) continue;
+ const realIndex = realpathOrNull(path.join(realChild, 'index.ts'));
+ if (realIndex && isFile(realIndex) && isWithinRoot(repoRoot, realIndex)) {
+ extensions.add(realIndex);
+ }
+ }
+ }
+
+ return Object.freeze({
+ skills: Object.freeze([...skills].sort(comparePiResourcePaths)),
+ promptTemplates: Object.freeze([...promptTemplates].sort(comparePiResourcePaths)),
+ extensions: Object.freeze([...extensions].sort(comparePiResourcePaths)),
+ });
+}
+
+/** Locale-independent path order so duplicate Skill names pick the same winner everywhere. */
+export function comparePiResourcePaths(left: string, right: string): number {
+ if (left < right) return -1;
+ if (left > right) return 1;
+ return 0;
+}
+
+/** Conservative CreateProcess command-line budget; the hard Windows cap is 32767. */
+export const PI_WINDOWS_SPAWN_ARGV_BUDGET = 30_000;
+/** Leave headroom under typical macOS/Linux ARG_MAX, which is shared with env. */
+export const PI_POSIX_SPAWN_ARGV_BUDGET = 128_000;
+
+export function estimateSpawnArgvLength(args: readonly string[]): number {
+ return args.reduce((total, arg) => total + arg.length + 3, 0);
+}
+
+export function piSpawnArgvBudget(platform: NodeJS.Platform): number | null {
+ if (platform === 'win32') return PI_WINDOWS_SPAWN_ARGV_BUDGET;
+ if (platform === 'darwin' || platform === 'linux') return PI_POSIX_SPAWN_ARGV_BUDGET;
+ return null;
+}
+
+export function assertPiSpawnArgvFitsPlatform(
+ args: readonly string[],
+ platform: NodeJS.Platform = process.platform,
+): void {
+ const budget = piSpawnArgvBudget(platform);
+ if (budget === null || estimateSpawnArgvLength(args) <= budget) return;
+ throw new Error(
+ 'This project has too many Pi skills, prompts, or extensions to start a task. Remove some and try again.',
+ );
+}
+
+export function filterPiProjectCliSkills(
+ skills: readonly string[],
+ disabledSkillPaths: readonly string[],
+): readonly string[] {
+ if (disabledSkillPaths.length === 0) return skills;
+ const denied = new Set<string>();
+ for (const disabled of disabledSkillPaths) {
+ const real = realpathOrNull(disabled) ?? path.resolve(disabled);
+ denied.add(real);
+ if (path.basename(real).toLowerCase() === 'skill.md') denied.add(path.dirname(real));
+ }
+ return Object.freeze(skills.filter((skillPath) => !denied.has(skillPath)));
+}
+
+export function piProjectResourceCliArgs(paths: PiProjectResourceCliPaths): string[] {
+ return [
+ ...paths.skills.flatMap((skillPath) => ['--skill', skillPath]),
+ ...paths.promptTemplates.flatMap((promptPath) => ['--prompt-template', promptPath]),
+ ...paths.extensions.flatMap((extensionPath) => ['--extension', extensionPath]),
+ ];
+}
diff --git a/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts b/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts
index ecd8e1ee33..d5e7f75b8c 100644
--- a/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts
+++ b/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts
@@ -23,6 +23,6 @@ export function piExplicitSkillRuntimePath(command: PiRuntimeCommand): string |
|| skillFile.includes('\0')
|| path.resolve(path.dirname(skillFile)) !== path.resolve(baseDir)
) return null;
- if (path.basename(skillFile) === 'SKILL.md') return baseDir;
+ if (path.basename(skillFile).toLowerCase() === 'skill.md') return baseDir;
return path.extname(skillFile) === '.md' ? skillFile : null;
}
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index ff520dc44c..ac18e9ef61 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -2290,6 +2290,60 @@ describe('Maker Pi runtime skill status', () => {
expect(wrongProject.skills.every((skill) => skill.runtimeStatus === 'discovered')).toBe(true);
});
+ it('marks Windows project-scope --skill loaded when frontmatter name differs from the folder', async () => {
+ const agent = createAgent(async (opts) => {
+ const handle = createHandle({ id: `pi-${opts.sessionId}`, agentKind: 'pi' });
+ handle.getRuntimeCapabilities = () => ({
+ sessionId: opts.sessionId,
+ capturedAt: '2026-09-14T00:00:00.000Z',
+ generation: 1,
+ status: 'loaded',
+ source: 'pi:get_commands',
+ commands: [{
+ name: 'skill:frontmatter-alias',
+ source: 'skill',
+ sourceInfo: {
+ source: 'local',
+ scope: 'project',
+ baseDir: '/repo/.pi/skills/folder-name',
+ path: '/repo/.pi/skills/folder-name/SKILL.md',
+ },
+ }],
+ });
+ return handle;
+ }, 'pi');
+ agent.listAgentSkills = vi.fn(async () => ({
+ skills: [{
+ kind: 'agent-skill' as const,
+ name: 'folder-name',
+ source: 'skill' as const,
+ scope: 'repo' as const,
+ path: '/repo/.pi/skills/folder-name/SKILL.md',
+ runtimeStatus: 'discovered' as const,
+ }],
+ }));
+ const maker = new Maker({
+ agents: { pi: agent },
+ storage: createStorage(),
+ logger: createLogger(),
+ });
+ await maker.createSession({
+ id: 'win-alias',
+ agentKind: 'pi',
+ workingDir: '/repo',
+ model: 'm',
+ });
+ const listed = await maker.listAgentSkills('pi', {
+ workingDir: '/repo',
+ sessionId: 'win-alias',
+ });
+ expect(listed.skills[0]).toMatchObject({
+ name: 'folder-name',
+ runtimeStatus: 'loaded',
+ runtimeCommandName: 'skill:frontmatter-alias',
+ });
+ });
+
it('keeps a project skill discovered when its source no longer matches the launch snapshot', async () => {
const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'maker-pi-skill-source-')));
const repoRoot = path.join(root, 'repo');
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index fc1a520f08..0ce4016694 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -294,21 +294,21 @@ async function mergePiRuntimeSkillStatuses(
const baseDir = command.sourceInfo.baseDir;
if (command.source !== 'skill' || !command.name.startsWith('skill:')) continue;
const skillName = command.name.slice('skill:'.length);
+ // Explicit --skill is `project` on Windows and `temporary` on macOS.
+ // Match that provenance by path first so frontmatter aliases still load.
+ const explicitPath = piExplicitSkillRuntimePath(command);
+ if (explicitPath) {
+ loadedExplicitSkills.set(canonicalPiRuntimePath(explicitPath), command.name);
+ if (typeof command.sourceInfo.path === 'string') {
+ loadedExplicitSkills.set(canonicalPiRuntimePath(command.sourceInfo.path), command.name);
+ }
+ continue;
+ }
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 (
@@ -328,7 +328,8 @@ async function mergePiRuntimeSkillStatuses(
const canonicalSkillPath = canonicalPiRuntimePath(skill.path);
if (!changedProjectSkills.has(canonicalSkillPath)) {
runtimeCommandName = loadedExplicitSkills.get(canonicalSkillPath)
- ?? [skill.path, path.dirname(path.dirname(skill.path))]
+ ?? loadedExplicitSkills.get(canonicalPiRuntimePath(path.dirname(skill.path)))
+ ?? [skill.path, path.dirname(skill.path), path.dirname(path.dirname(skill.path))]
.map(canonicalPiRuntimePath)
.map((skillPath) => loadedLegacyProjectSkills.get([skill.name, skillPath].join('\0')))
.find((commandName) => commandName !== undefined);
diff --git a/packages/maker-core/src/types/pi-runtime-capabilities.ts b/packages/maker-core/src/types/pi-runtime-capabilities.ts
index f5438fb859..76f650fce8 100644
--- a/packages/maker-core/src/types/pi-runtime-capabilities.ts
+++ b/packages/maker-core/src/types/pi-runtime-capabilities.ts
@@ -92,6 +92,8 @@ export interface PiRuntimeCapabilityManifest {
commands: readonly PiRuntimeCommand[];
/** Commands whose get_commands provenance resolves inside an enabled Cindy-managed Pi package. */
managedPackageCommandNames?: readonly string[];
+ /** Slash names whose every catalog entry is inside a managed package root or this session's explicit project paths. */
+ authorizedSlashCommandNames?: readonly string[];
/** Exact managed skills passed to this runtime at launch; never re-read from the global store. */
managedPackageSkills?: readonly PiManagedPackageSkillRuntimeSnapshot[];
error?: PiRuntimeCapabilityError;