pi-scenes 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +113 -6
- package/extensions/scenes.ts +696 -14
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# pi-scenes
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/pi-scenes)
|
|
4
|
+
[](https://www.npmjs.com/package/pi-scenes)
|
|
4
5
|
[](https://opensource.org/licenses/MIT)
|
|
5
6
|
[](https://pi.dev/packages)
|
|
6
7
|
|
|
@@ -44,9 +45,24 @@ Then `/reload` and `/scene` is live.
|
|
|
44
45
|
/scene off # common layer only (scene off)
|
|
45
46
|
/scene status # show active scene + effective packages/skills
|
|
46
47
|
/scene init # scaffold scenes.json template + scene skill dirs
|
|
48
|
+
/scene stats # usage dashboard: sessions, tool calls, reflections
|
|
49
|
+
/scene evolve # generate & apply evolution proposals (confirm-first)
|
|
50
|
+
/scene evolve auto # toggle auto-apply at session end (opt-in)
|
|
47
51
|
```
|
|
48
52
|
|
|
49
|
-
First run of `/scene` offers to generate the template.
|
|
53
|
+
First run of `/scene` offers to generate the template. It ships with **seven preset scenes + common** (all packages verified on npm, 2026-09):
|
|
54
|
+
|
|
55
|
+
| Layer | Preset packages | Why |
|
|
56
|
+
|---|---|---|
|
|
57
|
+
| `common` | `npm:pi-scenes`, `npm:pi-carryover` | the switcher itself + cross-session carryover — always needed |
|
|
58
|
+
| `coding` | `npm:pi-lens`, `npm:pi-subagents`, `npm:pi-git-worktree` | live LSP/lint feedback, delegated sub-agents, parallel worktrees |
|
|
59
|
+
| `office` | `npm:pi-docparser` | PDF/Office document parsing |
|
|
60
|
+
| `pm` | `npm:pi-web-access`, `npm:pi-goal-x`, `npm:@juicesharp/rpiv-todo` | market/competitor research, goal planning & audit, live todo overlay |
|
|
61
|
+
| `research` | `npm:pi-web-access`, `npm:pi-subagents` | multi-source search/fetch/PDF/video, parallel multi-angle digging |
|
|
62
|
+
| `writing` | `npm:pi-web-access` | source gathering & fact-checking with citations |
|
|
63
|
+
| `data` | `npm:pi-docparser`, `npm:pi-mcp-adapter` | table extraction, connect any MCP server (DB/BI) |
|
|
64
|
+
|
|
65
|
+
Edit it to fit your setup (each scene also gets a skill dir scaffold at `~/.pi/agent/scenes/<name>/skills/`):
|
|
50
66
|
|
|
51
67
|
```jsonc
|
|
52
68
|
// ~/.pi/agent/scenes.json
|
|
@@ -73,7 +89,44 @@ First run of `/scene` offers to generate the template. Edit it to fit your setup
|
|
|
73
89
|
}
|
|
74
90
|
```
|
|
75
91
|
|
|
76
|
-
Drop `SKILL.md` folders (or `.md` files) into a scene's skill directory; the whole directory toggles with the scene. `/scene init` scaffolds `~/.pi/agent/scenes/{common,coding,office}/skills/`.
|
|
92
|
+
Drop `SKILL.md` folders (or `.md` files) into a scene's skill directory; the whole directory toggles with the scene. `/scene init` scaffolds `~/.pi/agent/scenes/{common,coding,office,pm,research,writing,data}/skills/`.
|
|
93
|
+
|
|
94
|
+
## Self-evolution (usage-driven)
|
|
95
|
+
|
|
96
|
+
Scenes are not static. pi-scenes observes what you actually use and proposes updates:
|
|
97
|
+
|
|
98
|
+
- **Collect (passive)** — every `tool_call` is attributed to its package (via a static scan of installed sources); packages present in settings but absent from every scene definition are tracked as *absorb candidates*; at each session end a tiny LLM call reflects on which loaded skills were actually useful (a few hundred tokens, 30s timeout, fails silently).
|
|
99
|
+
- **Propose** — `/scene evolve` generates proposals:
|
|
100
|
+
- **absorb**: an unmanaged package seen in ≥2 sessions joins the scene it was observed in
|
|
101
|
+
- **retire**: a scene package with zero calls for 20 consecutive sessions (and a tool signal — command-only packages are protected) is proposed for removal; a skill the LLM never found useful (5+ "unused" reflections, 0 "useful") likewise
|
|
102
|
+
- **protected**: the `common` layer and packages without tool signals (e.g. `/anywhere`-style command-only extensions) are **never** auto-changed
|
|
103
|
+
- **Apply (confirm-first)** — each proposal shows a `scenes.json` diff and asks; accepted edits are backed up (`scenes.json.scenes-bak`) and hot-reloaded. `/scene evolve auto` opts into silent application at session end (changes take effect on the next natural reload).
|
|
104
|
+
|
|
105
|
+
Tunables live in `scenes.json`:
|
|
106
|
+
|
|
107
|
+
```jsonc
|
|
108
|
+
{
|
|
109
|
+
"evolve": {
|
|
110
|
+
"patience": 20, // sessions of zero usage before retire
|
|
111
|
+
"absorbThreshold": 2, // unmanaged sightings before absorb
|
|
112
|
+
"skillUnusedThreshold": 5 // "unused" reflections before skill retire
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Usage data: `~/.pi/agent/scenes-usage.json` (machine-local, inert). View anytime with `/scene stats`.
|
|
118
|
+
|
|
119
|
+
### Install ≠ load (two-layer model)
|
|
120
|
+
|
|
121
|
+
- **Loading is driven by `settings.json` only.** Switching = rewrite the `packages`/`skills` arrays + `ctx.reload()`; resources absent from the arrays are never loaded — no tools registered, no prompt tokens spent. Scene skill dirs (`~/.pi/agent/scenes/<name>/skills`) are not auto-discovered by pi, so they toggle with the scene.
|
|
122
|
+
- **Files stay on disk.** Switching away never uninstalls (`pi remove` for that); a switched-away package under `~/.pi/agent/npm/` is an inert file — instant switch-back, zero runtime cost.
|
|
123
|
+
|
|
124
|
+
In short: **installed forever, loaded per scene**. One caveat: extensions you installed manually (your own entries in settings) are yours — pi-scenes treats them as `borrowed`, never touches them, so they stay loaded in *every* scene.
|
|
125
|
+
|
|
126
|
+
### Duplicate & conflict handling
|
|
127
|
+
|
|
128
|
+
- Same spec in `common` and a scene → deduplicated at the union (loaded once).
|
|
129
|
+
- Same package, different spellings (e.g. `npm:x@1.0.3` vs bare `npm:x`) → identity-level dedupe keeps the first (common > scene); a manually pinned variant in settings is treated as `borrowed` (no duplicate injection). `/scene` and `/scene status` warn about such spelling mismatches so you can unify them.
|
|
77
130
|
|
|
78
131
|
## How it works
|
|
79
132
|
|
|
@@ -101,6 +154,7 @@ Drop `SKILL.md` folders (or `.md` files) into a scene's skill directory; the who
|
|
|
101
154
|
| `scenes.<name>.packages` | accepts `"npm:<pkg>"`, `"git:github.com/u/r"`, local paths, and object form (resource filtering, same grammar as pi settings) |
|
|
102
155
|
| `scenes.<name>.skills` | paths/directories, `~` expanded |
|
|
103
156
|
| `scenes.<name>.extends` | 🧪 inherit a parent scene (union merge + cycle detection) — forward-compatible entry for parent→child hierarchies |
|
|
157
|
+
| `evolve.patience` / `evolve.absorbThreshold` / `evolve.skillUnusedThreshold` | self-evolution tunables (see "Self-evolution") |
|
|
104
158
|
|
|
105
159
|
## Rollback
|
|
106
160
|
|
|
@@ -115,7 +169,7 @@ Before uninstalling, `/scene off` and prune entries you don't want to keep from
|
|
|
115
169
|
|
|
116
170
|
```bash
|
|
117
171
|
git clone https://github.com/Feng-H/pi-scenes && cd pi-scenes
|
|
118
|
-
npm test # node:test,
|
|
172
|
+
npm test # node:test, 14 cases: injection/reclaim + usage/evolution + conflict guards (no TUI needed)
|
|
119
173
|
```
|
|
120
174
|
|
|
121
175
|
Tests isolate via the `PI_SCENES_DIR` env var — your real `~/.pi/agent` is never touched.
|
|
@@ -170,9 +224,24 @@ pi install git:github.com/Feng-H/pi-scenes
|
|
|
170
224
|
/scene off # 仅保留通用层(关闭场景)
|
|
171
225
|
/scene status # 查看当前激活 + 生效的 packages/skills 清单
|
|
172
226
|
/scene init # 生成模板 scenes.json + 场景 skill 目录骨架
|
|
227
|
+
/scene stats # 用量仪表盘:会话数 / 工具调用 / 反思评分
|
|
228
|
+
/scene evolve # 生成并应用进化提案(逐条确认)
|
|
229
|
+
/scene evolve auto # 开关:会话结束自动应用(opt-in)
|
|
173
230
|
```
|
|
174
231
|
|
|
175
|
-
首次运行 `/scene`
|
|
232
|
+
首次运行 `/scene` 会询问是否生成模板,生成后编辑场景定义。模板内置 **七个预设场景 + 通用层**(包均在 npm 核验存在,2026-09):
|
|
233
|
+
|
|
234
|
+
| 层 | 预设 packages | 理由 |
|
|
235
|
+
|---|---|---|
|
|
236
|
+
| `common` | `npm:pi-scenes`、`npm:pi-carryover` | 切换器自身 + 跨会话承接,恒需 |
|
|
237
|
+
| `coding` | `npm:pi-lens`、`npm:pi-subagents`、`npm:pi-git-worktree` | LSP/lint 实时反馈、子代理委派、worktree 并行开发 |
|
|
238
|
+
| `office` | `npm:pi-docparser` | PDF/Office 文档解析 |
|
|
239
|
+
| `pm` | `npm:pi-web-access`、`npm:pi-goal-x`、`npm:@juicesharp/rpiv-todo` | 竞品/市场调研、目标规划与完成度审计、需求/任务清单 overlay |
|
|
240
|
+
| `research` | `npm:pi-web-access`、`npm:pi-subagents` | 多源搜索/抓取/PDF/视频,并行多角度深挖 |
|
|
241
|
+
| `writing` | `npm:pi-web-access` | 素材检索与事实核查(引用溯源) |
|
|
242
|
+
| `data` | `npm:pi-docparser`、`npm:pi-mcp-adapter` | 表格结构化抽取、接任意 MCP server(数据库/BI) |
|
|
243
|
+
|
|
244
|
+
每个场景同时生成 skill 目录骨架 `~/.pi/agent/scenes/<名>/skills/`,按需编辑:
|
|
176
245
|
|
|
177
246
|
```jsonc
|
|
178
247
|
// ~/.pi/agent/scenes.json
|
|
@@ -200,7 +269,44 @@ pi install git:github.com/Feng-H/pi-scenes
|
|
|
200
269
|
```
|
|
201
270
|
|
|
202
271
|
场景 skill 目录里放 `SKILL.md` 文件夹(或 `.md` 文件)即可,切换场景时整目录启停。
|
|
203
|
-
`/scene init` 会创建 `~/.pi/agent/scenes/{common,coding,office}/skills/` 骨架。
|
|
272
|
+
`/scene init` 会创建 `~/.pi/agent/scenes/{common,coding,office,pm,research,writing,data}/skills/` 骨架。
|
|
273
|
+
|
|
274
|
+
## 自进化(用量驱动)
|
|
275
|
+
|
|
276
|
+
场景不是静态的。pi-scenes 观察你的实际使用并提议更新:
|
|
277
|
+
|
|
278
|
+
- **采集(被动,零感知)**——每次 `tool_call` 通过静态扫描安装源码归因到包;settings 里存在但不在任何场景定义的包记为*吸收候选*;每个会话结束用一次小 LLM 调用反思哪些已加载 skill 真正有用(几百 token、30s 超时、失败静默)。
|
|
279
|
+
- **提案**——`/scene evolve` 生成提案:
|
|
280
|
+
- **吸收**:未纳管的包在 ≥2 个会话中出现 → 提议加入观察到的场景
|
|
281
|
+
- **淘汰**:场景包连续 20 个会话零调用(且必须有过工具信号——纯命令包受保护)→ 提议移出;skill 反思 5 次以上「未用到」且 0 次「有用」→ 提议移出
|
|
282
|
+
- **保护**:`common` 通用层与无工具信号的包(如只有 `/anywhere` 命令的扩展)**永不被自动变更**,只能用户手动改
|
|
283
|
+
- **应用(确认优先)**——每条提案展示 `scenes.json` diff 并逐条确认;接受后自动备份(`scenes.json.scenes-bak`)并热重载。`/scene evolve auto` 开启会话结束静默应用(下次自然重载生效)。
|
|
284
|
+
|
|
285
|
+
阈值在 `scenes.json` 可调:
|
|
286
|
+
|
|
287
|
+
```jsonc
|
|
288
|
+
{
|
|
289
|
+
"evolve": {
|
|
290
|
+
"patience": 20, // 连续零调用会话数 → 淘汰
|
|
291
|
+
"absorbThreshold": 2, // 未纳管出现次数 → 吸收
|
|
292
|
+
"skillUnusedThreshold": 5 // skill 反思未用到次数 → 淘汰
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
用量数据:`~/.pi/agent/scenes-usage.json`(本机局部、惰性)。随时 `/scene stats` 查看。
|
|
298
|
+
|
|
299
|
+
### 安装 ≠ 加载(两层模型)
|
|
300
|
+
|
|
301
|
+
- **加载只看 settings.json。** 切换 = 改写 packages/skills 数组 + `ctx.reload()`;不在数组里的资源不会被加载——不注册工具、不占 prompt token。场景 skill 目录(`~/.pi/agent/scenes/<名>/skills`)不是 pi 自动发现路径,天然随场景启停。
|
|
302
|
+
- **磁盘文件保留。** 切走不卸载(彻底清理用 `pi remove`);不在 settings 里的包只是惰性文件——切回秒级,零运行时成本。
|
|
303
|
+
|
|
304
|
+
一句话:**永远安装,只按场景加载**。注意:你手工 `pi install` 的条目属于你自己——pi-scenes 视为 `borrowed`,永不触碰,因此在**所有**场景都保持加载。
|
|
305
|
+
|
|
306
|
+
### 重复与冲突处理
|
|
307
|
+
|
|
308
|
+
- 同一写法在 common 与场景重复 → 并集时去重,只加载一次。
|
|
309
|
+
- 同包异写法(如 `npm:x@1.0.3` 与裸名 `npm:x`)→ 身份级去重取首个(common 优先);settings 里手动 pin 的异写法条目视为 `borrowed`,不重复注入。`/scene` 切换与 `/scene status` 会对异写法发出提醒,建议统一。
|
|
204
310
|
|
|
205
311
|
## 工作原理
|
|
206
312
|
|
|
@@ -228,6 +334,7 @@ pi install git:github.com/Feng-H/pi-scenes
|
|
|
228
334
|
| `scenes.<name>.packages` | 支持 `"npm:<pkg>"`、`"git:github.com/u/r"`、本地路径字符串,及 object form(资源过滤,同 pi settings 规范) |
|
|
229
335
|
| `scenes.<name>.skills` | 路径/目录数组,支持 `~` 展开 |
|
|
230
336
|
| `scenes.<name>.extends` | 🧪 继承父场景(union 合并,带环检测)——「主场景→子场景」层级的前向兼容入口 |
|
|
337
|
+
| `evolve.patience` / `evolve.absorbThreshold` / `evolve.skillUnusedThreshold` | 自进化阈值(见「自进化」节) |
|
|
231
338
|
|
|
232
339
|
## 回退方案
|
|
233
340
|
|
|
@@ -242,7 +349,7 @@ managed 注入的条目在卸载前建议先 `/scene off` + 手工清理 `packag
|
|
|
242
349
|
|
|
243
350
|
```bash
|
|
244
351
|
git clone https://github.com/Feng-H/pi-scenes && cd pi-scenes
|
|
245
|
-
npm test # node:test
|
|
352
|
+
npm test # node:test,14 用例:注入/回收 + 用量/进化 + 异写法冲突防护(无需 TUI)
|
|
246
353
|
```
|
|
247
354
|
|
|
248
355
|
测试用 `PI_SCENES_DIR` 环境变量隔离基目录,不碰真实 `~/.pi/agent`。
|
package/extensions/scenes.ts
CHANGED
|
@@ -24,10 +24,20 @@
|
|
|
24
24
|
* /scene off|none 仅保留通用层(关闭场景)
|
|
25
25
|
* /scene status 显示当前激活与生效资源
|
|
26
26
|
* /scene init 生成模板 scenes.json 与场景 skill 目录骨架
|
|
27
|
+
* /scene stats 用量仪表盘(会话数/工具调用/反思评分/未纳管观察)
|
|
28
|
+
* /scene evolve 生成进化提案并逐条确认应用(备份 + 热重载)
|
|
29
|
+
* /scene evolve auto 开关:会话结束自动应用进化(opt-in,不动 common/无工具包)
|
|
30
|
+
*
|
|
31
|
+
* 自进化(v0.2):
|
|
32
|
+
* 采集:tool_call 归因(静态扫描安装源码建 tool→pkg 表)+
|
|
33
|
+
* settings 未纳管条目观察 + 会话结束 LLM 反思 skill 有用性
|
|
34
|
+
* 提案:吸收(未纳管 ≥2 次)→ 淘汰(连续 20 会话零调用且有过工具信号)
|
|
35
|
+
* 保护:common 层与无工具信号的包(command-only)永不自动变更
|
|
27
36
|
*
|
|
28
37
|
* 文件:
|
|
29
|
-
* ~/.pi/agent/scenes.json
|
|
38
|
+
* ~/.pi/agent/scenes.json 场景定义(用户编辑;含 evolve 阈值配置)
|
|
30
39
|
* ~/.pi/agent/scenes-state.json 激活状态 + managed 追踪(本扩展维护)
|
|
40
|
+
* ~/.pi/agent/scenes-usage.json 用量记账与自进化数据(本扩展维护)
|
|
31
41
|
* ~/.pi/agent/settings.json pi 全局设置(仅动 packages/skills 两个数组)
|
|
32
42
|
* ~/.pi/agent/scenes/<名>/skills 各场景专属 skill 目录(约定,可自由改路径)
|
|
33
43
|
*
|
|
@@ -54,11 +64,44 @@ export interface SceneDef {
|
|
|
54
64
|
skills?: string[];
|
|
55
65
|
}
|
|
56
66
|
|
|
67
|
+
export interface EvolveConfig {
|
|
68
|
+
/** 连续多少个会话零调用后提议淘汰(默认 20) */
|
|
69
|
+
patience?: number;
|
|
70
|
+
/** 未纳管条目出现多少次后提议吸收(默认 2) */
|
|
71
|
+
absorbThreshold?: number;
|
|
72
|
+
/** skill 反思多少次「未用到」后提议淘汰(默认 5) */
|
|
73
|
+
skillUnusedThreshold?: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
57
76
|
export interface ScenesFile {
|
|
58
77
|
common?: SceneDef;
|
|
59
78
|
scenes?: Record<string, SceneDef>;
|
|
79
|
+
/** 自进化配置(v0.2) */
|
|
80
|
+
evolve?: EvolveConfig;
|
|
60
81
|
}
|
|
61
82
|
|
|
83
|
+
export interface ResourceUsage {
|
|
84
|
+
toolCalls?: number;
|
|
85
|
+
lastUsed?: string;
|
|
86
|
+
sessionsSeen?: number;
|
|
87
|
+
absentStreak?: number;
|
|
88
|
+
reflections?: { useful: number; unused: number };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface UsageFile {
|
|
92
|
+
autoEvolve?: boolean;
|
|
93
|
+
perScene: Record<string, { sessions: number; lastActive: string }>;
|
|
94
|
+
perResource: Record<string, ResourceUsage>;
|
|
95
|
+
/** 在 settings 中出现但不在任何场景定义的条目(吸收候选) */
|
|
96
|
+
unmanagedSeen: Record<string, { count: number; lastSeen: string; scenes: string[] }>;
|
|
97
|
+
/** 当前会话记账(跨 reload 存续):seen = 本会话用过的资源 key */
|
|
98
|
+
_current?: { file: string; scene: string | null; seen: string[] };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type Proposal =
|
|
102
|
+
| { kind: "absorb"; scene: string; entry: PackageEntry; reason: string }
|
|
103
|
+
| { kind: "retire"; scene: string; key: string; label: string; skillPath?: string; reason: string };
|
|
104
|
+
|
|
62
105
|
export interface SceneState {
|
|
63
106
|
/** 当前激活场景名;null = 仅通用层 */
|
|
64
107
|
active: string | null;
|
|
@@ -102,6 +145,192 @@ function removeFrom<T>(arr: T[] | undefined, targets: T[]): T[] {
|
|
|
102
145
|
return arr.filter((item) => !targets.some((t) => sameEntry(item, t)));
|
|
103
146
|
}
|
|
104
147
|
|
|
148
|
+
function specOf(e: PackageEntry): string {
|
|
149
|
+
return typeof e === "string" ? e : e.source;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 包条目的身份候选(用于工具归因匹配) */
|
|
153
|
+
function packageIdentity(entry: PackageEntry): string[] {
|
|
154
|
+
const spec = typeof entry === "string" ? entry : entry?.source ?? "";
|
|
155
|
+
if (!spec) return [];
|
|
156
|
+
const loc = specLocation(spec);
|
|
157
|
+
if (loc.kind === "npm" && loc.npmName) return [loc.npmName];
|
|
158
|
+
if (loc.kind === "git" && loc.gitDir) return [path.basename(loc.gitDir)];
|
|
159
|
+
if (loc.kind === "local" && loc.localPath) return [path.basename(expandHome(loc.localPath))];
|
|
160
|
+
return [];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** skill 名:SKILL.md frontmatter name → 一级标题 → 文件名 */
|
|
164
|
+
/** 身份级判等:同一包的不同写法(裸名 vs @版本 pin)视为同一资源 */
|
|
165
|
+
function sameResource(a: PackageEntry, b: PackageEntry): boolean {
|
|
166
|
+
if (sameEntry(a, b)) return true;
|
|
167
|
+
const ia = packageIdentity(a);
|
|
168
|
+
const ib = packageIdentity(b);
|
|
169
|
+
return ia.length > 0 && ia.some((x) => ib.includes(x));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 身份级去重(keep-first:common 优先于场景、子场景优先于父场景) */
|
|
173
|
+
function dedupeByIdentity(entries: PackageEntry[]): PackageEntry[] {
|
|
174
|
+
const out: PackageEntry[] = [];
|
|
175
|
+
for (const e of entries) if (!out.some((x) => sameResource(x, e))) out.push(e);
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function skillNameOf(file: string): string {
|
|
180
|
+
try {
|
|
181
|
+
const head = fs.readFileSync(file, "utf8").slice(0, 4000);
|
|
182
|
+
const m = head.match(/^name:\s*["']?([^"'\n#]+?)["']?\s*$/m);
|
|
183
|
+
if (m) return m[1].trim();
|
|
184
|
+
const t = head.match(/^#\s+(.+)$/m);
|
|
185
|
+
if (t) return t[1].trim();
|
|
186
|
+
} catch {}
|
|
187
|
+
return path.basename(file).replace(/\.md$/i, "");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** 展开场景 skill 条目为单个 skill 清单(目录→子 SKILL.md / .md 文件) */
|
|
191
|
+
function listSkillChildren(skillPaths: string[]): { id: string; label: string }[] {
|
|
192
|
+
const out: { id: string; label: string }[] = [];
|
|
193
|
+
for (const p of skillPaths) {
|
|
194
|
+
let stt: fs.Stats;
|
|
195
|
+
try {
|
|
196
|
+
stt = fs.statSync(p);
|
|
197
|
+
} catch {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (stt.isFile()) {
|
|
201
|
+
if (/\.md$/i.test(p)) out.push({ id: p, label: skillNameOf(p) });
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
let ents: fs.Dirent[];
|
|
205
|
+
try {
|
|
206
|
+
ents = fs.readdirSync(p, { withFileTypes: true });
|
|
207
|
+
} catch {
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
for (const e of ents) {
|
|
211
|
+
if (e.isDirectory()) {
|
|
212
|
+
const sk = path.join(p, e.name, "SKILL.md");
|
|
213
|
+
if (fs.existsSync(sk)) out.push({ id: sk, label: skillNameOf(sk) });
|
|
214
|
+
} else if (/\.md$/i.test(e.name) && !/^SKILL\.md$/i.test(e.name)) {
|
|
215
|
+
out.push({ id: path.join(p, e.name), label: skillNameOf(path.join(p, e.name)) });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function extractText(resp: unknown): string {
|
|
223
|
+
const r = resp as any;
|
|
224
|
+
const c = r?.choices?.[0]?.message?.content ?? r?.content ?? r?.text ?? "";
|
|
225
|
+
if (typeof c === "string") return c;
|
|
226
|
+
if (Array.isArray(c)) return c.filter((x: any) => x?.type === "text").map((x: any) => x.text).join("");
|
|
227
|
+
return "";
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function parseJsonLoose(text: string): any | null {
|
|
231
|
+
const stripped = text.replace(/```(?:json)?/g, "");
|
|
232
|
+
const start = stripped.indexOf("{");
|
|
233
|
+
const end = stripped.lastIndexOf("}");
|
|
234
|
+
if (start < 0 || end <= start) return null;
|
|
235
|
+
try {
|
|
236
|
+
return JSON.parse(stripped.slice(start, end + 1));
|
|
237
|
+
} catch {
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** 递归收集 JS/TS 源文件(限量,避免大包扫描过久) */
|
|
243
|
+
function collectJsFiles(root: string, out: string[], budget: { n: number }): void {
|
|
244
|
+
if (budget.n <= 0) return;
|
|
245
|
+
let ents: fs.Dirent[];
|
|
246
|
+
try {
|
|
247
|
+
ents = fs.readdirSync(root, { withFileTypes: true });
|
|
248
|
+
} catch {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const subdirs: string[] = [];
|
|
252
|
+
for (const e of ents) {
|
|
253
|
+
if (budget.n <= 0) return;
|
|
254
|
+
if (e.isFile() && /\.(ts|js|mjs|cjs)$/.test(e.name)) {
|
|
255
|
+
out.push(path.join(root, e.name));
|
|
256
|
+
budget.n -= 1;
|
|
257
|
+
} else if (e.isDirectory() && !["node_modules", ".git"].includes(e.name)) {
|
|
258
|
+
subdirs.push(path.join(root, e.name));
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
for (const d of subdirs) {
|
|
262
|
+
collectJsFiles(d, out, budget);
|
|
263
|
+
if (budget.n <= 0) return;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* 进化提案(纯函数):
|
|
269
|
+
* - 吸收:unmanaged 条目出现 ≥ absorbThreshold 次 → 提议加入观察到的场景
|
|
270
|
+
* - 淘汰:场景层包 absentStreak ≥ patience 且有工具信号(toolCalls>0 或归因表有工具)→ 提议移出
|
|
271
|
+
* - 保护:common 层永不淘汰;无任何工具信号的包(command-only,如 pi-anywhere)永不淘汰
|
|
272
|
+
* - skill:反思 useful==0 且 unused ≥ skillUnusedThreshold → 提议移出
|
|
273
|
+
*/
|
|
274
|
+
export function computeProposals(
|
|
275
|
+
cfg: ScenesFile,
|
|
276
|
+
usage: UsageFile,
|
|
277
|
+
opts: { patience?: number; absorbThreshold?: number; skillUnusedThreshold?: number; hasTools?: Set<string> } = {},
|
|
278
|
+
): Proposal[] {
|
|
279
|
+
const patience = opts.patience ?? cfg.evolve?.patience ?? 20;
|
|
280
|
+
const absorbThreshold = opts.absorbThreshold ?? cfg.evolve?.absorbThreshold ?? 2;
|
|
281
|
+
const skillUnused = opts.skillUnusedThreshold ?? cfg.evolve?.skillUnusedThreshold ?? 5;
|
|
282
|
+
const proposals: Proposal[] = [];
|
|
283
|
+
|
|
284
|
+
for (const [key, u] of Object.entries(usage.unmanagedSeen ?? {})) {
|
|
285
|
+
if (u.count < absorbThreshold) continue;
|
|
286
|
+
const scene = u.scenes[u.scenes.length - 1];
|
|
287
|
+
if (!scene || !cfg.scenes?.[scene]) continue;
|
|
288
|
+
let entry: PackageEntry;
|
|
289
|
+
try {
|
|
290
|
+
entry = JSON.parse(key) as PackageEntry;
|
|
291
|
+
} catch {
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
proposals.push({ kind: "absorb", scene, entry, reason: `${u.count} 个会话在场但不在任何场景定义` });
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
for (const [scene, def] of Object.entries(cfg.scenes ?? {})) {
|
|
298
|
+
for (const e of def.packages ?? []) {
|
|
299
|
+
const key = canonical(e);
|
|
300
|
+
const r = usage.perResource?.[key];
|
|
301
|
+
const signalCapable = (r?.toolCalls ?? 0) > 0 || opts.hasTools?.has(key);
|
|
302
|
+
if (!r || !signalCapable) continue;
|
|
303
|
+
if ((r.absentStreak ?? 0) >= patience) {
|
|
304
|
+
proposals.push({ kind: "retire", scene, key, label: specOf(e), reason: `连续 ${r.absentStreak} 个会话零调用(累计 ${r.toolCalls ?? 0} 次)` });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
for (const p of def.skills ?? []) {
|
|
308
|
+
const rl = usage.perResource?.[expandHome(p)]?.reflections;
|
|
309
|
+
if (!rl || rl.useful > 0 || rl.unused < skillUnused) continue;
|
|
310
|
+
proposals.push({ kind: "retire", scene, key: expandHome(p), label: p, skillPath: p, reason: `反思 ${rl.unused} 次均未用到` });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return proposals;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** 应用提案(纯函数):返回新 cfg,不改原对象 */
|
|
317
|
+
export function applyProposals(cfg: ScenesFile, proposals: Proposal[]): ScenesFile {
|
|
318
|
+
const next: ScenesFile = structuredClone(cfg);
|
|
319
|
+
next.scenes ??= {};
|
|
320
|
+
for (const p of proposals) {
|
|
321
|
+
const def = (next.scenes[p.scene] ??= {});
|
|
322
|
+
if (p.kind === "absorb") {
|
|
323
|
+
def.packages ??= [];
|
|
324
|
+
if (!def.packages.some((x) => sameEntry(x, p.entry))) def.packages.push(p.entry);
|
|
325
|
+
} else if (p.skillPath) {
|
|
326
|
+
def.skills = (def.skills ?? []).filter((s) => s !== p.skillPath);
|
|
327
|
+
} else {
|
|
328
|
+
def.packages = (def.packages ?? []).filter((e) => canonical(e) !== p.key);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return next;
|
|
332
|
+
}
|
|
333
|
+
|
|
105
334
|
function readJson<T>(file: string, fallback: T): T {
|
|
106
335
|
try {
|
|
107
336
|
return JSON.parse(fs.readFileSync(file, "utf8")) as T;
|
|
@@ -150,6 +379,7 @@ export interface CorePaths {
|
|
|
150
379
|
baseDir: string;
|
|
151
380
|
scenesFile: string;
|
|
152
381
|
stateFile: string;
|
|
382
|
+
usageFile: string;
|
|
153
383
|
settingsFile: string;
|
|
154
384
|
scenesRoot: string; // ~/.pi/agent/scenes(场景 skill 目录约定根)
|
|
155
385
|
npmDir: string; // ~/.pi/agent/npm
|
|
@@ -161,6 +391,7 @@ export function makeCore(baseDir: string) {
|
|
|
161
391
|
baseDir,
|
|
162
392
|
scenesFile: path.join(baseDir, "scenes.json"),
|
|
163
393
|
stateFile: path.join(baseDir, "scenes-state.json"),
|
|
394
|
+
usageFile: path.join(baseDir, "scenes-usage.json"),
|
|
164
395
|
settingsFile: path.join(baseDir, "settings.json"),
|
|
165
396
|
scenesRoot: path.join(baseDir, "scenes"),
|
|
166
397
|
npmDir: path.join(baseDir, "npm"),
|
|
@@ -190,6 +421,21 @@ export function makeCore(baseDir: string) {
|
|
|
190
421
|
writeJson(paths.stateFile, st);
|
|
191
422
|
}
|
|
192
423
|
|
|
424
|
+
function loadUsage(): UsageFile {
|
|
425
|
+
const u = readJson<Partial<UsageFile>>(paths.usageFile, {});
|
|
426
|
+
return {
|
|
427
|
+
autoEvolve: u.autoEvolve ?? false,
|
|
428
|
+
perScene: u.perScene ?? {},
|
|
429
|
+
perResource: u.perResource ?? {},
|
|
430
|
+
unmanagedSeen: u.unmanagedSeen ?? {},
|
|
431
|
+
_current: u._current,
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function saveUsage(usage: UsageFile): void {
|
|
436
|
+
writeJson(paths.usageFile, usage);
|
|
437
|
+
}
|
|
438
|
+
|
|
193
439
|
/** 解析场景(沿 extends 链 union 合并,带环检测)——主场景/子场景的落点 */
|
|
194
440
|
function resolveScene(name: string, cfg: ScenesFile): SceneDef {
|
|
195
441
|
const merged: SceneDef = { packages: [], skills: [] };
|
|
@@ -219,7 +465,7 @@ export function makeCore(baseDir: string) {
|
|
|
219
465
|
const common = cfg.common ?? {};
|
|
220
466
|
let scene: SceneDef = {};
|
|
221
467
|
if (active) scene = resolveScene(active, cfg);
|
|
222
|
-
const packages = dedupeEntries([...(common.packages ?? []), ...(scene.packages ?? [])]);
|
|
468
|
+
const packages = dedupeByIdentity(dedupeEntries([...(common.packages ?? []), ...(scene.packages ?? [])]));
|
|
223
469
|
const skills = [...new Set([...(common.skills ?? []), ...(scene.skills ?? [])].map(expandHome))];
|
|
224
470
|
return { packages, skills };
|
|
225
471
|
}
|
|
@@ -279,6 +525,9 @@ export function makeCore(baseDir: string) {
|
|
|
279
525
|
const inPre = (preInstallPackages ?? oldPkgs).some((x) => sameEntry(x, e));
|
|
280
526
|
if (!inPre) newManagedPkgs.push(e);
|
|
281
527
|
else result.borrowedPackages.push(e);
|
|
528
|
+
} else if (pkgs.some((x) => sameResource(x, e))) {
|
|
529
|
+
// 同包不同写法(如用户手动 pin 了版本):视为借用,避免重复注入与重复加载
|
|
530
|
+
result.borrowedPackages.push(e);
|
|
282
531
|
} else {
|
|
283
532
|
pkgs.push(e);
|
|
284
533
|
newManagedPkgs.push(e);
|
|
@@ -308,33 +557,247 @@ export function makeCore(baseDir: string) {
|
|
|
308
557
|
return result;
|
|
309
558
|
}
|
|
310
559
|
|
|
311
|
-
/**
|
|
560
|
+
/** 用量记账:新会话开始(session_file 变化才计数;reload 同文件不重复计) */
|
|
561
|
+
function beginSession(sessionFile: string | null, settingsPackages: PackageEntry[] | undefined): void {
|
|
562
|
+
const st = loadState();
|
|
563
|
+
const usage = loadUsage();
|
|
564
|
+
const file = sessionFile ?? "ephemeral";
|
|
565
|
+
if (usage._current?.file === file) return;
|
|
566
|
+
const now = new Date().toISOString();
|
|
567
|
+
if (st.active) {
|
|
568
|
+
const s = (usage.perScene[st.active] ??= { sessions: 0, lastActive: now });
|
|
569
|
+
s.sessions += 1;
|
|
570
|
+
s.lastActive = now;
|
|
571
|
+
}
|
|
572
|
+
// 未纳管观察:在 settings 但不在 target 且不在任何场景定义 → 吸收候选
|
|
573
|
+
const cfg = loadScenes();
|
|
574
|
+
const target = computeTarget(st.active, cfg);
|
|
575
|
+
const definedAnywhere: PackageEntry[] = [
|
|
576
|
+
...(cfg.common?.packages ?? []),
|
|
577
|
+
...Object.values(cfg.scenes ?? {}).flatMap((d) => d.packages ?? []),
|
|
578
|
+
];
|
|
579
|
+
for (const e of settingsPackages ?? []) {
|
|
580
|
+
if (target.packages.some((t) => sameEntry(t, e))) continue;
|
|
581
|
+
if (definedAnywhere.some((t) => sameEntry(t, e))) continue;
|
|
582
|
+
const key = canonical(e);
|
|
583
|
+
const u = (usage.unmanagedSeen[key] ??= { count: 0, lastSeen: now, scenes: [] });
|
|
584
|
+
u.count += 1;
|
|
585
|
+
u.lastSeen = now;
|
|
586
|
+
if (st.active && !u.scenes.includes(st.active)) u.scenes.push(st.active);
|
|
587
|
+
}
|
|
588
|
+
usage._current = { file, scene: st.active, seen: [] };
|
|
589
|
+
saveUsage(usage);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** 工具调用归因记账:toolName → 包 → 若在当前 target 中则计数并标记本会话 seen */
|
|
593
|
+
function recordToolUse(toolName: string, toolMap: Map<string, string>): boolean {
|
|
594
|
+
const pkg = toolMap.get(toolName);
|
|
595
|
+
if (!pkg) return false;
|
|
596
|
+
const st = loadState();
|
|
597
|
+
const cfg = loadScenes();
|
|
598
|
+
const target = computeTarget(st.active, cfg);
|
|
599
|
+
const entry = target.packages.find((e) => packageIdentity(e).includes(pkg));
|
|
600
|
+
if (!entry) return false;
|
|
601
|
+
const key = canonical(entry);
|
|
602
|
+
const usage = loadUsage();
|
|
603
|
+
const r = (usage.perResource[key] ??= {});
|
|
604
|
+
r.toolCalls = (r.toolCalls ?? 0) + 1;
|
|
605
|
+
r.lastUsed = new Date().toISOString();
|
|
606
|
+
if (usage._current && !usage._current.seen.includes(key)) usage._current.seen.push(key);
|
|
607
|
+
saveUsage(usage);
|
|
608
|
+
return true;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** 反思记账:skill 子项有用/无用计数,用到则父目录条目标记 seen(重置 streak) */
|
|
612
|
+
function recordReflection(used: string[], unused: string[]): void {
|
|
613
|
+
const st = loadState();
|
|
614
|
+
const cfg = loadScenes();
|
|
615
|
+
const target = computeTarget(st.active, cfg);
|
|
616
|
+
const usage = loadUsage();
|
|
617
|
+
const now = new Date().toISOString();
|
|
618
|
+
const markParent = (id: string) => {
|
|
619
|
+
const parent = target.skills.find((p) => id === p || id.startsWith(p + path.sep));
|
|
620
|
+
if (parent && usage._current && !usage._current.seen.includes(parent)) usage._current.seen.push(parent);
|
|
621
|
+
};
|
|
622
|
+
for (const id of used) {
|
|
623
|
+
const r = (usage.perResource[id] ??= {});
|
|
624
|
+
r.reflections ??= { useful: 0, unused: 0 };
|
|
625
|
+
r.reflections.useful += 1;
|
|
626
|
+
r.lastUsed = now;
|
|
627
|
+
markParent(id);
|
|
628
|
+
}
|
|
629
|
+
for (const id of unused) {
|
|
630
|
+
const r = (usage.perResource[id] ??= {});
|
|
631
|
+
r.reflections ??= { useful: 0, unused: 0 };
|
|
632
|
+
r.reflections.unused += 1;
|
|
633
|
+
}
|
|
634
|
+
saveUsage(usage);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** 会话结束:结算 absentStreak(reload 不结算,会话仍在继续) */
|
|
638
|
+
function endSession(reason: string): void {
|
|
639
|
+
if (reason === "reload") return;
|
|
640
|
+
const st = loadState();
|
|
641
|
+
const cfg = loadScenes();
|
|
642
|
+
const target = computeTarget(st.active, cfg);
|
|
643
|
+
const usage = loadUsage();
|
|
644
|
+
const seen = usage._current?.seen ?? [];
|
|
645
|
+
const keys = [...target.packages.map((e) => canonical(e)), ...target.skills];
|
|
646
|
+
for (const key of keys) {
|
|
647
|
+
const r = (usage.perResource[key] ??= {});
|
|
648
|
+
if (seen.includes(key)) {
|
|
649
|
+
r.absentStreak = 0;
|
|
650
|
+
r.sessionsSeen = (r.sessionsSeen ?? 0) + 1;
|
|
651
|
+
} else {
|
|
652
|
+
r.absentStreak = (r.absentStreak ?? 0) + 1;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
usage._current = undefined;
|
|
656
|
+
saveUsage(usage);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** 检测配置中「同一包多种写法」的冲突(如 common 写 @1.0.3、场景写裸名) */
|
|
660
|
+
function findSpecCollisions(cfg: ScenesFile): Array<{ id: string; entries: Array<{ where: string; spec: string }> }> {
|
|
661
|
+
const byId = new Map<string, Map<string, Array<{ where: string; spec: string }>>>();
|
|
662
|
+
const add = (layer: string, e: PackageEntry) => {
|
|
663
|
+
for (const id of packageIdentity(e)) {
|
|
664
|
+
const m = byId.get(id) ?? new Map();
|
|
665
|
+
const k = canonical(e);
|
|
666
|
+
m.set(k, [...(m.get(k) ?? []), { where: layer, spec: specOf(e) }]);
|
|
667
|
+
byId.set(id, m);
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
(cfg.common?.packages ?? []).forEach((e) => add("common", e));
|
|
671
|
+
for (const [name, def] of Object.entries(cfg.scenes ?? {})) (def.packages ?? []).forEach((e) => add(name, e));
|
|
672
|
+
const out: Array<{ id: string; entries: Array<{ where: string; spec: string }> }> = [];
|
|
673
|
+
for (const [id, m] of byId) {
|
|
674
|
+
if (m.size > 1) out.push({ id, entries: [...m.values()].flat() });
|
|
675
|
+
}
|
|
676
|
+
return out;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** 静态扫描安装目录,建 tool/command → 包名归因表 */
|
|
680
|
+
function buildToolMap(): { tools: Map<string, string>; commands: Map<string, string> } {
|
|
681
|
+
const tools = new Map<string, string>();
|
|
682
|
+
const commands = new Map<string, string>();
|
|
683
|
+
const roots: Array<{ dir: string; name: string }> = [];
|
|
684
|
+
const nm = path.join(paths.npmDir, "node_modules");
|
|
685
|
+
if (fs.existsSync(nm)) {
|
|
686
|
+
for (const e of fs.readdirSync(nm, { withFileTypes: true })) {
|
|
687
|
+
if (e.isDirectory() && e.name.startsWith("@")) {
|
|
688
|
+
for (const c of fs.readdirSync(path.join(nm, e.name), { withFileTypes: true })) {
|
|
689
|
+
if (c.isDirectory()) roots.push({ dir: path.join(nm, e.name, c.name), name: `${e.name}/${c.name}` });
|
|
690
|
+
}
|
|
691
|
+
} else if (e.isDirectory()) {
|
|
692
|
+
roots.push({ dir: path.join(nm, e.name), name: e.name });
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
const walkGit = (dir: string, depth: number): void => {
|
|
697
|
+
if (depth > 4) return;
|
|
698
|
+
let ents: fs.Dirent[];
|
|
699
|
+
try {
|
|
700
|
+
ents = fs.readdirSync(dir, { withFileTypes: true });
|
|
701
|
+
} catch {
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
if (ents.some((e) => e.isFile() && e.name === "package.json")) {
|
|
705
|
+
roots.push({ dir, name: path.basename(dir) });
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
for (const e of ents) if (e.isDirectory() && !e.name.startsWith(".")) walkGit(path.join(dir, e.name), depth + 1);
|
|
709
|
+
};
|
|
710
|
+
if (fs.existsSync(paths.gitRoot)) walkGit(paths.gitRoot, 0);
|
|
711
|
+
|
|
712
|
+
for (const root of roots) {
|
|
713
|
+
const files: string[] = [];
|
|
714
|
+
collectJsFiles(root.dir, files, { n: 60 });
|
|
715
|
+
for (const f of files) {
|
|
716
|
+
let src: string;
|
|
717
|
+
try {
|
|
718
|
+
src = fs.readFileSync(f, "utf8");
|
|
719
|
+
} catch {
|
|
720
|
+
continue;
|
|
721
|
+
}
|
|
722
|
+
for (const m of src.matchAll(/registerTool\s*\(\s*\{[\s\S]{0,600}?name\s*:\s*["'`]([^"'`]+)["'`]/g)) {
|
|
723
|
+
if (!tools.has(m[1])) tools.set(m[1], root.name);
|
|
724
|
+
}
|
|
725
|
+
for (const m of src.matchAll(/registerCommand\s*\(\s*["'`]([^"'`]+)["'`]/g)) {
|
|
726
|
+
if (!commands.has(m[1])) commands.set(m[1], root.name);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return { tools, commands };
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** 生成模板 scenes.json + 场景 skill 目录骨架(预设均为 npm 真实存在的包,2026-09 核验) */
|
|
312
734
|
function scaffold(): string[] {
|
|
313
735
|
const created: string[] = [];
|
|
314
736
|
const template: ScenesFile = {
|
|
315
737
|
common: {
|
|
316
|
-
description: "
|
|
317
|
-
packages: [
|
|
738
|
+
description: "通用层:任何场景都恒加载的基础设施",
|
|
739
|
+
packages: [
|
|
740
|
+
"npm:pi-scenes", // 场景切换器自身(常驻才能随时切)
|
|
741
|
+
"npm:pi-carryover", // 跨会话工作承接(上次干到哪、下次接着干)
|
|
742
|
+
],
|
|
318
743
|
skills: ["~/.pi/agent/scenes/common/skills"],
|
|
319
744
|
},
|
|
320
745
|
scenes: {
|
|
321
746
|
coding: {
|
|
322
|
-
description: "
|
|
323
|
-
packages: [
|
|
747
|
+
description: "写代码:实时代码反馈、子代理委派、并行分支",
|
|
748
|
+
packages: [
|
|
749
|
+
"npm:pi-lens", // LSP/linter/格式化实时代码反馈
|
|
750
|
+
"npm:pi-subagents", // 单代理委派 + 脚本化多代理工作流
|
|
751
|
+
"npm:pi-git-worktree", // git worktree 并行开发
|
|
752
|
+
],
|
|
324
753
|
skills: ["~/.pi/agent/scenes/coding/skills"],
|
|
325
754
|
},
|
|
326
755
|
office: {
|
|
327
756
|
description: "办公:文档处理与日常事务",
|
|
328
|
-
packages: [
|
|
757
|
+
packages: [
|
|
758
|
+
"npm:pi-docparser", // PDF/Office 文档解析抽取
|
|
759
|
+
],
|
|
329
760
|
skills: ["~/.pi/agent/scenes/office/skills"],
|
|
330
761
|
},
|
|
762
|
+
pm: {
|
|
763
|
+
description: "产品经理:竞品调研、目标规划与需求跟踪",
|
|
764
|
+
packages: [
|
|
765
|
+
"npm:pi-web-access", // 网页搜索/抓取/PDF/YouTube(竞品与市场调研)
|
|
766
|
+
"npm:pi-goal-x", // /goal 目标规划 + 独立完成度审计(roadmap/需求跟踪)
|
|
767
|
+
"npm:@juicesharp/rpiv-todo", // 需求/任务清单实时 overlay(抗 /reload 与压缩)
|
|
768
|
+
],
|
|
769
|
+
skills: ["~/.pi/agent/scenes/pm/skills"],
|
|
770
|
+
},
|
|
771
|
+
research: {
|
|
772
|
+
description: "咨询调研:多源检索、并行多角度深挖",
|
|
773
|
+
packages: [
|
|
774
|
+
"npm:pi-web-access", // 搜索/URL 抓取/PDF/视频理解(调研核心)
|
|
775
|
+
"npm:pi-subagents", // 多角度并行调研(每个子代理一源)
|
|
776
|
+
],
|
|
777
|
+
skills: ["~/.pi/agent/scenes/research/skills"],
|
|
778
|
+
},
|
|
779
|
+
writing: {
|
|
780
|
+
description: "写作:素材检索、事实核查、文体打磨",
|
|
781
|
+
packages: [
|
|
782
|
+
"npm:pi-web-access", // 素材检索与事实核查(引用溯源)
|
|
783
|
+
],
|
|
784
|
+
skills: ["~/.pi/agent/scenes/writing/skills"],
|
|
785
|
+
},
|
|
786
|
+
data: {
|
|
787
|
+
description: "数据分析:表格抽取、MCP 接数据库/BI",
|
|
788
|
+
packages: [
|
|
789
|
+
"npm:pi-docparser", // Excel/CSV/PDF 表格结构化抽取
|
|
790
|
+
"npm:pi-mcp-adapter", // 接任意 MCP server(数据库/BI/内部数据服务)
|
|
791
|
+
],
|
|
792
|
+
skills: ["~/.pi/agent/scenes/data/skills"],
|
|
793
|
+
},
|
|
331
794
|
},
|
|
332
795
|
};
|
|
333
796
|
if (!fs.existsSync(paths.scenesFile)) {
|
|
334
797
|
writeJson(paths.scenesFile, template);
|
|
335
798
|
created.push(paths.scenesFile);
|
|
336
799
|
}
|
|
337
|
-
for (const s of ["common", "coding", "office"]) {
|
|
800
|
+
for (const s of ["common", "coding", "office", "pm", "research", "writing", "data"]) {
|
|
338
801
|
const dir = path.join(paths.scenesRoot, s, "skills");
|
|
339
802
|
if (!fs.existsSync(dir)) {
|
|
340
803
|
fs.mkdirSync(dir, { recursive: true });
|
|
@@ -350,10 +813,18 @@ export function makeCore(baseDir: string) {
|
|
|
350
813
|
saveScenes,
|
|
351
814
|
loadState,
|
|
352
815
|
saveState,
|
|
816
|
+
loadUsage,
|
|
817
|
+
saveUsage,
|
|
353
818
|
resolveScene,
|
|
354
819
|
computeTarget,
|
|
355
820
|
isPackageInstalled,
|
|
356
821
|
applyToSettings,
|
|
822
|
+
findSpecCollisions,
|
|
823
|
+
beginSession,
|
|
824
|
+
recordToolUse,
|
|
825
|
+
recordReflection,
|
|
826
|
+
endSession,
|
|
827
|
+
buildToolMap,
|
|
357
828
|
scaffold,
|
|
358
829
|
};
|
|
359
830
|
}
|
|
@@ -363,10 +834,6 @@ export function makeCore(baseDir: string) {
|
|
|
363
834
|
const PICKER_OFF = "∅ 仅通用层(关闭场景)";
|
|
364
835
|
const PICKER_CANCEL = "—— 取消";
|
|
365
836
|
|
|
366
|
-
function specOf(e: PackageEntry): string {
|
|
367
|
-
return typeof e === "string" ? e : e.source;
|
|
368
|
-
}
|
|
369
|
-
|
|
370
837
|
export default function (pi: ExtensionAPI) {
|
|
371
838
|
const baseDir = process.env.PI_SCENES_DIR || path.join(os.homedir(), ".pi", "agent");
|
|
372
839
|
const core = makeCore(baseDir);
|
|
@@ -382,6 +849,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
382
849
|
|
|
383
850
|
const target = core.computeTarget(name, cfg);
|
|
384
851
|
|
|
852
|
+
// 同包多种写法:身份级去重已保证只加载首个,但提醒用户统一配置
|
|
853
|
+
const collisions = core.findSpecCollisions(cfg);
|
|
854
|
+
if (collisions.length > 0) {
|
|
855
|
+
ctx.ui.notify(
|
|
856
|
+
`⚠️ scenes.json 里同一包存在多种写法(已自动按首个生效,不重复加载):\n${collisions
|
|
857
|
+
.map((c) => ` · ${c.id}: ${c.entries.map((e) => `${e.where}=${e.spec}`).join(" | ")}`)
|
|
858
|
+
.join("\n")}\n建议统一写法,避免困惑`,
|
|
859
|
+
"info",
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
|
|
385
863
|
// 缺失包:确认后逐个 pi install(全局 scope pi 不自动装,必须显式装)
|
|
386
864
|
const missing = target.packages.filter((e) => !core.isPackageInstalled(e));
|
|
387
865
|
let preInstallPackages: PackageEntry[] | undefined;
|
|
@@ -420,7 +898,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
420
898
|
|
|
421
899
|
pi.registerCommand("scene", {
|
|
422
900
|
title: "场景切换",
|
|
423
|
-
description: "通用层+场景 一键切换 extension/skill(/scene、/scene <name>、/scene off、/scene status、/scene init)",
|
|
901
|
+
description: "通用层+场景 一键切换 extension/skill(/scene、/scene <name>、/scene off、/scene status、/scene init、/scene stats、/scene evolve)",
|
|
424
902
|
handler: async (args: string, ctx: any) => {
|
|
425
903
|
const arg = (args ?? "").trim();
|
|
426
904
|
|
|
@@ -451,16 +929,43 @@ export default function (pi: ExtensionAPI) {
|
|
|
451
929
|
const cfg = core.loadScenes();
|
|
452
930
|
const st = core.loadState();
|
|
453
931
|
const target = core.computeTarget(st.active, cfg);
|
|
932
|
+
const collisions = core.findSpecCollisions(cfg);
|
|
454
933
|
const lines = [
|
|
455
934
|
`当前场景:${st.active ? st.active : "(无,仅通用层)"}`,
|
|
456
935
|
`生效 packages(${target.packages.length}):${target.packages.map(specOf).join(", ") || "—"}`,
|
|
457
936
|
`生效 skills(${target.skills.length}):${target.skills.join(", ") || "—"}`,
|
|
458
937
|
`可用场景:${Object.keys(cfg.scenes ?? {}).join(", ") || "—"}`,
|
|
459
938
|
];
|
|
939
|
+
if (collisions.length > 0) {
|
|
940
|
+
lines.push(`⚠️ 同包多种写法(已按首个生效):${collisions.map((c) => `${c.id}(${c.entries.map((e) => e.spec).join("|")})`).join("、")}`);
|
|
941
|
+
}
|
|
460
942
|
ctx.ui.notify(lines.join("\n"), "info");
|
|
461
943
|
return;
|
|
462
944
|
}
|
|
463
945
|
|
|
946
|
+
if (arg === "stats") {
|
|
947
|
+
showStats(ctx);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
if (arg === "evolve auto") {
|
|
952
|
+
const usage = core.loadUsage();
|
|
953
|
+
usage.autoEvolve = !usage.autoEvolve;
|
|
954
|
+
core.saveUsage(usage);
|
|
955
|
+
ctx.ui.notify(
|
|
956
|
+
usage.autoEvolve
|
|
957
|
+
? "自动进化已开启:会话结束自动应用吸收/淘汰(不动 common 与无工具信号的包;变更下次重载生效)"
|
|
958
|
+
: "自动进化已关闭",
|
|
959
|
+
"info",
|
|
960
|
+
);
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
if (arg === "evolve") {
|
|
965
|
+
await runEvolve(ctx);
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
|
|
464
969
|
if (arg === "off" || arg === "none") {
|
|
465
970
|
await doSwitch(ctx, null);
|
|
466
971
|
return;
|
|
@@ -504,4 +1009,181 @@ export default function (pi: ExtensionAPI) {
|
|
|
504
1009
|
await doSwitch(ctx, name);
|
|
505
1010
|
},
|
|
506
1011
|
});
|
|
1012
|
+
|
|
1013
|
+
// ── v0.2:用量采集与自进化 ──────────────────────────────
|
|
1014
|
+
|
|
1015
|
+
let toolMapCache: { at: number; value: { tools: Map<string, string>; commands: Map<string, string> } } | null = null;
|
|
1016
|
+
function getToolMap() {
|
|
1017
|
+
if (toolMapCache && Date.now() - toolMapCache.at < 5 * 60_000) return toolMapCache.value;
|
|
1018
|
+
const value = core.buildToolMap();
|
|
1019
|
+
toolMapCache = { at: Date.now(), value };
|
|
1020
|
+
return value;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
function hasToolsForTarget(): Set<string> {
|
|
1024
|
+
const cfg = core.loadScenes();
|
|
1025
|
+
const st = core.loadState();
|
|
1026
|
+
const target = core.computeTarget(st.active, cfg);
|
|
1027
|
+
const owners = new Set(getToolMap().tools.values());
|
|
1028
|
+
return new Set(target.packages.filter((e) => packageIdentity(e).some((id) => owners.has(id))).map((e) => canonical(e)));
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
function backupScenes(): void {
|
|
1032
|
+
try {
|
|
1033
|
+
if (fs.existsSync(core.paths.scenesFile)) fs.copyFileSync(core.paths.scenesFile, `${core.paths.scenesFile}.scenes-bak`);
|
|
1034
|
+
} catch {}
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
function shortLabel(k: string): string {
|
|
1038
|
+
try {
|
|
1039
|
+
const v = JSON.parse(k);
|
|
1040
|
+
if (typeof v === "string") return v;
|
|
1041
|
+
if (v && typeof v === "object" && v.source) return v.source;
|
|
1042
|
+
} catch {}
|
|
1043
|
+
return k.split(path.sep).slice(-2).join("/");
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
function showStats(ctx: any): void {
|
|
1047
|
+
const usage = core.loadUsage();
|
|
1048
|
+
const lines: string[] = [];
|
|
1049
|
+
const scenes = Object.entries(usage.perScene);
|
|
1050
|
+
lines.push(`场景:${scenes.length ? scenes.map(([n, s]) => `${n} ${s.sessions} 次(最近 ${s.lastActive.slice(0, 10)})`).join(" · ") : "—"}`);
|
|
1051
|
+
const res = Object.entries(usage.perResource).filter(([, r]) => (r.toolCalls ?? 0) > 0 || r.reflections);
|
|
1052
|
+
lines.push(`资源用量(${res.length}):`);
|
|
1053
|
+
for (const [k, r] of res.slice(0, 20)) {
|
|
1054
|
+
const refl = r.reflections ? ` · 反思 ✓${r.reflections.useful}/✗${r.reflections.unused}` : "";
|
|
1055
|
+
lines.push(` ${shortLabel(k)}: 调用 ${r.toolCalls ?? 0} · 连续未用 ${r.absentStreak ?? "?"}${refl}`);
|
|
1056
|
+
}
|
|
1057
|
+
const unm = Object.entries(usage.unmanagedSeen).filter(([, u]) => u.count > 0);
|
|
1058
|
+
if (unm.length) lines.push(`未纳管观察:${unm.map(([k, u]) => `${shortLabel(k)} ×${u.count}(${u.scenes.join("/") || "?"})`).join(" · ")}`);
|
|
1059
|
+
lines.push(`自动进化:${usage.autoEvolve ? "on" : "off"}(/scene evolve auto 切换)`);
|
|
1060
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
async function runEvolve(ctx: any): Promise<void> {
|
|
1064
|
+
const cfg = core.loadScenes();
|
|
1065
|
+
const usage = core.loadUsage();
|
|
1066
|
+
const proposals = computeProposals(cfg, usage, { hasTools: hasToolsForTarget() });
|
|
1067
|
+
if (proposals.length === 0) {
|
|
1068
|
+
ctx.ui.notify("暂无进化提案(观察积累中,用 /scene stats 查看用量)", "info");
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
const accepted: Proposal[] = [];
|
|
1072
|
+
for (const p of proposals) {
|
|
1073
|
+
const head =
|
|
1074
|
+
p.kind === "absorb"
|
|
1075
|
+
? `吸收:scenes.${p.scene}.packages += ${specOf(p.entry)}`
|
|
1076
|
+
: `淘汰:scenes.${p.scene}.${p.skillPath ? "skills" : "packages"} -= ${p.label}`;
|
|
1077
|
+
const ok = await ctx.ui.confirm("场景进化提案", `${head}\n依据:${p.reason}\n\n应用这条吗?`);
|
|
1078
|
+
if (ok) accepted.push(p);
|
|
1079
|
+
}
|
|
1080
|
+
if (!accepted.length) {
|
|
1081
|
+
ctx.ui.notify("已取消(未做任何修改)", "info");
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
const next = applyProposals(cfg, accepted);
|
|
1085
|
+
backupScenes();
|
|
1086
|
+
core.saveScenes(next);
|
|
1087
|
+
const st = core.loadState();
|
|
1088
|
+
core.applyToSettings(core.computeTarget(st.active, next), st.active, undefined);
|
|
1089
|
+
ctx.ui.notify(`已应用 ${accepted.length} 条提案,正在热重载…`, "info");
|
|
1090
|
+
await ctx.reload();
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
function buildDigest(ctx: any): string {
|
|
1094
|
+
let entries: any[] = [];
|
|
1095
|
+
try {
|
|
1096
|
+
entries = ctx.sessionManager?.getEntries?.() ?? [];
|
|
1097
|
+
} catch {}
|
|
1098
|
+
const msgs = entries.filter((e) => e?.type === "message").slice(-40);
|
|
1099
|
+
return msgs
|
|
1100
|
+
.map((e) => {
|
|
1101
|
+
const role = e.message?.role ?? "?";
|
|
1102
|
+
const content = e.message?.content;
|
|
1103
|
+
const text =
|
|
1104
|
+
typeof content === "string"
|
|
1105
|
+
? content
|
|
1106
|
+
: Array.isArray(content)
|
|
1107
|
+
? content.filter((c: any) => c?.type === "text").map((c: any) => c.text).join(" ")
|
|
1108
|
+
: "";
|
|
1109
|
+
return `${role}: ${text.replace(/\s+/g, " ").slice(0, 160)}`;
|
|
1110
|
+
})
|
|
1111
|
+
.join("\n")
|
|
1112
|
+
.slice(0, 6000);
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
async function runReflection(ctx: any): Promise<void> {
|
|
1116
|
+
const st = core.loadState();
|
|
1117
|
+
const cfg = core.loadScenes();
|
|
1118
|
+
const target = core.computeTarget(st.active, cfg);
|
|
1119
|
+
const skills = listSkillChildren(target.skills);
|
|
1120
|
+
if (!skills.length) return;
|
|
1121
|
+
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
|
|
1122
|
+
if (!auth?.ok || !auth.apiKey) return;
|
|
1123
|
+
const sys =
|
|
1124
|
+
"你是 pi 资源使用分析器。根据会话记录判断哪些已加载 skill 实际被用到或对完成任务有帮助。只输出紧凑 JSON,禁止任何其他文字。";
|
|
1125
|
+
const user = `已加载 skill 清单:\n${skills.map((s) => `- ${s.label}`).join("\n")}\n\n会话尾部摘录:\n${buildDigest(ctx)}\n\n请输出 {"used":["<label>",...],"unused":["<label>",...]}。used=实际用到或明显有帮助;unused=完全未涉及。`;
|
|
1126
|
+
// 动态 import:测试环境(无 node_modules)不触达;pi 运行时由 jiti alias 解析
|
|
1127
|
+
const { complete } = await import("@earendil-works/pi-ai/compat");
|
|
1128
|
+
const resp = await complete(
|
|
1129
|
+
ctx.model,
|
|
1130
|
+
{ systemPrompt: sys, messages: [{ role: "user", content: user }] },
|
|
1131
|
+
{ apiKey: auth.apiKey, headers: auth.headers, env: auth.env, signal: AbortSignal.timeout(30_000), cacheRetention: "none" },
|
|
1132
|
+
);
|
|
1133
|
+
const parsed = parseJsonLoose(extractText(resp));
|
|
1134
|
+
if (!parsed || !Array.isArray(parsed.used) || !Array.isArray(parsed.unused)) return;
|
|
1135
|
+
const byLabel = new Map(skills.map((s) => [s.label, s.id]));
|
|
1136
|
+
const used = (parsed.used as unknown[]).map((l) => byLabel.get(String(l))).filter(Boolean) as string[];
|
|
1137
|
+
const unused = (parsed.unused as unknown[]).map((l) => byLabel.get(String(l))).filter(Boolean) as string[];
|
|
1138
|
+
core.recordReflection(used, unused);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
function maybeAutoEvolve(ctx: any, reason: string): void {
|
|
1142
|
+
const usage = core.loadUsage();
|
|
1143
|
+
if (!usage.autoEvolve) return;
|
|
1144
|
+
const cfg = core.loadScenes();
|
|
1145
|
+
const proposals = computeProposals(cfg, usage, { hasTools: hasToolsForTarget() });
|
|
1146
|
+
if (!proposals.length) return;
|
|
1147
|
+
const next = applyProposals(cfg, proposals);
|
|
1148
|
+
backupScenes();
|
|
1149
|
+
core.saveScenes(next);
|
|
1150
|
+
const st = core.loadState();
|
|
1151
|
+
core.applyToSettings(core.computeTarget(st.active, next), st.active, undefined);
|
|
1152
|
+
// 不在 shutdown 里 ctx.reload()(会递归触发 shutdown);变更下次自然重载生效
|
|
1153
|
+
if (reason !== "quit") {
|
|
1154
|
+
try {
|
|
1155
|
+
ctx.ui.notify(
|
|
1156
|
+
`自动进化已应用 ${proposals.length} 条提案(下次重载生效):\n${proposals.map((p) => (p.kind === "absorb" ? `+ ${specOf(p.entry)} → ${p.scene}` : `- ${p.label} (${p.scene})`)).join("\n")}`,
|
|
1157
|
+
"info",
|
|
1158
|
+
);
|
|
1159
|
+
} catch {}
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1164
|
+
try {
|
|
1165
|
+
const pkgs = readJson<Record<string, unknown>>(core.paths.settingsFile, {}).packages;
|
|
1166
|
+
core.beginSession(ctx.sessionManager?.getSessionFile?.() ?? null, Array.isArray(pkgs) ? (pkgs as PackageEntry[]) : []);
|
|
1167
|
+
} catch {}
|
|
1168
|
+
});
|
|
1169
|
+
|
|
1170
|
+
pi.on("tool_call", async (event) => {
|
|
1171
|
+
try {
|
|
1172
|
+
core.recordToolUse((event as any).toolName, getToolMap().tools);
|
|
1173
|
+
} catch {}
|
|
1174
|
+
});
|
|
1175
|
+
|
|
1176
|
+
pi.on("session_shutdown", async (event, ctx) => {
|
|
1177
|
+
const reason = (event as any)?.reason ?? "quit";
|
|
1178
|
+
if (reason === "reload") return;
|
|
1179
|
+
try {
|
|
1180
|
+
await runReflection(ctx);
|
|
1181
|
+
} catch {}
|
|
1182
|
+
try {
|
|
1183
|
+
core.endSession(reason);
|
|
1184
|
+
} catch {}
|
|
1185
|
+
try {
|
|
1186
|
+
maybeAutoEvolve(ctx, reason);
|
|
1187
|
+
} catch {}
|
|
1188
|
+
});
|
|
507
1189
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-scenes",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "pi
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "pi 扩展:场景切换器 + 资源自进化。通用层+分场景层打包 extension/skill,/scene 热切换;按实际用量(工具调用归因 + 会话结束 LLM 反思)生成吸收/淘汰提案,让场景定义随使用习惯进化。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package"
|
|
7
7
|
],
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
]
|
|
31
31
|
},
|
|
32
32
|
"peerDependencies": {
|
|
33
|
-
"@earendil-works/pi-coding-agent": "*"
|
|
33
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
34
|
+
"@earendil-works/pi-ai": "*"
|
|
34
35
|
}
|
|
35
36
|
}
|