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.
@@ -1,88 +1,96 @@
1
1
  /**
2
2
  * 测试 subagent-spawn-visible.ts:spawnVisible
3
3
  *
4
- * spawnVisible 深度依赖 tmux + execFileSync + 轮询。
5
- * 当 tmux 不可用时,会 fallback 到 spawnOnce。
6
- * 这里主要测试:tmux 成功路径 + fallback 路径 + 超时 + abort。
4
+ * 新实现通过 term-backend 抽象分屏(WezTerm/tmux),测试 mock 整个后端:
5
+ * 终端不可用 fallback / pane 消失后读取结果 / 超时 / abort。
7
6
  */
8
7
  import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
9
8
 
10
9
  vi.mock("../subagent-utils", () => ({
11
10
  getPiCommand: vi.fn(() => ({ command: "node", args: ["/usr/local/bin/pi"] })),
11
+ createVisibleTaskDir: vi.fn(() => ({
12
+ taskDir: "/tmp/pi-visible-test",
13
+ taskFile: "/tmp/pi-visible-test/task.txt",
14
+ sessionFile: "/tmp/pi-visible-test/session.jsonl",
15
+ launchScript: "/tmp/pi-visible-test/launch.sh",
16
+ })),
17
+ injectParentSession: vi.fn(),
12
18
  }));
13
- vi.mock("@earendil-works/pi-coding-agent", () => ({}));
14
19
  vi.mock("../subagent-spawn-once", () => ({
15
20
  spawnOnce: vi.fn(() => Promise.resolve({ exitCode: 0, output: "fallback", stderr: "" })),
16
21
  }));
17
22
 
