@wbline/pi-plan-build 0.0.0-stage → 0.0.2
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/CHANGELOG.md +62 -0
- package/LICENSE +21 -0
- package/README.md +91 -3
- package/package.json +52 -6
- package/src/config.ts +66 -0
- package/src/context.ts +97 -0
- package/src/core/guard.ts +168 -0
- package/src/core/prompts.ts +56 -0
- package/src/core/schema.ts +144 -0
- package/src/core/state.ts +409 -0
- package/src/core/steps.ts +94 -0
- package/src/engine.ts +170 -0
- package/src/index.ts +258 -0
- package/src/lifecycle.ts +92 -0
- package/src/tools/index.ts +16 -0
- package/src/tools/plan-exit.ts +95 -0
- package/src/tools/plan-outcome.ts +120 -0
- package/src/tools/plan-question.ts +80 -0
- package/src/tools/plan-steps.ts +153 -0
- package/src/tools/plan-task.ts +177 -0
package/src/engine.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PlanEngine:扩展运行时中枢。持有当前状态,执行转移并统一处理
|
|
3
|
+
* 持久化(appendEntry)、UI 刷新(setStatus/setWidget/notify)。
|
|
4
|
+
* 对比参考项目:不再有几十个闭包变量,所有变化都经过 apply()。
|
|
5
|
+
*/
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import type {
|
|
9
|
+
ExtensionAPI,
|
|
10
|
+
ExtensionContext,
|
|
11
|
+
} from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import type { Config } from "./config.ts";
|
|
13
|
+
import { type PromptPack, prompts } from "./core/prompts.ts";
|
|
14
|
+
import { decodeState, STATE_ENTRY_TYPE } from "./core/schema.ts";
|
|
15
|
+
import {
|
|
16
|
+
initialState,
|
|
17
|
+
type State,
|
|
18
|
+
statusLine,
|
|
19
|
+
type Transition,
|
|
20
|
+
TransitionError,
|
|
21
|
+
type TransitionResult,
|
|
22
|
+
transition,
|
|
23
|
+
widgetLines,
|
|
24
|
+
} from "./core/state.ts";
|
|
25
|
+
|
|
26
|
+
export class PlanEngine {
|
|
27
|
+
state: State = initialState;
|
|
28
|
+
readonly pi: ExtensionAPI;
|
|
29
|
+
private ctx: ExtensionContext | undefined;
|
|
30
|
+
config: Config;
|
|
31
|
+
/** awaiting_validation 的问询是否已在本次运行发过(防重放)。 */
|
|
32
|
+
validationAsked = false;
|
|
33
|
+
/** 状态损坏只读保护。 */
|
|
34
|
+
corrupt = false;
|
|
35
|
+
|
|
36
|
+
constructor(pi: ExtensionAPI, config: Config) {
|
|
37
|
+
this.pi = pi;
|
|
38
|
+
this.config = config;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
get P(): PromptPack {
|
|
42
|
+
return prompts(this.config.lang);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
setConfig(patch: Partial<Config>): void {
|
|
46
|
+
this.config = { ...this.config, ...patch };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
attachContext(ctx: ExtensionContext): void {
|
|
50
|
+
this.ctx = ctx;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** session_start:从分支条目恢复。 */
|
|
54
|
+
restore(entries: readonly { customType?: string; data?: unknown }[]): {
|
|
55
|
+
restored: boolean;
|
|
56
|
+
corruptEntry?: boolean;
|
|
57
|
+
} {
|
|
58
|
+
// 仅"最新"状态条目损坏才视为损坏:更早的坏条目之后若有合法状态,不进入只读保护
|
|
59
|
+
let restoredState: State | undefined;
|
|
60
|
+
let corruptAfterLatest = false;
|
|
61
|
+
for (const entry of entries) {
|
|
62
|
+
if (entry.customType !== STATE_ENTRY_TYPE || entry.data === undefined)
|
|
63
|
+
continue;
|
|
64
|
+
const decoded = decodeState(entry.data);
|
|
65
|
+
if (decoded) {
|
|
66
|
+
restoredState = decoded;
|
|
67
|
+
corruptAfterLatest = false;
|
|
68
|
+
} else {
|
|
69
|
+
corruptAfterLatest = true;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
this.state = restoredState ?? initialState;
|
|
73
|
+
this.corrupt = false;
|
|
74
|
+
return {
|
|
75
|
+
restored: restoredState !== undefined,
|
|
76
|
+
corruptEntry: corruptAfterLatest,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
apply(ev: Transition, ctx?: ExtensionContext): TransitionResult {
|
|
81
|
+
const c = ctx ?? this.ctx;
|
|
82
|
+
if (this.corrupt)
|
|
83
|
+
throw new TransitionError(
|
|
84
|
+
"持久化状态损坏,处于只读保护。请 /reload 或手工修复后重试。",
|
|
85
|
+
);
|
|
86
|
+
const prev = this.state;
|
|
87
|
+
const result = transition(this.state, ev);
|
|
88
|
+
this.state = result.state;
|
|
89
|
+
if (result.state !== prev) this.persist(); // 幂等转移不写重复条目
|
|
90
|
+
this.refreshUI(c, result.note);
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
tryApply(
|
|
95
|
+
ev: Transition,
|
|
96
|
+
ctx?: ExtensionContext,
|
|
97
|
+
): TransitionResult | { error: string } {
|
|
98
|
+
try {
|
|
99
|
+
return this.apply(ev, ctx);
|
|
100
|
+
} catch (e) {
|
|
101
|
+
if (e instanceof TransitionError) return { error: e.message };
|
|
102
|
+
throw e;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private persist(): void {
|
|
107
|
+
// 桥接契约:pi-acp-jetbrain 读 data.selectedMode 判断当前模式;
|
|
108
|
+
// decodeState 只挑已知字段,附加键不影响恢复。
|
|
109
|
+
this.pi.appendEntry(STATE_ENTRY_TYPE, {
|
|
110
|
+
...this.state,
|
|
111
|
+
selectedMode: this.state.mode,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
refreshUI(ctx?: ExtensionContext, note?: string): void {
|
|
116
|
+
const c = ctx ?? this.ctx;
|
|
117
|
+
if (!c) return;
|
|
118
|
+
// 模式徽标:底部状态栏(Plan=警告色,Build=强调色)
|
|
119
|
+
c.ui.setStatus(
|
|
120
|
+
"plan-build",
|
|
121
|
+
c.ui.theme.fg(
|
|
122
|
+
this.state.mode === "plan" ? "warning" : "accent",
|
|
123
|
+
statusLine(this.state),
|
|
124
|
+
),
|
|
125
|
+
);
|
|
126
|
+
c.ui.setWidget("plan-build-steps", widgetLines(this.state));
|
|
127
|
+
if (note) c.ui.notify(note, "info");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** canonical 计划文件路径:<cwd>/.pi/agent/plans/<yyyyMMdd-HHmm>-<标题slug>.md(随项目走,语义化命名) */
|
|
132
|
+
export function nextPlanPath(cwd: string, title: string): string {
|
|
133
|
+
const dir = path.join(cwd, ".pi", "agent", "plans");
|
|
134
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
135
|
+
const base = `${formatStamp(new Date())}-${titleSlug(title)}`;
|
|
136
|
+
for (let i = 0; i < 100; i++) {
|
|
137
|
+
const suffix = i === 0 ? "" : `-${i + 1}`;
|
|
138
|
+
const p = path.join(dir, `${base}${suffix}.md`);
|
|
139
|
+
try {
|
|
140
|
+
fs.writeFileSync(p, "", { flag: "wx" }); // 分配即占位,防同名重复分配
|
|
141
|
+
return p;
|
|
142
|
+
} catch {
|
|
143
|
+
/* 已存在 → 尝试下一个后缀 */
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const fallback = path.join(dir, `${base}-${Date.now()}.md`);
|
|
147
|
+
fs.writeFileSync(fallback, "", { flag: "wx" });
|
|
148
|
+
return fallback;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 本地时刻戳:20251008-1432 */
|
|
152
|
+
function formatStamp(d: Date): string {
|
|
153
|
+
const p = (n: number) => String(n).padStart(2, "0");
|
|
154
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 标题 → 文件名安全 slug:去非法字符、空白折叠为 -、截 40 字符、去首尾点。 */
|
|
158
|
+
function titleSlug(title: string): string {
|
|
159
|
+
const cleaned = title
|
|
160
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: 清理文件名中的控制字符正是本处目的
|
|
161
|
+
.replace(/[\\/:*?"<>|\x00-\x1f]/g, "")
|
|
162
|
+
.trim()
|
|
163
|
+
.replace(/\s+/g, "-");
|
|
164
|
+
return (
|
|
165
|
+
cleaned
|
|
166
|
+
.slice(0, 40)
|
|
167
|
+
.replace(/^[.-]+|[.-]+$/g, "")
|
|
168
|
+
.trim() || "plan"
|
|
169
|
+
);
|
|
170
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-plan-build v2 入口:Plan/Build 双模式扩展。
|
|
3
|
+
*
|
|
4
|
+
* 设计原则:分层模块 + 集中状态机 + 原生 UI(setStatus/setWidget/custom),
|
|
5
|
+
* 不接管 composer/editor,与其它扩展零冲突。详见 README.md。
|
|
6
|
+
*
|
|
7
|
+
* 命令:/plan-build 交互菜单(切换模式/状态/完成/放弃/语言/设置);
|
|
8
|
+
* /plan、/build 直切模式(IDE/ACP 桥接层约定按命令名调用)。
|
|
9
|
+
* 快捷键:Alt+M 切换模式
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import type {
|
|
14
|
+
ExtensionAPI,
|
|
15
|
+
ExtensionContext,
|
|
16
|
+
Theme,
|
|
17
|
+
} from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import { Key, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
|
|
19
|
+
import { configPath, loadConfig, saveConfig } from "./config.ts";
|
|
20
|
+
import { type Mode, type State, statusLine } from "./core/state.ts";
|
|
21
|
+
import { PlanEngine } from "./engine.ts";
|
|
22
|
+
import { wireLifecycle } from "./lifecycle.ts";
|
|
23
|
+
import { registerAllTools } from "./tools/index.ts";
|
|
24
|
+
|
|
25
|
+
export default function planBuild(pi: ExtensionAPI): void {
|
|
26
|
+
const loaded = loadConfig();
|
|
27
|
+
const engine = new PlanEngine(pi, loaded.config);
|
|
28
|
+
|
|
29
|
+
// --- 唯一命令:交互菜单 ---
|
|
30
|
+
pi.registerCommand("plan-build", {
|
|
31
|
+
description: "Plan/Build 菜单:切换模式、状态、完成、放弃、语言、设置",
|
|
32
|
+
handler: async (_args, ctx) => {
|
|
33
|
+
await openMenu(engine, ctx);
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
// --- 直切命令:pi-acp-jetbrain 桥接层 setSessionMode 按名字查找并发送 /plan 或 /build ---
|
|
38
|
+
const setMode = async (mode: Mode, ctx: ExtensionContext): Promise<void> => {
|
|
39
|
+
const r = engine.tryApply({ t: "mode.set", mode }, ctx);
|
|
40
|
+
if ("error" in r) ctx.ui.notify(r.error, "error");
|
|
41
|
+
};
|
|
42
|
+
pi.registerCommand("plan", {
|
|
43
|
+
description: "切换到 Plan 模式(只读规划)",
|
|
44
|
+
handler: (_args, ctx) => setMode("plan", ctx),
|
|
45
|
+
});
|
|
46
|
+
pi.registerCommand("build", {
|
|
47
|
+
description: "切换到 Build 模式",
|
|
48
|
+
handler: (_args, ctx) => setMode("build", ctx),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// --- 工具与生命周期 ---
|
|
52
|
+
registerAllTools(pi, engine);
|
|
53
|
+
wireLifecycle(pi, engine);
|
|
54
|
+
|
|
55
|
+
// --- 快捷键:Alt+M 切换模式(全局,不碰编辑器补全)---
|
|
56
|
+
pi.registerShortcut(Key.alt("m"), {
|
|
57
|
+
description: "切换 Plan/Build 模式",
|
|
58
|
+
handler: async (ctx) => {
|
|
59
|
+
const next = engine.state.mode === "plan" ? "build" : "plan";
|
|
60
|
+
const r = engine.tryApply({ t: "mode.set", mode: next }, ctx);
|
|
61
|
+
if ("error" in r) ctx.ui.notify(r.error, "error");
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// --- 启动模式应用(在首个 session_start 时)---
|
|
66
|
+
pi.on("session_start", (event, ctx) => {
|
|
67
|
+
// startup(进程启动)与 new(/new 新会话)都是全新状态,应用默认模式;
|
|
68
|
+
// resume/fork/reload 尊重恢复出的状态
|
|
69
|
+
if (event.reason !== "startup" && event.reason !== "new") return;
|
|
70
|
+
const mode =
|
|
71
|
+
engine.state.mode === "plan" ? "plan" : loaded.config.defaultMode;
|
|
72
|
+
if (mode !== engine.state.mode) engine.apply({ t: "mode.set", mode }, ctx);
|
|
73
|
+
else engine.refreshUI(ctx);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
if (loaded.warning) {
|
|
77
|
+
// factory 里只能注册,不能弹 UI;挂到首个 context 前的 session_start 提示。
|
|
78
|
+
pi.on("session_start", (_event, ctx) => {
|
|
79
|
+
if (loaded.warning) ctx.ui.notify(loaded.warning, "warning");
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// ============ 菜单 ============
|
|
85
|
+
|
|
86
|
+
type MenuAction = "toggle" | "status" | "done" | "abandon" | "lang" | "config";
|
|
87
|
+
|
|
88
|
+
function buildMenuItems(s: State): { id: MenuAction; label: string }[] {
|
|
89
|
+
const items: { id: MenuAction; label: string }[] = [
|
|
90
|
+
{
|
|
91
|
+
id: "toggle",
|
|
92
|
+
label: `切换模式 → ${s.mode === "plan" ? "Build" : "Plan"}`,
|
|
93
|
+
},
|
|
94
|
+
{ id: "status", label: "查看状态" },
|
|
95
|
+
];
|
|
96
|
+
if (s.plan) {
|
|
97
|
+
items.push({ id: "done", label: "标记计划完成" });
|
|
98
|
+
items.push({ id: "abandon", label: "放弃计划…" });
|
|
99
|
+
}
|
|
100
|
+
items.push({ id: "lang", label: "提示词语言 → 中/EN 切换" });
|
|
101
|
+
items.push({ id: "config", label: "设置文件…" });
|
|
102
|
+
return items;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function openMenu(
|
|
106
|
+
engine: PlanEngine,
|
|
107
|
+
ctx: ExtensionContext,
|
|
108
|
+
): Promise<void> {
|
|
109
|
+
if (!ctx.hasUI) return; // print/json 模式:无交互面
|
|
110
|
+
if (ctx.mode === "tui") {
|
|
111
|
+
const action = await ctx.ui.custom<MenuAction | undefined>(
|
|
112
|
+
(_tui, theme, _kb, done) => new MenuComponent(theme, engine.state, done),
|
|
113
|
+
);
|
|
114
|
+
await runAction(engine, ctx, action);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
// RPC:原生 select 单次选择
|
|
118
|
+
const items = buildMenuItems(engine.state);
|
|
119
|
+
const choice = await ctx.ui.select(
|
|
120
|
+
"Plan/Build 菜单",
|
|
121
|
+
items.map((x) => x.label),
|
|
122
|
+
);
|
|
123
|
+
const selected = items.find((x) => x.label === choice);
|
|
124
|
+
if (selected) await runAction(engine, ctx, selected.id);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function runAction(
|
|
128
|
+
engine: PlanEngine,
|
|
129
|
+
ctx: ExtensionContext,
|
|
130
|
+
action: MenuAction | undefined,
|
|
131
|
+
): Promise<void> {
|
|
132
|
+
if (!action) return;
|
|
133
|
+
const s = engine.state;
|
|
134
|
+
switch (action) {
|
|
135
|
+
case "toggle": {
|
|
136
|
+
const next = s.mode === "plan" ? "build" : "plan";
|
|
137
|
+
const r = engine.tryApply({ t: "mode.set", mode: next }, ctx);
|
|
138
|
+
if ("error" in r) ctx.ui.notify(r.error, "error");
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
case "status":
|
|
142
|
+
showPanel(ctx, statusBody(s));
|
|
143
|
+
return;
|
|
144
|
+
case "done": {
|
|
145
|
+
if (!s.plan) return;
|
|
146
|
+
const r = engine.tryApply({ t: "plan.complete" }, ctx);
|
|
147
|
+
if ("error" in r) ctx.ui.notify(r.error, "error");
|
|
148
|
+
else ctx.ui.notify("计划已标记完成。", "info");
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
case "abandon": {
|
|
152
|
+
if (!s.plan) return;
|
|
153
|
+
const reason =
|
|
154
|
+
(await ctx.ui.input(
|
|
155
|
+
"放弃计划(文件保留)",
|
|
156
|
+
"放弃原因,如:方向变了",
|
|
157
|
+
)) ?? "";
|
|
158
|
+
if (!reason.trim()) return; // 取消/空原因:不动
|
|
159
|
+
const r = engine.tryApply(
|
|
160
|
+
{ t: "plan.abandon", reason: reason.trim() },
|
|
161
|
+
ctx,
|
|
162
|
+
);
|
|
163
|
+
if ("error" in r) ctx.ui.notify(r.error, "error");
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
case "lang": {
|
|
167
|
+
const lang = engine.config.lang === "zh" ? "en" : "zh";
|
|
168
|
+
engine.setConfig({ lang });
|
|
169
|
+
saveConfig({ lang });
|
|
170
|
+
ctx.ui.notify(
|
|
171
|
+
`提示词语言:${lang === "en" ? "English" : "中文"}`,
|
|
172
|
+
"info",
|
|
173
|
+
);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
case "config": {
|
|
177
|
+
const p = configPath();
|
|
178
|
+
const body = fs.existsSync(p) ? fs.readFileSync(p, "utf8") : "{}";
|
|
179
|
+
showPanel(ctx, `${p}\n\n${body}`);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function statusBody(s: State): string {
|
|
186
|
+
const lines = [statusLine(s)];
|
|
187
|
+
if (s.plan) {
|
|
188
|
+
lines.push(`文件:${s.plan.path}${s.plan.saved ? "" : "(未写盘)"}`);
|
|
189
|
+
lines.push(`seq:${s.plan.seq} · 模式:${s.mode}`);
|
|
190
|
+
if (s.execution) {
|
|
191
|
+
lines.push(
|
|
192
|
+
...s.execution.steps.map((x) => ` ${x.n}. [${x.status}] ${x.text}`),
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
} else {
|
|
196
|
+
lines.push("没有当前计划。Plan 模式下让 agent 规划,或直接讨论。");
|
|
197
|
+
}
|
|
198
|
+
return lines.join("\n");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** TUI 菜单组件:↑↓ 选择、Enter 执行、Esc 关闭(执行后自动关闭)。 */
|
|
202
|
+
class MenuComponent {
|
|
203
|
+
private selected = 0;
|
|
204
|
+
constructor(
|
|
205
|
+
private readonly theme: Theme,
|
|
206
|
+
private readonly state: State,
|
|
207
|
+
private readonly done: (action: MenuAction | undefined) => void,
|
|
208
|
+
) {}
|
|
209
|
+
|
|
210
|
+
handleInput(data: string): void {
|
|
211
|
+
const count = buildMenuItems(this.state).length;
|
|
212
|
+
if (matchesKey(data, "escape")) this.done(undefined);
|
|
213
|
+
else if (matchesKey(data, "up"))
|
|
214
|
+
this.selected = (this.selected - 1 + count) % count;
|
|
215
|
+
else if (matchesKey(data, "down"))
|
|
216
|
+
this.selected = (this.selected + 1) % count;
|
|
217
|
+
else if (matchesKey(data, "return"))
|
|
218
|
+
this.done(buildMenuItems(this.state)[this.selected]?.id);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
render(width: number): string[] {
|
|
222
|
+
const th = this.theme;
|
|
223
|
+
const items = buildMenuItems(this.state);
|
|
224
|
+
const lines: string[] = ["", ` ${th.fg("accent", "Plan/Build")}`, ""];
|
|
225
|
+
items.forEach((item, i) => {
|
|
226
|
+
const row =
|
|
227
|
+
i === this.selected
|
|
228
|
+
? `${th.fg("accent", "❯ ")}${th.fg("accent", item.label)}`
|
|
229
|
+
: ` ${item.label}`;
|
|
230
|
+
lines.push(truncateToWidth(` ${row}`, width));
|
|
231
|
+
});
|
|
232
|
+
lines.push("", ` ${th.fg("dim", "↑↓ 选择 · Enter 执行 · Esc 关闭")}`, "");
|
|
233
|
+
return lines;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
invalidate() {}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function showPanel(ctx: ExtensionContext, body: string): void {
|
|
240
|
+
if (ctx.mode === "tui") {
|
|
241
|
+
void ctx.ui.custom<void>((_tui, _theme, _kb, done) => {
|
|
242
|
+
const lines = body.split("\n").map((l) => ` ${l}`);
|
|
243
|
+
return {
|
|
244
|
+
render(width: number) {
|
|
245
|
+
return lines.map((l) =>
|
|
246
|
+
l.length > width ? `${l.slice(0, width - 1)}…` : l,
|
|
247
|
+
);
|
|
248
|
+
},
|
|
249
|
+
handleInput(data: string) {
|
|
250
|
+
if (matchesKey(data, "escape") || matchesKey(data, "return")) done();
|
|
251
|
+
},
|
|
252
|
+
invalidate() {},
|
|
253
|
+
};
|
|
254
|
+
});
|
|
255
|
+
} else {
|
|
256
|
+
ctx.ui.notify(body, "info");
|
|
257
|
+
}
|
|
258
|
+
}
|
package/src/lifecycle.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 事件接线:session 恢复、tool_call 权限守卫、context 注入、agent_settled 验证问询。
|
|
3
|
+
* 每个 handler 都保持简短,逻辑下沉到 core 纯函数。
|
|
4
|
+
*/
|
|
5
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { buildContextBlock, injectContext } from "./context.ts";
|
|
7
|
+
import {
|
|
8
|
+
decideFileMutation,
|
|
9
|
+
extractMutationTargets,
|
|
10
|
+
FILE_MUTATION_TOOLS,
|
|
11
|
+
IDE_MUTATION_TOOLS,
|
|
12
|
+
realpathLike,
|
|
13
|
+
} from "./core/guard.ts";
|
|
14
|
+
import type { PlanEngine } from "./engine.ts";
|
|
15
|
+
|
|
16
|
+
export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
|
|
17
|
+
// --- 会话恢复 ---
|
|
18
|
+
pi.on("session_start", (_event, ctx) => {
|
|
19
|
+
engine.attachContext(ctx);
|
|
20
|
+
const entries = ctx.sessionManager.getBranch() as readonly {
|
|
21
|
+
customType?: string;
|
|
22
|
+
data?: unknown;
|
|
23
|
+
}[];
|
|
24
|
+
const { corruptEntry } = engine.restore(entries);
|
|
25
|
+
if (corruptEntry) {
|
|
26
|
+
engine.corrupt = true;
|
|
27
|
+
ctx.ui.notify(
|
|
28
|
+
"检测到损坏的计划状态条目,扩展进入只读保护;请检查会话文件或 /reload。",
|
|
29
|
+
"error",
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
engine.refreshUI(ctx);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
pi.on("session_info_changed", (_event, ctx) => engine.attachContext(ctx));
|
|
36
|
+
|
|
37
|
+
// --- 权限守卫(tool_call 可拦截)---
|
|
38
|
+
pi.on("tool_call", (event, ctx) => {
|
|
39
|
+
const s = engine.state;
|
|
40
|
+
const guarded =
|
|
41
|
+
FILE_MUTATION_TOOLS.has(event.toolName) ||
|
|
42
|
+
IDE_MUTATION_TOOLS.has(event.toolName);
|
|
43
|
+
if (!guarded) return;
|
|
44
|
+
if (s.mode === "build" && !engine.config.protectPlanFile) return; // 用户关闭保护
|
|
45
|
+
const planPath = s.plan?.path ? realpathLike(s.plan.path) : null;
|
|
46
|
+
const targets = extractMutationTargets(
|
|
47
|
+
event.toolName,
|
|
48
|
+
event.input,
|
|
49
|
+
ctx.cwd,
|
|
50
|
+
);
|
|
51
|
+
const decision = decideFileMutation(
|
|
52
|
+
event.toolName,
|
|
53
|
+
s.mode,
|
|
54
|
+
planPath,
|
|
55
|
+
s.plan?.saved ?? false,
|
|
56
|
+
targets,
|
|
57
|
+
);
|
|
58
|
+
if (decision.action === "block")
|
|
59
|
+
return { block: true, reason: decision.reason };
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// --- 上下文注入(prompt cache 友好)---
|
|
63
|
+
pi.on("context", (event) => {
|
|
64
|
+
const block = buildContextBlock(engine.state, engine.P);
|
|
65
|
+
if (!block) return;
|
|
66
|
+
return { messages: injectContext(event.messages, block) };
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// --- 验证问询:awaiting_validation 结算后问一次 ---
|
|
70
|
+
pi.on("agent_settled", async (_event, ctx) => {
|
|
71
|
+
const outcome = engine.state.plan?.outcome;
|
|
72
|
+
if (outcome?.kind !== "awaiting_validation" || engine.validationAsked)
|
|
73
|
+
return;
|
|
74
|
+
if (!ctx.hasUI || !ctx.isIdle()) return;
|
|
75
|
+
engine.validationAsked = true;
|
|
76
|
+
const passed = await ctx.ui.confirm(
|
|
77
|
+
"必需验证是否通过?",
|
|
78
|
+
outcome.userAction,
|
|
79
|
+
);
|
|
80
|
+
if (passed && engine.state.plan?.outcome?.kind === "awaiting_validation") {
|
|
81
|
+
engine.apply({ t: "plan.complete" }, ctx);
|
|
82
|
+
ctx.ui.notify("验证通过,计划已标记完成。", "info");
|
|
83
|
+
}
|
|
84
|
+
// 未通过/取消:什么都不做,计划保持开放;用户会在对话里说明失败详情。
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
// --- 卸载清理(widget/status 由 reload 重建)---
|
|
88
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
89
|
+
ctx.ui.setStatus("plan-build", undefined);
|
|
90
|
+
ctx.ui.setWidget("plan-build-steps", undefined);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** 工具族注册入口:7 个工具常驻(stable catalog,execute-time guards 保证模式正确性)。 */
|
|
2
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { PlanEngine } from "../engine.ts";
|
|
4
|
+
import { registerPlanExit } from "./plan-exit.ts";
|
|
5
|
+
import { registerPlanOutcome } from "./plan-outcome.ts";
|
|
6
|
+
import { registerQuestion } from "./plan-question.ts";
|
|
7
|
+
import { registerPlanStepTools } from "./plan-steps.ts";
|
|
8
|
+
import { registerPlanTask } from "./plan-task.ts";
|
|
9
|
+
|
|
10
|
+
export function registerAllTools(pi: ExtensionAPI, engine: PlanEngine): void {
|
|
11
|
+
registerPlanTask(pi, engine);
|
|
12
|
+
registerPlanExit(pi, engine);
|
|
13
|
+
registerPlanStepTools(pi, engine);
|
|
14
|
+
registerPlanOutcome(pi, engine);
|
|
15
|
+
registerQuestion(pi);
|
|
16
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** plan_exit:Plan 模式终点 —— 渲染审阅并请求实现授权(原生 select 对话框)。 */
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import type {
|
|
4
|
+
ExtensionAPI,
|
|
5
|
+
ExtensionToolContext,
|
|
6
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { Type } from "typebox";
|
|
8
|
+
import { parseSteps } from "../core/steps.ts";
|
|
9
|
+
import type { PlanEngine } from "../engine.ts";
|
|
10
|
+
|
|
11
|
+
const Params = Type.Object({});
|
|
12
|
+
|
|
13
|
+
const HERE = "本会话实现";
|
|
14
|
+
const STEPWISE = "分步实现";
|
|
15
|
+
const STAY = "留在 Plan 模式";
|
|
16
|
+
|
|
17
|
+
export function registerPlanExit(pi: ExtensionAPI, engine: PlanEngine): void {
|
|
18
|
+
pi.registerTool({
|
|
19
|
+
name: "plan_exit",
|
|
20
|
+
label: "Plan Exit",
|
|
21
|
+
description:
|
|
22
|
+
"Plan 模式专用:完整计划写盘且讨论收敛后调用。展示计划并请求实现授权(本会话/分步/留下)。接受范围不等于开始实现之外的授权;不要在文件未保存或讨论未完成时调用。",
|
|
23
|
+
parameters: Params,
|
|
24
|
+
async execute(_id, _params, _signal, _onUpdate, ctx: ExtensionToolContext) {
|
|
25
|
+
const s = engine.state;
|
|
26
|
+
if (s.mode !== "plan") {
|
|
27
|
+
return fail("plan_exit 仅在 Plan 模式可用。");
|
|
28
|
+
}
|
|
29
|
+
const plan = s.plan;
|
|
30
|
+
if (!plan) return fail("没有当前计划。先 plan_task new。");
|
|
31
|
+
if (!fs.existsSync(plan.path)) {
|
|
32
|
+
return fail(
|
|
33
|
+
`计划文件尚未写盘:${plan.path}。请先把完整计划写入该文件(用 write 工具),成功后调用 plan_exit。`,
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
const markdown = fs.readFileSync(plan.path, "utf8");
|
|
37
|
+
if (!markdown.trim()) {
|
|
38
|
+
// nextPlanPath 分配即建占位空文件,存在性检查恒真——必须校验内容非空
|
|
39
|
+
return fail(
|
|
40
|
+
`计划文件还是空的:${plan.path}。请先写入完整计划(含 ## 验证 小节与文末 "## 实现步骤" 编号列表),成功后再调用 plan_exit。`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
if (!plan.saved) engine.apply({ t: "plan.saved" }, ctx);
|
|
44
|
+
const parsed = parseSteps(markdown);
|
|
45
|
+
|
|
46
|
+
// 审阅渲染:把计划全文作为工具结果回显,模型轮结束后用户在对话里看到(无自定义 entry,减少 UI 接管)。
|
|
47
|
+
const review = `# 计划审阅:${plan.title}\n\n${markdown}`;
|
|
48
|
+
|
|
49
|
+
let choice: string | undefined;
|
|
50
|
+
if (ctx.hasUI) {
|
|
51
|
+
choice = await ctx.ui.select(`计划已就绪:${plan.title}`, [
|
|
52
|
+
HERE,
|
|
53
|
+
STEPWISE,
|
|
54
|
+
STAY,
|
|
55
|
+
]);
|
|
56
|
+
}
|
|
57
|
+
if (!choice || choice === STAY) {
|
|
58
|
+
return ok(
|
|
59
|
+
`${review}\n\n---\n已留在 Plan 模式。等待用户进一步指示;不要开始实现。`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (choice === STEPWISE) {
|
|
64
|
+
if (parsed.error) {
|
|
65
|
+
return fail(
|
|
66
|
+
`${review}\n\n---\n分步执行需要步骤列表:${parsed.error}`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
const r = engine.apply({ t: "exec.start", steps: parsed.steps }, ctx);
|
|
70
|
+
engine.apply({ t: "mode.set", mode: "build" }, ctx);
|
|
71
|
+
const n = r.state.execution?.steps.length ?? parsed.steps.length;
|
|
72
|
+
return ok(
|
|
73
|
+
`${review}\n\n---\n用户批准分步实现(共 ${n} 步),已切换到 Build 模式。第 1 步就绪但未开始:向用户简述第 1 步并等待其明确批准(如"继续"),批准后调用 plan_step_control start。`,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 本会话实现
|
|
78
|
+
engine.apply({ t: "mode.set", mode: "build" }, ctx);
|
|
79
|
+
return ok(
|
|
80
|
+
`${review}\n\n---\n用户批准在本会话实现,已切换到 Build 模式。请在批准的范围内实现全部工作,按计划 ## 验证 小节执行必需检查,完成后调用 plan_complete(或 plan_set_outcome 记录未竟事项)。`,
|
|
81
|
+
);
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function ok(t: string) {
|
|
87
|
+
return { content: [{ type: "text" as const, text: t }], details: undefined };
|
|
88
|
+
}
|
|
89
|
+
function fail(t: string) {
|
|
90
|
+
return {
|
|
91
|
+
content: [{ type: "text" as const, text: t }],
|
|
92
|
+
details: undefined,
|
|
93
|
+
isError: true as const,
|
|
94
|
+
};
|
|
95
|
+
}
|