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.
@@ -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, execSync } from "node:child_process";
8
- import type { SubagentResult, SubagentEvent } from "./types";
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, { cwd, shell: false, stdio: ["ignore", "pipe", "pipe"] });
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 { handleEvent(JSON.parse(line)); } catch { /* skip non-JSON */ }
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
- const checkSessionId = (text: string) => { if (!capturedSessionId) { const m = text.match(sessionIdRegex); if (m) capturedSessionId = m[1]; } };
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 (resolved) { clearInterval(stallChecker); return; }
93
+ if (session.isDone) { clearInterval(stallChecker); return; }
101
94
  if (Date.now() - lastActivityTime > STALL_MS) {
102
- resolved = true;
103
- clearTimeout(wallTimer);
104
- clearInterval(stallChecker);
105
- proc.kill("SIGTERM");
106
- setTimeout(() => { if (!proc.killed) proc.kill("SIGKILL"); }, 5000);
107
- resolve({ exitCode: 1, output: [...new Set(allAssistantTexts)].join("\n\n---\n\n") || "(stalled, no output for 5 min)", stderr, timedOut: true, subSessionId: capturedSessionId });
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
- if (resolved) return;
118
- resolved = true;
119
- clearInterval(stallChecker);
120
- clearTimeout(wallTimer);
121
- proc.kill("SIGTERM");
122
- setTimeout(() => { if (!proc.killed) proc.kill("SIGKILL"); }, 5000);
123
- resolve({ exitCode: 1, output: [...new Set(allAssistantTexts)].join("\n\n---\n\n") || "(timed out)", stderr, timedOut: true, subSessionId: capturedSessionId });
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
- proc.on("close", (code) => {
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 { handleEvent(JSON.parse(line)); } catch { /* skip */ }
127
+ try { session.parseStreamEvent(JSON.parse(line)); } catch { /* skip */ }
136
128
  }
137
-
138
- resolve({ exitCode: code ?? 1, output: [...new Set(allAssistantTexts)].join("\n\n---\n\n") || "(no output)", stderr, subSessionId: capturedSessionId });
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
- clearTimeout(wallTimer);
143
- clearInterval(stallChecker);
144
- if (resolved) return;
145
- resolved = true;
146
- resolve({ exitCode: 1, output: allAssistantTexts.join("\n\n---\n\n") || "", stderr: err.message, error: err.message, subSessionId: capturedSessionId });
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 kill = () => {
151
- if (!resolved) {
152
- resolved = true;
153
- clearTimeout(wallTimer);
154
- clearInterval(stallChecker);
155
- proc.kill("SIGTERM");
156
- if (capturedSessionId) resolve({ exitCode: 1, output: allAssistantTexts.join("\n\n---\n\n") || "", stderr: "aborted", subSessionId: capturedSessionId });
157
- setTimeout(() => { if (!proc.killed) proc.kill("SIGKILL"); }, 5000);
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) kill();
161
- else signal.addEventListener("abort", kill, { once: true });
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 — tmux 窗格中启动 pi 子进程,用户可实时观察
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 { execFileSync } from "node:child_process";
13
+ import { execSync } from "node:child_process";
8
14
  import * as fs from "node:fs";
9
- import * as path from "node:path";
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
- /** pi JSON 模式中的消息结构 */
15
- interface PiMessage {
16
- role?: string;
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 = fs.mkdtempSync(path.join(os.tmpdir(), "pi-visible-"));
37
- const taskFile = path.join(taskDir, "task.txt");
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
- const modelArg = (modelOverride || agentDef.model) ? ` --model ${modelOverride || agentDef.model}` : "";
47
- const launchScript = path.join(taskDir, "launch.sh");
48
- const script = [
49
- "#!/bin/bash",
50
- "export FNM_PATH=\"$HOME/.local/share/fnm\"",
51
- "if [ -d \"$FNM_PATH\" ]; then export PATH=\"$FNM_PATH:$PATH\" && eval \"$(fnm env --shell bash)\"; fi",
52
- `cd "${cwd}"`,
53
- "export PI_SUBAGENT_AUTO_EXIT=1",
54
- `export PI_SUBAGENT_SESSION='${sessionFile}'`,
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
- const fromPane = process.env.TMUX_PANE;
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(task, cwd, systemPromptPath, agentDef, signal, modelOverride, timeoutMs, onEvent);
54
+ return spawnOnce(
55
+ task, cwd, systemPromptPath, agentDef,
56
+ signal, modelOverride, timeoutMs, onEvent, parentSessionPath, extraEnv,
57
+ );
70
58
  }
71
59
 
72
- let lastLine = 0;
73
- let allTexts: string[] = [];
74
- let capturedSessionId: string | undefined;
60
+ // ─── SubagentSession 管理输出收集和退出 ─────────
75
61
 
76
- const collectTexts = (message: PiMessage) => {
77
- if (message?.role !== "assistant") return;
78
- for (const part of message.content ?? []) {
79
- if (part.type === "text" && part.text.trim()) {
80
- allTexts.push(part.text);
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 resolved = false;
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 (resolved) return;
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
- try {
113
- if (!/^%\d+$/.test(paneId)) { finish(); return; }
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
- const STALL_MS = 5 * 60 * 1000;
121
- if (Date.now() - lastActivityTime > STALL_MS) {
122
- if (resolved) return;
123
- resolved = true;
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
- closeTmuxPane(paneId);
126
- try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
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
- // 墙钟超时改为兜底(30 分钟绝对上限)
115
+ // ─── 墙钟超时兜底 ─────────────────────
116
+
135
117
  const TIMEOUT_MS = timeoutMs ?? 30 * 60 * 1000;
136
- const timer = setTimeout(() => {
137
- if (resolved) return;
138
- resolved = true;
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
- closeTmuxPane(paneId);
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 (resolved) return;
150
- resolved = true;
151
- clearInterval(pollInterval);
152
- clearTimeout(timer);
132
+ if (agentSession.isDone) return;
153
133
 
154
- try { execFileSync("sleep", ["0.5"], { stdio: "pipe" }); } catch { /* ignore */ }
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
- const output = allTexts.length > 0
172
- ? [...new Set(allTexts)].join("\n\n---\n\n")
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
- setTimeout(() => { try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ } }, 5000);
176
- resolve({ exitCode: 0, output, stderr: "", subSessionId: capturedSessionId });
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 kill = () => {
181
- if (!resolved) {
182
- resolved = true;
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(timer);
185
- closeTmuxPane(paneId);
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) kill();
191
- else signal.addEventListener("abort", kill, { once: true });
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
  }