18
- const { childProcessMock } = vi.hoisted(() => {
19
- const results: { error?: Error; stdout?: string }[] = [];
20
- let callIdx = 0;
23
+ const { backendMock, termDetect } = vi.hoisted(() => {
24
+ const backend = {
25
+ splitPane: vi.fn(() => "%42"),
26
+ killPane: vi.fn(),
27
+ isPaneAlive: vi.fn(() => true),
28
+ };
29
+ let detect: string | null = "tmux";
21
30
  return {
22
- childProcessMock: {
23
- __results: results,
24
- __reset: () => { callIdx = 0; results.length = 0; },
25
- execFileSync: (...args: any[]) => {
26
- const r = results[callIdx++];
27
- if (r?.error) throw r.error;
28
- return r?.stdout ?? "";
29
- },
31
+ backendMock: backend,
32
+ termDetect: {
33
+ set: (v: string | null) => { detect = v; },
34
+ get: () => detect,
30
35
  },
31
36
  };
32
37
  });
33
38
 
34
- vi.mock("node:child_process", async (importOriginal) => {
35
- const actual = await importOriginal() as any;
36
- return { ...actual, execFileSync: childProcessMock.execFileSync };
37
- });
39
+ vi.mock("../term-backend", () => ({
40
+ detectTerminal: () => termDetect.get(),
41
+ getBackend: () => backendMock,
42
+ }));
38
43
 
39
- const { fsMock } = vi.hoisted(() => {
40
- const mock = {
44
+ const { fsMock } = vi.hoisted(() => ({
45
+ fsMock: {
41
46
  existsSync: vi.fn(() => false),
42
47
  readFileSync: vi.fn(() => ""),
43
48
  writeFileSync: vi.fn(),
44
- mkdirSync: vi.fn(),
45
- mkdtempSync: vi.fn(() => "/tmp/pi-visible-test"),
46
49
  rmSync: vi.fn(),
47
- };
48
- return { fsMock: mock };
49
- });
50
+ },
51
+ }));
50
52
 
51
- vi.mock("node:fs", () => fsMock);
53
+ vi.mock("node:fs", async (importOriginal) => {
54
+ const actual = await importOriginal() as any;
55
+ return { ...actual, ...fsMock };
56
+ });
52
57
 
53
58
  import { spawnVisible } from "../subagent-spawn-visible";
54
59
  import { spawnOnce } from "../subagent-spawn-once";
60
+ import { createVisibleTaskDir } from "../subagent-utils";
55
61
 
56
62
  describe("spawnVisible", () => {
57
63
  beforeEach(() => {
58
64
  vi.useFakeTimers({ shouldAdvanceTime: true });
59
- childProcessMock.__reset();
65
+ termDetect.set("tmux");
66
+ backendMock.splitPane.mockReturnValue("%42");
67
+ backendMock.isPaneAlive.mockReturnValue(true);
68
+ backendMock.killPane.mockClear();
60
69
  fsMock.existsSync.mockReturnValue(false);
61
70
  fsMock.readFileSync.mockReturnValue("");
62
71
  });
63
72
  afterEach(() => {
64
73
  vi.useRealTimers();
65
- vi.restoreAllMocks();
66
74
  });
67
75
 
68
- it("tmux 不可用时 fallback 到 spawnOnce", async () => {
69
- // tmux split-window 失败 → fallback
70
- childProcessMock.__results.push({ error: new Error("tmux not found") });
71
-
76
+ it("终端不可用时 fallback 到 spawnOnce", async () => {
77
+ termDetect.set(null);
72
78
  const result = await spawnVisible("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] });
73
79
  expect(spawnOnce).toHaveBeenCalled();
74
80
  expect(result.exitCode).toBe(0);
75
81
  expect(result.output).toBe("fallback");
76
82
  });
77
83
 
78
- it("tmux 成功 + pane 消失后读取结果文件", async () => {
79
- // 1st call: tmux split-window → 成功,返回 pane ID
80
- childProcessMock.__results.push({ stdout: " %42\n" });
81
- // 2nd+ calls: tmux list-panes → 失败(pane 已消失)触发 finish
82
- childProcessMock.__results.push({ error: new Error("no pane") });
83
- childProcessMock.__results.push({ error: new Error("no pane") });
84
- // finish 内部调 execFileSync("sleep",...)
85
- childProcessMock.__results.push({ stdout: "" });
84
+ it("splitPane 失败时 fallback 到 spawnOnce", async () => {
85
+ backendMock.splitPane.mockImplementation(() => { throw new Error("split failed"); });
86
+ const result = await spawnVisible("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] });
87
+ expect(spawnOnce).toHaveBeenCalled();
88
+ expect(result.exitCode).toBe(0);
89
+ });
90
+
91
+ it("分屏成功 + pane 消失后读取结果文件", async () => {
92
+ // pane 消失触发 finish
93
+ backendMock.isPaneAlive.mockReturnValue(false);
86
94
 
87
95
  // session 文件有内容
88
96
  fsMock.existsSync.mockReturnValue(true);
@@ -97,43 +105,45 @@ describe("spawnVisible", () => {
97
105
  expect(result.output).toContain("hello");
98
106
  });
99
107
 
100
- it("超时时返回 timedOut", async () => {
101
- // tmux 成功
102
- childProcessMock.__results.push({ stdout: " %42\n" });
103
- // list-panes 一直成功(pane 存在),但无 session 文件
104
- for (let i = 0; i < 100; i++) {
105
- childProcessMock.__results.push({ stdout: "%42: [100x50] [active]" });
106
- }
108
+ it("超时时返回 timedOut 并清理 pane", async () => {
109
+ // pane 一直存活,但无 session 文件
110
+ backendMock.isPaneAlive.mockReturnValue(true);
107
111
  fsMock.existsSync.mockReturnValue(false);
108
112
 
109
113
  const resultPromise = spawnVisible("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, undefined, 1000);
110
114
 
111
- // 推进到超时
112
115
  await vi.advanceTimersByTimeAsync(3000);
113
116
 
114
117
  const result = await resultPromise;
115
118
  expect(result.timedOut).toBe(true);
119
+ expect(backendMock.killPane).toHaveBeenCalledWith("%42");
116
120
  });
117
121
 
118
- it("signal abort 时终止", async () => {
122
+ it("signal abort 时终止并清理", async () => {
119
123
  const controller = new AbortController();
120
-
121
- // tmux 成功
122
- childProcessMock.__results.push({ stdout: " %42\n" });
123
- // list-panes 持续成功
124
- for (let i = 0; i < 100; i++) {
125
- childProcessMock.__results.push({ stdout: "%42" });
126
- }
127
-
124
+ backendMock.isPaneAlive.mockReturnValue(true);
128
125
  fsMock.existsSync.mockReturnValue(false);
129
126
 
130
127
  const resultPromise = spawnVisible("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, controller.signal, undefined, 10000);
131
128
 
132
- // 触发 abort
133
129
  controller.abort();
134
130
 
135
131
  const result = await resultPromise;
136
132
  expect(result.stderr).toContain("aborted");
137
133
  expect(result.exitCode).toBe(1);
134
+ expect(backendMock.killPane).toHaveBeenCalled();
135
+ });
136
+
137
+ it("extraEnv 透传到 createVisibleTaskDir", async () => {
138
+ termDetect.set(null); // 直接走 fallback,验证参数传递
139
+ await spawnVisible(
140
+ "task", "/cwd", "/tmp/prompt.md", { tools: ["read"] },
141
+ undefined, undefined, undefined, undefined, undefined,
142
+ { PI_SUBAGENT_RUN_ID: "run-abc" },
143
+ );
144
+ expect(createVisibleTaskDir).toHaveBeenCalledWith(
145
+ "task", "/cwd", "/tmp/prompt.md", { tools: ["read"] },
146
+ undefined, { PI_SUBAGENT_RUN_ID: "run-abc" },
147
+ );
138
148
  });
139
149
  });
@@ -7,7 +7,7 @@ import { vi } from "vitest";
7
7
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
8
8
 
9
9
  export function createMockContext(entries: any[] = []): ExtensionContext {
10
- return {
10
+ return ({
11
11
  cwd: "/tmp/test",
12
12
  hasUI: true,
13
13
  ui: {
@@ -36,5 +36,5 @@ export function createMockContext(entries: any[] = []): ExtensionContext {
36
36
  getSystemPrompt: vi.fn().mockReturnValue(""),
37
37
  model: undefined,
38
38
  modelRegistry: {} as any,
39
- };
39
+ } as unknown) as ExtensionContext;
40
40
  }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 测试 timeout-config.ts — 超时优先级链解析
3
+ *
4
+ * 优先级:fallback(30min) < timeoutMs < agentTimeouts[name] < 显式传参
5
+ */
6
+ import { describe, it, expect, vi, beforeEach } from "vitest";
7
+
8
+ // mock getEffectiveConfig(三层合并由 shared-utils 测试覆盖,这里只测优先级链)
9
+ const { configMock } = vi.hoisted(() => ({
10
+ configMock: {
11
+ set: (v: any) => { (configMock as any).__v = v; },
12
+ get: () => (configMock as any).__v,
13
+ },
14
+ }));
15
+
16
+ vi.mock("@pi-atelier/shared-utils", () => ({
17
+ getEffectiveConfig: vi.fn((section: string, defaults: any) => ({
18
+ config: { ...defaults, ...(configMock.get() ?? {}) },
19
+ sources: {},
20
+ })),
21
+ }));
22
+
23
+ import { resolveSubagentTimeout, DEFAULT_SUBAGENT_TIMEOUT_MS } from "../timeout-config";
24
+ import { getEffectiveConfig } from "@pi-atelier/shared-utils";
25
+
26
+ describe("resolveSubagentTimeout — 优先级链", () => {
27
+ beforeEach(() => {
28
+ vi.clearAllMocks();
29
+ configMock.set(undefined);
30
+ });
31
+
32
+ it("无任何配置时返回 30min fallback", () => {
33
+ expect(resolveSubagentTimeout("any", "/cwd")).toBe(DEFAULT_SUBAGENT_TIMEOUT_MS);
34
+ expect(DEFAULT_SUBAGENT_TIMEOUT_MS).toBe(30 * 60 * 1000);
35
+ });
36
+
37
+ it("timeoutMs 配置覆盖 fallback", () => {
38
+ configMock.set({ timeoutMs: 1800000 });
39
+ expect(resolveSubagentTimeout("any", "/cwd")).toBe(1800000);
40
+ });
41
+
42
+ it("agentTimeouts 条目覆盖 timeoutMs", () => {
43
+ configMock.set({ timeoutMs: 1800000, agentTimeouts: { "fo-analyzer": 3600000 } });
44
+ expect(resolveSubagentTimeout("fo-analyzer", "/cwd")).toBe(3600000);
45
+ // 其他 agent 不受影响,走 timeoutMs
46
+ expect(resolveSubagentTimeout("fo-verifier", "/cwd")).toBe(1800000);
47
+ });
48
+
49
+ it("显式传参优先级最高", () => {
50
+ configMock.set({ timeoutMs: 1800000, agentTimeouts: { "fo-analyzer": 3600000 } });
51
+ expect(resolveSubagentTimeout("fo-analyzer", "/cwd", 600000)).toBe(600000);
52
+ });
53
+
54
+ it("显式传参 0 或负值视为未传", () => {
55
+ configMock.set({ timeoutMs: 1800000 });
56
+ expect(resolveSubagentTimeout("x", "/cwd", 0)).toBe(1800000);
57
+ expect(resolveSubagentTimeout("x", "/cwd", -1)).toBe(1800000);
58
+ });
59
+
60
+ it("无效配置值(非正数)回退低优先级来源", () => {
61
+ configMock.set({ timeoutMs: 0, agentTimeouts: { bad: -5 } });
62
+ expect(resolveSubagentTimeout("bad", "/cwd")).toBe(DEFAULT_SUBAGENT_TIMEOUT_MS);
63
+ });
64
+
65
+ it("经 getEffectiveConfig 三层合并读取(cwd 传递)", () => {
66
+ configMock.set({ timeoutMs: 900000 });
67
+ resolveSubagentTimeout("x", "/proj/dir");
68
+ expect(getEffectiveConfig).toHaveBeenCalledWith(
69
+ "subagent",
70
+ expect.objectContaining({ timeoutMs: DEFAULT_SUBAGENT_TIMEOUT_MS, agentTimeouts: {} }),
71
+ "/proj/dir",
72
+ );
73
+ });
74
+ });
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 子代理超时配置 — 优先级链单点解析
3
+ *
4
+ * 优先级(低 → 高):
5
+ * 代码 fallback (30min) < subagent.timeoutMs < subagent.agentTimeouts[name] < 调用方显式传参
6
+ *
7
+ * 配置经 shared-utils getEffectiveConfig() 三层合并:
8
+ * 代码默认 → 全局 ~/.pi/agent/settings.json → 项目 {cwd}/.pi/settings.json
9
+ */
10
+
11
+ import { getEffectiveConfig } from "@pi-atelier/shared-utils";
12
+
13
+ /** 超时配置 schema */
14
+ export interface SubagentTimeoutConfig {
15
+ /** 全局默认超时(毫秒) */
16
+ timeoutMs: number;
17
+ /** per-agent 超时覆盖(agent 名 → 毫秒) */
18
+ agentTimeouts: Record<string, number>;
19
+ }
20
+
21
+ /** 代码级 fallback:30 分钟 */
22
+ export const DEFAULT_SUBAGENT_TIMEOUT_MS = 30 * 60 * 1000;
23
+
24
+ /** subagent section 超时字段的 schema 默认值(用于三层合并与类型校验) */
25
+ export const SUBAGENT_TIMEOUT_DEFAULTS: SubagentTimeoutConfig = {
26
+ timeoutMs: DEFAULT_SUBAGENT_TIMEOUT_MS,
27
+ agentTimeouts: {},
28
+ };
29
+
30
+ /**
31
+ * 解析某个 agent 的有效超时。
32
+ *
33
+ * @param agentName agent 名(对应 agents/{name}.md)
34
+ * @param cwd 当前项目目录(用于项目级 .pi/settings.json 覆盖)
35
+ * @param explicit 调用方显式传参(最高优先级,undefined 表示未传)
36
+ */
37
+ export function resolveSubagentTimeout(
38
+ agentName: string,
39
+ cwd: string,
40
+ explicit?: number,
41
+ ): number {
42
+ const { config } = getEffectiveConfig(
43
+ "subagent",
44
+ SUBAGENT_TIMEOUT_DEFAULTS,
45
+ cwd,
46
+ );
47
+
48
+ if (explicit !== undefined && explicit > 0) return explicit;
49
+ const perAgent = config.agentTimeouts?.[agentName];
50
+ if (typeof perAgent === "number" && perAgent > 0) return perAgent;
51
+ if (typeof config.timeoutMs === "number" && config.timeoutMs > 0) {
52
+ return config.timeoutMs;
53
+ }
54
+ return DEFAULT_SUBAGENT_TIMEOUT_MS;
55
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "types": ["node"],
5
+ "outDir": "dist",
6
+ "rootDir": "."
7
+ },
8
+ "include": ["*.ts", "tests/**/*.ts"],
9
+ "exclude": ["vitest.config.ts"]
10
+ }
package/vitest.config.ts CHANGED
@@ -1,21 +1,14 @@
1
- import { defineConfig } from "vitest/config";
2
-
3
- // workflow 的测试使用内联实现(不依赖真实 pi 包)
4
- // peerDependencies 由 pi 运行时解析,测试阶段不需要
5
- export default defineConfig({
6
- test: {
7
- include: ["tests/**/*.test.ts"],
8
- exclude: ["**/*.subagent.test.ts"],
9
- coverage: {
10
- provider: "v8" as const,
11
- reporter: ["text", "html"],
12
- exclude: [
13
- "types.ts",
14
- "research-types.ts",
15
- "index.ts",
16
- "vitest.config.*",
17
- "tests/**",
18
- ],
19
- },
20
- },
21
- });
1
+ import { createConfig } from "../vitest.config.base";
2
+
3
+ export default createConfig({
4
+ include: ["tests/**/*.test.ts"],
5
+ test: {
6
+ coverage: {
7
+ exclude: [
8
+ "types.ts",
9
+ "research-types.ts",
10
+ "vitest.config.*",
11
+ ],
12
+ },
13
+ },
14
+ });
package/agent-loader.ts DELETED
@@ -1,88 +0,0 @@
1
- /**
2
- * workflow: Agent 定义加载器
3
- *
4
- * 从 ~/.pi/agent/agents/*.md 或 ~/.agents/agents/*.md 加载子代理定义。
5
- * 带 mtime 缓存,避免重复解析。
6
- */
7
-
8
- import * as fs from "node:fs";
9
- import * as path from "node:path";
10
- import * as os from "node:os";
11
-
12
- export interface AgentDef {
13
- name: string;
14
- tools: string[];
15
- model?: string;
16
- thinking?: string;
17
- systemPrompt: string;
18
- }
19
-
20
- interface CacheEntry {
21
- mtime: number;
22
- def: AgentDef;
23
- }
24
-
25
- const agentCache = new Map<string, CacheEntry>();
26
-
27
- export function loadAgentDef(agentName: string): AgentDef | null {
28
- const dirs = [
29
- path.join(os.homedir(), ".pi", "agent", "agents"),
30
- path.join(os.homedir(), ".agents", "agents"),
31
- ];
32
-
33
- for (const searchDir of dirs) {
34
- const filePath = path.join(searchDir, `${agentName}.md`);
35
- if (!fs.existsSync(filePath)) continue;
36
-
37
- const stat = fs.statSync(filePath);
38
- const cacheKey = filePath;
39
-
40
- const cached = agentCache.get(cacheKey);
41
- if (cached && cached.mtime === stat.mtimeMs) {
42
- return cached.def;
43
- }
44
-
45
- const content = fs.readFileSync(filePath, "utf-8");
46
- const def = parseAgentFile(content, agentName);
47
- if (def) {
48
- agentCache.set(cacheKey, { mtime: stat.mtimeMs, def });
49
- return def;
50
- }
51
- }
52
-
53
- return null;
54
- }
55
-
56
- function parseAgentFile(content: string, agentName: string): AgentDef {
57
- const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
58
- if (!fmMatch) {
59
- return {
60
- name: agentName,
61
- tools: ["read", "grep", "find", "ls"],
62
- systemPrompt: content.trim(),
63
- };
64
- }
65
-
66
- const fm = fmMatch[1];
67
- const body = content.slice(fmMatch[0].length).trim();
68
- const fields: Record<string, string> = {};
69
-
70
- for (const line of fm.split("\n")) {
71
- const idx = line.indexOf(":");
72
- if (idx > 0) {
73
- let val = line.slice(idx + 1).trim();
74
- if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
75
- val = val.slice(1, -1);
76
- }
77
- fields[line.slice(0, idx).trim()] = val;
78
- }
79
- }
80
-
81
- return {
82
- name: fields.name || agentName,
83
- tools: fields.tools ? fields.tools.split(",").map((t) => t.trim()).filter(Boolean) : ["read", "grep", "find", "ls"],
84
- model: fields.model || undefined,
85
- thinking: fields.thinking || undefined,
86
- systemPrompt: body || content.trim(),
87
- };
88
- }
@@ -1,183 +0,0 @@
1
- /**
2
- * Tests: agent-loader.ts — loadAgentDef + parseAgentFile + 缓存行为
3
- *
4
- * 测试场景(12 用例):
5
- * 1) 加载存在带 frontmatter 的 agent 文件 → 返回完整 AgentDef
6
- * 2) 加载存在无 frontmatter 的 agent 文件 → body 作为 systemPrompt
7
- * 3) 加载不存在的 agent → 返回 null
8
- * 4) 搜索两个路径(.pi/agent/agents 和 .agents/agents)
9
- * 5) 缓存命中(mtime 未变)→ 不重新读文件
10
- * 6) 缓存过期(mtime 改变)→ 重新读文件
11
- * 7) frontmatter 解析:name/tools/model/thinking 字段
12
- * 8) tools 逗号分隔
13
- * 9) 引号移除
14
- * 10) 无 tools 字段 → 默认 tools
15
- * 11) 空 body 情况
16
- */
17
-
18
- import { describe, it, expect, vi, beforeEach } from "vitest";
19
- import * as path from "node:path";
20
-
21
- const MOCK_HOME = "/home/testuser";
22
-
23
- // Track readFileSync call count
24
- let readFileCallCount = 0;
25
-
26
- vi.mock("node:os", () => ({ homedir: () => MOCK_HOME }));
27
-
28
- const mockFiles = new Map<string, { content: string; mtimeMs: number }>();
29
-
30
- vi.mock("node:fs", () => ({
31
- existsSync: (p: string) => mockFiles.has(p),
32
- statSync: (p: string) => {
33
- const entry = mockFiles.get(p);
34
- if (!entry) throw new Error(`ENOENT: ${p}`);
35
- return { mtimeMs: entry.mtimeMs };
36
- },
37
- readFileSync: (p: string, _encoding?: any) => {
38
- readFileCallCount++;
39
- const entry = mockFiles.get(p);
40
- if (!entry) throw new Error(`ENOENT: ${p}`);
41
- return entry.content;
42
- },
43
- promises: {},
44
- }));
45
-
46
- function addMockFile(fullRelPath: string, content: string, mtimeMs: number = 1000) {
47
- mockFiles.set(path.join(MOCK_HOME, fullRelPath), { content, mtimeMs });
48
- }
49
-
50
- import { loadAgentDef } from "../agent-loader";
51
-
52
- describe("loadAgentDef", () => {
53
- beforeEach(() => {
54
- mockFiles.clear();
55
- readFileCallCount = 0;
56
- });
57
-
58
- it("加载存在带 frontmatter 的 agent → 返回完整 AgentDef", () => {
59
- addMockFile(".pi/agent/agents/reviewer.md",
60
- "---\nname: reviewer\ntools: read,grep,find\nmodel: gpt-4\nthinking: auto\n---\n你是一个 code reviewer。",
61
- );
62
- const def = loadAgentDef("reviewer");
63
- expect(def).not.toBeNull();
64
- expect(def!.name).toBe("reviewer");
65
- expect(def!.tools).toEqual(["read", "grep", "find"]);
66
- expect(def!.model).toBe("gpt-4");
67
- expect(def!.thinking).toBe("auto");
68
- expect(def!.systemPrompt).toBe("你是一个 code reviewer。");
69
- });
70
-
71
- it("加载存在无 frontmatter 的 agent → body 作为 systemPrompt,默认 tools", () => {
72
- addMockFile(".pi/agent/agents/simple.md", "你是一个简单的 agent,不做任何工具调用。");
73
- const def = loadAgentDef("simple");
74
- expect(def).not.toBeNull();
75
- expect(def!.name).toBe("simple");
76
- expect(def!.tools).toEqual(["read", "grep", "find", "ls"]);
77
- expect(def!.systemPrompt).toBe("你是一个简单的 agent,不做任何工具调用。");
78
- expect(def!.model).toBeUndefined();
79
- });
80
-
81
- it("加载不存在 agent → 返回 null", () => {
82
- const def = loadAgentDef("nonexistent");
83
- expect(def).toBeNull();
84
- });
85
-
86
- it("优先搜索 .pi/agent/agents,再搜索 .agents/agents", () => {
87
- addMockFile(".agents/agents/fallback.md", "Fallback agent");
88
- const def = loadAgentDef("fallback");
89
- expect(def).not.toBeNull();
90
- expect(def!.systemPrompt).toBe("Fallback agent");
91
- });
92
-
93
- it("第一路径存在时,不使用第二路径", () => {
94
- addMockFile(".pi/agent/agents/dup.md", "Primary version");
95
- addMockFile(".agents/agents/dup.md", "Secondary version");
96
- const def = loadAgentDef("dup");
97
- expect(def).not.toBeNull();
98
- expect(def!.systemPrompt).toBe("Primary version");
99
- });
100
-
101
- it("缓存命中(mtime 未变)→ 只读一次文件", () => {
102
- addMockFile(".pi/agent/agents/cached.md",
103
- "---\nname: cached\ntools: read\n---\nContent",
104
- 1000,
105
- );
106
- // First call — load and cache
107
- const def1 = loadAgentDef("cached");
108
- expect(def1).not.toBeNull();
109
- const callsAfterFirst = readFileCallCount;
110
-
111
- // Second call — should use cache
112
- const def2 = loadAgentDef("cached");
113
- expect(def2).not.toBeNull();
114
- expect(readFileCallCount).toBe(callsAfterFirst);
115
- });
116
-
117
- it("缓存过期(mtime 改变)→ 重新读文件", () => {
118
- addMockFile(".pi/agent/agents/outdated.md",
119
- "---\nname: outdated\ntools: read\n---\nOld",
120
- 1000,
121
- );
122
- // First call — populate cache
123
- loadAgentDef("outdated");
124
- const callsAfterFirst = readFileCallCount;
125
-
126
- // Update file mtime and content
127
- addMockFile(".pi/agent/agents/outdated.md",
128
- "---\nname: outdated\ntools: read,grep\n---\nNew",
129
- 2000,
130
- );
131
-
132
- const def = loadAgentDef("outdated");
133
- expect(def).not.toBeNull();
134
- expect(def!.tools).toEqual(["read", "grep"]);
135
- expect(def!.systemPrompt).toBe("New");
136
- expect(readFileCallCount).toBe(callsAfterFirst + 1);
137
- });
138
-
139
- it("frontmatter 解析:引号去除", () => {
140
- addMockFile(".pi/agent/agents/quoted.md",
141
- `---\nname: "quoted-agent"\ntools: "read,grep"\nmodel: 'gpt-4'\n---\nPrompt body`,
142
- );
143
- const def = loadAgentDef("quoted");
144
- expect(def).not.toBeNull();
145
- expect(def!.name).toBe("quoted-agent");
146
- expect(def!.tools).toEqual(["read", "grep"]);
147
- expect(def!.model).toBe("gpt-4");
148
- });
149
-
150
- it("无 tools 字段 → 默认 tools", () => {
151
- addMockFile(".pi/agent/agents/notools.md", "---\nname: notools\n---\nJust a prompt");
152
- const def = loadAgentDef("notools");
153
- expect(def).not.toBeNull();
154
- expect(def!.tools).toEqual(["read", "grep", "find", "ls"]);
155
- });
156
-
157
- it("tools 逗号分隔含空格 → 正确 trim", () => {
158
- addMockFile(".pi/agent/agents/trimmed.md",
159
- "---\nname: trimmed\ntools: read , grep , find\n---\nContent",
160
- );
161
- const def = loadAgentDef("trimmed");
162
- expect(def).not.toBeNull();
163
- expect(def!.tools).toEqual(["read", "grep", "find"]);
164
- });
165
-
166
- it("不带 frontmatter 且 body 为空 → body 用 content.trim()", () => {
167
- addMockFile(".pi/agent/agents/emptybody.md", " \n \n");
168
- const def = loadAgentDef("emptybody");
169
- expect(def).not.toBeNull();
170
- expect(def!.systemPrompt).toBe("");
171
- });
172
-
173
- it("frontmatter 有额外未知字段 → 忽略,不报错", () => {
174
- addMockFile(".pi/agent/agents/extra.md",
175
- "---\nname: extra\ntools: read\nunknown_field: hello\n---\nContent",
176
- );
177
- const def = loadAgentDef("extra");
178
- expect(def).not.toBeNull();
179
- expect(def!.name).toBe("extra");
180
- expect(def!.tools).toEqual(["read"]);
181
- expect(def!.systemPrompt).toBe("Content");
182
- });
183
- });