pi-ate-workflow 0.2.4 → 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 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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ate-workflow",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "type": "commonjs",
5
5
  "main": "index.ts",
6
6
  "description": "Workflow orchestration extension for pi-coding-agent — subagent spawning, research workflow, output capture",
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 过滤无匹配时输出 "INFO: No tasks are running..." 且退出码 0,
74
- // 必须按 stdout 是否包含 pid 判定,不能依赖退出码
75
- return out.includes(String(pid));
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,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,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 { detectTerminal, getBackend } from "./term-backend";
20
- import type { TermBackend } from "./term-backend";
21
- import { createSafeCleanup } from "./visible-cleanup";
22
-
23
- export function spawnVisible(
24
- task: string,
25
- cwd: string,
26
- systemPromptPath: string,
27
- agentDef: { tools: string[]; model?: string },
28
- signal?: AbortSignal,
29
- modelOverride?: string,
30
- timeoutMs?: number,
31
- onEvent?: (event: SubagentEvent) => void,
32
- parentSessionPath?: string,
33
- extraEnv?: Record<string, string>,
34
- ): Promise<SubagentResult> {
35
- const { taskDir, sessionFile, launchScript } = createVisibleTaskDir(
36
- task, cwd, systemPromptPath, agentDef, modelOverride, extraEnv,
37
- );
38
-
39
- // 检测终端类型,不可用则降级到后台模式
40
- const termType = detectTerminal();
41
- if (!termType) {
42
- try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
43
- return spawnOnce(
44
- task, cwd, systemPromptPath, agentDef,
45
- signal, modelOverride, timeoutMs, onEvent, parentSessionPath, extraEnv,
46
- );
47
- }
48
-
49
- const backend: TermBackend = getBackend(termType);
50
- let paneId: string;
51
- try {
52
- paneId = backend.splitPane(cwd, launchScript);
53
- } catch {
54
- try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
55
- return spawnOnce(
56
- task, cwd, systemPromptPath, agentDef,
57
- signal, modelOverride, timeoutMs, onEvent, parentSessionPath, extraEnv,
58
- );
59
- }
60
-
61
- // ─── SubagentSession 管理输出收集和退出 ─────────
62
-
63
- const agentSession = new SubagentSession({
64
- onEvent,
65
- beforeResolve: (result) => {
66
- if (parentSessionPath && fs.existsSync(sessionFile)) {
67
- injectParentSession(sessionFile, parentSessionPath);
68
- }
69
- },
70
- });
71
-
72
- return new Promise<SubagentResult>((resolve) => {
73
- let lastLine = 0;
74
- let lastActivityTime = Date.now();
75
-
76
- // 有序安全清理:目录删除永不早于 pane 内进程树死透确认(实现见 visible-cleanup.ts)
77
- const safeCleanup = createSafeCleanup({ taskDir, paneId, backend });
78
-
79
- // ─── 轮询 session.jsonl ─────────────────
80
-
81
- const pollInterval = setInterval(() => {
82
- if (agentSession.isDone) return;
83
-
84
- // 读取新行并解析
85
- try {
86
- if (fs.existsSync(sessionFile)) {
87
- const content = fs.readFileSync(sessionFile, "utf-8");
88
- const lines = content.split("\n").filter((l) => l.trim());
89
- if (lines.length > lastLine) lastActivityTime = Date.now();
90
- for (let i = lastLine; i < lines.length; i++) {
91
- try { agentSession.parseSessionLine(JSON.parse(lines[i])); } catch { /* skip */ }
92
- }
93
- lastLine = lines.length;
94
- }
95
- } catch { /* ignore */ }
96
-
97
- // 检查 pane 是否存活
98
- if (!backend.isPaneAlive(paneId)) finish();
99
-
100
- // 活跃超时:5 分钟无新输出视为停滞
101
- if (Date.now() - lastActivityTime > 5 * 60 * 1000) {
102
- agentSession.resolveOnce({
103
- exitCode: 1,
104
- output: agentSession.formatOutput("(stalled, no output for 5 min)"),
105
- stderr: "",
106
- timedOut: true,
107
- });
108
- clearInterval(pollInterval);
109
- clearTimeout(wallTimer);
110
- void safeCleanup(true);
111
- }
112
- }, 2000);
113
-
114
- // ─── 墙钟超时兜底 ─────────────────────
115
-
116
- const TIMEOUT_MS = timeoutMs ?? 30 * 60 * 1000;
117
- const wallTimer = setTimeout(() => {
118
- agentSession.resolveOnce({
119
- exitCode: 1,
120
- output: agentSession.formatOutput("(timed out)"),
121
- stderr: "",
122
- timedOut: true,
123
- });
124
- clearInterval(pollInterval);
125
- void safeCleanup(true);
126
- }, TIMEOUT_MS);
127
-
128
- // ─── 正常结束:收集剩余输出 ────────────
129
-
130
- function finish() {
131
- if (agentSession.isDone) return;
132
-
133
- try { execSync("sleep 0.5", { stdio: "pipe" }); } catch { /* ignore */ }
134
- try {
135
- if (fs.existsSync(sessionFile)) {
136
- const content = fs.readFileSync(sessionFile, "utf-8");
137
- const lines = content.split("\n").filter((l) => l.trim());
138
- for (let i = lastLine; i < lines.length; i++) {
139
- try { agentSession.parseSessionLine(JSON.parse(lines[i])); } catch { /* skip */ }
140
- }
141
- }
142
- } catch { /* ignore */ }
143
-
144
- agentSession.resolveOnce({
145
- exitCode: 0,
146
- output: agentSession.formatOutput("(no output)"),
147
- stderr: "",
148
- });
149
- clearInterval(pollInterval);
150
- clearTimeout(wallTimer);
151
-
152
- // 有序清理临时目录(等 pane 内进程死透后删除;pane 由自动退出机制自行结束,
153
- // 死透等待期间用户仍可看到最终输出)
154
- void safeCleanup(false);
155
- }
156
-
157
- // ─── AbortSignal ──────────────────────
158
-
159
- if (signal) {
160
- const onAbort = () => {
161
- if (!agentSession.isDone) {
162
- agentSession.resolveOnce({
163
- exitCode: 1,
164
- output: agentSession.formatOutput(""),
165
- stderr: "aborted",
166
- });
167
- clearInterval(pollInterval);
168
- clearTimeout(wallTimer);
169
- void safeCleanup(true);
170
- }
171
- };
172
- if (signal.aborted) onAbort();
173
- else signal.addEventListener("abort", onAbort, { once: true });
174
- }
175
-
176
- // 将 session.result 连接到外部 resolve
177
- agentSession.result.then(resolve);
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
@@ -165,7 +165,7 @@ export function createVisibleTaskDir(
165
165
  `export PI_SUBAGENT_SESSION='${uSessionFile}'`,
166
166
  `export PI_SUBAGENT_NAME='pv-visible'`,
167
167
  extraEnvExports,
168
- `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}'`,
169
169
  ].filter(Boolean).join("\n");
170
170
  fs.writeFileSync(launchScript, script, { mode: 0o700 });
171
171