@aoshizuku/pi-subagent 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +173 -2
- package/agents/explore.md +20 -0
- package/agents/general.md +17 -0
- package/package.json +55 -5
- package/src/batcher.ts +77 -0
- package/src/child.ts +212 -0
- package/src/cleanup.ts +40 -0
- package/src/config.ts +181 -0
- package/src/detail.ts +408 -0
- package/src/focus.ts +240 -0
- package/src/hud-state.ts +183 -0
- package/src/index.ts +1013 -0
- package/src/list.ts +223 -0
- package/src/manager.ts +588 -0
- package/src/models.ts +80 -0
- package/src/observer.ts +275 -0
- package/src/prompts.ts +103 -0
- package/src/render.ts +592 -0
- package/src/result.ts +226 -0
- package/src/run.ts +204 -0
- package/src/settings.ts +140 -0
- package/src/shizuku-settings.ts +92 -0
- package/src/stop-confirm.ts +47 -0
- package/src/test-helpers.ts +194 -0
- package/src/tool-line.ts +85 -0
- package/src/types.ts +257 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AoShizuku
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,174 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-subagent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
给 pi 补上 **subagent**:模型把一个边界清楚的子任务交给一个拥有独立上下文窗口的子 agent,
|
|
4
|
+
子 agent 做完只把最终报告交回来。可以前台等结果,也可以丢到后台、完成时自动唤醒。
|
|
5
|
+
|
|
6
|
+
> **当前状态:Phase 1(前台)和 Phase 2(后台、续话、HUD 交互)已实现。** Phase 3(fork 上下文、verifier、worktree)还是设计
|
|
7
|
+
> (见 [docs/08-implementation.md](./docs/08-implementation.md) §3)。
|
|
8
|
+
|
|
9
|
+
## 做什么
|
|
10
|
+
|
|
11
|
+
- `agent` 工具:模型传 `description`(给用户看的短标签)、`prompt`(自包含的任务)和可选的 `agent_type`,
|
|
12
|
+
插件在**同一进程**里用 pi SDK 起一个全新的子会话跑完任务,只把最后一条 assistant 消息作为结果交回
|
|
13
|
+
- 一条回复里调用多次 `agent` 就是并行;所有调用共用一个上限 4 的 FIFO 队列,超出的显示 `queued (n)`
|
|
14
|
+
- `background: true`:立刻返回 `ag-N`,完成时以 `<subagent-notification>` 唤醒模型(投递策略同 pi-background-shell:
|
|
15
|
+
空闲时 3 秒合并窗口,忙时在轮次边界一次排出,Esc 中断后不自动起新一轮)。父 agent 被 Esc 中断不影响后台 agent
|
|
16
|
+
- `agent_send`:给运行中的 agent 追加指令(下一轮之前送达)、给排队中的拼到任务末尾、把已结束的从会话文件重新打开再跑一轮(上下文完整)
|
|
17
|
+
- `agent_stop`:停掉运行中或排队中的 agent,返回部分报告;模型自己停掉的不再通知
|
|
18
|
+
- 子会话只加载 `childExtensions` 白名单里的扩展(默认只有 pi-dsweb),工具只给类型 `tools` 里列出的;子会话里根本没有 `agent`,所以只有 1 层
|
|
19
|
+
- 内置两个类型:`explore`(只读:`read, grep, find, ls`)和 `general`(`read, bash, edit, write, grep, find, ls`);
|
|
20
|
+
父会话用 `powershell` 时,`general` 自动把 `bash` 换成 `powershell`
|
|
21
|
+
- 装了 [pi-hud](https://github.com/AoShizuku/pi-hud) 时,HUD 工具行下面显示 agent 行(运行中、排队中、60 秒内结束的,最多 4 行);
|
|
22
|
+
编辑器为空时按 `↓` 进入选择,`Enter` 打开详情浮层(实时 Activity、报告、对话记录路径),`x x` 停止,`Esc` 退出;全屏模式下也可以直接点击 agent 行
|
|
23
|
+
- `/agents` 在编辑器位置打开本会话全部 agent 的列表(`Enter` 在上方打开详情浮层);`/agents types` 列出已加载的类型和加载告警;`/agents reload` 重新读类型文件和配置
|
|
24
|
+
|
|
25
|
+
## 安装
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
cd pi-subagent
|
|
29
|
+
npm install
|
|
30
|
+
pi install npm:@aoshizuku/pi-subagent # 从 npm 安装
|
|
31
|
+
pi install git:github.com/AoShizuku/pi-subagent # 或从 GitHub 安装
|
|
32
|
+
pi install ./pi-subagent
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
只试一次:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pi -e ./pi-subagent/src/index.ts
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## 关键行为
|
|
42
|
+
|
|
43
|
+
| 点 | 做法 |
|
|
44
|
+
|---|---|
|
|
45
|
+
| 上下文 | 全新上下文:子 agent 看不到父对话,只能看到 `prompt`、项目的 AGENTS.md / CLAUDE.md、cwd |
|
|
46
|
+
| system prompt | 只追加不替换:子 agent 契约 + 类型正文进 `appendSystemPrompt`,pi 的 tools / rules 节保留 |
|
|
47
|
+
| 模型 | 调用参数 `model` > 配置 `types.<name>.model` > 类型文件 > 父会话模型。参数写错直接报错;类型或配置指定的不可用就退回父模型,结果末尾附 `note:` |
|
|
48
|
+
| provider | 父会话里扩展在运行时注册的 provider 会重放到子会话的 model runtime |
|
|
49
|
+
| 上下文预算 | 每个类型有 `context_limit`(默认 70%):上下文占用到这里插一条只进上下文的提醒,要求写报告;宽限 3 轮后还在调工具就停,状态 `context_limit`,最后一条 assistant 文本作为部分报告。只用提醒和中断,不撤工具,不让 prompt cache 失效。子会话关闭 auto-compaction |
|
|
50
|
+
| 轮数 | `max_turns`(默认 300)只防失控循环;剩 2 轮时提醒,用完就停,状态 `max_turns` |
|
|
51
|
+
| 结果 | `<subagent-result agent-id=… status=…>` 包住报告;超过 20,000 字符只内联开头,完整报告总在 `ag-N.result.md` |
|
|
52
|
+
| 不可信数据 | 报告里会提前闭合外层标签的片段(`</subagent-result`、`</subagent-notification` 等)被转义;规则要求父 agent 把报告当证据核实 |
|
|
53
|
+
| 一次性模式 | `pi -p` / `--mode json` 下 `background: true` 报错,工具描述和规则里不提后台;前台照常 |
|
|
54
|
+
| 失败 | `failed` / `max_turns` / `context_limit` / `aborted` 以错误结果返回(`isError`),正文带原因、已有的部分报告和下一步建议 |
|
|
55
|
+
| 中断 | 父 agent 被 Esc 中断 → 前台子会话 abort(后台的不受影响);排队中的直接出队;session 结束时 abort 并 dispose 所有子会话(最多等 5 秒),不发通知 |
|
|
56
|
+
| 通知 | 后台 agent 完成、失败、轮数耗尽、被用户(HUD / 详情浮层 / 列表里的 `x`)停止时通知;每个报告最多 8,000 字符、整批 24,000,超出的只给 result 文件路径 |
|
|
57
|
+
| 续话 | `agent_send` 重新打开子会话文件;父会话是内存会话时子会话也是内存会话,不能续话;上下文到过 `context_limit` 的也不能续话(两种情况结果里都不出现 `agent_send` 提示)。不提供在浮层里直接给子 agent 插话:要纠正就按 x 停掉,在主对话里说,由父 agent 续话 |
|
|
58
|
+
| 持久化 | 每个 agent 的状态以 `subagent` 自定义 entry 写进父会话(不进 LLM 上下文);`/resume` 或 `/reload` 后恢复,上一个进程里没跑完的标成 `aborted (session ended)`,编号接着往后排 |
|
|
59
|
+
| 文件 | 子会话文件和结果文件在 `<sessionDir>/subagents/<parentSessionId>/`,不会出现在 `/resume` 列表;父会话是内存会话时结果文件放到系统临时目录。其他父会话的目录超过 `retentionDays`(14 天)没有更新就整个删掉 |
|
|
60
|
+
|
|
61
|
+
## 自定义类型
|
|
62
|
+
|
|
63
|
+
Markdown + YAML frontmatter,放在 `~/.pi/agent/agents/*.md`(用户)或 `<项目>/.pi/agents/*.md`(项目,仅在项目受信任时加载)。
|
|
64
|
+
同名时项目 > 用户 > 内置,名字不区分大小写。
|
|
65
|
+
|
|
66
|
+
```markdown
|
|
67
|
+
---
|
|
68
|
+
name: api-tracer
|
|
69
|
+
description: Traces how an HTTP endpoint is handled, from route registration to the database call.
|
|
70
|
+
tools: read, grep, find, ls
|
|
71
|
+
model: anthropic/claude-haiku-4-5
|
|
72
|
+
thinking: low
|
|
73
|
+
context_limit: 60
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
You trace a single HTTP endpoint through the codebase. ...
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
| 字段 | 默认 | 说明 |
|
|
80
|
+
|---|---|---|
|
|
81
|
+
| `name` | 文件名 | `[a-z0-9][a-z0-9_-]*` |
|
|
82
|
+
| `description` | 必填 | 一行,进 `agent` 工具描述 |
|
|
83
|
+
| `tools` | `read, bash, edit, write, grep, find, ls` | pi 内置工具,或 `childExtensions` 里的扩展注册的工具(如 `web_search`;扩展没加载时忽略);`none` 表示不给工具 |
|
|
84
|
+
| `model` / `thinking` | 继承父会话 | |
|
|
85
|
+
| `context_limit` | 70 | 10–95,窗口百分比 |
|
|
86
|
+
| `max_turns` | 300 | ≥ 2,防失控的兜底 |
|
|
87
|
+
| `context_files` | `true` | 是否加载 AGENTS.md / CLAUDE.md |
|
|
88
|
+
| `skills` | `false` | 是否加载 skills |
|
|
89
|
+
| `background` | `false` | 调用方没传 `background` 时的默认值(`print` / `json` 模式下不生效) |
|
|
90
|
+
| `enabled` | `true` | `false` 可以禁用同名的低优先级类型 |
|
|
91
|
+
|
|
92
|
+
类型列表只在 session 开始时读一次(改了文件用 `/agents reload`),避免会话中途改动工具描述打掉 prompt cache。
|
|
93
|
+
|
|
94
|
+
## 配置
|
|
95
|
+
|
|
96
|
+
`~/.pi/agent/pi-subagent.json`(可选,只有全局配置):
|
|
97
|
+
|
|
98
|
+
```json
|
|
99
|
+
{
|
|
100
|
+
"types": { "explore": { "model": "deepseek/deepseek-flash", "thinking": "low", "context_limit": 60 } },
|
|
101
|
+
"maxConcurrent": 4,
|
|
102
|
+
"resultMaxChars": 20000,
|
|
103
|
+
"notifyMaxChars": 8000,
|
|
104
|
+
"notifyBatchMaxChars": 24000,
|
|
105
|
+
"retentionDays": 14,
|
|
106
|
+
"childExtensions": ["pi-dsweb"],
|
|
107
|
+
"confirmStop": true
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`confirmStop`:HUD 焦点模式、`/agents` 列表和详情浮层里,`x` 要按两次才停止 agent(类似 vim 的 `dd`)。
|
|
112
|
+
第一次 `x` 让选中行变成红色竖标加错误底色,提示行换成 `press x again to stop`;再按 `x` 才停,按其他任何键都只取消。
|
|
113
|
+
默认 `true`,设为 `false` 回到按一次就停。
|
|
114
|
+
|
|
115
|
+
`childExtensions`:子会话可以加载的扩展(包名,如 `"pi-dsweb"`,或扩展目录的绝对路径)。不带 scope 的名字按末段匹配,`"pi-dsweb"` 同时认得 `npm:@aoshizuku/pi-dsweb`、`git:github.com/AoShizuku/pi-dsweb` 和本地目录。默认是 `["pi-dsweb"]`,
|
|
116
|
+
写 `[]` 则子会话不加载任何扩展。非空时 pi 会先加载所有已安装的扩展再按名单过滤(被过滤掉的扩展的工厂函数仍会执行一次);
|
|
117
|
+
本插件、pi-ask-user、pi-autotitle、pi-hud、pi-bettertui、pi-background-shell 无论怎么写都会被剔除。
|
|
118
|
+
|
|
119
|
+
扩展加载进来**不等于**工具给了子 agent:一个类型只拿到它的 `tools` 里写了名字的扩展工具。内置的 `explore` 和 `general`
|
|
120
|
+
都列了 `web_search, web_fetch`,所以装了 [pi-dsweb](https://github.com/AoShizuku/pi-dsweb) 时它们能搜网页、读网页;没装时这两个名字被忽略。
|
|
121
|
+
|
|
122
|
+
## 键盘与鼠标(需要 pi-hud)
|
|
123
|
+
|
|
124
|
+
| 位置 | 按键 | 作用 |
|
|
125
|
+
|---|---|---|
|
|
126
|
+
| 编辑器为空、HUD 有 agent 行 | `↓` | 进入 agent 行选择(选中行左栏出现 accent 竖标、铺满主题的选中底色,下方出现提示行) |
|
|
127
|
+
| 选择中 | `↑` / `↓` | 移动;在第一行按 `↑` 退出 |
|
|
128
|
+
| 选择中 | `Enter` | 打开详情浮层,关闭后回到选择 |
|
|
129
|
+
| 选择中 | `x` `x` | 第一次进入确认(红色竖标 + 错误底色,提示行变成 `press x again to stop`),第二次停止选中的 agent(会通知模型) |
|
|
130
|
+
| 确认中 | `↑` / `↓` | 取消确认并移动 |
|
|
131
|
+
| 确认中 | 其他任何键(`Esc`、`Enter`、打字) | 只取消确认,按键被吞掉,留在选择里 |
|
|
132
|
+
| 选择中 | `Esc` | 退出选择(**不会**中断主 agent) |
|
|
133
|
+
| 选择中 | 其他键 | 退出选择,按键照常进编辑器 |
|
|
134
|
+
| 详情浮层 | `↑↓` / `PgUp` `PgDn` / 滚轮、`e`、`x x`、`c`、`Esc` | 滚动、展开 prompt、停止、复制 `pi --session <对话记录>` 命令、关闭 |
|
|
135
|
+
| `/agents` 列表(底部) | `↑↓`、`Enter`、`x x`、`Esc` / `q` | 选择、在列表上方打开详情浮层(关闭后回到列表)、停止、关闭 |
|
|
136
|
+
|
|
137
|
+
列表和详情浮层里的确认规则和选择模式一样:移动键取消并移动,其他键只取消(`Esc` 不会顺带关掉列表或浮层)。
|
|
138
|
+
`confirmStop: false` 时 `x` 按一次就停。
|
|
139
|
+
| 全屏模式 | 点击 agent 行 / `+N more` | 打开详情浮层 / 底部列表 |
|
|
140
|
+
|
|
141
|
+
选择模式在这些情况下自动退出:没有 agent 行了、`/hud off`、编辑器里有文字、对话框或选择器拿走了键盘、30 秒没有按键。
|
|
142
|
+
|
|
143
|
+
## 开发
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
npm install
|
|
147
|
+
npm run check # tsc --noEmit + vitest
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
单元测试用假的子会话工厂,不调用模型;`src/child.integration.test.ts` 用真实的 pi SDK 加 pi-ai 的 faux provider
|
|
151
|
+
跑完整的子会话(工具集、system prompt、会话文件、轮数预算、abort、后台通知、`agent_send` 续话、`agent_stop`),全部在临时目录里,不碰 `~/.pi`。
|
|
152
|
+
全屏模式下的鼠标点击和真实 TUI 里的焦点行为只能手动验证(清单见 docs/08 §5)。
|
|
153
|
+
|
|
154
|
+
## 文档
|
|
155
|
+
|
|
156
|
+
| 文档 | 内容 |
|
|
157
|
+
|---|---|
|
|
158
|
+
| [DESIGN.md](./DESIGN.md) | 总览:目标、核心结论、架构、分阶段、不做什么、待定问题 |
|
|
159
|
+
| [docs/01-research.md](./docs/01-research.md) | 上游调研:Claude Code、codex、minimax-code、pi 官方 example、两个 pi-subagents |
|
|
160
|
+
| [docs/02-runtime.md](./docs/02-runtime.md) | 子会话运行时:同进程 SDK 会话、资源加载、扩展、模型、递归防护、abort |
|
|
161
|
+
| [docs/03-tools-and-prompts.md](./docs/03-tools-and-prompts.md) | 工具面(`agent` / `agent_send` / `agent_stop`)、返回格式、写给模型的规则 |
|
|
162
|
+
| [docs/04-agent-types.md](./docs/04-agent-types.md) | agent 类型定义:文件格式、发现、内置类型、能力只减不增 |
|
|
163
|
+
| [docs/05-context-and-results.md](./docs/05-context-and-results.md) | 上下文交接(fresh / fork)、结果回传、截断、不可信数据 |
|
|
164
|
+
| [docs/06-lifecycle-and-notify.md](./docs/06-lifecycle-and-notify.md) | 状态机、并发、后台、通知投递、持久化与恢复、清理 |
|
|
165
|
+
| [docs/07-ui.md](./docs/07-ui.md) | 工具卡片、通知渲染、pi-hud 里的 agent 行、↓ 键盘选择、鼠标点击、详情浮层、`/agents` |
|
|
166
|
+
| [docs/08-implementation.md](./docs/08-implementation.md) | 模块划分、实现清单、测试计划 |
|
|
167
|
+
|
|
168
|
+
## 许可
|
|
169
|
+
|
|
170
|
+
MIT
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
本插件属于 Shizuku 系列 pi 插件([pi-shizuku](https://github.com/AoShizuku/pi-shizuku)):共用的左栏、设计语言与跨插件约定见总仓库。贡献方式见 [CONTRIBUTING.md](CONTRIBUTING.md)。
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: explore
|
|
3
|
+
description: Read-only search. Finds code, traces call paths and reports file paths with line numbers. Cannot edit files or run commands.
|
|
4
|
+
tools: read, grep, find, ls, web_search, web_fetch
|
|
5
|
+
thinking: low
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
You are a read-only search agent. You can read files and search the codebase; you cannot edit files or run commands.
|
|
9
|
+
|
|
10
|
+
How to work:
|
|
11
|
+
- Start with grep and find to locate candidates, then read only the line ranges that matter. Follow imports and call sites when the task asks how something works.
|
|
12
|
+
- If web_search and web_fetch are available, use them only when the task needs information from outside the codebase, such as library documentation or an error message. Cite the URLs you relied on.
|
|
13
|
+
- Stop as soon as you can answer the task. Do not read files just to be thorough.
|
|
14
|
+
|
|
15
|
+
Report format:
|
|
16
|
+
1. The direct answer, in a few sentences.
|
|
17
|
+
2. Evidence: one line per location, as `path:start-end` followed by what is there. Quote code only when the exact lines matter, and keep quotes short.
|
|
18
|
+
3. What you could not find or are unsure about.
|
|
19
|
+
|
|
20
|
+
If the task requires editing files or running commands, reply with one line saying so and stop; the parent will use a different agent type.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: general
|
|
3
|
+
description: Same tools as you. Use for bounded tasks that change files or run commands.
|
|
4
|
+
tools: read, bash, edit, write, grep, find, ls, web_search, web_fetch
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
You have the same built-in tools as your parent. Complete the task end to end within its stated scope.
|
|
8
|
+
|
|
9
|
+
Before you finish:
|
|
10
|
+
- If the task changed code and the project has a relevant check (type check, tests, linter), run the narrowest one that covers your change.
|
|
11
|
+
- Re-read your diff for unintended edits.
|
|
12
|
+
|
|
13
|
+
Report format:
|
|
14
|
+
1. Outcome in one or two sentences: done, partly done, or blocked.
|
|
15
|
+
2. Files changed, one per line, with a short note on each.
|
|
16
|
+
3. Verification: the commands you ran and their results, and what you did not verify.
|
|
17
|
+
4. Anything the parent must decide or follow up on.
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@aoshizuku/pi-subagent",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"description": "Subagents for pi: delegate a bounded task to a fresh in-process session with its own context window",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"author": "AoShizuku",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/AoShizuku/pi-subagent.git"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/AoShizuku/pi-subagent#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/AoShizuku/pi-subagent/issues"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"pi-package",
|
|
19
|
+
"pi-extension",
|
|
20
|
+
"subagent",
|
|
21
|
+
"agent"
|
|
22
|
+
],
|
|
23
|
+
"pi": {
|
|
24
|
+
"extensions": [
|
|
25
|
+
"./src/index.ts"
|
|
26
|
+
]
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"src",
|
|
30
|
+
"!src/**/*.test.ts",
|
|
31
|
+
"agents"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"typecheck": "tsc --noEmit",
|
|
35
|
+
"test": "vitest run",
|
|
36
|
+
"check": "npm run typecheck && npm run test"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@earendil-works/pi-ai": "*",
|
|
40
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
41
|
+
"@earendil-works/pi-tui": "*",
|
|
42
|
+
"typebox": "*"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@earendil-works/pi-ai": "^1.5.0",
|
|
46
|
+
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
47
|
+
"@earendil-works/pi-tui": "^1.5.0",
|
|
48
|
+
"@types/node": "^22.0.0",
|
|
49
|
+
"typebox": "1.3.27",
|
|
50
|
+
"typescript": "^5.9.0",
|
|
51
|
+
"vitest": "^3.2.4"
|
|
52
|
+
},
|
|
53
|
+
"publishConfig": {
|
|
54
|
+
"access": "public"
|
|
55
|
+
}
|
|
56
|
+
}
|
package/src/batcher.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Coalesces finished items into as few model wake-ups as possible (docs/06 §5.3).
|
|
2
|
+
// Generic copy of pi-background-shell src/batcher.ts; change both together (docs/08 §2).
|
|
3
|
+
//
|
|
4
|
+
// Idle agent: the first finished item opens a fixed window (not a sliding debounce).
|
|
5
|
+
// Items finishing inside it join the same message. If nothing else is running there is
|
|
6
|
+
// nothing to wait for, so the batch goes out immediately.
|
|
7
|
+
//
|
|
8
|
+
// Busy agent: pi's steer queue hands the model one message per turn
|
|
9
|
+
// (steeringMode "one-at-a-time"), so N separate notifications would cost N turns.
|
|
10
|
+
// Finished items are held here and drained in one piece at the next turn boundary.
|
|
11
|
+
|
|
12
|
+
export interface BatcherDeps<T> {
|
|
13
|
+
isIdle(): boolean;
|
|
14
|
+
hasRunning(): boolean;
|
|
15
|
+
/** Deliver a batch while the agent is idle (starts a turn). */
|
|
16
|
+
deliverIdle(batch: T[]): void;
|
|
17
|
+
windowMs: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_WINDOW_MS = 3000;
|
|
21
|
+
|
|
22
|
+
/** Holds finished items until they can be delivered as a single notification. */
|
|
23
|
+
export class NotificationBatcher<T> {
|
|
24
|
+
private readonly deps: BatcherDeps<T>;
|
|
25
|
+
private pending: T[] = [];
|
|
26
|
+
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
27
|
+
|
|
28
|
+
constructor(deps: BatcherDeps<T>) {
|
|
29
|
+
this.deps = deps;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Number of items waiting for delivery. */
|
|
33
|
+
get size(): number {
|
|
34
|
+
return this.pending.length;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Queue a finished item and deliver now, later, or at the next turn boundary. */
|
|
38
|
+
enqueue(item: T): void {
|
|
39
|
+
this.pending.push(item);
|
|
40
|
+
if (!this.deps.isIdle()) return;
|
|
41
|
+
if (!this.deps.hasRunning()) {
|
|
42
|
+
this.flushIdle();
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
this.timer ??= setTimeout(() => this.onWindowEnd(), this.deps.windowMs);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Remove and return everything pending; used at turn boundaries while the agent is busy. */
|
|
49
|
+
take(): T[] {
|
|
50
|
+
this.clearTimer();
|
|
51
|
+
const batch = this.pending;
|
|
52
|
+
this.pending = [];
|
|
53
|
+
return batch;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Deliver everything pending through the idle path right away. */
|
|
57
|
+
flushIdle(): void {
|
|
58
|
+
const batch = this.take();
|
|
59
|
+
if (batch.length > 0) this.deps.deliverIdle(batch);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Drop pending items and timers without delivering. */
|
|
63
|
+
dispose(): void {
|
|
64
|
+
this.take();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private onWindowEnd(): void {
|
|
68
|
+
this.timer = undefined;
|
|
69
|
+
// A busy agent picks the batch up at its next turn boundary instead.
|
|
70
|
+
if (this.deps.isIdle()) this.flushIdle();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private clearTimer(): void {
|
|
74
|
+
if (this.timer) clearTimeout(this.timer);
|
|
75
|
+
this.timer = undefined;
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/child.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// Real child sessions: in-process pi SDK sessions (docs/02 §2-§6).
|
|
2
|
+
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
type AgentSession,
|
|
7
|
+
createAgentSession,
|
|
8
|
+
DefaultResourceLoader,
|
|
9
|
+
getAgentDir,
|
|
10
|
+
type LoadExtensionsResult,
|
|
11
|
+
type ModelRegistry,
|
|
12
|
+
ModelRuntime,
|
|
13
|
+
SessionManager,
|
|
14
|
+
SettingsManager,
|
|
15
|
+
} from "@earendil-works/pi-coding-agent";
|
|
16
|
+
|
|
17
|
+
import { appendSystemPrompt } from "./prompts.js";
|
|
18
|
+
import type { ChildSession, ChildSessionFactory, ChildSpec } from "./run.js";
|
|
19
|
+
import { activeChildTools } from "./types.js";
|
|
20
|
+
|
|
21
|
+
/** Never available to a child, whatever its type lists (docs/02 §6). */
|
|
22
|
+
export const SELF_TOOLS = ["agent", "agent_send", "agent_stop", "ask_user_question"];
|
|
23
|
+
|
|
24
|
+
export interface ChildFactoryOptions {
|
|
25
|
+
/** The parent's registry (ctx.modelRegistry), source of runtime-registered providers. */
|
|
26
|
+
parentRegistry: ModelRegistry;
|
|
27
|
+
/** Default: getAgentDir() (~/.pi/agent, or PI_CODING_AGENT_DIR). */
|
|
28
|
+
agentDir?: string;
|
|
29
|
+
/** Extensions a child may load (docs/02 §5.2); read on every create so /agents reload applies. */
|
|
30
|
+
childExtensions?: () => readonly string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Never loaded into a child, whatever the allowlist says (docs/02 §5.2). */
|
|
34
|
+
export const DENIED_EXTENSIONS = ["pi-subagent", "pi-ask-user", "pi-autotitle", "pi-hud", "pi-bettertui", "pi-background-shell"];
|
|
35
|
+
|
|
36
|
+
interface ExtensionLike {
|
|
37
|
+
path: string;
|
|
38
|
+
resolvedPath: string;
|
|
39
|
+
sourceInfo: { source: string; baseDir?: string };
|
|
40
|
+
tools: Map<string, unknown>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function normalize(path: string): string {
|
|
44
|
+
return path.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function segments(ext: ExtensionLike): string[] {
|
|
48
|
+
return [ext.path, ext.resolvedPath, ext.sourceInfo.baseDir ?? "", ext.sourceInfo.source].flatMap((text) => normalize(text).split(/[/:@]/));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Does an allowlist entry name this extension? An entry is a package name (matched against the path segments
|
|
53
|
+
* and the package source, e.g. `npm:pi-foo`) or a path (matched as a prefix of the extension's paths).
|
|
54
|
+
*/
|
|
55
|
+
export function extensionMatches(ext: ExtensionLike, entry: string): boolean {
|
|
56
|
+
const wanted = normalize(entry.trim());
|
|
57
|
+
if (!wanted) return false;
|
|
58
|
+
if (/[/]/.test(wanted) && !wanted.startsWith("@")) {
|
|
59
|
+
return [ext.path, ext.resolvedPath, ext.sourceInfo.baseDir ?? "", ext.sourceInfo.source].some((path) => {
|
|
60
|
+
const candidate = normalize(path);
|
|
61
|
+
return candidate === wanted || candidate.startsWith(`${wanted}/`);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
const source = normalize(ext.sourceInfo.source);
|
|
65
|
+
if (source === wanted || source === `npm:${wanted}` || source.endsWith(`/${wanted}`)) return true;
|
|
66
|
+
// Scoped names (@scope/name) compare as consecutive segments.
|
|
67
|
+
const parts = wanted.split("/");
|
|
68
|
+
const all = segments(ext);
|
|
69
|
+
return all.some((_, index) => parts.every((part, offset) => all[index + offset] === part.replace(/^@/, "")));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Keep allowlisted extensions, minus the denied ones; also returns the tool names they register. */
|
|
73
|
+
export function filterExtensions<T extends ExtensionLike>(extensions: readonly T[], allowlist: readonly string[]): { kept: T[]; tools: string[] } {
|
|
74
|
+
const kept = extensions.filter(
|
|
75
|
+
(ext) => allowlist.some((entry) => extensionMatches(ext, entry)) && !DENIED_EXTENSIONS.some((name) => extensionMatches(ext, name)),
|
|
76
|
+
);
|
|
77
|
+
return { kept, tools: [...new Set(kept.flatMap((ext) => [...ext.tools.keys()]))] };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Copy providers that extensions registered at runtime (pi.registerProvider) into the child's runtime;
|
|
82
|
+
* they are not in models.json, so a fresh runtime would not know them (docs/02 §3).
|
|
83
|
+
* ModelRegistry keeps its runtime private (model-registry.ts:49), so the parent runtime cannot be shared.
|
|
84
|
+
*/
|
|
85
|
+
export function replayProviders(parent: ModelRegistry, child: ModelRuntime): void {
|
|
86
|
+
for (const id of parent.getRegisteredProviderIds()) {
|
|
87
|
+
const native = parent.getRegisteredNativeProvider(id);
|
|
88
|
+
if (native) {
|
|
89
|
+
child.registerNativeProvider(native);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const config = parent.getRegisteredProviderConfig(id);
|
|
93
|
+
if (config) child.registerProvider(id, config);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function createChildSessionFactory(options: ChildFactoryOptions): ChildSessionFactory {
|
|
98
|
+
return {
|
|
99
|
+
async create(spec) {
|
|
100
|
+
return wrapSession(await createChildAgentSession(spec, options));
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function createChildAgentSession(spec: ChildSpec, options: ChildFactoryOptions): Promise<AgentSession> {
|
|
106
|
+
const agentDir = options.agentDir ?? getAgentDir();
|
|
107
|
+
const modelRuntime = await ModelRuntime.create({
|
|
108
|
+
authPath: join(agentDir, "auth.json"),
|
|
109
|
+
modelsPath: join(agentDir, "models.json"),
|
|
110
|
+
});
|
|
111
|
+
replayProviders(options.parentRegistry, modelRuntime);
|
|
112
|
+
|
|
113
|
+
const settingsManager = SettingsManager.create(spec.cwd, agentDir);
|
|
114
|
+
const allowlist = options.childExtensions?.() ?? [];
|
|
115
|
+
// Tools registered by allowlisted extensions; a tools allowlist would otherwise leave them inactive (sdk.ts:72-87).
|
|
116
|
+
let extensionTools: string[] = [];
|
|
117
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
118
|
+
cwd: spec.cwd,
|
|
119
|
+
agentDir,
|
|
120
|
+
settingsManager,
|
|
121
|
+
// Default: no extensions at all. With an allowlist, pi loads the configured extensions and the
|
|
122
|
+
// override keeps only the allowed ones (resource-loader.ts:323, :628).
|
|
123
|
+
noExtensions: allowlist.length === 0,
|
|
124
|
+
...(allowlist.length > 0
|
|
125
|
+
? {
|
|
126
|
+
extensionsOverride: (base: LoadExtensionsResult): LoadExtensionsResult => {
|
|
127
|
+
const { kept, tools } = filterExtensions(base.extensions, allowlist);
|
|
128
|
+
extensionTools = tools;
|
|
129
|
+
return { ...base, extensions: kept };
|
|
130
|
+
},
|
|
131
|
+
}
|
|
132
|
+
: {}),
|
|
133
|
+
noPromptTemplates: true,
|
|
134
|
+
noThemes: true,
|
|
135
|
+
noSkills: !spec.type.skills,
|
|
136
|
+
noContextFiles: !spec.type.contextFiles,
|
|
137
|
+
// Append only: a custom system prompt would drop pi's tools/rules sections (system-prompt.ts:152-169).
|
|
138
|
+
appendSystemPrompt: appendSystemPrompt(spec.type),
|
|
139
|
+
});
|
|
140
|
+
await resourceLoader.reload();
|
|
141
|
+
// The context limit ends a long run with a report instead (docs/02 §9). A compaction rewrites the context,
|
|
142
|
+
// which costs a full uncached prefill, and summarizes away details of the task. The override lives in memory
|
|
143
|
+
// only and is never saved; it must follow resourceLoader.reload(), which re-reads the settings files. Only a
|
|
144
|
+
// settings write or /reload would drop it again, and a child session does neither.
|
|
145
|
+
settingsManager.applyOverrides({ compaction: { enabled: false } });
|
|
146
|
+
|
|
147
|
+
// agent_send to a finished agent reopens its transcript; the session restores the full history (docs/06 §6).
|
|
148
|
+
const sessionManager = spec.resumeFile
|
|
149
|
+
? SessionManager.open(spec.resumeFile, spec.sessionDir, spec.cwd)
|
|
150
|
+
: spec.sessionDir
|
|
151
|
+
? SessionManager.create(spec.cwd, spec.sessionDir, { parentSession: spec.parentSessionFile })
|
|
152
|
+
: SessionManager.inMemory(spec.cwd, { parentSession: spec.parentSessionFile });
|
|
153
|
+
|
|
154
|
+
// Prefer the child runtime's model object; fall back to the parent's (e.g. a virtual model, which cannot be replayed).
|
|
155
|
+
const model = spec.model
|
|
156
|
+
? (modelRuntime.getModel(spec.model.provider, spec.model.id) ?? options.parentRegistry.find(spec.model.provider, spec.model.id))
|
|
157
|
+
: undefined;
|
|
158
|
+
|
|
159
|
+
const { session } = await createAgentSession({
|
|
160
|
+
cwd: spec.cwd,
|
|
161
|
+
agentDir,
|
|
162
|
+
modelRuntime,
|
|
163
|
+
model,
|
|
164
|
+
thinkingLevel: spec.thinking,
|
|
165
|
+
// Only tools the type lists; an extension tool also needs its extension in the allowlist (docs/04 §4).
|
|
166
|
+
tools: activeChildTools(spec.type.tools, extensionTools),
|
|
167
|
+
excludeTools: SELF_TOOLS,
|
|
168
|
+
resourceLoader,
|
|
169
|
+
sessionManager,
|
|
170
|
+
settingsManager,
|
|
171
|
+
});
|
|
172
|
+
try {
|
|
173
|
+
// Usually no extensions are loaded; binding keeps the same lifecycle as other SDK sessions.
|
|
174
|
+
await session.bindExtensions({ mode: "print" });
|
|
175
|
+
if (!spec.resumeFile) session.setSessionName(spec.description);
|
|
176
|
+
} catch (error) {
|
|
177
|
+
session.dispose();
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
return session;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function wrapSession(session: AgentSession): ChildSession {
|
|
184
|
+
let disposed = false;
|
|
185
|
+
return {
|
|
186
|
+
get sessionFile() {
|
|
187
|
+
return session.sessionFile;
|
|
188
|
+
},
|
|
189
|
+
get model() {
|
|
190
|
+
const model = session.model;
|
|
191
|
+
return model ? `${model.provider}/${model.id}` : undefined;
|
|
192
|
+
},
|
|
193
|
+
get messages() {
|
|
194
|
+
return session.messages;
|
|
195
|
+
},
|
|
196
|
+
contextUsage: () => session.getContextUsage(),
|
|
197
|
+
subscribe: (listener) => session.subscribe(listener),
|
|
198
|
+
prompt: (text) => session.prompt(text, { expandPromptTemplates: false }),
|
|
199
|
+
abort: () => session.abort(),
|
|
200
|
+
steer: (customType, content) => {
|
|
201
|
+
void session.sendCustomMessage({ customType, content, display: false }, { deliverAs: "steer" }).catch(() => {});
|
|
202
|
+
},
|
|
203
|
+
steerUser: async (text) => {
|
|
204
|
+
await session.steer(text);
|
|
205
|
+
},
|
|
206
|
+
dispose: () => {
|
|
207
|
+
if (disposed) return;
|
|
208
|
+
disposed = true;
|
|
209
|
+
session.dispose();
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
package/src/cleanup.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Removes child session directories of other parent sessions after the retention period (docs/06 §8).
|
|
2
|
+
|
|
3
|
+
import { readdir, rm, stat } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
export const DAY_MS = 24 * 60 * 60 * 1000;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Delete `<root>/<parentId>/` directories (child transcripts and result files) whose newest file is older
|
|
10
|
+
* than `maxAgeMs`. The current parent's directory is never touched. Best effort: every filesystem error is
|
|
11
|
+
* ignored. Returns the number of directories removed.
|
|
12
|
+
*/
|
|
13
|
+
export async function cleanupOldSessions(root: string, currentParentId: string, maxAgeMs: number, now = Date.now()): Promise<number> {
|
|
14
|
+
let removed = 0;
|
|
15
|
+
const dirs = await readdir(root, { withFileTypes: true }).catch(() => []);
|
|
16
|
+
for (const entry of dirs) {
|
|
17
|
+
if (!entry.isDirectory() || entry.name === currentParentId) continue;
|
|
18
|
+
const dir = join(root, entry.name);
|
|
19
|
+
const newest = await newestMtime(dir);
|
|
20
|
+
if (newest === undefined || now - newest <= maxAgeMs) continue;
|
|
21
|
+
await rm(dir, { recursive: true, force: true }).then(
|
|
22
|
+
() => removed++,
|
|
23
|
+
() => {},
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
return removed;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Newest mtime of the directory itself and the files directly inside it. */
|
|
30
|
+
async function newestMtime(dir: string): Promise<number | undefined> {
|
|
31
|
+
const own = await stat(dir).catch(() => undefined);
|
|
32
|
+
if (!own) return undefined;
|
|
33
|
+
let newest = own.mtimeMs;
|
|
34
|
+
const names = await readdir(dir).catch(() => [] as string[]);
|
|
35
|
+
for (const name of names) {
|
|
36
|
+
const info = await stat(join(dir, name)).catch(() => undefined);
|
|
37
|
+
if (info) newest = Math.max(newest, info.mtimeMs);
|
|
38
|
+
}
|
|
39
|
+
return newest;
|
|
40
|
+
}
|