pi-ate-workflow 0.1.0

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.
Files changed (46) hide show
  1. package/README.en.md +102 -0
  2. package/README.md +104 -0
  3. package/agent-loader.ts +88 -0
  4. package/index.ts +18 -0
  5. package/output.ts +89 -0
  6. package/package.json +50 -0
  7. package/research-analysis.ts +64 -0
  8. package/research-catalog.ts +33 -0
  9. package/research-scan.ts +65 -0
  10. package/research-state.ts +46 -0
  11. package/research-types.ts +53 -0
  12. package/research-utils.ts +107 -0
  13. package/research.ts +52 -0
  14. package/state.ts +121 -0
  15. package/subagent-spawn-once.ts +164 -0
  16. package/subagent-spawn-visible.ts +194 -0
  17. package/subagent-utils.ts +38 -0
  18. package/subagent.ts +93 -0
  19. package/tests/agent-loader.test.ts +183 -0
  20. package/tests/agent-schema-extra.test.ts +107 -0
  21. package/tests/agent-schema.test.ts +116 -0
  22. package/tests/output.test.ts +107 -0
  23. package/tests/research-analysis.test.ts +155 -0
  24. package/tests/research-extra.test.ts +175 -0
  25. package/tests/research.test.ts +418 -0
  26. package/tests/smoke.subagent.test.ts +127 -0
  27. package/tests/state-manager.test.ts +245 -0
  28. package/tests/state.test.ts +298 -0
  29. package/tests/subagent-api.test.ts +158 -0
  30. package/tests/subagent-spawn-once.test.ts +154 -0
  31. package/tests/subagent-spawn-visible.test.ts +139 -0
  32. package/tests/subagent-utils.test.ts +124 -0
  33. package/tests/test-helpers.ts +40 -0
  34. package/tests/ui-updater.test.ts +129 -0
  35. package/tests/utils-find-session.test.ts +114 -0
  36. package/tests/utils-status-summary.test.ts +158 -0
  37. package/tests/utils.test.ts +48 -0
  38. package/tests/widget.test.ts +114 -0
  39. package/tests/workflow-execution.test.ts +165 -0
  40. package/tests/workflow-registration.test.ts +155 -0
  41. package/tests/workflow.test.ts +207 -0
  42. package/types.ts +24 -0
  43. package/utils.ts +74 -0
  44. package/vitest.config.ts +21 -0
  45. package/widget.ts +104 -0
  46. package/workflow.ts +113 -0
