pi-ate-workflow 0.2.3 → 0.2.5
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/index.ts +2 -1
- package/package.json +1 -1
- package/proc-guard.ts +171 -0
- package/subagent-jsonl-signal.ts +43 -0
- package/subagent-spawn-visible.ts +192 -181
- package/subagent-utils.ts +9 -1
- package/subagent.ts +140 -132
- package/tests/create-visible-taskdir.test.ts +30 -2
- package/tests/proc-guard.test.ts +192 -0
- package/tests/spawn-once-extra-env.test.ts +6 -1
- package/tests/subagent-failure-classification.test.ts +158 -0
- package/tests/subagent-failure-retry.test.ts +148 -0
- package/tests/subagent-model.test.ts +11 -9
- package/tests/subagent-spawn-visible.test.ts +47 -2
- package/tests/subagent-visible-jsonl-signal.test.ts +113 -0
- package/tests/sweep-stale.test.ts +116 -0
- package/tests/visible-cleanup.test.ts +152 -0
- package/utils.ts +133 -74
- package/visible-cleanup.ts +58 -0
package/index.ts
CHANGED
|
@@ -32,7 +32,8 @@ export { saveSubagentOutput, readSubagentOutput } from "./output";
|
|
|
32
32
|
export type { SubagentResult, SubagentEvent } from "./types";
|
|
33
33
|
export { createStateManager, createUIUpdater } from "./state";
|
|
34
34
|
export { registerWorkflowTool, type ActionDef } from "./workflow";
|
|
35
|
-
export { findSessionFile, getSubagentStatusSummary, isSubagentSuccess } from "./utils";
|
|
35
|
+
export { findSessionFile, getSubagentStatusSummary, isSubagentSuccess, isSystemicSubagentFailure, buildSystemicFailureResult, isEmptyPlaceholderOutput, EMPTY_OUTPUT_PLACEHOLDERS } from "./utils";
|
|
36
|
+
export { checkSessionJsonlTermination } from "./subagent-jsonl-signal";
|
|
36
37
|
export { discoverAgents, getAgentDescription } from "./agents";
|
|
37
38
|
export { AGENT_DIR, AGENTS_DIR } from "./paths";
|
|
38
39
|
|
package/package.json
CHANGED
package/proc-guard.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* proc-guard: 可见子代理进程身份探测与树杀
|
|
3
|
+
*
|
|
4
|
+
* 清理安全性基建:launch.sh 启动最前自报 proc.pid("shellPid winpid"),
|
|
5
|
+
* 清理侧据此判定 pane 内进程树死透——目录删除动作永不早于死透确认。
|
|
6
|
+
*
|
|
7
|
+
* 平台适用 pid 语义:Windows 用 winpid(MSYS2 bash 的 $$ 是 MSYS pid,
|
|
8
|
+
* taskkill 无法消费),Unix 用 shell pid($$ 本身即平台原生 pid,
|
|
9
|
+
* winpid=0 只是"无 Windows 原生 pid"标记,不构成 Unix 的降级信号)。
|
|
10
|
+
*/
|
|
11
|
+
import * as fs from "node:fs";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
import * as os from "node:os";
|
|
14
|
+
import { execFileSync } from "node:child_process";
|
|
15
|
+
|
|
16
|
+
/** 执行器抽象(依赖注入,测试可 mock;探测失败返回 null) */
|
|
17
|
+
export interface ProcGuardExecutor {
|
|
18
|
+
run(cmd: string, args: string[]): string | null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const defaultExecutor: ProcGuardExecutor = {
|
|
22
|
+
run(cmd, args) {
|
|
23
|
+
try {
|
|
24
|
+
return execFileSync(cmd, args, {
|
|
25
|
+
encoding: "utf-8",
|
|
26
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
27
|
+
});
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** proc.pid 自报信息(launch.sh 首行写入) */
|
|
35
|
+
export interface ProcPidInfo {
|
|
36
|
+
shellPid: number;
|
|
37
|
+
winpid: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 读取任务目录的 proc.pid;缺失/格式异常返回 null(走降级链) */
|
|
41
|
+
export function readProcPid(taskDir: string): ProcPidInfo | null {
|
|
42
|
+
try {
|
|
43
|
+
const raw = fs.readFileSync(path.join(taskDir, "proc.pid"), "utf-8").trim();
|
|
44
|
+
const m = raw.match(/^(\d+)\s+(\d+)$/);
|
|
45
|
+
if (!m) return null;
|
|
46
|
+
const shellPid = Number(m[1]);
|
|
47
|
+
const winpid = Number(m[2]);
|
|
48
|
+
if (shellPid <= 0) return null;
|
|
49
|
+
return { shellPid, winpid };
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 平台适用 pid:Windows 判 winpid,Unix 判 shell pid;无可用 pid 返回 null */
|
|
56
|
+
export function resolvePlatformPid(info: ProcPidInfo | null): number | null {
|
|
57
|
+
if (!info) return null;
|
|
58
|
+
if (process.platform === "win32") {
|
|
59
|
+
return info.winpid > 0 ? info.winpid : null;
|
|
60
|
+
}
|
|
61
|
+
return info.shellPid > 0 ? info.shellPid : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 判定 pid 是否存活。
|
|
66
|
+
* 探测命令失败(返回 null)时按存活处理——fail-safe,宁可多等/树杀,不误判死。
|
|
67
|
+
*/
|
|
68
|
+
export function isPidAlive(pid: number, executor: ProcGuardExecutor = defaultExecutor): boolean {
|
|
69
|
+
if (pid <= 0) return false;
|
|
70
|
+
if (process.platform === "win32") {
|
|
71
|
+
const out = executor.run("tasklist", ["/FI", `PID eq ${pid}`, "/NH"]);
|
|
72
|
+
if (out === null) return true; // 探测失败按存活处理(fail-safe:不误删)
|
|
73
|
+
// tasklist /NH 数据行格式:imagename pid session session# mem
|
|
74
|
+
// 按第二列精确匹配,防内存列数字子串误判(如 "22,222 K" 含 "222")
|
|
75
|
+
return out.split("\n").some((line) => (line.trim().split(/\s+/)[1] ?? "") === String(pid));
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
process.kill(pid, 0);
|
|
79
|
+
return true;
|
|
80
|
+
} catch (e: unknown) {
|
|
81
|
+
return (e as NodeJS.ErrnoException).code === "EPERM";
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 整树强杀(Windows taskkill /T /F 带走全部子孙;Unix kill -9 直接目标) */
|
|
86
|
+
export function killTree(pid: number, executor: ProcGuardExecutor = defaultExecutor): void {
|
|
87
|
+
if (pid <= 0) return;
|
|
88
|
+
if (process.platform === "win32") {
|
|
89
|
+
executor.run("taskkill", ["/T", "/F", "/PID", String(pid)]);
|
|
90
|
+
} else {
|
|
91
|
+
executor.run("kill", ["-9", String(pid)]);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface WaitForPidExitOptions {
|
|
96
|
+
timeoutMs?: number;
|
|
97
|
+
intervalMs?: number;
|
|
98
|
+
sleep?: (ms: number) => Promise<void>;
|
|
99
|
+
executor?: ProcGuardExecutor;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 等待 pid 死透:intervalMs 间隔轮询,timeoutMs 上限。
|
|
104
|
+
* 返回是否确认死透;超时未死透返回 false(由调用方决定树杀兜底)。
|
|
105
|
+
*/
|
|
106
|
+
export async function waitForPidExit(
|
|
107
|
+
pid: number,
|
|
108
|
+
options: WaitForPidExitOptions = {},
|
|
109
|
+
): Promise<boolean> {
|
|
110
|
+
const {
|
|
111
|
+
timeoutMs = 10_000,
|
|
112
|
+
intervalMs = 500,
|
|
113
|
+
sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),
|
|
114
|
+
executor = defaultExecutor,
|
|
115
|
+
} = options;
|
|
116
|
+
const deadline = Date.now() + timeoutMs;
|
|
117
|
+
while (Date.now() < deadline) {
|
|
118
|
+
if (!isPidAlive(pid, executor)) return true;
|
|
119
|
+
await sleep(intervalMs);
|
|
120
|
+
}
|
|
121
|
+
return !isPidAlive(pid, executor);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 超龄清扫默认阈值:24 小时 */
|
|
125
|
+
export const STALE_VISIBLE_TASK_DIR_MS = 24 * 60 * 60 * 1000;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 扫描 Temp 下超龄的 pi-visible-* 残留目录并删除。
|
|
129
|
+
* 兜底主进程意外退出导致延迟清理回调丢失的残留(定时器随进程消亡)。
|
|
130
|
+
*
|
|
131
|
+
* 超龄锚点:目录内全部条目(含文件)的最大 mtime,不取目录自身 mtime——
|
|
132
|
+
* Windows 文件系统下写文件内容不刷新父目录 mtime,取目录自身会把运行中的
|
|
133
|
+
* 长任务目录(stalled 轮询 5 分钟必然刷新 session.jsonl 的 mtime)误判为超龄。
|
|
134
|
+
* 逐目录容错:单个目录删除失败不中断扫描。
|
|
135
|
+
*/
|
|
136
|
+
export function sweepStaleVisibleTaskDirs(
|
|
137
|
+
tmpRoot: string = os.tmpdir(),
|
|
138
|
+
maxAgeMs: number = STALE_VISIBLE_TASK_DIR_MS,
|
|
139
|
+
): void {
|
|
140
|
+
try {
|
|
141
|
+
const entries = fs.readdirSync(tmpRoot);
|
|
142
|
+
for (const name of entries) {
|
|
143
|
+
if (!name.startsWith("pi-visible-")) continue;
|
|
144
|
+
const dir = path.join(tmpRoot, name);
|
|
145
|
+
try {
|
|
146
|
+
if (!isStaleVisibleTaskDir(dir, maxAgeMs)) continue;
|
|
147
|
+
// 死透检查:主进程崩溃后子代理可能仍活着(罕见但存在)——跳过本轮,下轮 sweep 再试
|
|
148
|
+
const pid = resolvePlatformPid(readProcPid(dir));
|
|
149
|
+
if (pid !== null && isPidAlive(pid)) continue;
|
|
150
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
151
|
+
} catch { /* 单目录失败容错 */ }
|
|
152
|
+
}
|
|
153
|
+
} catch { /* 扫描根不可读则跳过 */ }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 目录内全部条目的最大 mtime 是否超过 maxAgeMs */
|
|
157
|
+
function isStaleVisibleTaskDir(dir: string, maxAgeMs: number): boolean {
|
|
158
|
+
try {
|
|
159
|
+
const stat = fs.statSync(dir);
|
|
160
|
+
if (!stat.isDirectory()) return false;
|
|
161
|
+
let newest = stat.mtimeMs;
|
|
162
|
+
for (const entry of fs.readdirSync(dir)) {
|
|
163
|
+
try {
|
|
164
|
+
newest = Math.max(newest, fs.statSync(path.join(dir, entry)).mtimeMs);
|
|
165
|
+
} catch { /* 条目消失则跳过 */ }
|
|
166
|
+
}
|
|
167
|
+
return Date.now() - newest > maxAgeMs;
|
|
168
|
+
} catch {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* visible 模式系统性失败信号:子会话 session.jsonl 终结形态判定
|
|
3
|
+
*
|
|
4
|
+
* visible spawn 的子进程输出直进终端窗格、stderr 无数据源(pipe 拿不到数据),
|
|
5
|
+
* close 分支的失败信号改看 jsonl:文件缺失或无 message 事件(未进入对话阶段)
|
|
6
|
+
* = spawn 层阵亡,判系统性失败档。
|
|
7
|
+
*
|
|
8
|
+
* 注:pi 的 session.jsonl 没有 result/agent_end 类终结事件——正常会话末行
|
|
9
|
+
* 即 message 事件(2026-11 实测多个已终结会话),故「正常终结形态」的实态
|
|
10
|
+
* 信号 = 存在 message 事件(对话确实发生过)。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import * as fs from "node:fs";
|
|
14
|
+
|
|
15
|
+
/** 判定结果:ok=false 时 reason 说明异常形态(拼入系统性失败档报错) */
|
|
16
|
+
export interface JsonlTerminationSignal {
|
|
17
|
+
ok: boolean;
|
|
18
|
+
reason: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 判定子会话 session.jsonl 终结形态(visible 模式信号源,替代 stderr)。
|
|
23
|
+
* 由 subagent-spawn-visible.ts 的 finish() 在 close 时调用。
|
|
24
|
+
*/
|
|
25
|
+
export function checkSessionJsonlTermination(sessionFile: string): JsonlTerminationSignal {
|
|
26
|
+
if (!fs.existsSync(sessionFile)) {
|
|
27
|
+
return { ok: false, reason: "session.jsonl 缺失(子进程未建立会话)" };
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const content = fs.readFileSync(sessionFile, "utf-8");
|
|
31
|
+
const lines = content.split("\n").filter((l) => l.trim());
|
|
32
|
+
if (lines.length === 0) return { ok: false, reason: "session.jsonl 为空" };
|
|
33
|
+
for (const line of lines) {
|
|
34
|
+
try {
|
|
35
|
+
const e = JSON.parse(line);
|
|
36
|
+
if (e?.type === "message") return { ok: true, reason: "" };
|
|
37
|
+
} catch { /* skip non-JSON */ }
|
|
38
|
+
}
|
|
39
|
+
return { ok: false, reason: "session.jsonl 无 message 事件(未进入对话阶段)" };
|
|
40
|
+
} catch (err) {
|
|
41
|
+
return { ok: false, reason: `session.jsonl 读取失败: ${err instanceof Error ? err.message : String(err)}` };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -1,181 +1,192 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* workflow: 可见模式 spawn 实现
|
|
3
|
-
*
|
|
4
|
-
* spawnVisible — 在终端分屏中启动 pi 子进程,用户可实时观察
|
|
5
|
-
* 支持 WezTerm(优先)和 tmux,都不可用时降级到后台模式
|
|
6
|
-
* 使用 SubagentSession 管理输出收集和退出控制
|
|
7
|
-
*
|
|
8
|
-
* 自动退出机制:launch.sh 注入 PI_SUBAGENT_AUTO_EXIT=1,
|
|
9
|
-
* 子代理进程内由 pi-workflow 扩展入口的 agent_end handler
|
|
10
|
-
* 延迟退出(让 TUI 渲染末尾输出并完成 session.jsonl 刷盘)。
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import { execSync } from "node:child_process";
|
|
14
|
-
import * as fs from "node:fs";
|
|
15
|
-
import type { SubagentEvent, SubagentResult } from "./types";
|
|
16
|
-
import { spawnOnce } from "./subagent-spawn-once";
|
|
17
|
-
import { SubagentSession } from "./subagent-session";
|
|
18
|
-
import { createVisibleTaskDir, injectParentSession } from "./subagent-utils";
|
|
19
|
-
import {
|
|
20
|
-
import
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
)
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
1
|
+
/**
|
|
2
|
+
* workflow: 可见模式 spawn 实现
|
|
3
|
+
*
|
|
4
|
+
* spawnVisible — 在终端分屏中启动 pi 子进程,用户可实时观察
|
|
5
|
+
* 支持 WezTerm(优先)和 tmux,都不可用时降级到后台模式
|
|
6
|
+
* 使用 SubagentSession 管理输出收集和退出控制
|
|
7
|
+
*
|
|
8
|
+
* 自动退出机制:launch.sh 注入 PI_SUBAGENT_AUTO_EXIT=1,
|
|
9
|
+
* 子代理进程内由 pi-workflow 扩展入口的 agent_end handler
|
|
10
|
+
* 延迟退出(让 TUI 渲染末尾输出并完成 session.jsonl 刷盘)。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { execSync } from "node:child_process";
|
|
14
|
+
import * as fs from "node:fs";
|
|
15
|
+
import type { SubagentEvent, SubagentResult } from "./types";
|
|
16
|
+
import { spawnOnce } from "./subagent-spawn-once";
|
|
17
|
+
import { SubagentSession } from "./subagent-session";
|
|
18
|
+
import { createVisibleTaskDir, injectParentSession } from "./subagent-utils";
|
|
19
|
+
import { checkSessionJsonlTermination } from "./subagent-jsonl-signal";
|
|
20
|
+
import { detectTerminal, getBackend } from "./term-backend";
|
|
21
|
+
import type { TermBackend } from "./term-backend";
|
|
22
|
+
import { createSafeCleanup } from "./visible-cleanup";
|
|
23
|
+
import { DEFAULT_SUBAGENT_TIMEOUT_MS } from "./timeout-config";
|
|
24
|
+
|
|
25
|
+
/** 活跃超时:无新输出视为停滞的阈值(与 subagent-spawn-once 的 STALL_MS 语义对齐) */
|
|
26
|
+
const STALL_TIMEOUT_MS = 5 * 60 * 1000;
|
|
27
|
+
|
|
28
|
+
export function spawnVisible(
|
|
29
|
+
task: string,
|
|
30
|
+
cwd: string,
|
|
31
|
+
systemPromptPath: string,
|
|
32
|
+
agentDef: { tools: string[]; model?: string },
|
|
33
|
+
signal?: AbortSignal,
|
|
34
|
+
modelOverride?: string,
|
|
35
|
+
timeoutMs?: number,
|
|
36
|
+
onEvent?: (event: SubagentEvent) => void,
|
|
37
|
+
parentSessionPath?: string,
|
|
38
|
+
extraEnv?: Record<string, string>,
|
|
39
|
+
): Promise<SubagentResult> {
|
|
40
|
+
const { taskDir, sessionFile, launchScript } = createVisibleTaskDir(
|
|
41
|
+
task, cwd, systemPromptPath, agentDef, modelOverride, extraEnv,
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
// 检测终端类型,不可用则降级到后台模式
|
|
45
|
+
const termType = detectTerminal();
|
|
46
|
+
if (!termType) {
|
|
47
|
+
try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
|
|
48
|
+
return spawnOnce(
|
|
49
|
+
task, cwd, systemPromptPath, agentDef,
|
|
50
|
+
signal, modelOverride, timeoutMs, onEvent, parentSessionPath, extraEnv,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const backend: TermBackend = getBackend(termType);
|
|
55
|
+
let paneId: string;
|
|
56
|
+
try {
|
|
57
|
+
paneId = backend.splitPane(cwd, launchScript);
|
|
58
|
+
} catch {
|
|
59
|
+
try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
|
|
60
|
+
return spawnOnce(
|
|
61
|
+
task, cwd, systemPromptPath, agentDef,
|
|
62
|
+
signal, modelOverride, timeoutMs, onEvent, parentSessionPath, extraEnv,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ─── SubagentSession 管理输出收集和退出 ─────────
|
|
67
|
+
|
|
68
|
+
const agentSession = new SubagentSession({
|
|
69
|
+
onEvent,
|
|
70
|
+
beforeResolve: (result) => {
|
|
71
|
+
if (parentSessionPath && fs.existsSync(sessionFile)) {
|
|
72
|
+
injectParentSession(sessionFile, parentSessionPath);
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
return new Promise<SubagentResult>((resolve) => {
|
|
78
|
+
let lastLine = 0;
|
|
79
|
+
let lastActivityTime = Date.now();
|
|
80
|
+
|
|
81
|
+
// 有序安全清理:目录删除永不早于 pane 内进程树死透确认(实现见 visible-cleanup.ts)
|
|
82
|
+
const safeCleanup = createSafeCleanup({ taskDir, paneId, backend });
|
|
83
|
+
|
|
84
|
+
// ─── 轮询 session.jsonl ─────────────────
|
|
85
|
+
|
|
86
|
+
const pollInterval = setInterval(() => {
|
|
87
|
+
if (agentSession.isDone) return;
|
|
88
|
+
|
|
89
|
+
// 读取新行并解析(半行不推进:写侧未写完的行留给下一轮重读,防止行丢失)
|
|
90
|
+
try {
|
|
91
|
+
if (fs.existsSync(sessionFile)) {
|
|
92
|
+
const content = fs.readFileSync(sessionFile, "utf-8");
|
|
93
|
+
const lines = content.split("\n").filter((l) => l.trim());
|
|
94
|
+
const completeCount = content.endsWith("\n") ? lines.length : Math.max(0, lines.length - 1);
|
|
95
|
+
if (completeCount > lastLine) lastActivityTime = Date.now();
|
|
96
|
+
for (let i = lastLine; i < completeCount; i++) {
|
|
97
|
+
try { agentSession.parseSessionLine(JSON.parse(lines[i])); } catch { /* skip */ }
|
|
98
|
+
}
|
|
99
|
+
lastLine = completeCount;
|
|
100
|
+
}
|
|
101
|
+
} catch { /* ignore */ }
|
|
102
|
+
|
|
103
|
+
// 检查 pane 是否存活
|
|
104
|
+
if (!backend.isPaneAlive(paneId)) void finish();
|
|
105
|
+
|
|
106
|
+
// 活跃超时:STALL_TIMEOUT_MS 无新输出视为停滞
|
|
107
|
+
if (Date.now() - lastActivityTime > STALL_TIMEOUT_MS) {
|
|
108
|
+
agentSession.resolveOnce({
|
|
109
|
+
exitCode: 1,
|
|
110
|
+
output: agentSession.formatOutput(`(stalled, no output for ${Math.round(STALL_TIMEOUT_MS / 60000)} min)`),
|
|
111
|
+
stderr: "",
|
|
112
|
+
timedOut: true,
|
|
113
|
+
});
|
|
114
|
+
clearInterval(pollInterval);
|
|
115
|
+
clearTimeout(wallTimer);
|
|
116
|
+
void safeCleanup(true);
|
|
117
|
+
}
|
|
118
|
+
}, 2000);
|
|
119
|
+
|
|
120
|
+
// ─── 墙钟超时兜底 ─────────────────────
|
|
121
|
+
|
|
122
|
+
const TIMEOUT_MS = timeoutMs ?? DEFAULT_SUBAGENT_TIMEOUT_MS;
|
|
123
|
+
const wallTimer = setTimeout(() => {
|
|
124
|
+
agentSession.resolveOnce({
|
|
125
|
+
exitCode: 1,
|
|
126
|
+
output: agentSession.formatOutput("(timed out)"),
|
|
127
|
+
stderr: "",
|
|
128
|
+
timedOut: true,
|
|
129
|
+
});
|
|
130
|
+
clearInterval(pollInterval);
|
|
131
|
+
void safeCleanup(true);
|
|
132
|
+
}, TIMEOUT_MS);
|
|
133
|
+
|
|
134
|
+
// ─── 正常结束:收集剩余输出 ────────────
|
|
135
|
+
|
|
136
|
+
async function finish() {
|
|
137
|
+
if (agentSession.isDone) return;
|
|
138
|
+
|
|
139
|
+
// 等子代理尾部刷盘(跨平台:sleep 命令在非 MSYS2 环境不可用)
|
|
140
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
141
|
+
try {
|
|
142
|
+
if (fs.existsSync(sessionFile)) {
|
|
143
|
+
const content = fs.readFileSync(sessionFile, "utf-8");
|
|
144
|
+
const lines = content.split("\n").filter((l) => l.trim());
|
|
145
|
+
const completeCount = content.endsWith("\n") ? lines.length : Math.max(0, lines.length - 1);
|
|
146
|
+
for (let i = lastLine; i < completeCount; i++) {
|
|
147
|
+
try { agentSession.parseSessionLine(JSON.parse(lines[i])); } catch { /* skip */ }
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
} catch { /* ignore */ }
|
|
151
|
+
|
|
152
|
+
// visible 模式失败信号源:jsonl 终结形态(stderr 无数据源,见 checkSessionJsonlTermination 注释)。
|
|
153
|
+
// 异常时 error 注入信号源说明,由 runSubagent 分类为系统性失败档(跳过重试+报错透出);
|
|
154
|
+
// jsonl 正常终结但输出空 → 不注入,回落现状路径(正常完成零输出档)。
|
|
155
|
+
const jsonlSignal = checkSessionJsonlTermination(sessionFile);
|
|
156
|
+
agentSession.resolveOnce({
|
|
157
|
+
exitCode: 0,
|
|
158
|
+
output: agentSession.formatOutput("(no output)"),
|
|
159
|
+
stderr: "",
|
|
160
|
+
error: jsonlSignal.ok ? undefined : `visible 模式信号源=jsonl 终结形态:${jsonlSignal.reason}`,
|
|
161
|
+
});
|
|
162
|
+
clearInterval(pollInterval);
|
|
163
|
+
clearTimeout(wallTimer);
|
|
164
|
+
|
|
165
|
+
// 有序清理临时目录(等 pane 内进程死透后删除;pane 由自动退出机制自行结束,
|
|
166
|
+
// 死透等待期间用户仍可看到最终输出)
|
|
167
|
+
void safeCleanup(false);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ─── AbortSignal ──────────────────────
|
|
171
|
+
|
|
172
|
+
if (signal) {
|
|
173
|
+
const onAbort = () => {
|
|
174
|
+
if (!agentSession.isDone) {
|
|
175
|
+
agentSession.resolveOnce({
|
|
176
|
+
exitCode: 1,
|
|
177
|
+
output: agentSession.formatOutput(""),
|
|
178
|
+
stderr: "aborted",
|
|
179
|
+
});
|
|
180
|
+
clearInterval(pollInterval);
|
|
181
|
+
clearTimeout(wallTimer);
|
|
182
|
+
void safeCleanup(true);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
if (signal.aborted) onAbort();
|
|
186
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// 将 session.result 连接到外部 resolve
|
|
190
|
+
agentSession.result.then(resolve);
|
|
191
|
+
});
|
|
192
|
+
}
|
package/subagent-utils.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import * as fs from "node:fs";
|
|
6
6
|
import * as path from "node:path";
|
|
7
7
|
import * as os from "node:os";
|
|
8
|
+
import { sweepStaleVisibleTaskDirs } from "./proc-guard";
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* 将 Windows 反斜杠路径转为 Unix 正斜杠路径。
|
|
@@ -124,6 +125,8 @@ export function createVisibleTaskDir(
|
|
|
124
125
|
extraEnv?: Record<string, string>,
|
|
125
126
|
): VisibleTaskDir {
|
|
126
127
|
const taskDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-visible-"));
|
|
128
|
+
// 顺带清扫超龄残留(主进程意外退出导致清理回调丢失的目录)
|
|
129
|
+
sweepStaleVisibleTaskDirs();
|
|
127
130
|
const taskFile = path.join(taskDir, "task.txt");
|
|
128
131
|
fs.writeFileSync(taskFile, task, { encoding: "utf-8" });
|
|
129
132
|
|
|
@@ -147,9 +150,14 @@ export function createVisibleTaskDir(
|
|
|
147
150
|
const uSessionFile = toUnixPath(sessionFile);
|
|
148
151
|
const uSystemPromptPath = toUnixPath(systemPromptPath);
|
|
149
152
|
const uTaskFile = toUnixPath(taskFile);
|
|
153
|
+
const uProcPidFile = toUnixPath(path.join(taskDir, "proc.pid"));
|
|
150
154
|
|
|
151
155
|
const script = [
|
|
152
156
|
"#!/bin/bash",
|
|
157
|
+
// 进程身份自报:清理侧据此判定 pane 内进程死透(safe-cleanup-visible-subagent)
|
|
158
|
+
// $$ 为 shell pid;MSYS2/Git Bash 下经 /proc/$$/winpid 取 Windows 原生 pid,
|
|
159
|
+
// 非 MSYS2 环境回退 0(Unix 平台清理侧用 shell pid,winpid=0 不构成降级信号)
|
|
160
|
+
`echo "$$ $(cat /proc/$$/winpid 2>/dev/null || echo 0)" > '${uProcPidFile}' || true`,
|
|
153
161
|
'export FNM_PATH="$HOME/.local/share/fnm"',
|
|
154
162
|
'if [ -d "$FNM_PATH" ]; then export PATH="$FNM_PATH:$PATH" && eval "$(fnm env --shell bash)"; fi',
|
|
155
163
|
`cd "${uCwd}"`,
|
|
@@ -157,7 +165,7 @@ export function createVisibleTaskDir(
|
|
|
157
165
|
`export PI_SUBAGENT_SESSION='${uSessionFile}'`,
|
|
158
166
|
`export PI_SUBAGENT_NAME='pv-visible'`,
|
|
159
167
|
extraEnvExports,
|
|
160
|
-
`pi --session '${uSessionFile}' --tools ${agentDef.tools.join(",")} --append-system-prompt '${uSystemPromptPath}'${modelArg} @'${uTaskFile}'`,
|
|
168
|
+
`exec pi --session '${uSessionFile}' --tools ${agentDef.tools.join(",")} --append-system-prompt '${uSystemPromptPath}'${modelArg} @'${uTaskFile}'`,
|
|
161
169
|
].filter(Boolean).join("\n");
|
|
162
170
|
fs.writeFileSync(launchScript, script, { mode: 0o700 });
|
|
163
171
|
|