pi-sub-view 0.0.0-stage → 0.5.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xuqianhui
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,143 @@
1
- # Temporary Holding Version
1
+ # pi-sub-view —— 子代理会话的只读实时渲染窗
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给 pi-subagents 的子代理补一个 fabric 式的「实时看内容」窗口:**不起第二个 pi 进程、不写会话文件、不占 lease**,
4
+ 只 tail 子代理自己的 `session.jsonl` 并按 pi 的对话结构渲染(user / assistant / thinking / toolCall / toolResult),
5
+ 存活期间也能看。
6
+
7
+ ## 为什么不能直接 `pi --session <child>`
8
+
9
+ - 运行中的子会话文件正被 runner 进程 append 写(pi 用 `appendFileSync`,一次一条 entry);
10
+ - 再开一个 pi 打开同一会话 = 两个写者,撞 canonical-session/runner 的 lease 语义(pi-subagents 的
11
+ `process-terminal`/lease 证明就是防这个),而且子代理的会话树会被污染。
12
+
13
+ 只读 tail 没有这个问题:文件是 **append-only**,读方按字节偏移增量读;写方 compaction/fork 时整文件重写,
14
+ 读方检测 inode 变化 / size 回退后从头重放(已实现)。
15
+
16
+ ## 安装
17
+
18
+ ```bash
19
+ npm i -g pi-sub-view # 或:npx pi-sub-view --help(未发布时用本地路径)
20
+ # 本机(开发态):~/.pi/agent/bin/pi-sub-view -> ~/pi-plugins/pi-sub-view/view.mjs
21
+ ```
22
+
23
+ 纯 CLI、零依赖(node ≥ 20),不起 pi 进程、不占 pi-subagents 的 lease;`files` 白名单只打
24
+ `view.mjs + lib/ + extensions/ + README/LICENSE`(`npm pack --dry-run` 10 个文件 ~30 KB)。
25
+
26
+ 0.5.0 起同一个包还提供一个 **pi 扩展**(`pi.extensions` → `extensions/inspector.js`),把「终端 inspector 后端」
27
+ 注册给 pi-subagents(见下节)。本地开发态装法二选一:
28
+
29
+ ```bash
30
+ pi install ~/pi-plugins/pi-sub-view # npm/包形态:pi 读 package.json 的 pi.extensions
31
+ ln -s ~/pi-plugins/pi-sub-view ~/.pi/agent/extensions/pi-sub-view # ambient 形态(本机现状)
32
+ ```
33
+
34
+ ## 用法
35
+
36
+ ```bash
37
+ # 看(S1/S3/S4)
38
+ pi-sub-view # 最近一个子代理会话,实时跟随
39
+ pi-sub-view 2f538878 # runId 前缀(子代理 run id)
40
+ pi-sub-view --list 10 # 列最近 10 个(age / run / agent / state / model / 大小 / 路径)
41
+ pi-sub-view --finished 20 # 只看已结束(run 已终态或文件静默 > 60s)
42
+ pi-sub-view --roster # 当前父会话下的子代理 roster(▶ 标当前,键 n/p 切换用)
43
+ pi-sub-view --file <session.jsonl> [--once] [--full] [--lines N] [--system]
44
+
45
+ # 说(S2;复用 pi-subagents 的 steer 文件通道,source=pi-sub-view)
46
+ pi-sub-view --send "改做 B 方案" --run 2f538878 [--mode steer|follow_up|auto] [--index N]
47
+ pi-sub-view --send "..." --file <child session.jsonl> # 自动对上 async run
48
+ pi-sub-view --send "..." --dir <asyncDir> --receipts 60 # 等回执(status.json 账本)
49
+
50
+ # 从 pi-sub-session 走(按 runId/子串解析路径):
51
+ pi-sub-session --live 2f538878 # 当前终端前台跟随
52
+ pi-sub-session --live-window 2f538878 # tmux 分屏 / ptyxis 新标签
53
+ ```
54
+
55
+ 通用选项:`--once`(渲染完就退)、`--full`(不截断工具输出/思考)、`--lines N`(每条工具输出行数,默认 12)、
56
+ `--system`、`--no-color`、`--no-title`、`--json`(list/roster 出 JSON)、`--keys/--no-keys`。
57
+
58
+ S5 渲染件(2026-12-04):
59
+
60
+ ```bash
61
+ pi-sub-view --search 'toolResult|verdict' [-i] # 命中行整行高亮(--no-color 用 '>> ' 前缀),末尾报 matches: N lines
62
+ pi-sub-view --header # 头栏:runId8 · agent · model · 轮/工具 · tok · $cost · state
63
+ # --once 在末尾打(数字准);跟随模式开头打(计数从 0 起,live 看标题栏)
64
+ pi-sub-view --no-diff # 关掉 edit 的 diff 渲染,回纯摘要(输出与 0.3.0 逐字节一致)
65
+ ```
66
+
67
+ 空正则/非法正则报明确错误并 exit 1;`--search` 只影响显示,不改会话文件。
68
+
69
+ ## 交互
70
+
71
+ 纯输出流(不进 alternate screen),所以滚动 = 终端自己的 scrollback / 鼠标滚轮。
72
+
73
+ | 键 | 作用 |
74
+ |---|---|
75
+ | `n` / `]` / Tab | 切到同一父会话的下一个子代理(reset + 重放该会话) |
76
+ | `p` / `[` | 上一个 |
77
+ | `s` | 给当前子代理发 steer(Enter 发送 / 空行取消,回执实时打印) |
78
+ | `r` | 重载 roster |
79
+ | `q` / `Ctrl-C` | 退出(打印统计:轮数 / 工具次数 / token / 跟随时长) |
80
+
81
+ 终端标题实时显示 `sub:<runId8> · 运行中|静默 Ns · Nt · N▸ · tok`。
82
+
83
+ ## 发言通道(S2)
84
+
85
+ - 只走 pi-subagents 既有文件路由:`<asyncDir>/control/steer-requests/<ts>-<base64url(id)>.json`;
86
+ `steer-inbox-closed.json` 存在即拒绝(与上游同一判据),写完复查、中途关闭则撤回。
87
+ - **来源可区分**:请求带 `source: "pi-sub-view"`,落在 `status.json` 的 `steering.recent[].source`
88
+ 与逐 target 状态(`scheduled/routed/queued/delivered/failed/late`)里;父进程的工具 steer 不带该字段。
89
+ - 回执照 `status.json` 账本轮询打印:`[viewer] receipt #0=delivered` → `[viewer] 已送达`。
90
+ - 限额与上游一致:消息 ≤ 128 KiB、`mode ∈ {steer,follow_up,auto}`、`targetIndex` 非负整数。
91
+
92
+ ## Fleet 里的 Enter/H:终端 inspector 后端(S6,0.5.0)
93
+
94
+ pi-subagents 的 `/subagents-fleet` → `Enter`/`H` 走 Inspect 插件链(内置 herdr → ghostty → tmux → 外注册)。
95
+ 本机只有 ptyxis、平时又不在 tmux 里,所以此前会报 `No inspector plugin is available`。本包的扩展补上这一段:
96
+
97
+ - 插件名 `pi-sub-view`,用官方事件 `pi-subagents:inspector-register:v1` 注册(**不 import pi-subagents**,没装就静默);
98
+ - `available` 只做探测、**绝不 spawn**:要求存在图形会话(`WAYLAND_DISPLAY`/`DISPLAY`)+ 认得的终端;
99
+ - 支持 ptyxis / gnome-terminal / kgx / kitty / foot / wezterm / alacritty / konsole / xfce4-terminal / x-terminal-emulator
100
+ (优先级即此顺序),argv 数组拼接、不经 shell,标题 `sub:<runId 前 8 位>`,cwd 用 run 的 `status.cwd`;
101
+ - `open` 默认**逐字保真**上游给的 `launch.executable + launch.argv`(所以 pane 里的 steer/stop 与内置一致);
102
+ - 想在自己的渲染器里看:`export PI_SUB_VIEW_INSPECTOR=viewer` ⇒ 改成 `node view.mjs --file <steps[index].sessionFile>`;
103
+ - 只开不关:不写绑定,`owns()` 恒 `false`,因此 `inspector.status/close` 明确报「不支持」(与内置 Ghostty 同形态);
104
+ - 无图形会话(headless / CI)时 `available:false`,Fleet 仍按原逻辑报没有插件。
105
+
106
+ ```bash
107
+ # 现场验证(需要图形会话;无人值守轮不建窗)
108
+ pi # 跑一个后台子代理后:/subagents-fleet → Enter → H
109
+ ```
110
+
111
+ ## 渲染口径
112
+
113
+ | entry | 显示 |
114
+ |---|---|
115
+ | `user` | `▌ user` + 全文 |
116
+ | `assistant` | `● assistant · 模型/用量/费用`,text 全文、`✳ thinking` 默认 4 行、`▸ toolName 参数摘要` |
117
+ | `toolResult` | `⎿ toolName · 耗时 · +N lines` + 首 N 行(`isError` 红色 `⎿ !`) |
118
+ | `model_change` / `session_info` / `label` / `compaction` | 单行 dim |
119
+ | `toolCall` = `edit` / `multi_edit`(或参数含 oldText+newText) | 先打 `▸ edit` 摘要,再逐对渲染行级 diff:`-` 红 / `+` 绿 / 上下文 ±2 行,跳过段折成 `⋯ N lines`(`--no-diff` 关) |
120
+
121
+ ## 已知边界
122
+
123
+ - 渲染面只读;**唯一写入口**是 `lib/steer.mjs` 写 `control/steer-requests/`(不碰会话/事件文件,gate A2 机检);
124
+ - roster 只覆盖「同一父会话下的子代理」(跨项目的全局仍用 `--list`);
125
+ - 文件重写(compaction)会整段重放,滚动区里会出现重复内容(流式输出的固有限制,不清屏);
126
+ - 已结束的 run 若 `asyncDir` 已被回收 ⇒ 只剩会话文件,`--send` 会明确报错(不能 steer 终态 run)。
127
+ - inspector 后端只开不关(无 status/close);新 tab 里 Ctrl-C/关窗即可,关窗不影响子代理继续跑;
128
+ - `PI_SUB_VIEW_INSPECTOR=viewer` 需要 run 的 `status.steps[index].sessionFile`,旧 run 缺字段时明确 isError、不 spawn。
129
+
130
+ ## 验收
131
+
132
+ ```bash
133
+ bash ~/pi-plugins/.pi/plans/pi-sub-view/gate.sh # 0 过 / 1 挂 / 77 诚实 SKIP
134
+ ```
135
+ A1–A7 覆盖渲染/性能/跟随/重写/无写入;A8–A11 覆盖 `--search`(含反向 0 命中、非法正则 exit 1)、edit diff(含 old==new 反向控制)、
136
+ `--header`(含默认无头栏反向控制)、`--no-diff` 字节兼容;C1 覆盖打包面(package.json 字段 + `npm pack --dry-run` 清单);B1–B6 覆盖 roster、steer 协议(用**上游自己的消费者**读回)、
137
+ closed-inbox 拒绝、回执、pty 键控切换、已结束浏览;D1–D6 覆盖 S6 终端 inspector 后端(规划真值表、注册协议、
138
+ 探测零 spawn、open 命令、本机探测)。`npm test` 另有 18 条纯函数用例(零 GUI、零真实 spawn)。
139
+
140
+ ## 相关
141
+
142
+ - `~/.pi/agent/bin/pi-sub-session`(`--live` / `--live-window` 入口,兼有 `--open` 用完整 pi TUI 看**已结束**的会话)
143
+ - `~/.pi/agent/npm/node_modules/pi-subagents/docs/observability.md`(FleetView / fleet inspector / Inspect plugin)
@@ -0,0 +1,56 @@
1
+ // pi 扩展:把本仓的终端 inspector 后端注册给 pi-subagents(Fleet 的 Enter/H)。
2
+ //
3
+ // 走上游同步事件 pi-subagents:inspector-register:v1,request = { version:1, plugin },
4
+ // 结果回填 request.result;这里刻意不 import pi-subagents,没装时事件无人监听、静默跳过。
5
+ // 会话切换时先撤销旧注册再重新注册(dispose 幂等);关闭时清理函数里解绑并 dispose。
6
+ import { createViewerInspectorPlugin } from "../lib/inspector-plugin.mjs";
7
+
8
+ const REGISTER_EVENT = "pi-subagents:inspector-register:v1";
9
+
10
+ export default function inspectorExtension(pi) {
11
+ const plugin = createViewerInspectorPlugin();
12
+ let registration;
13
+ let closed = false;
14
+
15
+ // 撤销当前注册(上游 registration.dispose 本身幂等,这里再加一层保险)。
16
+ function dropRegistration() {
17
+ const current = registration;
18
+ registration = undefined;
19
+ try {
20
+ current?.dispose();
21
+ } catch {
22
+ // dispose 失败不应拖垮会话
23
+ }
24
+ }
25
+
26
+ function register() {
27
+ if (closed) return;
28
+ dropRegistration();
29
+ const request = { version: 1, plugin };
30
+ try {
31
+ pi.events.emit(REGISTER_EVENT, request);
32
+ } catch (cause) {
33
+ console.warn(`pi-sub-view: inspector registration failed: ${cause instanceof Error ? cause.message : String(cause)}`);
34
+ return;
35
+ }
36
+ // 没有 pi-subagents 监听:静默跳过,不影响其它扩展。
37
+ if (!request.result) return;
38
+ if (!request.result.ok) {
39
+ const reason = request.result.error;
40
+ console.warn(`pi-sub-view: inspector registration failed: ${reason instanceof Error ? reason.message : String(reason)}`);
41
+ return;
42
+ }
43
+ registration = request.result.registration;
44
+ }
45
+
46
+ const offSessionStart = pi.on("session_start", register);
47
+ const offSessionShutdown = pi.on("session_shutdown", dropRegistration);
48
+
49
+ return () => {
50
+ if (closed) return;
51
+ closed = true;
52
+ offSessionStart?.();
53
+ offSessionShutdown?.();
54
+ dropRegistration();
55
+ };
56
+ }
@@ -0,0 +1,164 @@
1
+ // pi-subagents 外注册 inspector 插件:非 tmux 的图形终端(ptyxis/GNOME 等)里打开只读 view.mjs。
2
+ //
3
+ // 契约(PLAN §8.2 与 pi-subagents docs/extension-api.md §Register an external inspector):
4
+ // plugin = { name, available(ctx), owns(ctx), open(ctx, launch, params) },无 status/close。
5
+ // - available/owns 绝不 spawn;只有 open 才启动进程。
6
+ // - 默认命令 = launch.executable + launch.argv(协议保真:steer/stop 仍由 Fleet 提供)。
7
+ // - PI_SUB_VIEW_INSPECTOR=viewer 时改用本仓 view.mjs --file <steps[index].sessionFile>。
8
+ // - 返回值与内置插件同形:{ content:[{type:"text",text}], details:{ mode:"management", results:[] } }。
9
+ import path from "node:path";
10
+ import { spawn as nodeSpawn } from "node:child_process";
11
+ import { fileURLToPath } from "node:url";
12
+ import { detectTerminal, planTerminalLaunch } from "./terminal.mjs";
13
+
14
+ const VIEW_MJS = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "view.mjs");
15
+ const OPEN_TIMEOUT_MS = 15_000;
16
+
17
+ /** 与内置插件一致的最小结果包装。 */
18
+ function result(text, isError = false) {
19
+ const response = {
20
+ content: [{ type: "text", text }],
21
+ details: { mode: "management", results: [] },
22
+ };
23
+ if (isError) response.isError = true;
24
+ return response;
25
+ }
26
+
27
+ function errorMessage(cause) {
28
+ return cause instanceof Error ? cause.message : String(cause);
29
+ }
30
+
31
+ /** 起一个 detached 子进程并等到它真正 spawn;15 s 超时或 ctx.signal 中止都会杀掉它并报错。 */
32
+ function launchDetached(spawn, executable, argv, { cwd, signal, timeoutMs = OPEN_TIMEOUT_MS }) {
33
+ return new Promise((resolve, reject) => {
34
+ if (signal?.aborted) {
35
+ reject(new Error("inspector open was aborted"));
36
+ return;
37
+ }
38
+ let child;
39
+ let settled = false;
40
+ const finish = (error) => {
41
+ if (settled) return;
42
+ settled = true;
43
+ clearTimeout(timer);
44
+ signal?.removeEventListener?.("abort", onAbort);
45
+ if (error) {
46
+ try {
47
+ child?.kill();
48
+ } catch {
49
+ // 子进程可能根本没起来,忽略 kill 失败
50
+ }
51
+ reject(error);
52
+ return;
53
+ }
54
+ resolve();
55
+ };
56
+ const onAbort = () => finish(new Error("inspector open was aborted"));
57
+ const timer = setTimeout(() => finish(new Error(`inspector launch timed out after ${timeoutMs} ms`)), timeoutMs);
58
+ signal?.addEventListener?.("abort", onAbort, { once: true });
59
+ // 检查与注册之间的取消窗口:刚订阅完再确认一次,否则已中止的 signal 永远等不到事件。
60
+ if (signal?.aborted) {
61
+ finish(new Error("inspector open was aborted"));
62
+ return;
63
+ }
64
+ try {
65
+ child = spawn(executable, argv, { cwd, detached: true, stdio: "ignore" });
66
+ } catch (cause) {
67
+ finish(cause instanceof Error ? cause : new Error(String(cause)));
68
+ return;
69
+ }
70
+ child.once("error", (cause) => finish(cause instanceof Error ? cause : new Error(String(cause))));
71
+ child.once("spawn", () => {
72
+ child.unref?.();
73
+ finish();
74
+ });
75
+ });
76
+ }
77
+
78
+ const NODE_BASENAME = /^node(js)?(\.exe)?$/i;
79
+
80
+ /** viewer 模式下挑一个真正的 node 执行器:compiled/bun 版 pi 的 process.execPath 不是 node,直接用会把脚本当 prompt。 */
81
+ export function nodeExecutable(launch) {
82
+ const candidates = [launch?.executable, process.execPath];
83
+ for (const candidate of candidates) {
84
+ if (typeof candidate === "string" && candidate !== "" && NODE_BASENAME.test(path.basename(candidate))) return candidate;
85
+ }
86
+ return undefined;
87
+ }
88
+
89
+ /** viewer 模式下取子会话 sessionFile:params.index → ctx.target.index → 0。 */
90
+ function viewerSessionFile(context, params) {
91
+ const index = params?.index ?? context.target?.index ?? 0;
92
+ const steps = context.target?.status?.steps;
93
+ const step = Array.isArray(steps) ? steps[index] : undefined;
94
+ return typeof step?.sessionFile === "string" && step.sessionFile ? step.sessionFile : undefined;
95
+ }
96
+
97
+ export function createViewerInspectorPlugin(deps = {}) {
98
+ const defaultEnv = deps.env ?? process.env;
99
+ const platform = deps.platform ?? process.platform;
100
+ const hasBinary = deps.hasBinary;
101
+ const spawn = deps.spawn ?? nodeSpawn;
102
+ const openTimeoutMs = deps.timeoutMs ?? OPEN_TIMEOUT_MS;
103
+ const defaultCwd = deps.cwd ?? process.cwd();
104
+
105
+ function plan(context, launch, params) {
106
+ const env = context.env ?? defaultEnv;
107
+ const cwd = context.target?.status?.cwd ?? defaultCwd;
108
+ const title = typeof context.target?.runId === "string" ? `sub:${context.target.runId.slice(0, 8)}` : undefined;
109
+ // 模式开关优先读动作上下文 env,其次读构造时的 env;测试/现场两种注入方式都成立。
110
+ const mode = context.env?.PI_SUB_VIEW_INSPECTOR ?? defaultEnv.PI_SUB_VIEW_INSPECTOR;
111
+ let command;
112
+ let viaViewer = false;
113
+ if (mode === "viewer") {
114
+ const sessionFile = viewerSessionFile(context, params);
115
+ if (!sessionFile) return { error: "viewer inspector mode requires ctx.target.status.steps[index].sessionFile" };
116
+ const executable = nodeExecutable(launch);
117
+ if (!executable) return { error: "viewer inspector mode requires a node executable (launch.executable / process.execPath)" };
118
+ command = { executable, argv: [VIEW_MJS, "--file", sessionFile] };
119
+ viaViewer = true;
120
+ } else {
121
+ command = { executable: launch.executable, argv: launch.argv };
122
+ }
123
+ const planResult = planTerminalLaunch({
124
+ env,
125
+ command,
126
+ hasBinary,
127
+ platform,
128
+ cwd,
129
+ title,
130
+ });
131
+ return { plan: planResult, cwd, viaViewer, focus: params?.focus === true };
132
+ }
133
+
134
+ return {
135
+ name: "pi-sub-view",
136
+ available(context) {
137
+ // 只做探测:此处任何分支都不得 spawn(gate D3 会数 spawn 次数)。
138
+ const env = context.env ?? defaultEnv;
139
+ return detectTerminal(env, { hasBinary, platform }) !== undefined;
140
+ },
141
+ owns() {
142
+ // 不在磁盘上写绑定,因此永远不"拥有"某个 inspector 绑定。
143
+ return false;
144
+ },
145
+ async open(context, launch, params = {}) {
146
+ const prepared = plan(context, launch, params);
147
+ if (prepared.error) return result(`pi-sub-view inspector error: ${prepared.error}`, true);
148
+ const { plan: launchPlan, cwd } = prepared;
149
+ if (!launchPlan.available) {
150
+ return result(`pi-sub-view inspector error: ${launchPlan.reason}`, true);
151
+ }
152
+ try {
153
+ await launchDetached(spawn, launchPlan.terminal.bin, launchPlan.argv, { cwd, signal: context.signal, timeoutMs: openTimeoutMs });
154
+ } catch (cause) {
155
+ return result(`pi-sub-view inspector error: ${errorMessage(cause)}`, true);
156
+ }
157
+ const runId = context.target?.runId ?? "(unknown run)";
158
+ const target = prepared.viaViewer ? "read-only viewer" : "inspector";
159
+ // --tab / --new-window 的焦点归属由终端方言决定;focus:false 时如实说明不能保证不抢焦点。
160
+ const focusNote = prepared.focus ? " Focus requested." : " This terminal cannot guarantee focus stays in the current tab.";
161
+ return result(`Opened ${target} in ${launchPlan.terminal.id} for async run ${runId} (${launchPlan.displayCommand}).${focusNote} Steer and stop stay in Fleet.`);
162
+ },
163
+ };
164
+ }
package/lib/runs.mjs ADDED
@@ -0,0 +1,77 @@
1
+ // pi-subagents 异步 run 的只读索引(status.json 契约见 docs/observability.md)。
2
+ // 目录:$PI_SUBAGENTS_TEMP_ROOT 或 /tmp/pi-subagents-<scope>/async-subagent-runs/<runId>/status.json
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+
7
+ export function asyncRoots() {
8
+ const roots = [];
9
+ const configured = process.env.PI_SUBAGENTS_TEMP_ROOT?.trim();
10
+ if (configured) roots.push(path.join(path.resolve(configured), "async-subagent-runs"));
11
+ let names = [];
12
+ try { names = fs.readdirSync(os.tmpdir()); } catch { names = []; }
13
+ for (const name of names) {
14
+ if (!name.startsWith("pi-subagents-")) continue;
15
+ const dir = path.join(os.tmpdir(), name, "async-subagent-runs");
16
+ try { if (fs.statSync(dir).isDirectory()) roots.push(dir); } catch { /* ignore */ }
17
+ }
18
+ return [...new Set(roots)];
19
+ }
20
+
21
+ function readJson(file) {
22
+ try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return undefined; }
23
+ }
24
+
25
+ export function listAsyncRuns() {
26
+ const runs = [];
27
+ for (const root of asyncRoots()) {
28
+ let names = [];
29
+ try { names = fs.readdirSync(root); } catch { continue; }
30
+ for (const name of names) {
31
+ const asyncDir = path.join(root, name);
32
+ const status = readJson(path.join(asyncDir, "status.json"));
33
+ if (!status || typeof status.runId !== "string") continue;
34
+ const step0 = status.steps?.[0];
35
+ runs.push({
36
+ runId: status.runId,
37
+ asyncDir,
38
+ state: status.state,
39
+ mode: status.mode,
40
+ cwd: status.cwd,
41
+ startedAt: status.startedAt,
42
+ endedAt: status.endedAt,
43
+ agent: step0?.agent ?? status.agent,
44
+ model: status.resolvedModel?.model ?? status.model ?? step0?.model,
45
+ sessionFile: status.sessionFile ?? step0?.sessionFile,
46
+ workflowKey: status.workflowKey,
47
+ parentWorkflowRunId: status.parentWorkflowRunId,
48
+ steps: status.steps ?? [],
49
+ });
50
+ }
51
+ }
52
+ return runs.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0));
53
+ }
54
+
55
+ /** 按 runId 前缀 / 会话文件 / 显式 dir 定位 asyncDir。 */
56
+ export function resolveAsyncRun({ runId, sessionFile, asyncDir } = {}) {
57
+ if (asyncDir) {
58
+ const status = readJson(path.join(asyncDir, "status.json"));
59
+ if (!status) throw new Error(`no status.json in '${asyncDir}'`);
60
+ return { asyncDir, status };
61
+ }
62
+ const runs = listAsyncRuns();
63
+ if (sessionFile) {
64
+ const hit = runs.find((r) => r.sessionFile && path.resolve(r.sessionFile) === path.resolve(sessionFile))
65
+ ?? runs.find((r) => r.steps.some((s) => s?.sessionFile && path.resolve(s.sessionFile) === path.resolve(sessionFile)));
66
+ if (hit) return { asyncDir: hit.asyncDir, status: readJson(path.join(hit.asyncDir, "status.json")) };
67
+ }
68
+ if (!runId) throw new Error("needs --run <id> / --dir <asyncDir>(或 --file <session.jsonl> 能对上某个 run)");
69
+ const hits = runs.filter((r) => r.runId === runId || r.runId.startsWith(runId));
70
+ if (hits.length === 0) throw new Error(`no async run matching '${runId}'(已结束并回收的 run 只剩会话文件,不能 steer)`);
71
+ if (hits.length > 1) throw new Error(`ambiguous run '${runId}': ${hits.map((h) => h.runId).join(", ")}`);
72
+ return { asyncDir: hits[0].asyncDir, status: readJson(path.join(hits[0].asyncDir, "status.json")) };
73
+ }
74
+
75
+ export function findRunSessionFile(run) {
76
+ return run.sessionFile ?? run.steps?.find((s) => s?.sessionFile)?.sessionFile;
77
+ }
@@ -0,0 +1,97 @@
1
+ // 子会话发现与元数据(只读)。
2
+ // 会话落盘布局(pi 自己写的,pi-subagents 依赖):
3
+ // <agentDir>/sessions/<项目slug>/<父会话文件>.jsonl
4
+ // <agentDir>/sessions/<项目slug>/<父会话文件>/<childRunId>/run-<N>/session.jsonl
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import os from "node:os";
8
+
9
+ export const AGENT_DIR = process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
10
+ // 允许测试/特殊布局改写会话根(gate.sh 用它造合成 roster,避免依赖本机历史)。
11
+ export const SESSIONS_ROOT = process.env.PI_SUB_VIEW_SESSIONS_ROOT || path.join(AGENT_DIR, "sessions");
12
+
13
+ export function isChildSessionPath(p) {
14
+ return /\/run-\d+\/session\.jsonl$/.test(p) || /\/child-session\/session\.jsonl$/.test(p);
15
+ }
16
+
17
+ export function runIdOf(file) {
18
+ const parts = file.split(path.sep);
19
+ const idx = parts.lastIndexOf("session.jsonl");
20
+ const parent = parts[idx - 2] || "";
21
+ const runDir = parts[idx - 1] || "";
22
+ if (/^run-\d+$/.test(runDir) && parent) return parent;
23
+ return parent || path.basename(path.dirname(file));
24
+ }
25
+
26
+ /** 同一父会话下的所有子会话(键控切换的 roster)。 */
27
+ export function parentDirOf(file) {
28
+ // .../<parent>.jsonl 与 .../<parent>.jsonl/<child>/run-N/session.jsonl 同目录
29
+ const parts = file.split(path.sep);
30
+ const idx = parts.lastIndexOf("session.jsonl");
31
+ // idx-2 = childRunId, idx-3 = parentSessionId
32
+ return path.join(...parts.slice(0, Math.max(0, idx - 2)));
33
+ }
34
+
35
+ export function listChildSessions(root = SESSIONS_ROOT) {
36
+ const out = [];
37
+ const walk = (dir, depth) => {
38
+ if (depth > 6) return;
39
+ let entries;
40
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
41
+ for (const e of entries) {
42
+ const full = path.join(dir, e.name);
43
+ if (e.isDirectory()) { walk(full, depth + 1); continue; }
44
+ if (e.isFile() && e.name === "session.jsonl" && isChildSessionPath(full)) {
45
+ try {
46
+ const st = fs.statSync(full);
47
+ out.push({ file: full, mtime: st.mtimeMs, size: st.size, runId: runIdOf(full), parentDir: parentDirOf(full) });
48
+ } catch { /* ignore */ }
49
+ }
50
+ }
51
+ };
52
+ walk(root, 0);
53
+ return out.sort((a, b) => b.mtime - a.mtime);
54
+ }
55
+
56
+ /** 只读前 8 KB 取 agent 名 / 首次模型(够用且便宜)。 */
57
+ export function childMeta(file) {
58
+ const meta = { agent: undefined, model: undefined, sessionName: undefined };
59
+ let text = "";
60
+ try {
61
+ const fd = fs.openSync(file, "r");
62
+ try {
63
+ const buf = Buffer.allocUnsafe(8192);
64
+ const read = fs.readSync(fd, buf, 0, buf.length, 0);
65
+ text = buf.subarray(0, read).toString("utf8");
66
+ } finally {
67
+ fs.closeSync(fd);
68
+ }
69
+ } catch {
70
+ return meta;
71
+ }
72
+ for (const line of text.split("\n")) {
73
+ if (!line.trim()) continue;
74
+ let entry;
75
+ try { entry = JSON.parse(line); } catch { continue; }
76
+ if (entry.type === "model_change" && !meta.model) meta.model = `${entry.provider ?? ""}/${entry.modelId ?? ""}`.replace(/^\//, "");
77
+ if (entry.type === "session_info" && entry.name) meta.sessionName = entry.name;
78
+ if (entry.type === "message" && !meta.agent) {
79
+ const sys = entry.message?.role === "system" ? entry.message?.content : undefined;
80
+ if (typeof sys === "string") {
81
+ const m = /<active_agent\s+name="([^"]+)"/.exec(sys);
82
+ if (m) meta.agent = m[1];
83
+ }
84
+ }
85
+ }
86
+ if (!meta.agent && meta.sessionName) {
87
+ const m = /^subagent-([a-z0-9_]+)-/i.exec(meta.sessionName);
88
+ if (m) meta.agent = m[1];
89
+ }
90
+ return meta;
91
+ }
92
+
93
+ export function siblingsOf(file) {
94
+ const parentDir = parentDirOf(file);
95
+ const all = listChildSessions();
96
+ return all.filter((s) => s.parentDir === parentDir);
97
+ }
package/lib/steer.mjs ADDED
@@ -0,0 +1,104 @@
1
+ // 向 async 子代理投递 steer —— 复用 pi-subagents 现有的文件控制通道,不自己发明协议。
2
+ //
3
+ // 契约(与 pi-subagents src/runs/background/control-channel.js 对齐,0.90.0 实测):
4
+ // <asyncDir>/control/steer-requests/<ts 左补零 13 位>-<base64url(id)>.json
5
+ // <asyncDir>/control/steer-inbox-closed.json 存在 ⇒ 拒绝(run 已不接受 steer)
6
+ // 请求体:{type:"steer", id, ts, message, mode?, targetIndex?, targetIndexes?, source?}
7
+ // 写完要复查 closed 文件:中途关闭则删除请求并报错(上游同样处理)。
8
+ //
9
+ // source 是给 operator 区分「谁发的」用的:本工具固定 source="pi-sub-view",
10
+ // 父进程的工具 steer 不带该值;status.json 的 steering.recent[].source 会带上它。
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { randomUUID } from "node:crypto";
14
+
15
+ export const MAX_STEER_MESSAGE_BYTES = 128 * 1024;
16
+ export const DEFAULT_SOURCE = "pi-sub-view";
17
+ const MODES = new Set(["steer", "follow_up", "auto"]);
18
+
19
+ function controlDir(asyncDir) { return path.join(asyncDir, "control"); }
20
+ function steerDir(asyncDir) { return path.join(controlDir(asyncDir), "steer-requests"); }
21
+ function closedPath(asyncDir) { return path.join(controlDir(asyncDir), "steer-inbox-closed.json"); }
22
+
23
+ function writeAtomic(filePath, payload) {
24
+ const dir = path.dirname(filePath);
25
+ fs.mkdirSync(dir, { recursive: true });
26
+ const temp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`);
27
+ try {
28
+ fs.writeFileSync(temp, JSON.stringify(payload, null, 2), { encoding: "utf8", flag: "wx" });
29
+ fs.renameSync(temp, filePath);
30
+ } finally {
31
+ fs.rmSync(temp, { force: true });
32
+ }
33
+ }
34
+
35
+ function validate({ message, mode, targetIndex, source }) {
36
+ if (!message.trim()) throw new Error("steer message must not be empty.");
37
+ if (Buffer.byteLength(message, "utf8") > MAX_STEER_MESSAGE_BYTES) {
38
+ throw new Error(`steer message exceeds ${MAX_STEER_MESSAGE_BYTES} UTF-8 bytes.`);
39
+ }
40
+ if (mode !== undefined && !MODES.has(mode)) throw new Error(`mode must be one of ${[...MODES].join("|")}.`);
41
+ if (targetIndex !== undefined && (!Number.isInteger(targetIndex) || targetIndex < 0 || targetIndex > 1_000_000)) {
42
+ throw new Error("targetIndex must be a non-negative integer.");
43
+ }
44
+ if (source !== undefined && (typeof source !== "string" || !source.trim() || source.length > 256)) {
45
+ throw new Error("source must be a non-empty string of at most 256 characters.");
46
+ }
47
+ }
48
+
49
+ export function sendSteer(asyncDir, { message, mode, targetIndex, source = DEFAULT_SOURCE, id, ts } = {}) {
50
+ const text = String(message ?? "");
51
+ validate({ message: text, mode, targetIndex, source });
52
+ const request = {
53
+ type: "steer",
54
+ id: id ?? randomUUID(),
55
+ ts: ts ?? Date.now(),
56
+ message: text.trim(),
57
+ ...(mode && mode !== "steer" ? { mode } : {}),
58
+ ...(targetIndex !== undefined ? { targetIndex } : {}),
59
+ ...(source ? { source } : {}),
60
+ };
61
+ if (fs.existsSync(closedPath(asyncDir))) throw new Error("Async run no longer accepts steering requests.");
62
+ const file = path.join(steerDir(asyncDir), `${String(request.ts).padStart(13, "0")}-${Buffer.from(request.id).toString("base64url")}.json`);
63
+ writeAtomic(file, request);
64
+ if (fs.existsSync(closedPath(asyncDir))) {
65
+ fs.rmSync(file, { force: true });
66
+ throw new Error("Async run stopped accepting steering before the request was committed.");
67
+ }
68
+ return { id: request.id, path: file, request };
69
+ }
70
+
71
+ /** 从 status.json 的 steering 账本读回执(source 与每个 target 的状态都在里面)。 */
72
+ export function readReceipt(asyncDir, id) {
73
+ let status;
74
+ try { status = JSON.parse(fs.readFileSync(path.join(asyncDir, "status.json"), "utf8")); } catch { return undefined; }
75
+ const entry = status?.steering?.recent?.find((r) => r.id === id);
76
+ if (!entry) return undefined;
77
+ return {
78
+ id: entry.id,
79
+ source: entry.source,
80
+ preview: entry.messagePreview,
81
+ targets: entry.targets ?? [],
82
+ states: (entry.targets ?? []).map((t) => t.state),
83
+ };
84
+ }
85
+
86
+ const TERMINAL = new Set(["delivered", "late", "recovered", "failed"]);
87
+
88
+ export async function waitReceipts(asyncDir, id, { timeoutMs = 60_000, intervalMs = 500, onUpdate } = {}) {
89
+ const deadline = Date.now() + timeoutMs;
90
+ let lastKey;
91
+ for (;;) {
92
+ const receipt = readReceipt(asyncDir, id);
93
+ if (receipt) {
94
+ const key = receipt.states.join(",");
95
+ if (key !== lastKey) {
96
+ lastKey = key;
97
+ onUpdate?.(receipt);
98
+ }
99
+ if (receipt.states.length > 0 && receipt.states.every((s) => TERMINAL.has(s))) return receipt;
100
+ }
101
+ if (Date.now() >= deadline) return readReceipt(asyncDir, id);
102
+ await new Promise((r) => setTimeout(r, intervalMs));
103
+ }
104
+ }