@@ -0,0 +1,53 @@
1
+ /**
2
+ * workflow: 研究管道类型定义
3
+ */
4
+
5
+ /** 文章条目 */
6
+ export interface Article {
7
+ /** sha256(url)[:12] */
8
+ id: string;
9
+ url: string;
10
+ title: string;
11
+ source_type: "academic" | "report" | "blog" | "other";
12
+ /** ISO datetime */
13
+ found_at: string;
14
+ /** 1-10 */
15
+ score: number;
16
+ /** sources/{source_name}/ */
17
+ dir: string;
18
+ /** {timestamp}_article.md */
19
+ file: string;
20
+ }
21
+
22
+ /** 文章在各子代理中的分析状态 */
23
+ export interface ArticleAnalysis {
24
+ direction: "pending" | "done" | "skipped";
25
+ source_eval: "pending" | "done" | "skipped";
26
+ interpretation: "pending" | "done" | "skipped";
27
+ }
28
+
29
+ /** 研究方向 */
30
+ export interface Direction {
31
+ id: string;
32
+ title: string;
33
+ description: string;
34
+ source_dirs: string[];
35
+ actionability: "high" | "medium" | "low";
36
+ status: "proposed" | "verifying" | "verified" | "rejected";
37
+ reject_reason?: string;
38
+ /** directions/{timestamp}_directions.md */
39
+ file?: string;
40
+ }
41
+
42
+ /** 主题研究状态 */
43
+ export interface TopicResearchState {
44
+ topic: string;
45
+ slug: string;
46
+ created_at: string;
47
+ queries_searched: Array<{ query: string; searched_at: string }>;
48
+ /** key = article.id */
49
+ articles: Record<string, ArticleAnalysis>;
50
+ directions: Direction[];
51
+ iteration: number;
52
+ max_iterations: number;
53
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * workflow: 研究管道工具函数
3
+ *
4
+ * 通用工具:slugify、urlToId、parseFrontmatter、getTimestamp
5
+ * 路径函数:getResearchDir、getDirectionsDir
6
+ */
7
+
8
+ import * as path from "node:path";
9
+ import { createHash } from "node:crypto";
10
+
11
+ /**
12
+ * 获取全局研究目录。
13
+ * 路径:{cwd}/docs/research/
14
+ */
15
+ export function getResearchDir(cwd: string): string {
16
+ return path.join(cwd, "docs", "research");
17
+ }
18
+
19
+ /**
20
+ * 获取按主题分的方向目录。
21
+ * 路径:{cwd}/docs/research/directions/{slug}/
22
+ */
23
+ export function getDirectionsDir(cwd: string, slug: string): string {
24
+ return path.join(getResearchDir(cwd), "directions", slug);
25
+ }
26
+
27
+ /**
28
+ * 旧函数保留别名(向后兼容)
29
+ * @deprecated 使用 getResearchDir + getDirectionsDir
30
+ */
31
+ export function getTopicDir(cwd: string, _slug: string): string {
32
+ return getResearchDir(cwd);
33
+ }
34
+
35
+ /**
36
+ * 解析 YAML-like frontmatter。
37
+ */
38
+ export function parseFrontmatter(content: string): Record<string, any> {
39
+ const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
40
+ if (!fmMatch) return {};
41
+
42
+ const fm = fmMatch[1];
43
+ const result: Record<string, any> = {};
44
+
45
+ for (const line of fm.split("\n")) {
46
+ const trimmed = line.trim();
47
+ if (!trimmed || trimmed.startsWith("#")) continue;
48
+
49
+ const colonIdx = trimmed.indexOf(":");
50
+ if (colonIdx <= 0) continue;
51
+
52
+ const key = trimmed.slice(0, colonIdx).trim();
53
+ let value: string = trimmed.slice(colonIdx + 1).trim();
54
+
55
+ if ((value.startsWith('"') && value.endsWith('"')) ||
56
+ (value.startsWith("'") && value.endsWith("'"))) {
57
+ value = value.slice(1, -1);
58
+ }
59
+
60
+ if (/^\d+$/.test(value)) {
61
+ value = parseInt(value, 10);
62
+ } else if (/^\d+\.\d+$/.test(value)) {
63
+ value = parseFloat(value);
64
+ } else if (value === "true") {
65
+ value = true;
66
+ } else if (value === "false") {
67
+ value = false;
68
+ }
69
+
70
+ result[key] = value;
71
+ }
72
+
73
+ return result;
74
+ }
75
+
76
+ /**
77
+ * 从 URL 生成唯一 ID:sha256(url)[:12]
78
+ */
79
+ export function urlToId(url: string): string {
80
+ return createHash("sha256").update(url).digest("hex").slice(0, 12);
81
+ }
82
+
83
+ /**
84
+ * 从主题文本生成 slug。
85
+ */
86
+ export function slugify(topic: string): string {
87
+ return topic
88
+ .toLowerCase()
89
+ .trim()
90
+ .replace(/\s+/g, "-")
91
+ .replace(/[^a-z0-9\u4e00-\u9fff-]/g, "")
92
+ .replace(/-+/g, "-")
93
+ .replace(/^-|-$/g, "");
94
+ }
95
+
96
+ /**
97
+ * 获取格式化时间戳:"2026-05-09T2000"
98
+ */
99
+ export function getTimestamp(): string {
100
+ const now = new Date();
101
+ const yyyy = now.getFullYear();
102
+ const MM = String(now.getMonth() + 1).padStart(2, "0");
103
+ const dd = String(now.getDate()).padStart(2, "0");
104
+ const hh = String(now.getHours()).padStart(2, "0");
105
+ const mm = String(now.getMinutes()).padStart(2, "0");
106
+ return `${yyyy}-${MM}-${dd}T${hh}${mm}`;
107
+ }
package/research.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * workflow: 研究管道基础设施(barrel export)
3
+ *
4
+ * 子模块:
5
+ * research-types.ts — 类型定义
6
+ * research-utils.ts — 通用工具(slugify, urlToId, getResearchDir 等)
7
+ * research-catalog.ts — catalog 管理
8
+ * research-state.ts — 主题方向状态管理
9
+ * research-analysis.ts — 全局文章分析状态
10
+ * research-scan.ts — 文件扫描
11
+ */
12
+
13
+ export type {
14
+ Article,
15
+ ArticleAnalysis as ArticleAnalysisType,
16
+ Direction,
17
+ TopicResearchState,
18
+ } from "./research-types";
19
+
20
+ export {
21
+ slugify,
22
+ urlToId,
23
+ parseFrontmatter,
24
+ getTimestamp,
25
+ getResearchDir,
26
+ getDirectionsDir,
27
+ getTopicDir,
28
+ } from "./research-utils";
29
+
30
+ export {
31
+ loadCatalog,
32
+ saveCatalog,
33
+ } from "./research-catalog";
34
+
35
+ export {
36
+ loadTopicState,
37
+ saveTopicState,
38
+ loadDirectionState,
39
+ saveDirectionState,
40
+ } from "./research-state";
41
+
42
+ export {
43
+ loadAnalysis,
44
+ saveAnalysis,
45
+ defaultAnalysis,
46
+ type ArticleAnalysis,
47
+ type AnalysisState,
48
+ } from "./research-analysis";
49
+
50
+ export {
51
+ scanNewSources,
52
+ } from "./research-scan";
package/state.ts ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * workflow: 通用状态管理
3
+ *
4
+ * 提供两个构建块:
5
+ * 1. createStateManager — 带持久化/恢复的状态管理器
6
+ * 2. createUIUpdater — TUI 状态栏 + Widget 更新器
7
+ *
8
+ * 每个技能/工具定义自己的状态类型,用这两个函数创建唯一管理器。
9
+ */
10
+
11
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import type { SessionEntry, CustomEntry } from "@earendil-works/pi-coding-agent";
13
+
14
+ // ============================================================
15
+ // StateManager
16
+ // ============================================================
17
+
18
+ export interface StateManager<T> {
19
+ /** 获取当前 state(同一引用,mutable update) */
20
+ get(): T;
21
+ /** 替换当前 state */
22
+ set(state: T): void;
23
+ /** 重置为 initialState */
24
+ reset(): void;
25
+ /** 持久化状态到 session entry */
26
+ persist(ctx: ExtensionContext): void;
27
+ /** 从 session entries 恢复状态 */
28
+ restore(ctx: ExtensionContext): void;
29
+ }
30
+
31
+ /**
32
+ * 创建带持久化的状态管理器。
33
+ *
34
+ * restore() 边界行为:
35
+ * - 无匹配 entry → 状态保持 initialState,不报错
36
+ * - 多条匹配 → 取最后一条(最新的)
37
+ * - entry.data 损坏(null/非对象/数组)→ 用 initialState 覆盖,不崩溃
38
+ *
39
+ * @param options.stateFile 持久化文件路径(当前未用,保留接口兼容)
40
+ * @param options.initialState 初始状态
41
+ * @param options.sessionEntryType pi.appendEntry 的 customType
42
+ * @param options.onPersist 可选的持久化回调(用于实际写入 JSON 等)
43
+ */
44
+ export function createStateManager<T>(options: {
45
+ stateFile: string;
46
+ initialState: T;
47
+ sessionEntryType: string;
48
+ onPersist?: (state: T) => void;
49
+ }): StateManager<T> {
50
+ const initialSnapshot = structuredClone(options.initialState);
51
+ let state: T = structuredClone(options.initialState);
52
+ const entryType = options.sessionEntryType;
53
+
54
+ return {
55
+ get(): T { return state; },
56
+ set(s: T): void { state = s; },
57
+ reset(): void { state = structuredClone(initialSnapshot); },
58
+ persist(_ctx: ExtensionContext): void {
59
+ if (options.onPersist) options.onPersist(state);
60
+ },
61
+ restore(ctx: ExtensionContext): void {
62
+ const entries = ctx.sessionManager.getEntries();
63
+ const matching = entries.filter(
64
+ (e: SessionEntry): e is CustomEntry => e.type === "custom" && (e as CustomEntry).customType === entryType,
65
+ );
66
+ if (matching.length === 0) return;
67
+ const latest = matching[matching.length - 1];
68
+ const data = (latest as CustomEntry).data;
69
+ if (data === null || data === undefined || typeof data !== "object" || Array.isArray(data)) {
70
+ state = structuredClone(initialSnapshot);
71
+ return;
72
+ }
73
+ state = { ...structuredClone(initialSnapshot), ...data } as T;
74
+ },
75
+ };
76
+ }
77
+
78
+ // ============================================================
79
+ // UIUpdater
80
+ // ============================================================
81
+
82
+ export interface UIUpdater<T> {
83
+ /** 根据当前 state 更新 status + widget */
84
+ update(ctx: ExtensionContext, state: T): void;
85
+ /** 清除 status + widget */
86
+ clear(ctx: ExtensionContext): void;
87
+ }
88
+
89
+ /**
90
+ * 创建 UI 更新器。
91
+ *
92
+ * @param options.statusKey ctx.ui.setStatus/setWidget 的 key
93
+ * @param options.phases 每个阶段的 UI 配置。value 用字符串匹配 state.phase。
94
+ */
95
+ export function createUIUpdater<T extends { phase?: string }>(options: {
96
+ statusKey: string;
97
+ phases: Array<{
98
+ value: string;
99
+ icon: string;
100
+ label: string;
101
+ color: string;
102
+ }>;
103
+ }): UIUpdater<T> {
104
+ return {
105
+ update(ctx: ExtensionContext, state: T): void {
106
+ const phase = state.phase;
107
+ const pc = options.phases.find(p => p.value === phase);
108
+ if (pc && pc.icon) {
109
+ ctx.ui.setStatus(options.statusKey, `${pc.icon} ${pc.label}`);
110
+ ctx.ui.setWidget(options.statusKey, [`${pc.icon} ${pc.label}`]);
111
+ } else {
112
+ ctx.ui.setStatus(options.statusKey, undefined);
113
+ ctx.ui.setWidget(options.statusKey, undefined);
114
+ }
115
+ },
116
+ clear(ctx: ExtensionContext): void {
117
+ ctx.ui.setStatus(options.statusKey, undefined);
118
+ ctx.ui.setWidget(options.statusKey, undefined);
119
+ },
120
+ };
121
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * workflow: 后台 spawn 实现
3
+ *
4
+ * spawnOnce — 后台模式(pipe stdout,流式解析 JSON)
5
+ */
6
+
7
+ import { spawn, execSync } from "node:child_process";
8
+ import type { SubagentResult, SubagentEvent } from "./types";
9
+ import { getPiCommand } from "./subagent-utils";
10
+
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
+ export function spawnOnce(
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
+ ): Promise<SubagentResult> {
38
+ const pi = getPiCommand();
39
+ const args = [
40
+ ...pi.args,
41
+ "--mode", "json",
42
+ "-p",
43
+ "--tools", agentDef.tools.join(","),
44
+ "--append-system-prompt", systemPromptPath,
45
+ ];
46
+ if (modelOverride || agentDef.model) {
47
+ args.push("--model", modelOverride || agentDef.model!);
48
+ }
49
+ args.push(task);
50
+
51
+ return new Promise<SubagentResult>((resolve) => {
52
+ const proc = spawn(pi.command, args, { cwd, shell: false, stdio: ["ignore", "pipe", "pipe"] });
53
+
54
+ let stdout = "";
55
+ let stderr = "";
56
+ let allAssistantTexts: string[] = [];
57
+ let processedOffset = 0;
58
+ let resolved = false;
59
+ let capturedSessionId: string | undefined;
60
+ const sessionIdRegex = /\{"type":"session","version":\d+,"id":"([^"]+)"/;
61
+
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
+ proc.stdout.on("data", (data: Buffer) => {
81
+ stdout += data.toString();
82
+ const newData = stdout.slice(processedOffset);
83
+ for (const line of newData.split("\n")) {
84
+ if (!line.trim()) continue;
85
+ try { handleEvent(JSON.parse(line)); } catch { /* skip non-JSON */ }
86
+ }
87
+ processedOffset = stdout.lastIndexOf("\n") + 1;
88
+ });
89
+
90
+ const checkSessionId = (text: string) => { if (!capturedSessionId) { const m = text.match(sessionIdRegex); if (m) capturedSessionId = m[1]; } };
91
+ const origOnData = proc.stdout.listeners("data").pop();
92
+ if (origOnData) proc.stdout.on("data", (buf: Buffer) => checkSessionId(buf.toString()));
93
+
94
+ proc.stderr.on("data", (data: Buffer) => { stderr += data.toString(); });
95
+
96
+ // 活跃超时:有新输出就续命
97
+ let lastActivityTime = Date.now();
98
+ const STALL_MS = 5 * 60 * 1000;
99
+ const stallChecker = setInterval(() => {
100
+ if (resolved) { clearInterval(stallChecker); return; }
101
+ 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 });
108
+ }
109
+ }, 5000);
110
+
111
+ // 更新活跃时间(在 stdout data handler 里追踪)
112
+ proc.stdout.prependListener("data", () => { lastActivityTime = Date.now(); });
113
+
114
+ // 墙钟兜底
115
+ const TIMEOUT_MS = timeoutMs ?? 30 * 60 * 1000;
116
+ 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 });
124
+ }, TIMEOUT_MS);
125
+
126
+ proc.on("close", (code) => {
127
+ clearTimeout(wallTimer);
128
+ clearInterval(stallChecker);
129
+ if (resolved) return;
130
+ resolved = true;
131
+
132
+ const remaining = stdout.slice(processedOffset);
133
+ for (const line of remaining.split("\n")) {
134
+ if (!line.trim()) continue;
135
+ try { handleEvent(JSON.parse(line)); } catch { /* skip */ }
136
+ }
137
+
138
+ resolve({ exitCode: code ?? 1, output: [...new Set(allAssistantTexts)].join("\n\n---\n\n") || "(no output)", stderr, subSessionId: capturedSessionId });
139
+ });
140
+
141
+ 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 });
147
+ });
148
+
149
+ 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);
158
+ }
159
+ };
160
+ if (signal.aborted) kill();
161
+ else signal.addEventListener("abort", kill, { once: true });
162
+ }
163
+ });
164
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * workflow: 可见模式 spawn 实现
3
+ *
4
+ * spawnVisible — tmux 窗格中启动 pi 子进程,用户可实时观察
5
+ */
6
+
7
+ import { execFileSync } from "node:child_process";
8
+ 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";
12
+ 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
+ }
25
+
26
+ export function spawnVisible(
27
+ task: string,
28
+ cwd: string,
29
+ systemPromptPath: string,
30
+ agentDef: { tools: string[]; model?: string },
31
+ signal?: AbortSignal,
32
+ modelOverride?: string,
33
+ timeoutMs?: number,
34
+ onEvent?: (event: SubagentEvent) => void,
35
+ ): 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"
44
+ );
45
+
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 });
59
+
60
+ let paneId: string;
61
+ 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();
67
+ } catch {
68
+ try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
69
+ return spawnOnce(task, cwd, systemPromptPath, agentDef, signal, modelOverride, timeoutMs, onEvent);
70
+ }
71
+
72
+ let lastLine = 0;
73
+ let allTexts: string[] = [];
74
+ let capturedSessionId: string | undefined;
75
+
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);
81
+ }
82
+ }
83
+ };
84
+
85
+ return new Promise<SubagentResult>((resolve) => {
86
+ let resolved = false;
87
+ let lastActivityTime = Date.now();
88
+
89
+ const pollInterval = setInterval(() => {
90
+ if (resolved) return;
91
+
92
+ try {
93
+ if (fs.existsSync(sessionFile)) {
94
+ const content = fs.readFileSync(sessionFile, "utf-8");
95
+ const lines = content.split("\n").filter(l => l.trim());
96
+ if (lines.length > lastLine) lastActivityTime = Date.now();
97
+ 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 */ }
107
+ }
108
+ lastLine = lines.length;
109
+ }
110
+ } catch { /* ignore */ }
111
+
112
+ try {
113
+ if (!/^%\d+$/.test(paneId)) { finish(); return; }
114
+ execFileSync("tmux", ["list-panes", "-t", paneId], { stdio: "pipe" });
115
+ } catch {
116
+ finish();
117
+ }
118
+
119
+ // 活跃超时:5 分钟无新输出视为停滞
120
+ const STALL_MS = 5 * 60 * 1000;
121
+ if (Date.now() - lastActivityTime > STALL_MS) {
122
+ if (resolved) return;
123
+ resolved = true;
124
+ 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 });
131
+ }
132
+ }, 2000);
133
+
134
+ // 墙钟超时改为兜底(30 分钟绝对上限)
135
+ const TIMEOUT_MS = timeoutMs ?? 30 * 60 * 1000;
136
+ const timer = setTimeout(() => {
137
+ if (resolved) return;
138
+ resolved = true;
139
+ 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 });
146
+ }, TIMEOUT_MS);
147
+
148
+ function finish() {
149
+ if (resolved) return;
150
+ resolved = true;
151
+ clearInterval(pollInterval);
152
+ clearTimeout(timer);
153
+
154
+ try { execFileSync("sleep", ["0.5"], { stdio: "pipe" }); } catch { /* ignore */ }
155
+ try {
156
+ if (fs.existsSync(sessionFile)) {
157
+ const content = fs.readFileSync(sessionFile, "utf-8");
158
+ const lines = content.split("\n").filter(l => l.trim());
159
+ 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 */ }
167
+ }
168
+ }
169
+ } catch { /* ignore */ }
170
+
171
+ const output = allTexts.length > 0
172
+ ? [...new Set(allTexts)].join("\n\n---\n\n")
173
+ : "(no output)";
174
+
175
+ setTimeout(() => { try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ } }, 5000);
176
+ resolve({ exitCode: 0, output, stderr: "", subSessionId: capturedSessionId });
177
+ }
178
+
179
+ if (signal) {
180
+ const kill = () => {
181
+ if (!resolved) {
182
+ resolved = true;
183
+ 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 });
188
+ }
189
+ };
190
+ if (signal.aborted) kill();
191
+ else signal.addEventListener("abort", kill, { once: true });
192
+ }
193
+ });
194
+ }