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,155 @@
1
+ /**
2
+ * Tests: workflow.ts — registerWorkflowTool 工具注册 + gate
3
+ *
4
+ * 测试场景(5 用例):
5
+ * 1) registerTool 被调用,参数 schema 包含 action 枚举
6
+ * 2) promptSnippet 和 promptGuidelines 透传
7
+ * 3) gate 返回 {pass:false} → handler 不执行
8
+ * 4) gate 返回 {pass:true} → handler 正常执行
9
+ * 5) 未知 action 返回可读错误
10
+ */
11
+
12
+ import { describe, it, expect, vi } from "vitest";
13
+ import type { ExtensionContext, ExtensionAPI } from "@earendil-works/pi-coding-agent";
14
+ import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
15
+ import { createMockContext } from "./test-helpers";
16
+
17
+ // ============================================================
18
+ // Types
19
+ // ============================================================
20
+
21
+ interface ActionDef<T> {
22
+ description: string;
23
+ handler: (params: any, state: T, ctx: ExtensionContext, signal?: AbortSignal, onUpdate?: any) => Promise<AgentToolResult<any>>;
24
+ gate?: (state: T) => { pass: boolean; reason?: string };
25
+ }
26
+ interface StateManager<T> { get(): T; set(s: T): void; reset(): void; persist(ctx: ExtensionContext): void; restore(ctx: ExtensionContext): void }
27
+ interface UIUpdater<T> { update(ctx: ExtensionContext, state: T): void; clear(ctx: ExtensionContext): void }
28
+
29
+ // ============================================================
30
+ // Inline implementation
31
+ // ============================================================
32
+
33
+ function registerWorkflowTool<T>(pi: ExtensionAPI, options: {
34
+ name: string; description: string; promptSnippet?: string; promptGuidelines?: string[];
35
+ actions: Record<string, ActionDef<T>>; stateManager: StateManager<T>; uiUpdater: UIUpdater<T>;
36
+ }): void {
37
+ const actionNames = Object.keys(options.actions);
38
+ pi.registerTool({
39
+ name: options.name,
40
+ label: options.name,
41
+ description: options.description,
42
+ promptSnippet: options.promptSnippet,
43
+ promptGuidelines: options.promptGuidelines,
44
+ parameters: { type: "object", properties: { action: { type: "string", enum: actionNames } }, required: ["action"] },
45
+ execute: async (_tcId: string, params: any, signal: AbortSignal | undefined, onUpdate: any, ctx: ExtensionContext): Promise<AgentToolResult<any>> => {
46
+ const { action, ...actionParams } = params;
47
+ const actionDef = options.actions[action as string];
48
+ if (!actionDef) {
49
+ return { content: [{ type: "text" as const, text: `未知 action: "${action}"。可用: ${actionNames.join(", ")}` }], details: { error: `unknown_action: ${action}` }, terminate: false };
50
+ }
51
+ if (actionDef.gate) {
52
+ const gateResult = actionDef.gate(options.stateManager.get());
53
+ if (!gateResult.pass) {
54
+ return { content: [{ type: "text" as const, text: `Gate 阻止: ${gateResult.reason}` }], details: { error: `gate_blocked: ${gateResult.reason}` }, terminate: false };
55
+ }
56
+ }
57
+ try {
58
+ const result = await actionDef.handler(actionParams, options.stateManager.get(), ctx, signal, onUpdate);
59
+ options.stateManager.persist(ctx);
60
+ options.uiUpdater.update(ctx, options.stateManager.get());
61
+ return result;
62
+ } catch (err) {
63
+ options.stateManager.persist(ctx);
64
+ options.uiUpdater.update(ctx, options.stateManager.get());
65
+ throw err;
66
+ }
67
+ },
68
+ } as any);
69
+ }
70
+
71
+ // ============================================================
72
+ // Fixtures
73
+ // ============================================================
74
+
75
+ interface TestState { phase: string; items: string[]; round: number }
76
+ const INITIAL: TestState = { phase: "idle", items: [], round: 0 };
77
+
78
+ function mockSM(): StateManager<TestState> {
79
+ let s: TestState = { ...INITIAL };
80
+ return { get: vi.fn(() => s), set: vi.fn((v: TestState) => { s = v; }), reset: vi.fn(() => { s = { ...INITIAL }; }), persist: vi.fn(), restore: vi.fn() };
81
+ }
82
+ function mockUI(): UIUpdater<TestState> { return { update: vi.fn(), clear: vi.fn() }; }
83
+ function mockAPI(): ExtensionAPI {
84
+ return { on: vi.fn(), registerTool: vi.fn(), registerCommand: vi.fn(), registerShortcut: vi.fn(), registerFlag: vi.fn(), getFlag: vi.fn(), registerMessageRenderer: vi.fn(), sendMessage: vi.fn(), sendUserMessage: vi.fn(), appendEntry: vi.fn(), setSessionName: vi.fn(), getSessionName: vi.fn(), setLabel: vi.fn(), getActiveTools: vi.fn().mockReturnValue([]), getAllTools: vi.fn().mockReturnValue([]), setActiveTools: vi.fn(), refreshTools: vi.fn(), getCommands: vi.fn().mockReturnValue([]), setModel: vi.fn(), getThinkingLevel: vi.fn(), setThinkingLevel: vi.fn(), exec: vi.fn() } as any;
85
+ }
86
+
87
+ // ============================================================
88
+ // Tests: 工具注册
89
+ // ============================================================
90
+
91
+ describe("registerWorkflowTool — 工具注册", () => {
92
+ const defaultHandler = () => Promise.resolve({ content: [{ type: "text" as const, text: "ok" }], details: {} });
93
+
94
+ it("registerTool 被调用,参数 schema 包含 action 枚举", () => {
95
+ const api = mockAPI();
96
+ registerWorkflowTool(api, { name: "pv", description: "PV", actions: { plan: { description: "plan", handler: defaultHandler }, execute: { description: "exec", handler: defaultHandler } }, stateManager: mockSM(), uiUpdater: mockUI() });
97
+ expect(api.registerTool).toHaveBeenCalledTimes(1);
98
+ const def = (api.registerTool as any).mock.calls[0][0];
99
+ expect(def.name).toBe("pv");
100
+ expect(def.parameters.properties.action.enum).toEqual(["plan", "execute"]);
101
+ });
102
+
103
+ it("promptSnippet 和 promptGuidelines 透传", () => {
104
+ const api = mockAPI();
105
+ const gs = ["不要并行执行", "每次检查状态"];
106
+ registerWorkflowTool(api, { name: "pv", description: "PV", promptSnippet: "/pv 启动", promptGuidelines: gs, actions: { plan: { description: "plan", handler: defaultHandler } }, stateManager: mockSM(), uiUpdater: mockUI() });
107
+ const def = (api.registerTool as any).mock.calls[0][0];
108
+ expect(def.promptSnippet).toBe("/pv 启动");
109
+ expect(def.promptGuidelines).toEqual(gs);
110
+ });
111
+ });
112
+
113
+ // ============================================================
114
+ // Tests: gate
115
+ // ============================================================
116
+
117
+ describe("registerWorkflowTool — gate", () => {
118
+ it("gate {pass:false} → handler 不执行,返回阻止信息", async () => {
119
+ const api = mockAPI();
120
+ const sm = mockSM();
121
+ const handler = vi.fn();
122
+ registerWorkflowTool(api, { name: "pv", description: "PV", actions: { exec: { description: "exec", handler, gate: (s) => s.phase === "ready" ? { pass: true } : { pass: false, reason: `not ready: ${s.phase}` } } }, stateManager: sm, uiUpdater: mockUI() });
123
+ const def = (api.registerTool as any).mock.calls[0][0];
124
+ const r = await def.execute("c1", { action: "exec" }, undefined, undefined, createMockContext());
125
+ expect(handler).not.toHaveBeenCalled();
126
+ expect(r.content[0]).toEqual(expect.objectContaining({ text: expect.stringContaining("Gate 阻止") }));
127
+ });
128
+
129
+ it("gate {pass:true} → handler 正常执行", async () => {
130
+ const api = mockAPI();
131
+ const sm = mockSM();
132
+ sm.get().phase = "ready";
133
+ const handler = vi.fn().mockResolvedValue({ content: [{ type: "text" as const, text: "done" }], details: {} });
134
+ registerWorkflowTool(api, { name: "pv", description: "PV", actions: { exec: { description: "exec", handler, gate: (s) => s.phase === "ready" ? { pass: true } : { pass: false, reason: "not ready" } } }, stateManager: sm, uiUpdater: mockUI() });
135
+ const def = (api.registerTool as any).mock.calls[0][0];
136
+ const r = await def.execute("c1", { action: "exec" }, undefined, undefined, createMockContext());
137
+ expect(handler).toHaveBeenCalledTimes(1);
138
+ expect(r).toEqual({ content: [{ type: "text", text: "done" }], details: {} });
139
+ });
140
+ });
141
+
142
+ // ============================================================
143
+ // Tests: 未知 action
144
+ // ============================================================
145
+
146
+ describe("registerWorkflowTool — 未知 action", () => {
147
+ it("返回可读错误而非崩溃", async () => {
148
+ const api = mockAPI();
149
+ registerWorkflowTool(api, { name: "pv", description: "PV", actions: { plan: { description: "plan", handler: () => Promise.resolve({ content: [{ type: "text" as const, text: "ok" }], details: {} }) } }, stateManager: mockSM(), uiUpdater: mockUI() });
150
+ const def = (api.registerTool as any).mock.calls[0][0];
151
+ const r = await def.execute("c1", { action: "nonexistent" }, undefined, undefined, createMockContext());
152
+ expect(r.content[0]).toEqual(expect.objectContaining({ text: expect.stringContaining("未知 action") }));
153
+ expect((r as any).details.error).toContain("unknown_action");
154
+ });
155
+ });
@@ -0,0 +1,207 @@
1
+ /**
2
+ * 测试 workflow.ts:registerWorkflowTool
3
+ */
4
+ import { describe, it, expect, vi, beforeEach } from "vitest";
5
+
6
+ // mock typebox
7
+ vi.mock("@sinclair/typebox", () => ({
8
+ Type: {
9
+ Object: vi.fn((obj: any) => obj),
10
+ Union: vi.fn((arr: any[]) => arr),
11
+ Literal: vi.fn((val: string) => val),
12
+ Optional: vi.fn((val: any) => val),
13
+ String: vi.fn((opts?: any) => ({ type: "string", ...opts })),
14
+ },
15
+ }));
16
+
17
+ // mock pi SDK
18
+ vi.mock("@earendil-works/pi-coding-agent", () => ({}));
19
+
20
+ import { registerWorkflowTool } from "../workflow";
21
+
22
+ function createMockPi() {
23
+ let registeredTool: any = null;
24
+ return {
25
+ registerTool: vi.fn((tool: any) => { registeredTool = tool; }),
26
+ getRegisteredTool: () => registeredTool,
27
+ };
28
+ }
29
+
30
+ function createMockStateManager<T>(initialState: T) {
31
+ let state = initialState;
32
+ return {
33
+ get: vi.fn(() => state),
34
+ set: vi.fn((s: T) => { state = s; }),
35
+ reset: vi.fn(),
36
+ persist: vi.fn(),
37
+ restore: vi.fn(),
38
+ };
39
+ }
40
+
41
+ function createMockUIUpdater<T>() {
42
+ return {
43
+ update: vi.fn(),
44
+ clear: vi.fn(),
45
+ };
46
+ }
47
+
48
+ function createMockCtx() {
49
+ return {} as any;
50
+ }
51
+
52
+ describe("registerWorkflowTool", () => {
53
+ it("注册工具并传入正确参数", () => {
54
+ const pi = createMockPi();
55
+ const sm = createMockStateManager({ phase: "idle" });
56
+ const ui = createMockUIUpdater();
57
+
58
+ registerWorkflowTool(pi as any, {
59
+ name: "test-tool",
60
+ description: "测试工具",
61
+ actions: {
62
+ start: {
63
+ description: "开始",
64
+ handler: vi.fn().mockResolvedValue({ content: [{ type: "text", text: "started" }], terminate: false }),
65
+ },
66
+ },
67
+ stateManager: sm as any,
68
+ uiUpdater: ui as any,
69
+ });
70
+
71
+ expect(pi.registerTool).toHaveBeenCalledOnce();
72
+ const tool = pi.getRegisteredTool();
73
+ expect(tool.name).toBe("test-tool");
74
+ expect(tool.description).toBe("测试工具");
75
+ });
76
+
77
+ it("执行已知 action 时调用 handler 并 persist", async () => {
78
+ const pi = createMockPi();
79
+ const sm = createMockStateManager({ phase: "idle" });
80
+ const ui = createMockUIUpdater();
81
+ const handler = vi.fn().mockResolvedValue({
82
+ content: [{ type: "text", text: "done" }],
83
+ details: {},
84
+ terminate: false,
85
+ });
86
+
87
+ registerWorkflowTool(pi as any, {
88
+ name: "test-tool",
89
+ description: "测试",
90
+ actions: {
91
+ run: { description: "执行", handler },
92
+ },
93
+ stateManager: sm as any,
94
+ uiUpdater: ui as any,
95
+ });
96
+
97
+ const tool = pi.getRegisteredTool();
98
+ const result = await tool.execute("tc1", { action: "run" }, undefined, undefined, createMockCtx());
99
+
100
+ expect(handler).toHaveBeenCalledOnce();
101
+ expect(sm.persist).toHaveBeenCalled();
102
+ expect(ui.update).toHaveBeenCalled();
103
+ expect(result.content[0].text).toBe("done");
104
+ });
105
+
106
+ it("执行未知 action 时返回错误", async () => {
107
+ const pi = createMockPi();
108
+ const sm = createMockStateManager({ phase: "idle" });
109
+ const ui = createMockUIUpdater();
110
+
111
+ registerWorkflowTool(pi as any, {
112
+ name: "test-tool",
113
+ description: "测试",
114
+ actions: {
115
+ start: {
116
+ description: "开始",
117
+ handler: vi.fn().mockResolvedValue({ content: [{ type: "text", text: "ok" }], terminate: false }),
118
+ },
119
+ },
120
+ stateManager: sm as any,
121
+ uiUpdater: ui as any,
122
+ });
123
+
124
+ const tool = pi.getRegisteredTool();
125
+ const result = await tool.execute("tc1", { action: "unknown" }, undefined, undefined, createMockCtx());
126
+
127
+ expect(result.content[0].text).toContain("未知 action");
128
+ expect(result.details.error).toContain("unknown_action");
129
+ });
130
+
131
+ it("gate 阻止时返回 gate_blocked", async () => {
132
+ const pi = createMockPi();
133
+ const sm = createMockStateManager({ phase: "busy" });
134
+ const ui = createMockUIUpdater();
135
+
136
+ registerWorkflowTool(pi as any, {
137
+ name: "test-tool",
138
+ description: "测试",
139
+ actions: {
140
+ start: {
141
+ description: "开始",
142
+ handler: vi.fn().mockResolvedValue({ content: [{ type: "text", text: "ok" }], terminate: false }),
143
+ gate: (state: any) => state.phase === "busy" ? { pass: false, reason: "正在运行" } : { pass: true },
144
+ },
145
+ },
146
+ stateManager: sm as any,
147
+ uiUpdater: ui as any,
148
+ });
149
+
150
+ const tool = pi.getRegisteredTool();
151
+ const result = await tool.execute("tc1", { action: "start" }, undefined, undefined, createMockCtx());
152
+
153
+ expect(result.content[0].text).toContain("Gate 阻止");
154
+ expect(result.details.error).toContain("gate_blocked");
155
+ });
156
+
157
+ it("handler 抛异常时 persist 后向上传播", async () => {
158
+ const pi = createMockPi();
159
+ const sm = createMockStateManager({ phase: "idle" });
160
+ const ui = createMockUIUpdater();
161
+
162
+ registerWorkflowTool(pi as any, {
163
+ name: "test-tool",
164
+ description: "测试",
165
+ actions: {
166
+ fail: {
167
+ description: "失败",
168
+ handler: vi.fn().mockRejectedValue(new Error("handler error")),
169
+ },
170
+ },
171
+ stateManager: sm as any,
172
+ uiUpdater: ui as any,
173
+ });
174
+
175
+ const tool = pi.getRegisteredTool();
176
+ await expect(tool.execute("tc1", { action: "fail" }, undefined, undefined, createMockCtx()))
177
+ .rejects.toThrow("handler error");
178
+
179
+ // 即使异常也要 persist
180
+ expect(sm.persist).toHaveBeenCalled();
181
+ expect(ui.update).toHaveBeenCalled();
182
+ });
183
+
184
+ it("gate 通过时正常执行", async () => {
185
+ const pi = createMockPi();
186
+ const sm = createMockStateManager({ phase: "idle" });
187
+ const ui = createMockUIUpdater();
188
+
189
+ registerWorkflowTool(pi as any, {
190
+ name: "test-tool",
191
+ description: "测试",
192
+ actions: {
193
+ start: {
194
+ description: "开始",
195
+ handler: vi.fn().mockResolvedValue({ content: [{ type: "text", text: "ok" }], terminate: false }),
196
+ gate: () => ({ pass: true }),
197
+ },
198
+ },
199
+ stateManager: sm as any,
200
+ uiUpdater: ui as any,
201
+ });
202
+
203
+ const tool = pi.getRegisteredTool();
204
+ const result = await tool.execute("tc1", { action: "start" }, undefined, undefined, createMockCtx());
205
+ expect(result.content[0].text).toBe("ok");
206
+ });
207
+ });
package/types.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * workflow: 通用类型定义
3
+ *
4
+ * 只含与业务无关的通用类型。PV 专用类型保留在 plan-verify。
5
+ */
6
+
7
+ /** 子代理执行结果 */
8
+ export interface SubagentResult {
9
+ exitCode: number;
10
+ output: string;
11
+ stderr: string;
12
+ error?: string;
13
+ timedOut?: boolean;
14
+ subSessionId?: string;
15
+ }
16
+
17
+ /** 子代理实时事件,用于转发到父窗口 TUI */
18
+ export interface SubagentEvent {
19
+ type: "tool" | "thinking" | "message";
20
+ toolName?: string;
21
+ toolArgs?: Record<string, unknown>;
22
+ text?: string;
23
+ message?: unknown;
24
+ }
package/utils.ts ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * workflow: 子代理通用工具函数
3
+ *
4
+ * findSessionFile / getSubagentStatusSummary / isSubagentSuccess
5
+ * 所有使用 runSubagent 的扩展共享。
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
+ /**
13
+ * 从 ~/.pi/agent/sessions/ 中找到指定会话 ID 对应的文件路径
14
+ */
15
+ export function findSessionFile(sessionId: string): string | undefined {
16
+ const sessionDir = path.join(os.homedir(), ".pi", "agent", "sessions");
17
+ if (!fs.existsSync(sessionDir)) return undefined;
18
+
19
+ for (const projectDir of fs.readdirSync(sessionDir)) {
20
+ const projectPath = path.join(sessionDir, projectDir);
21
+ if (!fs.statSync(projectPath).isDirectory()) continue;
22
+ for (const file of fs.readdirSync(projectPath)) {
23
+ if (file.includes(sessionId)) {
24
+ return path.join(projectPath, file);
25
+ }
26
+ }
27
+ }
28
+ return undefined;
29
+ }
30
+
31
+ /**
32
+ * 读取子代理会话的最新状态摘要
33
+ */
34
+ export function getSubagentStatusSummary(sessionId: string): string | undefined {
35
+ const filePath = findSessionFile(sessionId);
36
+ if (!filePath) return undefined;
37
+ try {
38
+ const content = fs.readFileSync(filePath, "utf-8");
39
+ const lines = content.split("\n").filter(Boolean);
40
+
41
+ let msgCount = 0;
42
+ let lastToolName = "";
43
+ let lastTs = "";
44
+ for (const line of lines) {
45
+ try {
46
+ const e = JSON.parse(line);
47
+ if (e.type === "message" && e.message?.role === "assistant") {
48
+ msgCount++;
49
+ lastTs = e.timestamp || lastTs;
50
+ for (const c of e.message.content || []) {
51
+ if (c.type === "toolCall") lastToolName = c.name;
52
+ }
53
+ }
54
+ } catch { /* skip */ }
55
+ }
56
+
57
+ const age = lastTs ? `(${lastTs.slice(11, 19)})` : "";
58
+ const toolInfo = lastToolName ? `,最近动作: ${lastToolName}` : "";
59
+ return `${msgCount}条消息${toolInfo} ${age} [${(content.length / 1024).toFixed(0)}KB]`;
60
+ } catch {
61
+ return undefined;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * 判断子代理是否成功执行
67
+ *
68
+ * 成功条件:exitCode=0 且无 error 且未超时,
69
+ * 或者输出足够长(>100字符)且不是空输出且未超时。
70
+ */
71
+ export function isSubagentSuccess(result: { exitCode: number; output: string; error?: string; timedOut?: boolean }): boolean {
72
+ if (result.exitCode === 0 && !result.error && !result.timedOut) return true;
73
+ return result.output.length > 100 && result.output !== "(no output)" && !result.timedOut;
74
+ }
@@ -0,0 +1,21 @@
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
+ });
package/widget.ts ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * workflow: 子代理实时活动 Widget
3
+ *
4
+ * 创建子代理的实时活动 Widget,用于在 TUI 中显示子代理运行状态。
5
+ */
6
+
7
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
8
+ import { truncateToWidth } from "@earendil-works/pi-tui";
9
+ import type { SubagentEvent } from "./types";
10
+
11
+ /**
12
+ * 创建子代理的实时活动 Widget。
13
+ * 返回 { onEvent, cleanup },用于 runSubagent 的回调和完成后清理。
14
+ *
15
+ * 用法:
16
+ * const widget = createSubagentWidget(ctx, { title: "─ 执行 ─" });
17
+ * const result = await runSubagent(task, prompt, tools, cwd, signal, model, timeout, widget.onEvent);
18
+ * widget.cleanup();
19
+ */
20
+ export function createSubagentWidget(
21
+ ctx: ExtensionContext,
22
+ options?: {
23
+ title?: string;
24
+ icon?: string;
25
+ maxLines?: number;
26
+ },
27
+ ) {
28
+ const activityLines: string[] = [];
29
+ let thinkingTimer: ReturnType<typeof setTimeout> | null = null;
30
+ let isThinking = false;
31
+ let thinkingStart = 0;
32
+ let updateTimer: ReturnType<typeof setTimeout> | null = null;
33
+
34
+ const title = options?.title ?? "─ 子代理 ─";
35
+ const maxLines = options?.maxLines ?? 4;
36
+ const toolIcon = options?.icon ?? "🔧";
37
+
38
+ const scheduleWidgetUpdate = () => {
39
+ if (updateTimer) return;
40
+ updateTimer = setTimeout(() => {
41
+ updateTimer = null;
42
+ ctx.ui.setWidget("subagent-activity", (_tui, theme) => ({
43
+ render: (width?: number) => {
44
+ const maxLineWidth = Math.max(10, (width ?? 80) - 4);
45
+ const recent = activityLines.slice(-maxLines).map(
46
+ line => truncateToWidth(line, maxLineWidth, "...")
47
+ );
48
+ const header = truncateToWidth(
49
+ theme.fg("warning", title),
50
+ maxLineWidth, "..."
51
+ );
52
+ return [header, ...recent];
53
+ },
54
+ invalidate: () => {},
55
+ }));
56
+ }, 300);
57
+ };
58
+
59
+ const onEvent = (event: SubagentEvent) => {
60
+ switch (event.type) {
61
+ case "tool": {
62
+ const name = event.toolName || "?";
63
+ const toolLine = `${toolIcon} ${name}`;
64
+ const last = activityLines[activityLines.length - 1];
65
+ if (last && (last.startsWith(toolIcon) || last.startsWith("💭"))) {
66
+ activityLines[activityLines.length - 1] = toolLine;
67
+ } else {
68
+ activityLines.push(toolLine);
69
+ }
70
+ isThinking = false;
71
+ if (thinkingTimer) { clearTimeout(thinkingTimer); thinkingTimer = null; }
72
+ break;
73
+ }
74
+ case "thinking": {
75
+ if (!isThinking) {
76
+ isThinking = true;
77
+ thinkingStart = Date.now();
78
+ activityLines.push(`💭 思考中...`);
79
+ }
80
+ if (!thinkingTimer) {
81
+ thinkingTimer = setTimeout(() => {
82
+ activityLines[activityLines.length - 1] = `💭 思考中 (${Math.floor((Date.now() - thinkingStart) / 1000)}s)`;
83
+ }, 5000);
84
+ }
85
+ break;
86
+ }
87
+ case "message": {
88
+ isThinking = false;
89
+ if (thinkingTimer) { clearTimeout(thinkingTimer); thinkingTimer = null; }
90
+ activityLines.push(`💬 正在生成...`);
91
+ break;
92
+ }
93
+ }
94
+ scheduleWidgetUpdate();
95
+ };
96
+
97
+ const cleanup = () => {
98
+ if (updateTimer) clearTimeout(updateTimer);
99
+ if (thinkingTimer) clearTimeout(thinkingTimer);
100
+ ctx.ui.setWidget("subagent-activity", undefined);
101
+ };
102
+
103
+ return { onEvent, cleanup };
104
+ }