Skip to content

Commit f04ef71

Browse files
authored
Merge pull request #60 from jnMetaCode/sync/v6-pi-harness
feat(pi): 新增 Pi (oh-my-pi) harness 支持(关 #44,对齐上游 v6.0.0)
2 parents 483621d + a3349d4 commit f04ef71

7 files changed

Lines changed: 351 additions & 2 deletions

File tree

.pi/extensions/superpowers.ts

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import { readFileSync } from "node:fs";
2+
import { dirname, resolve } from "node:path";
3+
import { fileURLToPath } from "node:url";
4+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5+
6+
const EXTREMELY_IMPORTANT_MARKER = "<EXTREMELY_IMPORTANT>";
7+
const BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for pi";
8+
9+
const extensionDir = dirname(fileURLToPath(import.meta.url));
10+
const packageRoot = resolve(extensionDir, "../..");
11+
const skillsDir = resolve(packageRoot, "skills");
12+
const bootstrapSkillPath = resolve(skillsDir, "using-superpowers", "SKILL.md");
13+
14+
let cachedBootstrap: string | null | undefined;
15+
16+
export default function superpowersPiExtension(pi: ExtensionAPI) {
17+
let injectBootstrap = true;
18+
19+
pi.on("resources_discover", async () => ({
20+
skillPaths: [skillsDir],
21+
}));
22+
23+
pi.on("session_start", async () => {
24+
injectBootstrap = true;
25+
});
26+
27+
pi.on("session_compact", async () => {
28+
injectBootstrap = true;
29+
});
30+
31+
pi.on("agent_end", async () => {
32+
injectBootstrap = false;
33+
});
34+
35+
pi.on("context", async (event) => {
36+
if (!injectBootstrap) return;
37+
if (event.messages.some(messageContainsBootstrap)) return;
38+
39+
const bootstrap = getBootstrapContent();
40+
if (!bootstrap) return;
41+
42+
const bootstrapMessage = {
43+
role: "user" as const,
44+
content: [{ type: "text" as const, text: bootstrap }],
45+
timestamp: Date.now(),
46+
};
47+
48+
const insertAt = firstNonCompactionSummaryIndex(event.messages);
49+
return {
50+
messages: [
51+
...event.messages.slice(0, insertAt),
52+
bootstrapMessage,
53+
...event.messages.slice(insertAt),
54+
],
55+
};
56+
});
57+
}
58+
59+
function getBootstrapContent(): string | null {
60+
if (cachedBootstrap !== undefined) return cachedBootstrap;
61+
62+
try {
63+
const skillContent = readFileSync(bootstrapSkillPath, "utf8");
64+
const body = stripFrontmatter(skillContent);
65+
cachedBootstrap = `${EXTREMELY_IMPORTANT_MARKER}
66+
${BOOTSTRAP_MARKER}
67+
68+
You have superpowers.
69+
70+
The using-superpowers skill content is included below and is already loaded for this Pi session. Follow it now. Do not try to load using-superpowers again.
71+
72+
${body}
73+
74+
${piToolMapping()}
75+
</EXTREMELY_IMPORTANT>`;
76+
return cachedBootstrap;
77+
} catch {
78+
cachedBootstrap = null;
79+
return null;
80+
}
81+
}
82+
83+
function stripFrontmatter(content: string): string {
84+
const match = content.match(/^---\n[\s\S]*?\n---\n([\s\S]*)$/);
85+
return (match ? match[1] : content).trim();
86+
}
87+
88+
function piToolMapping(): string {
89+
return `## Pi tool mapping
90+
91+
Pi has native skills but does not expose Claude Code's \`Skill\` tool. When a Superpowers instruction says to invoke a skill, use Pi's native skill system instead: load the relevant \`SKILL.md\` with \`read\` when the skill applies, or let a human invoke \`/skill:name\` explicitly.
92+
93+
Pi's built-in coding tools are lowercase: \`read\`, \`write\`, \`edit\`, \`bash\`, plus optional \`grep\`, \`find\`, and \`ls\`. Use those for the corresponding actions: read a file, create or edit files, run shell commands, search file contents, find files by name, and list directories.
94+
95+
Pi does not ship a standard subagent tool. If a subagent tool such as \`subagent\` from \`pi-subagents\` is available, use it for Superpowers subagent workflows. If no subagent tool is available, do the work in this session or explain the missing capability instead of inventing \`Task\` calls.
96+
97+
Pi does not ship a standard task-list tool. If an installed todo/task tool is available, use it. Otherwise track work in plan files or a repo-local \`TODO.md\` when task tracking is needed. Treat older \`TodoWrite\` references as this task-tracking action.`;
98+
}
99+
100+
function messageContainsBootstrap(message: unknown): boolean {
101+
const content = (message as { content?: unknown }).content;
102+
if (typeof content === "string") return content.includes(BOOTSTRAP_MARKER);
103+
if (!Array.isArray(content)) return false;
104+
return content.some((part) => {
105+
return (
106+
part &&
107+
typeof part === "object" &&
108+
(part as { type?: unknown }).type === "text" &&
109+
typeof (part as { text?: unknown }).text === "string" &&
110+
(part as { text: string }).text.includes(BOOTSTRAP_MARKER)
111+
);
112+
});
113+
}
114+
115+
function firstNonCompactionSummaryIndex(messages: unknown[]): number {
116+
let index = 0;
117+
while ((messages[index] as { role?: unknown } | undefined)?.role === "compactionSummary") {
118+
index += 1;
119+
}
120+
return index;
121+
}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ cp -r superpowers-zh/skills /your/project/.qoder/skills # Qoder(阿里 AI
223223
| Claw Code | `.claw/skills/*/SKILL.md` | Rust 版 CLI agent,兼容 Claude Code 的 SKILL.md 格式 |
224224
| Qoder | `.qoder/skills/*/SKILL.md` + `.qoder/rules/superpowers-zh.md` | 阿里 AI IDE,自动生成 `trigger: always_on` 的 bootstrap rule |
225225

226-
> **详细安装指南**[Kiro](docs/README.kiro.md) · [DeerFlow](docs/README.deerflow.md) · [Trae](docs/README.trae.md) · [Antigravity](docs/README.antigravity.md) · [VS Code](docs/README.vscode.md) · [Codex](docs/README.codex.md) · [OpenCode](docs/README.opencode.md) · [OpenClaw](docs/README.openclaw.md) · [Windsurf](docs/README.windsurf.md) · [Gemini CLI](docs/README.gemini-cli.md) · [Aider](docs/README.aider.md) · [Qwen Code](docs/README.qwen.md) · [Hermes Agent](docs/README.hermes.md) · [Qoder](docs/README.qoder.md) · [Kimi Code](docs/README.kimi.md)
226+
> **详细安装指南**[Kiro](docs/README.kiro.md) · [DeerFlow](docs/README.deerflow.md) · [Trae](docs/README.trae.md) · [Antigravity](docs/README.antigravity.md) · [VS Code](docs/README.vscode.md) · [Codex](docs/README.codex.md) · [OpenCode](docs/README.opencode.md) · [OpenClaw](docs/README.openclaw.md) · [Windsurf](docs/README.windsurf.md) · [Gemini CLI](docs/README.gemini-cli.md) · [Aider](docs/README.aider.md) · [Qwen Code](docs/README.qwen.md) · [Hermes Agent](docs/README.hermes.md) · [Qoder](docs/README.qoder.md) · [Kimi Code](docs/README.kimi.md) · [Pi](docs/README.pi.md)
227227
228228
### 卸载 / 误装清理(v1.2.1+)
229229

docs/README.pi.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Superpowers 中文版 · Pi 指南
2+
3+
[Pi](https://github.com/earendil-works/pi)(oh-my-pi)上使用 superpowers-zh 的完整说明。
4+
5+
## 安装
6+
7+
superpowers-zh 通过 Pi 的扩展机制集成,**直接指向仓库现有的 `skills/` 目录**——不复制 skill、不建 symlink、无额外运行时依赖。
8+
9+
集成由 `package.json` 里的 `pi` 字段声明:
10+
11+
```json
12+
"pi": {
13+
"skills": ["./skills"],
14+
"extensions": ["./.pi/extensions/superpowers.ts"]
15+
}
16+
```
17+
18+
并带 `pi-package` keyword,便于 Pi 发现这是一个 Pi 包。
19+
20+
按 Pi 的包安装方式安装 `superpowers-zh`(参考 Pi 文档的包管理命令),Pi 会读取上述 `pi` 配置,挂载 `skills/` 并加载 `.pi/extensions/superpowers.ts` 扩展。
21+
22+
## 工作原理
23+
24+
`.pi/extensions/superpowers.ts` 注册了 Pi 的生命周期钩子:
25+
26+
1. **`resources_discover`** — 把仓库的 `skills/` 目录贡献给 Pi 的技能系统;
27+
2. **`session_start` / `session_compact`** — 标记需要重新注入 bootstrap;
28+
3. **`context`** — 在会话上下文中注入 `using-superpowers` 的内容(去除 frontmatter)+ Pi 工具映射,作为「You have superpowers」bootstrap,让 skill 在恰当时机被遵循;
29+
4. **`agent_end`** — 一轮结束后停止重复注入。
30+
31+
注入带有唯一标记,已存在时不会重复注入;并且会插入到 compaction summary 之后,避免被压缩流程吞掉。
32+
33+
## 工具映射
34+
35+
Pi 有原生技能系统,但**不暴露** `Skill` 工具。skill 内容描述「动作」,在 Pi 上对应到小写工具:
36+
37+
- 「调用某个 skill」→ Pi 原生技能:用 `read` 加载对应 `SKILL.md`,或由人类显式 `/skill:name`
38+
- 「读/写/改文件」→ `read` / `write` / `edit`
39+
- 「跑 shell 命令」→ `bash`
40+
- 「搜索文件内容」→ `grep`,「按名找文件」→ `find`,「列目录」→ `ls`
41+
- 「分派子智能体」→ 若装了 `pi-subagents``subagent` 工具则用之;没有则在本会话内完成或说明能力缺失,**不要**臆造 `Task` 调用
42+
- 「待办清单」→ 若装了 todo/task 工具则用之;否则用 plan 文件或仓库内 `TODO.md` 跟踪;旧的 `TodoWrite` 引用按此处理
43+
44+
完整映射见 [`skills/using-superpowers/references/pi-tools.md`](../skills/using-superpowers/references/pi-tools.md),扩展也会把同样的映射注入会话。
45+
46+
## 验证
47+
48+
```bash
49+
bash tests/pi/run-tests.sh
50+
```
51+
52+
该测试动态加载扩展并校验:声明了 `pi` 包配置、注册了正确的生命周期钩子(且无 pre-compaction 注入)、`resources_discover` 贡献了 `skills/` 目录、`session_start` 注入了「You have superpowers」+「Pi tool mapping」、pi-tools 参考文档存在。
53+
54+
> 注:扩展是 TypeScript(仅 `import type`,运行时无类型依赖)。Node 22.6–23.5 需 `--experimental-strip-types`(run-tests.sh 已带),23.6+ 默认支持。

package.json

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
".codex-plugin/",
2727
".opencode/INSTALL.md",
2828
".opencode/plugins/",
29+
".pi/extensions/",
2930
"CLAUDE.md",
3031
"GEMINI.md",
3132
"RELEASE-NOTES.md",
@@ -62,8 +63,17 @@
6263
"中文",
6364
"tdd",
6465
"debugging",
65-
"code-review"
66+
"code-review",
67+
"pi-package"
6668
],
69+
"pi": {
70+
"skills": [
71+
"./skills"
72+
],
73+
"extensions": [
74+
"./.pi/extensions/superpowers.ts"
75+
]
76+
},
6777
"repository": {
6878
"type": "git",
6979
"url": "git+https://github.com/jnMetaCode/superpowers-zh.git"
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Pi Tool Mapping
2+
3+
Skills speak in actions ("dispatch a subagent", "create a todo", "read a file"). On Pi these resolve to the tools below.
4+
5+
| Action skills request | Pi equivalent |
6+
| --- | --- |
7+
| Invoke a skill | Pi native skills: load the relevant `SKILL.md` with `read`, or let the human use `/skill:name` |
8+
| Read a file | `read` |
9+
| Create a file | `write` |
10+
| Edit a file | `edit` |
11+
| Run a shell command | `bash` |
12+
| Search file contents | `grep` when active; otherwise `bash` with `rg`/`grep` |
13+
| Find files by name | `find` or `bash` with shell globs |
14+
| List files and subdirectories | `ls` when active; otherwise `bash` with `ls` |
15+
| Dispatch a subagent (`Subagent (general-purpose):` template) | Use an installed subagent tool such as `subagent` from `pi-subagents` if available |
16+
| Task tracking ("create a todo", "mark complete") | Use an installed todo/task tool if available, otherwise track tasks in the plan or `TODO.md` |
17+
18+
## Skills
19+
20+
Pi discovers skills from configured skill directories and installed Pi packages. A Superpowers Pi package should expose `skills/` through its `pi.skills` manifest entry. Pi does not expose Claude Code's `Skill` tool, but the agent should still follow the Superpowers rule: when a skill applies, load and follow it before responding.
21+
22+
## Subagents
23+
24+
Pi core does not ship a standard subagent tool. The `pi-subagents` package is a strong optional companion and provides a `subagent` tool with single-agent, chain, parallel, async, forked-context, and resume/status workflows. If no subagent tool is available, do not fabricate `Task` calls; execute sequentially in the current session or explain that the optional subagent capability is not installed.
25+
26+
## Task lists
27+
28+
Pi core does not ship a standard task-list tool. If a todo/task extension is installed, use its documented tool. Otherwise use Superpowers plan files, checklists in Markdown, or a repo-local `TODO.md` for task tracking. Older Superpowers docs may refer to `TodoWrite`; treat that as the task-tracking action above.

tests/pi/run-tests.sh

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
4+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
5+
6+
# 扩展是 TypeScript(仅 `import type`,运行时无类型依赖)。Node 22.6–23.5
7+
# 需要 --experimental-strip-types 才能 import .ts;23.6+ 默认开启,该 flag 仍兼容。
8+
node --experimental-strip-types "$SCRIPT_DIR/test-pi-extension.mjs"

tests/pi/test-pi-extension.mjs

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import assert from 'node:assert/strict';
2+
import { readFile } from 'node:fs/promises';
3+
import { existsSync } from 'node:fs';
4+
import { dirname, resolve } from 'node:path';
5+
import { fileURLToPath, pathToFileURL } from 'node:url';
6+
import test from 'node:test';
7+
8+
const __dirname = dirname(fileURLToPath(import.meta.url));
9+
const repoRoot = resolve(__dirname, '../..');
10+
const packageJsonPath = resolve(repoRoot, 'package.json');
11+
const extensionPath = resolve(repoRoot, '.pi/extensions/superpowers.ts');
12+
const piToolsPath = resolve(repoRoot, 'skills/using-superpowers/references/pi-tools.md');
13+
14+
async function readPackageJson() {
15+
return JSON.parse(await readFile(packageJsonPath, 'utf8'));
16+
}
17+
18+
async function loadExtension() {
19+
const handlers = new Map();
20+
const pi = {
21+
on(event, handler) {
22+
if (!handlers.has(event)) handlers.set(event, []);
23+
handlers.get(event).push(handler);
24+
},
25+
};
26+
const mod = await import(pathToFileURL(extensionPath).href + `?cachebust=${Date.now()}-${Math.random()}`);
27+
mod.default(pi);
28+
return { handlers };
29+
}
30+
31+
function firstHandler(handlers, event) {
32+
const eventHandlers = handlers.get(event) ?? [];
33+
assert.equal(eventHandlers.length, 1, `expected one ${event} handler`);
34+
return eventHandlers[0];
35+
}
36+
37+
function textOf(message) {
38+
if (typeof message.content === 'string') return message.content;
39+
return message.content
40+
.filter((part) => part.type === 'text')
41+
.map((part) => part.text)
42+
.join('\n');
43+
}
44+
45+
test('package.json declares a pi package with skills and extension resources', async () => {
46+
const pkg = await readPackageJson();
47+
48+
assert.equal(pkg.name, 'superpowers-zh');
49+
assert.ok(pkg.keywords.includes('pi-package'));
50+
assert.deepEqual(pkg.pi.skills, ['./skills']);
51+
assert.deepEqual(pkg.pi.extensions, ['./.pi/extensions/superpowers.ts']);
52+
});
53+
54+
test('extension registers lifecycle hooks without pre-compaction injection', async () => {
55+
const { handlers } = await loadExtension();
56+
57+
for (const event of ['resources_discover', 'session_start', 'session_compact', 'context', 'agent_end']) {
58+
assert.equal((handlers.get(event) ?? []).length, 1, `missing ${event} handler`);
59+
}
60+
assert.equal((handlers.get('session_before_compact') ?? []).length, 0);
61+
});
62+
63+
test('resources_discover contributes the bundled skills directory', async () => {
64+
const { handlers } = await loadExtension();
65+
const discover = firstHandler(handlers, 'resources_discover');
66+
67+
const result = await discover({ type: 'resources_discover', cwd: repoRoot, reason: 'startup' }, {});
68+
69+
assert.deepEqual(result.skillPaths, [resolve(repoRoot, 'skills')]);
70+
});
71+
72+
test('startup context injects the bootstrap as one user message until agent_end', async () => {
73+
const { handlers } = await loadExtension();
74+
const sessionStart = firstHandler(handlers, 'session_start');
75+
const context = firstHandler(handlers, 'context');
76+
const agentEnd = firstHandler(handlers, 'agent_end');
77+
78+
await sessionStart({ type: 'session_start', reason: 'startup' }, {});
79+
80+
const originalMessages = [
81+
{ role: 'user', content: [{ type: 'text', text: 'Let us make a react todo list' }], timestamp: 1 },
82+
];
83+
const result = await context({ type: 'context', messages: originalMessages }, {});
84+
85+
assert.equal(result.messages.length, 2);
86+
assert.equal(result.messages[0].role, 'user');
87+
assert.match(textOf(result.messages[0]), /You have superpowers/);
88+
assert.match(textOf(result.messages[0]), /Pi tool mapping/);
89+
assert.equal(result.messages[1], originalMessages[0]);
90+
91+
const repeatedProviderRequest = await context({ type: 'context', messages: originalMessages }, {});
92+
assert.equal(repeatedProviderRequest.messages.length, 2);
93+
assert.match(textOf(repeatedProviderRequest.messages[0]), /You have superpowers/);
94+
95+
const alreadyInjected = await context({ type: 'context', messages: result.messages }, {});
96+
assert.equal(alreadyInjected, undefined, 'bootstrap should not duplicate when already present');
97+
98+
await agentEnd({ type: 'agent_end', messages: [] }, {});
99+
const afterEnd = await context({ type: 'context', messages: originalMessages }, {});
100+
assert.equal(afterEnd, undefined, 'startup bootstrap should clear after agent_end');
101+
});
102+
103+
test('session_compact injects bootstrap after compaction summaries, not before compaction', async () => {
104+
const { handlers } = await loadExtension();
105+
const sessionCompact = firstHandler(handlers, 'session_compact');
106+
const context = firstHandler(handlers, 'context');
107+
108+
await sessionCompact({ type: 'session_compact', compactionEntry: {}, fromExtension: false }, {});
109+
110+
const summary = { role: 'compactionSummary', summary: 'Prior work summary', tokensBefore: 123, timestamp: 1 };
111+
const user = { role: 'user', content: [{ type: 'text', text: 'Continue' }], timestamp: 2 };
112+
const result = await context({ type: 'context', messages: [summary, user] }, {});
113+
114+
assert.equal(result.messages.length, 3);
115+
assert.equal(result.messages[0], summary);
116+
assert.equal(result.messages[1].role, 'user');
117+
assert.match(textOf(result.messages[1]), /You have superpowers/);
118+
assert.equal(result.messages[2], user);
119+
});
120+
121+
test('pi tools reference documents pi-specific mappings', async () => {
122+
assert.equal(existsSync(piToolsPath), true, 'pi-tools.md should exist');
123+
const text = await readFile(piToolsPath, 'utf8');
124+
125+
for (const expected of ['Skill', 'Task', 'TodoWrite', 'read', 'write', 'edit', 'bash']) {
126+
assert.match(text, new RegExp(expected));
127+
}
128+
});

0 commit comments

Comments
 (0)