pi-ate-workflow 0.2.4 → 0.2.6
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 +7 -4
- package/subagent-jsonl-signal.ts +76 -0
- package/subagent-spawn-once.ts +31 -5
- package/subagent-spawn-visible.ts +192 -179
- package/subagent-utils.ts +29 -12
- package/subagent.ts +140 -132
- package/tests/proc-guard.test.ts +5 -0
- package/tests/spawn-once-extra-env.test.ts +17 -6
- package/tests/subagent-failure-classification.test.ts +158 -0
- package/tests/subagent-failure-retry.test.ts +148 -0
- package/tests/subagent-find-session-file.test.ts +214 -0
- package/tests/subagent-spawn-once-jsonl-crosscheck.test.ts +243 -0
- package/tests/subagent-spawn-once.test.ts +16 -6
- package/tests/subagent-spawn-visible.test.ts +24 -0
- package/tests/subagent-visible-jsonl-signal.test.ts +113 -0
- package/tests/sweep-stale.test.ts +15 -0
- package/utils.ts +133 -74
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, crossCheckOnceSessionJsonl } 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
CHANGED
|
@@ -69,10 +69,10 @@ export function isPidAlive(pid: number, executor: ProcGuardExecutor = defaultExe
|
|
|
69
69
|
if (pid <= 0) return false;
|
|
70
70
|
if (process.platform === "win32") {
|
|
71
71
|
const out = executor.run("tasklist", ["/FI", `PID eq ${pid}`, "/NH"]);
|
|
72
|
-
if (out === null) return true;
|
|
73
|
-
// tasklist
|
|
74
|
-
//
|
|
75
|
-
return out.
|
|
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
76
|
}
|
|
77
77
|
try {
|
|
78
78
|
process.kill(pid, 0);
|
|
@@ -144,6 +144,9 @@ export function sweepStaleVisibleTaskDirs(
|
|
|
144
144
|
const dir = path.join(tmpRoot, name);
|
|
145
145
|
try {
|
|
146
146
|
if (!isStaleVisibleTaskDir(dir, maxAgeMs)) continue;
|
|
147
|
+
// 死透检查:主进程崩溃后子代理可能仍活着(罕见但存在)——跳过本轮,下轮 sweep 再试
|
|
148
|
+
const pid = resolvePlatformPid(readProcPid(dir));
|
|
149
|
+
if (pid !== null && isPidAlive(pid)) continue;
|
|
147
150
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
148
151
|
} catch { /* 单目录失败容错 */ }
|
|
149
152
|
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 子代理系统性失败信号:子会话 session.jsonl 终结形态判定(visible / once 两种 spawn 模式共用)
|
|
3
|
+
*
|
|
4
|
+
* visible spawn 的子进程输出直进终端窗格、stderr 无数据源(pipe 拿不到数据);
|
|
5
|
+
* once spawn 的子进程加载崩溃经 bash 包装时可出现 exitCode=0 且 stderr 空。
|
|
6
|
+
* 两种模式下 close 分支的 exitCode/stderr 判定都会失效,失败信号改看 jsonl:
|
|
7
|
+
* 文件缺失或无 message 事件(未进入对话阶段)= spawn 层阵亡,判系统性失败档。
|
|
8
|
+
*
|
|
9
|
+
* 注:pi 的 session.jsonl 没有 result/agent_end 类终结事件——正常会话末行
|
|
10
|
+
* 即 message 事件(2026-11 实测多个已终结会话),故「正常终结形态」的实态
|
|
11
|
+
* 信号 = 存在 message 事件(对话确实发生过)。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import * as fs from "node:fs";
|
|
15
|
+
import { findSessionFileById } from "./subagent-utils";
|
|
16
|
+
|
|
17
|
+
/** 判定结果:ok=false 时 reason 说明异常形态(拼入系统性失败档报错) */
|
|
18
|
+
export interface JsonlTerminationSignal {
|
|
19
|
+
ok: boolean;
|
|
20
|
+
reason: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 判定子会话 session.jsonl 终结形态(visible 模式信号源,替代 stderr)。
|
|
25
|
+
* 由 subagent-spawn-visible.ts 的 finish() 在 close 时调用。
|
|
26
|
+
*/
|
|
27
|
+
export function checkSessionJsonlTermination(sessionFile: string): JsonlTerminationSignal {
|
|
28
|
+
if (!fs.existsSync(sessionFile)) {
|
|
29
|
+
return { ok: false, reason: "session.jsonl 缺失(子进程未建立会话)" };
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const content = fs.readFileSync(sessionFile, "utf-8");
|
|
33
|
+
const lines = content.split("\n").filter((l) => l.trim());
|
|
34
|
+
if (lines.length === 0) return { ok: false, reason: "session.jsonl 为空" };
|
|
35
|
+
for (const line of lines) {
|
|
36
|
+
try {
|
|
37
|
+
const e = JSON.parse(line);
|
|
38
|
+
if (e?.type === "message") return { ok: true, reason: "" };
|
|
39
|
+
} catch { /* skip non-JSON */ }
|
|
40
|
+
}
|
|
41
|
+
return { ok: false, reason: "session.jsonl 无 message 事件(未进入对话阶段)" };
|
|
42
|
+
} catch (err) {
|
|
43
|
+
return { ok: false, reason: `session.jsonl 读取失败: ${err instanceof Error ? err.message : String(err)}` };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** once 模式交叉校验 error 措辞前缀(runSubagent 据 error 字段归系统性失败档;测试锁字面量) */
|
|
48
|
+
const ONCE_CROSS_CHECK_SOURCE = "once 模式信号源=jsonl 交叉校验";
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* once 模式失败信号源:空占位形态下的 jsonl 交叉校验(与 visible 模式信号源对齐)。
|
|
52
|
+
* 由 subagent-spawn-once.ts 的 close 分支在等待尾刷容忍窗后调用:
|
|
53
|
+
* - 无 session 事件 → 子会话未建立,直接判异常(不查文件)
|
|
54
|
+
* - 有 session 事件 → findSessionFileById 定位子会话文件;缺失或终结形态异常 → 判异常
|
|
55
|
+
* - 判定正常 → 返回 undefined(不注入 error,维持现行为)
|
|
56
|
+
*
|
|
57
|
+
* @returns 异常形态返回 error 文案(含 sessionId 与判定原因);正常返回 undefined
|
|
58
|
+
*/
|
|
59
|
+
export function crossCheckOnceSessionJsonl(
|
|
60
|
+
capturedSessionId: string | undefined,
|
|
61
|
+
cwd: string,
|
|
62
|
+
exitCode: number | null,
|
|
63
|
+
stderr: string,
|
|
64
|
+
): string | undefined {
|
|
65
|
+
const exitInfo = `exitCode=${exitCode ?? 1},stderr ${stderr.trim() ? "非空" : "空"}——疑似进程加载崩溃经 bash 包装假退出`;
|
|
66
|
+
if (!capturedSessionId) {
|
|
67
|
+
return `${ONCE_CROSS_CHECK_SOURCE}:stdout 无 session 事件,子会话未建立(${exitInfo},bash 包装退出码不可信)`;
|
|
68
|
+
}
|
|
69
|
+
const sessionFile = findSessionFileById(capturedSessionId, cwd);
|
|
70
|
+
if (!sessionFile) {
|
|
71
|
+
return `${ONCE_CROSS_CHECK_SOURCE}:子会话 ${capturedSessionId} 的 session.jsonl 缺失(session 目录中未找到该会话文件)(${exitInfo})`;
|
|
72
|
+
}
|
|
73
|
+
const signal = checkSessionJsonlTermination(sessionFile);
|
|
74
|
+
if (signal.ok) return undefined;
|
|
75
|
+
return `${ONCE_CROSS_CHECK_SOURCE}:子会话 ${capturedSessionId} 的 ${signal.reason}(${exitInfo})`;
|
|
76
|
+
}
|
package/subagent-spawn-once.ts
CHANGED
|
@@ -9,6 +9,14 @@ import { spawn } from "node:child_process";
|
|
|
9
9
|
import { SubagentSession } from "./subagent-session";
|
|
10
10
|
import type { SubagentEvent, SubagentResult } from "./types";
|
|
11
11
|
import { getPiCommand } from "./subagent-utils";
|
|
12
|
+
import { crossCheckOnceSessionJsonl } from "./subagent-jsonl-signal";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 空占位形态下 jsonl 交叉校验前的等待——孤儿进程 jsonl 尾刷容忍窗
|
|
16
|
+
* (与 visible 模式 finish 尾刷同款常数;spec: subagent-spawn-runtime)。
|
|
17
|
+
* 导出仅供测试推进 fake timers 时引用,不进 barrel。
|
|
18
|
+
*/
|
|
19
|
+
export const JSONL_CROSS_CHECK_DELAY_MS = 500;
|
|
12
20
|
|
|
13
21
|
export function spawnOnce(
|
|
14
22
|
task: string,
|
|
@@ -126,11 +134,29 @@ export function spawnOnce(
|
|
|
126
134
|
if (!line.trim()) continue;
|
|
127
135
|
try { session.parseStreamEvent(JSON.parse(line)); } catch { /* skip */ }
|
|
128
136
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
137
|
+
const exitCode = code ?? 1;
|
|
138
|
+
const output = session.formatOutput("(no output)");
|
|
139
|
+
|
|
140
|
+
// 正常路径(有 assistant 文本)零变化:立即返回,不等待、不交叉校验。
|
|
141
|
+
// 触发条件取「未收集到任何文本」而非 isEmptyPlaceholderOutput 的包含匹配,
|
|
142
|
+
// 避免正文里恰好含占位字面量的真实输出被误判。
|
|
143
|
+
if (session.formatOutput("").trim() !== "") {
|
|
144
|
+
session.resolveOnce({ exitCode, output, stderr });
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 空占位形态 → once 模式信号源=jsonl 交叉校验(spec: subagent-spawn-runtime)。
|
|
149
|
+
// 先等 JSONL_CROSS_CHECK_DELAY_MS(bash 异常退出时 pi 孤儿进程尚在跑、jsonl 未刷盘的窗口),
|
|
150
|
+
// 再按 capturedSessionId 定位子会话文件判定;注入 error 后由 runSubagent 归系统性失败档(不重试)。
|
|
151
|
+
setTimeout(() => {
|
|
152
|
+
if (session.isDone) return; // 等待窗内已被 abort / 超时先行 resolve
|
|
153
|
+
session.resolveOnce({
|
|
154
|
+
exitCode,
|
|
155
|
+
output,
|
|
156
|
+
stderr,
|
|
157
|
+
error: crossCheckOnceSessionJsonl(session.capturedSessionId, cwd, code, stderr),
|
|
158
|
+
});
|
|
159
|
+
}, JSONL_CROSS_CHECK_DELAY_MS);
|
|
134
160
|
});
|
|
135
161
|
|
|
136
162
|
proc.on("error", (err) => {
|
|
@@ -1,179 +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
|
-
import {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const
|
|
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
|
-
|
|
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
|
-
}
|
|
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
|
@@ -36,19 +36,27 @@ export function injectParentSession(sessionFilePath: string, parentPath: string)
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
/**
|
|
39
|
-
* 通过 sessionId 查找子代理 session
|
|
40
|
-
*
|
|
39
|
+
* 通过 sessionId 查找子代理 session 文件路径(只读定位,无副作用)。
|
|
40
|
+
* 路径推导:PI_CODING_AGENT_SESSION_DIR ∨ ~/.pi/agent/sessions + cwd slug 子目录
|
|
41
|
+
* + 首行 header.id 匹配(按修改时间降序,只查最近 20 个 .jsonl)。
|
|
42
|
+
*
|
|
43
|
+
* 从 findAndInjectParentSession 抽出(opsx-subarch-cmds-late 7.1),
|
|
44
|
+
* 供 spawnOnce close 分支的 jsonl 交叉校验复用;路径推导逻辑零变化。
|
|
45
|
+
*
|
|
46
|
+
* @returns 命中返回 session 文件路径;未命中(sessionId 空 / 目录缺失 / 无匹配)返回 undefined
|
|
41
47
|
*/
|
|
42
|
-
export function
|
|
43
|
-
if (!sessionId
|
|
48
|
+
export function findSessionFileById(sessionId: string | undefined, cwd: string): string | undefined {
|
|
49
|
+
if (!sessionId) return undefined;
|
|
44
50
|
const baseDir = process.env.PI_CODING_AGENT_SESSION_DIR
|
|
45
51
|
|| path.join(os.homedir(), ".pi/agent/sessions");
|
|
46
52
|
if (!fs.existsSync(baseDir)) return;
|
|
47
53
|
|
|
48
|
-
// 从 cwd 推导 session
|
|
49
|
-
|
|
54
|
+
// 从 cwd 推导 session 子目录——与 pi SDK session-manager 的 slug 公式逐字一致
|
|
55
|
+
// (去掉单个前导分隔符;其余 / 与 \ 与盘符冒号全部换成 -)。只替换 / 时 Windows 盘符
|
|
56
|
+
// 冒号残留 → 永远定位不到 pi 实际写入的目录(findAndInjectParentSession 曾因此在 Windows 静默空转)。
|
|
57
|
+
const cwdSlug = "--" + cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-") + "--";
|
|
50
58
|
const sessionDir = path.join(baseDir, cwdSlug);
|
|
51
|
-
if (!fs.existsSync(sessionDir)) return;
|
|
59
|
+
if (!fs.existsSync(sessionDir)) return undefined;
|
|
52
60
|
|
|
53
61
|
try {
|
|
54
62
|
// 按修改时间降序,优先检查最近的文件
|
|
@@ -67,13 +75,22 @@ export function findAndInjectParentSession(sessionId: string | undefined, parent
|
|
|
67
75
|
fs.closeSync(fd);
|
|
68
76
|
const firstLine = buf.toString("utf-8").split("\n")[0];
|
|
69
77
|
const header = JSON.parse(firstLine);
|
|
70
|
-
if (header.id === sessionId)
|
|
71
|
-
injectParentSession(filePath, parentPath);
|
|
72
|
-
return;
|
|
73
|
-
}
|
|
78
|
+
if (header.id === sessionId) return filePath;
|
|
74
79
|
} catch { /* skip */ }
|
|
75
80
|
}
|
|
76
81
|
} catch { /* skip */ }
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 通过 sessionId 查找子代理 session 文件并注入 parentSession。
|
|
87
|
+
* 用于 spawnOnce 模式(session 文件路径未知,需要按 ID 搜索)。
|
|
88
|
+
* 定位委托 findSessionFileById(抽取后本调用方行为零变化)。
|
|
89
|
+
*/
|
|
90
|
+
export function findAndInjectParentSession(sessionId: string | undefined, parentPath: string, cwd: string): void {
|
|
91
|
+
if (!sessionId || !parentPath) return;
|
|
92
|
+
const filePath = findSessionFileById(sessionId, cwd);
|
|
93
|
+
if (filePath) injectParentSession(filePath, parentPath);
|
|
77
94
|
}
|
|
78
95
|
|
|
79
96
|
/**
|
|
@@ -165,7 +182,7 @@ export function createVisibleTaskDir(
|
|
|
165
182
|
`export PI_SUBAGENT_SESSION='${uSessionFile}'`,
|
|
166
183
|
`export PI_SUBAGENT_NAME='pv-visible'`,
|
|
167
184
|
extraEnvExports,
|
|
168
|
-
`pi --session '${uSessionFile}' --tools ${agentDef.tools.join(",")} --append-system-prompt '${uSystemPromptPath}'${modelArg} @'${uTaskFile}'`,
|
|
185
|
+
`exec pi --session '${uSessionFile}' --tools ${agentDef.tools.join(",")} --append-system-prompt '${uSystemPromptPath}'${modelArg} @'${uTaskFile}'`,
|
|
169
186
|
].filter(Boolean).join("\n");
|
|
170
187
|
fs.writeFileSync(launchScript, script, { mode: 0o700 });
|
|
171
188
|
|