pi-ate-workflow 0.1.0 → 0.2.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.
- 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 +1 -2
- 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 +15 -21
- package/agent-loader.ts +0 -88
- package/tests/agent-loader.test.ts +0 -183
package/subagent-utils.ts
CHANGED
|
@@ -1,14 +1,80 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* workflow: 子代理工具函数
|
|
3
|
-
*
|
|
4
|
-
* 从 PV 的 subagent.ts 提取的通用函数。
|
|
5
3
|
*/
|
|
6
4
|
|
|
7
|
-
import { spawn } from "node:child_process";
|
|
8
5
|
import * as fs from "node:fs";
|
|
9
6
|
import * as path from "node:path";
|
|
10
7
|
import * as os from "node:os";
|
|
11
8
|
|
|
9
|
+
/**
|
|
10
|
+
* 将 Windows 反斜杠路径转为 Unix 正斜杠路径。
|
|
11
|
+
* launch.sh 在 bash 里执行,反斜杠会被解释为转义字符导致路径错误。
|
|
12
|
+
*/
|
|
13
|
+
function toUnixPath(p: string): string {
|
|
14
|
+
return p.replace(/\\/g, "/");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 将 parentSession 注入子代理 session JSONL 首行的 header。
|
|
19
|
+
* 用于建立主会话→子代理会话的关联链。
|
|
20
|
+
*/
|
|
21
|
+
export function injectParentSession(sessionFilePath: string, parentPath: string): void {
|
|
22
|
+
try {
|
|
23
|
+
const content = fs.readFileSync(sessionFilePath, "utf-8");
|
|
24
|
+
const firstNewline = content.indexOf("\n");
|
|
25
|
+
const firstLine = firstNewline >= 0 ? content.slice(0, firstNewline) : content;
|
|
26
|
+
const rest = firstNewline >= 0 ? content.slice(firstNewline) : "";
|
|
27
|
+
try {
|
|
28
|
+
const header = JSON.parse(firstLine);
|
|
29
|
+
if (header.type === "session" && !header.parentSession) {
|
|
30
|
+
header.parentSession = parentPath;
|
|
31
|
+
fs.writeFileSync(sessionFilePath, JSON.stringify(header) + rest, "utf-8");
|
|
32
|
+
}
|
|
33
|
+
} catch { /* 首行不是有效 JSON,跳过 */ }
|
|
34
|
+
} catch { /* 文件不存在或无法读取,跳过 */ }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 通过 sessionId 查找子代理 session 文件并注入 parentSession。
|
|
39
|
+
* 用于 spawnOnce 模式(session 文件路径未知,需要按 ID 搜索)。
|
|
40
|
+
*/
|
|
41
|
+
export function findAndInjectParentSession(sessionId: string | undefined, parentPath: string, cwd: string): void {
|
|
42
|
+
if (!sessionId || !parentPath) return;
|
|
43
|
+
const baseDir = process.env.PI_CODING_AGENT_SESSION_DIR
|
|
44
|
+
|| path.join(os.homedir(), ".pi/agent/sessions");
|
|
45
|
+
if (!fs.existsSync(baseDir)) return;
|
|
46
|
+
|
|
47
|
+
// 从 cwd 推导 session 子目录
|
|
48
|
+
const cwdSlug = "--" + cwd.replace(/^\//, "").replace(/\//g, "-") + "--";
|
|
49
|
+
const sessionDir = path.join(baseDir, cwdSlug);
|
|
50
|
+
if (!fs.existsSync(sessionDir)) return;
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
// 按修改时间降序,优先检查最近的文件
|
|
54
|
+
const files = fs.readdirSync(sessionDir)
|
|
55
|
+
.filter(f => f.endsWith(".jsonl"))
|
|
56
|
+
.map(f => ({ name: f, mtime: fs.statSync(path.join(sessionDir, f)).mtimeMs }))
|
|
57
|
+
.sort((a, b) => b.mtime - a.mtime)
|
|
58
|
+
.slice(0, 20);
|
|
59
|
+
|
|
60
|
+
for (const { name } of files) {
|
|
61
|
+
const filePath = path.join(sessionDir, name);
|
|
62
|
+
try {
|
|
63
|
+
const fd = fs.openSync(filePath, "r");
|
|
64
|
+
const buf = Buffer.alloc(500);
|
|
65
|
+
fs.readSync(fd, buf, 0, 500, 0);
|
|
66
|
+
fs.closeSync(fd);
|
|
67
|
+
const firstLine = buf.toString("utf-8").split("\n")[0];
|
|
68
|
+
const header = JSON.parse(firstLine);
|
|
69
|
+
if (header.id === sessionId) {
|
|
70
|
+
injectParentSession(filePath, parentPath);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
} catch { /* skip */ }
|
|
74
|
+
}
|
|
75
|
+
} catch { /* skip */ }
|
|
76
|
+
}
|
|
77
|
+
|
|
12
78
|
/**
|
|
13
79
|
* 获取启动 pi 的 command + args。
|
|
14
80
|
* 优先用当前进程的可执行文件路径,回退到 PATH 中的 "pi"。
|
|
@@ -36,3 +102,64 @@ export async function writeTempPrompt(content: string): Promise<string> {
|
|
|
36
102
|
await fs.promises.writeFile(filePath, content, { encoding: "utf-8", mode: 0o600 });
|
|
37
103
|
return filePath;
|
|
38
104
|
}
|
|
105
|
+
|
|
106
|
+
/** 可见模式的临时目录信息 */
|
|
107
|
+
export interface VisibleTaskDir {
|
|
108
|
+
taskDir: string;
|
|
109
|
+
taskFile: string;
|
|
110
|
+
sessionFile: string;
|
|
111
|
+
launchScript: string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 创建可见模式的临时目录和启动脚本。
|
|
116
|
+
* 调用方负责在结束时删除 taskDir。
|
|
117
|
+
*/
|
|
118
|
+
export function createVisibleTaskDir(
|
|
119
|
+
task: string,
|
|
120
|
+
cwd: string,
|
|
121
|
+
systemPromptPath: string,
|
|
122
|
+
agentDef: { tools: string[]; model?: string },
|
|
123
|
+
modelOverride?: string,
|
|
124
|
+
extraEnv?: Record<string, string>,
|
|
125
|
+
): VisibleTaskDir {
|
|
126
|
+
const taskDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-visible-"));
|
|
127
|
+
const taskFile = path.join(taskDir, "task.txt");
|
|
128
|
+
fs.writeFileSync(taskFile, task, { encoding: "utf-8" });
|
|
129
|
+
|
|
130
|
+
const sessionFile = path.join(taskDir, "session.jsonl");
|
|
131
|
+
|
|
132
|
+
const modelArg = (modelOverride || agentDef.model)
|
|
133
|
+
? ` --model ${modelOverride || agentDef.model}`
|
|
134
|
+
: "";
|
|
135
|
+
|
|
136
|
+
// extraEnv 生成 shell export 行(安全转义单引号)
|
|
137
|
+
const extraEnvExports = extraEnv
|
|
138
|
+
? Object.entries(extraEnv)
|
|
139
|
+
.map(([k, v]) => `export ${k}='${v.split("'").join("'\\''")}'`)
|
|
140
|
+
.join("\n")
|
|
141
|
+
: "";
|
|
142
|
+
|
|
143
|
+
const launchScript = path.join(taskDir, "launch.sh");
|
|
144
|
+
|
|
145
|
+
// launch.sh 在 bash 里执行,所有路径必须用 Unix 格式(正斜杠)
|
|
146
|
+
const uCwd = toUnixPath(cwd);
|
|
147
|
+
const uSessionFile = toUnixPath(sessionFile);
|
|
148
|
+
const uSystemPromptPath = toUnixPath(systemPromptPath);
|
|
149
|
+
const uTaskFile = toUnixPath(taskFile);
|
|
150
|
+
|
|
151
|
+
const script = [
|
|
152
|
+
"#!/bin/bash",
|
|
153
|
+
'export FNM_PATH="$HOME/.local/share/fnm"',
|
|
154
|
+
'if [ -d "$FNM_PATH" ]; then export PATH="$FNM_PATH:$PATH" && eval "$(fnm env --shell bash)"; fi',
|
|
155
|
+
`cd "${uCwd}"`,
|
|
156
|
+
"export PI_SUBAGENT_AUTO_EXIT=1",
|
|
157
|
+
`export PI_SUBAGENT_SESSION='${uSessionFile}'`,
|
|
158
|
+
`export PI_SUBAGENT_NAME='pv-visible'`,
|
|
159
|
+
extraEnvExports,
|
|
160
|
+
`pi --session '${uSessionFile}' --tools ${agentDef.tools.join(",")} --append-system-prompt '${uSystemPromptPath}'${modelArg} @'${uTaskFile}'`,
|
|
161
|
+
].filter(Boolean).join("\n");
|
|
162
|
+
fs.writeFileSync(launchScript, script, { mode: 0o700 });
|
|
163
|
+
|
|
164
|
+
return { taskDir, taskFile, sessionFile, launchScript };
|
|
165
|
+
}
|
package/subagent.ts
CHANGED
|
@@ -2,15 +2,34 @@
|
|
|
2
2
|
* workflow: 子代理执行器公开 API
|
|
3
3
|
*
|
|
4
4
|
* spawn 实现在 subagent-spawn-once.ts 和 subagent-spawn-visible.ts。
|
|
5
|
+
* 超时在 timeout-config.ts 单点解析(fallback < timeoutMs < agentTimeouts < 显式传参)。
|
|
6
|
+
* 桥接在 intercom-bridge.ts 默认注入(PI_SUBAGENT_* 5 变量)。
|
|
5
7
|
*/
|
|
6
8
|
|
|
7
9
|
import * as fs from "node:fs";
|
|
8
10
|
import * as path from "node:path";
|
|
9
11
|
import type { SubagentResult, SubagentEvent } from "./types";
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
+
import {
|
|
13
|
+
createVisibleTaskDir,
|
|
14
|
+
findAndInjectParentSession,
|
|
15
|
+
writeTempPrompt,
|
|
16
|
+
} from "./subagent-utils";
|
|
17
|
+
import { loadAgentDef } from "@pi-atelier/shared-utils";
|
|
12
18
|
import { spawnOnce } from "./subagent-spawn-once";
|
|
13
19
|
import { spawnVisible } from "./subagent-spawn-visible";
|
|
20
|
+
import { resolveSubagentTimeout } from "./timeout-config";
|
|
21
|
+
import {
|
|
22
|
+
buildIntercomBridge,
|
|
23
|
+
resolveOrchestratorName,
|
|
24
|
+
} from "./intercom-bridge";
|
|
25
|
+
|
|
26
|
+
/** 模块级 session 文件解析器,由各扩展在 session_start 时注册 */
|
|
27
|
+
let _sessionFileResolver: (() => string | undefined) | undefined;
|
|
28
|
+
|
|
29
|
+
/** 各扩展在 session_start hook 中调用,注册当前会话文件路径的获取方式 */
|
|
30
|
+
export function setSessionFileResolver(resolver: (() => string | undefined) | undefined) {
|
|
31
|
+
_sessionFileResolver = resolver;
|
|
32
|
+
}
|
|
14
33
|
|
|
15
34
|
/** 格式约束,拼入 task 让子代理自检,执行后验证 */
|
|
16
35
|
export interface OutputConstraint {
|
|
@@ -37,11 +56,14 @@ export function validateOutputConstraints(output: string, constraints: OutputCon
|
|
|
37
56
|
}
|
|
38
57
|
|
|
39
58
|
/**
|
|
40
|
-
*
|
|
41
|
-
*
|
|
59
|
+
* 运行子代理(唯一 spawn 路径)。
|
|
60
|
+
*
|
|
61
|
+
* 超时:timeoutMs 参数为显式传参(最高优先级);未传时由配置链解析
|
|
62
|
+
* (代码 fallback 30min < subagent.timeoutMs < subagent.agentTimeouts[agentName])。
|
|
63
|
+
* 桥接:默认注入 PI_SUBAGENT_* 桥接环境变量(extraEnv 传入的变量优先保留)。
|
|
42
64
|
*
|
|
43
65
|
* @param agentName 对应 ~/.pi/agent/agents/{name}.md
|
|
44
|
-
* @param visible true=在 tmux 窗格中可见运行(默认),false=后台运行
|
|
66
|
+
* @param visible true=在 tmux/WezTerm 窗格中可见运行(默认),false=后台运行
|
|
45
67
|
*/
|
|
46
68
|
export async function runSubagent(
|
|
47
69
|
agentName: string,
|
|
@@ -53,13 +75,25 @@ export async function runSubagent(
|
|
|
53
75
|
onEvent?: (event: SubagentEvent) => void,
|
|
54
76
|
outputConstraints?: OutputConstraint[],
|
|
55
77
|
visible: boolean = true,
|
|
78
|
+
extraEnv?: Record<string, string>,
|
|
56
79
|
): Promise<SubagentResult> {
|
|
57
|
-
const agentDef = loadAgentDef(agentName);
|
|
80
|
+
const agentDef = loadAgentDef(agentName, cwd);
|
|
58
81
|
if (!agentDef) {
|
|
59
|
-
throw new Error(`子代理定义 "${agentName}" 未找到。请确保 ~/.pi/agent/agents
|
|
82
|
+
throw new Error(`子代理定义 "${agentName}" 未找到。请确保 ${agentName}.md 在 ~/.pi/agent/agents/、~/.agents/agents/ 或项目级 .pi/agents/ 中存在。`);
|
|
60
83
|
}
|
|
61
84
|
|
|
62
|
-
|
|
85
|
+
// 超时单点解析:显式传参 > agentTimeouts > timeoutMs > fallback
|
|
86
|
+
const effectiveTimeout = resolveSubagentTimeout(agentName, cwd, timeoutMs);
|
|
87
|
+
|
|
88
|
+
// 自动解析当前会话文件路径,用于建立 parentSession 关联
|
|
89
|
+
const parentSessionPath = _sessionFileResolver?.();
|
|
90
|
+
|
|
91
|
+
// 桥接环境变量:默认注入,调用方 extraEnv 优先
|
|
92
|
+
const orchestratorName = await resolveOrchestratorName();
|
|
93
|
+
const bridgeEnv = buildIntercomBridge(orchestratorName, agentName);
|
|
94
|
+
const env = { ...bridgeEnv, ...extraEnv };
|
|
95
|
+
|
|
96
|
+
const useVisible = visible && !!(process.env.TMUX || process.env.WEZTERM_PANE);
|
|
63
97
|
|
|
64
98
|
const tmpPromptPath = await writeTempPrompt(agentDef.systemPrompt);
|
|
65
99
|
|
|
@@ -75,10 +109,15 @@ export async function runSubagent(
|
|
|
75
109
|
: `${fullTask}\n\n---\n\n⚠️ 你上一轮的输出不符合格式约束:\n${validateOutputConstraints(lastResult!.output, outputConstraints!).join("\n")}\n\n请修正格式后重新输出完整的审查结果。不要重复工具调用,直接输出修正后的文本。`;
|
|
76
110
|
|
|
77
111
|
const result = useVisible
|
|
78
|
-
? await spawnVisible(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride,
|
|
79
|
-
: await spawnOnce(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride,
|
|
112
|
+
? await spawnVisible(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env)
|
|
113
|
+
: await spawnOnce(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env);
|
|
80
114
|
lastResult = result;
|
|
81
115
|
|
|
116
|
+
// 后台模式:子进程退出后通过 sessionId 查找 session 文件并注入 parentSession
|
|
117
|
+
if (!useVisible && parentSessionPath && result.subSessionId) {
|
|
118
|
+
findAndInjectParentSession(result.subSessionId, parentSessionPath, cwd);
|
|
119
|
+
}
|
|
120
|
+
|
|
82
121
|
if (!outputConstraints?.length) break;
|
|
83
122
|
if (result.exitCode !== 0 && result.output.length <= 100) break;
|
|
84
123
|
|
package/term-backend.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 终端分屏后端抽象(接口 + 检测 + 分派)
|
|
3
|
+
*
|
|
4
|
+
* 统一 WezTerm 和 tmux 的分屏操作接口,
|
|
5
|
+
* 让 spawnVisible 不关心底层终端实现。
|
|
6
|
+
* 后端实现分别在 term-wezterm.ts / term-tmux.ts。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { weztermBackend } from "./term-wezterm";
|
|
10
|
+
import { tmuxBackend } from "./term-tmux";
|
|
11
|
+
|
|
12
|
+
export type TermType = "wezterm" | "tmux";
|
|
13
|
+
|
|
14
|
+
export interface TermBackend {
|
|
15
|
+
/** 在新分屏中运行命令,返回新 pane 的 ID */
|
|
16
|
+
splitPane(cwd: string, command: string): string;
|
|
17
|
+
/** 关闭指定 pane */
|
|
18
|
+
killPane(paneId: string): void;
|
|
19
|
+
/** 检查 pane 是否还存活 */
|
|
20
|
+
isPaneAlive(paneId: string): boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 检测当前终端类型:WezTerm 优先于 tmux */
|
|
24
|
+
export function detectTerminal(): TermType | null {
|
|
25
|
+
if (process.env.WEZTERM_PANE) return "wezterm";
|
|
26
|
+
if (process.env.TMUX) return "tmux";
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 根据终端类型获取对应后端 */
|
|
31
|
+
export function getBackend(type: TermType): TermBackend {
|
|
32
|
+
return type === "wezterm" ? weztermBackend : tmuxBackend;
|
|
33
|
+
}
|
package/term-tmux.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tmux 分屏后端
|
|
3
|
+
*
|
|
4
|
+
* 分屏策略与 WezTerm 相同:
|
|
5
|
+
* 第 1 个子代理左右分,第 2+ 个从第 1 个子 pane 上下分。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { execFileSync, execSync } from "node:child_process";
|
|
9
|
+
import * as fs from "node:fs";
|
|
10
|
+
import * as os from "node:os";
|
|
11
|
+
import * as path from "node:path";
|
|
12
|
+
import type { TermBackend } from "./term-backend";
|
|
13
|
+
|
|
14
|
+
/** tmux 版:映射文件路径 */
|
|
15
|
+
function tmuxSubPaneMapPath(mainPaneId: string): string {
|
|
16
|
+
return path.join(os.tmpdir(), `pi-tmux-subpane-${mainPaneId}.json`);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 读取 tmux 第 1 个子 pane ID */
|
|
20
|
+
function readFirstTmuxSubPane(mainPaneId: string): string | null {
|
|
21
|
+
try {
|
|
22
|
+
const mapFile = tmuxSubPaneMapPath(mainPaneId);
|
|
23
|
+
if (!fs.existsSync(mapFile)) return null;
|
|
24
|
+
const { firstSubPaneId } = JSON.parse(fs.readFileSync(mapFile, "utf-8"));
|
|
25
|
+
if (!firstSubPaneId) {
|
|
26
|
+
fs.unlinkSync(mapFile);
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
return String(firstSubPaneId);
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 记录 tmux 第 1 个子 pane ID */
|
|
36
|
+
function saveFirstTmuxSubPane(mainPaneId: string, subPaneId: string): void {
|
|
37
|
+
try {
|
|
38
|
+
const mapFile = tmuxSubPaneMapPath(mainPaneId);
|
|
39
|
+
fs.writeFileSync(mapFile, JSON.stringify({ firstSubPaneId: subPaneId }));
|
|
40
|
+
} catch {
|
|
41
|
+
/* ignore */
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const tmuxBackend: TermBackend = {
|
|
46
|
+
splitPane(_cwd: string, command: string): string {
|
|
47
|
+
const fromPane = process.env.TMUX_PANE;
|
|
48
|
+
let args: string[];
|
|
49
|
+
|
|
50
|
+
const firstSub = fromPane ? readFirstTmuxSubPane(fromPane) : null;
|
|
51
|
+
|
|
52
|
+
if (!firstSub) {
|
|
53
|
+
// 第 1 个子代理:左右分
|
|
54
|
+
args = ["split-window", "-h", "-d"];
|
|
55
|
+
if (fromPane) args.push("-t", fromPane);
|
|
56
|
+
} else {
|
|
57
|
+
// 第 2+ 个子代理:从第 1 个子 pane 上下分
|
|
58
|
+
args = ["split-window", "-v", "-d", "-t", firstSub];
|
|
59
|
+
}
|
|
60
|
+
args.push("-P", "-F", "#{pane_id}", "bash", command);
|
|
61
|
+
|
|
62
|
+
const newPaneId = execFileSync("tmux", args, { encoding: "utf8" }).trim();
|
|
63
|
+
|
|
64
|
+
// 第 1 个子代理创建后,记录映射
|
|
65
|
+
if (!firstSub && fromPane) {
|
|
66
|
+
saveFirstTmuxSubPane(fromPane, newPaneId);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return newPaneId;
|
|
70
|
+
},
|
|
71
|
+
killPane(paneId: string): void {
|
|
72
|
+
try {
|
|
73
|
+
execSync(`tmux kill-pane -t ${paneId}`, { stdio: "pipe" });
|
|
74
|
+
} catch {
|
|
75
|
+
/* ignore */
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
isPaneAlive(paneId: string): boolean {
|
|
79
|
+
try {
|
|
80
|
+
execSync(`tmux list-panes -t ${paneId}`, { stdio: "pipe" });
|
|
81
|
+
return true;
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
};
|
package/term-wezterm.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WezTerm 分屏后端
|
|
3
|
+
*
|
|
4
|
+
* 分屏策略:
|
|
5
|
+
* 第 1 个子代理 --right(左右分,保留宽度)
|
|
6
|
+
* 第 2+ 个子代理从第 1 个子 pane --bottom(上下分,宽度不变)
|
|
7
|
+
*
|
|
8
|
+
* 通过临时文件记录主 pane → 第 1 个子 pane 的映射关系,
|
|
9
|
+
* 只认自己创建的子 pane,不会误用其他会话的 pane。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { execFileSync, execSync } from "node:child_process";
|
|
13
|
+
import * as fs from "node:fs";
|
|
14
|
+
import * as os from "node:os";
|
|
15
|
+
import * as path from "node:path";
|
|
16
|
+
import type { TermBackend } from "./term-backend";
|
|
17
|
+
|
|
18
|
+
/** 主 pane → 第 1 个子 pane 的映射文件路径 */
|
|
19
|
+
function subPaneMapPath(mainPaneId: string): string {
|
|
20
|
+
return path.join(os.tmpdir(), `pi-subpane-${mainPaneId}.json`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 读取第 1 个子 pane ID,如果 pane 还活着就返回 */
|
|
24
|
+
function readFirstSubPane(mainPaneId: string): string | null {
|
|
25
|
+
try {
|
|
26
|
+
const mapFile = subPaneMapPath(mainPaneId);
|
|
27
|
+
if (!fs.existsSync(mapFile)) return null;
|
|
28
|
+
const { firstSubPaneId } = JSON.parse(fs.readFileSync(mapFile, "utf-8"));
|
|
29
|
+
// 验证 pane 还活着
|
|
30
|
+
if (!firstSubPaneId || !isWezPaneAlive(String(firstSubPaneId))) {
|
|
31
|
+
fs.unlinkSync(mapFile); // 死了就清掉映射
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
return String(firstSubPaneId);
|
|
35
|
+
} catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 记录第 1 个子 pane ID */
|
|
41
|
+
function saveFirstSubPane(mainPaneId: string, subPaneId: string): void {
|
|
42
|
+
try {
|
|
43
|
+
const mapFile = subPaneMapPath(mainPaneId);
|
|
44
|
+
fs.writeFileSync(mapFile, JSON.stringify({ firstSubPaneId: subPaneId }));
|
|
45
|
+
} catch {
|
|
46
|
+
/* ignore */
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 检查 wezterm pane 是否存活 */
|
|
51
|
+
function isWezPaneAlive(paneId: string): boolean {
|
|
52
|
+
try {
|
|
53
|
+
const list = execSync("wezterm cli list --format json", {
|
|
54
|
+
encoding: "utf8",
|
|
55
|
+
}).trim();
|
|
56
|
+
const panes = JSON.parse(list) as Array<{ pane_id: number }>;
|
|
57
|
+
return panes.some((p) => String(p.pane_id) === paneId);
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const weztermBackend: TermBackend = {
|
|
64
|
+
splitPane(cwd: string, command: string): string {
|
|
65
|
+
const currentPane = process.env.WEZTERM_PANE;
|
|
66
|
+
let args: string[];
|
|
67
|
+
|
|
68
|
+
// 查找我们之前创建的第 1 个子 pane
|
|
69
|
+
const firstSub = currentPane ? readFirstSubPane(currentPane) : null;
|
|
70
|
+
|
|
71
|
+
if (!firstSub) {
|
|
72
|
+
// 第 1 个子代理:从主 pane 左右分
|
|
73
|
+
args = ["cli", "split-pane", "--right", "--cwd", cwd];
|
|
74
|
+
if (currentPane) args.push("--pane-id", currentPane);
|
|
75
|
+
} else {
|
|
76
|
+
// 第 2+ 个子代理:从第 1 个子 pane 上下分
|
|
77
|
+
args = [
|
|
78
|
+
"cli",
|
|
79
|
+
"split-pane",
|
|
80
|
+
"--bottom",
|
|
81
|
+
"--cwd",
|
|
82
|
+
cwd,
|
|
83
|
+
"--pane-id",
|
|
84
|
+
firstSub,
|
|
85
|
+
];
|
|
86
|
+
}
|
|
87
|
+
args.push("--", "bash", command);
|
|
88
|
+
|
|
89
|
+
const newPaneId = execFileSync("wezterm", args, {
|
|
90
|
+
encoding: "utf8",
|
|
91
|
+
}).trim();
|
|
92
|
+
|
|
93
|
+
// 第 1 个子代理创建后,记录映射
|
|
94
|
+
if (!firstSub && currentPane) {
|
|
95
|
+
saveFirstSubPane(currentPane, newPaneId);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return newPaneId;
|
|
99
|
+
},
|
|
100
|
+
killPane(paneId: string): void {
|
|
101
|
+
try {
|
|
102
|
+
execSync(`wezterm cli kill-pane --pane-id ${paneId}`, {
|
|
103
|
+
stdio: "pipe",
|
|
104
|
+
});
|
|
105
|
+
} catch {
|
|
106
|
+
/* ignore */
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
isPaneAlive(paneId: string): boolean {
|
|
110
|
+
return isWezPaneAlive(paneId);
|
|
111
|
+
},
|
|
112
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 测试 createVisibleTaskDir — 可见模式临时目录与 launch.sh 生成
|
|
3
|
+
*
|
|
4
|
+
* extraEnv → export 行注入、单引号转义、Unix 路径转换、AUTO_EXIT 注入
|
|
5
|
+
*/
|
|
6
|
+
import { describe, it, expect } from "vitest";
|
|
7
|
+
import * as fs from "node:fs";
|
|
8
|
+
import * as os from "node:os";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import { createVisibleTaskDir } from "../subagent-utils";
|
|
11
|
+
|
|
12
|
+
function cleanupDir(dir: string) {
|
|
13
|
+
try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe("createVisibleTaskDir — launch.sh 生成", () => {
|
|
17
|
+
it("extraEnv 写入 export 行", () => {
|
|
18
|
+
const extraEnv = {
|
|
19
|
+
PI_SUBAGENT_ORCHESTRATOR_TARGET: "my-session",
|
|
20
|
+
PI_SUBAGENT_RUN_ID: "run-abc",
|
|
21
|
+
PI_SUBAGENT_CHILD_AGENT: "pv-test",
|
|
22
|
+
PI_SUBAGENT_CHILD_INDEX: "1",
|
|
23
|
+
};
|
|
24
|
+
const dir = createVisibleTaskDir("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, extraEnv);
|
|
25
|
+
try {
|
|
26
|
+
const script = fs.readFileSync(dir.launchScript, "utf-8");
|
|
27
|
+
expect(script).toContain("export PI_SUBAGENT_ORCHESTRATOR_TARGET='my-session'");
|
|
28
|
+
expect(script).toContain("export PI_SUBAGENT_RUN_ID='run-abc'");
|
|
29
|
+
expect(script).toContain("export PI_SUBAGENT_CHILD_AGENT='pv-test'");
|
|
30
|
+
expect(script).toContain("export PI_SUBAGENT_CHILD_INDEX='1'");
|
|
31
|
+
} finally { cleanupDir(dir.taskDir); }
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("不传 extraEnv 时 launch.sh 不含 PI_SUBAGENT_*(桥接变量除外)", () => {
|
|
35
|
+
const dir = createVisibleTaskDir("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] });
|
|
36
|
+
try {
|
|
37
|
+
const script = fs.readFileSync(dir.launchScript, "utf-8");
|
|
38
|
+
expect(script).not.toContain("PI_SUBAGENT_ORCHESTRATOR_TARGET=");
|
|
39
|
+
expect(script).toContain("export PI_SUBAGENT_AUTO_EXIT=1");
|
|
40
|
+
} finally { cleanupDir(dir.taskDir); }
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("值含单引号时安全转义", () => {
|
|
44
|
+
const dir = createVisibleTaskDir("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, { TEST_KEY: "it's a value" });
|
|
45
|
+
try {
|
|
46
|
+
const script = fs.readFileSync(dir.launchScript, "utf-8");
|
|
47
|
+
expect(script).toContain("export TEST_KEY='it'\\''s a value'");
|
|
48
|
+
} finally { cleanupDir(dir.taskDir); }
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("Windows 反斜杠路径转为 Unix 正斜杠", () => {
|
|
52
|
+
const dir = createVisibleTaskDir("task", "C:\\Users\\test\\project", "/tmp/prompt.md", { tools: ["read"] });
|
|
53
|
+
try {
|
|
54
|
+
const script = fs.readFileSync(dir.launchScript, "utf-8");
|
|
55
|
+
expect(script).toContain('cd "C:/Users/test/project"');
|
|
56
|
+
expect(script).not.toContain("C:\\\\Users");
|
|
57
|
+
} finally { cleanupDir(dir.taskDir); }
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("task 写入 task.txt,session 路径指向 taskDir", () => {
|
|
61
|
+
const dir = createVisibleTaskDir("do the thing", "/cwd", "/tmp/prompt.md", { tools: ["read", "bash"] });
|
|
62
|
+
try {
|
|
63
|
+
expect(fs.readFileSync(dir.taskFile, "utf-8")).toBe("do the thing");
|
|
64
|
+
expect(dir.sessionFile.startsWith(dir.taskDir)).toBe(true);
|
|
65
|
+
expect(path.dirname(dir.launchScript)).toBe(dir.taskDir);
|
|
66
|
+
} finally { cleanupDir(dir.taskDir); }
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("modelOverride 写入 --model 参数", () => {
|
|
70
|
+
const dir = createVisibleTaskDir("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, "zai/glm-5.2");
|
|
71
|
+
try {
|
|
72
|
+
const script = fs.readFileSync(dir.launchScript, "utf-8");
|
|
73
|
+
expect(script).toContain("--model zai/glm-5.2");
|
|
74
|
+
} finally { cleanupDir(dir.taskDir); }
|
|
75
|
+
});
|
|
76
|
+
});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 测试 intercom-bridge.ts — 桥接环境变量构建与唯一性
|
|
3
|
+
*/
|
|
4
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
5
|
+
import {
|
|
6
|
+
buildIntercomBridge,
|
|
7
|
+
resolveOrchestratorName,
|
|
8
|
+
setOrchestratorNameResolver,
|
|
9
|
+
} from "../intercom-bridge";
|
|
10
|
+
|
|
11
|
+
describe("buildIntercomBridge", () => {
|
|
12
|
+
it("返回完整 5 变量集", () => {
|
|
13
|
+
const env = buildIntercomBridge("orch-1", "fo-analyzer");
|
|
14
|
+
expect(env).toEqual({
|
|
15
|
+
PI_SUBAGENT_ORCHESTRATOR_TARGET: "orch-1",
|
|
16
|
+
PI_SUBAGENT_RUN_ID: expect.stringMatching(/^run-/) as string,
|
|
17
|
+
PI_SUBAGENT_CHILD_AGENT: "fo-analyzer",
|
|
18
|
+
PI_SUBAGENT_CHILD_INDEX: "1",
|
|
19
|
+
PI_SUBAGENT_INTERCOM_SESSION_NAME: expect.stringContaining("fo-analyzer") as string,
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it("orchestrator 名为空时回退 orchestrator", () => {
|
|
24
|
+
const env = buildIntercomBridge(undefined, "pv-executor");
|
|
25
|
+
expect(env.PI_SUBAGENT_ORCHESTRATOR_TARGET).toBe("orchestrator");
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("同一进程连续两次调用的 run-id 与 session-name 互不相同", () => {
|
|
29
|
+
const e1 = buildIntercomBridge("o", "agent-a");
|
|
30
|
+
const e2 = buildIntercomBridge("o", "agent-a");
|
|
31
|
+
expect(e1.PI_SUBAGENT_RUN_ID).not.toBe(e2.PI_SUBAGENT_RUN_ID);
|
|
32
|
+
expect(e1.PI_SUBAGENT_INTERCOM_SESSION_NAME).not.toBe(e2.PI_SUBAGENT_INTERCOM_SESSION_NAME);
|
|
33
|
+
// child-index 进程内自增(跨用例共享模块计数器,断言递增关系)
|
|
34
|
+
expect(Number(e2.PI_SUBAGENT_CHILD_INDEX)).toBe(Number(e1.PI_SUBAGENT_CHILD_INDEX) + 1);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("不同 agent 名注入各自的 CHILD_AGENT", () => {
|
|
38
|
+
expect(buildIntercomBridge("o", "fo-analyzer").PI_SUBAGENT_CHILD_AGENT).toBe("fo-analyzer");
|
|
39
|
+
expect(buildIntercomBridge("o", "fr-searcher").PI_SUBAGENT_CHILD_AGENT).toBe("fr-searcher");
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe("resolveOrchestratorName", () => {
|
|
44
|
+
beforeEach(() => {
|
|
45
|
+
setOrchestratorNameResolver(undefined);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("未注册 resolver 时返回 undefined", async () => {
|
|
49
|
+
expect(await resolveOrchestratorName()).toBeUndefined();
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("注册后返回 resolver 结果", async () => {
|
|
53
|
+
setOrchestratorNameResolver(async () => "main-session");
|
|
54
|
+
expect(await resolveOrchestratorName()).toBe("main-session");
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("resolver 抛错时安全降级为 undefined", async () => {
|
|
58
|
+
setOrchestratorNameResolver(() => { throw new Error("boom"); });
|
|
59
|
+
expect(await resolveOrchestratorName()).toBeUndefined();
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("resolver 可注销", async () => {
|
|
63
|
+
setOrchestratorNameResolver(async () => "x");
|
|
64
|
+
setOrchestratorNameResolver(undefined);
|
|
65
|
+
expect(await resolveOrchestratorName()).toBeUndefined();
|
|
66
|
+
});
|
|
67
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 测试 subagent.ts:validateOutputConstraints 纯函数
|
|
3
|
+
*/
|
|
4
|
+
import { describe, it, expect } from "vitest";
|
|
5
|
+
import { validateOutputConstraints } from "../subagent";
|
|
6
|
+
|
|
7
|
+
describe("validateOutputConstraints", () => {
|
|
8
|
+
it("无约束时返回空列表", () => {
|
|
9
|
+
expect(validateOutputConstraints("hello", [])).toEqual([]);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it("全部通过返回空列表", () => {
|
|
13
|
+
const constraints = [
|
|
14
|
+
{ rule: "必须是 JSON", validate: (s: string) => (s.startsWith("{") ? null : "not json") },
|
|
15
|
+
];
|
|
16
|
+
expect(validateOutputConstraints('{"ok":true}', constraints)).toEqual([]);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("有不通过的返回错误列表", () => {
|
|
20
|
+
const constraints = [
|
|
21
|
+
{ rule: "必须是 JSON", validate: (s: string) => (s.startsWith("{") ? null : "not json") },
|
|
22
|
+
{ rule: "包含 ok", validate: (s: string) => (s.includes("ok") ? null : "missing ok") },
|
|
23
|
+
];
|
|
24
|
+
expect(validateOutputConstraints("plain text", constraints)).toEqual(["not json", "missing ok"]);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it("部分通过只返回不通过的", () => {
|
|
28
|
+
const constraints = [
|
|
29
|
+
{ rule: "包含 ok", validate: (s: string) => (s.includes("ok") ? null : "missing ok") },
|
|
30
|
+
{ rule: "包含 err", validate: (s: string) => (s.includes("err") ? null : "missing err") },
|
|
31
|
+
];
|
|
32
|
+
expect(validateOutputConstraints("has ok but not e", constraints)).toEqual(["missing err"]);
|
|
33
|
+
});
|
|
34
|
+
});
|