pi-ate-workflow 0.1.0 → 0.2.1
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/README.en.md +2 -0
- package/README.md +2 -0
- package/agents.ts +2 -0
- package/index.ts +97 -18
- package/intercom-bridge.ts +53 -0
- package/package.json +59 -48
- package/paths.ts +7 -0
- package/research-scan.ts +113 -65
- package/research-utils.ts +118 -107
- package/research.ts +53 -52
- package/subagent-model.ts +82 -0
- package/subagent-session.ts +132 -0
- package/subagent-spawn-once.ts +83 -81
- package/subagent-spawn-visible.ts +106 -119
- package/subagent-utils.ts +130 -3
- package/subagent.ts +49 -10
- package/term-backend.ts +33 -0
- package/term-tmux.ts +86 -0
- package/term-wezterm.ts +112 -0
- package/tests/create-visible-taskdir.test.ts +76 -0
- package/tests/intercom-bridge.test.ts +67 -0
- package/tests/output-constraints.test.ts +34 -0
- package/tests/research-analysis.test.ts +6 -6
- package/tests/research.test.ts +2 -1
- package/tests/smoke.subagent.test.ts +22 -96
- package/tests/spawn-once-extra-env.test.ts +91 -0
- package/tests/subagent-api.test.ts +81 -40
- package/tests/subagent-model.test.ts +90 -0
- package/tests/subagent-session.test.ts +83 -0
- package/tests/subagent-spawn-visible.test.ts +69 -59
- package/tests/test-helpers.ts +2 -2
- package/tests/timeout-config.test.ts +74 -0
- package/timeout-config.ts +55 -0
- package/tsconfig.json +10 -0
- package/vitest.config.ts +14 -21
- package/agent-loader.ts +0 -88
- package/tests/agent-loader.test.ts +0 -183
package/subagent-spawn-once.ts
CHANGED
|
@@ -2,29 +2,14 @@
|
|
|
2
2
|
* workflow: 后台 spawn 实现
|
|
3
3
|
*
|
|
4
4
|
* spawnOnce — 后台模式(pipe stdout,流式解析 JSON)
|
|
5
|
+
* 使用 SubagentSession 管理输出收集和退出控制
|
|
5
6
|
*/
|
|
6
7
|
|
|
7
|
-
import { spawn
|
|
8
|
-
import
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { SubagentSession } from "./subagent-session";
|
|
10
|
+
import type { SubagentEvent, SubagentResult } from "./types";
|
|
9
11
|
import { getPiCommand } from "./subagent-utils";
|
|
10
12
|
|
|
11
|
-
/** pi JSON 模式输出的事件行 */
|
|
12
|
-
interface PiJsonEvent {
|
|
13
|
-
type: string;
|
|
14
|
-
id?: string;
|
|
15
|
-
toolName?: string;
|
|
16
|
-
args?: Record<string, unknown>;
|
|
17
|
-
assistantMessageEvent?: { type: string; delta?: string };
|
|
18
|
-
message?: PiMessage;
|
|
19
|
-
messages?: PiMessage[];
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** pi JSON 模式中的消息结构 */
|
|
23
|
-
interface PiMessage {
|
|
24
|
-
role?: string;
|
|
25
|
-
content?: Array<{ type: string; text?: string }>;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
13
|
export function spawnOnce(
|
|
29
14
|
task: string,
|
|
30
15
|
cwd: string,
|
|
@@ -34,6 +19,8 @@ export function spawnOnce(
|
|
|
34
19
|
modelOverride?: string,
|
|
35
20
|
timeoutMs?: number,
|
|
36
21
|
onEvent?: (event: SubagentEvent) => void,
|
|
22
|
+
parentSessionPath?: string,
|
|
23
|
+
extraEnv?: Record<string, string>,
|
|
37
24
|
): Promise<SubagentResult> {
|
|
38
25
|
const pi = getPiCommand();
|
|
39
26
|
const args = [
|
|
@@ -48,117 +35,132 @@ export function spawnOnce(
|
|
|
48
35
|
}
|
|
49
36
|
args.push(task);
|
|
50
37
|
|
|
38
|
+
const session = new SubagentSession({ onEvent });
|
|
39
|
+
|
|
51
40
|
return new Promise<SubagentResult>((resolve) => {
|
|
52
|
-
const proc = spawn(pi.command, args, {
|
|
41
|
+
const proc = spawn(pi.command, args, {
|
|
42
|
+
cwd,
|
|
43
|
+
shell: false,
|
|
44
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
45
|
+
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
|
|
46
|
+
});
|
|
53
47
|
|
|
54
48
|
let stdout = "";
|
|
55
49
|
let stderr = "";
|
|
56
|
-
let allAssistantTexts: string[] = [];
|
|
57
50
|
let processedOffset = 0;
|
|
58
|
-
let resolved = false;
|
|
59
|
-
let capturedSessionId: string | undefined;
|
|
60
51
|
const sessionIdRegex = /\{"type":"session","version":\d+,"id":"([^"]+)"/;
|
|
61
52
|
|
|
62
|
-
const collectAssistantTexts = (message: PiMessage) => {
|
|
63
|
-
if (message?.role !== "assistant") return;
|
|
64
|
-
for (const part of message.content ?? []) {
|
|
65
|
-
if (part.type === "text" && part.text.trim()) {
|
|
66
|
-
allAssistantTexts.push(part.text);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
const handleEvent = (event: PiJsonEvent) => {
|
|
72
|
-
if (event.type === "session" && event.id && !capturedSessionId) capturedSessionId = event.id;
|
|
73
|
-
if (event.type === "tool_execution_start") onEvent?.({ type: "tool", toolName: event.toolName, toolArgs: event.args });
|
|
74
|
-
if (event.type === "message_update" && event.assistantMessageEvent?.type === "text_delta") onEvent?.({ type: "thinking", text: event.assistantMessageEvent.delta });
|
|
75
|
-
if (event.type === "message_end") collectAssistantTexts(event.message);
|
|
76
|
-
if (event.type === "turn_end") { collectAssistantTexts(event.message); onEvent?.({ type: "message", message: event.message }); }
|
|
77
|
-
if (event.type === "agent_end" && Array.isArray(event.messages)) { for (const msg of event.messages) collectAssistantTexts(msg); }
|
|
78
|
-
};
|
|
79
|
-
|
|
80
53
|
proc.stdout.on("data", (data: Buffer) => {
|
|
81
54
|
stdout += data.toString();
|
|
82
55
|
const newData = stdout.slice(processedOffset);
|
|
83
56
|
for (const line of newData.split("\n")) {
|
|
84
57
|
if (!line.trim()) continue;
|
|
85
|
-
try {
|
|
58
|
+
try { session.parseStreamEvent(JSON.parse(line)); } catch { /* skip non-JSON */ }
|
|
86
59
|
}
|
|
87
60
|
processedOffset = stdout.lastIndexOf("\n") + 1;
|
|
88
61
|
});
|
|
89
62
|
|
|
90
|
-
|
|
63
|
+
// 额外监听:捕获 sessionId(stdout 里可能跨 chunk 断裂)
|
|
64
|
+
const checkSessionId = (text: string) => {
|
|
65
|
+
if (!session.capturedSessionId) {
|
|
66
|
+
const m = text.match(sessionIdRegex);
|
|
67
|
+
if (m) session.capturedSessionId = m[1];
|
|
68
|
+
}
|
|
69
|
+
};
|
|
91
70
|
const origOnData = proc.stdout.listeners("data").pop();
|
|
92
71
|
if (origOnData) proc.stdout.on("data", (buf: Buffer) => checkSessionId(buf.toString()));
|
|
93
72
|
|
|
94
73
|
proc.stderr.on("data", (data: Buffer) => { stderr += data.toString(); });
|
|
95
74
|
|
|
75
|
+
// ─── 清理辅助 ─────────────────────────────
|
|
76
|
+
|
|
77
|
+
const killProc = () => {
|
|
78
|
+
proc.kill("SIGTERM");
|
|
79
|
+
setTimeout(() => { if (!proc.killed) proc.kill("SIGKILL"); }, 5000);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const clearTimers = () => {
|
|
83
|
+
clearTimeout(wallTimer);
|
|
84
|
+
clearInterval(stallChecker);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// ─── 计时器 ─────────────────────────────────
|
|
88
|
+
|
|
96
89
|
// 活跃超时:有新输出就续命
|
|
97
90
|
let lastActivityTime = Date.now();
|
|
98
91
|
const STALL_MS = 5 * 60 * 1000;
|
|
99
92
|
const stallChecker = setInterval(() => {
|
|
100
|
-
if (
|
|
93
|
+
if (session.isDone) { clearInterval(stallChecker); return; }
|
|
101
94
|
if (Date.now() - lastActivityTime > STALL_MS) {
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
95
|
+
session.resolveOnce({
|
|
96
|
+
exitCode: 1,
|
|
97
|
+
output: session.formatOutput("(stalled, no output for 5 min)"),
|
|
98
|
+
stderr,
|
|
99
|
+
timedOut: true,
|
|
100
|
+
});
|
|
101
|
+
killProc();
|
|
108
102
|
}
|
|
109
103
|
}, 5000);
|
|
110
104
|
|
|
111
|
-
// 更新活跃时间(在 stdout data handler 里追踪)
|
|
112
105
|
proc.stdout.prependListener("data", () => { lastActivityTime = Date.now(); });
|
|
113
106
|
|
|
114
107
|
// 墙钟兜底
|
|
115
108
|
const TIMEOUT_MS = timeoutMs ?? 30 * 60 * 1000;
|
|
116
109
|
const wallTimer = setTimeout(() => {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
110
|
+
session.resolveOnce({
|
|
111
|
+
exitCode: 1,
|
|
112
|
+
output: session.formatOutput("(timed out)"),
|
|
113
|
+
stderr,
|
|
114
|
+
timedOut: true,
|
|
115
|
+
});
|
|
116
|
+
killProc();
|
|
124
117
|
}, TIMEOUT_MS);
|
|
125
118
|
|
|
126
|
-
|
|
127
|
-
clearTimeout(wallTimer);
|
|
128
|
-
clearInterval(stallChecker);
|
|
129
|
-
if (resolved) return;
|
|
130
|
-
resolved = true;
|
|
119
|
+
// ─── 进程事件 ─────────────────────────────
|
|
131
120
|
|
|
121
|
+
proc.on("close", (code) => {
|
|
122
|
+
clearTimers();
|
|
123
|
+
// 处理剩余未解析的 stdout
|
|
132
124
|
const remaining = stdout.slice(processedOffset);
|
|
133
125
|
for (const line of remaining.split("\n")) {
|
|
134
126
|
if (!line.trim()) continue;
|
|
135
|
-
try {
|
|
127
|
+
try { session.parseStreamEvent(JSON.parse(line)); } catch { /* skip */ }
|
|
136
128
|
}
|
|
137
|
-
|
|
138
|
-
|
|
129
|
+
session.resolveOnce({
|
|
130
|
+
exitCode: code ?? 1,
|
|
131
|
+
output: session.formatOutput("(no output)"),
|
|
132
|
+
stderr,
|
|
133
|
+
});
|
|
139
134
|
});
|
|
140
135
|
|
|
141
136
|
proc.on("error", (err) => {
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
137
|
+
clearTimers();
|
|
138
|
+
session.resolveOnce({
|
|
139
|
+
exitCode: 1,
|
|
140
|
+
output: session.formatOutput(""),
|
|
141
|
+
stderr: err.message,
|
|
142
|
+
error: err.message,
|
|
143
|
+
});
|
|
147
144
|
});
|
|
148
145
|
|
|
146
|
+
// ─── AbortSignal ──────────────────────────
|
|
147
|
+
|
|
149
148
|
if (signal) {
|
|
150
|
-
const
|
|
151
|
-
if (!
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
149
|
+
const onAbort = () => {
|
|
150
|
+
if (!session.isDone) {
|
|
151
|
+
session.resolveOnce({
|
|
152
|
+
exitCode: 1,
|
|
153
|
+
output: session.formatOutput(""),
|
|
154
|
+
stderr: "aborted",
|
|
155
|
+
});
|
|
156
|
+
killProc();
|
|
158
157
|
}
|
|
159
158
|
};
|
|
160
|
-
if (signal.aborted)
|
|
161
|
-
else signal.addEventListener("abort",
|
|
159
|
+
if (signal.aborted) onAbort();
|
|
160
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
162
161
|
}
|
|
162
|
+
|
|
163
|
+
// 将 session.result 连接到外部 resolve
|
|
164
|
+
session.result.then(resolve);
|
|
163
165
|
});
|
|
164
166
|
}
|
|
@@ -1,27 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* workflow: 可见模式 spawn 实现
|
|
3
3
|
*
|
|
4
|
-
* spawnVisible —
|
|
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 刷盘)。
|
|
5
11
|
*/
|
|
6
12
|
|
|
7
|
-
import {
|
|
13
|
+
import { execSync } from "node:child_process";
|
|
8
14
|
import * as fs from "node:fs";
|
|
9
|
-
import
|
|
10
|
-
import * as os from "node:os";
|
|
11
|
-
import type { SubagentResult, SubagentEvent } from "./types";
|
|
15
|
+
import type { SubagentEvent, SubagentResult } from "./types";
|
|
12
16
|
import { spawnOnce } from "./subagent-spawn-once";
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
content?: Array<{ type: string; text?: string }>;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** 关闭 tmux 窗格 */
|
|
21
|
-
function closeTmuxPane(paneId: string): void {
|
|
22
|
-
if (!/^%\d+$/.test(paneId)) return;
|
|
23
|
-
try { execFileSync("tmux", ["kill-pane", "-t", paneId], { stdio: "pipe" }); } catch { /* ignore */ }
|
|
24
|
-
}
|
|
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";
|
|
25
21
|
|
|
26
22
|
export function spawnVisible(
|
|
27
23
|
task: string,
|
|
@@ -32,163 +28,154 @@ export function spawnVisible(
|
|
|
32
28
|
modelOverride?: string,
|
|
33
29
|
timeoutMs?: number,
|
|
34
30
|
onEvent?: (event: SubagentEvent) => void,
|
|
31
|
+
parentSessionPath?: string,
|
|
32
|
+
extraEnv?: Record<string, string>,
|
|
35
33
|
): Promise<SubagentResult> {
|
|
36
|
-
const taskDir =
|
|
37
|
-
|
|
38
|
-
fs.writeFileSync(taskFile, task, { encoding: "utf-8" });
|
|
39
|
-
|
|
40
|
-
const sessionFile = path.join(taskDir, "session.jsonl");
|
|
41
|
-
|
|
42
|
-
const subagentDonePath = path.join(
|
|
43
|
-
os.homedir(), ".pi/agent/git/github.com/HazAT/pi-interactive-subagents/pi-extension/subagents/subagent-done.ts"
|
|
34
|
+
const { taskDir, sessionFile, launchScript } = createVisibleTaskDir(
|
|
35
|
+
task, cwd, systemPromptPath, agentDef, modelOverride, extraEnv,
|
|
44
36
|
);
|
|
45
37
|
|
|
46
|
-
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
`export PI_SUBAGENT_NAME='pv-visible'`,
|
|
56
|
-
`pi --session '${sessionFile}' -e '${subagentDonePath}' --tools ${agentDef.tools.join(",")} --append-system-prompt ${systemPromptPath}${modelArg} @${taskFile}`,
|
|
57
|
-
].join("\n");
|
|
58
|
-
fs.writeFileSync(launchScript, script, { mode: 0o700 });
|
|
38
|
+
// 检测终端类型,不可用则降级到后台模式
|
|
39
|
+
const termType = detectTerminal();
|
|
40
|
+
if (!termType) {
|
|
41
|
+
try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
|
|
42
|
+
return spawnOnce(
|
|
43
|
+
task, cwd, systemPromptPath, agentDef,
|
|
44
|
+
signal, modelOverride, timeoutMs, onEvent, parentSessionPath, extraEnv,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
59
47
|
|
|
48
|
+
const backend: TermBackend = getBackend(termType);
|
|
60
49
|
let paneId: string;
|
|
61
50
|
try {
|
|
62
|
-
|
|
63
|
-
const args = ["split-window", "-h", "-d"];
|
|
64
|
-
if (fromPane) args.push("-t", fromPane);
|
|
65
|
-
args.push("-P", "-F", "#{pane_id}", "bash", launchScript);
|
|
66
|
-
paneId = execFileSync("tmux", args, { encoding: "utf8" }).trim();
|
|
51
|
+
paneId = backend.splitPane(cwd, launchScript);
|
|
67
52
|
} catch {
|
|
68
53
|
try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
|
|
69
|
-
return spawnOnce(
|
|
54
|
+
return spawnOnce(
|
|
55
|
+
task, cwd, systemPromptPath, agentDef,
|
|
56
|
+
signal, modelOverride, timeoutMs, onEvent, parentSessionPath, extraEnv,
|
|
57
|
+
);
|
|
70
58
|
}
|
|
71
59
|
|
|
72
|
-
|
|
73
|
-
let allTexts: string[] = [];
|
|
74
|
-
let capturedSessionId: string | undefined;
|
|
60
|
+
// ─── SubagentSession 管理输出收集和退出 ─────────
|
|
75
61
|
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if (
|
|
80
|
-
|
|
62
|
+
const agentSession = new SubagentSession({
|
|
63
|
+
onEvent,
|
|
64
|
+
beforeResolve: (result) => {
|
|
65
|
+
if (parentSessionPath && fs.existsSync(sessionFile)) {
|
|
66
|
+
injectParentSession(sessionFile, parentSessionPath);
|
|
81
67
|
}
|
|
82
|
-
}
|
|
83
|
-
};
|
|
68
|
+
},
|
|
69
|
+
});
|
|
84
70
|
|
|
85
71
|
return new Promise<SubagentResult>((resolve) => {
|
|
86
|
-
let
|
|
72
|
+
let lastLine = 0;
|
|
87
73
|
let lastActivityTime = Date.now();
|
|
88
74
|
|
|
75
|
+
const cleanup = () => {
|
|
76
|
+
backend.killPane(paneId);
|
|
77
|
+
try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// ─── 轮询 session.jsonl ─────────────────
|
|
81
|
+
|
|
89
82
|
const pollInterval = setInterval(() => {
|
|
90
|
-
if (
|
|
83
|
+
if (agentSession.isDone) return;
|
|
91
84
|
|
|
85
|
+
// 读取新行并解析
|
|
92
86
|
try {
|
|
93
87
|
if (fs.existsSync(sessionFile)) {
|
|
94
88
|
const content = fs.readFileSync(sessionFile, "utf-8");
|
|
95
|
-
const lines = content.split("\n").filter(l => l.trim());
|
|
89
|
+
const lines = content.split("\n").filter((l) => l.trim());
|
|
96
90
|
if (lines.length > lastLine) lastActivityTime = Date.now();
|
|
97
91
|
for (let i = lastLine; i < lines.length; i++) {
|
|
98
|
-
try {
|
|
99
|
-
const entry = JSON.parse(lines[i]);
|
|
100
|
-
if (entry.type === "session" && entry.id) capturedSessionId = entry.id;
|
|
101
|
-
if (entry.type === "message" && entry.message) collectTexts(entry.message);
|
|
102
|
-
if (entry.type === "tool_execution_start") onEvent?.({ type: "tool", toolName: entry.toolName, toolArgs: entry.args });
|
|
103
|
-
if (entry.type === "agent_end" && Array.isArray(entry.messages)) {
|
|
104
|
-
for (const msg of entry.messages) collectTexts(msg);
|
|
105
|
-
}
|
|
106
|
-
} catch { /* skip */ }
|
|
92
|
+
try { agentSession.parseSessionLine(JSON.parse(lines[i])); } catch { /* skip */ }
|
|
107
93
|
}
|
|
108
94
|
lastLine = lines.length;
|
|
109
95
|
}
|
|
110
96
|
} catch { /* ignore */ }
|
|
111
97
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
execFileSync("tmux", ["list-panes", "-t", paneId], { stdio: "pipe" });
|
|
115
|
-
} catch {
|
|
116
|
-
finish();
|
|
117
|
-
}
|
|
98
|
+
// 检查 pane 是否存活
|
|
99
|
+
if (!backend.isPaneAlive(paneId)) finish();
|
|
118
100
|
|
|
119
101
|
// 活跃超时:5 分钟无新输出视为停滞
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
102
|
+
if (Date.now() - lastActivityTime > 5 * 60 * 1000) {
|
|
103
|
+
agentSession.resolveOnce({
|
|
104
|
+
exitCode: 1,
|
|
105
|
+
output: agentSession.formatOutput("(stalled, no output for 5 min)"),
|
|
106
|
+
stderr: "",
|
|
107
|
+
timedOut: true,
|
|
108
|
+
});
|
|
124
109
|
clearInterval(pollInterval);
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const output = allTexts.length > 0
|
|
128
|
-
? [...new Set(allTexts)].join("\n\n---\n\n")
|
|
129
|
-
: "(stalled, no output for 5 min)";
|
|
130
|
-
resolve({ exitCode: 1, output, stderr: "", timedOut: true, subSessionId: capturedSessionId });
|
|
110
|
+
clearTimeout(wallTimer);
|
|
111
|
+
cleanup();
|
|
131
112
|
}
|
|
132
113
|
}, 2000);
|
|
133
114
|
|
|
134
|
-
//
|
|
115
|
+
// ─── 墙钟超时兜底 ─────────────────────
|
|
116
|
+
|
|
135
117
|
const TIMEOUT_MS = timeoutMs ?? 30 * 60 * 1000;
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
118
|
+
const wallTimer = setTimeout(() => {
|
|
119
|
+
agentSession.resolveOnce({
|
|
120
|
+
exitCode: 1,
|
|
121
|
+
output: agentSession.formatOutput("(timed out)"),
|
|
122
|
+
stderr: "",
|
|
123
|
+
timedOut: true,
|
|
124
|
+
});
|
|
139
125
|
clearInterval(pollInterval);
|
|
140
|
-
|
|
141
|
-
try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
|
|
142
|
-
const output = allTexts.length > 0
|
|
143
|
-
? [...new Set(allTexts)].join("\n\n---\n\n")
|
|
144
|
-
: "(timed out)";
|
|
145
|
-
resolve({ exitCode: 1, output, stderr: "", timedOut: true, subSessionId: capturedSessionId });
|
|
126
|
+
cleanup();
|
|
146
127
|
}, TIMEOUT_MS);
|
|
147
128
|
|
|
129
|
+
// ─── 正常结束:收集剩余输出 ────────────
|
|
130
|
+
|
|
148
131
|
function finish() {
|
|
149
|
-
if (
|
|
150
|
-
resolved = true;
|
|
151
|
-
clearInterval(pollInterval);
|
|
152
|
-
clearTimeout(timer);
|
|
132
|
+
if (agentSession.isDone) return;
|
|
153
133
|
|
|
154
|
-
try {
|
|
134
|
+
try { execSync("sleep 0.5", { stdio: "pipe" }); } catch { /* ignore */ }
|
|
155
135
|
try {
|
|
156
136
|
if (fs.existsSync(sessionFile)) {
|
|
157
137
|
const content = fs.readFileSync(sessionFile, "utf-8");
|
|
158
|
-
const lines = content.split("\n").filter(l => l.trim());
|
|
138
|
+
const lines = content.split("\n").filter((l) => l.trim());
|
|
159
139
|
for (let i = lastLine; i < lines.length; i++) {
|
|
160
|
-
try {
|
|
161
|
-
const entry = JSON.parse(lines[i]);
|
|
162
|
-
if (entry.type === "message" && entry.message) collectTexts(entry.message);
|
|
163
|
-
if (entry.type === "agent_end" && Array.isArray(entry.messages)) {
|
|
164
|
-
for (const msg of entry.messages) collectTexts(msg);
|
|
165
|
-
}
|
|
166
|
-
} catch { /* skip */ }
|
|
140
|
+
try { agentSession.parseSessionLine(JSON.parse(lines[i])); } catch { /* skip */ }
|
|
167
141
|
}
|
|
168
142
|
}
|
|
169
143
|
} catch { /* ignore */ }
|
|
170
144
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
: "(no output)"
|
|
145
|
+
agentSession.resolveOnce({
|
|
146
|
+
exitCode: 0,
|
|
147
|
+
output: agentSession.formatOutput("(no output)"),
|
|
148
|
+
stderr: "",
|
|
149
|
+
});
|
|
150
|
+
clearInterval(pollInterval);
|
|
151
|
+
clearTimeout(wallTimer);
|
|
174
152
|
|
|
175
|
-
|
|
176
|
-
|
|
153
|
+
// 延迟清理临时目录(让用户看到最终输出;pane 由自动退出机制自行结束)
|
|
154
|
+
setTimeout(() => {
|
|
155
|
+
try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
|
|
156
|
+
}, 5000);
|
|
177
157
|
}
|
|
178
158
|
|
|
159
|
+
// ─── AbortSignal ──────────────────────
|
|
160
|
+
|
|
179
161
|
if (signal) {
|
|
180
|
-
const
|
|
181
|
-
if (!
|
|
182
|
-
|
|
162
|
+
const onAbort = () => {
|
|
163
|
+
if (!agentSession.isDone) {
|
|
164
|
+
agentSession.resolveOnce({
|
|
165
|
+
exitCode: 1,
|
|
166
|
+
output: agentSession.formatOutput(""),
|
|
167
|
+
stderr: "aborted",
|
|
168
|
+
});
|
|
183
169
|
clearInterval(pollInterval);
|
|
184
|
-
clearTimeout(
|
|
185
|
-
|
|
186
|
-
try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
|
|
187
|
-
resolve({ exitCode: 1, output: allTexts.join("\n\n---\n\n") || "", stderr: "aborted", subSessionId: capturedSessionId });
|
|
170
|
+
clearTimeout(wallTimer);
|
|
171
|
+
cleanup();
|
|
188
172
|
}
|
|
189
173
|
};
|
|
190
|
-
if (signal.aborted)
|
|
191
|
-
else signal.addEventListener("abort",
|
|
174
|
+
if (signal.aborted) onAbort();
|
|
175
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
192
176
|
}
|
|
177
|
+
|
|
178
|
+
// 将 session.result 连接到外部 resolve
|
|
179
|
+
agentSession.result.then(resolve);
|
|
193
180
|
});
|
|
194
181
|
}
|